Compare commits

...
Author SHA1 Message Date
Cursor Agent b2af107f91 fix: cloud switch retry and encrypted catalog availability handling
- Fix cloud environment switch showing ON for error/offline states, which
  blocked retry since React Native Switch only fires onValueChange on
  transitions. The switch now only shows ON for connected/connecting/
  reconnecting states, allowing users to toggle ON to retry from error
  or offline states.

- Fix DesktopConnectionCatalogStore.get returning an empty Option when
  an encrypted catalog exists but safe storage is unavailable. This
  silently hid the catalog and risked overwriting it. Now fails with
  ElectronSafeStorageAvailabilityError so callers can surface the issue
  instead of treating it as an empty catalog.
2026-06-21 21:34:09 +00:00
Julius Marminge 38f46e6971 Refresh mobile dependency lockfile
- Update React Native peer dependency snapshots and local module hashes
2026-06-21 14:19:53 -07:00
Julius Marmingeandcodex ed0b6119c2 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-18 00:20:24 -07:00
Julius Marmingeandcodex b01bf05c50 Restore retained environment HTTP test helper
Co-authored-by: codex <[email protected]>
2026-06-18 00:19:18 -07:00
Julius Marmingeandcodex 344fca1edc Restore client behavior and stabilize async UI state
Co-authored-by: codex <[email protected]>
2026-06-18 00:17:04 -07:00
Julius Marminge c09f491b37 nuke browser tests cause codex just gets caught up in them 2026-06-18 00:00:47 -07:00
Julius Marmingeandcodex c55ae239ff Harden terminal reconnection and asset URL handling
- Keep terminal state consistent across close, reopen, and stale metadata
- Load historical attachments through signed asset URLs
- Serialize resizes and ignore requests for closed terminals

Co-authored-by: codex <[email protected]>
2026-06-17 22:24:54 -07:00
Julius Marminge ca35205f43 Stabilize draft promotion and live session recovery
- Finalize promoted drafts from inferred live threads
- Retry transient RPC and thread sync failures within a session
- Preserve full thread history and delay shell cache persistence
2026-06-17 19:26:56 -07:00
Julius Marminge 2b9cf7d18a Refactor connection-aware asset and VCS state handling
- Route mobile/web asset URLs through shared runtime state
- Replace remote HTTP header plumbing with environment asset URLs
- Add optional cached remote status reads without upstream refresh
2026-06-17 16:36:38 -07:00
Julius Marmingeandcodex a2ed9bbb4f Fix browser atom command mocks
Co-authored-by: codex <[email protected]>
2026-06-17 00:41:42 -07:00
Julius Marmingeandcodex 841bbd9a17 Harden connection state handling across app
- adopt atom command results for connection and relay flows
- preserve relay error trace IDs and improve failure handling
- add coverage for auth, registration, and environment updates

Co-authored-by: codex <[email protected]>
2026-06-16 23:47:55 -07:00
Julius Marminge 55228d4119 rm doc 2026-06-16 23:38:01 -07:00
Julius Marminge ebda0b6d28 rm service indirection 2026-06-16 23:38:01 -07:00
Julius Marmingeandcodex bd079220f8 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-16 23:38:01 -07:00
Julius Marmingeandcodex c1281076e6 Merge origin/main into codex/connection-state-audit
Co-authored-by: codex <[email protected]>
2026-06-16 16:47:56 -07:00
Julius Marmingeandcodex 449d7993d1 Centralize client runtime state management
Co-authored-by: codex <[email protected]>
2026-06-16 15:42:37 -07:00
Julius Marmingeandcodex 2eaface4b1 Rewrite client connection architecture
Move web, desktop, server, and mobile connection state onto the shared client runtime while preserving the separately reviewed native mobile UI stack.

Co-authored-by: codex <[email protected]>
2026-06-16 11:11:45 -07:00
589 changed files with 36693 additions and 53089 deletions

No files matched your search

-46
View File
@@ -60,52 +60,6 @@ jobs:
- name: Test
run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
@@ -0,0 +1,297 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform";
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
const decodeConnectionCatalog = Schema.decodeEffect(
Schema.fromJsonString(ConnectionCatalogDocument),
);
function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean> | null = null) {
return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)),
decryptString: (value) => {
return Effect.gen(function* () {
const decoded = textDecoder.decode(value);
if (
!decoded.startsWith("encrypted:") ||
(failDecrypt !== null && (yield* Ref.get(failDecrypt)))
) {
return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({
cause: new Error("invalid encrypted catalog"),
});
}
return decoded.slice("encrypted:".length);
});
},
} satisfies ElectronSafeStorage.ElectronSafeStorageShape);
}
function makeLayer(
baseDir: string,
encryptionAvailable = true,
failDecrypt: Ref.Ref<boolean> | null = null,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = NodeServices.layer,
) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
const safeStorageLayer = makeSafeStorageLayer(encryptionAvailable, failDecrypt);
const dependencies = Layer.mergeAll(
environmentLayer,
safeStorageLayer,
NodeServices.layer,
fileSystemLayer,
);
const savedEnvironmentsLayer = DesktopSavedEnvironments.layer.pipe(
Layer.provideMerge(dependencies),
);
return DesktopConnectionCatalogStore.layer.pipe(
Layer.provideMerge(savedEnvironmentsLayer),
Layer.provideMerge(dependencies),
);
}
const withStore = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopConnectionCatalogStore.DesktopConnectionCatalogStore>,
encryptionAvailable = true,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer(baseDir, encryptionAvailable)));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopConnectionCatalogStore", () => {
it.effect("persists, reads, and clears an encrypted connection catalog", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalog = '{"schemaVersion":1,"targets":[]}';
assert.isTrue(yield* store.set(catalog));
assert.deepStrictEqual(yield* store.get, Option.some(catalog));
yield* store.clear;
assert.deepStrictEqual(yield* store.get, Option.none());
}),
),
);
it.effect("does not persist when secure storage is unavailable", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
assert.isFalse(yield* store.set("{}"));
assert.deepStrictEqual(yield* store.get, Option.none());
}),
false,
),
);
it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>
withStore(
Effect.gen(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const records: readonly PersistedSavedEnvironmentRecord[] = [
{
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
httpBaseUrl: "https://relay.example.com/",
wsBaseUrl: "wss://relay.example.com/",
createdAt: "2026-06-01T00:00:00.000Z",
lastConnectedAt: null,
relayManaged: { relayUrl: "https://relay-control.example.com/" },
},
{
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
httpBaseUrl: "http://127.0.0.1:41773/",
wsBaseUrl: "ws://127.0.0.1:41773/",
createdAt: "2026-06-02T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
{
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
createdAt: "2026-06-03T00:00:00.000Z",
lastConnectedAt: null,
},
];
yield* savedEnvironments.setRegistry(records);
assert.isTrue(
yield* savedEnvironments.setSecret({
environmentId: EnvironmentId.make("bearer-environment"),
secret: "legacy-token",
}),
);
const migrated = yield* store.get;
assert.isTrue(Option.isSome(migrated));
if (Option.isNone(migrated)) {
return;
}
const catalog = yield* decodeConnectionCatalog(migrated.value);
assert.deepInclude(catalog.targets[0], {
_tag: "RelayConnectionTarget",
environmentId: EnvironmentId.make("relay-environment"),
label: "Relay",
});
assert.deepInclude(catalog.targets[1], {
_tag: "SshConnectionTarget",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
connectionId: "ssh:ssh-environment",
});
assert.deepInclude(catalog.targets[2], {
_tag: "BearerConnectionTarget",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
connectionId: "bearer:bearer-environment",
});
assert.deepInclude(catalog.profiles[0], {
_tag: "SshConnectionProfile",
connectionId: "ssh:ssh-environment",
environmentId: EnvironmentId.make("ssh-environment"),
label: "SSH",
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
});
assert.deepInclude(catalog.profiles[1], {
_tag: "BearerConnectionProfile",
connectionId: "bearer:bearer-environment",
environmentId: EnvironmentId.make("bearer-environment"),
label: "Bearer",
httpBaseUrl: "https://bearer.example.com/",
wsBaseUrl: "wss://bearer.example.com/",
});
assert.equal(catalog.credentials.length, 1);
assert.equal(catalog.credentials[0]?.connectionId, "bearer:bearer-environment");
assert.equal(catalog.credentials[0]?.credential._tag, "BearerConnectionCredential");
if (catalog.credentials[0]?.credential._tag === "BearerConnectionCredential") {
assert.equal(catalog.credentials[0].credential.token, "legacy-token");
}
yield* savedEnvironments.setRegistry([]);
assert.deepEqual(yield* store.get, migrated);
}),
),
);
it.effect("surfaces malformed catalog documents without deleting them", () =>
withStore(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
const catalogPath = `${environment.stateDir}/connection-catalog.json`;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(catalogPath, "{not-json");
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(yield* fileSystem.readFileString(catalogPath), "{not-json");
}),
),
);
it.effect("surfaces catalog filesystem failures instead of treating them as missing", () =>
Effect.gen(function* () {
const baseFileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(makeLayer(baseDir, true, null, fileSystemLayer)),
);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.cause, permissionError);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-connection-catalog-test-",
});
const failDecrypt = yield* Ref.make(false);
const layer = makeLayer(baseDir, true, failDecrypt);
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe(
Effect.provide(layer),
);
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
yield* Ref.set(failDecrypt, true);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
@@ -0,0 +1,332 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionTarget,
RelayConnectionTarget,
SshConnectionProfile,
SshConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
ConnectionCatalogDocument as RuntimeConnectionCatalogDocument,
type ConnectionCatalogDocument as RuntimeConnectionCatalogDocumentType,
} from "@t3tools/client-runtime/platform";
import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const EncryptedConnectionCatalogDocument = Schema.Struct({
version: Schema.Literal(1),
encryptedCatalog: Schema.String,
});
type EncryptedConnectionCatalogDocument = typeof EncryptedConnectionCatalogDocument.Type;
const EncryptedConnectionCatalogDocumentJson = fromLenientJson(EncryptedConnectionCatalogDocument);
const decodeEncryptedConnectionCatalogDocumentJson = Schema.decodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const encodeEncryptedConnectionCatalogDocumentJson = Schema.encodeEffect(
EncryptedConnectionCatalogDocumentJson,
);
const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString(
RuntimeConnectionCatalogDocument,
);
const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect(
RuntimeConnectionCatalogDocumentJson,
);
export class DesktopConnectionCatalogStoreWriteError extends Data.TaggedError(
"DesktopConnectionCatalogStoreWriteError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to write desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreDecodeError extends Data.TaggedError(
"DesktopConnectionCatalogStoreDecodeError",
)<{
readonly cause: Encoding.EncodingError;
}> {
override get message() {
return "Failed to decode the desktop connection catalog.";
}
}
export class DesktopConnectionCatalogStoreReadError extends Data.TaggedError(
"DesktopConnectionCatalogStoreReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop connection catalog: ${this.cause.message}`;
}
}
export class DesktopConnectionCatalogStoreMigrationError extends Data.TaggedError(
"DesktopConnectionCatalogStoreMigrationError",
)<{
readonly cause: unknown;
}> {
override get message() {
return "Failed to migrate legacy desktop saved environments.";
}
}
export interface DesktopConnectionCatalogStoreShape {
readonly get: Effect.Effect<
Option.Option<string>,
| DesktopConnectionCatalogStoreReadError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
| DesktopConnectionCatalogStoreWriteError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageEncryptError
>;
readonly clear: Effect.Effect<void>;
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
DesktopConnectionCatalogStoreShape
>()("@t3tools/desktop/app/DesktopConnectionCatalogStore") {}
function decodeSecretBytes(
encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),
);
}
const readDocument = (
fileSystem: FileSystem.FileSystem,
catalogPath: string,
): Effect.Effect<
Option.Option<EncryptedConnectionCatalogDocument>,
PlatformError.PlatformError | Schema.SchemaError
> =>
fileSystem.readFileString(catalogPath).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed(Option.none<EncryptedConnectionCatalogDocument>())
: decodeEncryptedConnectionCatalogDocumentJson(raw).pipe(Effect.map(Option.some)),
),
);
const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(function* (input: {
readonly fileSystem: FileSystem.FileSystem;
readonly path: Path.Path;
readonly catalogPath: string;
readonly document: EncryptedConnectionCatalogDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* Effect.gen(function* () {
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
yield* input.fileSystem.rename(tempPath, input.catalogPath);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not remove a temporary connection catalog file.", {
tempPath,
error,
}),
),
),
),
);
});
function connectionId(prefix: "bearer" | "ssh", environmentId: string): string {
return `${prefix}:${environmentId}`;
}
const migrateSavedEnvironmentRecords = Effect.fn(
"desktop.connectionCatalogStore.migrateSavedEnvironmentRecords",
)(function* (
records: readonly PersistedSavedEnvironmentRecord[],
savedEnvironments: DesktopSavedEnvironments.DesktopSavedEnvironmentsShape,
): Effect.fn.Return<
RuntimeConnectionCatalogDocumentType,
DesktopSavedEnvironments.DesktopSavedEnvironmentsGetSecretError
> {
const targets: Array<RuntimeConnectionCatalogDocumentType["targets"][number]> = [];
const profiles: Array<RuntimeConnectionCatalogDocumentType["profiles"][number]> = [];
const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];
for (const record of records) {
if (record.relayManaged !== undefined) {
targets.push(
new RelayConnectionTarget({
environmentId: record.environmentId,
label: record.label,
}),
);
continue;
}
if (record.desktopSsh !== undefined) {
const id = connectionId("ssh", record.environmentId);
targets.push(
new SshConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new SshConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
target: record.desktopSsh,
}),
);
continue;
}
const id = connectionId("bearer", record.environmentId);
targets.push(
new BearerConnectionTarget({
environmentId: record.environmentId,
label: record.label,
connectionId: id,
}),
);
profiles.push(
new BearerConnectionProfile({
connectionId: id,
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments.getSecret(record.environmentId);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
credential: new BearerConnectionCredential({ token: token.value }),
});
}
}
return {
schemaVersion: 1,
targets,
profiles,
credentials,
remoteDpopTokens: [],
};
});
export const layer = Layer.effect(
DesktopConnectionCatalogStore,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
path,
catalogPath,
document: { version: 1, encryptedCatalog },
suffix,
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreWriteError({ cause })));
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry;
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);
yield* writeCatalog(encoded);
return Option.some(encoded);
}).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));
return DesktopConnectionCatalogStore.of({
get: Effect.gen(function* () {
const document = yield* readDocument(fileSystem, catalogPath).pipe(
Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),
);
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* safeStorage.isEncryptionAvailable)) {
return yield* new ElectronSafeStorage.ElectronSafeStorageAvailabilityError({
cause: new Error(
"Safe storage encryption is unavailable; cannot decrypt the existing connection catalog",
),
});
}
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
return true;
}),
clear: fileSystem.remove(catalogPath, { force: true }).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not clear the desktop connection catalog.", {
catalogPath,
error,
}),
),
Effect.withSpan("desktop.connectionCatalogStore.clear"),
),
});
}),
);
@@ -1,9 +1,9 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Electron from "electron";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError",
+7 -11
View File
@@ -10,12 +10,10 @@ import {
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import {
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
setSavedEnvironmentRegistry,
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
clearConnectionCatalog,
getConnectionCatalog,
setConnectionCatalog,
} from "./methods/connectionCatalog.ts";
import {
getAdvertisedEndpoints,
getServerExposureState,
@@ -59,11 +57,9 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings);
yield* ipc.handle(getSavedEnvironmentRegistry);
yield* ipc.handle(setSavedEnvironmentRegistry);
yield* ipc.handle(getSavedEnvironmentSecret);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment);
+3 -5
View File
@@ -20,11 +20,9 @@ export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
export const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
export const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
export const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
export const GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
+1 -1
View File
@@ -59,7 +59,7 @@ function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInpu
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers),
HttpClientRequest.setHeaders(Object.fromEntries(headers.entries())),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
@@ -0,0 +1,37 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopConnectionCatalogStore from "../../app/DesktopConnectionCatalogStore.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getConnectionCatalog = makeIpcMethod({
channel: IpcChannels.GET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.connectionCatalog.get")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return Option.getOrNull(yield* store.get);
}),
});
export const setConnectionCatalog = makeIpcMethod({
channel: IpcChannels.SET_CONNECTION_CATALOG_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.connectionCatalog.set")(function* (catalog) {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
return yield* store.set(catalog);
}),
});
export const clearConnectionCatalog = makeIpcMethod({
channel: IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.connectionCatalog.clear")(function* () {
const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;
yield* store.clear;
}),
});
@@ -1,76 +0,0 @@
import { EnvironmentId, PersistedSavedEnvironmentRecordSchema } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopSavedEnvironments from "../../settings/DesktopSavedEnvironments.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const SavedEnvironmentRegistryPayload = Schema.Array(PersistedSavedEnvironmentRecordSchema);
const NonBlankString = Schema.String.check(
Schema.makeFilter((value) =>
value.trim().length > 0 ? undefined : "Expected a non-empty string",
),
);
const SetSavedEnvironmentSecretInput = Schema.Struct({
environmentId: EnvironmentId,
secret: NonBlankString,
});
export const getSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: Schema.Void,
result: SavedEnvironmentRegistryPayload,
handler: Effect.fn("desktop.ipc.savedEnvironments.getRegistry")(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.getRegistry;
}),
});
export const setSavedEnvironmentRegistry = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL,
payload: SavedEnvironmentRegistryPayload,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.setRegistry")(function* (records) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry(records);
}),
});
export const getSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.savedEnvironments.getSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return Option.getOrNull(yield* savedEnvironments.getSecret(environmentId));
}),
});
export const setSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: SetSavedEnvironmentSecretInput,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.savedEnvironments.setSecret")(function* ({
environmentId,
secret,
}) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
return yield* savedEnvironments.setSecret({
environmentId,
secret,
});
}),
});
export const removeSavedEnvironmentSecret = makeIpcMethod({
channel: IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
payload: EnvironmentId,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.savedEnvironments.removeSecret")(function* (environmentId) {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.removeSecret(environmentId);
}),
});
@@ -1,11 +1,11 @@
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import {
EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema,
+2 -1
View File
@@ -29,6 +29,7 @@ import * as DesktopApp from "./app/DesktopApp.ts";
import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
@@ -117,7 +118,7 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer,
DesktopClientSettings.layer,
DesktopSavedEnvironments.layer,
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer,
DesktopObservability.layer,
+4 -10
View File
@@ -42,16 +42,10 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
getSavedEnvironmentRegistry: () =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, { environmentId, secret }),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(IpcChannels.REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
setConnectionCatalog: (catalog) =>
ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
@@ -289,7 +289,7 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("treats malformed saved environment documents as empty", () =>
it.effect("surfaces malformed saved environment documents", () =>
withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -298,10 +298,15 @@ describe("DesktopSavedEnvironments", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.instanceOf(
registryError,
DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError,
);
const secretError = yield* savedEnvironments
.getSecret(savedRegistryRecord.environmentId)
.pipe(Effect.flip);
assert.instanceOf(secretError, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError);
}),
),
);
@@ -82,6 +82,16 @@ export class DesktopSavedEnvironmentsWriteError extends Data.TaggedError(
}
}
export class DesktopSavedEnvironmentsReadError extends Data.TaggedError(
"DesktopSavedEnvironmentsReadError",
)<{
readonly cause: PlatformError.PlatformError | Schema.SchemaError;
}> {
override get message() {
return `Failed to read desktop saved environments: ${this.cause.message}`;
}
}
export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentSecretDecodeError",
)<{
@@ -93,6 +103,7 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
}
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError;
@@ -103,7 +114,10 @@ export type DesktopSavedEnvironmentsSetSecretError =
| ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>;
readonly getRegistry: Effect.Effect<
readonly PersistedSavedEnvironmentRecord[],
DesktopSavedEnvironmentsReadError
>;
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
@@ -176,18 +190,20 @@ function normalizeSavedEnvironmentRegistryDocument(
function readRegistryDocument(
fileSystem: FileSystem.FileSystem,
registryPath: string,
): Effect.Effect<SavedEnvironmentRegistryDocument> {
): Effect.Effect<
SavedEnvironmentRegistryDocument,
PlatformError.PlatformError | Schema.SchemaError
> {
return fileSystem.readFileString(registryPath).pipe(
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed({ version: 1, records: [] }),
onSome: (raw) =>
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.catch((error) =>
error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
),
Effect.flatMap((raw) =>
raw === null
? Effect.succeed({ version: 1, records: [] })
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
),
}),
),
);
}
@@ -267,13 +283,14 @@ export const layer = Layer.effect(
Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
Effect.withSpan("desktop.savedEnvironments.getRegistry"),
),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
@@ -281,7 +298,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
@@ -299,7 +316,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
@@ -331,7 +348,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
);
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (
!document.records.some(
(record) =>
+5
View File
@@ -131,6 +131,11 @@ const config: ExpoConfig = {
{
ios: {
deploymentTarget: "18.0",
// AppCheckCore 11.3+ includes Swift and needs module maps for these Objective-C dependencies.
extraPods: [
{ name: "GoogleUtilities", modular_headers: true },
{ name: "RecaptchaInterop", modular_headers: true },
],
},
},
],
+2 -1
View File
@@ -1,7 +1,8 @@
{
"cli": {
"version": ">= 18.4.0",
"appVersionSource": "remote"
"appVersionSource": "remote",
"promptToConfigurePushNotifications": false
},
"build": {
"development": {
+1
View File
@@ -77,6 +77,7 @@
"expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12",
"expo-network": "~56.0.5",
"expo-notifications": "~56.0.14",
"expo-paste-input": "^0.1.15",
"expo-router": "~56.2.7",
+5 -8
View File
@@ -16,10 +16,8 @@ import { useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import {
useRemoteEnvironmentBootstrap,
useRemoteEnvironmentState,
} from "../state/use-remote-environment-registry";
import { useWorkspaceState } from "../state/workspace";
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
@@ -42,12 +40,13 @@ function AppNavigator() {
}
function AppNavigatorContent() {
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const { state } = useWorkspaceState();
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
useAgentNotificationNavigation();
useThreadOutboxDrain();
const handleSettingsTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
@@ -81,7 +80,7 @@ function AppNavigatorContent() {
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
};
if (isLoadingSavedConnection) {
if (state.isLoadingConnections) {
return <LoadingScreen message="Loading remote workspace…" />;
}
@@ -129,8 +128,6 @@ export default function RootLayout() {
DMSans_500Medium,
DMSans_700Bold,
});
useRemoteEnvironmentBootstrap();
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
+6 -5
View File
@@ -1,5 +1,6 @@
import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useState } from "react";
import { Alert, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -111,12 +112,12 @@ export default function ConnectionsNewRouteScreen() {
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
try {
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
await onConnectPress(pairingUrl);
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
const result = await onConnectPress(pairingUrl);
if (AsyncResult.isSuccess(result)) {
dismissRoute(router);
} catch {
} else {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
+12 -4
View File
@@ -2,17 +2,20 @@ import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Text as RNText, View } from "react-native";
import { useProjects, useThreadShells } from "../state/entities";
import { useWorkspaceState } from "../state/workspace";
import { buildThreadRoutePath } from "../lib/routes";
import { useRemoteCatalog } from "../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { useThemeColor } from "../lib/useThemeColor";
/* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() {
const { projects, state: catalogState, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
@@ -32,9 +35,13 @@ export default function HomeRouteScreen() {
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
hideNavigationBar: false,
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
allowToolbarIntegration: true,
},
}}
@@ -104,6 +111,7 @@ export default function HomeRouteScreen() {
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
onAddConnection={() => router.push("/connections/new")}
onOpenEnvironments={() => router.push("/settings/environments")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
@@ -1,5 +1,5 @@
import { Stack, useLocalSearchParams } from "expo-router";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime";
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
+16 -14
View File
@@ -8,16 +8,17 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { useProjects, useThreadShells } from "../../state/entities";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { type RemoteCatalogState, useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
function deriveProjectEmptyState(catalogState: WorkspaceState): {
readonly title: string;
readonly detail: string;
readonly loading: boolean;
} {
if (catalogState.isLoadingSavedConnections) {
if (catalogState.isLoadingConnections) {
return {
title: "Loading environments",
detail: "Checking saved environments on this device.",
@@ -25,7 +26,7 @@ function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
};
}
if (!catalogState.hasSavedConnections) {
if (!catalogState.hasConnections) {
return {
title: "No environments connected",
detail: "Add an environment before creating a task.",
@@ -33,7 +34,12 @@ function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
};
}
if (catalogState.connectionState === "disconnected" && !catalogState.hasLoadedShellSnapshot) {
if (
(catalogState.connectionState === "available" ||
catalogState.connectionState === "offline" ||
catalogState.connectionState === "error") &&
!catalogState.hasLoadedShellSnapshot
) {
return {
title: "Environment unavailable",
detail:
@@ -63,8 +69,9 @@ function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
}
export default function NewTaskRoute() {
const { projects, state: catalogState, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const projects = useProjects();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const router = useRouter();
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
@@ -183,15 +190,10 @@ export default function NewTaskRoute() {
<View className="flex-row items-center justify-between gap-3">
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={item.environmentId}
size={20}
projectTitle={item.title}
httpBaseUrl={
savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null
}
workspaceRoot={item.workspaceRoot}
bearerToken={
savedConnectionsById[item.environmentId]?.bearerToken ?? null
}
/>
</View>
<View className="flex-1">
+291 -110
View File
@@ -1,32 +1,38 @@
import { useAuth } from "@clerk/expo";
import { Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
ScrollView,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { connectCloudEnvironment } from "../../features/cloud/linkEnvironment";
import {
hasCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "../../features/cloud/publicConfig";
import {
useManagedRelayEnvironments,
useManagedRelayEnvironmentStatus,
} from "../../features/cloud/managedRelayState";
type RelayEnvironmentView,
useConnectionController,
} from "../../features/connection/useConnectionController";
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
import { availableCloudEnvironmentPresentation } from "../../features/cloud/cloudEnvironmentPresentation";
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
import { ConnectionStatusDot } from "../../features/connection/ConnectionStatusDot";
import { splitEnvironmentSections } from "../../features/connection/environmentSections";
import { cn } from "../../lib/cn";
import { mobileRuntime } from "../../lib/runtime";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import {
connectSavedEnvironment,
useRemoteConnections,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
export default function SettingsEnvironmentsRouteScreen() {
const {
@@ -37,7 +43,11 @@ export default function SettingsEnvironmentsRouteScreen() {
} = useRemoteConnections();
const router = useRouter();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const { localEnvironments, connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
cloudEnvironments: null,
});
const hasLocalEnvironments = localEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const accentColor = useThemeColor("--color-icon-muted");
@@ -69,9 +79,9 @@ export default function SettingsEnvironmentsRouteScreen() {
paddingTop: 16,
}}
>
{hasEnvironments ? (
{hasLocalEnvironments ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{connectedEnvironments.map((environment, index) => (
{localEnvironments.map((environment, index) => (
<View
key={environment.environmentId}
collapsable={false}
@@ -108,54 +118,43 @@ export default function SettingsEnvironmentsRouteScreen() {
</View>
)}
{hasCloudPublicConfig() ? <ConfiguredCloudEnvironmentRows /> : null}
{hasCloudPublicConfig() ? (
<ConfiguredCloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
/>
) : null}
</ScrollView>
</View>
);
}
function ConfiguredCloudEnvironmentRows() {
const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { savedConnectionsById } = useRemoteEnvironmentState();
const cloudEnvironmentsState = useManagedRelayEnvironments();
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
null,
);
function ConfiguredCloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = useMemo(
() =>
(cloudEnvironmentsState.data ?? []).filter(
(environment) => savedConnectionsById[environment.environmentId] === undefined,
),
[cloudEnvironmentsState.data, savedConnectionsById],
);
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
async (environment: RelayClientEnvironmentRecord) => {
setConnectingCloudEnvironmentId(environment.environmentId);
try {
const token = await getToken(resolveRelayClerkTokenOptions());
if (!token) {
throw new Error("Sign in to T3 Cloud before connecting.");
}
await mobileRuntime.runPromise(
connectCloudEnvironment({
clerkToken: token,
environment,
}).pipe(Effect.flatMap(connectSavedEnvironment)),
);
} catch (error) {
Alert.alert(
"Connect failed",
error instanceof Error ? error.message : "Could not connect to this environment.",
);
} finally {
setConnectingCloudEnvironmentId(null);
}
},
[getToken],
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
if (!isSignedIn) return null;
return (
@@ -164,11 +163,13 @@ function ConfiguredCloudEnvironmentRows() {
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={cloudEnvironmentsState.isPending}
onPress={cloudEnvironmentsState.refresh}
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{cloudEnvironmentsState.isPending ? (
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
@@ -176,33 +177,48 @@ function ConfiguredCloudEnvironmentRows() {
</Pressable>
</View>
{availableCloudEnvironments.length > 0 ? (
{hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
isConnecting={connectingCloudEnvironmentId === environment.environmentId}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : cloudEnvironmentsState.data === null ? (
) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : cloudEnvironmentsState.error ? (
) : controller.relayDiscovery.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-[15px] font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-[13px] leading-[18px] text-foreground-muted">
{cloudEnvironmentsState.error}
{controller.relayDiscovery.error}
</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
@@ -215,23 +231,128 @@ function ConfiguredCloudEnvironmentRows() {
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayClientEnvironmentRecord;
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly isConnecting: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
const mutedColor = useThemeColor("--color-icon-muted");
const statusState = useManagedRelayEnvironmentStatus(props.environment);
const status = statusState.data;
const disabled = props.isConnecting;
const statusText =
status === null
? (statusState.error ?? (statusState.isPending ? "Checking status..." : "Status unavailable"))
: status.status === "online"
? "Online"
: (status.error ?? "Offline");
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={
props.environment.connectionState === "connected" ||
props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting"
}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
return (
<View
collapsable={false}
@@ -240,36 +361,96 @@ function CloudEnvironmentRow(props: {
props.borderTop && "border-t border-border",
)}
>
<View className="h-9 w-9 items-center justify-center rounded-[14px] bg-subtle">
<SymbolView
name="cloud"
size={17}
tintColor={mutedColor}
type="monochrome"
weight="semibold"
/>
</View>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-[16px] font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
{props.environment.label}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{props.environment.endpoint.httpBaseUrl}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{statusText}
</Text>
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-[16px] font-t3-bold leading-[21px] text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-[12px] leading-[16px]", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-[12px] leading-[16px]", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-[12px] leading-[16px] underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId);
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
</View>
<Pressable
accessibilityRole="button"
disabled={disabled}
onPress={props.onConnect}
className="min-h-[40px] min-w-[88px] items-center justify-center rounded-[14px] bg-primary px-4 active:opacity-70 disabled:opacity-50"
>
<Text className="text-[13px] font-t3-bold text-primary-foreground">
{props.isConnecting ? "Connecting" : "Connect"}
</Text>
</Pressable>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId);
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-[12px] font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
+136 -81
View File
@@ -8,6 +8,13 @@ import type { ComponentProps, ReactNode } from "react";
import { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
isAtomCommandInterrupted,
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { AppText as Text } from "../../components/AppText";
import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences";
import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
@@ -18,10 +25,10 @@ import {
hasCloudPublicConfig,
resolveRelayClerkTokenOptions,
} from "../../features/cloud/publicConfig";
import { mobileRuntime } from "../../lib/runtime";
import { runtime } from "../../lib/runtime";
import { loadPreferences } from "../../lib/storage";
import { useThemeColor } from "../../lib/useThemeColor";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
@@ -32,7 +39,7 @@ export default function SettingsRouteScreen() {
function LocalSettingsRouteScreen() {
const insets = useSafeAreaInsets();
const { savedConnectionsById } = useRemoteEnvironmentState();
const { savedConnectionsById } = useSavedRemoteConnections();
const environmentCount = Object.keys(savedConnectionsById).length;
return (
@@ -70,7 +77,7 @@ function ConfiguredSettingsRouteScreen() {
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { savedConnectionsById } = useRemoteEnvironmentState();
const { savedConnectionsById } = useSavedRemoteConnections();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
@@ -87,8 +94,13 @@ function ConfiguredSettingsRouteScreen() {
setNotificationStatus("unsupported");
return;
}
const permission = await Notifications.getPermissionsAsync();
setNotificationStatus(permission.granted ? "enabled" : "disabled");
const result = await settlePromise(() => Notifications.getPermissionsAsync());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "notification permission refresh" });
setNotificationStatus("disabled");
return;
}
setNotificationStatus(result.value.granted ? "enabled" : "disabled");
}, []);
useEffect(() => {
@@ -104,60 +116,66 @@ function ConfiguredSettingsRouteScreen() {
setLiveActivityStatus("signed-out");
return;
}
void loadPreferences().then(
(preferences) => {
setLiveActivityStatus(preferences.liveActivitiesEnabled === false ? "disabled" : "enabled");
},
() => {
void (async () => {
const result = await settlePromise(() => loadPreferences());
if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "live activity preference load" });
setLiveActivityStatus("enabled");
},
);
return;
}
setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
})();
}, [isLoaded, isSignedIn]);
const requestNotifications = useCallback(async () => {
try {
const result = await mobileRuntime.runPromise(
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(
requestAgentNotificationPermission.pipe(
Effect.tap((permission) =>
permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
),
),
);
if (result.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
return;
}
if (result.type === "unsupported") {
setNotificationStatus("unsupported");
),
);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
Alert.alert(
"Notifications unavailable",
"Live Activity notifications are only available on iOS.",
error instanceof Error ? error.message : "Could not request notification permission.",
);
return;
}
setNotificationStatus("disabled");
if (result.canAskAgain) {
Alert.alert("Notifications disabled", "Notifications were not enabled.");
return;
}
return;
}
if (result.value.type === "granted") {
setNotificationStatus("enabled");
Alert.alert(
"Notifications disabled",
"Notifications were denied for this app. Open Settings to enable them.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
"Notifications enabled",
"Live Activity notifications are enabled for this device.",
);
} catch (error) {
return;
}
if (result.value.type === "unsupported") {
setNotificationStatus("unsupported");
Alert.alert(
"Notifications unavailable",
error instanceof Error ? error.message : "Could not request notification permission.",
"Live Activity notifications are only available on iOS.",
);
return;
}
setNotificationStatus("disabled");
if (result.value.canAskAgain) {
Alert.alert("Notifications disabled", "Notifications were not enabled.");
return;
}
Alert.alert(
"Notifications disabled",
"Notifications were denied for this app. Open Settings to enable them.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
}, []);
const promptSignIn = useCallback(() => {
@@ -178,36 +196,51 @@ function ConfiguredSettingsRouteScreen() {
}
setLiveActivityStatus("linking");
try {
const token = await getToken(resolveRelayClerkTokenOptions());
if (!token) {
promptSignIn();
setLiveActivityStatus("signed-out");
return;
}
await mobileRuntime.runPromise(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: token,
connections,
}),
);
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
} catch (error) {
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (tokenResult._tag === "Failure") {
setLiveActivityStatus("disabled");
const error = squashAtomCommandFailure(tokenResult);
Alert.alert(
"Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
);
return;
}
if (!tokenResult.value) {
promptSignIn();
setLiveActivityStatus("signed-out");
return;
}
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: tokenResult.value,
connections,
}),
),
);
if (updateResult._tag === "Failure") {
setLiveActivityStatus("disabled");
if (!isAtomCommandInterrupted(updateResult)) {
const error = squashAtomCommandFailure(updateResult);
Alert.alert(
"Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.",
);
}
return;
}
refreshManagedRelayEnvironments();
setLiveActivityStatus("enabled");
Alert.alert(
"Live Activities enabled",
environmentCount > 0
? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`
: "Live Activity updates are enabled. Add an environment to start receiving updates.",
);
}, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
const handleDeviceNotificationsChange = useCallback(
@@ -234,19 +267,36 @@ function ConfiguredSettingsRouteScreen() {
if (!enabled) {
setLiveActivityStatus("disabled");
void (async () => {
try {
const token = isSignedIn ? await getToken(resolveRelayClerkTokenOptions()) : null;
await mobileRuntime.runPromise(
let token: string | null = null;
if (isSignedIn) {
const tokenResult = await settlePromise(() =>
getToken(resolveRelayClerkTokenOptions()),
);
if (tokenResult._tag === "Failure") {
reportAtomCommandResult(tokenResult, {
label: "live activity disable token lookup",
});
return;
}
token = tokenResult.value;
}
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: token,
connections,
}),
);
refreshManagedRelayEnvironments();
} catch {
// The switch is optimistic; a future refresh reconciles relay state.
),
);
if (updateResult._tag === "Failure") {
reportAtomCommandResult(updateResult, {
label: "live activity disable",
});
return;
}
refreshManagedRelayEnvironments();
})();
return;
}
@@ -382,15 +432,20 @@ function SettingsRow(props: {
style={{ opacity: props.disabled ? 0.45 : 1 }}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text>
{props.value ? (
<Text
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
numberOfLines={1}
>
{props.value}
</Text>
) : null}
<Text className="shrink-0 text-[17px] text-foreground" numberOfLines={1}>
{props.label}
</Text>
<View className="min-w-0 flex-1 items-end">
{props.value ? (
<Text
className="max-w-[180px] text-right text-[16px] text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{props.value}
</Text>
) : null}
</View>
<SymbolView
name="chevron.right"
size={16}
+45 -24
View File
@@ -1,65 +1,86 @@
import { SymbolView } from "expo-symbols";
import { useState } from "react";
import { Image, View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
const loadedFaviconUrls = new Set<string>();
/* ─── Component ──────────────────────────────────────────────────────── */
export function ProjectFavicon(props: {
readonly environmentId: EnvironmentId;
readonly size?: number;
readonly projectTitle: string;
readonly httpBaseUrl?: string | null;
readonly workspaceRoot?: string | null;
readonly bearerToken?: string | null;
}) {
const size = props.size ?? 42;
const iconMuted = useThemeColor("--color-icon-subtle");
const faviconUrl =
props.httpBaseUrl && props.workspaceRoot
? `${props.httpBaseUrl}/api/project-favicon?cwd=${encodeURIComponent(props.workspaceRoot)}`
: null;
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
faviconUrl && loadedFaviconUrls.has(faviconUrl) ? "loaded" : "loading",
const faviconUrl = useAssetUrl(
props.environmentId,
props.workspaceRoot === null || props.workspaceRoot === undefined
? null
: { _tag: "project-favicon", cwd: props.workspaceRoot },
);
const showImage = faviconUrl && status === "loaded";
return (
<ProjectFaviconImage
key={faviconUrl}
faviconUrl={faviconUrl}
projectTitle={props.projectTitle}
size={size}
/>
);
}
function ProjectFaviconImage(props: {
readonly faviconUrl: string | null;
readonly projectTitle: string;
readonly size: number;
}) {
const iconMuted = useThemeColor("--color-icon-subtle");
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
props.faviconUrl && loadedFaviconUrls.has(props.faviconUrl) ? "loaded" : "loading",
);
const showImage = props.faviconUrl !== null && status === "loaded";
return (
<View
style={{
width: size,
height: size,
width: props.size,
height: props.size,
alignItems: "center",
justifyContent: "center",
}}
>
{/* Folder icon fallback (matches web's FolderIcon) */}
{!showImage ? (
<SymbolView name="folder.fill" size={size * 0.78} tintColor={iconMuted} type="monochrome" />
<SymbolView
name="folder.fill"
size={props.size * 0.78}
tintColor={iconMuted}
type="monochrome"
/>
) : null}
{/* Favicon image (hidden until loaded) */}
{faviconUrl ? (
{props.faviconUrl ? (
<Image
source={{
uri: faviconUrl,
...(props.bearerToken
? { headers: { Authorization: `Bearer ${props.bearerToken}` } }
: {}),
uri: props.faviconUrl,
}}
accessibilityLabel={`${props.projectTitle} favicon`}
style={{
width: size,
height: size,
borderRadius: size * 0.16,
width: props.size,
height: props.size,
borderRadius: props.size * 0.16,
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
}}
resizeMode="contain"
onLoad={() => {
if (faviconUrl) loadedFaviconUrls.add(faviconUrl);
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
setStatus("loaded");
}}
onError={() => setStatus("error")}
+122
View File
@@ -0,0 +1,122 @@
import {
ConnectionCatalogDocument,
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
} from "@t3tools/client-runtime/platform";
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { migrateLegacyConnectionCatalog } from "./migration";
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => catalogError("decode", cause),
});
return yield* Effect.fromResult(
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
});
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
catalog: ConnectionCatalogDocumentType,
) {
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
return JSON.stringify(encoded);
});
interface CatalogStore {
readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
readonly update: (
transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,
) => Effect.Effect<void, ConnectionTransientError>;
}
export interface SecureCatalogStorage {
readonly getItem: (key: string) => Effect.Effect<string | null, ConnectionTransientError>;
readonly setItem: (key: string, value: string) => Effect.Effect<void, ConnectionTransientError>;
readonly deleteItem: (key: string) => Effect.Effect<void, ConnectionTransientError>;
}
export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogStore")(function* (
storage: SecureCatalogStorage,
) {
const state = yield* Ref.make<Option.Option<ConnectionCatalogDocumentType>>(Option.none());
const lock = yield* Semaphore.make(1);
const loadLegacyCatalog = Effect.fn("mobile.connectionStorage.loadLegacyCatalog")(function* () {
const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY);
const catalog =
legacyRaw === null || legacyRaw.trim() === ""
? EMPTY_CONNECTION_CATALOG_DOCUMENT
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
Effect.mapError((cause) => catalogError("migrate", cause)),
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
),
),
);
if (legacyRaw !== null && legacyRaw.trim() !== "") {
const encoded = yield* encodeCatalog(catalog);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* storage.deleteItem(LEGACY_CONNECTIONS_KEY);
}
return catalog;
});
const loadUnlocked = Effect.fn("mobile.connectionStorage.loadCatalog")(function* () {
const cached = yield* Ref.get(state);
if (Option.isSome(cached)) {
return cached.value;
}
const raw = yield* storage.getItem(CONNECTION_CATALOG_KEY);
let catalog: ConnectionCatalogDocumentType;
if (raw !== null && raw.trim() !== "") {
catalog = yield* decodeCatalog(raw).pipe(
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
),
);
} else {
catalog = yield* loadLegacyCatalog();
}
yield* Ref.set(state, Option.some(catalog));
return catalog;
});
const read = lock.withPermits(1)(loadUnlocked());
const update: CatalogStore["update"] = Effect.fn("mobile.connectionStorage.updateCatalog")(
function* (transform) {
yield* lock.withPermits(1)(
Effect.gen(function* () {
const next = transform(yield* loadUnlocked());
const encoded = yield* encodeCatalog(next);
yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);
yield* Ref.set(state, Option.some(next));
}),
);
},
);
return { read, update } satisfies CatalogStore;
});
+5
View File
@@ -0,0 +1,5 @@
import { createEnvironmentCatalogAtoms } from "@t3tools/client-runtime/state/connections";
import { connectionAtomRuntime } from "./runtime";
export const environmentCatalog = createEnvironmentCatalogAtoms(connectionAtomRuntime);
@@ -0,0 +1,78 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { migrateLegacyConnectionCatalog } from "./migration";
describe("migrateLegacyConnectionCatalog", () => {
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
Effect.gen(function* () {
const bearerEnvironmentId = EnvironmentId.make("bearer-environment");
const relayEnvironmentId = EnvironmentId.make("relay-environment");
const catalog = yield* migrateLegacyConnectionCatalog(
JSON.stringify({
connections: [
{
environmentId: bearerEnvironmentId,
environmentLabel: "Local Mac",
pairingUrl: "https://local.example.test/pair",
displayUrl: "https://local.example.test",
httpBaseUrl: "https://local.example.test",
wsBaseUrl: "wss://local.example.test",
bearerToken: "bearer-token",
authenticationMethod: "bearer",
},
{
environmentId: relayEnvironmentId,
environmentLabel: "Cloud Mac",
pairingUrl: "https://relay.example.test",
displayUrl: "https://relay.example.test",
httpBaseUrl: "https://relay.example.test",
wsBaseUrl: "wss://relay.example.test",
bearerToken: null,
authenticationMethod: "dpop",
relayManaged: true,
},
],
}),
);
expect(catalog.targets).toHaveLength(2);
expect(
catalog.targets.find((target) => target.environmentId === bearerEnvironmentId)?._tag,
).toBe("BearerConnectionTarget");
expect(
catalog.targets.find((target) => target.environmentId === relayEnvironmentId)?._tag,
).toBe("RelayConnectionTarget");
expect(catalog.profiles).toHaveLength(1);
expect(catalog.credentials).toHaveLength(1);
expect(catalog.credentials[0]?.credential).toMatchObject({
_tag: "BearerConnectionCredential",
token: "bearer-token",
});
}),
);
it.effect("drops invalid legacy bearer entries without credentials", () =>
Effect.gen(function* () {
const catalog = yield* migrateLegacyConnectionCatalog(
JSON.stringify({
connections: [
{
environmentId: EnvironmentId.make("invalid-bearer"),
environmentLabel: "Invalid",
pairingUrl: "https://invalid.example.test/pair",
displayUrl: "https://invalid.example.test",
httpBaseUrl: "https://invalid.example.test",
wsBaseUrl: "wss://invalid.example.test",
bearerToken: null,
authenticationMethod: "bearer",
},
],
}),
);
expect(catalog.targets).toEqual([]);
}),
);
});
+110
View File
@@ -0,0 +1,110 @@
import {
BearerConnectionCredential,
BearerConnectionProfile,
BearerConnectionRegistration,
RelayConnectionRegistration,
RelayConnectionTarget,
BearerConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
type ConnectionCatalogDocument,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
registerConnectionInCatalog,
} from "@t3tools/client-runtime/platform";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const LegacySavedRemoteConnection = Schema.Struct({
environmentId: EnvironmentId,
environmentLabel: Schema.String,
pairingUrl: Schema.String,
displayUrl: Schema.String,
httpBaseUrl: Schema.String,
wsBaseUrl: Schema.String,
bearerToken: Schema.NullOr(Schema.String),
authenticationMethod: Schema.optionalKey(Schema.Literals(["bearer", "dpop"])),
dpopAccessToken: Schema.optionalKey(Schema.String),
relayManaged: Schema.optionalKey(Schema.Literal(true)),
});
const LegacyConnectionDocument = Schema.Struct({
connections: Schema.optionalKey(Schema.Array(LegacySavedRemoteConnection)),
});
const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnectionDocument);
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
"LegacyConnectionMigrationError",
{
message: Schema.String,
},
) {}
function isRelayManaged(connection: typeof LegacySavedRemoteConnection.Type): boolean {
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
}
function migrateConnection(
document: ConnectionCatalogDocument,
connection: typeof LegacySavedRemoteConnection.Type,
): ConnectionCatalogDocument {
if (isRelayManaged(connection)) {
return registerConnectionInCatalog(
document,
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: connection.environmentId,
label: connection.environmentLabel,
}),
}),
);
}
if (connection.bearerToken === null || connection.bearerToken.trim() === "") {
return document;
}
const connectionId = `bearer:${connection.environmentId}`;
return registerConnectionInCatalog(
document,
new BearerConnectionRegistration({
target: new BearerConnectionTarget({
environmentId: connection.environmentId,
label: connection.environmentLabel,
connectionId,
}),
profile: new BearerConnectionProfile({
connectionId,
environmentId: connection.environmentId,
label: connection.environmentLabel,
httpBaseUrl: connection.httpBaseUrl,
wsBaseUrl: connection.wsBaseUrl,
}),
credential: new BearerConnectionCredential({
token: connection.bearerToken,
}),
}),
);
}
export const migrateLegacyConnectionCatalog = Effect.fn(
"mobile.connectionMigration.migrateCatalog",
)(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
new LegacyConnectionMigrationError({
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
}),
});
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
Effect.mapError(
(cause) =>
new LegacyConnectionMigrationError({
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
}),
),
);
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
});
+35
View File
@@ -0,0 +1,35 @@
import { ConnectionOnboarding } from "@t3tools/client-runtime/connection";
import {
createAtomCommandScheduler,
createRuntimeCommand,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { connectionAtomRuntime } from "./runtime";
const onboardingScheduler = createAtomCommandScheduler();
export const connectPairingUrl = createRuntimeCommand(connectionAtomRuntime, {
label: "mobile:connection:connect-pairing-url",
scheduler: onboardingScheduler,
concurrency: { mode: "singleFlight", key: (pairingUrl: string) => pairingUrl },
execute: (pairingUrl: string) =>
ConnectionOnboarding.pipe(
Effect.flatMap((onboarding) => onboarding.registerPairing({ pairingUrl })),
),
});
export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime, {
label: "mobile:connection:update-bearer",
scheduler: onboardingScheduler,
concurrency: {
mode: "serial",
key: (input: { readonly environmentId: EnvironmentId }) => input.environmentId,
},
execute: (input: {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly httpBaseUrl: string;
}) => ConnectionOnboarding.pipe(Effect.flatMap((onboarding) => onboarding.updateBearer(input))),
});
+200
View File
@@ -0,0 +1,200 @@
import {
ClientPresentation,
CloudSession,
EnvironmentOwnedDataCleanup,
PlatformConnectionSource,
RelayDeviceIdentity,
SshEnvironmentGateway,
} from "@t3tools/client-runtime/platform";
import {
ConnectionBlockedError,
ConnectionTransientError,
ConnectionWakeups,
Connectivity,
} from "@t3tools/client-runtime/connection";
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { AuthStandardClientScopes } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as Network from "expo-network";
import { AppState } from "react-native";
import { authClientMetadata } from "../lib/authClientMetadata";
import { loadOrCreateAgentAwarenessDeviceId } from "../lib/storage";
import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { connectionStorageLayer } from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
if (state.isConnected === false || state.isInternetReachable === false) {
return "offline";
}
if (state.isConnected === true) {
return "online";
}
return "unknown";
}
const connectivityLayer = Layer.succeed(
Connectivity,
Connectivity.of({
status: Effect.tryPromise({
try: () => Network.getNetworkStateAsync(),
catch: () => undefined,
}).pipe(
Effect.match({
onFailure: () => "unknown" as const,
onSuccess: networkStatus,
}),
),
changes: Stream.callback((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
Network.addNetworkStateListener((state) => {
Queue.offerUnsafe(queue, networkStatus(state));
}),
),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
}),
);
const wakeupsLayer = Layer.succeed(
ConnectionWakeups,
ConnectionWakeups.of({
changes: Stream.merge(
Stream.callback<"application-active">((queue) =>
Effect.acquireRelease(
Effect.sync(() =>
AppState.addEventListener("change", (state) => {
if (state === "active") {
Queue.offerUnsafe(queue, "application-active");
}
}),
),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
managedRelayAccountChanges(appAtomRegistry).pipe(
Stream.map(() => "credentials-changed" as const),
),
),
}),
);
const capabilitiesLayer = Layer.succeedContext(
Context.make(
CloudSession,
CloudSession.of({
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
message: "Sign in to T3 Cloud to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
Effect.mapError(
(error) =>
new ConnectionTransientError({
reason: "network",
message: error.message,
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
message: "The T3 Cloud session is unavailable.",
});
}
return token;
}),
}),
).pipe(
Context.add(
RelayDeviceIdentity,
RelayDeviceIdentity.of({
deviceId: Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
message: `Could not load the mobile device identity: ${String(cause)}`,
}),
}).pipe(Effect.map(Option.some)),
}),
),
Context.add(
ClientPresentation,
ClientPresentation.of({
metadata: authClientMetadata(),
scopes: AuthStandardClientScopes,
}),
),
Context.add(
SshEnvironmentGateway,
SshEnvironmentGateway.of({
provision: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
message: "SSH environments are only available in the desktop app.",
}),
),
prepare: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
message: "SSH environments are only available in the desktop app.",
}),
),
disconnect: () => Effect.void,
}),
),
),
);
const platformConnectionSourceLayer = Layer.succeed(
PlatformConnectionSource,
PlatformConnectionSource.of({
registrations: Stream.empty,
}),
);
const environmentOwnedDataCleanupLayer = Layer.succeed(
EnvironmentOwnedDataCleanup,
EnvironmentOwnedDataCleanup.of({
clear: (environmentId) =>
Effect.all(
[
Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
],
{ concurrency: "unbounded", discard: true },
).pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not clear mobile environment-owned data.", {
environmentId,
cause,
}),
),
),
}),
);
export const connectionPlatformLayer = Layer.mergeAll(
connectionStorageLayer,
connectivityLayer,
wakeupsLayer,
capabilitiesLayer,
platformConnectionSourceLayer,
environmentOwnedDataCleanupLayer,
);
+16
View File
@@ -0,0 +1,16 @@
import { connectionLayer as clientConnectionLayer } from "@t3tools/client-runtime/connection";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
import { runtimeContextLayer } from "../lib/runtime";
import { connectionPlatformLayer } from "./platform";
const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
export const connectionLayer = clientConnectionLayer.pipe(
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
);
export const connectionAtomRuntime = Atom.runtime(connectionLayer);
@@ -0,0 +1,84 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import {
CONNECTION_CATALOG_KEY,
LEGACY_CONNECTIONS_KEY,
makeCatalogStore,
type SecureCatalogStorage,
} from "./catalog-store";
function makeStorage(initial: Readonly<Record<string, string>>) {
const values = new Map(Object.entries(initial));
const deleted: Array<string> = [];
const storage: SecureCatalogStorage = {
getItem: (key) => Effect.sync(() => values.get(key) ?? null),
setItem: (key, value) =>
Effect.sync(() => {
values.set(key, value);
}),
deleteItem: (key) =>
Effect.sync(() => {
deleted.push(key);
values.delete(key);
}),
};
return { deleted, storage, values };
}
describe("mobile connection catalog storage", () => {
it.effect("recovers from a corrupt current catalog", () =>
Effect.gen(function* () {
const memory = makeStorage({
[CONNECTION_CATALOG_KEY]: "{not-json",
});
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY]);
}),
);
it.effect("replaces and removes a corrupt legacy catalog", () =>
Effect.gen(function* () {
const memory = makeStorage({
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({ connections: [{ invalid: true }] }),
});
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toEqual([]);
expect(memory.deleted).toEqual([LEGACY_CONNECTIONS_KEY]);
expect(memory.values.has(CONNECTION_CATALOG_KEY)).toBe(true);
}),
);
it.effect("falls back to valid legacy data when the current catalog is corrupt", () =>
Effect.gen(function* () {
const memory = makeStorage({
[CONNECTION_CATALOG_KEY]: "{not-json",
[LEGACY_CONNECTIONS_KEY]: JSON.stringify({
connections: [
{
environmentId: "legacy-environment",
environmentLabel: "Legacy",
pairingUrl: "https://legacy.example.test/pair",
displayUrl: "https://legacy.example.test",
httpBaseUrl: "https://legacy.example.test",
wsBaseUrl: "wss://legacy.example.test",
bearerToken: "legacy-token",
authenticationMethod: "bearer",
},
],
}),
});
const catalog = yield* makeCatalogStore(memory.storage);
expect((yield* catalog.read).targets).toHaveLength(1);
expect(memory.deleted).toEqual([CONNECTION_CATALOG_KEY, LEGACY_CONNECTIONS_KEY]);
yield* catalog.update((document) => document);
expect(memory.values.has(CONNECTION_CATALOG_KEY)).toBe(true);
expect(memory.values.has(LEGACY_CONNECTIONS_KEY)).toBe(false);
}),
);
});
+432
View File
@@ -0,0 +1,432 @@
import {
ConnectionPersistenceError,
ConnectionRegistrationStore,
ConnectionTargetStore,
EnvironmentCacheStore,
registerConnectionInCatalog,
removeConnectionFromCatalog,
removeCatalogValue,
replaceCatalogValue,
} from "@t3tools/client-runtime/platform";
import { RemoteDpopAccessTokenStore } from "@t3tools/client-runtime/authorization";
import {
ConnectionCredentialStore,
ConnectionProfileStore,
ConnectionTransientError,
} from "@t3tools/client-runtime/connection";
import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
thread: OrchestrationThread,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
message: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
}
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
function* (
environmentId: EnvironmentId,
operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(
Paths.document,
THREAD_SNAPSHOT_CACHE_DIRECTORY,
encodeURIComponent(environmentId),
);
if (operation !== "clear-environment") {
directory.create({ idempotent: true, intermediates: true });
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
});
},
);
const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
environmentId: EnvironmentId,
threadId: ThreadId,
operation: "load-thread" | "save-thread" | "remove-thread",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(
yield* threadSnapshotDirectory(environmentId, operation),
threadSnapshotFileName(threadId),
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.getItemAsync(key),
catch: (cause) => catalogError("load", cause),
}),
setItem: (key, value) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(key, value),
catch: (cause) => catalogError("save", cause),
}),
deleteItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(key),
catch: (cause) => catalogError("delete", cause),
}),
};
function shellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
const shellSnapshotFileInDirectory = Effect.fn(
"mobile.connectionStorage.shellSnapshotFileInDirectory",
)(function* (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
directoryName: string,
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, directoryName);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const shellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "save-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, SHELL_SNAPSHOT_CACHE_DIRECTORY);
const legacyShellSnapshotFile = (
environmentId: EnvironmentId,
operation: "load-shell" | "clear-environment",
) => shellSnapshotFileInDirectory(environmentId, operation, LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY);
export const connectionStorageLayer = Layer.effectContext(
Effect.gen(function* () {
const catalog = yield* makeCatalogStore(secureCatalogStorage);
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
});
const profileStore = ConnectionProfileStore.of({
get: (connectionId) =>
catalog.read.pipe(
Effect.map((document) =>
Option.fromUndefinedOr(
document.profiles.find((candidate) => candidate.connectionId === connectionId),
),
),
),
put: (profile) =>
catalog.update((document) => ({
...document,
profiles: replaceCatalogValue(document.profiles, (value) => value.connectionId, profile),
})),
remove: (connectionId) =>
catalog.update((document) => ({
...document,
profiles: removeCatalogValue(
document.profiles,
(value) => value.connectionId,
connectionId,
),
})),
});
const credentialStore = ConnectionCredentialStore.of({
get: (connectionId) =>
catalog.read.pipe(
Effect.map((document) =>
Option.fromUndefinedOr(
document.credentials.find((entry) => entry.connectionId === connectionId)?.credential,
),
),
),
put: (connectionId, credential) =>
catalog.update((document) => ({
...document,
credentials: replaceCatalogValue(document.credentials, (value) => value.connectionId, {
connectionId,
credential,
}),
})),
remove: (connectionId) =>
catalog.update((document) => ({
...document,
credentials: removeCatalogValue(
document.credentials,
(value) => value.connectionId,
connectionId,
),
})),
});
const remoteTokenStore = RemoteDpopAccessTokenStore.of({
get: (environmentId) =>
catalog.read.pipe(
Effect.map((document) =>
Option.fromUndefinedOr(
document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
),
),
),
put: (token) =>
catalog.update((document) => ({
...document,
remoteDpopTokens: replaceCatalogValue(
document.remoteDpopTokens,
(value) => value.environmentId,
token,
),
})),
remove: (environmentId) =>
catalog.update((document) => ({
...document,
remoteDpopTokens: removeCatalogValue(
document.remoteDpopTokens,
(value) => value.environmentId,
environmentId,
),
})),
});
const cacheStore = EnvironmentCacheStore.of({
loadShell: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "load-shell");
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
if (!legacyFile.exists) {
return Option.none();
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
}),
saveShell: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "save-shell");
const stored = {
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
}),
saveThread: (environmentId, thread) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
if (file.exists) {
file.delete();
}
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
),
),
clear: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
environmentId,
"clear-environment",
);
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
});
return Context.make(ConnectionTargetStore, targetStore).pipe(
Context.add(ConnectionRegistrationStore, registrationStore),
Context.add(ConnectionProfileStore, profileStore),
Context.add(ConnectionCredentialStore, credentialStore),
Context.add(RemoteDpopAccessTokenStore, remoteTokenStore),
Context.add(EnvironmentCacheStore, cacheStore),
);
}),
);
@@ -2,7 +2,8 @@ import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import * as Layer from "effect/Layer";
import { HttpClient } from "effect/unstable/http";
import type { SavedRemoteConnection } from "../../lib/connection";
@@ -33,90 +34,85 @@ const connection: SavedRemoteConnection = {
bearerToken: "local-bearer",
};
const runWithHttpClient = <A, E>(
effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient>,
): Promise<A> =>
Effect.runPromise(
effect.pipe(
Effect.provideService(ManagedRelayClient, null as never),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
),
);
const testLayer = Layer.mergeAll(
Layer.succeed(ManagedRelayClient, null as never),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
);
describe("liveActivityPreferences", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("pushes disabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
it.effect("pushes disabled Live Activity preferences to relay registrations", () =>
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: "clerk-token",
connections: [connection],
}),
);
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
}).pipe(Effect.provide(testLayer)),
);
it("pushes enabled Live Activity preferences to relay registrations", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
it.effect("pushes enabled Live Activity preferences to relay registrations", () =>
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: "clerk-token",
connections: [connection],
}),
);
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
}).pipe(Effect.provide(testLayer)),
);
it("keeps local preferences refreshable when signed out", async () => {
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
it.effect("keeps local preferences refreshable when signed out", () =>
Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: false,
clerkToken: null,
connections: [connection],
}),
);
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
});
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled();
}).pipe(Effect.provide(testLayer)),
);
it("does not try to re-link managed relay connections without bearer credentials", async () => {
it.effect("does not try to re-link managed relay connections without bearer credentials", () => {
const managedConnection: SavedRemoteConnection = {
...connection,
bearerToken: null,
};
await runWithHttpClient(
setLiveActivityUpdatesEnabled({
return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
enabled: true,
clerkToken: "clerk-token",
connections: [connection, managedConnection],
}),
);
});
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token",
connection,
});
}).pipe(Effect.provide(testLayer));
});
});
@@ -1,6 +1,6 @@
import * as Effect from "effect/Effect";
import { HttpClient } from "effect/unstable/http";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage";
@@ -1,6 +1,6 @@
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import type { MobilePreferences } from "../../lib/storage";
import type { Preferences } from "../../lib/storage";
export function makeRelayDeviceRegistrationRequest(input: {
readonly deviceId: string;
@@ -10,7 +10,7 @@ export function makeRelayDeviceRegistrationRequest(input: {
readonly pushToken?: string;
readonly pushToStartToken?: string;
readonly notificationsEnabled: boolean;
readonly preferences: MobilePreferences;
readonly preferences: Preferences;
}): RelayDeviceRegistrationRequest {
const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false;
return {
@@ -6,15 +6,16 @@ import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import Constants from "expo-constants";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import type { ManagedRelayClient } from "@t3tools/client-runtime";
import { type ManagedRelayClient } from "@t3tools/client-runtime/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import { verifyDpopProof } from "@t3tools/shared/dpop";
import type { SavedRemoteConnection } from "../../lib/connection";
import { mobileCryptoLayer } from "../cloud/dpop";
import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer";
import { cryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
__resetAgentAwarenessRemoteRegistrationForTest,
@@ -33,6 +34,12 @@ const secureStore = vi.hoisted(() => new Map<string, string>());
const widgetMocks = vi.hoisted(() => ({
getInstances: vi.fn(() => []),
}));
const backgroundRuntime = vi.hoisted(() => ({
pending: [] as Array<{
readonly operation: unknown;
readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
}>,
}));
vi.mock("expo-constants", () => ({
default: {
@@ -95,17 +102,11 @@ vi.mock("react-native", () => ({
}));
vi.mock("../../lib/runtime", () => ({
mobileRuntime: {
runPromise: <A, E>(operation: Effect.Effect<A, E>) =>
Effect.runPromise(
operation.pipe(
Effect.provide(
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
),
runtime: {
runPromiseExit: (operation: unknown) =>
new Promise((resolve) => {
backgroundRuntime.pending.push({ operation, resolve });
}),
},
}));
@@ -138,34 +139,40 @@ function savedConnection(): SavedRemoteConnection {
};
}
const runRegistrationEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> =>
Effect.runPromise(
effect.pipe(
Effect.provide(
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
);
const relayTestLayer = managedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cryptoLayer)),
);
async function waitForFetchCalls(
fetchMock: ReturnType<typeof vi.fn>,
count: number,
): Promise<void> {
for (let attempt = 0; attempt < 20; attempt += 1) {
if (fetchMock.mock.calls.length >= count) {
return;
const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
function* () {
let idlePasses = 0;
for (;;) {
yield* Effect.promise(() => Promise.resolve());
const pending = backgroundRuntime.pending.shift();
if (!pending) {
idlePasses++;
if (idlePasses >= 3) {
return;
}
continue;
}
idlePasses = 0;
const exit = yield* Effect.exit(
pending.operation as Effect.Effect<unknown, unknown, ManagedRelayClient>,
);
yield* Effect.sync(() => {
pending.resolve(exit);
});
}
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
},
);
describe("makeRelayDeviceRegistrationRequest", () => {
beforeEach(() => {
vi.unstubAllGlobals();
vi.stubGlobal("__DEV__", false);
secureStore.clear();
backgroundRuntime.pending.length = 0;
Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest();
widgetMocks.getInstances.mockReset();
@@ -243,7 +250,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull();
});
it("registers at most one listener while a Live Activity push token is pending", async () => {
it.effect("registers at most one listener while a Live Activity push token is pending", () => {
registerAgentAwarenessConnection(savedConnection());
const addPushTokenListener = vi.fn();
const activity = {
@@ -251,56 +258,64 @@ describe("makeRelayDeviceRegistrationRequest", () => {
addPushTokenListener,
};
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
return Effect.gen(function* () {
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
});
it("reports Live Activity token registration as skipped when relay auth is unavailable", async () => {
it.effect(
"reports Live Activity token registration as skipped when relay auth is unavailable",
() => {
registerAgentAwarenessConnection(savedConnection());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
return Effect.gen(function* () {
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
}).pipe(Effect.provide(relayTestLayer));
},
);
it.effect(
"registers APNS-started Live Activities for relay updates without mutating them locally",
() => {
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
start: vi.fn(),
update: vi.fn(),
end: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* refreshActiveLiveActivityRemoteRegistration();
expect(activity.getPushToken).toHaveBeenCalled();
expect(activity.start).not.toHaveBeenCalled();
expect(activity.update).not.toHaveBeenCalled();
expect(activity.end).not.toHaveBeenCalled();
}).pipe(Effect.provide(relayTestLayer));
},
);
it.effect("refreshes APNs registration for connected environments after settings changes", () => {
registerAgentAwarenessConnection(savedConnection());
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
};
return Effect.gen(function* () {
yield* runBackgroundOperations();
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
});
yield* refreshAgentAwarenessRegistration();
it("registers APNS-started Live Activities for relay updates without mutating them locally", async () => {
const activity = {
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(),
start: vi.fn(),
update: vi.fn(),
end: vi.fn(),
};
widgetMocks.getInstances.mockReturnValue([activity] as never);
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
await runRegistrationEffect(refreshActiveLiveActivityRemoteRegistration());
expect(activity.getPushToken).toHaveBeenCalled();
expect(activity.start).not.toHaveBeenCalled();
expect(activity.update).not.toHaveBeenCalled();
expect(activity.end).not.toHaveBeenCalled();
});
it("refreshes APNs registration for connected environments after settings changes", async () => {
registerAgentAwarenessConnection(savedConnection());
await new Promise((resolve) => setTimeout(resolve, 0));
vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
await runRegistrationEffect(refreshAgentAwarenessRegistration());
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("registers the APNs device when cloud auth becomes available", () => {
@@ -330,7 +345,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
yield* runBackgroundOperations();
expect(fetchMock).toHaveBeenCalledTimes(2);
const [request, init] = fetchMock.mock.calls[1] as unknown as [
@@ -357,7 +372,65 @@ describe("makeRelayDeviceRegistrationRequest", () => {
nowEpochSeconds: proofIat(dpop),
}),
).toMatchObject({ ok: true });
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("coalesces simultaneous sign-in and environment connection registrations", () => {
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
Response.json(
url.endsWith("/v1/client/dpop-token")
? {
access_token: "relay-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 300,
scope: "mobile:registration",
}
: { ok: true },
),
);
});
vi.stubGlobal("fetch", fetchMock);
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
vi.mocked(Notifications.getPermissionsAsync).mockClear();
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
registerAgentAwarenessConnection(savedConnection());
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(Notifications.getPermissionsAsync).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("continues queued device registration after a failed auth lookup", () => {
Constants.expoConfig!.extra = {
relay: {
url: "https://relay.example.test/",
},
};
const tokenProvider = vi
.fn<() => Promise<string | null>>()
.mockRejectedValueOnce(new Error("auth unavailable"))
.mockResolvedValue("clerk-token-user-a");
setAgentAwarenessRelayTokenProvider(tokenProvider);
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
expect(tokenListener).toBeDefined();
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(backgroundRuntime.pending).toHaveLength(0);
expect(tokenProvider).toHaveBeenCalledTimes(2);
}).pipe(Effect.provide(relayTestLayer));
});
it("only registers again when the authenticated identity changes", () => {
@@ -367,7 +440,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true);
});
it("registers rotated APNs tokens without rereading the native token", async () => {
it.effect("registers rotated APNs tokens without rereading the native token", () => {
const fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
return Promise.resolve(
@@ -398,9 +471,10 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(tokenListener).toBeDefined();
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
});
it.effect(
@@ -432,13 +506,13 @@ describe("makeRelayDeviceRegistrationRequest", () => {
registerAgentAwarenessConnection(savedConnection());
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () {
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2));
yield* runBackgroundOperations();
fetchMock.mockClear();
unregisterAgentAwarenessConnection(savedConnection().environmentId);
expect(fetchMock).not.toHaveBeenCalled();
});
}).pipe(Effect.provide(relayTestLayer));
},
);
});
@@ -8,10 +8,16 @@ import {
type RelayDeviceRegistrationRequest,
type RelayLiveActivityRegistrationRequest,
} from "@t3tools/contracts/relay";
import { ManagedRelayClient } from "@t3tools/client-runtime";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { ManagedRelayClient } from "@t3tools/client-runtime/relay";
import {
isAtomCommandInterrupted,
settleAsyncResult,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { SavedRemoteConnection } from "../../lib/connection";
import { mobileRuntime } from "../../lib/runtime";
import { runtime } from "../../lib/runtime";
import {
loadAgentAwarenessDeviceId,
loadOrCreateAgentAwarenessDeviceId,
@@ -29,6 +35,20 @@ let pushTokenSubscription: { remove: () => void } | null = null;
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
let relayTokenProvider: (() => Promise<string | null>) | null = null;
let relayTokenProviderIdentity: string | null = null;
let deviceRegistrationGeneration = 0;
let activeDeviceRegistration: {
readonly input: DeviceRegistrationInput;
operation: Promise<void>;
} | null = null;
let pendingDeviceRegistration: {
readonly input: DeviceRegistrationInput;
readonly context: string;
} | null = null;
interface DeviceRegistrationInput {
readonly pushToStartToken?: string;
readonly observedPushToken?: string;
}
export function normalizeAgentAwarenessRelayBaseUrl(
value: string | null | undefined,
@@ -68,6 +88,11 @@ export function setAgentAwarenessRelayTokenProvider(
const isExistingIdentity =
provider !== null &&
!shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);
if (!isExistingIdentity) {
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
}
relayTokenProvider = provider;
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
if (!provider) {
@@ -90,7 +115,7 @@ export function setAgentAwarenessRelayTokenProvider(
if (isExistingIdentity) {
return;
}
runRegistrationInBackground(registerDevice(), "device registration after cloud sign-in failed");
enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
}
function iosMajorVersion(): number {
@@ -149,20 +174,41 @@ const relayToken = Effect.gen(function* () {
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
expectedGeneration: number,
): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled before relay request", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
if (!readRelayConfig()) return;
const token = yield* relayToken;
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
if (!token) {
logRegistrationDebug("relay device registration skipped; user is not signed in");
return;
}
const client = yield* ManagedRelayClient;
logRegistrationDebug("relay device registration request started", {
expectedGeneration,
});
yield* client.registerDevice({
clerkToken: token,
payload: body,
});
logRegistrationDebug("relay device registration request completed", {
expectedGeneration,
});
});
}
@@ -213,10 +259,11 @@ function logRegistrationError(context: string, error: unknown): void {
if (!__DEV__) {
return;
}
console.warn(
`[agent-awareness] ${context}`,
error instanceof Error ? error.message : String(error),
);
console.warn(`[agent-awareness] ${context}`, {
message: error instanceof Error ? error.message : String(error),
traceId: findErrorTraceId(error),
error,
});
}
function logRegistrationDebug(context: string, details?: unknown): void {
@@ -230,20 +277,107 @@ function runRegistrationInBackground(
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
context: string,
): void {
void mobileRuntime.runPromise(operation).catch((error: unknown) => {
logRegistrationError(context, error);
});
void (async () => {
const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
logRegistrationError(context, squashAtomCommandFailure(result));
}
})();
}
function registerDevice(input?: {
readonly pushToStartToken?: string;
readonly observedPushToken?: string;
}): Effect.Effect<void, unknown, ManagedRelayClient> {
function mergeDeviceRegistrationInput(
current: DeviceRegistrationInput,
next: DeviceRegistrationInput,
): DeviceRegistrationInput {
return {
...((next.pushToStartToken ?? current.pushToStartToken)
? { pushToStartToken: next.pushToStartToken ?? current.pushToStartToken }
: {}),
...((next.observedPushToken ?? current.observedPushToken)
? { observedPushToken: next.observedPushToken ?? current.observedPushToken }
: {}),
};
}
function registrationAddsInformation(
current: DeviceRegistrationInput,
next: DeviceRegistrationInput,
): boolean {
return (
(next.pushToStartToken !== undefined && next.pushToStartToken !== current.pushToStartToken) ||
(next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken)
);
}
function startPendingDeviceRegistration(): void {
if (activeDeviceRegistration || !pendingDeviceRegistration) {
return;
}
const next = pendingDeviceRegistration;
pendingDeviceRegistration = null;
const generation = deviceRegistrationGeneration;
logRegistrationDebug("device registration started", {
generation,
hasObservedPushToken: next.input.observedPushToken !== undefined,
hasPushToStartToken: next.input.pushToStartToken !== undefined,
});
const registration = {
input: next.input,
operation: Promise.resolve(),
};
activeDeviceRegistration = registration;
registration.operation = (async () => {
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(registerDevice(next.input, generation)),
);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
logRegistrationError(next.context, squashAtomCommandFailure(result));
}
logRegistrationDebug("device registration finished", { generation });
if (activeDeviceRegistration === registration) {
activeDeviceRegistration = null;
}
startPendingDeviceRegistration();
})();
}
function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {
if (
activeDeviceRegistration &&
!registrationAddsInformation(activeDeviceRegistration.input, input)
) {
logRegistrationDebug("device registration coalesced with active request", {
generation: deviceRegistrationGeneration,
});
return;
}
logRegistrationDebug("device registration enqueued", {
generation: deviceRegistrationGeneration,
hasActiveRegistration: activeDeviceRegistration !== null,
hasPendingRegistration: pendingDeviceRegistration !== null,
});
pendingDeviceRegistration = pendingDeviceRegistration
? {
input: mergeDeviceRegistrationInput(pendingDeviceRegistration.input, input),
context,
}
: { input, context };
startPendingDeviceRegistration();
}
function registerDevice(
input: DeviceRegistrationInput = {},
expectedGeneration = deviceRegistrationGeneration,
): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) {
logRegistrationDebug("device registration skipped; platform does not support it");
return;
}
logRegistrationDebug("device registration loading local state", { expectedGeneration });
const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
@@ -255,6 +389,10 @@ function registerDevice(input?: {
}),
]);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
logRegistrationDebug("device registration local state ready", {
expectedGeneration,
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
});
yield* registerDeviceWithRelay(
makeRelayDeviceRegistrationRequest({
deviceId,
@@ -266,6 +404,7 @@ function registerDevice(input?: {
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
preferences,
}),
expectedGeneration,
);
});
}
@@ -277,10 +416,7 @@ function registerDeviceForCurrentUser(
}
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
runRegistrationInBackground(
registerDeviceForCurrentUser(pushToStartToken),
"push-to-start token registration failed",
);
enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed");
}
function ensurePushToStartListener(): void {
@@ -303,8 +439,8 @@ function ensurePushTokenListener(): void {
pushTokenSubscription = Notifications.addPushTokenListener((token) => {
if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) {
runRegistrationInBackground(
registerDevice({ observedPushToken: token.data.trim() }),
enqueueDeviceRegistration(
{ observedPushToken: token.data.trim() },
"native APNs token rotation registration failed",
);
}
@@ -319,7 +455,7 @@ export function registerAgentAwarenessConnection(connection: SavedRemoteConnecti
environmentConnections.set(connection.environmentId, connection);
ensurePushToStartListener();
ensurePushTokenListener();
runRegistrationInBackground(registerDevice(), "device registration failed");
enqueueDeviceRegistration({}, "device registration failed");
runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(),
"active live activity registration after environment connection failed",
@@ -372,6 +508,9 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
}
relayTokenProvider = null;
relayTokenProviderIdentity = null;
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
}
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -0,0 +1,60 @@
import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { appAtomRegistry } from "../../state/atom-registry";
import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider";
import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration";
vi.mock("@clerk/expo", () => ({
ClerkProvider: vi.fn(),
useAuth: vi.fn(),
}));
vi.mock("@clerk/expo/token-cache", () => ({
tokenCache: {},
}));
vi.mock("../../lib/runtime", () => ({
runtime: {
runPromiseExit: vi.fn(),
},
}));
vi.mock("../../connection/catalog", () => ({
environmentCatalog: {
removeRelayEnvironments: {},
},
}));
vi.mock("./publicConfig", () => ({
resolveCloudPublicConfig: vi.fn(() => ({
clerk: { publishableKey: null },
relay: { url: null },
})),
resolveRelayClerkTokenOptions: vi.fn(),
}));
vi.mock("../agent-awareness/remoteRegistration", () => ({
setAgentAwarenessRelayTokenProvider: vi.fn(),
unregisterAgentAwarenessDeviceForCurrentUser: vi.fn(),
}));
afterEach(() => {
deactivateCloudRelayAccount();
vi.clearAllMocks();
});
describe("CloudAuthProvider relay account isolation", () => {
it("clears relay and agent-awareness credentials before cleanup can fail", async () => {
const tokenProvider = async () => "account-1-token";
activateCloudRelayAccount("account-1", tokenProvider);
expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");
deactivateCloudRelayAccount();
const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);
expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();
expect(vi.mocked(setAgentAwarenessRelayTokenProvider)).toHaveBeenLastCalledWith(null);
await cleanup;
});
});
@@ -1,63 +1,149 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime";
import { ManagedRelayClient, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import { type ReactNode, useEffect, useRef } from "react";
import { mobileRuntime } from "../../lib/runtime";
import { environmentCatalog } from "../../connection/catalog";
import { runtime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache() {
return settleAsyncResult(() =>
runtime.runPromiseExit(
ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
),
);
}
export function deactivateCloudRelayAccount(): void {
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
}
export function activateCloudRelayAccount(
accountId: string,
tokenProvider: () => Promise<string | null>,
): void {
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken: tokenProvider,
});
}
function CloudAuthBridge(props: { readonly children: ReactNode }) {
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
reportFailure: false,
reportDefect: false,
});
const previousTokenProviderRef = useRef<{
readonly userId: string;
readonly provider: () => Promise<string | null>;
} | null>(null);
const observedAccountRef = useRef<string | null | undefined>(undefined);
const accountTransitionRef = useRef<Promise<void> | null>(null);
useEffect(() => {
let cancelled = false;
if (!isLoaded) {
return;
}
const previousObservedAccount = observedAccountRef.current;
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
const queueAccountCleanup = (
previous: {
readonly userId: string;
readonly provider: () => Promise<string | null>;
} | null,
) => {
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
accountTransitionRef.current = previousTransition.then(async () => {
const cleanup = [
resetManagedRelayTokenCache(),
removeRelayEnvironments(),
...(previous
? [
settleAsyncResult(() =>
runtime.runPromiseExit(
unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
),
),
]
: []),
];
const results = await Promise.all(cleanup);
for (const result of results) {
reportAtomCommandResult(result, { label: "cloud account cleanup" });
}
});
return accountTransitionRef.current;
};
if (!isSignedIn || !userId) {
const previous = previousTokenProviderRef.current;
previousTokenProviderRef.current = null;
if (previous) {
void mobileRuntime
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
.catch(() => undefined);
deactivateCloudRelayAccount();
if (previousObservedAccount !== null) {
void queueAccountCleanup(previous);
}
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
return;
}
const previous = previousTokenProviderRef.current;
if (previous && previous.userId !== userId) {
void mobileRuntime
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
.catch(() => undefined);
}
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
previousTokenProviderRef.current = { userId, provider: tokenProvider };
setAgentAwarenessRelayTokenProvider(tokenProvider, userId);
setManagedRelaySession(
appAtomRegistry,
createManagedRelaySession({
accountId: userId,
readClerkToken: tokenProvider,
}),
);
}, [getToken, isLoaded, isSignedIn, userId]);
const activateSession = () => {
if (cancelled) {
return;
}
previousTokenProviderRef.current = { userId, provider: tokenProvider };
activateCloudRelayAccount(userId, tokenProvider);
};
const activateAfterTransition = (transition: Promise<void>) => {
void (async () => {
const result = await settlePromise(async () => {
await transition;
activateSession();
});
reportAtomCommandResult(result, { label: "cloud account activation" });
})();
};
if (
previousObservedAccount !== undefined &&
previousObservedAccount !== null &&
previousObservedAccount !== userId
) {
previousTokenProviderRef.current = null;
deactivateCloudRelayAccount();
activateAfterTransition(queueAccountCleanup(previous));
} else {
activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
}
return () => {
cancelled = true;
};
}, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
useEffect(
() => () => {
previousTokenProviderRef.current = null;
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
deactivateCloudRelayAccount();
},
[],
);
@@ -72,8 +158,7 @@ export function CloudAuthProvider(props: { readonly children: ReactNode }) {
useEffect(() => {
if (!publishableKey || !relayUrl) {
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
deactivateCloudRelayAccount();
}
}, [publishableKey, relayUrl]);
@@ -0,0 +1,18 @@
export function isCloudDebugEnabled(): boolean {
return (
(typeof __DEV__ !== "undefined" && __DEV__) ||
(typeof globalThis !== "undefined" &&
(globalThis as { __T3_CLOUD_DEBUG__?: boolean }).__T3_CLOUD_DEBUG__ === true)
);
}
export function cloudDebugLog(event: string, data?: Record<string, unknown>): void {
if (!isCloudDebugEnabled()) {
return;
}
if (data) {
console.log(`[t3-cloud] ${event}`, data);
} else {
console.log(`[t3-cloud] ${event}`);
}
}
@@ -0,0 +1,88 @@
import { EnvironmentId } from "@t3tools/contracts";
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import { describe, expect, it } from "vite-plus/test";
import { availableCloudEnvironmentPresentation } from "./cloudEnvironmentPresentation";
function relayStatus(
status: RelayEnvironmentStatusResponse["status"],
error?: string,
traceId?: string,
): RelayEnvironmentStatusResponse {
return {
environmentId: EnvironmentId.make("environment-cloud"),
endpoint: {
httpBaseUrl: "https://cloud.example.test/",
wsBaseUrl: "wss://cloud.example.test/ws",
providerKind: "cloudflare_tunnel",
},
status,
checkedAt: "2026-06-05T16:49:11.000Z",
...(error ? { error } : {}),
...(traceId ? { traceId } : {}),
};
}
describe("available cloud environment presentation", () => {
it("presents an online unsaved environment as available, not connected", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status: relayStatus("online"),
statusError: null,
statusErrorTraceId: null,
}),
).toEqual({
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: "Available · Relay online",
});
});
it("keeps relay status checks distinct from connection attempts", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: true,
status: null,
statusError: null,
statusErrorTraceId: null,
}),
).toEqual({
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: "Available · Checking relay status...",
});
});
it("surfaces an offline relay as an error", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status: relayStatus("offline", "Tunnel is unavailable.", "trace-offline"),
statusError: null,
statusErrorTraceId: null,
}),
).toEqual({
connectionError: "Tunnel is unavailable.",
connectionErrorTraceId: "trace-offline",
connectionState: "error",
statusText: "Tunnel is unavailable.",
});
});
it("preserves trace metadata for relay request failures", () => {
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status: null,
statusError: "Could not get relay environment status.",
statusErrorTraceId: "trace-status",
}),
).toMatchObject({
connectionError: "Could not get relay environment status.",
connectionErrorTraceId: "trace-status",
});
});
});
@@ -0,0 +1,53 @@
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
export interface AvailableCloudEnvironmentPresentation {
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly statusText: string;
}
export function availableCloudEnvironmentPresentation(input: {
readonly isStatusPending: boolean;
readonly status: RelayEnvironmentStatusResponse | null;
readonly statusError: string | null;
readonly statusErrorTraceId: string | null;
}): AvailableCloudEnvironmentPresentation {
if (input.status?.status === "online") {
return {
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: "Available · Relay online",
};
}
if (input.status?.status === "offline") {
const connectionError = input.status.error ?? "Relay is offline.";
return {
connectionError,
connectionErrorTraceId: input.status.traceId ?? null,
connectionState: "error",
statusText: connectionError,
};
}
if (input.statusError) {
return {
connectionError: input.statusError,
connectionErrorTraceId: input.statusErrorTraceId,
connectionState: "error",
statusText: input.statusError,
};
}
return {
connectionError: null,
connectionErrorTraceId: null,
connectionState: "available",
statusText: input.isStatusPending
? "Available · Checking relay status..."
: "Available · Relay status unknown",
};
}
+6 -6
View File
@@ -12,7 +12,7 @@ import {
createDpopProof,
generateDpopProofKeyPair,
loadOrCreateDpopProofKeyPair,
mobileCryptoLayer,
cryptoLayer,
} from "./dpop";
vi.mock("expo-crypto", () => ({
@@ -75,7 +75,7 @@ describe("mobile DPoP", () => {
expect(Buffer.from(digest).toString("hex")).toBe(
NodeCrypto.createHash("sha256").update("typed-array").digest("hex"),
);
}).pipe(Effect.provide(mobileCryptoLayer)),
}).pipe(Effect.provide(cryptoLayer)),
);
it.effect("persists and reuses the installation proof key", () =>
@@ -86,7 +86,7 @@ describe("mobile DPoP", () => {
expect(second.thumbprint).toBe(first.thumbprint);
expect(second.privateJwk).toEqual(first.privateJwk);
}).pipe(Effect.provide(mobileCryptoLayer)),
}).pipe(Effect.provide(cryptoLayer)),
);
it.effect("rejects malformed persisted proof keys", () =>
@@ -96,7 +96,7 @@ describe("mobile DPoP", () => {
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
expect(error.message).toBe("Stored DPoP proof key is invalid.");
}).pipe(Effect.provide(mobileCryptoLayer)),
}).pipe(Effect.provide(cryptoLayer)),
);
it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () =>
@@ -135,7 +135,7 @@ describe("mobile DPoP", () => {
nowEpochSeconds: proofIat(bootstrap.proof),
}),
).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
}).pipe(Effect.provide(mobileCryptoLayer)),
}).pipe(Effect.provide(cryptoLayer)),
);
it.effect("signs DPoP proofs with RFC 9449 htu normalization", () =>
@@ -161,6 +161,6 @@ describe("mobile DPoP", () => {
nowEpochSeconds: proofIat(proof.proof),
}),
).toMatchObject({ ok: true });
}).pipe(Effect.provide(mobileCryptoLayer)),
}).pipe(Effect.provide(cryptoLayer)),
);
});
+1 -1
View File
@@ -70,7 +70,7 @@ function toExpoDigestAlgorithm(
}
}
export const mobileCryptoLayer = Layer.succeed(
export const cryptoLayer = Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: ExpoCrypto.getRandomBytes,
@@ -8,8 +8,8 @@ import {
managedRelayClientLayer,
ManagedRelayClient,
ManagedRelayDpopSigner,
remoteHttpClientLayer,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/relay";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { HttpClient } from "effect/unstable/http";
import {
@@ -55,6 +55,8 @@ const savedConnection = {
bearerToken: "local-bearer",
};
const stableClerkToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzEyMyJ9.test";
const createProofMock = vi.fn(
(input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
Effect.succeed(`dpop:${input.method}:${input.url}`),
@@ -352,7 +354,7 @@ describe("mobile cloud link environment client", () => {
});
vi.stubGlobal("fetch", fetchMock);
yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }));
yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: stableClerkToken }));
expect(
fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),
@@ -425,9 +427,11 @@ describe("mobile cloud link environment client", () => {
yield* withCloudServices(
Effect.gen(function* () {
const records = yield* listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" });
const records = yield* listCloudEnvironmentsWithStatus({
clerkToken: stableClerkToken,
});
yield* connectCloudEnvironment({
clerkToken: "clerk-token",
clerkToken: stableClerkToken,
environment: records[0]!.environment,
});
}),
@@ -658,6 +662,7 @@ describe("mobile cloud link environment client", () => {
_tag: "CloudEnvironmentLinkError",
message:
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
traceId: "trace-test",
});
expect(fetchMock).toHaveBeenCalledTimes(3);
}),
@@ -1003,6 +1008,7 @@ describe("mobile cloud link environment client", () => {
_tag: "CloudEnvironmentLinkError",
message:
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
traceId: "trace-connect",
});
}),
);
@@ -16,22 +16,23 @@ import {
type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
RelayEnvironmentConnectScope,
RelayEnvironmentStatusScope,
RelayProtectedError,
type RelayDpopAccessTokenScope,
type RelayProtectedError as RelayProtectedErrorType,
type RelayClientEnvironmentRecord,
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
type RelayManagedEndpointProviderKind,
} from "@t3tools/contracts/relay";
import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
exchangeRemoteDpopAccessToken,
fetchRemoteEnvironmentDescriptor,
makeEnvironmentHttpApiClient,
ManagedRelayClient,
type ManagedRelayClientError,
ManagedRelayDpopSigner,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/relay";
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
import { mobileAuthClientMetadata } from "../../lib/authClientMetadata";
import { authClientMetadata } from "../../lib/authClientMetadata";
import type { SavedRemoteConnection } from "../../lib/connection";
import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
import { resolveCloudPublicConfig } from "./publicConfig";
@@ -56,6 +57,7 @@ function readRelayUrl(): string | null {
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
readonly message: string;
readonly cause?: unknown;
readonly traceId?: string;
}> {}
export interface CloudEnvironmentRecordWithStatus {
@@ -64,7 +66,6 @@ export interface CloudEnvironmentRecordWithStatus {
readonly statusError: string | null;
}
const isRelayProtectedError = Schema.is(RelayProtectedError);
const isEnvironmentCloudApiError = Schema.is(
Schema.Union([
EnvironmentHttpBadRequestError,
@@ -82,11 +83,13 @@ const MANAGED_ENDPOINT_PROVIDER_KIND =
function cloudEnvironmentLinkError(message: string) {
return (cause: unknown) => {
const environmentError = findEnvironmentCloudApiError(cause);
const traceId = findErrorTraceId(cause);
return new CloudEnvironmentLinkError({
message: environmentError
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
: withDevCause(message, cause),
cause,
...(traceId === null ? {} : { traceId }),
});
};
}
@@ -148,31 +151,22 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
case "RelayAgentActivityPublishProofInvalidError":
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`;
return `Relay encountered an internal error (${error.reason}).`;
}
}
function decodedRelayClientError(message: string) {
return (cause: unknown) => {
const relayError = findRelayProtectedError(cause);
return (cause: ManagedRelayClientError) => {
const relayError = cause.relayError;
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
return new CloudEnvironmentLinkError({
message: detail ? `${message}: ${detail}` : message,
cause,
...(cause.traceId ? { traceId: cause.traceId } : {}),
});
};
}
function findRelayProtectedError(cause: unknown): RelayProtectedErrorType | null {
if (isRelayProtectedError(cause)) {
return cause;
}
if (typeof cause !== "object" || cause === null) {
return null;
}
return "cause" in cause ? findRelayProtectedError(cause.cause) : null;
}
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
if (isEnvironmentCloudApiError(cause)) {
return cause;
@@ -462,23 +456,26 @@ export function listCloudEnvironmentsWithStatus(input: {
});
}
function connectRelayManagedEnvironment(input: {
readonly clerkToken: string;
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
readonly expectedEnvironment?: RelayClientEnvironmentRecord;
}): Effect.Effect<
SavedRemoteConnection,
CloudEnvironmentLinkError,
HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
> {
return Effect.gen(function* () {
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const deviceId = yield* Effect.tryPromise({
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
function* () {
return yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
},
);
const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
function* (input: {
readonly clerkToken: string;
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
readonly expectedEnvironment?: RelayClientEnvironmentRecord;
}) {
yield* Effect.annotateCurrentSpan({ "environment.id": input.environmentId });
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelayClient;
const deviceId = yield* loadAgentAwarenessDeviceId();
const connect = yield* relayClient
.connectEnvironment({
clerkToken: input.clerkToken,
@@ -528,7 +525,7 @@ function connectRelayManagedEnvironment(input: {
httpBaseUrl: connect.endpoint.httpBaseUrl,
credential: connect.credential,
dpopProof: bootstrapDpop,
clientMetadata: mobileAuthClientMetadata(),
clientMetadata: authClientMetadata(),
}).pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
@@ -548,9 +545,9 @@ function connectRelayManagedEnvironment(input: {
authenticationMethod: "dpop",
dpopAccessToken: bootstrap.access_token,
relayManaged: true,
};
});
}
} satisfies SavedRemoteConnection;
},
);
export function connectCloudEnvironment(input: {
readonly clerkToken: string;
@@ -1,42 +1,46 @@
import {
managedRelayClientLayer,
managedRelayClientLayer as makeManagedRelayClientLayer,
ManagedRelayDpopSigner,
ManagedRelayDpopSignerError,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/relay";
import { RelayMobileClientId } from "@t3tools/contracts/relay";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
const mobileRelayDpopSignerLayer = Layer.effect(
const relayDpopSignerLayer = Layer.effect(
ManagedRelayDpopSigner,
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const loadProofKey = yield* Effect.cached(
loadOrCreateDpopProofKeyPair().pipe(Effect.provideService(Crypto.Crypto, crypto)),
);
return ManagedRelayDpopSigner.of({
thumbprint: Effect.suspend(() =>
loadOrCreateDpopProofKeyPair().pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proofKey) => proofKey.thumbprint),
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
),
thumbprint: loadProofKey.pipe(
Effect.map((proofKey) => proofKey.thumbprint),
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
Effect.withSpan("mobile.managedRelayDpopSigner.loadThumbprint"),
),
createProof: (input) =>
Effect.gen(function* () {
const proofKey = yield* loadOrCreateDpopProofKeyPair().pipe(
Effect.provideService(Crypto.Crypto, crypto),
);
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(
function* (input) {
const proofKey = yield* loadProofKey;
return yield* createDpopProof({ ...input, proofKey }).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proof) => proof.proof),
);
}).pipe(Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause }))),
},
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
),
});
}),
);
export const mobileManagedRelayClientLayer = (relayUrl: string) =>
managedRelayClientLayer({ relayUrl, clientId: RelayMobileClientId }).pipe(
Layer.provideMerge(mobileRelayDpopSignerLayer),
);
export const managedRelayClientLayer = (relayUrl: string) =>
makeManagedRelayClientLayer({
relayUrl,
clientId: RelayMobileClientId,
accessTokenStore: managedRelayAccessTokenStore,
}).pipe(Layer.provideMerge(relayDpopSignerLayer));
@@ -3,20 +3,24 @@ import {
createManagedRelayQueryManager,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/relay";
import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
import { useCallback, useEffect } from "react";
import { mobileRuntimeContextLayer } from "../../lib/runtime";
import { runtimeContextLayer } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { cloudDebugLog } from "./cloudDebugLog";
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
const managedRelayAtomRuntime = Atom.runtime(runtimeContextLayer);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime, {
onQueryEvent: (event) =>
cloudDebugLog(`query:${event.operation}:${event.stage}:${event.phase}`, { ...event }),
});
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
@@ -33,6 +37,15 @@ export function useManagedRelayEnvironments() {
? managedRelayQueryManager.environmentsAtom(accountId)
: EMPTY_ENVIRONMENTS_ATOM;
const result = useAtomValue(atom);
const snapshot = readManagedRelaySnapshotState(result);
useEffect(() => {
if (snapshot.error) {
console.error("[t3-cloud] Relay environment listing failed", {
message: snapshot.error,
traceId: snapshot.errorTraceId,
});
}
}, [snapshot.error, snapshot.errorTraceId]);
const refresh = useCallback(() => {
if (accountId) {
managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
@@ -40,7 +53,7 @@ export function useManagedRelayEnvironments() {
}, [accountId]);
return {
...readManagedRelaySnapshotState(result),
...snapshot,
accountId,
refresh,
};
@@ -53,6 +66,16 @@ export function useManagedRelayEnvironmentStatus(environment: RelayClientEnviron
? managedRelayQueryManager.environmentStatusAtom({ accountId, environment })
: EMPTY_ENVIRONMENT_STATUS_ATOM;
const result = useAtomValue(atom);
const snapshot = readManagedRelaySnapshotState(result);
useEffect(() => {
if (snapshot.error) {
console.error("[t3-cloud] Relay environment status failed", {
environmentId: environment.environmentId,
message: snapshot.error,
traceId: snapshot.errorTraceId,
});
}
}, [environment.environmentId, snapshot.error, snapshot.errorTraceId]);
const refresh = useCallback(() => {
if (accountId) {
managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, {
@@ -63,7 +86,7 @@ export function useManagedRelayEnvironmentStatus(environment: RelayClientEnviron
}, [accountId, environment]);
return {
...readManagedRelaySnapshotState(result),
...snapshot,
accountId,
refresh,
};
@@ -0,0 +1,51 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
const secureStore = vi.hoisted(() => new Map<string, string>());
vi.mock("expo-secure-store", () => ({
getItemAsync: vi.fn((key: string) => Promise.resolve(secureStore.get(key) ?? null)),
setItemAsync: vi.fn((key: string, value: string) => {
secureStore.set(key, value);
return Promise.resolve();
}),
deleteItemAsync: vi.fn((key: string) => {
secureStore.delete(key);
return Promise.resolve();
}),
}));
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
it.effect("round-trips and clears persisted managed relay access tokens", () =>
Effect.gen(function* () {
secureStore.clear();
const entries = [
{
accountId: "user-1",
clientId: "t3-mobile",
relayUrl: "https://relay.example.test",
thumbprint: "thumbprint",
scopes: ["environment:connect"],
accessToken: "access-token",
expiresAtMillis: 1_800_000,
},
] as const;
yield* managedRelayAccessTokenStore.save(entries);
expect(yield* managedRelayAccessTokenStore.load).toEqual(entries);
yield* managedRelayAccessTokenStore.clear;
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
}),
);
it.effect("falls back to an empty cache when persisted data is invalid", () =>
Effect.gen(function* () {
secureStore.clear();
secureStore.set("t3code.cloud.relay-access-tokens", "not-json");
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
}),
);
@@ -0,0 +1,107 @@
import {
type ManagedRelayAccessTokenCacheEntry,
type ManagedRelayAccessTokenStore,
} from "@t3tools/client-runtime/relay";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
const MANAGED_RELAY_TOKEN_CACHE_KEY = "t3code.cloud.relay-access-tokens";
const MANAGED_RELAY_TOKEN_CACHE_VERSION = 1;
const ManagedRelayAccessTokenCacheEntrySchema = Schema.Struct({
accountId: Schema.String,
clientId: Schema.Literals(["t3-mobile", "t3-web"]),
relayUrl: Schema.String,
thumbprint: Schema.String,
scopes: Schema.Array(
Schema.Literals(["environment:connect", "environment:status", "mobile:registration"]),
),
accessToken: Schema.String,
expiresAtMillis: Schema.Number,
});
const ManagedRelayAccessTokenCacheSchema = Schema.fromJsonString(
Schema.Struct({
version: Schema.Literal(MANAGED_RELAY_TOKEN_CACHE_VERSION),
entries: Schema.Array(ManagedRelayAccessTokenCacheEntrySchema),
}),
);
const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
ManagedRelayAccessTokenCacheSchema,
);
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
readonly message: string;
readonly cause: unknown;
}> {}
const storeError =
(message: string) =>
(cause: unknown): ManagedRelayTokenStoreError =>
new ManagedRelayTokenStoreError({ message, cause });
function logStoreFailure(operation: string) {
return (error: ManagedRelayTokenStoreError) =>
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
Effect.annotateLogs({
errorTag: error._tag,
message: error.message,
}),
);
}
const loadManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: storeError("Could not read persisted relay access tokens."),
}).pipe(
Effect.flatMap((encoded) =>
encoded === null
? Effect.succeed<ReadonlyArray<ManagedRelayAccessTokenCacheEntry>>([])
: decodeManagedRelayAccessTokenCache(encoded).pipe(
Effect.map((cache) => cache.entries),
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
),
),
);
const saveManagedRelayAccessTokens = (entries: ReadonlyArray<ManagedRelayAccessTokenCacheEntry>) =>
encodeManagedRelayAccessTokenCache({
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
entries,
}).pipe(
Effect.mapError(storeError("Could not encode relay access tokens.")),
Effect.flatMap((encoded) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
catch: storeError("Could not persist relay access tokens."),
}),
),
);
const clearManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: storeError("Could not clear persisted relay access tokens."),
});
export const managedRelayAccessTokenStore: ManagedRelayAccessTokenStore = {
load: loadManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure("load")),
Effect.orElseSucceed(() => []),
Effect.withSpan("mobile.managedRelayTokenStore.load"),
),
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
saveManagedRelayAccessTokens(entries).pipe(
Effect.tapError(logStoreFailure("save")),
Effect.ignore,
),
),
clear: clearManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure("clear")),
Effect.ignore,
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
),
};
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
import { hasTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -94,9 +94,9 @@ describe("resolveCloudPublicConfig", () => {
});
it("keeps tracing disabled unless every public tracing value is configured", () => {
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
expect(hasTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
expect(
hasMobileTracingPublicConfig(
hasTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
@@ -106,7 +106,7 @@ describe("resolveCloudPublicConfig", () => {
),
).toBe(false);
expect(
hasMobileTracingPublicConfig(
hasTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
@@ -70,13 +70,13 @@ type Configured<T> = {
readonly [Key in keyof T]: NonNullable<T[Key]>;
};
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
type TracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
readonly observability: Configured<CloudPublicConfig["observability"]>;
};
export function hasMobileTracingPublicConfig(
export function hasTracingPublicConfig(
config: CloudPublicConfig = resolveCloudPublicConfig(),
): config is MobileTracingPublicConfig {
): config is TracingPublicConfig {
return Boolean(
config.observability.tracesUrl &&
config.observability.tracesDataset &&
@@ -1,31 +1,26 @@
import { SymbolView } from "expo-symbols";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useState } from "react";
import { Pressable, View } from "react-native";
import { Alert, Pressable, View } from "react-native";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
if (environment.connectionError) {
return null;
}
switch (environment.connectionState) {
case "ready":
return "Connected";
case "connecting":
return "Connecting";
case "reconnecting":
return "Reconnecting";
case "disconnected":
return null;
case "idle":
return null;
}
return connectionStatusText({
phase: environment.connectionState,
error: environment.connectionError,
traceId: environment.connectionErrorTraceId,
});
}
export function ConnectionEnvironmentRow(props: {
@@ -37,7 +32,7 @@ export function ConnectionEnvironmentRow(props: {
readonly onUpdate: (
environmentId: EnvironmentId,
updates: { readonly label: string; readonly displayUrl: string },
) => void;
) => Promise<AtomCommandResult<unknown, unknown>>;
}) {
const [label, setLabel] = useState(props.environment.environmentLabel);
const [url, setUrl] = useState(props.environment.displayUrl);
@@ -47,13 +42,25 @@ export function ConnectionEnvironmentRow(props: {
const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground");
const statusLabel = connectionStatusLabel(props.environment);
const handleSave = useCallback(() => {
props.onUpdate(props.environment.environmentId, {
const statusTraceId = props.environment.connectionErrorTraceId;
const hasConnectionFailure = props.environment.connectionError !== null;
const isRetrying =
props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting";
const handleSave = useCallback(async () => {
const result = await props.onUpdate(props.environment.environmentId, {
label: label.trim(),
displayUrl: url.trim(),
});
props.onToggle();
if (AsyncResult.isSuccess(result)) {
props.onToggle();
return;
}
const error = Cause.squash(result.cause);
Alert.alert(
"Could not update environment",
error instanceof Error ? error.message : "The environment could not be updated.",
);
}, [label, url, props]);
return (
@@ -64,10 +71,7 @@ export function ConnectionEnvironmentRow(props: {
>
<ConnectionStatusDot
state={props.environment.connectionState}
pulse={
props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting"
}
pulse={isRetrying}
size={8}
/>
@@ -82,16 +86,35 @@ export function ConnectionEnvironmentRow(props: {
{props.environment.displayUrl}
</Text>
{statusLabel ? (
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{statusLabel}
</Text>
) : null}
{props.environment.connectionError ? (
<Text
className="text-[12px] leading-[16px] text-rose-500 dark:text-rose-400"
numberOfLines={2}
className={cn(
"text-[12px] leading-[16px]",
hasConnectionFailure ? "text-rose-500 dark:text-rose-400" : "text-foreground-muted",
)}
numberOfLines={props.expanded ? undefined : 1}
selectable={props.expanded}
>
{props.environment.connectionError}
{statusLabel}
{statusTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className="underline"
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(statusTraceId);
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{statusTraceId}
</Text>
</>
) : null}
</Text>
) : null}
</View>
@@ -11,12 +11,19 @@ import Animated, {
import type { RemoteClientConnectionState } from "../../lib/connection";
function statusDotTone(state: RemoteClientConnectionState): {
export type ConnectionStatusDotState = RemoteClientConnectionState;
function statusDotTone(state: ConnectionStatusDotState): {
readonly dotColor: string;
readonly haloColor: string;
} {
switch (state) {
case "ready":
case "available":
return {
dotColor: "#9ca3af",
haloColor: "rgba(156,163,175,0.42)",
};
case "connected":
return {
dotColor: "#34d399",
haloColor: "rgba(52,211,153,0.48)",
@@ -27,8 +34,8 @@ function statusDotTone(state: RemoteClientConnectionState): {
dotColor: "#f59e0b",
haloColor: "rgba(245,158,11,0.5)",
};
case "idle":
case "disconnected":
case "offline":
case "error":
return {
dotColor: "#ef4444",
haloColor: "rgba(239,68,68,0.48)",
@@ -63,7 +70,7 @@ function usePulseAnimation(pulse: boolean) {
}
export function ConnectionStatusDot(props: {
readonly state: RemoteClientConnectionState;
readonly state: ConnectionStatusDotState;
readonly pulse: boolean;
readonly size?: number;
}) {
@@ -0,0 +1,108 @@
import {
type EnvironmentConnectionPhase,
type EnvironmentConnectionPresentation,
} from "@t3tools/client-runtime/connection";
import { SymbolView } from "expo-symbols";
import { ActivityIndicator, Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
function noticeTitle(phase: EnvironmentConnectionPhase, environmentLabel: string): string {
switch (phase) {
case "offline":
return "You are offline";
case "connecting":
return `Connecting to ${environmentLabel}...`;
case "reconnecting":
return `Reconnecting to ${environmentLabel}...`;
case "error":
return `${environmentLabel} is unavailable`;
case "available":
return `${environmentLabel} is disconnected`;
case "connected":
return "";
}
}
function noticeDetail(
phase: EnvironmentConnectionPhase,
resourceName: string,
error: string | null,
): string {
if (error) {
return `The app will keep retrying automatically. ${error}`;
}
switch (phase) {
case "offline":
return `Cached data remains available. The ${resourceName} will load when your connection returns.`;
case "connecting":
case "reconnecting":
return `The ${resourceName} will load as soon as the environment is ready.`;
case "available":
case "error":
return `Reconnect the environment to load the ${resourceName}.`;
case "connected":
return "";
}
}
export function EnvironmentConnectionNotice(props: {
readonly environmentLabel: string;
readonly connection: EnvironmentConnectionPresentation;
readonly resourceName: string;
readonly onRetry: () => void;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const isRetrying =
props.connection.phase === "connecting" || props.connection.phase === "reconnecting";
return (
<View className="flex-1 items-center justify-center px-8">
<View className="max-w-[320px] items-center gap-3">
{isRetrying ? (
<ActivityIndicator size="small" color={iconColor} />
) : (
<SymbolView
name={props.connection.phase === "offline" ? "wifi.slash" : "bolt.horizontal.circle"}
size={24}
tintColor={iconColor}
type="monochrome"
/>
)}
<Text className="text-center text-[17px] font-t3-bold leading-[22px] text-foreground">
{noticeTitle(props.connection.phase, props.environmentLabel)}
</Text>
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
{noticeDetail(props.connection.phase, props.resourceName, props.connection.error)}
{props.connection.traceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className="underline decoration-dotted"
onPress={() => copyTextWithHaptic(props.connection.traceId!)}
>
{props.connection.traceId}
</Text>
</>
) : null}
</Text>
{props.connection.phase !== "offline" ? (
<Pressable
accessibilityRole="button"
className="mt-1 rounded-full bg-subtle px-4 py-2.5 active:opacity-70"
onPress={props.onRetry}
>
<Text className="text-[13px] font-t3-bold text-foreground">Retry now</Text>
</Pressable>
) : null}
</View>
</View>
);
}
@@ -3,7 +3,7 @@ import type { RemoteClientConnectionState } from "../../lib/connection";
export function connectionTone(state: RemoteClientConnectionState): StatusTone {
switch (state) {
case "ready":
case "connected":
return {
label: "Connected",
pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16",
@@ -21,15 +21,21 @@ export function connectionTone(state: RemoteClientConnectionState): StatusTone {
pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
textClassName: "text-sky-700 dark:text-sky-300",
};
case "disconnected":
case "error":
return {
label: "Disconnected",
label: "Connection failed",
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
textClassName: "text-rose-700 dark:text-rose-300",
};
case "idle":
case "offline":
return {
label: "Idle",
label: "Offline",
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
textClassName: "text-rose-700 dark:text-rose-300",
};
case "available":
return {
label: "Available",
pillClassName: "bg-neutral-500/10 dark:bg-neutral-500/16",
textClassName: "text-neutral-600 dark:text-neutral-300",
};
@@ -0,0 +1,130 @@
import { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import { describe, expect, it } from "vite-plus/test";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { splitEnvironmentSections } from "./environmentSections";
function connectedEnvironment(
input: Omit<Partial<ConnectedEnvironmentSummary>, "environmentId"> & {
readonly environmentId: string;
readonly isRelayManaged: boolean;
},
): ConnectedEnvironmentSummary {
return {
environmentId: EnvironmentId.make(input.environmentId),
environmentLabel: input.environmentLabel ?? input.environmentId,
displayUrl: input.displayUrl ?? `https://${input.environmentId}.example.test/`,
isRelayManaged: input.isRelayManaged,
connectionState: input.connectionState ?? "connected",
connectionError: input.connectionError ?? null,
connectionErrorTraceId: input.connectionErrorTraceId ?? null,
};
}
function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord {
return {
environmentId: EnvironmentId.make(environmentId),
label: environmentId,
endpoint: {
httpBaseUrl: `https://${environmentId}.cloud.example.test/`,
wsBaseUrl: `wss://${environmentId}.cloud.example.test/ws`,
providerKind: "cloudflare_tunnel",
},
linkedAt: "2026-01-01T00:00:00.000Z",
};
}
describe("mobile environment settings sections", () => {
it("keeps saved relay-managed connections under T3 Cloud", () => {
const local = connectedEnvironment({
environmentId: "environment-local",
isRelayManaged: false,
});
const cloud = connectedEnvironment({
environmentId: "environment-cloud",
isRelayManaged: true,
});
const sections = splitEnvironmentSections({
connectedEnvironments: [cloud, local],
cloudEnvironments: [
cloudEnvironment("environment-cloud"),
cloudEnvironment("environment-new"),
],
});
expect(sections.localEnvironments).toEqual([local]);
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
expect(
sections.availableCloudEnvironments.map((environment) => environment.environmentId),
).toEqual([EnvironmentId.make("environment-new")]);
});
it("keeps saved relay-managed connections visible when cloud listing is unavailable", () => {
const cloud = connectedEnvironment({
environmentId: "environment-cloud",
isRelayManaged: true,
connectionState: "reconnecting",
connectionError: "Environment did not respond before the connection timeout.",
});
const sections = splitEnvironmentSections({
connectedEnvironments: [cloud],
cloudEnvironments: null,
});
expect(sections.localEnvironments).toEqual([]);
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
expect(sections.availableCloudEnvironments).toEqual([]);
});
it("keeps an available saved relay environment as a fallback when listing is unavailable", () => {
const cloud = connectedEnvironment({
environmentId: "environment-cloud",
isRelayManaged: true,
connectionState: "available",
});
const sections = splitEnvironmentSections({
connectedEnvironments: [cloud],
cloudEnvironments: null,
});
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
expect(sections.availableCloudEnvironments).toEqual([]);
});
it("does not duplicate a saved relay environment in the available cloud listing", () => {
const cloud = connectedEnvironment({
environmentId: "environment-cloud",
isRelayManaged: true,
connectionState: "available",
});
const listedCloud = cloudEnvironment("environment-cloud");
const sections = splitEnvironmentSections({
connectedEnvironments: [cloud],
cloudEnvironments: [listedCloud],
});
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
expect(sections.availableCloudEnvironments).toEqual([]);
});
it("keeps failed relay environments in the local connection row", () => {
const cloud = connectedEnvironment({
environmentId: "environment-cloud",
isRelayManaged: true,
connectionState: "error",
connectionError: "Connection failed.",
});
const sections = splitEnvironmentSections({
connectedEnvironments: [cloud],
cloudEnvironments: [cloudEnvironment("environment-cloud")],
});
expect(sections.connectedCloudEnvironments).toEqual([cloud]);
expect(sections.availableCloudEnvironments).toEqual([]);
});
});
@@ -0,0 +1,31 @@
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
export interface EnvironmentSectionsInput {
readonly connectedEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly cloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord> | null;
}
export interface EnvironmentSections {
readonly localEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly availableCloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord>;
}
export function splitEnvironmentSections(input: EnvironmentSectionsInput): EnvironmentSections {
const savedEnvironmentIds = new Set(
input.connectedEnvironments.map((environment) => environment.environmentId),
);
return {
localEnvironments: input.connectedEnvironments.filter(
(environment) => !environment.isRelayManaged,
),
connectedCloudEnvironments: input.connectedEnvironments.filter(
(environment) => environment.isRelayManaged,
),
availableCloudEnvironments: (input.cloudEnvironments ?? []).filter(
(environment) => !savedEnvironmentIds.has(environment.environmentId),
),
};
}
@@ -0,0 +1,125 @@
import { useAtomValue } from "@effect/atom-react";
import {
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { useCallback, useMemo } from "react";
import { environmentCatalog } from "../../connection/catalog";
import {
connectPairingUrl as connectPairingUrlAtom,
updateBearerConnection,
} from "../../connection/onboarding";
import { useEnvironments } from "../../state/environments";
import { relayEnvironmentDiscovery } from "../../state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
import { projectWorkspaceEnvironment, type WorkspaceEnvironment } from "../../state/workspaceModel";
export interface RelayEnvironmentView {
readonly environment: RelayClientEnvironmentRecord;
readonly availability: "checking" | "online" | "offline" | "error";
readonly status: RelayEnvironmentStatusResponse | null;
readonly error: string | null;
readonly traceId: string | null;
}
export function useConnectionController() {
const { environments } = useEnvironments();
const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
const connectPairingUrlMutation = useAtomCommand(connectPairingUrlAtom, {
reportFailure: false,
});
const updateBearer = useAtomCommand(updateBearerConnection, { reportFailure: false });
const registerEnvironment = useAtomCommand(environmentCatalog.register, "environment register");
const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove");
const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const refreshRelayEnvironments = useAtomCommand(
relayEnvironmentDiscovery.refresh,
"relay environment refresh",
);
const connectedEnvironments = useMemo<ReadonlyArray<WorkspaceEnvironment>>(
() => environments.map(projectWorkspaceEnvironment),
[environments],
);
const registeredIds = useMemo(
() => new Set(connectedEnvironments.map((environment) => environment.environmentId)),
[connectedEnvironments],
);
const relayEnvironments = useMemo<ReadonlyArray<RelayEnvironmentView>>(
() =>
[...discovery.environments.values()].map((entry) => ({
environment: entry.environment,
availability: entry.availability,
status: Option.getOrNull(entry.status),
error: Option.getOrNull(entry.error)?.message ?? null,
traceId: Option.getOrNull(entry.error)?.traceId ?? null,
})),
[discovery.environments],
);
const availableRelayEnvironments = useMemo(
() => relayEnvironments.filter((entry) => !registeredIds.has(entry.environment.environmentId)),
[registeredIds, relayEnvironments],
);
const connectPairingUrl = useCallback(
(pairingUrl: string) => connectPairingUrlMutation(pairingUrl),
[connectPairingUrlMutation],
);
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
registerEnvironment(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[registerEnvironment],
);
const removeEnvironment = useCallback(
(environmentId: EnvironmentId) => removeEnvironmentMutation(environmentId),
[removeEnvironmentMutation],
);
const retryEnvironment = useCallback(
(environmentId: EnvironmentId) => retryEnvironmentMutation(environmentId),
[retryEnvironmentMutation],
);
const updateEnvironment = useCallback(
(
environmentId: EnvironmentId,
updates: { readonly label: string; readonly displayUrl: string },
) =>
updateBearer({
environmentId,
label: updates.label,
httpBaseUrl: updates.displayUrl,
}),
[updateBearer],
);
return {
connectedEnvironments,
relayEnvironments,
availableRelayEnvironments,
relayDiscovery: {
isRefreshing: discovery.refreshing,
isOffline: discovery.offline,
error: Option.getOrNull(discovery.error)?.message ?? null,
errorTraceId: Option.getOrNull(discovery.error)?.traceId ?? null,
},
connectPairingUrl,
connectRelayEnvironment,
removeEnvironment,
retryEnvironment,
updateEnvironment,
refreshRelayEnvironments,
};
}
+168 -123
View File
@@ -1,11 +1,11 @@
import type {
EnvironmentScopedProjectShell,
EnvironmentScopedThreadShell,
VcsStatusState,
} from "@t3tools/client-runtime";
import {
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -13,29 +13,29 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import type { RemoteCatalogState } from "../../state/use-remote-catalog";
import { useVcsStatus } from "../../state/use-vcs-status";
import { threadStatusTone } from "../threads/threadPresentation";
/* ─── Types ──────────────────────────────────────────────────────────── */
interface HomeScreenProps {
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly catalogState: RemoteCatalogState;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string;
readonly onAddConnection: () => void;
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
readonly onOpenEnvironments: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
}
interface ProjectGroup {
readonly key: string;
readonly project: EnvironmentScopedProjectShell;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
const projectGroupActivityOrder = Order.mapInput(
@@ -49,7 +49,7 @@ const projectGroupActivityOrder = Order.mapInput(
/* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: string } {
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
switch (thread.session?.status) {
case "running":
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
@@ -67,11 +67,11 @@ function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: s
const COLLAPSED_THREAD_LIMIT = 6;
function deriveEmptyState(props: {
readonly catalogState: RemoteCatalogState;
readonly catalogState: WorkspaceState;
readonly projectCount: number;
}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
const { catalogState } = props;
if (catalogState.isLoadingSavedConnections) {
if (catalogState.isLoadingConnections) {
return {
title: "Loading environments",
detail: "Checking saved environments on this device.",
@@ -79,7 +79,7 @@ function deriveEmptyState(props: {
};
}
if (!catalogState.hasSavedConnections) {
if (!catalogState.hasConnections) {
return {
title: "No environments connected",
detail: "Add an environment to load projects and start coding sessions.",
@@ -87,7 +87,12 @@ function deriveEmptyState(props: {
};
}
if (catalogState.connectionState === "disconnected" && !catalogState.hasLoadedShellSnapshot) {
if (
(catalogState.connectionState === "available" ||
catalogState.connectionState === "offline" ||
catalogState.connectionState === "error") &&
!catalogState.hasLoadedShellSnapshot
) {
return {
title: "Environment unavailable",
detail:
@@ -127,10 +132,8 @@ function deriveEmptyState(props: {
/* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: {
readonly project: EnvironmentScopedProjectShell;
readonly project: EnvironmentProject;
readonly totalThreadCount: number;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
}) {
@@ -139,11 +142,10 @@ function ProjectGroupLabel(props: {
return (
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
environmentId={props.project.environmentId}
size={18}
projectTitle={props.project.title}
httpBaseUrl={props.httpBaseUrl}
workspaceRoot={props.project.workspaceRoot}
bearerToken={props.bearerToken}
/>
<Text
className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted"
@@ -167,26 +169,11 @@ function ProjectGroupLabel(props: {
);
}
/* ─── Git summary line ──────────────────────────────────────────────── */
function gitSummaryParts(gitStatus: VcsStatusState): ReadonlyArray<string> {
if (!gitStatus.data) return [];
const { data } = gitStatus;
const parts: string[] = [];
if (data.hasWorkingTreeChanges) {
parts.push(`${data.workingTree.files.length} changed`);
}
if (data.aheadCount > 0) parts.push(`${data.aheadCount} ahead`);
if (data.behindCount > 0) parts.push(`${data.behindCount} behind`);
if (data.pr?.state === "open") parts.push(`PR #${data.pr.number}`);
return parts;
}
/* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: {
readonly thread: EnvironmentScopedThreadShell;
readonly projectCwd: string | null;
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly onPress: () => void;
readonly isLast: boolean;
}) {
@@ -196,15 +183,9 @@ function ThreadRow(props: {
const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
const branch = props.thread.branch;
// Subscribe to live git status — only when thread has a branch set.
// Threads sharing the same cwd share one WS subscription via ref-counting.
const cwd = branch ? (props.thread.worktreePath ?? props.projectCwd) : null;
const gitStatus = useVcsStatus({
environmentId: cwd ? props.thread.environmentId : null,
cwd,
});
const gitParts = gitSummaryParts(gitStatus);
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
Boolean(part),
);
return (
<Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
@@ -262,8 +243,8 @@ function ThreadRow(props: {
</View>
</View>
{/* Branch + git info */}
{branch ? (
{/* Environment + branch */}
{subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
@@ -276,13 +257,8 @@ function ThreadRow(props: {
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{branch}
{subtitleParts.join(" · ")}
</Text>
{gitParts.length > 0 ? (
<Text className="text-[11px] text-foreground-tertiary">
{" · " + gitParts.join(" · ")}
</Text>
) : null}
</View>
) : null}
</View>
@@ -293,8 +269,61 @@ function ThreadRow(props: {
/* ─── Main screen ────────────────────────────────────────────────────── */
function staleCatalogPillLabel(props: { readonly catalogState: WorkspaceState }): string {
if (props.catalogState.networkStatus === "offline") {
return "You are offline";
}
const connectingEnvironments = props.catalogState.connectingEnvironments;
if (connectingEnvironments.length === 1) {
return `Reconnecting to ${connectingEnvironments[0]!.environmentLabel}`;
}
if (connectingEnvironments.length > 1) {
return `Reconnecting ${connectingEnvironments.length} environments`;
}
return "Not connected";
}
function StaleCatalogStatusPill(props: {
readonly catalogState: WorkspaceState;
readonly onPress: () => void;
}) {
const iconColor = useThemeColor("--color-icon-muted");
const label = staleCatalogPillLabel(props);
const isReconnecting = props.catalogState.connectingEnvironments.length > 0;
return (
<Pressable
accessibilityRole="button"
onPress={props.onPress}
className="flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
style={{
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.12,
shadowRadius: 24,
}}
>
{isReconnecting ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="wifi.slash"
size={15}
tintColor={iconColor}
type="monochrome"
weight="semibold"
/>
)}
<Text className="max-w-[260px] text-[13px] font-t3-bold text-foreground" numberOfLines={1}>
{label}
</Text>
</Pressable>
);
}
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
const toggleExpanded = useCallback((key: string) => {
@@ -328,7 +357,7 @@ export function HomeScreen(props: HomeScreenProps) {
/* Group filtered threads by project */
const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
const byProject = new Map<string, EnvironmentScopedThreadShell[]>();
const byProject = new Map<string, EnvironmentThreadShell[]>();
for (const thread of filteredThreads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = byProject.get(key);
@@ -351,77 +380,93 @@ export function HomeScreen(props: HomeScreenProps) {
/* Empty states */
const hasAnyThreads = props.threads.length > 0;
const hasResults = filteredThreads.length > 0;
const shouldShowConnectionStatus =
props.catalogState.networkStatus === "offline" ||
props.catalogState.hasConnectingEnvironment ||
(props.catalogState.hasLoadedShellSnapshot && !props.catalogState.hasReadyEnvironment);
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
className="flex-1 bg-screen"
contentContainerStyle={{
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
gap: 20,
}}
>
{!hasAnyThreads ? (
<View>
<EmptyState
title={emptyState.title}
detail={emptyState.detail}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
/>
{emptyState.loading ? (
<View className="absolute right-5 top-5">
<ActivityIndicator color={accentColor} />
</View>
) : null}
</View>
) : !hasResults ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : (
projectGroups.map((group) => {
const connection = props.savedConnectionsById[group.project.environmentId];
const isExpanded = expandedProjects.has(group.key);
const visibleThreads = isExpanded
? group.threads
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
<View key={group.key}>
<ProjectGroupLabel
project={group.project}
totalThreadCount={group.threads.length}
httpBaseUrl={connection?.httpBaseUrl ?? null}
bearerToken={connection?.bearerToken ?? null}
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
/>
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{visibleThreads.map((thread, i) => (
<ThreadRow
key={`${thread.environmentId}:${thread.id}`}
thread={thread}
projectCwd={group.project.workspaceRoot}
onPress={() => props.onSelectThread(thread)}
isLast={i === visibleThreads.length - 1}
/>
))}
<View className="flex-1 bg-screen">
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
className="flex-1"
contentContainerStyle={{
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
gap: 20,
}}
>
{!hasAnyThreads ? (
<View>
<EmptyState
title={emptyState.title}
detail={emptyState.detail}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
/>
{emptyState.loading ? (
<View className="absolute right-5 top-5">
<ActivityIndicator color={accentColor} />
</View>
</View>
);
})
)}
</ScrollView>
) : null}
</View>
) : !hasResults ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : (
projectGroups.map((group) => {
const isExpanded = expandedProjects.has(group.key);
const visibleThreads = isExpanded
? group.threads
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
<View key={group.key}>
<ProjectGroupLabel
project={group.project}
totalThreadCount={group.threads.length}
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
/>
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{visibleThreads.map((thread, i) => (
<ThreadRow
key={`${thread.environmentId}:${thread.id}`}
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
onPress={() => props.onSelectThread(thread)}
isLast={i === visibleThreads.length - 1}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
{shouldShowConnectionStatus ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<StaleCatalogStatusPill
catalogState={props.catalogState}
onPress={props.onOpenEnvironments}
/>
</View>
) : null}
</View>
);
}
@@ -1,53 +0,0 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import { makeMobileTracingLayer } from "./mobileTracing";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
it.effect("exports spans through the scoped mobile OTLP layer", () => {
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
const tracingLayer = makeMobileTracingLayer(
{
tracesUrl: "https://api.axiom.test/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
{
appVariant: "test",
serviceVersion: "1.2.3",
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const tracedApplication = Layer.effectDiscard(
Effect.void.pipe(Effect.withSpan("mobile.test.span"), withRelayClientTracing),
).pipe(Layer.provide(tracingLayer));
return Effect.gen(function* () {
yield* Layer.build(tracedApplication);
expect(fetchFn).not.toHaveBeenCalled();
}).pipe(
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
expect(fetchFn).toHaveBeenCalledOnce();
const [url, init] = fetchFn.mock.calls[0]!;
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
}),
),
);
});
@@ -0,0 +1,97 @@
import { expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import { makeTracingLayer } from "./tracing";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
it.effect("exports spans through the scoped mobile OTLP layer", () => {
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
const tracingLayer = makeTracingLayer(
{
tracesUrl: "https://api.axiom.test/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
{
appVariant: "test",
serviceVersion: "1.2.3",
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const tracedApplication = Layer.effectDiscard(
Effect.void.pipe(Effect.withSpan("mobile.test.span"), withRelayClientTracing),
).pipe(Layer.provide(tracingLayer));
return Effect.gen(function* () {
yield* Layer.build(tracedApplication);
expect(fetchFn).not.toHaveBeenCalled();
}).pipe(
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
expect(fetchFn).toHaveBeenCalledOnce();
const [url, init] = fetchFn.mock.calls[0]!;
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
}),
),
);
});
it.effect("does not let OTLP serialization failures alter application effects", () => {
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
const tracingLayer = makeTracingLayer(
{
tracesUrl: "https://api.axiom.test/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
{
appVariant: "test",
serviceVersion: "1.2.3",
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const failure = { durationNanos: 1n };
const tracedApplication = Layer.effectDiscard(
Effect.fail(failure).pipe(
Effect.withSpan("mobile.test.failed-span"),
withRelayClientTracing,
Effect.exit,
Effect.flatMap((exit) => {
const reason = exit._tag === "Failure" ? exit.cause.reasons[0] : undefined;
return reason && Cause.isFailReason(reason)
? Effect.sync(() => {
expect(reason.error).toBe(failure);
})
: Effect.die(new Error("Expected the original typed failure."));
}),
),
).pipe(Layer.provide(tracingLayer));
return Layer.build(tracedApplication).pipe(
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
expect(fetchFn).toHaveBeenCalledOnce();
expect(new TextDecoder().decode(fetchFn.mock.calls[0]?.[1]?.body as Uint8Array)).toContain(
"mobile.test.failed-span",
);
}),
),
);
});
@@ -1,32 +1,29 @@
import Constants from "expo-constants";
import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
import { hasTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
export interface MobileTracingConfig {
export interface TracingConfig {
readonly tracesUrl: string;
readonly tracesDataset: string;
readonly tracesToken: string;
}
export interface MobileTracingResource {
export interface TracingResource {
readonly serviceVersion?: string;
readonly appVariant: string;
}
export function resolveMobileTracingConfig(): MobileTracingConfig | null {
export function resolveTracingConfig(): TracingConfig | null {
const config = resolveCloudPublicConfig();
if (!hasMobileTracingPublicConfig(config)) {
if (!hasTracingPublicConfig(config)) {
return null;
}
const { tracesUrl, tracesDataset, tracesToken } = config.observability;
return { tracesUrl, tracesDataset, tracesToken };
}
export function makeMobileTracingLayer(
config: MobileTracingConfig | null,
resource: MobileTracingResource,
) {
export function makeTracingLayer(config: TracingConfig | null, resource: TracingResource) {
return makeRelayClientTracingLayer(config, {
serviceName: "t3-mobile-relay-client",
serviceVersion: resource.serviceVersion,
@@ -35,7 +32,7 @@ export function makeMobileTracingLayer(
});
}
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
export const tracingLayer = makeTracingLayer(resolveTracingConfig(), {
serviceVersion: Constants.expoConfig?.version,
appVariant:
typeof Constants.expoConfig?.extra?.appVariant === "string"
@@ -2,23 +2,25 @@ import {
addProjectRemoteSourceLabel,
addProjectRemoteSourcePathHint,
addProjectRemoteSourceProvider,
appendBrowsePathSegment,
buildAddProjectRemoteSourceReadiness,
buildProjectCreateCommand,
canNavigateUp,
ensureBrowseDirectoryPath,
findExistingAddProject,
getAddProjectInitialQuery,
resolveAddProjectPath,
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime/operations/projects";
import {
appendBrowsePathSegment,
canNavigateUp,
ensureBrowseDirectoryPath,
getBrowseDirectoryPath,
getBrowseLeafPathSegment,
getBrowseParentPath,
hasTrailingPathSeparator,
inferProjectTitleFromPath,
isFilesystemBrowseQuery,
resolveAddProjectPath,
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/state/projects";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
@@ -26,21 +28,23 @@ import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
import * as Cause from "effect/Cause";
import * as Order from "effect/Order";
import { AsyncResult } from "effect/unstable/reactivity";
import { useProjects, useServerConfigs } from "../../state/entities";
import { filesystemEnvironment } from "../../state/filesystem";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import { sourceControlEnvironment } from "../../state/sourceControl";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner";
import { SourceControlIcon } from "../../components/SourceControlIcon";
import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { useFilesystemBrowse } from "../../state/use-filesystem-browse";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
import {
refreshSourceControlDiscoveryForEnvironment,
useSourceControlDiscovery,
} from "../../state/use-source-control-discovery";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
interface EnvironmentOption {
readonly environmentId: EnvironmentId;
@@ -224,12 +228,12 @@ function ProjectPathInput(props: {
}
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const { serverConfigByEnvironmentId } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const serverConfigByEnvironmentId = useServerConfigs();
const { savedConnectionsById } = useSavedRemoteConnections();
return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
const options = Object.values(savedConnectionsById).map((connection) => {
const config = serverConfigByEnvironmentId[connection.environmentId];
const config = serverConfigByEnvironmentId.get(connection.environmentId);
return {
environmentId: connection.environmentId,
label: connection.environmentLabel,
@@ -336,17 +340,19 @@ export function AddProjectSourceScreen() {
const iconColor = useThemeColor("--color-icon");
const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
useSelectedEnvironment();
const discoveryState = useSourceControlDiscovery(selectedEnvironment?.environmentId ?? null);
const discoveryState = useEnvironmentQuery(
selectedEnvironment === null
? null
: sourceControlEnvironment.discovery({
environmentId: selectedEnvironment.environmentId,
input: {},
}),
);
const readiness = useMemo(
() => buildAddProjectRemoteSourceReadiness(discoveryState.data),
[discoveryState.data],
);
useEffect(() => {
if (!selectedEnvironment) return;
void refreshSourceControlDiscoveryForEnvironment(selectedEnvironment.environmentId);
}, [selectedEnvironment]);
return (
<AddProjectShell>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
@@ -435,13 +441,12 @@ export function AddProjectSourceScreen() {
function useCreateProject(environment: EnvironmentOption | null) {
const router = useRouter();
const { projects } = useRemoteCatalog();
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
const projects = useProjects();
return useCallback(
async (workspaceRoot: string) => {
if (!environment) return;
const client = getEnvironmentClient(environment.environmentId);
if (!client) throw new Error("Environment API is not available.");
const existing = findExistingAddProject({
projects,
@@ -462,14 +467,19 @@ function useCreateProject(environment: EnvironmentOption | null) {
}
const projectId = ProjectId.make(uuidv4());
await client.orchestration.dispatchCommand(
buildProjectCreateCommand({
commandId: CommandId.make(uuidv4()),
projectId,
workspaceRoot,
createdAt: new Date().toISOString(),
}),
);
const command = buildProjectCreateCommand({
commandId: CommandId.make(uuidv4()),
projectId,
workspaceRoot,
createdAt: new Date().toISOString(),
});
const result = await createProject({
environmentId: environment.environmentId,
input: command,
});
if (AsyncResult.isFailure(result)) {
return result;
}
router.replace({
pathname: "/new/draft",
params: {
@@ -478,8 +488,9 @@ function useCreateProject(environment: EnvironmentOption | null) {
title: inferProjectTitleFromPath(workspaceRoot),
},
});
return result;
},
[environment, projects, router],
[createProject, environment, projects, router],
);
}
@@ -495,6 +506,9 @@ function useEnvironmentFromParam(): EnvironmentOption | null {
}
export function AddProjectRepositoryScreen() {
const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
reportFailure: false,
});
const router = useRouter();
const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
const environment = useEnvironmentFromParam();
@@ -507,28 +521,33 @@ export function AddProjectRepositoryScreen() {
if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
setError(null);
setIsSubmitting(true);
try {
const provider = addProjectRemoteSourceProvider(source);
if (!provider) {
const remoteUrl = repositoryInput.trim();
router.push({
pathname: "/new/add-project/destination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl,
repositoryTitle: remoteUrl,
},
});
return;
}
const provider = addProjectRemoteSourceProvider(source);
if (!provider) {
const remoteUrl = repositoryInput.trim();
router.push({
pathname: "/new/add-project/destination",
params: {
environmentId: environment.environmentId,
source,
remoteUrl,
repositoryTitle: remoteUrl,
},
});
setIsSubmitting(false);
return;
}
const client = getEnvironmentClient(environment.environmentId);
if (!client) throw new Error("Environment API is not available.");
const repository = await client.sourceControl.lookupRepository({
const result = await lookupRepositoryQuery({
environmentId: environment.environmentId,
input: {
provider,
repository: repositoryInput.trim(),
});
},
});
if (AsyncResult.isFailure(result)) {
setError(errorMessage(Cause.squash(result.cause)));
} else {
const repository = result.value;
router.push({
pathname: "/new/add-project/destination",
params: {
@@ -538,12 +557,9 @@ export function AddProjectRepositoryScreen() {
repositoryTitle: repository.nameWithOwner,
},
});
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
}
}, [environment, isSubmitting, repositoryInput, router, source]);
setIsSubmitting(false);
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, router, source]);
return (
<AddProjectShell>
@@ -593,7 +609,14 @@ function FolderBrowser(props: {
() => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null),
[browseDirectoryPath],
);
const browseState = useFilesystemBrowse(props.environment.environmentId, browseInput);
const browseState = useEnvironmentQuery(
browseInput === null
? null
: filesystemEnvironment.browse({
environmentId: props.environment.environmentId,
input: browseInput,
}),
);
const visibleBrowseEntries = useMemo(
() =>
Arr.sort(
@@ -686,13 +709,11 @@ export function AddProjectLocalFolderScreen() {
}
setIsSubmitting(true);
try {
await createProject(resolved.path);
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
const result = await createProject(resolved.path);
if (result && AsyncResult.isFailure(result)) {
setError(errorMessage(Cause.squash(result.cause)));
}
setIsSubmitting(false);
}, [createProject, environment, isSubmitting, pathInput]);
return (
@@ -725,6 +746,9 @@ export function AddProjectLocalFolderScreen() {
}
export function AddProjectDestinationScreen() {
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
reportFailure: false,
});
const params = useLocalSearchParams<{
environmentId?: string;
remoteUrl?: string;
@@ -759,20 +783,23 @@ export function AddProjectDestinationScreen() {
}
setIsSubmitting(true);
try {
const client = getEnvironmentClient(environment.environmentId);
if (!client) throw new Error("Environment API is not available.");
const result = await client.sourceControl.cloneRepository({
const cloneResult = await cloneRepository({
environmentId: environment.environmentId,
input: {
remoteUrl,
destinationPath: resolved.path,
});
await createProject(result.cwd);
} catch (nextError) {
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
},
});
if (AsyncResult.isFailure(cloneResult)) {
setError(errorMessage(Cause.squash(cloneResult.cause)));
} else {
const createResult = await createProject(cloneResult.value.cwd);
if (createResult && AsyncResult.isFailure(createResult)) {
setError(errorMessage(Cause.squash(createResult.cause)));
}
}
}, [createProject, environment, isSubmitting, pathInput, remoteUrl]);
setIsSubmitting(false);
}, [cloneRepository, createProject, environment, isSubmitting, pathInput, remoteUrl]);
return (
<AddProjectShell>
+65 -24
View File
@@ -16,8 +16,12 @@ import {
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { useAtomCommand } from "../../state/use-atom-command";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { useReviewCacheForThread } from "./reviewState";
import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
import {
@@ -29,6 +33,7 @@ import { useReviewFileVisibility } from "./reviewFileVisibility";
import { useReviewSections } from "./useReviewSections";
import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge";
import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController";
import { resolveReviewAvailability } from "./reviewAvailability";
const IOS_NAV_BAR_HEIGHT = 44;
const REVIEW_HEADER_SPACING = 0;
@@ -114,6 +119,9 @@ export function ReviewSheet() {
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
const environment = useEnvironmentPresentation(environmentId);
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
const selectedTheme = colorScheme === "dark" ? "dark" : "light";
@@ -126,7 +134,12 @@ export function ReviewSheet() {
selectedSection,
refreshSelectedSection,
selectSection,
} = useReviewSections({ environmentId, threadId, reviewCache });
} = useReviewSections({
enabled: isEnvironmentReady,
environmentId,
threadId,
reviewCache,
});
const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } =
useReviewDiffData({
threadKey: reviewCache.threadKey,
@@ -187,6 +200,17 @@ export function ReviewSheet() {
const parsedDiffNotice =
parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
const hasCachedSelectedDiff = selectedSection?.diff != null;
const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
hasEnvironmentPresentation: environment.isReady,
isEnvironmentConnected: isEnvironmentReady,
hasCachedSelectedDiff,
hasAnyCachedDiff,
});
const handleRetryEnvironment = useCallback(() => {
void retryEnvironment(environmentId);
}, [environmentId, retryEnvironment]);
const listHeader = useMemo(() => {
const children: ReactElement[] = [];
@@ -312,34 +336,51 @@ export function ReviewSheet() {
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
{reviewSections.map((section) => (
{showSectionToolbar ? (
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
{reviewSections.map((section) => (
<Stack.Toolbar.MenuAction
key={section.id}
icon={section.id === selectedSection?.id ? "checkmark" : "circle"}
onPress={() => selectSection(section.id)}
subtitle={section.subtitle ?? undefined}
>
<Stack.Toolbar.Label>{section.title}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
<Stack.Toolbar.MenuAction
key={section.id}
icon={section.id === selectedSection?.id ? "checkmark" : "circle"}
onPress={() => selectSection(section.id)}
subtitle={section.subtitle ?? undefined}
icon="arrow.clockwise"
disabled={
loadingGitDiffs ||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
}
onPress={() => void refreshSelectedSection()}
subtitle="Reload current diff"
>
<Stack.Toolbar.Label>{section.title}</Stack.Toolbar.Label>
<Stack.Toolbar.Label>Refresh</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
<Stack.Toolbar.MenuAction
icon="arrow.clockwise"
disabled={
loadingGitDiffs ||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
}
onPress={() => void refreshSelectedSection()}
subtitle="Reload current diff"
>
<Stack.Toolbar.Label>Refresh</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
) : null}
<View className="flex-1 bg-sheet">
{selectedSection && parsedDiff.kind === "files" ? (
{showConnectionNotice ? (
<View style={{ flex: 1, paddingTop: topContentInset }}>
<EnvironmentConnectionNotice
environmentLabel={environment.presentation?.entry.target.label ?? "Environment"}
connection={
environment.presentation?.connection ?? {
phase: "available",
error: null,
traceId: null,
}
}
resourceName="review"
onRetry={handleRetryEnvironment}
/>
</View>
) : selectedSection && parsedDiff.kind === "files" ? (
<View
className="flex-1"
style={{
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveReviewAvailability } from "./reviewAvailability";
describe("resolveReviewAvailability", () => {
it("keeps section navigation available when another section is cached offline", () => {
expect(
resolveReviewAvailability({
hasEnvironmentPresentation: true,
isEnvironmentConnected: false,
hasCachedSelectedDiff: false,
hasAnyCachedDiff: true,
}),
).toEqual({
showConnectionNotice: true,
showSectionToolbar: true,
});
});
it("hides section navigation when no review section is available offline", () => {
expect(
resolveReviewAvailability({
hasEnvironmentPresentation: true,
isEnvironmentConnected: false,
hasCachedSelectedDiff: false,
hasAnyCachedDiff: false,
}),
).toEqual({
showConnectionNotice: true,
showSectionToolbar: false,
});
});
it("shows cached selected content and navigation while offline", () => {
expect(
resolveReviewAvailability({
hasEnvironmentPresentation: true,
isEnvironmentConnected: false,
hasCachedSelectedDiff: true,
hasAnyCachedDiff: true,
}),
).toEqual({
showConnectionNotice: false,
showSectionToolbar: true,
});
});
});
@@ -0,0 +1,19 @@
export function resolveReviewAvailability(input: {
readonly hasEnvironmentPresentation: boolean;
readonly isEnvironmentConnected: boolean;
readonly hasCachedSelectedDiff: boolean;
readonly hasAnyCachedDiff: boolean;
}): {
readonly showConnectionNotice: boolean;
readonly showSectionToolbar: boolean;
} {
const showConnectionNotice =
input.hasEnvironmentPresentation &&
!input.isEnvironmentConnected &&
!input.hasCachedSelectedDiff;
return {
showConnectionNotice,
showSectionToolbar: !showConnectionNotice || input.hasAnyCachedDiff,
};
}
@@ -1,110 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId, ReviewDiffPreviewResult } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { getEnvironmentClient } from "../../state/environment-session-registry";
const REVIEW_DIFF_PREVIEW_STALE_TIME_MS = 5_000;
const REVIEW_DIFF_PREVIEW_IDLE_TTL_MS = 5 * 60_000;
const REVIEW_DIFF_PREVIEW_KEY_SEPARATOR = "\u001f";
export interface ReviewDiffPreviewState {
readonly data: ReviewDiffPreviewResult | null;
readonly error: string | null;
readonly isPending: boolean;
readonly refresh: () => void;
}
function makeReviewDiffPreviewKey(input: {
readonly environmentId: EnvironmentId;
readonly cwd: string;
}): string {
return `${input.environmentId}${REVIEW_DIFF_PREVIEW_KEY_SEPARATOR}${input.cwd}`;
}
function parseReviewDiffPreviewKey(key: string): {
readonly environmentId: EnvironmentId;
readonly cwd: string;
} {
const [environmentId, cwd = ""] = key.split(REVIEW_DIFF_PREVIEW_KEY_SEPARATOR);
return {
environmentId: environmentId as EnvironmentId,
cwd,
};
}
const reviewDiffPreviewAtom = Atom.family((key: string) =>
Atom.make(
Effect.promise(async (): Promise<ReviewDiffPreviewResult> => {
const target = parseReviewDiffPreviewKey(key);
const client = getEnvironmentClient(target.environmentId);
if (!client) {
throw new Error("Remote connection is not ready.");
}
return client.review.getDiffPreview({ cwd: target.cwd });
}),
).pipe(
Atom.swr({
staleTime: REVIEW_DIFF_PREVIEW_STALE_TIME_MS,
revalidateOnMount: true,
}),
Atom.setIdleTTL(REVIEW_DIFF_PREVIEW_IDLE_TTL_MS),
Atom.withLabel(`mobile:review:diff-preview:${key}`),
),
);
const EMPTY_REVIEW_DIFF_PREVIEW_RESULT_ATOM = Atom.make(
AsyncResult.initial<ReviewDiffPreviewResult, never>(false),
).pipe(Atom.keepAlive, Atom.withLabel("mobile:review:diff-preview:null"));
function readReviewDiffPreviewError(
result: AsyncResult.AsyncResult<ReviewDiffPreviewResult, unknown>,
): string | null {
if (result._tag !== "Failure") {
return null;
}
const error = Cause.squash(result.cause);
return error instanceof Error ? error.message : "Failed to load review diffs.";
}
export function useReviewDiffPreview(input: {
readonly environmentId?: EnvironmentId;
readonly cwd: string | null;
}): ReviewDiffPreviewState {
const key = useMemo(() => {
if (!input.environmentId || !input.cwd) {
return null;
}
return makeReviewDiffPreviewKey({ environmentId: input.environmentId, cwd: input.cwd });
}, [input.cwd, input.environmentId]);
const atom = key ? reviewDiffPreviewAtom(key) : null;
const result = useAtomValue(atom ?? EMPTY_REVIEW_DIFF_PREVIEW_RESULT_ATOM);
const refresh = useCallback(() => {
if (atom) {
appAtomRegistry.refresh(atom);
}
}, [atom]);
if (!atom) {
return {
data: null,
error: null,
isPending: false,
refresh,
};
}
return {
data: Option.getOrNull(AsyncResult.value(result)),
error: readReviewDiffPreviewError(result),
isPending: result.waiting,
refresh,
};
}
@@ -1,12 +1,12 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useCallback, useEffect, useMemo } from "react";
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { checkpointDiffManager, loadCheckpointDiff } from "../../state/use-checkpoint-diff";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useCheckpointDiff } from "../../state/queries";
import { useEnvironmentQuery } from "../../state/query";
import { reviewEnvironment } from "../../state/review";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useReviewDiffPreview } from "./reviewDiffPreviewState";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import {
buildReviewSectionItems,
getDefaultReviewSectionId,
@@ -17,29 +17,30 @@ import {
setReviewAsyncError,
setReviewGitSections,
setReviewSelectedSectionId,
setReviewTurnDiffLoading,
setReviewTurnDiff,
setReviewTurnDiffLoading,
type ReviewCacheForThread,
} from "./reviewState";
export function useReviewSections(input: {
readonly enabled?: boolean;
readonly environmentId?: EnvironmentId;
readonly threadId?: ThreadId;
readonly reviewCache: ReviewCacheForThread;
}) {
const { environmentId, reviewCache, threadId } = input;
const enabled = input.enabled ?? true;
const selectedThread = useSelectedThreadDetail();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const diffPreview = useReviewDiffPreview({ environmentId, cwd: selectedThreadCwd });
const refreshDiffPreview = diffPreview.refresh;
const diffPreview = useEnvironmentQuery(
enabled && environmentId !== undefined && selectedThreadCwd !== null
? reviewEnvironment.diffPreview({
environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const { loadingTurnIds } = reviewCache.asyncState;
const error = diffPreview.error ?? reviewCache.asyncState.error;
const loadingGitDiffs = diffPreview.isPending;
const turnDiffByIdRef = useRef(reviewCache.turnDiffById);
useEffect(() => {
turnDiffByIdRef.current = reviewCache.turnDiffById;
}, [reviewCache.turnDiffById]);
useEffect(() => {
if (reviewCache.threadKey && diffPreview.data) {
@@ -51,14 +52,16 @@ export function useReviewSections(input: {
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
[selectedThread?.checkpoints],
);
const checkpointBySectionId = useMemo(() => {
return Object.fromEntries(
readyCheckpoints.map((checkpoint) => [
getReviewSectionIdForCheckpoint(checkpoint),
checkpoint,
]),
) as Record<string, OrchestrationCheckpointSummary>;
}, [readyCheckpoints]);
const checkpointBySectionId = useMemo(
() =>
Object.fromEntries(
readyCheckpoints.map((checkpoint) => [
getReviewSectionIdForCheckpoint(checkpoint),
checkpoint,
]),
) as Record<string, OrchestrationCheckpointSummary>,
[readyCheckpoints],
);
const reviewSections = useMemo(
() =>
buildReviewSectionItems({
@@ -87,7 +90,6 @@ export function useReviewSections(input: {
() => getDefaultReviewSectionId(reviewSections),
[reviewSections],
);
const hasReviewSections = reviewSections.length > 0;
const selectedSectionIdExists = useMemo(
() =>
reviewCache.selectedSectionId
@@ -96,140 +98,69 @@ export function useReviewSections(input: {
[reviewCache.selectedSectionId, reviewSections],
);
const loadTurnDiff = useCallback(
async (checkpoint: OrchestrationCheckpointSummary, force = false) => {
if (!environmentId || !threadId) {
return;
}
const sectionId = getReviewSectionIdForCheckpoint(checkpoint);
if (reviewCache.threadKey) {
setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
}
if (!force && turnDiffByIdRef.current[sectionId] !== undefined) {
return;
}
const target = {
environmentId,
threadId,
fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1),
toTurnCount: checkpoint.checkpointTurnCount,
ignoreWhitespace: false,
cacheScope: sectionId,
};
const cached = checkpointDiffManager.getSnapshot(target).data;
if (!force && cached) {
if (reviewCache.threadKey) {
setReviewTurnDiff(reviewCache.threadKey, sectionId, cached.diff);
}
return;
}
if (!getEnvironmentClient(environmentId)) {
if (reviewCache.threadKey) {
setReviewAsyncError(reviewCache.threadKey, "Remote connection is not ready.");
}
return;
}
if (reviewCache.threadKey) {
setReviewTurnDiffLoading(reviewCache.threadKey, sectionId, true);
setReviewAsyncError(reviewCache.threadKey, null);
}
try {
const result = await loadCheckpointDiff(target, { force });
if (reviewCache.threadKey) {
if (result) {
setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff);
}
}
} catch (cause) {
if (reviewCache.threadKey) {
setReviewAsyncError(
reviewCache.threadKey,
cause instanceof Error ? cause.message : "Failed to load turn diff.",
);
}
} finally {
if (reviewCache.threadKey) {
setReviewTurnDiffLoading(reviewCache.threadKey, sectionId, false);
}
}
},
[environmentId, reviewCache.threadKey, threadId],
);
useEffect(() => {
if (!hasReviewSections) {
return;
}
if (reviewCache.threadKey && (!reviewCache.selectedSectionId || !selectedSectionIdExists)) {
if (
reviewSections.length > 0 &&
reviewCache.threadKey &&
(!reviewCache.selectedSectionId || !selectedSectionIdExists)
) {
setReviewSelectedSectionId(reviewCache.threadKey, fallbackSectionId);
}
}, [
fallbackSectionId,
hasReviewSections,
reviewCache.selectedSectionId,
reviewCache.threadKey,
reviewSections.length,
selectedSectionIdExists,
]);
const latestCheckpoint = readyCheckpoints[0] ?? null;
const latestSectionId = latestCheckpoint
? getReviewSectionIdForCheckpoint(latestCheckpoint)
let activeCheckpoint = readyCheckpoints[0] ?? null;
if (selectedSection?.kind === "turn") {
activeCheckpoint = checkpointBySectionId[selectedSection.id] ?? activeCheckpoint;
}
const activeSectionId = activeCheckpoint
? getReviewSectionIdForCheckpoint(activeCheckpoint)
: null;
const latestTurnDiffLoaded = latestSectionId
? reviewCache.turnDiffById[latestSectionId] !== undefined
: true;
const latestTurnDiffLoading = latestSectionId ? loadingTurnIds[latestSectionId] === true : false;
const activeTurnDiff = useCheckpointDiff({
environmentId: enabled ? (environmentId ?? null) : null,
threadId: enabled ? (threadId ?? null) : null,
fromTurnCount:
enabled && activeCheckpoint ? Math.max(0, activeCheckpoint.checkpointTurnCount - 1) : null,
toTurnCount: enabled ? (activeCheckpoint?.checkpointTurnCount ?? null) : null,
ignoreWhitespace: false,
});
useEffect(() => {
if (!latestCheckpoint || !latestSectionId || latestTurnDiffLoaded || latestTurnDiffLoading) {
if (!reviewCache.threadKey || !activeSectionId) {
return;
}
void loadTurnDiff(latestCheckpoint);
}, [
latestCheckpoint,
latestSectionId,
latestTurnDiffLoaded,
latestTurnDiffLoading,
loadTurnDiff,
]);
const selectedTurnCheckpoint =
selectedSection?.kind === "turn" ? (checkpointBySectionId[selectedSection.id] ?? null) : null;
const selectedTurnDiffMissing =
selectedSection?.kind === "turn" && selectedSection.diff === null && selectedTurnCheckpoint;
const selectedTurnDiffLoading =
selectedSection?.kind === "turn" ? loadingTurnIds[selectedSection.id] === true : false;
setReviewTurnDiffLoading(reviewCache.threadKey, activeSectionId, activeTurnDiff.isPending);
}, [activeSectionId, activeTurnDiff.isPending, reviewCache.threadKey]);
useEffect(() => {
if (!selectedTurnDiffMissing || selectedTurnDiffLoading) {
if (!reviewCache.threadKey || !activeSectionId || !activeTurnDiff.data) {
return;
}
setReviewTurnDiff(reviewCache.threadKey, activeSectionId, activeTurnDiff.data.diff);
setReviewAsyncError(reviewCache.threadKey, null);
}, [activeSectionId, activeTurnDiff.data, reviewCache.threadKey]);
void loadTurnDiff(selectedTurnDiffMissing);
}, [loadTurnDiff, selectedTurnDiffLoading, selectedTurnDiffMissing]);
useEffect(() => {
if (reviewCache.threadKey && activeTurnDiff.error) {
setReviewAsyncError(reviewCache.threadKey, activeTurnDiff.error);
}
}, [activeTurnDiff.error, reviewCache.threadKey]);
const refreshSelectedSection = useCallback(async () => {
if (!selectedSection) {
if (!enabled) {
return;
}
if (selectedSection.kind === "turn") {
const checkpoint = checkpointBySectionId[selectedSection.id];
if (checkpoint) {
await loadTurnDiff(checkpoint, true);
}
if (selectedSection?.kind === "turn") {
activeTurnDiff.refresh();
return;
}
refreshDiffPreview();
}, [checkpointBySectionId, loadTurnDiff, refreshDiffPreview, selectedSection]);
diffPreview.refresh();
}, [activeTurnDiff, diffPreview, enabled, selectedSection?.kind]);
const selectSection = useCallback(
(sectionId: string) => {
@@ -241,8 +172,8 @@ export function useReviewSections(input: {
);
return {
error,
loadingGitDiffs,
error: diffPreview.error ?? activeTurnDiff.error ?? reviewCache.asyncState.error,
loadingGitDiffs: diffPreview.isPending,
loadingTurnIds,
reviewSections,
selectedSection,
@@ -1,18 +1,19 @@
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import {
attachTerminalSession,
useTerminalSession,
useTerminalSessionTarget,
} from "../../state/use-terminal-session";
import { terminalEnvironment } from "../../state/terminal";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAttachedTerminalSession } from "../../state/use-terminal-session";
import { TerminalSurface } from "./NativeTerminalSurface";
import { hasNativeTerminalSurface } from "./nativeTerminalModule";
import { terminalDebugLog } from "./terminalDebugLog";
import {
buildThreadTerminalAttachInput,
type TerminalGridSize,
type ThreadTerminalSubscriptionIdentity,
} from "./threadTerminalPanelModel";
interface ThreadTerminalPanelProps {
readonly environmentId: EnvironmentId;
@@ -29,108 +30,93 @@ const DEFAULT_TERMINAL_ROWS = 24;
export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
props: ThreadTerminalPanelProps,
) {
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
const nativeTerminalAvailable = hasNativeTerminalSurface();
const terminalId = DEFAULT_TERMINAL_ID;
const target = useTerminalSessionTarget({
environmentId: props.environmentId,
threadId: props.threadId,
terminalId,
});
const terminal = useTerminalSession(target);
const [lastGridSize, setLastGridSize] = useState({
const lastGridSizeRef = useRef<TerminalGridSize>({
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
});
const lastGridSizeRef = useRef(lastGridSize);
lastGridSizeRef.current = lastGridSize;
const subscriptionIdentity = useMemo<ThreadTerminalSubscriptionIdentity>(
() => ({
environmentId: props.environmentId,
threadId: props.threadId,
terminalId,
cwd: props.cwd,
worktreePath: props.worktreePath,
}),
[props.cwd, props.environmentId, props.threadId, props.worktreePath, terminalId],
);
const attachInput = useMemo(
() =>
props.visible
? buildThreadTerminalAttachInput(subscriptionIdentity, lastGridSizeRef.current)
: null,
[props.visible, subscriptionIdentity],
);
const terminal = useAttachedTerminalSession({
environmentId: props.environmentId,
terminal: attachInput,
});
const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
const isRunning = terminal.status === "running" || terminal.status === "starting";
useEffect(() => {
if (!props.visible) {
return;
}
const client = getEnvironmentClient(props.environmentId);
if (!client) {
terminalDebugLog("panel:attach-skip", {
reason: "no-environment-client",
const sendResize = useCallback(
(size: TerminalGridSize) => {
void resizeTerminal({
environmentId: props.environmentId,
input: {
threadId: props.threadId,
terminalId,
cols: size.cols,
rows: size.rows,
},
});
return;
},
[props.environmentId, props.threadId, resizeTerminal, terminalId],
);
useEffect(() => {
if (isRunning) {
sendResize(lastGridSizeRef.current);
}
terminalDebugLog("panel:attach", {
environmentId: props.environmentId,
threadId: props.threadId,
terminalId,
});
return attachTerminalSession({
environmentId: props.environmentId,
client,
terminal: {
threadId: props.threadId,
terminalId,
cwd: props.cwd,
worktreePath: props.worktreePath,
cols: lastGridSizeRef.current.cols,
rows: lastGridSizeRef.current.rows,
},
});
}, [
props.cwd,
props.environmentId,
props.threadId,
props.worktreePath,
props.visible,
terminalId,
]);
}, [isRunning, sendResize]);
const handleInput = useCallback(
(data: string) => {
const client = getEnvironmentClient(props.environmentId);
if (!client || !isRunning) {
if (!isRunning) {
return;
}
void client.terminal.write({
threadId: props.threadId,
terminalId,
data,
void writeTerminal({
environmentId: props.environmentId,
input: {
threadId: props.threadId,
terminalId,
data,
},
});
},
[isRunning, props.environmentId, props.threadId, terminalId],
[isRunning, props.environmentId, props.threadId, terminalId, writeTerminal],
);
const handleResize = useCallback(
(size: { readonly cols: number; readonly rows: number }) => {
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
(size: TerminalGridSize) => {
const previousSize = lastGridSizeRef.current;
if (size.cols === previousSize.cols && size.rows === previousSize.rows) {
return;
}
setLastGridSize(size);
const client = getEnvironmentClient(props.environmentId);
if (!client || !isRunning) {
lastGridSizeRef.current = size;
if (!isRunning) {
return;
}
void client.terminal.resize({
threadId: props.threadId,
terminalId,
cols: size.cols,
rows: size.rows,
});
sendResize(size);
},
[
isRunning,
lastGridSize.cols,
lastGridSize.rows,
props.environmentId,
props.threadId,
terminalId,
],
[isRunning, sendResize],
);
if (!props.visible) {
@@ -1,10 +1,5 @@
import {
DEFAULT_TERMINAL_ID,
EnvironmentId,
type TerminalAttachStreamEvent,
ThreadId,
} from "@t3tools/contracts";
import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import { SymbolView } from "expo-symbols";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,17 +19,19 @@ import {
import { EmptyState } from "../../components/EmptyState";
import { GlassSurface } from "../../components/GlassSurface";
import { LoadingScreen } from "../../components/LoadingScreen";
import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { terminalEnvironment } from "../../state/terminal";
import { useAtomCommand } from "../../state/use-atom-command";
import { useWorkspaceState } from "../../state/workspace";
import { buildThreadTerminalNavigation } from "../../lib/routes";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
import {
attachTerminalSession,
useAttachedTerminalSession,
useKnownTerminalSessions,
useTerminalSession,
useTerminalSessionTarget,
} from "../../state/use-terminal-session";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { TerminalSurface } from "./NativeTerminalSurface";
import { getPierreTerminalTheme } from "./terminalTheme";
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
@@ -44,11 +41,10 @@ import {
getTerminalSurfaceReplayBuffer,
TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
} from "./terminalBufferReplay";
import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
import {
resolveTerminalOpenLocation,
stagePendingTerminalLaunch,
takePendingTerminalLaunch,
type PendingTerminalLaunch,
} from "./terminalLaunchContext";
import {
basename,
@@ -158,8 +154,12 @@ function pickRunningTerminalSessionForBootstrap(
export function ThreadTerminalRouteScreen() {
const router = useRouter();
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const { state: workspaceState } = useWorkspaceState();
const params = useLocalSearchParams<{
environmentId?: string | string[];
threadId?: string | string[];
@@ -174,6 +174,8 @@ export function ThreadTerminalRouteScreen() {
? EnvironmentId.make(routeEnvironmentIdRaw)
: null;
const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
const environment = useEnvironmentPresentation(routeEnvironmentId);
const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
const requestedTerminalId = firstRouteParam(params.terminalId);
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
const cachedFontSize = getCachedTerminalFontSize();
@@ -189,6 +191,47 @@ export function ThreadTerminalRouteScreen() {
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
const runningSession = useMemo(
() => pickRunningTerminalSessionForBootstrap(knownSessions),
[knownSessions],
);
const activeKnownSession = useMemo(
() => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
[knownSessions, terminalId],
);
const launchTarget = useMemo(
() =>
selectedThread
? {
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
terminalId,
}
: null,
[selectedThread, terminalId],
);
const launchTargetKey = launchTarget
? `${launchTarget.environmentId}:${launchTarget.threadId}:${launchTarget.terminalId}`
: null;
const [pendingLaunchEntry, setPendingLaunchEntry] = useState<{
readonly key: string | null;
readonly launch: PendingTerminalLaunch | null;
}>(() => ({
key: launchTargetKey,
launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
}));
const pendingLaunch =
pendingLaunchEntry.key === launchTargetKey ? pendingLaunchEntry.launch : null;
const hasResolvedPendingLaunch = pendingLaunchEntry.key === launchTargetKey;
const [initialAttachGridEntry, setInitialAttachGridEntry] = useState(() => ({
key: launchTargetKey,
size: cachedRouteGridSize ?? {
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
},
}));
const initialAttachGridSize =
initialAttachGridEntry.key === launchTargetKey ? initialAttachGridEntry.size : null;
const [lastGridSize, setLastGridSize] = useState(
cachedRouteGridSize ?? {
cols: DEFAULT_TERMINAL_COLS,
@@ -198,11 +241,10 @@ export function ThreadTerminalRouteScreen() {
const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
const hasOpenedRef = useRef(false);
const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const attachStreamLogCountRef = useRef(0);
const firstNonEmptyBufferLoggedRef = useRef(false);
const lastBufferReplayKeyRef = useRef<string | null>(null);
const sentInitialInputKeyRef = useRef<string | null>(null);
const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState(
cachedFontSize !== null,
@@ -216,12 +258,78 @@ export function ThreadTerminalRouteScreen() {
terminalId,
value: null,
});
const target = useTerminalSessionTarget({
const shouldRedirectToRunningTerminal =
requestedTerminalId === null &&
runningSession !== null &&
runningSession.target.terminalId !== terminalId;
const launchLocationCandidate = useMemo(() => {
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
return null;
}
if (pendingLaunch) {
return {
cwd: pendingLaunch.cwd,
worktreePath: pendingLaunch.worktreePath,
};
}
return resolveTerminalOpenLocation({
terminalLocation: activeKnownSession?.state.summary ?? null,
activeSessionLocation: activeKnownSession?.state.summary ?? null,
workspaceRoot: selectedThreadProject.workspaceRoot,
threadShellWorktreePath: selectedThread.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
});
}, [
activeKnownSession?.state.summary,
pendingLaunch,
selectedThread,
selectedThreadDetail?.worktreePath,
selectedThreadProject?.workspaceRoot,
]);
const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
key: launchTargetKey,
location: launchLocationCandidate,
}));
const launchLocation =
initialLaunchLocationEntry.key === launchTargetKey ? initialLaunchLocationEntry.location : null;
const terminalAttachInput = useMemo(
() =>
selectedThread !== null &&
launchLocation !== null &&
hasResolvedPendingLaunch &&
initialAttachGridSize !== null &&
hasResolvedFontPreference &&
hasMeasuredSurface &&
isEnvironmentReady &&
!shouldRedirectToRunningTerminal
? {
threadId: selectedThread.id,
terminalId,
cwd: launchLocation.cwd,
worktreePath: launchLocation.worktreePath,
cols: initialAttachGridSize.cols,
rows: initialAttachGridSize.rows,
...(pendingLaunch?.env ? { env: pendingLaunch.env } : {}),
...(pendingLaunch ? { restartIfNotRunning: true } : {}),
}
: null,
[
hasMeasuredSurface,
hasResolvedFontPreference,
hasResolvedPendingLaunch,
initialAttachGridSize,
isEnvironmentReady,
launchLocation,
pendingLaunch,
selectedThread,
shouldRedirectToRunningTerminal,
terminalId,
],
);
const terminal = useAttachedTerminalSession({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
terminalId,
terminal: terminalAttachInput,
});
const terminal = useTerminalSession(target);
const terminalKey = selectedThread
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
: terminalId;
@@ -293,23 +401,6 @@ export function ThreadTerminalRouteScreen() {
() => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
[selectedEnvironmentConnection?.environmentLabel],
);
const runningSession = useMemo(
() => pickRunningTerminalSessionForBootstrap(knownSessions),
[knownSessions],
);
const activeKnownSession = useMemo(
() => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
[knownSessions, terminalId],
);
const terminalAttachLaunchHintsRef = useRef({
terminalSummary: terminal.summary,
activeKnownSummary: activeKnownSession?.state.summary ?? null,
});
terminalAttachLaunchHintsRef.current = {
terminalSummary: terminal.summary,
activeKnownSummary: activeKnownSession?.state.summary ?? null,
};
const terminalTheme = getPierreTerminalTheme(appearanceScheme);
const pendingModifier =
@@ -406,145 +497,88 @@ export function ThreadTerminalRouteScreen() {
],
);
const logAttachStreamEvent = useCallback((event: TerminalAttachStreamEvent) => {
const n = ++attachStreamLogCountRef.current;
if (event.type === "output" && n > 32 && n % 64 !== 0) {
useEffect(() => {
if (pendingLaunchEntry.key === launchTargetKey) {
return;
}
if (event.type === "snapshot") {
terminalDebugLog("attach:stream", {
n,
type: event.type,
status: event.snapshot.status,
historyLen: event.snapshot.history.length,
cwd: event.snapshot.cwd,
});
return;
}
if (event.type === "output") {
terminalDebugLog("attach:stream", { n, type: event.type, dataLen: event.data.length });
return;
}
terminalDebugLog("attach:stream", { n, type: event.type });
}, []);
const attachTerminal = useCallback(() => {
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
terminalDebugLog("attach:abort", { reason: "no-thread-or-workspace" });
return null;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
terminalDebugLog("attach:abort", {
reason: "no-environment-client",
environmentId: selectedThread.environmentId,
});
return null;
}
const pendingLaunchTarget = {
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
terminalId,
};
const pendingLaunch = takePendingTerminalLaunch(pendingLaunchTarget);
let initialInputSent = false;
try {
const launchLocation = pendingLaunch
? {
cwd: pendingLaunch.cwd,
worktreePath: pendingLaunch.worktreePath,
}
: resolveTerminalOpenLocation({
terminalLocation: terminalAttachLaunchHintsRef.current.terminalSummary,
activeSessionLocation: terminalAttachLaunchHintsRef.current.activeKnownSummary,
workspaceRoot: selectedThreadProject.workspaceRoot,
threadShellWorktreePath: selectedThread.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
});
terminalDebugLog("attach:start", {
terminalId,
threadId: selectedThread.id,
cols: lastGridSize.cols,
rows: lastGridSize.rows,
cwd: launchLocation.cwd,
worktreePath: launchLocation.worktreePath,
});
return attachTerminalSession({
environmentId: selectedThread.environmentId,
client,
terminal: {
threadId: selectedThread.id,
terminalId,
cwd: launchLocation.cwd,
worktreePath: launchLocation.worktreePath,
cols: lastGridSize.cols,
rows: lastGridSize.rows,
env: pendingLaunch?.env,
...(pendingLaunch ? { restartIfNotRunning: true } : {}),
},
onEvent: logAttachStreamEvent,
onSnapshot: () => {
if (!pendingLaunch?.initialInput || initialInputSent) {
return;
}
initialInputSent = true;
void client.terminal.write({
threadId: selectedThread.id,
terminalId,
data: pendingLaunch.initialInput,
});
},
});
} catch (error) {
terminalDebugLog("attach:error", {
message: error instanceof Error ? error.message : String(error),
});
if (pendingLaunch) {
stagePendingTerminalLaunch({
target: pendingLaunchTarget,
launch: pendingLaunch,
});
}
throw error;
}
}, [
lastGridSize.cols,
lastGridSize.rows,
logAttachStreamEvent,
selectedThreadDetail?.worktreePath,
selectedThread,
selectedThreadProject?.workspaceRoot,
terminalId,
]);
const attachTerminalRef = useRef(attachTerminal);
attachTerminalRef.current = attachTerminal;
const selectedThreadRef = useRef(selectedThread);
selectedThreadRef.current = selectedThread;
const selectedThreadProjectBootstrapRef = useRef(selectedThreadProject);
selectedThreadProjectBootstrapRef.current = selectedThreadProject;
const runningSessionRef = useRef(runningSession);
runningSessionRef.current = runningSession;
const terminalBootstrapRef = useRef({
status: terminal.status,
bufferLen: terminal.buffer.length,
});
terminalBootstrapRef.current = {
status: terminal.status,
bufferLen: terminal.buffer.length,
};
setPendingLaunchEntry({
key: launchTargetKey,
launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
});
}, [launchTarget, launchTargetKey, pendingLaunchEntry.key]);
useEffect(() => {
if (initialAttachGridEntry.key === launchTargetKey) {
return;
}
setInitialAttachGridEntry({
key: launchTargetKey,
size: cachedRouteGridSize ?? {
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
},
});
}, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);
useEffect(() => {
if (
initialLaunchLocationEntry.key === launchTargetKey &&
initialLaunchLocationEntry.location !== null
) {
return;
}
if (initialLaunchLocationEntry.key === launchTargetKey && launchLocationCandidate === null) {
return;
}
setInitialLaunchLocationEntry({
key: launchTargetKey,
location: launchLocationCandidate,
});
}, [
initialLaunchLocationEntry.key,
initialLaunchLocationEntry.location,
launchLocationCandidate,
launchTargetKey,
]);
useEffect(() => {
if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
return;
}
router.replace(buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId));
}, [router, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
useEffect(() => {
const initialInput = pendingLaunch?.initialInput;
if (
!initialInput ||
!selectedThread ||
terminal.version === 0 ||
sentInitialInputKeyRef.current === launchTargetKey
) {
return;
}
sentInitialInputKeyRef.current = launchTargetKey;
void writeTerminal({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
terminalId,
data: initialInput,
},
});
}, [
launchTargetKey,
pendingLaunch?.initialInput,
selectedThread,
terminal.version,
terminalId,
writeTerminal,
]);
useEffect(() => {
hasOpenedRef.current = false;
attachStreamLogCountRef.current = 0;
firstNonEmptyBufferLoggedRef.current = false;
sentInitialInputKeyRef.current = null;
}, [terminalKey]);
const clearBufferReplayTimer = useCallback(() => {
@@ -638,99 +672,22 @@ export function ThreadTerminalRouteScreen() {
});
}, [fontSize, hasResolvedFontPreference]);
// Subscribes `terminal.attach` once per route+terminal until thread/env/attach args change.
// Use refs for `attachTerminal` / `selectedThread` / `runningSession`: their identities change when
// unrelated store updates (e.g. terminal buffer) re-render the parent, which was firing cleanup
// → detach immediately after the first snapshot.
useEffect(() => {
if (!hasResolvedFontPreference || !hasMeasuredSurface) {
return;
}
const thread = selectedThreadRef.current;
const project = selectedThreadProjectBootstrapRef.current;
const running = runningSessionRef.current;
const termSnap = terminalBootstrapRef.current;
const bootstrapAction = resolveTerminalRouteBootstrap({
hasThread: thread !== null,
hasWorkspaceRoot: Boolean(project?.workspaceRoot),
hasOpened: hasOpenedRef.current,
requestedTerminalId,
currentTerminalId: terminalId,
runningTerminalId: running?.target.terminalId ?? null,
currentTerminalStatus: termSnap.status,
// Metadata summary (cwd/status) is not scrollback. Only `terminal.attach` fills `buffer`;
// treating summary as "hydrated" skipped attach while status was running → empty surface.
hasCurrentTerminalHydration: termSnap.bufferLen > 0,
});
if (bootstrapAction.kind !== "idle") {
terminalDebugLog("bootstrap:action", {
kind: bootstrapAction.kind,
hasOpenedBefore: hasOpenedRef.current,
hasHydration: termSnap.bufferLen > 0,
terminalStatus: termSnap.status,
bufLen: termSnap.bufferLen,
});
}
if (bootstrapAction.kind === "idle" || !thread) {
return;
}
if (bootstrapAction.kind === "redirect") {
router.replace(buildThreadTerminalNavigation(thread, bootstrapAction.terminalId));
return;
}
hasOpenedRef.current = true;
try {
const detach = attachTerminalRef.current();
terminalDebugLog("bootstrap:subscribe", { hasDetach: Boolean(detach) });
if (!detach) {
hasOpenedRef.current = false;
return;
}
return () => {
detach();
hasOpenedRef.current = false;
terminalDebugLog("bootstrap:unsubscribe");
};
} catch (error) {
hasOpenedRef.current = false;
terminalDebugLog("bootstrap:attach-threw", {
message: error instanceof Error ? error.message : String(error),
});
return;
}
}, [
hasMeasuredSurface,
hasResolvedFontPreference,
requestedTerminalId,
router,
selectedThread?.environmentId,
selectedThread?.id,
selectedThreadProject?.workspaceRoot,
terminalId,
]);
const writeInput = useCallback(
(data: string) => {
if (!selectedThread || !isRunning) {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
void client.terminal.write({
threadId: selectedThread.id,
terminalId,
data,
void writeTerminal({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
terminalId,
data,
},
});
},
[isRunning, selectedThread, terminalId],
[isRunning, selectedThread, terminalId, writeTerminal],
);
const handleInput = useCallback(
@@ -782,16 +739,14 @@ export function ThreadTerminalRouteScreen() {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
void client.terminal.resize({
threadId: selectedThread.id,
terminalId,
cols: size.cols,
rows: size.rows,
void resizeTerminal({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
terminalId,
cols: size.cols,
rows: size.rows,
},
});
},
[
@@ -802,6 +757,7 @@ export function ThreadTerminalRouteScreen() {
readyBufferReplayKey,
routeEnvironmentId,
routeThreadId,
resizeTerminal,
scheduleBufferReplayReady,
selectedThread,
terminalId,
@@ -855,17 +811,15 @@ export function ThreadTerminalRouteScreen() {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
setPendingModifierState({ terminalId, value: null });
void client.terminal.clear({
threadId: selectedThread.id,
terminalId,
void clearTerminal({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
terminalId,
},
});
}, [selectedThread, terminalId]);
}, [clearTerminal, selectedThread, terminalId]);
const handleToolbarActionPress = useCallback(
(action: TerminalToolbarAction) => {
@@ -905,9 +859,14 @@ export function ThreadTerminalRouteScreen() {
const handleShowKeyboard = useCallback(() => {
setKeyboardFocusRequest((current) => current + 1);
}, []);
const handleRetryEnvironment = useCallback(() => {
if (routeEnvironmentId !== null) {
void retryEnvironment(routeEnvironmentId);
}
}, [retryEnvironment, routeEnvironmentId]);
if (!selectedThread) {
if (isLoadingSavedConnection) {
if (workspaceState.isLoadingConnections) {
return <LoadingScreen message="Opening terminal…" />;
}
@@ -932,6 +891,10 @@ export function ThreadTerminalRouteScreen() {
);
}
if (!environment.isReady && environment.presentation === null) {
return <LoadingScreen message="Opening terminal…" />;
}
return (
<>
<Stack.Screen
@@ -980,152 +943,178 @@ export function ThreadTerminalRouteScreen() {
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground>
<Stack.Toolbar.Label>
{getTerminalStatusLabel({
status: terminal.status,
hasRunningSubprocess: terminal.hasRunningSubprocess,
})}
</Stack.Toolbar.Label>
<Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
<Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
{isEnvironmentReady ? (
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground>
<Stack.Toolbar.Label>
{getTerminalStatusLabel({
status: terminal.status,
hasRunningSubprocess: terminal.hasRunningSubprocess,
})}
</Stack.Toolbar.Label>
<Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
<Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
discoverabilityLabel="Decrease terminal text size"
onPress={handleDecreaseFontSize}
>
<Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
discoverabilityLabel="Increase terminal text size"
onPress={handleIncreaseFontSize}
>
<Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
{terminalMenuSessions.map((session) => (
<Stack.Toolbar.MenuAction
key={session.terminalId}
icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
onPress={() => handleSelectTerminal(session.terminalId)}
subtitle={[
getTerminalStatusLabel({ status: session.status }),
basename(session.cwd),
]
.filter(Boolean)
.join(" · ")}
>
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
<Stack.Toolbar.MenuAction
disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
discoverabilityLabel="Decrease terminal text size"
onPress={handleDecreaseFontSize}
icon="plus"
onPress={handleOpenNewTerminal}
subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
>
<Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
discoverabilityLabel="Increase terminal text size"
onPress={handleIncreaseFontSize}
>
<Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
{terminalMenuSessions.map((session) => (
<Stack.Toolbar.MenuAction
key={session.terminalId}
icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
onPress={() => handleSelectTerminal(session.terminalId)}
subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
.filter(Boolean)
.join(" · ")}
>
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
<Stack.Toolbar.MenuAction
icon="plus"
onPress={handleOpenNewTerminal}
subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
>
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
</Stack.Toolbar>
) : null}
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
<View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
<TerminalSurface
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
isRunning={isRunning}
keyboardFocusRequest={keyboardFocusRequest}
onInput={handleInput}
onResize={handleResize}
style={{ flex: 1 }}
terminalKey={terminalKey}
{!isEnvironmentReady ? (
<EnvironmentConnectionNotice
environmentLabel={
environment.presentation?.entry.target.label ??
selectedEnvironmentConnection?.environmentLabel ??
"Environment"
}
connection={
environment.presentation?.connection ?? {
phase: "available",
error: null,
traceId: null,
}
}
resourceName="terminal"
onRetry={handleRetryEnvironment}
/>
</View>
{isAccessoryVisible ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
style={{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
}}
>
<ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
<ComposerToolbarScroller
contentPaddingRight={2}
fadeOpaque={terminalTheme.background}
fadeTransparent={`${terminalTheme.background}00`}
>
{terminalToolbarActions.map((action) => {
const active =
action.kind === "modifier" && pendingModifier === action.modifier;
return (
<ComposerToolbarButton
key={action.key}
active={active}
label={action.label}
maxWidth={120}
minWidth={action.label.length > 1 ? 56 : 44}
onPress={() => handleToolbarActionPress(action)}
showChevron={false}
textTransform={
action.kind === "modifier" || action.kind === "clear"
? "uppercase"
: "none"
}
/>
);
})}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel="Dismiss keyboard"
icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
onPress={handleDismissKeyboard}
showChevron={false}
/>
</ComposerToolbarRow>
</View>
</KeyboardStickyView>
) : !keyboardState.isVisible ? (
<Pressable
accessibilityLabel="Show keyboard"
accessibilityRole="button"
onPress={handleShowKeyboard}
style={({ pressed }) => ({
bottom: 16,
borderRadius: 28,
opacity: pressed ? 0.72 : 1,
position: "absolute",
right: 16,
})}
>
<GlassSurface
chrome="none"
glassEffectStyle="regular"
tintColor="transparent"
style={{
alignItems: "center",
borderRadius: 24,
height: 48,
justifyContent: "center",
width: 48,
}}
pointerEvents="none"
>
<SymbolView
name={{ ios: "keyboard", android: "keyboard" }}
size={20}
tintColor={terminalTheme.foreground}
type="monochrome"
) : (
<>
<View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
<TerminalSurface
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
isRunning={isRunning}
keyboardFocusRequest={keyboardFocusRequest}
onInput={handleInput}
onResize={handleResize}
style={{ flex: 1 }}
terminalKey={terminalKey}
/>
</GlassSurface>
</Pressable>
) : null}
</View>
{isAccessoryVisible ? (
<KeyboardStickyView
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
style={{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
}}
>
<ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
<ComposerToolbarScroller
contentPaddingRight={2}
fadeOpaque={terminalTheme.background}
fadeTransparent={`${terminalTheme.background}00`}
>
{terminalToolbarActions.map((action) => {
const active =
action.kind === "modifier" && pendingModifier === action.modifier;
return (
<ComposerToolbarButton
key={action.key}
active={active}
label={action.label}
maxWidth={120}
minWidth={action.label.length > 1 ? 56 : 44}
onPress={() => handleToolbarActionPress(action)}
showChevron={false}
textTransform={
action.kind === "modifier" || action.kind === "clear"
? "uppercase"
: "none"
}
/>
);
})}
</ComposerToolbarScroller>
<ComposerToolbarButton
accessibilityLabel="Dismiss keyboard"
icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
onPress={handleDismissKeyboard}
showChevron={false}
/>
</ComposerToolbarRow>
</View>
</KeyboardStickyView>
) : !keyboardState.isVisible ? (
<Pressable
accessibilityLabel="Show keyboard"
accessibilityRole="button"
onPress={handleShowKeyboard}
style={({ pressed }) => ({
bottom: 16,
borderRadius: 28,
opacity: pressed ? 0.72 : 1,
position: "absolute",
right: 16,
})}
>
<GlassSurface
chrome="none"
glassEffectStyle="regular"
tintColor="transparent"
style={{
alignItems: "center",
borderRadius: 24,
height: 48,
justifyContent: "center",
width: 48,
}}
pointerEvents="none"
>
<SymbolView
name={{ ios: "keyboard", android: "keyboard" }}
size={20}
tintColor={terminalTheme.foreground}
type="monochrome"
/>
</GlassSurface>
</Pressable>
) : null}
</>
)}
</View>
</>
);
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
@@ -1,4 +1,4 @@
import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import { DEFAULT_TERMINAL_ID, type ProjectScript } from "@t3tools/contracts";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
import * as Arr from "effect/Array";
@@ -0,0 +1,40 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
buildThreadTerminalAttachInput,
threadTerminalSubscriptionKey,
type ThreadTerminalSubscriptionIdentity,
} from "./threadTerminalPanelModel";
const identity: ThreadTerminalSubscriptionIdentity = {
environmentId: EnvironmentId.make("env-1"),
threadId: ThreadId.make("thread-1"),
terminalId: "default",
cwd: "/repo",
worktreePath: "/repo",
};
describe("threadTerminalSubscriptionKey", () => {
it("does not include mutable terminal dimensions", () => {
const initialAttach = buildThreadTerminalAttachInput(identity, { cols: 80, rows: 24 });
const resizedAttach = buildThreadTerminalAttachInput(identity, { cols: 132, rows: 40 });
expect(initialAttach).not.toEqual(resizedAttach);
expect(threadTerminalSubscriptionKey({ ...identity, ...initialAttach })).toBe(
threadTerminalSubscriptionKey({ ...identity, ...resizedAttach }),
);
});
it.each([
["environment", { environmentId: EnvironmentId.make("env-2") }],
["thread", { threadId: ThreadId.make("thread-2") }],
["terminal", { terminalId: "term-2" }],
["cwd", { cwd: "/repo/packages/app" }],
["worktree", { worktreePath: "/repo/worktrees/feature" }],
])("changes when the %s identity changes", (_label, update) => {
expect(threadTerminalSubscriptionKey({ ...identity, ...update })).not.toBe(
threadTerminalSubscriptionKey(identity),
);
});
});
@@ -0,0 +1,40 @@
import type { EnvironmentId, TerminalAttachInput } from "@t3tools/contracts";
export interface ThreadTerminalSubscriptionIdentity {
readonly environmentId: EnvironmentId;
readonly threadId: TerminalAttachInput["threadId"];
readonly terminalId: TerminalAttachInput["terminalId"];
readonly cwd: string;
readonly worktreePath: string | null;
}
export interface TerminalGridSize {
readonly cols: number;
readonly rows: number;
}
export function threadTerminalSubscriptionKey(
identity: ThreadTerminalSubscriptionIdentity,
): string {
return JSON.stringify([
identity.environmentId,
identity.threadId,
identity.terminalId,
identity.cwd,
identity.worktreePath,
]);
}
export function buildThreadTerminalAttachInput(
identity: ThreadTerminalSubscriptionIdentity,
gridSize: TerminalGridSize,
): TerminalAttachInput {
return {
threadId: identity.threadId,
terminalId: identity.terminalId,
cwd: identity.cwd,
worktreePath: identity.worktreePath,
cols: gridSize.cols,
rows: gridSize.rows,
};
}
@@ -1,11 +1,15 @@
import { Stack, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { InteractionManager, View, useColorScheme } from "react-native";
import { Alert, InteractionManager, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
import { EnvironmentId } from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
@@ -19,27 +23,16 @@ import { ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { buildThreadRoutePath } from "../../lib/routes";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { useProjects } from "../../state/entities";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useProjectActions } from "./use-project-actions";
function withModelSelectionOption(
selection: ModelSelection,
id: string,
value: string | boolean | undefined,
): ModelSelection {
const options = (selection.options ?? []).filter((option) => option.id !== id);
return {
...selection,
options: value === undefined ? options : [...options, { id, value }],
};
}
function formatTitleCase(value: string): string {
return value.length === 0 ? value : `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
}
import { useCreateProjectThread } from "./use-project-actions";
function formatWorkspaceLabel(input: {
readonly workspaceMode: string;
@@ -59,8 +52,8 @@ export function NewTaskDraftScreen(props: {
readonly projectId?: string;
};
}) {
const { projects } = useRemoteCatalog();
const { onCreateThreadWithOptions } = useProjectActions();
const projects = useProjects();
const createProjectThread = useCreateProjectThread();
const flow = useNewTaskFlow();
const router = useRouter();
const insets = useSafeAreaInsets();
@@ -169,39 +162,18 @@ export function NewTaskDraftScreen(props: {
})),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
capabilities: flow.selectedModelOption?.capabilities,
selections: flow.selectedModel?.options,
}),
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
);
const optionsMenuActions = useMemo(
() => [
{
id: "options-effort",
title: "Effort",
subtitle: `${flow.effort.charAt(0).toUpperCase()}${flow.effort.slice(1)}`,
subactions: CLAUDE_AGENT_EFFORT_OPTIONS.map((level) => ({
id: `options:effort:${level}`,
title: `${level}${level === "high" ? " (default)" : ""}`,
state: flow.effort === level ? ("on" as const) : undefined,
})),
},
{
id: "options-fast-mode",
title: "Fast Mode",
subtitle: flow.fastMode ? "On" : "Off",
subactions: ([false, true] as const).map((value) => ({
id: `options:fast-mode:${value ? "on" : "off"}`,
title: value ? "On" : "Off",
state: flow.fastMode === value ? ("on" as const) : undefined,
})),
},
{
id: "options-context-window",
title: "Context Window",
subtitle: flow.contextWindow,
subactions: (["200k", "1M"] as const).map((value) => ({
id: `options:context-window:${value}`,
title: `${value}${value === "1M" ? " (default)" : ""}`,
state: flow.contextWindow === value ? ("on" as const) : undefined,
})),
},
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
@@ -241,7 +213,7 @@ export function NewTaskDraftScreen(props: {
}),
},
],
[flow.contextWindow, flow.effort, flow.fastMode, flow.interactionMode, flow.runtimeMode],
[flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
);
const workspaceMenuActions = useMemo(() => {
@@ -302,14 +274,10 @@ export function NewTaskDraftScreen(props: {
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const configurationLabel = useMemo(() => {
const parts = [
formatTitleCase(flow.effort),
flow.fastMode ? "Fast" : null,
flow.contextWindow !== "1M" ? flow.contextWindow : null,
].filter((part): part is string => Boolean(part));
return parts.length > 0 ? parts.join(" · ") : "Configuration";
}, [flow.contextWindow, flow.effort, flow.fastMode]);
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
@@ -338,16 +306,9 @@ export function NewTaskDraftScreen(props: {
}
function handleOptionsMenuAction(event: string) {
if (event.startsWith("options:effort:")) {
flow.setEffort(event.slice("options:effort:".length) as typeof flow.effort);
return;
}
if (event.startsWith("options:fast-mode:")) {
flow.setFastMode(event.endsWith(":on"));
return;
}
if (event.startsWith("options:context-window:")) {
flow.setContextWindow(event.slice("options:context-window:".length));
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
flow.setSelectedModelOptions(providerOptions);
return;
}
if (event.startsWith("options:runtime:")) {
@@ -415,42 +376,33 @@ export function NewTaskDraftScreen(props: {
}
flow.setSubmitting(true);
try {
const modelWithOptions: ModelSelection =
flow.selectedModelOption?.providerDriver === "claudeAgent"
? withModelSelectionOption(
withModelSelectionOption(
withModelSelectionOption(flow.selectedModel, "effort", flow.effort),
"fastMode",
flow.fastMode || undefined,
),
"contextWindow",
flow.contextWindow,
)
: flow.selectedModelOption?.providerDriver === "codex"
? withModelSelectionOption(flow.selectedModel, "fastMode", flow.fastMode || undefined)
: flow.selectedModel;
const result = await createProjectThread({
project: flow.selectedProject,
modelSelection: flow.selectedModel,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
});
flow.setSubmitting(false);
const createdThread = await onCreateThreadWithOptions({
project: flow.selectedProject,
modelSelection: modelWithOptions,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
});
if (createdThread) {
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(createdThread));
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
Alert.alert(
"Could not start task",
error instanceof Error ? error.message : "The task could not be started.",
);
}
} finally {
flow.setSubmitting(false);
return;
}
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(result.value));
}
if (!selectedProject) {
@@ -10,7 +10,7 @@ export interface PendingApprovalCardProps {
readonly onRespond: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
) => Promise<unknown>;
}
export function PendingApprovalCard(props: PendingApprovalCardProps) {
@@ -20,7 +20,7 @@ export interface PendingUserInputCardProps {
questionId: string,
customAnswer: string,
) => void;
readonly onSubmit: () => Promise<void>;
readonly onSubmit: () => Promise<unknown>;
}
export function PendingUserInputCard(props: PendingUserInputCardProps) {
@@ -2,7 +2,7 @@ import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass
import type {
EnvironmentId,
ModelSelection,
OrchestrationThread,
OrchestrationThreadShell,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
@@ -15,7 +15,14 @@ import {
} from "@t3tools/shared/composerTrigger";
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import { Image, Pressable, useColorScheme, View, type ViewStyle } from "react-native";
import {
ActivityIndicator,
Image,
Pressable,
useColorScheme,
View,
type ViewStyle,
} from "react-native";
import ImageViewing from "react-native-image-viewing";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -43,11 +50,12 @@ import {
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
/**
@@ -68,7 +76,9 @@ export interface ThreadComposerProps {
readonly placeholder: string;
readonly bottomInset?: number;
readonly connectionState: RemoteClientConnectionState;
readonly selectedThread: OrchestrationThread;
readonly connectionError: string | null;
readonly environmentLabel: string | null;
readonly selectedThread: OrchestrationThreadShell;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
@@ -79,11 +89,12 @@ export interface ThreadComposerProps {
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => Promise<void>;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => Promise<void>;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<void>;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onReconnectEnvironment: () => void;
readonly onExpandedChange?: (expanded: boolean) => void;
}
@@ -126,21 +137,67 @@ function ComposerSurface(props: {
);
}
function withModelSelectionOption(
selection: ModelSelection,
id: string,
value: string | boolean | undefined,
): ModelSelection {
const options = (selection.options ?? []).filter((option) => option.id !== id);
return {
...selection,
options: value === undefined ? options : [...options, { id, value }],
};
function composerConnectionStatus(input: {
readonly connectionError: string | null;
readonly connectionState: RemoteClientConnectionState;
readonly environmentLabel: string | null;
}): { readonly kind: "unavailable" | "reconnecting"; readonly label: string } | null {
const environmentLabel = input.environmentLabel ?? "Environment";
switch (input.connectionState) {
case "connecting":
case "reconnecting":
return {
kind: "reconnecting",
label:
input.connectionError === null
? `Reconnecting to ${environmentLabel}...`
: `Failed to connect. Retrying ${environmentLabel}...`,
};
case "offline":
return { kind: "unavailable", label: "You are offline" };
case "error":
return {
kind: "unavailable",
label: input.connectionError
? `Failed to connect to ${environmentLabel}: ${input.connectionError}`
: `Failed to connect to ${environmentLabel}`,
};
case "available":
return { kind: "unavailable", label: `${environmentLabel} is not connected` };
case "connected":
return null;
}
}
function formatTitleCase(value: string): string {
return value.length === 0 ? value : `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
}
const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: {
readonly onPress: () => void;
readonly status: { readonly kind: "unavailable" | "reconnecting"; readonly label: string };
}) {
const isReconnecting = props.status.kind === "reconnecting";
return (
<View className="items-center pb-2">
<Pressable
accessibilityRole="button"
onPress={props.onPress}
className="max-w-full flex-row items-center gap-2 rounded-full bg-white/90 px-3 py-2 shadow-sm active:opacity-70 dark:bg-neutral-900/90"
>
{isReconnecting ? (
<ActivityIndicator size="small" color="#8e8e93" />
) : (
<View className="h-2 w-2 rounded-full bg-red-500" />
)}
<Text
className="max-w-[260px] text-[13px] font-t3-bold leading-[17px] text-foreground"
numberOfLines={1}
>
{props.status.label}
</Text>
</Pressable>
</View>
);
});
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
const isDarkMode = useColorScheme() === "dark";
@@ -154,7 +211,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const isExpanded = isFocused;
const canSend = props.connectionState === "ready" && hasContent;
const canSend = hasContent;
const onPressImage = useCallback(
(uri: string) => {
@@ -182,13 +239,20 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}, [onExpandedChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting" ||
props.queueCount > 0;
props.selectedThread.session?.status === "starting";
const sendLabel = props.activeThreadBusy || props.queueCount > 0 ? "Queue" : "Send";
const sendLabel =
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
? "Queue"
: "Send";
const currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
const connectionStatus = composerConnectionStatus({
connectionError: props.connectionError,
connectionState: props.connectionState,
environmentLabel: props.environmentLabel,
});
const toolbarFadeOpaque = isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)";
const toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)";
const selectedProviderStatus = useMemo(() => {
@@ -200,18 +264,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
);
}, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
// Extract current model options (effort, fastMode, contextWindow)
const selectedProviderDriver = selectedProviderStatus?.driver ?? null;
const currentEffort =
selectedProviderDriver === "claudeAgent"
? (getModelSelectionStringOptionValue(currentModelSelection, "effort") ?? "high")
: "high";
const currentFastMode =
getModelSelectionBooleanOptionValue(currentModelSelection, "fastMode") ?? false;
const currentContextWindow =
selectedProviderDriver === "claudeAgent"
? (getModelSelectionStringOptionValue(currentModelSelection, "contextWindow") ?? "1M")
: "1M";
// ── Trigger detection ────────────────────────────────────
const [composerSelection, setComposerSelection] = useState(() => ({
start: props.draftMessage.length,
@@ -394,8 +446,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
const handleSend = useCallback(() => {
onSendMessage();
inputRef.current?.blur();
void onSendMessage().then(() => {
inputRef.current?.blur();
});
}, [onSendMessage]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
@@ -413,7 +466,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
);
setComposerSelection({ start: result.cursor, end: result.cursor });
onChangeDraftMessage(result.text);
void onUpdateInteractionMode(item.command);
onUpdateInteractionMode(item.command);
return;
}
@@ -452,14 +505,18 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
option.selection.instanceId === currentModelSelection.instanceId &&
option.selection.model === currentModelSelection.model,
) ?? null;
const configurationLabel = useMemo(() => {
const parts = [
formatTitleCase(currentEffort),
currentFastMode ? "Fast" : null,
currentContextWindow !== "1M" ? currentContextWindow : null,
].filter((part): part is string => Boolean(part));
return parts.length > 0 ? parts.join(" · ") : "Configuration";
}, [currentContextWindow, currentEffort, currentFastMode]);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
capabilities: currentModelOption?.capabilities,
selections: currentModelSelection.options,
}),
[currentModelOption?.capabilities, currentModelSelection.options],
);
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() =>
providerGroups.map((group) => ({
@@ -486,36 +543,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
// ── Options menu ─────────────────────────────────────────
const optionsMenuActions = useMemo(
() => [
{
id: "options-effort",
title: "Effort",
subtitle: `${currentEffort.charAt(0).toUpperCase()}${currentEffort.slice(1)}`,
subactions: CLAUDE_AGENT_EFFORT_OPTIONS.map((level) => ({
id: `options:effort:${level}`,
title: `${level}${level === "high" ? " (default)" : ""}`,
state: currentEffort === level ? ("on" as const) : undefined,
})),
},
{
id: "options-fast-mode",
title: "Fast Mode",
subtitle: currentFastMode ? "On" : "Off",
subactions: ([false, true] as const).map((value) => ({
id: `options:fast-mode:${value ? "on" : "off"}`,
title: value ? "On" : "Off",
state: currentFastMode === value ? ("on" as const) : undefined,
})),
},
{
id: "options-context-window",
title: "Context Window",
subtitle: currentContextWindow,
subactions: (["200k", "1M"] as const).map((value) => ({
id: `options:context-window:${value}`,
title: `${value}${value === "1M" ? " (default)" : ""}`,
state: currentContextWindow === value ? ("on" as const) : undefined,
})),
},
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
@@ -555,13 +583,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}),
},
],
[
currentEffort,
currentFastMode,
currentContextWindow,
currentRuntimeMode,
currentInteractionMode,
],
[currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
);
// ── Menu handlers ────────────────────────────────────────
@@ -572,51 +594,27 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
void props.onUpdateModelSelection(option.selection);
props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
if (event.startsWith("options:effort:")) {
const effort = event.slice("options:effort:".length);
const updated: ModelSelection =
selectedProviderDriver === "claudeAgent"
? withModelSelectionOption(
currentModelSelection,
"effort",
effort as typeof currentEffort,
)
: currentModelSelection;
void props.onUpdateModelSelection(updated);
return;
}
if (event.startsWith("options:fast-mode:")) {
const fastMode = event.endsWith(":on");
const nextFast = fastMode || undefined;
if (selectedProviderDriver === "opencode") {
return;
}
const updated = withModelSelectionOption(currentModelSelection, "fastMode", nextFast);
void props.onUpdateModelSelection(updated);
return;
}
if (event.startsWith("options:context-window:")) {
const contextWindow = event.slice("options:context-window:".length);
const updated: ModelSelection =
selectedProviderDriver === "claudeAgent"
? withModelSelectionOption(currentModelSelection, "contextWindow", contextWindow)
: currentModelSelection;
void props.onUpdateModelSelection(updated);
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
props.onUpdateModelSelection({
...currentModelSelection,
options: providerOptions,
});
return;
}
if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
void props.onUpdateRuntimeMode(runtimeMode);
props.onUpdateRuntimeMode(runtimeMode);
return;
}
if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
void props.onUpdateInteractionMode(interactionMode);
props.onUpdateInteractionMode(interactionMode);
}
}
@@ -652,6 +650,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
</View>
) : null}
{connectionStatus ? (
<ComposerConnectionStatusPill
status={connectionStatus}
onPress={props.onReconnectEnvironment}
/>
) : null}
<ComposerSurface
isDarkMode={isDarkMode}
style={
@@ -755,11 +760,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
{!isExpanded ? (
showStopAction ? (
<ControlPill
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
/>
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
) : (
<ControlPill
icon="arrow.up"
@@ -809,7 +810,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
<ComposerToolbarButton
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
onPress={props.onStopThread}
showChevron={false}
/>
) : null}
@@ -1,8 +1,9 @@
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type {
ApprovalRequestId,
EnvironmentId,
ModelSelection,
OrchestrationThread,
OrchestrationThreadShell,
ProviderApprovalDecision,
ProviderInteractionMode,
RuntimeMode,
@@ -23,7 +24,7 @@ import { AppText as Text } from "../../components/AppText";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import type { LayoutVariant } from "../../lib/layout";
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
import type {
PendingApproval,
@@ -39,13 +40,14 @@ import {
ThreadComposer,
} from "./ThreadComposer";
import { ThreadFeed } from "./ThreadFeed";
import type { ThreadContentPresentation } from "./threadContentPresentation";
export interface ThreadDetailScreenProps {
readonly selectedThread: OrchestrationThread;
readonly selectedThread: OrchestrationThreadShell;
readonly contentPresentation: ThreadContentPresentation;
readonly screenTone: StatusTone;
readonly connectionError: string | null;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly environmentLabel: string | null;
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
readonly activeWorkStartedAt: string | null;
readonly activePendingApproval: PendingApproval | null;
@@ -56,30 +58,29 @@ export interface ThreadDetailScreenProps {
readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle";
readonly connectionStateLabel: EnvironmentConnectionPhase;
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: MobileLayoutVariant;
readonly layoutVariant?: LayoutVariant;
readonly onOpenDrawer: () => void;
readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => Promise<void>;
readonly onSendMessage: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>;
readonly onUpdateThreadInteractionMode: (
interactionMode: ProviderInteractionMode,
) => Promise<void>;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<void>;
readonly onReconnectEnvironment: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onRespondToApproval: (
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
questionId: string,
@@ -90,7 +91,7 @@ export interface ThreadDetailScreenProps {
questionId: string,
customAnswer: string,
) => void;
readonly onSubmitUserInput: () => Promise<void>;
readonly onSubmitUserInput: () => Promise<unknown>;
readonly showContent?: boolean;
}
@@ -306,10 +307,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
>
<ThreadFeed
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
feed={props.selectedThreadFeed}
httpBaseUrl={props.httpBaseUrl}
bearerToken={props.bearerToken}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
contentTopInset={headerHeight}
@@ -363,6 +364,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
@@ -376,6 +379,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={props.onSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
+112 -65
View File
@@ -2,7 +2,7 @@ import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { ThreadId, TurnId } from "@t3tools/contracts";
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
@@ -12,6 +12,7 @@ import {
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import {
ActivityIndicator,
Image,
Linking,
type NativeScrollEvent,
@@ -37,7 +38,6 @@ import {
} from "../../native/SelectableMarkdownText";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { CopyTextButton } from "../../components/CopyTextButton";
import {
parseReviewCommentMessageSegments,
@@ -53,7 +53,7 @@ import {
} from "../review/nativeReviewDiffAdapter";
import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn";
import type { MobileLayoutVariant } from "../../lib/mobileLayout";
import type { LayoutVariant } from "../../lib/layout";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
import {
@@ -63,7 +63,8 @@ import {
} from "../../lib/threadActivity";
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
import { relativeTime } from "../../lib/time";
import { messageImageUrl } from "./threadPresentation";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { useAssetUrl } from "../../state/assets";
const THREAD_FEED_END_THRESHOLD = 80;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
@@ -80,19 +81,45 @@ function formatMessageTime(input: string): string {
}
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly contentPresentation: ThreadContentPresentation;
readonly agentLabel: string;
readonly latestTurn: ThreadFeedLatestTurn | null;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly layoutVariant?: MobileLayoutVariant;
readonly layoutVariant?: LayoutVariant;
readonly composerExpanded?: boolean;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
}
function MessageAttachmentImage(props: {
readonly environmentId: EnvironmentId;
readonly attachmentId: string;
readonly className: string;
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
}) {
const uri = useAssetUrl(props.environmentId, {
_tag: "attachment",
attachmentId: props.attachmentId,
});
if (uri === null) {
return (
<View className={`${props.className} items-center justify-center`}>
<ActivityIndicator />
</View>
);
}
return (
<TouchableOpacity activeOpacity={0.7} onPress={() => props.onPressImage(uri)}>
<Image source={{ uri }} className={props.className} resizeMode="cover" />
</TouchableOpacity>
);
}
function stripShellWrapper(value: string): string {
const trimmed = value.trim();
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
@@ -654,7 +681,7 @@ function useMarkdownStyles(): MarkdownStyleSets {
function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number },
props: Pick<ThreadFeedProps, "bearerToken" | "httpBaseUrl" | "skills"> & {
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
readonly expandedWorkRows: Record<string, boolean>;
@@ -733,26 +760,14 @@ function renderFeedEntry(
/>
) : null}
{attachments.map((attachment) => {
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
if (!uri) {
return null;
}
const headers = props.bearerToken
? { Authorization: `Bearer ${props.bearerToken}` }
: undefined;
return (
<TouchableOpacity
<MessageAttachmentImage
key={attachment.id}
activeOpacity={0.7}
onPress={() => props.onPressImage(uri, headers)}
>
<Image
source={{ uri, ...(headers ? { headers } : {}) }}
className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
resizeMode="cover"
/>
</TouchableOpacity>
environmentId={props.environmentId}
attachmentId={attachment.id}
className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
onPressImage={props.onPressImage}
/>
);
})}
</View>
@@ -801,27 +816,14 @@ function renderFeedEntry(
)
) : null}
{attachments.map((attachment) => {
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
if (!uri) {
return null;
}
const headers = props.bearerToken
? { Authorization: `Bearer ${props.bearerToken}` }
: undefined;
return (
<TouchableOpacity
<MessageAttachmentImage
key={attachment.id}
activeOpacity={0.7}
className="mt-1.5"
onPress={() => props.onPressImage(uri, headers)}
>
<Image
source={{ uri, ...(headers ? { headers } : {}) }}
className="aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
resizeMode="cover"
/>
</TouchableOpacity>
environmentId={props.environmentId}
attachmentId={attachment.id}
className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
onPressImage={props.onPressImage}
/>
);
})}
{showAssistantMeta ? (
@@ -1220,6 +1222,37 @@ function compactFileName(filePath: string): string {
return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
}
function ThreadFeedPlaceholder(props: {
readonly bottomInset: number;
readonly detail: string;
readonly horizontalPadding: number;
readonly loading?: boolean;
readonly title: string;
readonly topInset: number;
}) {
return (
<View
style={{
flex: 1,
flexGrow: 1,
alignItems: "center",
justifyContent: "center",
paddingTop: props.topInset,
paddingBottom: props.bottomInset,
paddingHorizontal: props.horizontalPadding + 24,
}}
>
<View className="max-w-[320px] items-center gap-2">
{props.loading ? <ActivityIndicator style={{ marginBottom: 6 }} /> : null}
<Text className="text-center font-t3-bold text-lg text-foreground">{props.title}</Text>
<Text className="text-center text-sm leading-5 text-foreground-secondary">
{props.detail}
</Text>
</View>
</View>
);
}
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -1446,9 +1479,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const renderItem = useCallback(
(info: { item: ThreadFeedEntry; index: number }) =>
renderFeedEntry(info, {
bearerToken: props.bearerToken,
environmentId: props.environmentId,
copiedRowId,
httpBaseUrl: props.httpBaseUrl,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
@@ -1481,30 +1513,45 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleTurnFold,
onToggleWorkGroup,
onToggleWorkRow,
props.bearerToken,
props.httpBaseUrl,
props.environmentId,
props.skills,
],
);
if (props.contentPresentation.kind === "loading") {
return (
<ThreadFeedPlaceholder
title="Loading conversation"
detail="Fetching the latest messages from this environment."
loading
topInset={topContentInset}
bottomInset={bottomContentInset}
horizontalPadding={horizontalPadding}
/>
);
}
if (props.contentPresentation.kind === "unavailable") {
return (
<ThreadFeedPlaceholder
title={props.contentPresentation.title}
detail={props.contentPresentation.detail}
topInset={topContentInset}
bottomInset={bottomContentInset}
horizontalPadding={horizontalPadding}
/>
);
}
if (props.feed.length === 0) {
return (
<ScrollView
style={{ flex: 1 }}
contentInsetAdjustmentBehavior="never"
contentInset={{ top: topContentInset, bottom: bottomContentInset }}
contentOffset={{ x: 0, y: -topContentInset }}
scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }}
contentContainerStyle={{
flexGrow: 1,
paddingHorizontal: horizontalPadding,
}}
>
<EmptyState
title="No conversation yet"
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
/>
</ScrollView>
<ThreadFeedPlaceholder
title="No conversation yet"
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
topInset={topContentInset}
bottomInset={bottomContentInset}
horizontalPadding={horizontalPadding}
/>
);
}
@@ -9,7 +9,7 @@ import {
type GitActionRequestInput,
requiresDefaultBranchConfirmation,
resolveQuickAction,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/state/vcs";
import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react";
@@ -1,6 +1,13 @@
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Modal, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
import {
type ColorValue,
Modal,
Pressable,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
@@ -15,21 +22,19 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill";
import { useProjects, useThreadShells } from "../../state/entities";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "./threadPresentation";
import {
EnvironmentScopedProjectShell,
EnvironmentScopedThreadShell,
} from "@t3tools/client-runtime";
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
const threadActivityOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
title: Order.String,
}),
(thread: EnvironmentScopedThreadShell) => ({
(thread: EnvironmentThreadShell) => ({
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
title: thread.title,
}),
@@ -37,11 +42,9 @@ const threadActivityOrder = Order.mapInput(
export function ThreadNavigationDrawer(props: {
readonly visible: boolean;
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onStartNewTask: () => void;
}) {
const insets = useSafeAreaInsets();
@@ -57,26 +60,6 @@ export function ThreadNavigationDrawer(props: {
const primaryForeground = useThemeColor("--color-primary-foreground");
const borderSubtleColor = useThemeColor("--color-border-subtle");
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects: props.projects, threads: props.threads }),
[props.projects, props.threads],
);
const groupedThreads = useMemo(
() =>
repositoryGroups.map((group) => {
const threads: EnvironmentScopedThreadShell[] = [];
for (const projectGroup of group.projects) {
threads.push(...projectGroup.threads);
}
return {
key: group.key,
title: group.projects[0]?.project.title ?? group.title,
threads: Arr.sort(threads, threadActivityOrder),
};
}),
[repositoryGroups],
);
useEffect(() => {
if (props.visible) {
setMounted(true);
@@ -186,76 +169,116 @@ export function ThreadNavigationDrawer(props: {
</Pressable>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 12 }}
contentContainerStyle={{
gap: 20,
paddingHorizontal: 14,
}}
>
{groupedThreads.map((group) => (
<View key={group.key} className="gap-3">
<Text
className="px-1 text-[15px] font-t3-bold text-foreground-muted"
style={{ letterSpacing: -0.2 }}
>
{group.title}
</Text>
<View className="overflow-hidden rounded-[22px] bg-card">
{group.threads.length === 0 ? (
<View className="px-4 py-4">
<Text className="text-[14px] font-medium text-foreground-tertiary">
No threads yet
</Text>
</View>
) : (
group.threads.map((thread, index) => {
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
const selected = props.selectedThreadKey === threadKey;
return (
<Pressable
key={threadKey}
onPress={() => {
props.onSelectThread(thread);
props.onClose();
}}
style={{
paddingHorizontal: 16,
paddingVertical: 15,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: borderSubtleColor,
backgroundColor: selected ? undefined : "transparent",
}}
className={selected ? "bg-subtle" : undefined}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text className="text-[16px] font-t3-bold" numberOfLines={1}>
{thread.title}
</Text>
<Text
className="text-[13px] font-medium text-foreground-muted"
numberOfLines={1}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
<StatusPill {...threadStatusTone(thread)} />
</View>
</Pressable>
);
})
)}
</View>
</View>
))}
</ScrollView>
<ThreadNavigationDrawerContent
bottomInset={Math.max(insets.bottom, 18)}
borderSubtleColor={borderSubtleColor}
selectedThreadKey={props.selectedThreadKey}
onClose={props.onClose}
onSelectThread={props.onSelectThread}
/>
</Animated.View>
</GestureDetector>
</View>
</Modal>
);
}
function ThreadNavigationDrawerContent(props: {
readonly bottomInset: number;
readonly borderSubtleColor: ColorValue;
readonly selectedThreadKey: string | null;
readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
}) {
const projects = useProjects();
const threads = useThreadShells();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const groupedThreads = useMemo(
() =>
repositoryGroups.map((group) => {
const threads: EnvironmentThreadShell[] = [];
for (const projectGroup of group.projects) {
threads.push(...projectGroup.threads);
}
return {
key: group.key,
title: group.projects[0]?.project.title ?? group.title,
threads: Arr.sort(threads, threadActivityOrder),
};
}),
[repositoryGroups],
);
return (
<ScrollView
showsVerticalScrollIndicator={false}
contentInset={{ bottom: props.bottomInset + 12 }}
contentContainerStyle={{
gap: 20,
paddingHorizontal: 14,
}}
>
{groupedThreads.map((group) => (
<View key={group.key} className="gap-3">
<Text
className="px-1 text-[15px] font-t3-bold text-foreground-muted"
style={{ letterSpacing: -0.2 }}
>
{group.title}
</Text>
<View className="overflow-hidden rounded-[22px] bg-card">
{group.threads.length === 0 ? (
<View className="px-4 py-4">
<Text className="text-[14px] font-medium text-foreground-tertiary">
No threads yet
</Text>
</View>
) : (
group.threads.map((thread, index) => {
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
const selected = props.selectedThreadKey === threadKey;
return (
<Pressable
key={threadKey}
onPress={() => {
props.onSelectThread(thread);
props.onClose();
}}
style={{
paddingHorizontal: 16,
paddingVertical: 15,
borderTopWidth: index === 0 ? 0 : 1,
borderTopColor: props.borderSubtleColor,
backgroundColor: selected ? undefined : "transparent",
}}
className={selected ? "bg-subtle" : undefined}
>
<View className="flex-row items-start justify-between gap-3">
<View className="flex-1 gap-1">
<Text className="text-[16px] font-t3-bold" numberOfLines={1}>
{thread.title}
</Text>
<Text
className="text-[13px] font-medium text-foreground-muted"
numberOfLines={1}
>
{relativeTime(thread.updatedAt ?? thread.createdAt)}
</Text>
</View>
<StatusPill {...threadStatusTone(thread)} />
</View>
</Pressable>
);
})
)}
</View>
</View>
))}
</ScrollView>
);
}
@@ -1,14 +1,20 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Arr from "effect/Array";
import * as Option from "effect/Option";
import { pipe } from "effect/Function";
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import {
EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useWorkspaceState } from "../../state/workspace";
import { useThemeColor } from "../../lib/useThemeColor";
import { useVcsStatus } from "../../state/use-vcs-status";
import { useEnvironmentQuery } from "../../state/query";
import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
import { vcsEnvironment } from "../../state/vcs";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
@@ -16,13 +22,13 @@ import { buildThreadRoutePath, buildThreadTerminalNavigation } from "../../lib/r
import { scopedThreadKey } from "../../lib/scopedEntities";
import { connectionTone } from "../connection/connectionTone";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import {
useRemoteConnections,
useRemoteConnectionStatus,
useRemoteEnvironmentState,
useRemoteEnvironmentRuntime,
} from "../../state/use-remote-environment-registry";
import { useKnownTerminalSessions } from "../../state/use-terminal-session";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
import { useThreadSelection } from "../../state/use-thread-selection";
import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
import {
@@ -38,12 +44,14 @@ import { terminalDebugLog } from "../terminal/terminalDebugLog";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { threadEnvironment } from "../../state/threads";
import { projectThreadContentPresentation } from "./threadContentPresentation";
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
@@ -58,22 +66,31 @@ function OpeningThreadLoadingScreen() {
}
export function ThreadRouteScreen() {
const { isLoadingSavedConnection, environmentStateById, pendingConnectionError } =
useRemoteEnvironmentState();
const { connectionState, connectionError: aggregateConnectionError } =
useRemoteConnectionStatus();
const { projects, threads } = useRemoteCatalog();
const { state: workspaceState } = useWorkspaceState();
const { connectionState } = useRemoteConnectionStatus();
const { onReconnectEnvironment } = useRemoteConnections();
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const selectedThreadDetailState = useSelectedThreadDetailState();
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
const { selectedThreadCwd } = useSelectedThreadWorktree();
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const commands = useSelectedThreadCommands({
refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
});
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread metadata update",
);
const setThreadRuntimeMode = useAtomCommand(
threadEnvironment.setRuntimeMode,
"thread runtime mode",
);
const setThreadInteractionMode = useAtomCommand(
threadEnvironment.setInteractionMode,
"thread interaction mode",
);
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const router = useRouter();
const params = useLocalSearchParams<{
environmentId?: string | string[];
@@ -83,12 +100,10 @@ export function ThreadRouteScreen() {
const environmentIdRaw = firstRouteParam(params.environmentId);
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
const threadId = firstRouteParam(params.threadId);
const routeEnvironmentRuntime = environmentId
? (environmentStateById[environmentId] ?? null)
: null;
const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? connectionState;
const routeConnectionError =
pendingConnectionError ?? routeEnvironmentRuntime?.connectionError ?? aggregateConnectionError;
const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
/* ─── Native header theming ──────────────────────────────────────── */
const iconColor = String(useThemeColor("--color-icon"));
@@ -96,10 +111,14 @@ export function ThreadRouteScreen() {
const secondaryFg = String(useThemeColor("--color-foreground-secondary"));
/* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const knownTerminalSessions = useKnownTerminalSessions({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
@@ -113,6 +132,12 @@ export function ThreadRouteScreen() {
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
);
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
const handleReconnectEnvironment = useCallback(() => {
if (!environmentId) {
return;
}
onReconnectEnvironment(environmentId);
}, [environmentId, onReconnectEnvironment]);
/* ─── Git action progress (for overlay banner) ──────────────────── */
const gitActionProgressTarget = useMemo(
@@ -131,6 +156,69 @@ export function ThreadRouteScreen() {
const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections");
}, [router]);
const handleUpdateThreadModelSelection = useCallback(
(modelSelection: ModelSelection) => {
if (!selectedThread) {
return;
}
return updateThreadMetadata({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
modelSelection,
},
});
},
[selectedThread, updateThreadMetadata],
);
const handleUpdateThreadRuntimeMode = useCallback(
(runtimeMode: RuntimeMode) => {
if (!selectedThread) {
return;
}
return setThreadRuntimeMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
runtimeMode,
},
});
},
[selectedThread, setThreadRuntimeMode],
);
const handleUpdateThreadInteractionMode = useCallback(
(interactionMode: ProviderInteractionMode) => {
if (!selectedThread) {
return;
}
return setThreadInteractionMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
interactionMode,
},
});
},
[selectedThread, setThreadInteractionMode],
);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
(selectedThread.session?.status !== "running" &&
selectedThread.session?.status !== "starting")
) {
return;
}
return interruptThreadTurn({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
...(selectedThread.session.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
: {}),
},
});
}, [interruptThreadTurn, selectedThread]);
const handleOpenTerminal = useCallback(
(nextTerminalId?: string | null) => {
@@ -238,7 +326,7 @@ export function ThreadRouteScreen() {
if (!selectedThread) {
const stillHydrating =
isLoadingSavedConnection ||
workspaceState.isLoadingConnections ||
routeConnectionState === "connecting" ||
routeConnectionState === "reconnecting";
@@ -265,19 +353,14 @@ export function ThreadRouteScreen() {
);
}
if (!selectedThreadDetail) {
return <OpeningThreadLoadingScreen />;
}
const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const serverConfig =
routeEnvironmentRuntime?.serverConfig ??
pipe(
Object.values(environmentStateById),
Arr.map((runtime) => runtime.serverConfig),
Arr.findFirst((value) => value !== null),
Option.getOrNull,
);
const contentPresentation = projectThreadContentPresentation({
hasDetail: selectedThreadDetail !== null,
detailError: Option.getOrNull(selectedThreadDetailState.error),
detailDeleted: selectedThreadDetailState.status === "deleted",
connectionState: routeConnectionState,
});
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
const headerSubtitle = [
selectedThreadProject?.title ?? null,
@@ -313,7 +396,7 @@ export function ThreadRouteScreen() {
letterSpacing: -0.4,
}}
>
{selectedThreadDetail.title}
{selectedThread.title}
</RNText>
<RNText
numberOfLines={1}
@@ -333,7 +416,7 @@ export function ThreadRouteScreen() {
/>
<ThreadGitControls
currentBranch={selectedThreadDetail.branch}
currentBranch={selectedThread.branch}
gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel}
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
@@ -350,11 +433,11 @@ export function ThreadRouteScreen() {
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThreadDetail}
selectedThread={selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null}
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={requests.activePendingApproval}
@@ -377,11 +460,12 @@ export function ThreadRouteScreen() {
onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage}
serverConfig={serverConfig}
onStopThread={commands.onStopThread}
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -390,8 +474,6 @@ export function ThreadRouteScreen() {
<ThreadNavigationDrawer
visible={drawerVisible}
projects={projects}
threads={threads}
selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => {
@@ -1,10 +0,0 @@
export const CLAUDE_AGENT_EFFORT_OPTIONS = [
"low",
"medium",
"high",
"xhigh",
"max",
"ultrathink",
] as const;
export type ClaudeAgentEffort = (typeof CLAUDE_AGENT_EFFORT_OPTIONS)[number];
@@ -6,11 +6,12 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useVcsStatus } from "../../../state/use-vcs-status";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
import { vcsEnvironment } from "../../../state/vcs";
import { SheetActionButton } from "./gitSheetComponents";
export function GitBranchesSheet() {
@@ -27,10 +28,14 @@ export function GitBranchesSheet() {
const foregroundColor = useThemeColor("--color-foreground");
const subtleStrongColor = useThemeColor("--color-subtle-strong");
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
const currentWorktreePath = selectedThreadWorktreePath;
@@ -5,11 +5,12 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
import { useVcsStatus } from "../../../state/use-vcs-status";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
import { vcsEnvironment } from "../../../state/vcs";
import { SheetActionButton } from "./gitSheetComponents";
export function GitCommitSheet() {
@@ -27,10 +28,14 @@ export function GitCommitSheet() {
const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground");
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const busy = gitState.gitOperationLabel !== null;
const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
@@ -1,4 +1,4 @@
import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime";
import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime/state/vcs";
import { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
import * as Arr from "effect/Array";
import * as Result from "effect/Result";
@@ -3,7 +3,7 @@ import {
buildMenuItems,
getGitActionDisabledReason,
requiresDefaultBranchConfirmation,
} from "@t3tools/client-runtime";
} from "@t3tools/client-runtime/state/vcs";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
@@ -14,11 +14,12 @@ import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText";
import { buildThreadReviewRoutePath } from "../../../lib/routes";
import { useVcsStatus } from "../../../state/use-vcs-status";
import { useEnvironmentQuery } from "../../../state/query";
import { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
import { vcsEnvironment } from "../../../state/vcs";
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
export function GitOverviewSheet() {
@@ -36,10 +37,14 @@ export function GitOverviewSheet() {
const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border");
const gitStatus = useVcsStatus({
environmentId: selectedThread?.environmentId ?? null,
cwd: selectedThreadCwd,
});
const gitStatus = useEnvironmentQuery(
selectedThread !== null && selectedThreadCwd !== null
? vcsEnvironment.status({
environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
const currentWorktreePath = selectedThreadWorktreePath;
@@ -1,9 +1,10 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import React, { useCallback, useMemo, useRef, useState } from "react";
import type {
EnvironmentId,
ModelSelection,
ProviderInteractionMode,
ProviderOptionSelection,
RuntimeMode,
ServerProviderSkill,
} from "@t3tools/contracts";
@@ -11,6 +12,7 @@ import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tool
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
@@ -23,21 +25,17 @@ import {
setComposerDraftText,
useComposerDraft,
} from "../../state/use-composer-drafts";
import { vcsRefManager, useVcsRefs } from "../../state/use-vcs-refs";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { useBranches } from "../../state/queries";
import {
setPendingConnectionError,
useRemoteEnvironmentState,
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
import { EnvironmentScopedProjectShell, type VcsRef } from "@t3tools/client-runtime";
import type { ClaudeAgentEffort } from "./claudeEffortOptions";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
function normalizeSelectedWorktreePath(
project: EnvironmentScopedProjectShell,
branch: VcsRef,
): string | null {
function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null {
if (!branch.worktreePath) {
return null;
}
@@ -47,7 +45,7 @@ function normalizeSelectedWorktreePath(
export function branchBadgeLabel(input: {
readonly branch: VcsRef;
readonly project: EnvironmentScopedProjectShell | null;
readonly project: EnvironmentProject | null;
}): string | null {
if (input.branch.current) {
return "current";
@@ -67,7 +65,7 @@ export function branchBadgeLabel(input: {
type NewTaskFlowContextValue = {
readonly logicalProjects: ReadonlyArray<{
readonly key: string;
readonly project: EnvironmentScopedProjectShell;
readonly project: EnvironmentProject;
}>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
@@ -83,15 +81,12 @@ type NewTaskFlowContextValue = {
readonly availableBranches: ReadonlyArray<VcsRef>;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
readonly effort: ClaudeAgentEffort;
readonly fastMode: boolean;
readonly contextWindow: string;
readonly expandedProvider: string | null;
readonly environments: ReadonlyArray<{
readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
}>;
readonly selectedProject: EnvironmentScopedProjectShell | null;
readonly selectedProject: EnvironmentProject | null;
readonly modelOptions: ReadonlyArray<ModelOption>;
readonly selectedModel: ModelSelection | null;
readonly selectedModelOption: ModelOption | null;
@@ -99,7 +94,7 @@ type NewTaskFlowContextValue = {
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly filteredBranches: ReadonlyArray<VcsRef>;
readonly reset: () => void;
readonly setProject: (project: EnvironmentScopedProjectShell) => void;
readonly setProject: (project: EnvironmentProject) => void;
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly setSelectedModelKey: (key: string | null) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
@@ -114,17 +109,18 @@ type NewTaskFlowContextValue = {
readonly loadBranches: () => Promise<void>;
readonly setRuntimeMode: (value: RuntimeMode) => void;
readonly setInteractionMode: (value: ProviderInteractionMode) => void;
readonly setEffort: (value: ClaudeAgentEffort) => void;
readonly setFastMode: (value: boolean) => void;
readonly setContextWindow: (value: string) => void;
readonly setSelectedModelOptions: (
value: ReadonlyArray<ProviderOptionSelection> | undefined,
) => void;
readonly setExpandedProvider: (value: string | null) => void;
};
const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const { projects, serverConfigByEnvironmentId, threads } = useRemoteCatalog();
const { savedConnectionsById } = useRemoteEnvironmentState();
const projects = useProjects();
const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
@@ -146,16 +142,21 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
entry,
): entry is {
readonly key: string;
readonly project: EnvironmentScopedProjectShell;
readonly project: EnvironmentProject;
} => entry !== null,
),
),
[repositoryGroups],
);
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
projects[0]?.environmentId ?? null,
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const selectedEnvironmentId =
selectedEnvironmentIdOverride !== null &&
projects.some((project) => project.environmentId === selectedEnvironmentIdOverride)
? selectedEnvironmentIdOverride
: (projects[0]?.environmentId ?? null);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
@@ -168,17 +169,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
DEFAULT_PROVIDER_INTERACTION_MODE,
);
const [effort, setEffort] = useState<ClaudeAgentEffort>("high");
const [fastMode, setFastMode] = useState(false);
const [contextWindow, setContextWindow] = useState("1M");
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
Record<string, ModelSelection>
>({});
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const reset = useCallback(() => {
console.log("[new task flow] reset", {
defaultEnvironmentId: projects[0]?.environmentId ?? null,
projectCount: projects.length,
});
setSelectedEnvironmentId(projects[0]?.environmentId ?? null);
setSelectedEnvironmentId(null);
setSelectedProjectKey(null);
setSelectedModelKey(null);
setWorkspaceMode("local");
@@ -188,22 +185,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setBranchQuery("");
setRuntimeMode(DEFAULT_RUNTIME_MODE);
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
setEffort("high");
setFastMode(false);
setContextWindow("1M");
setModelSelectionOverrides({});
setExpandedProvider(null);
}, [projects]);
useEffect(() => {
if (selectedEnvironmentId !== null || projects.length === 0) {
return;
}
console.log("[new task flow] initializing environment", {
environmentId: projects[0]!.environmentId,
});
setSelectedEnvironmentId(projects[0]!.environmentId);
}, [projects, selectedEnvironmentId]);
}, []);
const environments = useMemo(
() =>
@@ -254,6 +238,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
) ??
projectsForEnvironment[0] ??
null;
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
);
const selectedProjectDraftKey = selectedProject
? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
: null;
@@ -264,19 +251,29 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const modelOptions = useMemo(
() =>
buildModelOptions(
selectedProject
? (serverConfigByEnvironmentId[selectedProject.environmentId] ?? null)
: null,
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
),
[selectedProject, serverConfigByEnvironmentId],
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
);
const selectedModel =
const defaultModelKey = selectedProject?.defaultModelSelection
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
: null;
const baseSelectedModel =
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
(defaultModelKey
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
: null) ??
selectedProject?.defaultModelSelection ??
modelOptions[0]?.selection ??
null;
const selectedModelIdentity = baseSelectedModel
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
: null;
const selectedModel =
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
baseSelectedModel;
const selectedModelOption =
modelOptions.find(
@@ -286,11 +283,27 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.model === selectedModel.model,
) ?? null;
const selectedProviderSkills =
(selectedProject
? serverConfigByEnvironmentId[selectedProject.environmentId]
: null
)?.providers.find((provider) => provider.instanceId === selectedModel?.instanceId)?.skills ??
[];
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [];
const setSelectedModelOptions = useCallback(
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
if (!selectedModel || !selectedModelIdentity) {
return;
}
const nextSelection: ModelSelection = options
? { ...selectedModel, options }
: {
instanceId: selectedModel.instanceId,
model: selectedModel.model,
};
setModelSelectionOverrides((current) => ({
...current,
[selectedModelIdentity]: nextSelection,
}));
},
[selectedModel, selectedModelIdentity],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
const setPrompt = useCallback(
@@ -343,7 +356,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}),
[selectedProject?.environmentId, selectedProject?.workspaceRoot],
);
const branchState = useVcsRefs(branchTarget);
const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending;
const availableBranches = useMemo(
() =>
@@ -366,13 +379,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
}, [availableBranches, branchQuery]);
const setProject = useCallback((project: EnvironmentScopedProjectShell) => {
const setProject = useCallback((project: EnvironmentProject) => {
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(project.environmentId);
setSelectedProjectKey(nextProjectKey);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
@@ -381,6 +395,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedProjectKey(null);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const selectBranch = useCallback(
@@ -400,37 +415,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
try {
const result = await vcsRefManager.load({
environmentId: selectedProject.environmentId,
cwd: selectedProject.workspaceRoot,
query: null,
});
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
return;
}
setPendingConnectionError(null);
const branches = pipe(
result?.refs ?? [],
Arr.filter((branch) => !branch.isRemote),
);
if (workspaceMode === "worktree" && !selectedBranchName) {
const preferredBranch =
branches.find((branch) => branch.current)?.name ??
branches.find((branch) => branch.isDefault)?.name ??
null;
if (preferredBranch) {
setSelectedBranchName(preferredBranch);
}
}
} catch {
if (loadVersion !== branchLoadVersionRef.current) {
return;
}
setPendingConnectionError("Failed to load branches.");
branchState.refresh();
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
return;
}
}, [selectedBranchName, selectedProject, selectedProjectKey, workspaceMode]);
setPendingConnectionError(null);
if (workspaceMode === "worktree" && !selectedBranchName) {
const preferredBranch =
availableBranches.find((branch) => branch.current)?.name ??
availableBranches.find((branch) => branch.isDefault)?.name ??
null;
if (preferredBranch) {
setSelectedBranchName(preferredBranch);
}
}
}, [
availableBranches,
branchState,
selectedBranchName,
selectedProject,
selectedProjectKey,
workspaceMode,
]);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
@@ -449,9 +455,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
availableBranches,
runtimeMode,
interactionMode,
effort,
fastMode,
contextWindow,
expandedProvider,
environments,
selectedProject,
@@ -477,9 +480,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
loadBranches,
setRuntimeMode,
setInteractionMode,
setEffort,
setFastMode,
setContextWindow,
setSelectedModelOptions,
setExpandedProvider,
}),
[
@@ -487,11 +488,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
availableBranches,
branchQuery,
branchesLoading,
contextWindow,
effort,
environments,
expandedProvider,
fastMode,
filteredBranches,
interactionMode,
loadBranches,
@@ -508,6 +506,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModelKey,
selectedModelOption,
selectedProviderSkills,
setSelectedModelOptions,
selectedProject,
selectedProjectKey,
selectedWorktreePath,
@@ -522,24 +521,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
],
);
useEffect(() => {
console.log("[new task flow] state", {
availableBranchCount: availableBranches.length,
environmentCount: environments.length,
logicalProjectCount: logicalProjects.length,
selectedEnvironmentId,
selectedProjectKey,
selectedProjectTitle: selectedProject?.title ?? null,
});
}, [
availableBranches.length,
environments.length,
logicalProjects.length,
selectedEnvironmentId,
selectedProject?.title,
selectedProjectKey,
]);
return <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;
}
@@ -0,0 +1,57 @@
import { describe, expect, it } from "@effect/vitest";
import { projectThreadContentPresentation } from "./threadContentPresentation";
describe("thread content presentation", () => {
it("renders cached detail while its environment reconnects", () => {
expect(
projectThreadContentPresentation({
hasDetail: true,
detailError: null,
detailDeleted: false,
connectionState: "reconnecting",
}),
).toEqual({ kind: "ready" });
});
it("loads missing detail inside the thread screen when connected", () => {
expect(
projectThreadContentPresentation({
hasDetail: false,
detailError: null,
detailDeleted: false,
connectionState: "connected",
}),
).toEqual({ kind: "loading" });
});
it("explains uncached detail while disconnected instead of loading forever", () => {
expect(
projectThreadContentPresentation({
hasDetail: false,
detailError: null,
detailDeleted: false,
connectionState: "error",
}),
).toEqual({
kind: "unavailable",
title: "Messages not cached",
detail: "Reconnect this environment to load the conversation.",
});
});
it("surfaces detail errors before presenting a loading state", () => {
expect(
projectThreadContentPresentation({
hasDetail: false,
detailError: "The thread stream failed.",
detailDeleted: false,
connectionState: "connected",
}),
).toEqual({
kind: "unavailable",
title: "Could not load conversation",
detail: "The thread stream failed.",
});
});
});
@@ -0,0 +1,43 @@
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
export type ThreadContentPresentation =
| { readonly kind: "ready" }
| { readonly kind: "loading" }
| {
readonly kind: "unavailable";
readonly title: string;
readonly detail: string;
};
export function projectThreadContentPresentation(input: {
readonly hasDetail: boolean;
readonly detailError: string | null;
readonly detailDeleted: boolean;
readonly connectionState: EnvironmentConnectionPhase;
}): ThreadContentPresentation {
if (input.hasDetail) {
return { kind: "ready" };
}
if (input.detailDeleted) {
return {
kind: "unavailable",
title: "Thread unavailable",
detail: "This thread was deleted or is no longer available.",
};
}
if (input.detailError !== null) {
return {
kind: "unavailable",
title: "Could not load conversation",
detail: input.detailError,
};
}
if (input.connectionState === "connected") {
return { kind: "loading" };
}
return {
kind: "unavailable",
title: "Messages not cached",
detail: "Reconnect this environment to load the conversation.",
};
}
@@ -1,12 +1,12 @@
import type { StatusTone } from "../../components/StatusPill";
import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
export function threadSortValue(thread: EnvironmentScopedThreadShell): number {
export function threadSortValue(thread: EnvironmentThreadShell): number {
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
return Number.isNaN(candidate) ? 0 : candidate;
}
export function threadStatusTone(thread: EnvironmentScopedThreadShell): StatusTone {
export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
const status = thread.session?.status;
if (status === "running") {
return {
@@ -42,12 +42,3 @@ export function threadStatusTone(thread: EnvironmentScopedThreadShell): StatusTo
textClassName: "text-neutral-600 dark:text-neutral-300",
};
}
export function messageImageUrl(httpBaseUrl: string | null, attachmentId: string): string | null {
if (!httpBaseUrl) {
return null;
}
const url = new URL(`/attachments/${encodeURIComponent(attachmentId)}`, httpBaseUrl);
return url.toString();
}
@@ -1,67 +1,26 @@
import { useCallback } from "react";
import { EnvironmentScopedProjectShell, type VcsRef } from "@t3tools/client-runtime";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { mapAtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type EnvironmentId,
MessageId,
ThreadId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { buildTemporaryWorktreeBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { uuidv4 } from "../../lib/uuid";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { threadEnvironment } from "../../state/threads";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { environmentRuntimeManager } from "../../state/use-environment-runtime";
import { vcsRefManager } from "../../state/use-vcs-refs";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import {
setPendingConnectionError,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
function useRefreshRemoteData() {
const { savedConnectionsById } = useRemoteEnvironmentState();
return useCallback(
async (environmentIds?: ReadonlyArray<EnvironmentId>) => {
const targets =
environmentIds ??
Object.values(savedConnectionsById).map((connection) => connection.environmentId);
await Promise.all(
targets.map(async (environmentId) => {
const client = getEnvironmentClient(environmentId);
if (!client) {
return;
}
try {
const serverConfig = await client.server.getConfig();
environmentRuntimeManager.patch({ environmentId }, (current) => ({
...current,
serverConfig,
connectionError: null,
}));
} catch (error) {
environmentRuntimeManager.patch({ environmentId }, (current) => ({
...current,
connectionError:
error instanceof Error ? error.message : "Failed to refresh remote data.",
}));
}
}),
);
},
[savedConnectionsById],
);
}
import { uuidv4 } from "../../lib/uuid";
import { useAtomCommand } from "../../state/use-atom-command";
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
@@ -73,13 +32,12 @@ function deriveThreadTitleFromPrompt(value: string): string {
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
}
export function useProjectActions() {
const { threads } = useRemoteCatalog();
const refreshRemoteData = useRefreshRemoteData();
export function useCreateProjectThread() {
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const onCreateThreadWithOptions = useCallback(
return useCallback(
async (input: {
readonly project: EnvironmentScopedProjectShell;
readonly project: EnvironmentProject;
readonly modelSelection: ModelSelection;
readonly envMode: "local" | "worktree";
readonly branch: string | null;
@@ -89,174 +47,76 @@ export function useProjectActions() {
readonly initialMessageText: string;
readonly initialAttachments: ReadonlyArray<DraftComposerImageAttachment>;
}) => {
const client = getEnvironmentClient(input.project.environmentId);
if (!client) {
return null;
}
const metadata = makeTurnCommandMetadata();
const threadId = ThreadId.make(metadata.threadId);
const createdAt = metadata.createdAt;
const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
if (initialMessageText.length === 0) {
return null;
const error = new Error("Enter a task before starting the thread.");
setPendingConnectionError(error.message);
return AsyncResult.failure(Cause.fail(error));
}
if (input.envMode === "worktree" && !input.branch) {
return null;
const error = new Error("Select a base branch before creating a worktree.");
setPendingConnectionError(error.message);
return AsyncResult.failure(Cause.fail(error));
}
const isWorktree = input.envMode === "worktree";
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.make(metadata.commandId),
threadId,
message: {
messageId: MessageId.make(metadata.messageId),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
},
modelSelection: input.modelSelection,
titleSeed: nextTitle,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
bootstrap: {
createThread: {
projectId: input.project.id,
title: nextTitle,
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
branch: input.branch,
worktreePath: isWorktree ? null : input.worktreePath,
createdAt,
},
...(isWorktree
? {
prepareWorktree: {
projectCwd: input.project.workspaceRoot,
baseBranch: input.branch!,
branch: buildTemporaryWorktreeBranchName(uuidv4),
},
runSetupScript: true,
}
: {}),
},
createdAt,
});
await refreshRemoteData([input.project.environmentId]);
return {
const result = await startTurn({
environmentId: input.project.environmentId,
threadId,
};
},
[refreshRemoteData],
);
const onCreateThread = useCallback(
async (project: EnvironmentScopedProjectShell) => {
const latestProjectThread =
threads.find(
(thread) =>
thread.environmentId === project.environmentId && thread.projectId === project.id,
) ?? null;
const modelSelection =
project.defaultModelSelection ?? latestProjectThread?.modelSelection ?? null;
if (!modelSelection) {
setPendingConnectionError("This project does not have a default model configured yet.");
return null;
}
return await onCreateThreadWithOptions({
project,
modelSelection,
envMode: "local",
branch: null,
worktreePath: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
initialMessageText: "",
initialAttachments: [],
input: {
commandId: CommandId.make(metadata.commandId),
threadId,
message: {
messageId: MessageId.make(metadata.messageId),
role: "user",
text: initialMessageText,
attachments: input.initialAttachments,
},
modelSelection: input.modelSelection,
titleSeed: nextTitle,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
bootstrap: {
createThread: {
projectId: input.project.id,
title: nextTitle,
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
branch: input.branch,
worktreePath: isWorktree ? null : input.worktreePath,
createdAt: metadata.createdAt,
},
...(isWorktree
? {
prepareWorktree: {
projectCwd: input.project.workspaceRoot,
baseBranch: input.branch!,
branch: buildTemporaryWorktreeBranchName(uuidv4),
},
runSetupScript: true,
}
: {}),
},
createdAt: metadata.createdAt,
},
});
},
[onCreateThreadWithOptions, threads],
);
const onListProjectBranches = useCallback(
async (project: EnvironmentScopedProjectShell): Promise<ReadonlyArray<VcsRef>> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return [];
}
try {
const result = await vcsRefManager.load(
{ environmentId: project.environmentId, cwd: project.workspaceRoot, query: null },
client.vcs,
{ limit: 100 },
);
return (result?.refs ?? []).filter((branch) => !branch.isRemote);
} catch (error) {
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to load branches.",
error instanceof Error ? error.message : "The task could not be started.",
);
return [];
return AsyncResult.failure(result.cause);
}
setPendingConnectionError(null);
return mapAtomCommandResult(result, () =>
scopeThreadRef(input.project.environmentId, threadId),
);
},
[],
[startTurn],
);
const onCreateProjectWorktree = useCallback(
async (
project: EnvironmentScopedProjectShell,
nextWorktree: {
readonly baseBranch: string;
readonly newBranch: string;
},
): Promise<{
readonly branch: string;
readonly worktreePath: string;
} | null> => {
const client = getEnvironmentClient(project.environmentId);
if (!client) {
return null;
}
try {
const result = await client.vcs.createWorktree({
cwd: project.workspaceRoot,
refName: nextWorktree.baseBranch,
newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch),
path: null,
});
vcsRefManager.invalidate({
environmentId: project.environmentId,
cwd: project.workspaceRoot,
query: null,
});
return {
branch: result.worktree.refName,
worktreePath: result.worktree.path,
};
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to create worktree.",
);
return null;
}
},
[],
);
return {
onCreateThread,
onCreateThreadWithOptions,
onListProjectBranches,
onCreateProjectWorktree,
onRefreshProjects: refreshRemoteData,
};
}
+1 -1
View File
@@ -1,7 +1,7 @@
import type { AuthClientPresentationMetadata } from "@t3tools/contracts";
import { Platform } from "react-native";
export function mobileAuthClientMetadata(): AuthClientPresentationMetadata {
export function authClientMetadata(): AuthClientPresentationMetadata {
return {
label: "T3 Code Mobile",
deviceType: "mobile",
+3 -3
View File
@@ -3,13 +3,13 @@ import { EnvironmentId } from "@t3tools/contracts";
import {
isRelayManagedConnection,
mobileAuthClientMetadata,
authClientMetadata,
redactPairingCredential,
toStableSavedRemoteConnection,
} from "./connection";
vi.mock("./runtime", () => ({
mobileRuntime: {
runtime: {
runPromise: vi.fn(),
},
}));
@@ -22,7 +22,7 @@ vi.mock("react-native", () => ({
describe("mobile remote connection records", () => {
it("identifies mobile token exchanges for authorized-client presentation", () => {
expect(mobileAuthClientMetadata()).toEqual({
expect(authClientMetadata()).toEqual({
label: "T3 Code Mobile",
deviceType: "mobile",
os: "iOS",
+4 -54
View File
@@ -1,18 +1,8 @@
import { EnvironmentId } from "@t3tools/contracts";
import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
} from "@t3tools/client-runtime";
import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote";
import * as Effect from "effect/Effect";
import { mobileAuthClientMetadata } from "./authClientMetadata";
import { mobileRuntime } from "./runtime";
import { stripPairingTokenFromUrl } from "@t3tools/shared/remote";
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
export { mobileAuthClientMetadata } from "./authClientMetadata";
export interface RemoteConnectionInput {
readonly pairingUrl: string;
}
export { authClientMetadata } from "./authClientMetadata";
export interface SavedRemoteConnection {
readonly environmentId: EnvironmentId;
@@ -27,12 +17,7 @@ export interface SavedRemoteConnection {
readonly relayManaged?: true;
}
export type RemoteClientConnectionState =
| "idle"
| "connecting"
| "ready"
| "reconnecting"
| "disconnected";
export type RemoteClientConnectionState = EnvironmentConnectionPhase;
export function redactPairingCredential(pairingUrl: string): string {
const trimmed = pairingUrl.trim();
@@ -59,38 +44,3 @@ export function toStableSavedRemoteConnection(
const { dpopAccessToken: _, ...stableConnection } = connection;
return stableConnection;
}
export async function bootstrapRemoteConnection(
input: RemoteConnectionInput,
): Promise<SavedRemoteConnection> {
const target = resolveRemotePairingTarget({
pairingUrl: input.pairingUrl,
});
const { descriptor, bootstrap } = await mobileRuntime.runPromise(
Effect.all(
{
descriptor: fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
}),
bootstrap: bootstrapRemoteBearerSession({
httpBaseUrl: target.httpBaseUrl,
credential: target.credential,
clientMetadata: mobileAuthClientMetadata(),
}),
},
{ concurrency: "unbounded" },
),
);
return {
environmentId: descriptor.environmentId,
environmentLabel: descriptor.label,
pairingUrl: redactPairingCredential(input.pairingUrl),
displayUrl: target.httpBaseUrl,
httpBaseUrl: target.httpBaseUrl,
wsBaseUrl: target.wsBaseUrl,
bearerToken: bootstrap.access_token,
authenticationMethod: "bearer",
};
}
@@ -2,19 +2,16 @@ function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
export type MobileLayoutVariant = "compact" | "split";
export type LayoutVariant = "compact" | "split";
export interface MobileLayout {
readonly variant: MobileLayoutVariant;
export interface Layout {
readonly variant: LayoutVariant;
readonly usesSplitView: boolean;
readonly listPaneWidth: number | null;
readonly shellPadding: number;
}
export function deriveMobileLayout(input: {
readonly width: number;
readonly height: number;
}): MobileLayout {
export function deriveLayout(input: { readonly width: number; readonly height: number }): Layout {
const { width, height } = input;
const shortestEdge = Math.min(width, height);
const wideEnoughForSplit = width >= 900 || (width >= 700 && shortestEdge >= 700);
Loaded 100 of 589 files, more files were not shown because too many files have changed in this diff. Show more