Compare commits

...
Author SHA1 Message Date
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 36685 additions and 53089 deletions

No files matched your search

-46
View File
@@ -60,52 +60,6 @@ jobs:
- name: Test - name: Test
run: vp run 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: mobile_native_static_analysis:
name: Mobile Native Static Analysis name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26 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,328 @@
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 Option.none<string>();
}
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 Electron from "electron";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import * as Context from "effect/Context";
import * as Electron from "electron"; import * as Data from "effect/Data";
export class ElectronSafeStorageAvailabilityError extends Data.TaggedError( export class ElectronSafeStorageAvailabilityError extends Data.TaggedError(
"ElectronSafeStorageAvailabilityError", "ElectronSafeStorageAvailabilityError",
+7 -11
View File
@@ -10,12 +10,10 @@ import {
} from "./methods/cloudAuth.ts"; } from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import { import {
getSavedEnvironmentRegistry, clearConnectionCatalog,
getSavedEnvironmentSecret, getConnectionCatalog,
removeSavedEnvironmentSecret, setConnectionCatalog,
setSavedEnvironmentRegistry, } from "./methods/connectionCatalog.ts";
setSavedEnvironmentSecret,
} from "./methods/savedEnvironments.ts";
import { import {
getAdvertisedEndpoints, getAdvertisedEndpoints,
getServerExposureState, getServerExposureState,
@@ -59,11 +57,9 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(getClientSettings); yield* ipc.handle(getClientSettings);
yield* ipc.handle(setClientSettings); yield* ipc.handle(setClientSettings);
yield* ipc.handle(getSavedEnvironmentRegistry); yield* ipc.handle(getConnectionCatalog);
yield* ipc.handle(setSavedEnvironmentRegistry); yield* ipc.handle(setConnectionCatalog);
yield* ipc.handle(getSavedEnvironmentSecret); yield* ipc.handle(clearConnectionCatalog);
yield* ipc.handle(setSavedEnvironmentSecret);
yield* ipc.handle(removeSavedEnvironmentSecret);
yield* ipc.handle(discoverSshHosts); yield* ipc.handle(discoverSshHosts);
yield* ipc.handle(ensureSshEnvironment); 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_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings"; export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-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 GET_CONNECTION_CATALOG_CHANNEL = "desktop:get-connection-catalog";
export const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry"; export const SET_CONNECTION_CATALOG_CHANNEL = "desktop:set-connection-catalog";
export const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret"; export const CLEAR_CONNECTION_CATALOG_CHANNEL = "desktop:clear-connection-catalog";
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 DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts"; export const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment"; export const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
export const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-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 method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers); const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe( const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers), HttpClientRequest.setHeaders(Object.fromEntries(headers.entries())),
input.body === undefined input.body === undefined
? identity ? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined), : 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 { import {
bootstrapRemoteBearerSession, bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState, fetchRemoteSessionState,
issueRemoteWebSocketTicket, issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError, RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError, type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime"; } from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { import {
EnvironmentAuthInvalidError, EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema, 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 DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts"; import * as DesktopCloudAuth from "./app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts"; import * as DesktopCloudAuthTokenStore from "./app/DesktopCloudAuthTokenStore.ts";
import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts"; import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts"; import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts"; import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
@@ -117,7 +118,7 @@ const desktopFoundationLayer = Layer.mergeAll(
DesktopLifecycle.layerShutdown, DesktopLifecycle.layerShutdown,
DesktopAppSettings.layer, DesktopAppSettings.layer,
DesktopClientSettings.layer, DesktopClientSettings.layer,
DesktopSavedEnvironments.layer, DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
DesktopCloudAuthTokenStore.layer, DesktopCloudAuthTokenStore.layer,
DesktopAssets.layer, DesktopAssets.layer,
DesktopObservability.layer, DesktopObservability.layer,
+4 -10
View File
@@ -42,16 +42,10 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL), getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) => setClientSettings: (settings) =>
ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings), ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings),
getSavedEnvironmentRegistry: () => getConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.GET_CONNECTION_CATALOG_CHANNEL),
ipcRenderer.invoke(IpcChannels.GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL), setConnectionCatalog: (catalog) =>
setSavedEnvironmentRegistry: (records) => ipcRenderer.invoke(IpcChannels.SET_CONNECTION_CATALOG_CHANNEL, catalog),
ipcRenderer.invoke(IpcChannels.SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records), clearConnectionCatalog: () => ipcRenderer.invoke(IpcChannels.CLEAR_CONNECTION_CATALOG_CHANNEL),
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),
discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL), discoverSshHosts: () => ipcRenderer.invoke(IpcChannels.DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) => ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult( unwrapEnsureSshEnvironmentResult(
@@ -289,7 +289,7 @@ describe("DesktopSavedEnvironments", () => {
), ),
); );
it.effect("treats malformed saved environment documents as empty", () => it.effect("surfaces malformed saved environment documents", () =>
withSavedEnvironments( withSavedEnvironments(
Effect.gen(function* () { Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment; const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -298,10 +298,15 @@ describe("DesktopSavedEnvironments", () => {
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json"); yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json");
assert.deepEqual(yield* savedEnvironments.getRegistry, []); const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip);
assert.isTrue( assert.instanceOf(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)), 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( export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
"DesktopSavedEnvironmentSecretDecodeError", "DesktopSavedEnvironmentSecretDecodeError",
)<{ )<{
@@ -93,6 +103,7 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Data.TaggedError(
} }
export type DesktopSavedEnvironmentsGetSecretError = export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentSecretDecodeError | DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageAvailabilityError | ElectronSafeStorage.ElectronSafeStorageAvailabilityError
| ElectronSafeStorage.ElectronSafeStorageDecryptError; | ElectronSafeStorage.ElectronSafeStorageDecryptError;
@@ -103,7 +114,10 @@ export type DesktopSavedEnvironmentsSetSecretError =
| ElectronSafeStorage.ElectronSafeStorageEncryptError; | ElectronSafeStorage.ElectronSafeStorageEncryptError;
export interface DesktopSavedEnvironmentsShape { export interface DesktopSavedEnvironmentsShape {
readonly getRegistry: Effect.Effect<readonly PersistedSavedEnvironmentRecord[]>; readonly getRegistry: Effect.Effect<
readonly PersistedSavedEnvironmentRecord[],
DesktopSavedEnvironmentsReadError
>;
readonly setRegistry: ( readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[], records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>; ) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
@@ -176,18 +190,20 @@ function normalizeSavedEnvironmentRegistryDocument(
function readRegistryDocument( function readRegistryDocument(
fileSystem: FileSystem.FileSystem, fileSystem: FileSystem.FileSystem,
registryPath: string, registryPath: string,
): Effect.Effect<SavedEnvironmentRegistryDocument> { ): Effect.Effect<
SavedEnvironmentRegistryDocument,
PlatformError.PlatformError | Schema.SchemaError
> {
return fileSystem.readFileString(registryPath).pipe( return fileSystem.readFileString(registryPath).pipe(
Effect.option, Effect.catch((error) =>
Effect.flatMap( error.reason._tag === "NotFound" ? Effect.succeed<string | null>(null) : Effect.fail(error),
Option.match({ ),
onNone: () => Effect.succeed({ version: 1, records: [] }), Effect.flatMap((raw) =>
onSome: (raw) => raw === null
decodeSavedEnvironmentRegistryDocumentJson(raw).pipe( ? Effect.succeed({ version: 1, records: [] })
: decodeSavedEnvironmentRegistryDocumentJson(raw).pipe(
Effect.map(normalizeSavedEnvironmentRegistryDocument), Effect.map(normalizeSavedEnvironmentRegistryDocument),
Effect.orElseSucceed(() => ({ version: 1, records: [] })),
), ),
}),
), ),
); );
} }
@@ -267,13 +283,14 @@ export const layer = Layer.effect(
Effect.map((document) => Effect.map((document) =>
document.records.map((record) => toPersistedSavedEnvironmentRecord(record)), document.records.map((record) => toPersistedSavedEnvironmentRecord(record)),
), ),
Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })),
Effect.withSpan("desktop.savedEnvironments.getRegistry"), Effect.withSpan("desktop.savedEnvironments.getRegistry"),
), ),
setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) { setRegistry: Effect.fn("desktop.savedEnvironments.setRegistry")(function* (records) {
const currentDocument = yield* readRegistryDocument( const currentDocument = yield* readRegistryDocument(
fileSystem, fileSystem,
environment.savedEnvironmentRegistryPath, environment.savedEnvironmentRegistryPath,
); ).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
yield* writeDocument(preserveExistingSecrets(currentDocument, records)); yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}), }),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) { getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
@@ -281,7 +298,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument( const document = yield* readRegistryDocument(
fileSystem, fileSystem,
environment.savedEnvironmentRegistryPath, environment.savedEnvironmentRegistryPath,
); ).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsReadError({ cause })));
const encoded = Option.fromNullishOr( const encoded = Option.fromNullishOr(
document.records.find((record) => record.environmentId === environmentId) document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken, ?.encryptedBearerToken,
@@ -299,7 +316,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument( const document = yield* readRegistryDocument(
fileSystem, fileSystem,
environment.savedEnvironmentRegistryPath, environment.savedEnvironmentRegistryPath,
); ).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (!(yield* safeStorage.isEncryptionAvailable)) { if (!(yield* safeStorage.isEncryptionAvailable)) {
return false; return false;
@@ -331,7 +348,7 @@ export const layer = Layer.effect(
const document = yield* readRegistryDocument( const document = yield* readRegistryDocument(
fileSystem, fileSystem,
environment.savedEnvironmentRegistryPath, environment.savedEnvironmentRegistryPath,
); ).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if ( if (
!document.records.some( !document.records.some(
(record) => (record) =>
+5
View File
@@ -131,6 +131,11 @@ const config: ExpoConfig = {
{ {
ios: { ios: {
deploymentTarget: "18.0", 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": { "cli": {
"version": ">= 18.4.0", "version": ">= 18.4.0",
"appVersionSource": "remote" "appVersionSource": "remote",
"promptToConfigurePushNotifications": false
}, },
"build": { "build": {
"development": { "development": {
+1
View File
@@ -77,6 +77,7 @@
"expo-haptics": "~56.0.3", "expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14", "expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12", "expo-linking": "~56.0.12",
"expo-network": "~56.0.5",
"expo-notifications": "~56.0.14", "expo-notifications": "~56.0.14",
"expo-paste-input": "^0.1.15", "expo-paste-input": "^0.1.15",
"expo-router": "~56.2.7", "expo-router": "~56.2.7",
+5 -8
View File
@@ -16,10 +16,8 @@ import { useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen"; import { LoadingScreen } from "../components/LoadingScreen";
import { import { useWorkspaceState } from "../state/workspace";
useRemoteEnvironmentBootstrap, import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
useRemoteEnvironmentState,
} from "../state/use-remote-environment-registry";
import { RegistryContext } from "@effect/atom-react"; import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry"; import { appAtomRegistry } from "../state/atom-registry";
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider"; import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
@@ -42,12 +40,13 @@ function AppNavigator() {
} }
function AppNavigatorContent() { function AppNavigatorContent() {
const { isLoadingSavedConnection } = useRemoteEnvironmentState(); const { state } = useWorkspaceState();
const { collapse, isExpanded } = useClerkSettingsSheetDetent(); const { collapse, isExpanded } = useClerkSettingsSheetDetent();
const colorScheme = useColorScheme(); const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar"); const statusBarBg = useThemeColor("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet"); const sheetStyle = useResolveClassNames("bg-sheet");
useAgentNotificationNavigation(); useAgentNotificationNavigation();
useThreadOutboxDrain();
const handleSettingsTransitionEnd = useCallback( const handleSettingsTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => { (event: { data: { closing: boolean } }) => {
@@ -81,7 +80,7 @@ function AppNavigatorContent() {
sheetAllowedDetents: isExpanded ? [0.92] : [0.7], sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
}; };
if (isLoadingSavedConnection) { if (state.isLoadingConnections) {
return <LoadingScreen message="Loading remote workspace…" />; return <LoadingScreen message="Loading remote workspace…" />;
} }
@@ -129,8 +128,6 @@ export default function RootLayout() {
DMSans_500Medium, DMSans_500Medium,
DMSans_700Bold, DMSans_700Bold,
}); });
useRemoteEnvironmentBootstrap();
return ( return (
<RegistryContext.Provider value={appAtomRegistry}> <RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider> <CloudAuthProvider>
+6 -5
View File
@@ -1,5 +1,6 @@
import { CameraView, useCameraPermissions } from "expo-camera"; import { CameraView, useCameraPermissions } from "expo-camera";
import { Stack, useLocalSearchParams, useRouter } from "expo-router"; import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Alert, ScrollView, View } from "react-native"; import { Alert, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -111,12 +112,12 @@ export default function ConnectionsNewRouteScreen() {
const handleSubmit = useCallback(async () => { const handleSubmit = useCallback(async () => {
setIsSubmitting(true); setIsSubmitting(true);
try { const pairingUrl = buildPairingUrl(hostInput, codeInput);
const pairingUrl = buildPairingUrl(hostInput, codeInput); onChangeConnectionPairingUrl(pairingUrl);
onChangeConnectionPairingUrl(pairingUrl); const result = await onConnectPress(pairingUrl);
await onConnectPress(pairingUrl); if (AsyncResult.isSuccess(result)) {
dismissRoute(router); dismissRoute(router);
} catch { } else {
setIsSubmitting(false); setIsSubmitting(false);
} }
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]); }, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
+12 -4
View File
@@ -2,17 +2,20 @@ import { Stack, useRouter } from "expo-router";
import { useState } from "react"; import { useState } from "react";
import { Text as RNText, View } from "react-native"; 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 { buildThreadRoutePath } from "../lib/routes";
import { useRemoteCatalog } from "../state/use-remote-catalog"; import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen"; import { HomeScreen } from "../features/home/HomeScreen";
import { useThemeColor } from "../lib/useThemeColor"; import { useThemeColor } from "../lib/useThemeColor";
/* ─── Route screen ───────────────────────────────────────────────────── */ /* ─── Route screen ───────────────────────────────────────────────────── */
export default function HomeRouteScreen() { export default function HomeRouteScreen() {
const { projects, state: catalogState, threads } = useRemoteCatalog(); const projects = useProjects();
const { savedConnectionsById } = useRemoteEnvironmentState(); const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const router = useRouter(); const router = useRouter();
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
@@ -32,9 +35,13 @@ export default function HomeRouteScreen() {
headerTitle: "", headerTitle: "",
headerSearchBarOptions: { headerSearchBarOptions: {
placeholder: "Search threads", placeholder: "Search threads",
hideNavigationBar: false,
onChangeText: (event) => { onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text); setSearchQuery(event.nativeEvent.text);
}, },
onCancelButtonPress: () => {
setSearchQuery("");
},
allowToolbarIntegration: true, allowToolbarIntegration: true,
}, },
}} }}
@@ -104,6 +111,7 @@ export default function HomeRouteScreen() {
savedConnectionsById={savedConnectionsById} savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery} searchQuery={searchQuery}
onAddConnection={() => router.push("/connections/new")} onAddConnection={() => router.push("/connections/new")}
onOpenEnvironments={() => router.push("/settings/environments")}
onSelectThread={(thread) => { onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread)); router.push(buildThreadRoutePath(thread));
}} }}
@@ -1,5 +1,5 @@
import { Stack, useLocalSearchParams } from "expo-router"; 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"; 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 { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon"; 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 { 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 title: string;
readonly detail: string; readonly detail: string;
readonly loading: boolean; readonly loading: boolean;
} { } {
if (catalogState.isLoadingSavedConnections) { if (catalogState.isLoadingConnections) {
return { return {
title: "Loading environments", title: "Loading environments",
detail: "Checking saved environments on this device.", detail: "Checking saved environments on this device.",
@@ -25,7 +26,7 @@ function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
}; };
} }
if (!catalogState.hasSavedConnections) { if (!catalogState.hasConnections) {
return { return {
title: "No environments connected", title: "No environments connected",
detail: "Add an environment before creating a task.", 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 { return {
title: "Environment unavailable", title: "Environment unavailable",
detail: detail:
@@ -63,8 +69,9 @@ function deriveProjectEmptyState(catalogState: RemoteCatalogState): {
} }
export default function NewTaskRoute() { export default function NewTaskRoute() {
const { projects, state: catalogState, threads } = useRemoteCatalog(); const projects = useProjects();
const { savedConnectionsById } = useRemoteEnvironmentState(); const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const router = useRouter(); const router = useRouter();
const insets = useSafeAreaInsets(); const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron"); 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="flex-row items-center justify-between gap-3">
<View className="h-7 w-7 items-center justify-center"> <View className="h-7 w-7 items-center justify-center">
<ProjectFavicon <ProjectFavicon
environmentId={item.environmentId}
size={20} size={20}
projectTitle={item.title} projectTitle={item.title}
httpBaseUrl={
savedConnectionsById[item.environmentId]?.httpBaseUrl ?? null
}
workspaceRoot={item.workspaceRoot} workspaceRoot={item.workspaceRoot}
bearerToken={
savedConnectionsById[item.environmentId]?.bearerToken ?? null
}
/> />
</View> </View>
<View className="flex-1"> <View className="flex-1">
+287 -110
View File
@@ -1,32 +1,38 @@
import { useAuth } from "@clerk/expo"; import { useAuth } from "@clerk/expo";
import { Stack, useRouter } from "expo-router"; import { Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols"; import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts"; import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; import { useCallback, useState } from "react";
import * as Effect from "effect/Effect"; import {
import { useCallback, useMemo, useState } from "react"; ActivityIndicator,
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native"; Pressable,
ScrollView,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText"; import { AppText as Text } from "../../components/AppText";
import { connectCloudEnvironment } from "../../features/cloud/linkEnvironment";
import { import {
hasCloudPublicConfig, type RelayEnvironmentView,
resolveRelayClerkTokenOptions, useConnectionController,
} from "../../features/cloud/publicConfig"; } from "../../features/connection/useConnectionController";
import { import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
useManagedRelayEnvironments, import { availableCloudEnvironmentPresentation } from "../../features/cloud/cloudEnvironmentPresentation";
useManagedRelayEnvironmentStatus,
} from "../../features/cloud/managedRelayState";
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow"; import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
import { ConnectionStatusDot } from "../../features/connection/ConnectionStatusDot";
import { splitEnvironmentSections } from "../../features/connection/environmentSections";
import { cn } from "../../lib/cn"; import { cn } from "../../lib/cn";
import { mobileRuntime } from "../../lib/runtime"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor"; import { useThemeColor } from "../../lib/useThemeColor";
import { import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
connectSavedEnvironment, import { useRemoteConnections } from "../../state/use-remote-environment-registry";
useRemoteConnections,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
export default function SettingsEnvironmentsRouteScreen() { export default function SettingsEnvironmentsRouteScreen() {
const { const {
@@ -37,7 +43,11 @@ export default function SettingsEnvironmentsRouteScreen() {
} = useRemoteConnections(); } = useRemoteConnections();
const router = useRouter(); const router = useRouter();
const insets = useSafeAreaInsets(); 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 [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const accentColor = useThemeColor("--color-icon-muted"); const accentColor = useThemeColor("--color-icon-muted");
@@ -69,9 +79,9 @@ export default function SettingsEnvironmentsRouteScreen() {
paddingTop: 16, paddingTop: 16,
}} }}
> >
{hasEnvironments ? ( {hasLocalEnvironments ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card"> <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{connectedEnvironments.map((environment, index) => ( {localEnvironments.map((environment, index) => (
<View <View
key={environment.environmentId} key={environment.environmentId}
collapsable={false} collapsable={false}
@@ -108,54 +118,43 @@ export default function SettingsEnvironmentsRouteScreen() {
</View> </View>
)} )}
{hasCloudPublicConfig() ? <ConfiguredCloudEnvironmentRows /> : null} {hasCloudPublicConfig() ? (
<ConfiguredCloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
/>
) : null}
</ScrollView> </ScrollView>
</View> </View>
); );
} }
function ConfiguredCloudEnvironmentRows() { function ConfiguredCloudEnvironmentRows(props: {
const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
const { savedConnectionsById } = useRemoteEnvironmentState(); readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
const cloudEnvironmentsState = useManagedRelayEnvironments(); }) {
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>( const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
null, const controller = useConnectionController();
);
const iconColor = useThemeColor("--color-icon"); const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = useMemo( const availableCloudEnvironments = controller.availableRelayEnvironments;
() => const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
(cloudEnvironmentsState.data ?? []).filter( const hasCloudRows =
(environment) => savedConnectionsById[environment.environmentId] === undefined, props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
),
[cloudEnvironmentsState.data, savedConnectionsById],
);
const handleConnectCloudEnvironment = useCallback( const handleConnectCloudEnvironment = useCallback(
async (environment: RelayClientEnvironmentRecord) => { (entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
setConnectingCloudEnvironmentId(environment.environmentId); [controller],
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],
); );
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
if (!isSignedIn) return null; if (!isSignedIn) return null;
return ( return (
@@ -164,11 +163,13 @@ function ConfiguredCloudEnvironmentRows() {
<Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text> <Text className="text-[13px] font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable <Pressable
accessibilityRole="button" accessibilityRole="button"
disabled={cloudEnvironmentsState.isPending} disabled={controller.relayDiscovery.isRefreshing}
onPress={cloudEnvironmentsState.refresh} onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50" 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" /> <ActivityIndicator color={iconColor} size="small" />
) : ( ) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" /> <SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
@@ -176,33 +177,48 @@ function ConfiguredCloudEnvironmentRows() {
</Pressable> </Pressable>
</View> </View>
{availableCloudEnvironments.length > 0 ? ( {hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card"> <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{availableCloudEnvironments.map((environment, index) => ( {props.connectedCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow <ConnectedCloudEnvironmentRow
key={environment.environmentId} key={environment.environmentId}
environment={environment} environment={environment}
borderTop={index !== 0} 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)} onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/> />
))} ))}
</View> </View>
) : cloudEnvironmentsState.data === null ? ( ) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6"> <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} /> <ActivityIndicator color={iconColor} />
<Text className="text-center text-[14px] leading-[20px] text-foreground-muted"> <Text className="text-center text-[14px] leading-[20px] text-foreground-muted">
Loading linked cloud environments. Loading linked cloud environments.
</Text> </Text>
</View> </View>
) : cloudEnvironmentsState.error ? ( ) : controller.relayDiscovery.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5"> <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-[15px] font-t3-bold text-foreground"> <Text className="text-[15px] font-t3-bold text-foreground">
Could not load T3 Cloud environments Could not load T3 Cloud environments
</Text> </Text>
<Text className="text-[13px] leading-[18px] text-foreground-muted"> <Text className="text-[13px] leading-[18px] text-foreground-muted">
{cloudEnvironmentsState.error} {controller.relayDiscovery.error}
</Text> </Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View> </View>
) : ( ) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5"> <View collapsable={false} className="rounded-[24px] bg-card p-5">
@@ -215,23 +231,124 @@ function ConfiguredCloudEnvironmentRows() {
); );
} }
function CloudEnvironmentRow(props: { function ConnectedCloudEnvironmentRow(props: {
readonly environment: RelayClientEnvironmentRecord; readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean; readonly borderTop: boolean;
readonly isConnecting: boolean; readonly errorExpanded: boolean;
readonly onConnect: () => void; readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) { }) {
const mutedColor = useThemeColor("--color-icon-muted"); return (
const statusState = useManagedRelayEnvironmentStatus(props.environment); <CloudEnvironmentRowShell
const status = statusState.data; borderTop={props.borderTop}
const disabled = props.isConnecting; connectionError={props.environment.connectionError}
const statusText = connectionErrorTraceId={props.environment.connectionErrorTraceId}
status === null connectionState={props.environment.connectionState}
? (statusState.error ?? (statusState.isPending ? "Checking status..." : "Status unavailable")) errorExpanded={props.errorExpanded}
: status.status === "online" label={props.environment.environmentLabel}
? "Online" onValueChange={(enabled) => {
: (status.error ?? "Offline"); if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
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 ( return (
<View <View
collapsable={false} collapsable={false}
@@ -240,36 +357,96 @@ function CloudEnvironmentRow(props: {
props.borderTop && "border-t border-border", 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"> <View className="min-w-0 flex-1 gap-0.5">
<Text className="text-[16px] font-t3-bold leading-[21px] text-foreground" numberOfLines={1}> <View className="min-w-0 flex-row items-center gap-2">
{props.environment.label} <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
</Text> <Text
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}> className="min-w-0 flex-shrink text-[16px] font-t3-bold leading-[21px] text-foreground"
{props.environment.endpoint.httpBaseUrl} numberOfLines={1}
</Text> >
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}> {props.label}
{statusText} </Text>
</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> </View>
<Pressable <Switch
accessibilityRole="button" disabled={props.disabled}
disabled={disabled} ios_backgroundColor={track}
onPress={props.onConnect} onValueChange={props.onValueChange}
className="min-h-[40px] min-w-[88px] items-center justify-center rounded-[14px] bg-primary px-4 active:opacity-70 disabled:opacity-50" trackColor={{ false: track, true: activeTrack }}
> value={props.value}
<Text className="text-[13px] font-t3-bold text-primary-foreground"> />
{props.isConnecting ? "Connecting" : "Connect"}
</Text>
</Pressable>
</View> </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 { Alert, Linking, Pressable, ScrollView, Switch, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context"; 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 { AppText as Text } from "../../components/AppText";
import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences"; import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences";
import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions"; import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions";
@@ -18,10 +25,10 @@ import {
hasCloudPublicConfig, hasCloudPublicConfig,
resolveRelayClerkTokenOptions, resolveRelayClerkTokenOptions,
} from "../../features/cloud/publicConfig"; } from "../../features/cloud/publicConfig";
import { mobileRuntime } from "../../lib/runtime"; import { runtime } from "../../lib/runtime";
import { loadPreferences } from "../../lib/storage"; import { loadPreferences } from "../../lib/storage";
import { useThemeColor } from "../../lib/useThemeColor"; 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 NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking"; type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
@@ -32,7 +39,7 @@ export default function SettingsRouteScreen() {
function LocalSettingsRouteScreen() { function LocalSettingsRouteScreen() {
const insets = useSafeAreaInsets(); const insets = useSafeAreaInsets();
const { savedConnectionsById } = useRemoteEnvironmentState(); const { savedConnectionsById } = useSavedRemoteConnections();
const environmentCount = Object.keys(savedConnectionsById).length; const environmentCount = Object.keys(savedConnectionsById).length;
return ( return (
@@ -70,7 +77,7 @@ function ConfiguredSettingsRouteScreen() {
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent(); const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser(); const { user } = useUser();
const { savedConnectionsById } = useRemoteEnvironmentState(); const { savedConnectionsById } = useSavedRemoteConnections();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking"); const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking"); const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
@@ -87,8 +94,13 @@ function ConfiguredSettingsRouteScreen() {
setNotificationStatus("unsupported"); setNotificationStatus("unsupported");
return; return;
} }
const permission = await Notifications.getPermissionsAsync(); const result = await settlePromise(() => Notifications.getPermissionsAsync());
setNotificationStatus(permission.granted ? "enabled" : "disabled"); if (result._tag === "Failure") {
reportAtomCommandResult(result, { label: "notification permission refresh" });
setNotificationStatus("disabled");
return;
}
setNotificationStatus(result.value.granted ? "enabled" : "disabled");
}, []); }, []);
useEffect(() => { useEffect(() => {
@@ -104,60 +116,66 @@ function ConfiguredSettingsRouteScreen() {
setLiveActivityStatus("signed-out"); setLiveActivityStatus("signed-out");
return; return;
} }
void loadPreferences().then( void (async () => {
(preferences) => { const result = await settlePromise(() => loadPreferences());
setLiveActivityStatus(preferences.liveActivitiesEnabled === false ? "disabled" : "enabled"); if (result._tag === "Failure") {
}, reportAtomCommandResult(result, { label: "live activity preference load" });
() => {
setLiveActivityStatus("enabled"); setLiveActivityStatus("enabled");
}, return;
); }
setLiveActivityStatus(result.value.liveActivitiesEnabled === false ? "disabled" : "enabled");
})();
}, [isLoaded, isSignedIn]); }, [isLoaded, isSignedIn]);
const requestNotifications = useCallback(async () => { const requestNotifications = useCallback(async () => {
try { const result = await settleAsyncResult(() =>
const result = await mobileRuntime.runPromise( runtime.runPromiseExit(
requestAgentNotificationPermission.pipe( requestAgentNotificationPermission.pipe(
Effect.tap((permission) => Effect.tap((permission) =>
permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void, permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,
), ),
), ),
); ),
if (result.type === "granted") { );
setNotificationStatus("enabled"); if (result._tag === "Failure") {
Alert.alert( if (!isAtomCommandInterrupted(result)) {
"Notifications enabled", const error = squashAtomCommandFailure(result);
"Live Activity notifications are enabled for this device.",
);
return;
}
if (result.type === "unsupported") {
setNotificationStatus("unsupported");
Alert.alert( Alert.alert(
"Notifications unavailable", "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( Alert.alert(
"Notifications disabled", "Notifications enabled",
"Notifications were denied for this app. Open Settings to enable them.", "Live Activity notifications are enabled for this device.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
); );
} catch (error) { return;
}
if (result.value.type === "unsupported") {
setNotificationStatus("unsupported");
Alert.alert( Alert.alert(
"Notifications unavailable", "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(() => { const promptSignIn = useCallback(() => {
@@ -178,36 +196,51 @@ function ConfiguredSettingsRouteScreen() {
} }
setLiveActivityStatus("linking"); setLiveActivityStatus("linking");
try { const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
const token = await getToken(resolveRelayClerkTokenOptions()); if (tokenResult._tag === "Failure") {
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) {
setLiveActivityStatus("disabled"); setLiveActivityStatus("disabled");
const error = squashAtomCommandFailure(tokenResult);
Alert.alert( Alert.alert(
"Live Activities unavailable", "Live Activities unavailable",
error instanceof Error ? error.message : "Could not enable Live Activity updates.", 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]); }, [connections, environmentCount, getToken, isSignedIn, promptSignIn]);
const handleDeviceNotificationsChange = useCallback( const handleDeviceNotificationsChange = useCallback(
@@ -234,19 +267,36 @@ function ConfiguredSettingsRouteScreen() {
if (!enabled) { if (!enabled) {
setLiveActivityStatus("disabled"); setLiveActivityStatus("disabled");
void (async () => { void (async () => {
try { let token: string | null = null;
const token = isSignedIn ? await getToken(resolveRelayClerkTokenOptions()) : null; if (isSignedIn) {
await mobileRuntime.runPromise( 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({ setLiveActivityUpdatesEnabled({
enabled: false, enabled: false,
clerkToken: token, clerkToken: token,
connections, connections,
}), }),
); ),
refreshManagedRelayEnvironments(); );
} catch { if (updateResult._tag === "Failure") {
// The switch is optimistic; a future refresh reconciles relay state. reportAtomCommandResult(updateResult, {
label: "live activity disable",
});
return;
} }
refreshManagedRelayEnvironments();
})(); })();
return; return;
} }
@@ -382,15 +432,20 @@ function SettingsRow(props: {
style={{ opacity: props.disabled ? 0.45 : 1 }} style={{ opacity: props.disabled ? 0.45 : 1 }}
> >
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" /> <SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="flex-1 text-[17px] text-foreground">{props.label}</Text> <Text className="shrink-0 text-[17px] text-foreground" numberOfLines={1}>
{props.value ? ( {props.label}
<Text </Text>
className="max-w-[180px] text-right text-[16px] text-foreground-muted" <View className="min-w-0 flex-1 items-end">
numberOfLines={1} {props.value ? (
> <Text
{props.value} className="max-w-[180px] text-right text-[16px] text-foreground-muted"
</Text> ellipsizeMode="middle"
) : null} numberOfLines={1}
>
{props.value}
</Text>
) : null}
</View>
<SymbolView <SymbolView
name="chevron.right" name="chevron.right"
size={16} size={16}
+45 -24
View File
@@ -1,65 +1,86 @@
import { SymbolView } from "expo-symbols"; import { SymbolView } from "expo-symbols";
import { useState } from "react"; import { useState } from "react";
import { Image, View } from "react-native"; import { Image, View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { useThemeColor } from "../lib/useThemeColor"; import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */ /* ─── Favicon cache (matches web pattern) ────────────────────────────── */
const loadedFaviconUrls = new Set<string>(); const loadedFaviconUrls = new Set<string>();
/* ─── Component ──────────────────────────────────────────────────────── */ /* ─── Component ──────────────────────────────────────────────────────── */
export function ProjectFavicon(props: { export function ProjectFavicon(props: {
readonly environmentId: EnvironmentId;
readonly size?: number; readonly size?: number;
readonly projectTitle: string; readonly projectTitle: string;
readonly httpBaseUrl?: string | null;
readonly workspaceRoot?: string | null; readonly workspaceRoot?: string | null;
readonly bearerToken?: string | null;
}) { }) {
const size = props.size ?? 42; const size = props.size ?? 42;
const iconMuted = useThemeColor("--color-icon-subtle"); const faviconUrl = useAssetUrl(
props.environmentId,
const faviconUrl = props.workspaceRoot === null || props.workspaceRoot === undefined
props.httpBaseUrl && props.workspaceRoot ? null
? `${props.httpBaseUrl}/api/project-favicon?cwd=${encodeURIComponent(props.workspaceRoot)}` : { _tag: "project-favicon", cwd: props.workspaceRoot },
: null;
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
faviconUrl && loadedFaviconUrls.has(faviconUrl) ? "loaded" : "loading",
); );
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 ( return (
<View <View
style={{ style={{
width: size, width: props.size,
height: size, height: props.size,
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
}} }}
> >
{/* Folder icon fallback (matches web's FolderIcon) */} {/* Folder icon fallback (matches web's FolderIcon) */}
{!showImage ? ( {!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} ) : null}
{/* Favicon image (hidden until loaded) */} {/* Favicon image (hidden until loaded) */}
{faviconUrl ? ( {props.faviconUrl ? (
<Image <Image
source={{ source={{
uri: faviconUrl, uri: props.faviconUrl,
...(props.bearerToken
? { headers: { Authorization: `Bearer ${props.bearerToken}` } }
: {}),
}} }}
accessibilityLabel={`${props.projectTitle} favicon`}
style={{ style={{
width: size, width: props.size,
height: size, height: props.size,
borderRadius: size * 0.16, borderRadius: props.size * 0.16,
...(showImage ? {} : { position: "absolute" as const, opacity: 0 }), ...(showImage ? {} : { position: "absolute" as const, opacity: 0 }),
}} }}
resizeMode="contain" resizeMode="contain"
onLoad={() => { onLoad={() => {
if (faviconUrl) loadedFaviconUrls.add(faviconUrl); if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
setStatus("loaded"); setStatus("loaded");
}} }}
onError={() => setStatus("error")} 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 { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts"; 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 { HttpClient } from "effect/unstable/http";
import type { SavedRemoteConnection } from "../../lib/connection"; import type { SavedRemoteConnection } from "../../lib/connection";
@@ -33,90 +34,85 @@ const connection: SavedRemoteConnection = {
bearerToken: "local-bearer", bearerToken: "local-bearer",
}; };
const runWithHttpClient = <A, E>( const testLayer = Layer.mergeAll(
effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient>, Layer.succeed(ManagedRelayClient, null as never),
): Promise<A> => Layer.succeed(
Effect.runPromise( HttpClient.HttpClient,
effect.pipe( HttpClient.make(() => Effect.die("unexpected HTTP request")),
Effect.provideService(ManagedRelayClient, null as never), ),
Effect.provideService( );
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
),
);
describe("liveActivityPreferences", () => { describe("liveActivityPreferences", () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
it("pushes disabled Live Activity preferences to relay registrations", async () => { it.effect("pushes disabled Live Activity preferences to relay registrations", () =>
await runWithHttpClient( Effect.gen(function* () {
setLiveActivityUpdatesEnabled({ yield* setLiveActivityUpdatesEnabled({
enabled: false, enabled: false,
clerkToken: "clerk-token", clerkToken: "clerk-token",
connections: [connection], connections: [connection],
}), });
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false }); expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token", clerkToken: "clerk-token",
connection, connection,
}); });
}); }).pipe(Effect.provide(testLayer)),
);
it("pushes enabled Live Activity preferences to relay registrations", async () => { it.effect("pushes enabled Live Activity preferences to relay registrations", () =>
await runWithHttpClient( Effect.gen(function* () {
setLiveActivityUpdatesEnabled({ yield* setLiveActivityUpdatesEnabled({
enabled: true, enabled: true,
clerkToken: "clerk-token", clerkToken: "clerk-token",
connections: [connection], connections: [connection],
}), });
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true }); expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: true });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token", clerkToken: "clerk-token",
connection, connection,
}); });
}); }).pipe(Effect.provide(testLayer)),
);
it("keeps local preferences refreshable when signed out", async () => { it.effect("keeps local preferences refreshable when signed out", () =>
await runWithHttpClient( Effect.gen(function* () {
setLiveActivityUpdatesEnabled({ yield* setLiveActivityUpdatesEnabled({
enabled: false, enabled: false,
clerkToken: null, clerkToken: null,
connections: [connection], connections: [connection],
}), });
);
expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false }); expect(savePreferencesPatch).toHaveBeenCalledWith({ liveActivitiesEnabled: false });
expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1); expect(refreshAgentAwarenessRegistration).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).not.toHaveBeenCalled(); 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 = { const managedConnection: SavedRemoteConnection = {
...connection, ...connection,
bearerToken: null, bearerToken: null,
}; };
await runWithHttpClient( return Effect.gen(function* () {
setLiveActivityUpdatesEnabled({ yield* setLiveActivityUpdatesEnabled({
enabled: true, enabled: true,
clerkToken: "clerk-token", clerkToken: "clerk-token",
connections: [connection, managedConnection], connections: [connection, managedConnection],
}), });
);
expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1); expect(linkEnvironmentToCloud).toHaveBeenCalledTimes(1);
expect(linkEnvironmentToCloud).toHaveBeenCalledWith({ expect(linkEnvironmentToCloud).toHaveBeenCalledWith({
clerkToken: "clerk-token", clerkToken: "clerk-token",
connection, connection,
}); });
}).pipe(Effect.provide(testLayer));
}); });
}); });
@@ -1,6 +1,6 @@
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import { HttpClient } from "effect/unstable/http"; 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 type { SavedRemoteConnection } from "../../lib/connection";
import { savePreferencesPatch } from "../../lib/storage"; import { savePreferencesPatch } from "../../lib/storage";
@@ -1,6 +1,6 @@
import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay"; import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
import type { MobilePreferences } from "../../lib/storage"; import type { Preferences } from "../../lib/storage";
export function makeRelayDeviceRegistrationRequest(input: { export function makeRelayDeviceRegistrationRequest(input: {
readonly deviceId: string; readonly deviceId: string;
@@ -10,7 +10,7 @@ export function makeRelayDeviceRegistrationRequest(input: {
readonly pushToken?: string; readonly pushToken?: string;
readonly pushToStartToken?: string; readonly pushToStartToken?: string;
readonly notificationsEnabled: boolean; readonly notificationsEnabled: boolean;
readonly preferences: MobilePreferences; readonly preferences: Preferences;
}): RelayDeviceRegistrationRequest { }): RelayDeviceRegistrationRequest {
const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false; const liveActivitiesEnabled = input.preferences.liveActivitiesEnabled !== false;
return { return {
@@ -6,15 +6,16 @@ import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest"; import { describe, expect, it } from "@effect/vitest";
import Constants from "expo-constants"; import Constants from "expo-constants";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http"; 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 type { EnvironmentId } from "@t3tools/contracts";
import { verifyDpopProof } from "@t3tools/shared/dpop"; import { verifyDpopProof } from "@t3tools/shared/dpop";
import type { SavedRemoteConnection } from "../../lib/connection"; import type { SavedRemoteConnection } from "../../lib/connection";
import { mobileCryptoLayer } from "../cloud/dpop"; import { cryptoLayer } from "../cloud/dpop";
import { mobileManagedRelayClientLayer } from "../cloud/managedRelayLayer"; import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload"; import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import { import {
__resetAgentAwarenessRemoteRegistrationForTest, __resetAgentAwarenessRemoteRegistrationForTest,
@@ -33,6 +34,12 @@ const secureStore = vi.hoisted(() => new Map<string, string>());
const widgetMocks = vi.hoisted(() => ({ const widgetMocks = vi.hoisted(() => ({
getInstances: vi.fn(() => []), 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", () => ({ vi.mock("expo-constants", () => ({
default: { default: {
@@ -95,17 +102,11 @@ vi.mock("react-native", () => ({
})); }));
vi.mock("../../lib/runtime", () => ({ vi.mock("../../lib/runtime", () => ({
mobileRuntime: { runtime: {
runPromise: <A, E>(operation: Effect.Effect<A, E>) => runPromiseExit: (operation: unknown) =>
Effect.runPromise( new Promise((resolve) => {
operation.pipe( backgroundRuntime.pending.push({ operation, resolve });
Effect.provide( }),
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
),
}, },
})); }));
@@ -138,34 +139,40 @@ function savedConnection(): SavedRemoteConnection {
}; };
} }
const runRegistrationEffect = <A, E>(effect: Effect.Effect<A, E, ManagedRelayClient>): Promise<A> => const relayTestLayer = managedRelayClientLayer("https://relay.example.test").pipe(
Effect.runPromise( Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cryptoLayer)),
effect.pipe( );
Effect.provide(
mobileManagedRelayClientLayer("https://relay.example.test").pipe(
Layer.provide(Layer.mergeAll(FetchHttpClient.layer, mobileCryptoLayer)),
),
),
),
);
async function waitForFetchCalls( const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
fetchMock: ReturnType<typeof vi.fn>, function* () {
count: number, let idlePasses = 0;
): Promise<void> { for (;;) {
for (let attempt = 0; attempt < 20; attempt += 1) { yield* Effect.promise(() => Promise.resolve());
if (fetchMock.mock.calls.length >= count) { const pending = backgroundRuntime.pending.shift();
return; 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", () => { describe("makeRelayDeviceRegistrationRequest", () => {
beforeEach(() => { beforeEach(() => {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
vi.stubGlobal("__DEV__", false); vi.stubGlobal("__DEV__", false);
secureStore.clear(); secureStore.clear();
backgroundRuntime.pending.length = 0;
Constants.expoConfig!.extra = {}; Constants.expoConfig!.extra = {};
__resetAgentAwarenessRemoteRegistrationForTest(); __resetAgentAwarenessRemoteRegistrationForTest();
widgetMocks.getInstances.mockReset(); widgetMocks.getInstances.mockReset();
@@ -243,7 +250,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull(); 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()); registerAgentAwarenessConnection(savedConnection());
const addPushTokenListener = vi.fn(); const addPushTokenListener = vi.fn();
const activity = { const activity = {
@@ -251,56 +258,64 @@ describe("makeRelayDeviceRegistrationRequest", () => {
addPushTokenListener, addPushTokenListener,
}; };
await expect( return Effect.gen(function* () {
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })), expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
).resolves.toBe(false); expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
await expect(
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
expect(activity.getPushToken).toHaveBeenCalledTimes(2); expect(activity.getPushToken).toHaveBeenCalledTimes(2);
expect(addPushTokenListener).toHaveBeenCalledTimes(1); 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()); registerAgentAwarenessConnection(savedConnection());
const activity = { return Effect.gen(function* () {
getPushToken: vi.fn(() => Promise.resolve("activity-token")), yield* runBackgroundOperations();
addPushTokenListener: vi.fn(), vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
};
await expect( yield* refreshAgentAwarenessRegistration();
runRegistrationEffect(registerLiveActivityPushToken({ activity: activity as never })),
).resolves.toBe(false);
});
it("registers APNS-started Live Activities for relay updates without mutating them locally", async () => { expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
const activity = { }).pipe(Effect.provide(relayTestLayer));
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);
}); });
it.effect("registers the APNs device when cloud auth becomes available", () => { it.effect("registers the APNs device when cloud auth becomes available", () => {
@@ -330,7 +345,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () { return Effect.gen(function* () {
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2)); yield* runBackgroundOperations();
expect(fetchMock).toHaveBeenCalledTimes(2); expect(fetchMock).toHaveBeenCalledTimes(2);
const [request, init] = fetchMock.mock.calls[1] as unknown as [ const [request, init] = fetchMock.mock.calls[1] as unknown as [
@@ -357,7 +372,65 @@ describe("makeRelayDeviceRegistrationRequest", () => {
nowEpochSeconds: proofIat(dpop), nowEpochSeconds: proofIat(dpop),
}), }),
).toMatchObject({ ok: true }); ).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", () => { it("only registers again when the authenticated identity changes", () => {
@@ -367,7 +440,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true); 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 fetchMock = vi.fn((request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request); const url = request instanceof Request ? request.url : String(request);
return Promise.resolve( return Promise.resolve(
@@ -398,9 +471,10 @@ describe("makeRelayDeviceRegistrationRequest", () => {
expect(tokenListener).toBeDefined(); expect(tokenListener).toBeDefined();
tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never); tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
await new Promise((resolve) => setTimeout(resolve, 0)); return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1); expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(relayTestLayer));
}); });
it.effect( it.effect(
@@ -432,13 +506,13 @@ describe("makeRelayDeviceRegistrationRequest", () => {
registerAgentAwarenessConnection(savedConnection()); registerAgentAwarenessConnection(savedConnection());
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
return Effect.gen(function* () { return Effect.gen(function* () {
yield* Effect.promise(() => waitForFetchCalls(fetchMock, 2)); yield* runBackgroundOperations();
fetchMock.mockClear(); fetchMock.mockClear();
unregisterAgentAwarenessConnection(savedConnection().environmentId); unregisterAgentAwarenessConnection(savedConnection().environmentId);
expect(fetchMock).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled();
}); }).pipe(Effect.provide(relayTestLayer));
}, },
); );
}); });
@@ -8,10 +8,16 @@ import {
type RelayDeviceRegistrationRequest, type RelayDeviceRegistrationRequest,
type RelayLiveActivityRegistrationRequest, type RelayLiveActivityRegistrationRequest,
} from "@t3tools/contracts/relay"; } 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 type { SavedRemoteConnection } from "../../lib/connection";
import { mobileRuntime } from "../../lib/runtime"; import { runtime } from "../../lib/runtime";
import { import {
loadAgentAwarenessDeviceId, loadAgentAwarenessDeviceId,
loadOrCreateAgentAwarenessDeviceId, loadOrCreateAgentAwarenessDeviceId,
@@ -29,6 +35,20 @@ let pushTokenSubscription: { remove: () => void } | null = null;
let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null; let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
let relayTokenProvider: (() => Promise<string | null>) | null = null; let relayTokenProvider: (() => Promise<string | null>) | null = null;
let relayTokenProviderIdentity: string | 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( export function normalizeAgentAwarenessRelayBaseUrl(
value: string | null | undefined, value: string | null | undefined,
@@ -68,6 +88,11 @@ export function setAgentAwarenessRelayTokenProvider(
const isExistingIdentity = const isExistingIdentity =
provider !== null && provider !== null &&
!shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity); !shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);
if (!isExistingIdentity) {
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
}
relayTokenProvider = provider; relayTokenProvider = provider;
relayTokenProviderIdentity = provider ? (identity ?? null) : null; relayTokenProviderIdentity = provider ? (identity ?? null) : null;
if (!provider) { if (!provider) {
@@ -90,7 +115,7 @@ export function setAgentAwarenessRelayTokenProvider(
if (isExistingIdentity) { if (isExistingIdentity) {
return; return;
} }
runRegistrationInBackground(registerDevice(), "device registration after cloud sign-in failed"); enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
} }
function iosMajorVersion(): number { function iosMajorVersion(): number {
@@ -149,20 +174,41 @@ const relayToken = Effect.gen(function* () {
function registerDeviceWithRelay( function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest, body: RelayDeviceRegistrationRequest,
expectedGeneration: number,
): Effect.Effect<void, unknown, ManagedRelayClient> { ): Effect.Effect<void, unknown, ManagedRelayClient> {
return Effect.gen(function* () { return Effect.gen(function* () {
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled before relay request", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
if (!readRelayConfig()) return; if (!readRelayConfig()) return;
const token = yield* relayToken; const token = yield* relayToken;
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
expectedGeneration,
currentGeneration: deviceRegistrationGeneration,
});
return;
}
if (!token) { if (!token) {
logRegistrationDebug("relay device registration skipped; user is not signed in"); logRegistrationDebug("relay device registration skipped; user is not signed in");
return; return;
} }
const client = yield* ManagedRelayClient; const client = yield* ManagedRelayClient;
logRegistrationDebug("relay device registration request started", {
expectedGeneration,
});
yield* client.registerDevice({ yield* client.registerDevice({
clerkToken: token, clerkToken: token,
payload: body, payload: body,
}); });
logRegistrationDebug("relay device registration request completed", {
expectedGeneration,
});
}); });
} }
@@ -213,10 +259,11 @@ function logRegistrationError(context: string, error: unknown): void {
if (!__DEV__) { if (!__DEV__) {
return; return;
} }
console.warn( console.warn(`[agent-awareness] ${context}`, {
`[agent-awareness] ${context}`, message: error instanceof Error ? error.message : String(error),
error instanceof Error ? error.message : String(error), traceId: findErrorTraceId(error),
); error,
});
} }
function logRegistrationDebug(context: string, details?: unknown): void { function logRegistrationDebug(context: string, details?: unknown): void {
@@ -230,20 +277,107 @@ function runRegistrationInBackground(
operation: Effect.Effect<unknown, unknown, ManagedRelayClient>, operation: Effect.Effect<unknown, unknown, ManagedRelayClient>,
context: string, context: string,
): void { ): void {
void mobileRuntime.runPromise(operation).catch((error: unknown) => { void (async () => {
logRegistrationError(context, error); const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
}); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
logRegistrationError(context, squashAtomCommandFailure(result));
}
})();
} }
function registerDevice(input?: { function mergeDeviceRegistrationInput(
readonly pushToStartToken?: string; current: DeviceRegistrationInput,
readonly observedPushToken?: string; next: DeviceRegistrationInput,
}): Effect.Effect<void, unknown, ManagedRelayClient> { ): 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* () { return Effect.gen(function* () {
if (!canRegisterRemoteLiveActivities()) { if (!canRegisterRemoteLiveActivities()) {
logRegistrationDebug("device registration skipped; platform does not support it");
return; return;
} }
logRegistrationDebug("device registration loading local state", { expectedGeneration });
const [deviceId, preferences] = yield* Effect.all([ const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({ Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(), try: () => loadOrCreateAgentAwarenessDeviceId(),
@@ -255,6 +389,10 @@ function registerDevice(input?: {
}), }),
]); ]);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken); const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
logRegistrationDebug("device registration local state ready", {
expectedGeneration,
notificationsEnabled: pushTokenRegistration.notificationsEnabled,
});
yield* registerDeviceWithRelay( yield* registerDeviceWithRelay(
makeRelayDeviceRegistrationRequest({ makeRelayDeviceRegistrationRequest({
deviceId, deviceId,
@@ -266,6 +404,7 @@ function registerDevice(input?: {
notificationsEnabled: pushTokenRegistration.notificationsEnabled, notificationsEnabled: pushTokenRegistration.notificationsEnabled,
preferences, preferences,
}), }),
expectedGeneration,
); );
}); });
} }
@@ -277,10 +416,7 @@ function registerDeviceForCurrentUser(
} }
function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void { function registerPushToStartTokenForCurrentUser(pushToStartToken: string): void {
runRegistrationInBackground( enqueueDeviceRegistration({ pushToStartToken }, "push-to-start token registration failed");
registerDeviceForCurrentUser(pushToStartToken),
"push-to-start token registration failed",
);
} }
function ensurePushToStartListener(): void { function ensurePushToStartListener(): void {
@@ -303,8 +439,8 @@ function ensurePushTokenListener(): void {
pushTokenSubscription = Notifications.addPushTokenListener((token) => { pushTokenSubscription = Notifications.addPushTokenListener((token) => {
if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) { if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) {
runRegistrationInBackground( enqueueDeviceRegistration(
registerDevice({ observedPushToken: token.data.trim() }), { observedPushToken: token.data.trim() },
"native APNs token rotation registration failed", "native APNs token rotation registration failed",
); );
} }
@@ -319,7 +455,7 @@ export function registerAgentAwarenessConnection(connection: SavedRemoteConnecti
environmentConnections.set(connection.environmentId, connection); environmentConnections.set(connection.environmentId, connection);
ensurePushToStartListener(); ensurePushToStartListener();
ensurePushTokenListener(); ensurePushTokenListener();
runRegistrationInBackground(registerDevice(), "device registration failed"); enqueueDeviceRegistration({}, "device registration failed");
runRegistrationInBackground( runRegistrationInBackground(
refreshActiveLiveActivityRemoteRegistration(), refreshActiveLiveActivityRemoteRegistration(),
"active live activity registration after environment connection failed", "active live activity registration after environment connection failed",
@@ -372,6 +508,9 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
} }
relayTokenProvider = null; relayTokenProvider = null;
relayTokenProviderIdentity = null; relayTokenProviderIdentity = null;
deviceRegistrationGeneration++;
activeDeviceRegistration = null;
pendingDeviceRegistration = null;
} }
export function unregisterAgentAwarenessDeviceForCurrentUser( 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 { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache"; 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 { 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 { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import { import {
setAgentAwarenessRelayTokenProvider, setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser, unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration"; } from "../agent-awareness/remoteRegistration";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig"; 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 }) { function CloudAuthBridge(props: { readonly children: ReactNode }) {
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false }); const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
reportFailure: false,
reportDefect: false,
});
const previousTokenProviderRef = useRef<{ const previousTokenProviderRef = useRef<{
readonly userId: string; readonly userId: string;
readonly provider: () => Promise<string | null>; readonly provider: () => Promise<string | null>;
} | null>(null); } | null>(null);
const observedAccountRef = useRef<string | null | undefined>(undefined);
const accountTransitionRef = useRef<Promise<void> | null>(null);
useEffect(() => { useEffect(() => {
let cancelled = false;
if (!isLoaded) { if (!isLoaded) {
return; 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) { if (!isSignedIn || !userId) {
const previous = previousTokenProviderRef.current; const previous = previousTokenProviderRef.current;
previousTokenProviderRef.current = null; previousTokenProviderRef.current = null;
if (previous) { deactivateCloudRelayAccount();
void mobileRuntime if (previousObservedAccount !== null) {
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider)) void queueAccountCleanup(previous);
.catch(() => undefined);
} }
setAgentAwarenessRelayTokenProvider(null);
setManagedRelaySession(appAtomRegistry, null);
return; return;
} }
const previous = previousTokenProviderRef.current; const previous = previousTokenProviderRef.current;
if (previous && previous.userId !== userId) {
void mobileRuntime
.runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))
.catch(() => undefined);
}
const tokenProvider = () => getToken(resolveRelayClerkTokenOptions()); const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
previousTokenProviderRef.current = { userId, provider: tokenProvider }; const activateSession = () => {
setAgentAwarenessRelayTokenProvider(tokenProvider, userId); if (cancelled) {
setManagedRelaySession( return;
appAtomRegistry, }
createManagedRelaySession({ previousTokenProviderRef.current = { userId, provider: tokenProvider };
accountId: userId, activateCloudRelayAccount(userId, tokenProvider);
readClerkToken: tokenProvider, };
}), const activateAfterTransition = (transition: Promise<void>) => {
); void (async () => {
}, [getToken, isLoaded, isSignedIn, userId]); 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( useEffect(
() => () => { () => () => {
previousTokenProviderRef.current = null; previousTokenProviderRef.current = null;
setAgentAwarenessRelayTokenProvider(null); deactivateCloudRelayAccount();
setManagedRelaySession(appAtomRegistry, null);
}, },
[], [],
); );
@@ -72,8 +158,7 @@ export function CloudAuthProvider(props: { readonly children: ReactNode }) {
useEffect(() => { useEffect(() => {
if (!publishableKey || !relayUrl) { if (!publishableKey || !relayUrl) {
setAgentAwarenessRelayTokenProvider(null); deactivateCloudRelayAccount();
setManagedRelaySession(appAtomRegistry, null);
} }
}, [publishableKey, relayUrl]); }, [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, createDpopProof,
generateDpopProofKeyPair, generateDpopProofKeyPair,
loadOrCreateDpopProofKeyPair, loadOrCreateDpopProofKeyPair,
mobileCryptoLayer, cryptoLayer,
} from "./dpop"; } from "./dpop";
vi.mock("expo-crypto", () => ({ vi.mock("expo-crypto", () => ({
@@ -75,7 +75,7 @@ describe("mobile DPoP", () => {
expect(Buffer.from(digest).toString("hex")).toBe( expect(Buffer.from(digest).toString("hex")).toBe(
NodeCrypto.createHash("sha256").update("typed-array").digest("hex"), 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", () => it.effect("persists and reuses the installation proof key", () =>
@@ -86,7 +86,7 @@ describe("mobile DPoP", () => {
expect(second.thumbprint).toBe(first.thumbprint); expect(second.thumbprint).toBe(first.thumbprint);
expect(second.privateJwk).toEqual(first.privateJwk); expect(second.privateJwk).toEqual(first.privateJwk);
}).pipe(Effect.provide(mobileCryptoLayer)), }).pipe(Effect.provide(cryptoLayer)),
); );
it.effect("rejects malformed persisted proof keys", () => it.effect("rejects malformed persisted proof keys", () =>
@@ -96,7 +96,7 @@ describe("mobile DPoP", () => {
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip); const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
expect(error.message).toBe("Stored DPoP proof key is invalid."); 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", () => it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () =>
@@ -135,7 +135,7 @@ describe("mobile DPoP", () => {
nowEpochSeconds: proofIat(bootstrap.proof), nowEpochSeconds: proofIat(bootstrap.proof),
}), }),
).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint }); ).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
}).pipe(Effect.provide(mobileCryptoLayer)), }).pipe(Effect.provide(cryptoLayer)),
); );
it.effect("signs DPoP proofs with RFC 9449 htu normalization", () => it.effect("signs DPoP proofs with RFC 9449 htu normalization", () =>
@@ -161,6 +161,6 @@ describe("mobile DPoP", () => {
nowEpochSeconds: proofIat(proof.proof), nowEpochSeconds: proofIat(proof.proof),
}), }),
).toMatchObject({ ok: true }); ).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.Crypto,
Crypto.make({ Crypto.make({
randomBytes: ExpoCrypto.getRandomBytes, randomBytes: ExpoCrypto.getRandomBytes,
@@ -8,8 +8,8 @@ import {
managedRelayClientLayer, managedRelayClientLayer,
ManagedRelayClient, ManagedRelayClient,
ManagedRelayDpopSigner, ManagedRelayDpopSigner,
remoteHttpClientLayer, } from "@t3tools/client-runtime/relay";
} from "@t3tools/client-runtime"; import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { HttpClient } from "effect/unstable/http"; import { HttpClient } from "effect/unstable/http";
import { import {
@@ -55,6 +55,8 @@ const savedConnection = {
bearerToken: "local-bearer", bearerToken: "local-bearer",
}; };
const stableClerkToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzEyMyJ9.test";
const createProofMock = vi.fn( const createProofMock = vi.fn(
(input: { readonly method: string; readonly url: string; readonly accessToken?: string }) => (input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
Effect.succeed(`dpop:${input.method}:${input.url}`), Effect.succeed(`dpop:${input.method}:${input.url}`),
@@ -352,7 +354,7 @@ describe("mobile cloud link environment client", () => {
}); });
vi.stubGlobal("fetch", fetchMock); vi.stubGlobal("fetch", fetchMock);
yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" })); yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: stableClerkToken }));
expect( expect(
fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")), fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),
@@ -425,9 +427,11 @@ describe("mobile cloud link environment client", () => {
yield* withCloudServices( yield* withCloudServices(
Effect.gen(function* () { Effect.gen(function* () {
const records = yield* listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }); const records = yield* listCloudEnvironmentsWithStatus({
clerkToken: stableClerkToken,
});
yield* connectCloudEnvironment({ yield* connectCloudEnvironment({
clerkToken: "clerk-token", clerkToken: stableClerkToken,
environment: records[0]!.environment, environment: records[0]!.environment,
}); });
}), }),
@@ -658,6 +662,7 @@ describe("mobile cloud link environment client", () => {
_tag: "CloudEnvironmentLinkError", _tag: "CloudEnvironmentLinkError",
message: message:
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).", "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); expect(fetchMock).toHaveBeenCalledTimes(3);
}), }),
@@ -1003,6 +1008,7 @@ describe("mobile cloud link environment client", () => {
_tag: "CloudEnvironmentLinkError", _tag: "CloudEnvironmentLinkError",
message: message:
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.", "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, type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
RelayEnvironmentConnectScope, RelayEnvironmentConnectScope,
RelayEnvironmentStatusScope, RelayEnvironmentStatusScope,
RelayProtectedError,
type RelayDpopAccessTokenScope, type RelayDpopAccessTokenScope,
type RelayProtectedError as RelayProtectedErrorType, type RelayProtectedError as RelayProtectedErrorType,
type RelayClientEnvironmentRecord, type RelayClientEnvironmentRecord,
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType, type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
type RelayManagedEndpointProviderKind, type RelayManagedEndpointProviderKind,
} from "@t3tools/contracts/relay"; } 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 { import {
exchangeRemoteDpopAccessToken,
fetchRemoteEnvironmentDescriptor,
makeEnvironmentHttpApiClient,
ManagedRelayClient, ManagedRelayClient,
type ManagedRelayClientError,
ManagedRelayDpopSigner, 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 type { SavedRemoteConnection } from "../../lib/connection";
import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage"; import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
import { resolveCloudPublicConfig } from "./publicConfig"; import { resolveCloudPublicConfig } from "./publicConfig";
@@ -56,6 +57,7 @@ function readRelayUrl(): string | null {
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{ export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
readonly message: string; readonly message: string;
readonly cause?: unknown; readonly cause?: unknown;
readonly traceId?: string;
}> {} }> {}
export interface CloudEnvironmentRecordWithStatus { export interface CloudEnvironmentRecordWithStatus {
@@ -64,7 +66,6 @@ export interface CloudEnvironmentRecordWithStatus {
readonly statusError: string | null; readonly statusError: string | null;
} }
const isRelayProtectedError = Schema.is(RelayProtectedError);
const isEnvironmentCloudApiError = Schema.is( const isEnvironmentCloudApiError = Schema.is(
Schema.Union([ Schema.Union([
EnvironmentHttpBadRequestError, EnvironmentHttpBadRequestError,
@@ -82,11 +83,13 @@ const MANAGED_ENDPOINT_PROVIDER_KIND =
function cloudEnvironmentLinkError(message: string) { function cloudEnvironmentLinkError(message: string) {
return (cause: unknown) => { return (cause: unknown) => {
const environmentError = findEnvironmentCloudApiError(cause); const environmentError = findEnvironmentCloudApiError(cause);
const traceId = findErrorTraceId(cause);
return new CloudEnvironmentLinkError({ return new CloudEnvironmentLinkError({
message: environmentError message: environmentError
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}` ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
: withDevCause(message, cause), : withDevCause(message, cause),
cause, cause,
...(traceId === null ? {} : { traceId }),
}); });
}; };
} }
@@ -148,31 +151,22 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
case "RelayAgentActivityPublishProofInvalidError": case "RelayAgentActivityPublishProofInvalidError":
return `Relay rejected the agent activity publish proof (${error.reason}).`; return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError": 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) { function decodedRelayClientError(message: string) {
return (cause: unknown) => { return (cause: ManagedRelayClientError) => {
const relayError = findRelayProtectedError(cause); const relayError = cause.relayError;
const detail = relayError ? relayProtectedErrorMessage(relayError) : null; const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
return new CloudEnvironmentLinkError({ return new CloudEnvironmentLinkError({
message: detail ? `${message}: ${detail}` : message, message: detail ? `${message}: ${detail}` : message,
cause, 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 { function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
if (isEnvironmentCloudApiError(cause)) { if (isEnvironmentCloudApiError(cause)) {
return cause; return cause;
@@ -462,23 +456,26 @@ export function listCloudEnvironmentsWithStatus(input: {
}); });
} }
function connectRelayManagedEnvironment(input: { const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
readonly clerkToken: string; function* () {
readonly environmentId: RelayClientEnvironmentRecord["environmentId"]; return yield* Effect.tryPromise({
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({
try: () => loadOrCreateAgentAwarenessDeviceId(), try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."), 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 const connect = yield* relayClient
.connectEnvironment({ .connectEnvironment({
clerkToken: input.clerkToken, clerkToken: input.clerkToken,
@@ -528,7 +525,7 @@ function connectRelayManagedEnvironment(input: {
httpBaseUrl: connect.endpoint.httpBaseUrl, httpBaseUrl: connect.endpoint.httpBaseUrl,
credential: connect.credential, credential: connect.credential,
dpopProof: bootstrapDpop, dpopProof: bootstrapDpop,
clientMetadata: mobileAuthClientMetadata(), clientMetadata: authClientMetadata(),
}).pipe( }).pipe(
Effect.mapError( Effect.mapError(
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."), cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
@@ -548,9 +545,9 @@ function connectRelayManagedEnvironment(input: {
authenticationMethod: "dpop", authenticationMethod: "dpop",
dpopAccessToken: bootstrap.access_token, dpopAccessToken: bootstrap.access_token,
relayManaged: true, relayManaged: true,
}; } satisfies SavedRemoteConnection;
}); },
} );
export function connectCloudEnvironment(input: { export function connectCloudEnvironment(input: {
readonly clerkToken: string; readonly clerkToken: string;
@@ -1,42 +1,46 @@
import { import {
managedRelayClientLayer, managedRelayClientLayer as makeManagedRelayClientLayer,
ManagedRelayDpopSigner, ManagedRelayDpopSigner,
ManagedRelayDpopSignerError, ManagedRelayDpopSignerError,
} from "@t3tools/client-runtime"; } from "@t3tools/client-runtime/relay";
import { RelayMobileClientId } from "@t3tools/contracts/relay"; import { RelayMobileClientId } from "@t3tools/contracts/relay";
import * as Crypto from "effect/Crypto"; import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer"; import * as Layer from "effect/Layer";
import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop"; import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
const mobileRelayDpopSignerLayer = Layer.effect( const relayDpopSignerLayer = Layer.effect(
ManagedRelayDpopSigner, ManagedRelayDpopSigner,
Effect.gen(function* () { Effect.gen(function* () {
const crypto = yield* Crypto.Crypto; const crypto = yield* Crypto.Crypto;
const loadProofKey = yield* Effect.cached(
loadOrCreateDpopProofKeyPair().pipe(Effect.provideService(Crypto.Crypto, crypto)),
);
return ManagedRelayDpopSigner.of({ return ManagedRelayDpopSigner.of({
thumbprint: Effect.suspend(() => thumbprint: loadProofKey.pipe(
loadOrCreateDpopProofKeyPair().pipe( Effect.map((proofKey) => proofKey.thumbprint),
Effect.provideService(Crypto.Crypto, crypto), Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
Effect.map((proofKey) => proofKey.thumbprint), Effect.withSpan("mobile.managedRelayDpopSigner.loadThumbprint"),
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
),
), ),
createProof: (input) => createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(
Effect.gen(function* () { function* (input) {
const proofKey = yield* loadOrCreateDpopProofKeyPair().pipe( const proofKey = yield* loadProofKey;
Effect.provideService(Crypto.Crypto, crypto),
);
return yield* createDpopProof({ ...input, proofKey }).pipe( return yield* createDpopProof({ ...input, proofKey }).pipe(
Effect.provideService(Crypto.Crypto, crypto), Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proof) => proof.proof), Effect.map((proof) => proof.proof),
); );
}).pipe(Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause }))), },
Effect.mapError((cause) => new ManagedRelayDpopSignerError({ cause })),
),
}); });
}), }),
); );
export const mobileManagedRelayClientLayer = (relayUrl: string) => export const managedRelayClientLayer = (relayUrl: string) =>
managedRelayClientLayer({ relayUrl, clientId: RelayMobileClientId }).pipe( makeManagedRelayClientLayer({
Layer.provideMerge(mobileRelayDpopSignerLayer), relayUrl,
); clientId: RelayMobileClientId,
accessTokenStore: managedRelayAccessTokenStore,
}).pipe(Layer.provideMerge(relayDpopSignerLayer));
@@ -3,20 +3,24 @@ import {
createManagedRelayQueryManager, createManagedRelayQueryManager,
managedRelaySessionAtom, managedRelaySessionAtom,
readManagedRelaySnapshotState, readManagedRelaySnapshotState,
} from "@t3tools/client-runtime"; } from "@t3tools/client-runtime/relay";
import type { import type {
RelayClientEnvironmentRecord, RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse, RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay"; } from "@t3tools/contracts/relay";
import { AsyncResult, Atom } from "effect/unstable/reactivity"; 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 { 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( const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]), AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
@@ -33,6 +37,15 @@ export function useManagedRelayEnvironments() {
? managedRelayQueryManager.environmentsAtom(accountId) ? managedRelayQueryManager.environmentsAtom(accountId)
: EMPTY_ENVIRONMENTS_ATOM; : EMPTY_ENVIRONMENTS_ATOM;
const result = useAtomValue(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(() => { const refresh = useCallback(() => {
if (accountId) { if (accountId) {
managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId); managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
@@ -40,7 +53,7 @@ export function useManagedRelayEnvironments() {
}, [accountId]); }, [accountId]);
return { return {
...readManagedRelaySnapshotState(result), ...snapshot,
accountId, accountId,
refresh, refresh,
}; };
@@ -53,6 +66,16 @@ export function useManagedRelayEnvironmentStatus(environment: RelayClientEnviron
? managedRelayQueryManager.environmentStatusAtom({ accountId, environment }) ? managedRelayQueryManager.environmentStatusAtom({ accountId, environment })
: EMPTY_ENVIRONMENT_STATUS_ATOM; : EMPTY_ENVIRONMENT_STATUS_ATOM;
const result = useAtomValue(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(() => { const refresh = useCallback(() => {
if (accountId) { if (accountId) {
managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, { managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, {
@@ -63,7 +86,7 @@ export function useManagedRelayEnvironmentStatus(environment: RelayClientEnviron
}, [accountId, environment]); }, [accountId, environment]);
return { return {
...readManagedRelaySnapshotState(result), ...snapshot,
accountId, accountId,
refresh, 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 { describe, expect, it, vi } from "vite-plus/test";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig"; import { hasTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({ vi.mock("expo-constants", () => ({
default: { default: {
@@ -94,9 +94,9 @@ describe("resolveCloudPublicConfig", () => {
}); });
it("keeps tracing disabled unless every public tracing value is configured", () => { it("keeps tracing disabled unless every public tracing value is configured", () => {
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false); expect(hasTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
expect( expect(
hasMobileTracingPublicConfig( hasTracingPublicConfig(
resolveCloudPublicConfig({ resolveCloudPublicConfig({
observability: { observability: {
tracesUrl: "https://api.axiom.co/v1/traces", tracesUrl: "https://api.axiom.co/v1/traces",
@@ -106,7 +106,7 @@ describe("resolveCloudPublicConfig", () => {
), ),
).toBe(false); ).toBe(false);
expect( expect(
hasMobileTracingPublicConfig( hasTracingPublicConfig(
resolveCloudPublicConfig({ resolveCloudPublicConfig({
observability: { observability: {
tracesUrl: "https://api.axiom.co/v1/traces", tracesUrl: "https://api.axiom.co/v1/traces",
@@ -70,13 +70,13 @@ type Configured<T> = {
readonly [Key in keyof T]: NonNullable<T[Key]>; readonly [Key in keyof T]: NonNullable<T[Key]>;
}; };
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & { type TracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
readonly observability: Configured<CloudPublicConfig["observability"]>; readonly observability: Configured<CloudPublicConfig["observability"]>;
}; };
export function hasMobileTracingPublicConfig( export function hasTracingPublicConfig(
config: CloudPublicConfig = resolveCloudPublicConfig(), config: CloudPublicConfig = resolveCloudPublicConfig(),
): config is MobileTracingPublicConfig { ): config is TracingPublicConfig {
return Boolean( return Boolean(
config.observability.tracesUrl && config.observability.tracesUrl &&
config.observability.tracesDataset && config.observability.tracesDataset &&
@@ -1,31 +1,26 @@
import { SymbolView } from "expo-symbols"; 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 type { EnvironmentId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useState } from "react"; 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 Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor"; import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; 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 type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { ConnectionStatusDot } from "./ConnectionStatusDot"; import { ConnectionStatusDot } from "./ConnectionStatusDot";
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null { function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
if (environment.connectionError) { return connectionStatusText({
return null; phase: environment.connectionState,
} error: environment.connectionError,
traceId: environment.connectionErrorTraceId,
switch (environment.connectionState) { });
case "ready":
return "Connected";
case "connecting":
return "Connecting";
case "reconnecting":
return "Reconnecting";
case "disconnected":
return null;
case "idle":
return null;
}
} }
export function ConnectionEnvironmentRow(props: { export function ConnectionEnvironmentRow(props: {
@@ -37,7 +32,7 @@ export function ConnectionEnvironmentRow(props: {
readonly onUpdate: ( readonly onUpdate: (
environmentId: EnvironmentId, environmentId: EnvironmentId,
updates: { readonly label: string; readonly displayUrl: string }, updates: { readonly label: string; readonly displayUrl: string },
) => void; ) => Promise<AtomCommandResult<unknown, unknown>>;
}) { }) {
const [label, setLabel] = useState(props.environment.environmentLabel); const [label, setLabel] = useState(props.environment.environmentLabel);
const [url, setUrl] = useState(props.environment.displayUrl); const [url, setUrl] = useState(props.environment.displayUrl);
@@ -47,13 +42,25 @@ export function ConnectionEnvironmentRow(props: {
const primaryFg = useThemeColor("--color-primary-foreground"); const primaryFg = useThemeColor("--color-primary-foreground");
const dangerFg = useThemeColor("--color-danger-foreground"); const dangerFg = useThemeColor("--color-danger-foreground");
const statusLabel = connectionStatusLabel(props.environment); const statusLabel = connectionStatusLabel(props.environment);
const statusTraceId = props.environment.connectionErrorTraceId;
const handleSave = useCallback(() => { const hasConnectionFailure = props.environment.connectionError !== null;
props.onUpdate(props.environment.environmentId, { 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(), label: label.trim(),
displayUrl: url.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]); }, [label, url, props]);
return ( return (
@@ -64,10 +71,7 @@ export function ConnectionEnvironmentRow(props: {
> >
<ConnectionStatusDot <ConnectionStatusDot
state={props.environment.connectionState} state={props.environment.connectionState}
pulse={ pulse={isRetrying}
props.environment.connectionState === "connecting" ||
props.environment.connectionState === "reconnecting"
}
size={8} size={8}
/> />
@@ -82,16 +86,35 @@ export function ConnectionEnvironmentRow(props: {
{props.environment.displayUrl} {props.environment.displayUrl}
</Text> </Text>
{statusLabel ? ( {statusLabel ? (
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{statusLabel}
</Text>
) : null}
{props.environment.connectionError ? (
<Text <Text
className="text-[12px] leading-[16px] text-rose-500 dark:text-rose-400" className={cn(
numberOfLines={2} "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> </Text>
) : null} ) : null}
</View> </View>
@@ -11,12 +11,19 @@ import Animated, {
import type { RemoteClientConnectionState } from "../../lib/connection"; import type { RemoteClientConnectionState } from "../../lib/connection";
function statusDotTone(state: RemoteClientConnectionState): { export type ConnectionStatusDotState = RemoteClientConnectionState;
function statusDotTone(state: ConnectionStatusDotState): {
readonly dotColor: string; readonly dotColor: string;
readonly haloColor: string; readonly haloColor: string;
} { } {
switch (state) { switch (state) {
case "ready": case "available":
return {
dotColor: "#9ca3af",
haloColor: "rgba(156,163,175,0.42)",
};
case "connected":
return { return {
dotColor: "#34d399", dotColor: "#34d399",
haloColor: "rgba(52,211,153,0.48)", haloColor: "rgba(52,211,153,0.48)",
@@ -27,8 +34,8 @@ function statusDotTone(state: RemoteClientConnectionState): {
dotColor: "#f59e0b", dotColor: "#f59e0b",
haloColor: "rgba(245,158,11,0.5)", haloColor: "rgba(245,158,11,0.5)",
}; };
case "idle": case "offline":
case "disconnected": case "error":
return { return {
dotColor: "#ef4444", dotColor: "#ef4444",
haloColor: "rgba(239,68,68,0.48)", haloColor: "rgba(239,68,68,0.48)",
@@ -63,7 +70,7 @@ function usePulseAnimation(pulse: boolean) {
} }
export function ConnectionStatusDot(props: { export function ConnectionStatusDot(props: {
readonly state: RemoteClientConnectionState; readonly state: ConnectionStatusDotState;
readonly pulse: boolean; readonly pulse: boolean;
readonly size?: number; 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 { export function connectionTone(state: RemoteClientConnectionState): StatusTone {
switch (state) { switch (state) {
case "ready": case "connected":
return { return {
label: "Connected", label: "Connected",
pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16", 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", pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
textClassName: "text-sky-700 dark:text-sky-300", textClassName: "text-sky-700 dark:text-sky-300",
}; };
case "disconnected": case "error":
return { return {
label: "Disconnected", label: "Connection failed",
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16", pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
textClassName: "text-rose-700 dark:text-rose-300", textClassName: "text-rose-700 dark:text-rose-300",
}; };
case "idle": case "offline":
return { 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", pillClassName: "bg-neutral-500/10 dark:bg-neutral-500/16",
textClassName: "text-neutral-600 dark:text-neutral-300", 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 { import {
EnvironmentScopedProjectShell, type EnvironmentProject,
EnvironmentScopedThreadShell, type EnvironmentThreadShell,
VcsStatusState, } from "@t3tools/client-runtime/state/shell";
} from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols"; import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState } from "react"; import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native"; import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array"; import * as Arr from "effect/Array";
import * as Order from "effect/Order"; import * as Order from "effect/Order";
import { useThemeColor } from "../../lib/useThemeColor"; import { useThemeColor } from "../../lib/useThemeColor";
@@ -13,29 +13,29 @@ import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText"; import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState"; import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon"; import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection"; import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities"; import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time"; 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"; import { threadStatusTone } from "../threads/threadPresentation";
/* ─── Types ──────────────────────────────────────────────────────────── */ /* ─── Types ──────────────────────────────────────────────────────────── */
interface HomeScreenProps { interface HomeScreenProps {
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>; readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>; readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly catalogState: RemoteCatalogState; readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>; readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string; readonly searchQuery: string;
readonly onAddConnection: () => void; readonly onAddConnection: () => void;
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void; readonly onOpenEnvironments: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
} }
interface ProjectGroup { interface ProjectGroup {
readonly key: string; readonly key: string;
readonly project: EnvironmentScopedProjectShell; readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>; readonly threads: ReadonlyArray<EnvironmentThreadShell>;
} }
const projectGroupActivityOrder = Order.mapInput( const projectGroupActivityOrder = Order.mapInput(
@@ -49,7 +49,7 @@ const projectGroupActivityOrder = Order.mapInput(
/* ─── Status indicator colors ────────────────────────────────────────── */ /* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: EnvironmentScopedThreadShell): { bg: string; fg: string } { function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
switch (thread.session?.status) { switch (thread.session?.status) {
case "running": case "running":
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" }; 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; const COLLAPSED_THREAD_LIMIT = 6;
function deriveEmptyState(props: { function deriveEmptyState(props: {
readonly catalogState: RemoteCatalogState; readonly catalogState: WorkspaceState;
readonly projectCount: number; readonly projectCount: number;
}): { readonly title: string; readonly detail: string; readonly loading: boolean } { }): { readonly title: string; readonly detail: string; readonly loading: boolean } {
const { catalogState } = props; const { catalogState } = props;
if (catalogState.isLoadingSavedConnections) { if (catalogState.isLoadingConnections) {
return { return {
title: "Loading environments", title: "Loading environments",
detail: "Checking saved environments on this device.", detail: "Checking saved environments on this device.",
@@ -79,7 +79,7 @@ function deriveEmptyState(props: {
}; };
} }
if (!catalogState.hasSavedConnections) { if (!catalogState.hasConnections) {
return { return {
title: "No environments connected", title: "No environments connected",
detail: "Add an environment to load projects and start coding sessions.", 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 { return {
title: "Environment unavailable", title: "Environment unavailable",
detail: detail:
@@ -127,10 +132,8 @@ function deriveEmptyState(props: {
/* ─── Project group header ───────────────────────────────────────────── */ /* ─── Project group header ───────────────────────────────────────────── */
function ProjectGroupLabel(props: { function ProjectGroupLabel(props: {
readonly project: EnvironmentScopedProjectShell; readonly project: EnvironmentProject;
readonly totalThreadCount: number; readonly totalThreadCount: number;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
readonly isExpanded: boolean; readonly isExpanded: boolean;
readonly onToggleExpand: () => void; readonly onToggleExpand: () => void;
}) { }) {
@@ -139,11 +142,10 @@ function ProjectGroupLabel(props: {
return ( return (
<View className="flex-row items-center gap-2.5 px-1 pb-2"> <View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon <ProjectFavicon
environmentId={props.project.environmentId}
size={18} size={18}
projectTitle={props.project.title} projectTitle={props.project.title}
httpBaseUrl={props.httpBaseUrl}
workspaceRoot={props.project.workspaceRoot} workspaceRoot={props.project.workspaceRoot}
bearerToken={props.bearerToken}
/> />
<Text <Text
className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted" 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 ─────────────────────────────────────────────────────── */ /* ─── Thread row ─────────────────────────────────────────────────────── */
function ThreadRow(props: { function ThreadRow(props: {
readonly thread: EnvironmentScopedThreadShell; readonly thread: EnvironmentThreadShell;
readonly projectCwd: string | null; readonly environmentLabel: string | null;
readonly onPress: () => void; readonly onPress: () => void;
readonly isLast: boolean; readonly isLast: boolean;
}) { }) {
@@ -196,15 +183,9 @@ function ThreadRow(props: {
const tone = threadStatusTone(props.thread); const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt); const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
const branch = props.thread.branch; const branch = props.thread.branch;
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
// Subscribe to live git status — only when thread has a branch set. Boolean(part),
// 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);
return ( return (
<Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}> <Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
@@ -262,8 +243,8 @@ function ThreadRow(props: {
</View> </View>
</View> </View>
{/* Branch + git info */} {/* Environment + branch */}
{branch ? ( {subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}> <View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView <SymbolView
name="arrow.triangle.branch" name="arrow.triangle.branch"
@@ -276,13 +257,8 @@ function ThreadRow(props: {
numberOfLines={1} numberOfLines={1}
style={{ fontFamily: "monospace" }} style={{ fontFamily: "monospace" }}
> >
{branch} {subtitleParts.join(" · ")}
</Text> </Text>
{gitParts.length > 0 ? (
<Text className="text-[11px] text-foreground-tertiary">
{" · " + gitParts.join(" · ")}
</Text>
) : null}
</View> </View>
) : null} ) : null}
</View> </View>
@@ -293,8 +269,61 @@ function ThreadRow(props: {
/* ─── Main screen ────────────────────────────────────────────────────── */ /* ─── 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) { export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set()); const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted"); const accentColor = useThemeColor("--color-icon-muted");
const toggleExpanded = useCallback((key: string) => { const toggleExpanded = useCallback((key: string) => {
@@ -328,7 +357,7 @@ export function HomeScreen(props: HomeScreenProps) {
/* Group filtered threads by project */ /* Group filtered threads by project */
const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => { const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
const byProject = new Map<string, EnvironmentScopedThreadShell[]>(); const byProject = new Map<string, EnvironmentThreadShell[]>();
for (const thread of filteredThreads) { for (const thread of filteredThreads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId); const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = byProject.get(key); const existing = byProject.get(key);
@@ -351,77 +380,93 @@ export function HomeScreen(props: HomeScreenProps) {
/* Empty states */ /* Empty states */
const hasAnyThreads = props.threads.length > 0; const hasAnyThreads = props.threads.length > 0;
const hasResults = filteredThreads.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({ const emptyState = deriveEmptyState({
catalogState: props.catalogState, catalogState: props.catalogState,
projectCount: props.projects.length, projectCount: props.projects.length,
}); });
return ( return (
<ScrollView <View className="flex-1 bg-screen">
contentInsetAdjustmentBehavior="automatic" <ScrollView
showsVerticalScrollIndicator={false} contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag" showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag"
className="flex-1 bg-screen" keyboardShouldPersistTaps="handled"
contentContainerStyle={{ className="flex-1"
paddingHorizontal: 16, contentContainerStyle={{
paddingTop: 8, paddingHorizontal: 16,
paddingBottom: 24, paddingTop: 8,
gap: 20, paddingBottom: 24,
}} gap: 20,
> }}
{!hasAnyThreads ? ( >
<View> {!hasAnyThreads ? (
<EmptyState <View>
title={emptyState.title} <EmptyState
detail={emptyState.detail} title={emptyState.title}
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined} detail={emptyState.detail}
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined} actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
/> onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
{emptyState.loading ? ( />
<View className="absolute right-5 top-5"> {emptyState.loading ? (
<ActivityIndicator color={accentColor} /> <View className="absolute right-5 top-5">
</View> <ActivityIndicator color={accentColor} />
) : 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> </View>
</View> ) : null}
); </View>
}) ) : !hasResults ? (
)} <EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
</ScrollView> ) : (
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 Constants from "expo-constants";
import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing"; 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 tracesUrl: string;
readonly tracesDataset: string; readonly tracesDataset: string;
readonly tracesToken: string; readonly tracesToken: string;
} }
export interface MobileTracingResource { export interface TracingResource {
readonly serviceVersion?: string; readonly serviceVersion?: string;
readonly appVariant: string; readonly appVariant: string;
} }
export function resolveMobileTracingConfig(): MobileTracingConfig | null { export function resolveTracingConfig(): TracingConfig | null {
const config = resolveCloudPublicConfig(); const config = resolveCloudPublicConfig();
if (!hasMobileTracingPublicConfig(config)) { if (!hasTracingPublicConfig(config)) {
return null; return null;
} }
const { tracesUrl, tracesDataset, tracesToken } = config.observability; const { tracesUrl, tracesDataset, tracesToken } = config.observability;
return { tracesUrl, tracesDataset, tracesToken }; return { tracesUrl, tracesDataset, tracesToken };
} }
export function makeMobileTracingLayer( export function makeTracingLayer(config: TracingConfig | null, resource: TracingResource) {
config: MobileTracingConfig | null,
resource: MobileTracingResource,
) {
return makeRelayClientTracingLayer(config, { return makeRelayClientTracingLayer(config, {
serviceName: "t3-mobile-relay-client", serviceName: "t3-mobile-relay-client",
serviceVersion: resource.serviceVersion, serviceVersion: resource.serviceVersion,
@@ -35,7 +32,7 @@ export function makeMobileTracingLayer(
}); });
} }
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), { export const tracingLayer = makeTracingLayer(resolveTracingConfig(), {
serviceVersion: Constants.expoConfig?.version, serviceVersion: Constants.expoConfig?.version,
appVariant: appVariant:
typeof Constants.expoConfig?.extra?.appVariant === "string" typeof Constants.expoConfig?.extra?.appVariant === "string"
@@ -2,23 +2,25 @@ import {
addProjectRemoteSourceLabel, addProjectRemoteSourceLabel,
addProjectRemoteSourcePathHint, addProjectRemoteSourcePathHint,
addProjectRemoteSourceProvider, addProjectRemoteSourceProvider,
appendBrowsePathSegment,
buildAddProjectRemoteSourceReadiness, buildAddProjectRemoteSourceReadiness,
buildProjectCreateCommand, buildProjectCreateCommand,
canNavigateUp,
ensureBrowseDirectoryPath,
findExistingAddProject, findExistingAddProject,
getAddProjectInitialQuery, getAddProjectInitialQuery,
resolveAddProjectPath,
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime/operations/projects";
import {
appendBrowsePathSegment,
canNavigateUp,
ensureBrowseDirectoryPath,
getBrowseDirectoryPath, getBrowseDirectoryPath,
getBrowseLeafPathSegment, getBrowseLeafPathSegment,
getBrowseParentPath, getBrowseParentPath,
hasTrailingPathSeparator, hasTrailingPathSeparator,
inferProjectTitleFromPath, inferProjectTitleFromPath,
isFilesystemBrowseQuery, isFilesystemBrowseQuery,
resolveAddProjectPath, } from "@t3tools/client-runtime/state/projects";
sortAddProjectProviderSources,
type AddProjectRemoteSource,
} from "@t3tools/client-runtime";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts"; import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router"; import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols"; 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 { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array"; import * as Arr from "effect/Array";
import * as Cause from "effect/Cause";
import * as Order from "effect/Order"; 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 { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ErrorBanner } from "../../components/ErrorBanner"; import { ErrorBanner } from "../../components/ErrorBanner";
import { SourceControlIcon } from "../../components/SourceControlIcon"; import { SourceControlIcon } from "../../components/SourceControlIcon";
import { useThemeColor } from "../../lib/useThemeColor"; import { useThemeColor } from "../../lib/useThemeColor";
import { uuidv4 } from "../../lib/uuid"; import { uuidv4 } from "../../lib/uuid";
import { getEnvironmentClient } from "../../state/environment-session-registry"; import { useAtomCommand } from "../../state/use-atom-command";
import { useFilesystemBrowse } from "../../state/use-filesystem-browse"; import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
import { useRemoteCatalog } from "../../state/use-remote-catalog"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
import {
refreshSourceControlDiscoveryForEnvironment,
useSourceControlDiscovery,
} from "../../state/use-source-control-discovery";
interface EnvironmentOption { interface EnvironmentOption {
readonly environmentId: EnvironmentId; readonly environmentId: EnvironmentId;
@@ -224,12 +228,12 @@ function ProjectPathInput(props: {
} }
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> { function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const { serverConfigByEnvironmentId } = useRemoteCatalog(); const serverConfigByEnvironmentId = useServerConfigs();
const { savedConnectionsById } = useRemoteEnvironmentState(); const { savedConnectionsById } = useSavedRemoteConnections();
return useMemo<ReadonlyArray<EnvironmentOption>>(() => { return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
const options = Object.values(savedConnectionsById).map((connection) => { const options = Object.values(savedConnectionsById).map((connection) => {
const config = serverConfigByEnvironmentId[connection.environmentId]; const config = serverConfigByEnvironmentId.get(connection.environmentId);
return { return {
environmentId: connection.environmentId, environmentId: connection.environmentId,
label: connection.environmentLabel, label: connection.environmentLabel,
@@ -336,17 +340,19 @@ export function AddProjectSourceScreen() {
const iconColor = useThemeColor("--color-icon"); const iconColor = useThemeColor("--color-icon");
const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } = const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
useSelectedEnvironment(); useSelectedEnvironment();
const discoveryState = useSourceControlDiscovery(selectedEnvironment?.environmentId ?? null); const discoveryState = useEnvironmentQuery(
selectedEnvironment === null
? null
: sourceControlEnvironment.discovery({
environmentId: selectedEnvironment.environmentId,
input: {},
}),
);
const readiness = useMemo( const readiness = useMemo(
() => buildAddProjectRemoteSourceReadiness(discoveryState.data), () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
[discoveryState.data], [discoveryState.data],
); );
useEffect(() => {
if (!selectedEnvironment) return;
void refreshSourceControlDiscoveryForEnvironment(selectedEnvironment.environmentId);
}, [selectedEnvironment]);
return ( return (
<AddProjectShell> <AddProjectShell>
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null} {environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
@@ -435,13 +441,12 @@ export function AddProjectSourceScreen() {
function useCreateProject(environment: EnvironmentOption | null) { function useCreateProject(environment: EnvironmentOption | null) {
const router = useRouter(); const router = useRouter();
const { projects } = useRemoteCatalog(); const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
const projects = useProjects();
return useCallback( return useCallback(
async (workspaceRoot: string) => { async (workspaceRoot: string) => {
if (!environment) return; if (!environment) return;
const client = getEnvironmentClient(environment.environmentId);
if (!client) throw new Error("Environment API is not available.");
const existing = findExistingAddProject({ const existing = findExistingAddProject({
projects, projects,
@@ -462,14 +467,19 @@ function useCreateProject(environment: EnvironmentOption | null) {
} }
const projectId = ProjectId.make(uuidv4()); const projectId = ProjectId.make(uuidv4());
await client.orchestration.dispatchCommand( const command = buildProjectCreateCommand({
buildProjectCreateCommand({ commandId: CommandId.make(uuidv4()),
commandId: CommandId.make(uuidv4()), projectId,
projectId, workspaceRoot,
workspaceRoot, createdAt: new Date().toISOString(),
createdAt: new Date().toISOString(), });
}), const result = await createProject({
); environmentId: environment.environmentId,
input: command,
});
if (AsyncResult.isFailure(result)) {
return result;
}
router.replace({ router.replace({
pathname: "/new/draft", pathname: "/new/draft",
params: { params: {
@@ -478,8 +488,9 @@ function useCreateProject(environment: EnvironmentOption | null) {
title: inferProjectTitleFromPath(workspaceRoot), title: inferProjectTitleFromPath(workspaceRoot),
}, },
}); });
return result;
}, },
[environment, projects, router], [createProject, environment, projects, router],
); );
} }
@@ -495,6 +506,9 @@ function useEnvironmentFromParam(): EnvironmentOption | null {
} }
export function AddProjectRepositoryScreen() { export function AddProjectRepositoryScreen() {
const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
reportFailure: false,
});
const router = useRouter(); const router = useRouter();
const params = useLocalSearchParams<{ environmentId?: string; source?: string }>(); const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
const environment = useEnvironmentFromParam(); const environment = useEnvironmentFromParam();
@@ -507,28 +521,33 @@ export function AddProjectRepositoryScreen() {
if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return; if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
setError(null); setError(null);
setIsSubmitting(true); setIsSubmitting(true);
try { const provider = addProjectRemoteSourceProvider(source);
const provider = addProjectRemoteSourceProvider(source); if (!provider) {
if (!provider) { const remoteUrl = repositoryInput.trim();
const remoteUrl = repositoryInput.trim(); router.push({
router.push({ pathname: "/new/add-project/destination",
pathname: "/new/add-project/destination", params: {
params: { environmentId: environment.environmentId,
environmentId: environment.environmentId, source,
source, remoteUrl,
remoteUrl, repositoryTitle: remoteUrl,
repositoryTitle: remoteUrl, },
}, });
}); setIsSubmitting(false);
return; return;
} }
const client = getEnvironmentClient(environment.environmentId); const result = await lookupRepositoryQuery({
if (!client) throw new Error("Environment API is not available."); environmentId: environment.environmentId,
const repository = await client.sourceControl.lookupRepository({ input: {
provider, provider,
repository: repositoryInput.trim(), repository: repositoryInput.trim(),
}); },
});
if (AsyncResult.isFailure(result)) {
setError(errorMessage(Cause.squash(result.cause)));
} else {
const repository = result.value;
router.push({ router.push({
pathname: "/new/add-project/destination", pathname: "/new/add-project/destination",
params: { params: {
@@ -538,12 +557,9 @@ export function AddProjectRepositoryScreen() {
repositoryTitle: repository.nameWithOwner, 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 ( return (
<AddProjectShell> <AddProjectShell>
@@ -593,7 +609,14 @@ function FolderBrowser(props: {
() => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null), () => (browseDirectoryPath.length > 0 ? { partialPath: browseDirectoryPath } : null),
[browseDirectoryPath], [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( const visibleBrowseEntries = useMemo(
() => () =>
Arr.sort( Arr.sort(
@@ -686,13 +709,11 @@ export function AddProjectLocalFolderScreen() {
} }
setIsSubmitting(true); setIsSubmitting(true);
try { const result = await createProject(resolved.path);
await createProject(resolved.path); if (result && AsyncResult.isFailure(result)) {
} catch (nextError) { setError(errorMessage(Cause.squash(result.cause)));
setError(errorMessage(nextError));
} finally {
setIsSubmitting(false);
} }
setIsSubmitting(false);
}, [createProject, environment, isSubmitting, pathInput]); }, [createProject, environment, isSubmitting, pathInput]);
return ( return (
@@ -725,6 +746,9 @@ export function AddProjectLocalFolderScreen() {
} }
export function AddProjectDestinationScreen() { export function AddProjectDestinationScreen() {
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
reportFailure: false,
});
const params = useLocalSearchParams<{ const params = useLocalSearchParams<{
environmentId?: string; environmentId?: string;
remoteUrl?: string; remoteUrl?: string;
@@ -759,20 +783,23 @@ export function AddProjectDestinationScreen() {
} }
setIsSubmitting(true); setIsSubmitting(true);
try { const cloneResult = await cloneRepository({
const client = getEnvironmentClient(environment.environmentId); environmentId: environment.environmentId,
if (!client) throw new Error("Environment API is not available."); input: {
const result = await client.sourceControl.cloneRepository({
remoteUrl, remoteUrl,
destinationPath: resolved.path, destinationPath: resolved.path,
}); },
await createProject(result.cwd); });
} catch (nextError) { if (AsyncResult.isFailure(cloneResult)) {
setError(errorMessage(nextError)); setError(errorMessage(Cause.squash(cloneResult.cause)));
} finally { } else {
setIsSubmitting(false); 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 ( return (
<AddProjectShell> <AddProjectShell>
+65 -24
View File
@@ -16,8 +16,12 @@ import {
import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText"; 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 { useThemeColor } from "../../lib/useThemeColor";
import { useThreadDraftForThread } from "../../state/use-thread-composer-state"; import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { useReviewCacheForThread } from "./reviewState"; import { useReviewCacheForThread } from "./reviewState";
import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface"; import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
import { import {
@@ -29,6 +33,7 @@ import { useReviewFileVisibility } from "./reviewFileVisibility";
import { useReviewSections } from "./useReviewSections"; import { useReviewSections } from "./useReviewSections";
import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge"; import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge";
import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController"; import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController";
import { resolveReviewAvailability } from "./reviewAvailability";
const IOS_NAV_BAR_HEIGHT = 44; const IOS_NAV_BAR_HEIGHT = 44;
const REVIEW_HEADER_SPACING = 0; const REVIEW_HEADER_SPACING = 0;
@@ -114,6 +119,9 @@ export function ReviewSheet() {
environmentId: EnvironmentId; environmentId: EnvironmentId;
threadId: ThreadId; 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 { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
const reviewCache = useReviewCacheForThread({ environmentId, threadId }); const reviewCache = useReviewCacheForThread({ environmentId, threadId });
const selectedTheme = colorScheme === "dark" ? "dark" : "light"; const selectedTheme = colorScheme === "dark" ? "dark" : "light";
@@ -126,7 +134,12 @@ export function ReviewSheet() {
selectedSection, selectedSection,
refreshSelectedSection, refreshSelectedSection,
selectSection, selectSection,
} = useReviewSections({ environmentId, threadId, reviewCache }); } = useReviewSections({
enabled: isEnvironmentReady,
environmentId,
threadId,
reviewCache,
});
const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } = const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } =
useReviewDiffData({ useReviewDiffData({
threadKey: reviewCache.threadKey, threadKey: reviewCache.threadKey,
@@ -187,6 +200,17 @@ export function ReviewSheet() {
const parsedDiffNotice = const parsedDiffNotice =
parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null; 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 listHeader = useMemo(() => {
const children: ReactElement[] = []; const children: ReactElement[] = [];
@@ -312,34 +336,51 @@ export function ReviewSheet() {
}} }}
/> />
<Stack.Toolbar placement="right"> {showSectionToolbar ? (
<Stack.Toolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground> <Stack.Toolbar placement="right">
{reviewSections.map((section) => ( <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 <Stack.Toolbar.MenuAction
key={section.id} icon="arrow.clockwise"
icon={section.id === selectedSection?.id ? "checkmark" : "circle"} disabled={
onPress={() => selectSection(section.id)} loadingGitDiffs ||
subtitle={section.subtitle ?? undefined} (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>
))} </Stack.Toolbar.Menu>
<Stack.Toolbar.MenuAction </Stack.Toolbar>
icon="arrow.clockwise" ) : null}
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>
<View className="flex-1 bg-sheet"> <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 <View
className="flex-1" className="flex-1"
style={{ 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 type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
import { getEnvironmentClient } from "../../state/environment-session-registry"; import { useCheckpointDiff } from "../../state/queries";
import { checkpointDiffManager, loadCheckpointDiff } from "../../state/use-checkpoint-diff"; import { useEnvironmentQuery } from "../../state/query";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; import { reviewEnvironment } from "../../state/review";
import { useSelectedThreadDetail } from "../../state/use-thread-detail"; import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useReviewDiffPreview } from "./reviewDiffPreviewState"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { import {
buildReviewSectionItems, buildReviewSectionItems,
getDefaultReviewSectionId, getDefaultReviewSectionId,
@@ -17,29 +17,30 @@ import {
setReviewAsyncError, setReviewAsyncError,
setReviewGitSections, setReviewGitSections,
setReviewSelectedSectionId, setReviewSelectedSectionId,
setReviewTurnDiffLoading,
setReviewTurnDiff, setReviewTurnDiff,
setReviewTurnDiffLoading,
type ReviewCacheForThread, type ReviewCacheForThread,
} from "./reviewState"; } from "./reviewState";
export function useReviewSections(input: { export function useReviewSections(input: {
readonly enabled?: boolean;
readonly environmentId?: EnvironmentId; readonly environmentId?: EnvironmentId;
readonly threadId?: ThreadId; readonly threadId?: ThreadId;
readonly reviewCache: ReviewCacheForThread; readonly reviewCache: ReviewCacheForThread;
}) { }) {
const { environmentId, reviewCache, threadId } = input; const { environmentId, reviewCache, threadId } = input;
const enabled = input.enabled ?? true;
const selectedThread = useSelectedThreadDetail(); const selectedThread = useSelectedThreadDetail();
const { selectedThreadCwd } = useSelectedThreadWorktree(); const { selectedThreadCwd } = useSelectedThreadWorktree();
const diffPreview = useReviewDiffPreview({ environmentId, cwd: selectedThreadCwd }); const diffPreview = useEnvironmentQuery(
const refreshDiffPreview = diffPreview.refresh; enabled && environmentId !== undefined && selectedThreadCwd !== null
? reviewEnvironment.diffPreview({
environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const { loadingTurnIds } = reviewCache.asyncState; 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(() => { useEffect(() => {
if (reviewCache.threadKey && diffPreview.data) { if (reviewCache.threadKey && diffPreview.data) {
@@ -51,14 +52,16 @@ export function useReviewSections(input: {
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []), () => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
[selectedThread?.checkpoints], [selectedThread?.checkpoints],
); );
const checkpointBySectionId = useMemo(() => { const checkpointBySectionId = useMemo(
return Object.fromEntries( () =>
readyCheckpoints.map((checkpoint) => [ Object.fromEntries(
getReviewSectionIdForCheckpoint(checkpoint), readyCheckpoints.map((checkpoint) => [
checkpoint, getReviewSectionIdForCheckpoint(checkpoint),
]), checkpoint,
) as Record<string, OrchestrationCheckpointSummary>; ]),
}, [readyCheckpoints]); ) as Record<string, OrchestrationCheckpointSummary>,
[readyCheckpoints],
);
const reviewSections = useMemo( const reviewSections = useMemo(
() => () =>
buildReviewSectionItems({ buildReviewSectionItems({
@@ -87,7 +90,6 @@ export function useReviewSections(input: {
() => getDefaultReviewSectionId(reviewSections), () => getDefaultReviewSectionId(reviewSections),
[reviewSections], [reviewSections],
); );
const hasReviewSections = reviewSections.length > 0;
const selectedSectionIdExists = useMemo( const selectedSectionIdExists = useMemo(
() => () =>
reviewCache.selectedSectionId reviewCache.selectedSectionId
@@ -96,140 +98,69 @@ export function useReviewSections(input: {
[reviewCache.selectedSectionId, reviewSections], [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(() => { useEffect(() => {
if (!hasReviewSections) { if (
return; reviewSections.length > 0 &&
} reviewCache.threadKey &&
(!reviewCache.selectedSectionId || !selectedSectionIdExists)
if (reviewCache.threadKey && (!reviewCache.selectedSectionId || !selectedSectionIdExists)) { ) {
setReviewSelectedSectionId(reviewCache.threadKey, fallbackSectionId); setReviewSelectedSectionId(reviewCache.threadKey, fallbackSectionId);
} }
}, [ }, [
fallbackSectionId, fallbackSectionId,
hasReviewSections,
reviewCache.selectedSectionId, reviewCache.selectedSectionId,
reviewCache.threadKey, reviewCache.threadKey,
reviewSections.length,
selectedSectionIdExists, selectedSectionIdExists,
]); ]);
const latestCheckpoint = readyCheckpoints[0] ?? null; let activeCheckpoint = readyCheckpoints[0] ?? null;
const latestSectionId = latestCheckpoint if (selectedSection?.kind === "turn") {
? getReviewSectionIdForCheckpoint(latestCheckpoint) activeCheckpoint = checkpointBySectionId[selectedSection.id] ?? activeCheckpoint;
}
const activeSectionId = activeCheckpoint
? getReviewSectionIdForCheckpoint(activeCheckpoint)
: null; : null;
const latestTurnDiffLoaded = latestSectionId const activeTurnDiff = useCheckpointDiff({
? reviewCache.turnDiffById[latestSectionId] !== undefined environmentId: enabled ? (environmentId ?? null) : null,
: true; threadId: enabled ? (threadId ?? null) : null,
const latestTurnDiffLoading = latestSectionId ? loadingTurnIds[latestSectionId] === true : false; fromTurnCount:
enabled && activeCheckpoint ? Math.max(0, activeCheckpoint.checkpointTurnCount - 1) : null,
toTurnCount: enabled ? (activeCheckpoint?.checkpointTurnCount ?? null) : null,
ignoreWhitespace: false,
});
useEffect(() => { useEffect(() => {
if (!latestCheckpoint || !latestSectionId || latestTurnDiffLoaded || latestTurnDiffLoading) { if (!reviewCache.threadKey || !activeSectionId) {
return; return;
} }
setReviewTurnDiffLoading(reviewCache.threadKey, activeSectionId, activeTurnDiff.isPending);
void loadTurnDiff(latestCheckpoint); }, [activeSectionId, activeTurnDiff.isPending, reviewCache.threadKey]);
}, [
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;
useEffect(() => { useEffect(() => {
if (!selectedTurnDiffMissing || selectedTurnDiffLoading) { if (!reviewCache.threadKey || !activeSectionId || !activeTurnDiff.data) {
return; return;
} }
setReviewTurnDiff(reviewCache.threadKey, activeSectionId, activeTurnDiff.data.diff);
setReviewAsyncError(reviewCache.threadKey, null);
}, [activeSectionId, activeTurnDiff.data, reviewCache.threadKey]);
void loadTurnDiff(selectedTurnDiffMissing); useEffect(() => {
}, [loadTurnDiff, selectedTurnDiffLoading, selectedTurnDiffMissing]); if (reviewCache.threadKey && activeTurnDiff.error) {
setReviewAsyncError(reviewCache.threadKey, activeTurnDiff.error);
}
}, [activeTurnDiff.error, reviewCache.threadKey]);
const refreshSelectedSection = useCallback(async () => { const refreshSelectedSection = useCallback(async () => {
if (!selectedSection) { if (!enabled) {
return; return;
} }
if (selectedSection?.kind === "turn") {
if (selectedSection.kind === "turn") { activeTurnDiff.refresh();
const checkpoint = checkpointBySectionId[selectedSection.id];
if (checkpoint) {
await loadTurnDiff(checkpoint, true);
}
return; return;
} }
diffPreview.refresh();
refreshDiffPreview(); }, [activeTurnDiff, diffPreview, enabled, selectedSection?.kind]);
}, [checkpointBySectionId, loadTurnDiff, refreshDiffPreview, selectedSection]);
const selectSection = useCallback( const selectSection = useCallback(
(sectionId: string) => { (sectionId: string) => {
@@ -241,8 +172,8 @@ export function useReviewSections(input: {
); );
return { return {
error, error: diffPreview.error ?? activeTurnDiff.error ?? reviewCache.asyncState.error,
loadingGitDiffs, loadingGitDiffs: diffPreview.isPending,
loadingTurnIds, loadingTurnIds,
reviewSections, reviewSections,
selectedSection, selectedSection,
@@ -1,18 +1,19 @@
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts"; import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols"; 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 { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText"; import { AppText as Text } from "../../components/AppText";
import { getEnvironmentClient } from "../../state/environment-session-registry"; import { terminalEnvironment } from "../../state/terminal";
import { import { useAtomCommand } from "../../state/use-atom-command";
attachTerminalSession, import { useAttachedTerminalSession } from "../../state/use-terminal-session";
useTerminalSession,
useTerminalSessionTarget,
} from "../../state/use-terminal-session";
import { TerminalSurface } from "./NativeTerminalSurface"; import { TerminalSurface } from "./NativeTerminalSurface";
import { hasNativeTerminalSurface } from "./nativeTerminalModule"; import { hasNativeTerminalSurface } from "./nativeTerminalModule";
import { terminalDebugLog } from "./terminalDebugLog"; import {
buildThreadTerminalAttachInput,
type TerminalGridSize,
type ThreadTerminalSubscriptionIdentity,
} from "./threadTerminalPanelModel";
interface ThreadTerminalPanelProps { interface ThreadTerminalPanelProps {
readonly environmentId: EnvironmentId; readonly environmentId: EnvironmentId;
@@ -29,108 +30,93 @@ const DEFAULT_TERMINAL_ROWS = 24;
export const ThreadTerminalPanel = memo(function ThreadTerminalPanel( export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
props: ThreadTerminalPanelProps, props: ThreadTerminalPanelProps,
) { ) {
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
const nativeTerminalAvailable = hasNativeTerminalSurface(); const nativeTerminalAvailable = hasNativeTerminalSurface();
const terminalId = DEFAULT_TERMINAL_ID; const terminalId = DEFAULT_TERMINAL_ID;
const target = useTerminalSessionTarget({ const lastGridSizeRef = useRef<TerminalGridSize>({
environmentId: props.environmentId,
threadId: props.threadId,
terminalId,
});
const terminal = useTerminalSession(target);
const [lastGridSize, setLastGridSize] = useState({
cols: DEFAULT_TERMINAL_COLS, cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS, rows: DEFAULT_TERMINAL_ROWS,
}); });
const lastGridSizeRef = useRef(lastGridSize); const subscriptionIdentity = useMemo<ThreadTerminalSubscriptionIdentity>(
lastGridSizeRef.current = lastGridSize; () => ({
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 terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
const isRunning = terminal.status === "running" || terminal.status === "starting"; const isRunning = terminal.status === "running" || terminal.status === "starting";
useEffect(() => { const sendResize = useCallback(
if (!props.visible) { (size: TerminalGridSize) => {
return; void resizeTerminal({
}
const client = getEnvironmentClient(props.environmentId);
if (!client) {
terminalDebugLog("panel:attach-skip", {
reason: "no-environment-client",
environmentId: props.environmentId, 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);
} }
}, [isRunning, sendResize]);
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,
]);
const handleInput = useCallback( const handleInput = useCallback(
(data: string) => { (data: string) => {
const client = getEnvironmentClient(props.environmentId); if (!isRunning) {
if (!client || !isRunning) {
return; return;
} }
void client.terminal.write({ void writeTerminal({
threadId: props.threadId, environmentId: props.environmentId,
terminalId, input: {
data, threadId: props.threadId,
terminalId,
data,
},
}); });
}, },
[isRunning, props.environmentId, props.threadId, terminalId], [isRunning, props.environmentId, props.threadId, terminalId, writeTerminal],
); );
const handleResize = useCallback( const handleResize = useCallback(
(size: { readonly cols: number; readonly rows: number }) => { (size: TerminalGridSize) => {
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) { const previousSize = lastGridSizeRef.current;
if (size.cols === previousSize.cols && size.rows === previousSize.rows) {
return; return;
} }
setLastGridSize(size); lastGridSizeRef.current = size;
const client = getEnvironmentClient(props.environmentId); if (!isRunning) {
if (!client || !isRunning) {
return; return;
} }
void client.terminal.resize({ sendResize(size);
threadId: props.threadId,
terminalId,
cols: size.cols,
rows: size.rows,
});
}, },
[ [isRunning, sendResize],
isRunning,
lastGridSize.cols,
lastGridSize.rows,
props.environmentId,
props.threadId,
terminalId,
],
); );
if (!props.visible) { if (!props.visible) {
@@ -1,10 +1,5 @@
import { import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
DEFAULT_TERMINAL_ID, import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
EnvironmentId,
type TerminalAttachStreamEvent,
ThreadId,
} from "@t3tools/contracts";
import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { SymbolView } from "expo-symbols"; import { SymbolView } from "expo-symbols";
import { Stack, useLocalSearchParams, useRouter } from "expo-router"; import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,17 +19,19 @@ import {
import { EmptyState } from "../../components/EmptyState"; import { EmptyState } from "../../components/EmptyState";
import { GlassSurface } from "../../components/GlassSurface"; import { GlassSurface } from "../../components/GlassSurface";
import { LoadingScreen } from "../../components/LoadingScreen"; 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 { buildThreadTerminalNavigation } from "../../lib/routes";
import { getEnvironmentClient } from "../../state/environment-session-registry";
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
import { import {
attachTerminalSession, useAttachedTerminalSession,
useKnownTerminalSessions, useKnownTerminalSessions,
useTerminalSession,
useTerminalSessionTarget,
} from "../../state/use-terminal-session"; } from "../../state/use-terminal-session";
import { useThreadSelection } from "../../state/use-thread-selection"; import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadDetail } from "../../state/use-thread-detail"; import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { TerminalSurface } from "./NativeTerminalSurface"; import { TerminalSurface } from "./NativeTerminalSurface";
import { getPierreTerminalTheme } from "./terminalTheme"; import { getPierreTerminalTheme } from "./terminalTheme";
import { loadPreferences, savePreferencesPatch } from "../../lib/storage"; import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
@@ -44,11 +41,10 @@ import {
getTerminalSurfaceReplayBuffer, getTerminalSurfaceReplayBuffer,
TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
} from "./terminalBufferReplay"; } from "./terminalBufferReplay";
import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
import { import {
resolveTerminalOpenLocation, resolveTerminalOpenLocation,
stagePendingTerminalLaunch,
takePendingTerminalLaunch, takePendingTerminalLaunch,
type PendingTerminalLaunch,
} from "./terminalLaunchContext"; } from "./terminalLaunchContext";
import { import {
basename, basename,
@@ -158,8 +154,12 @@ function pickRunningTerminalSessionForBootstrap(
export function ThreadTerminalRouteScreen() { export function ThreadTerminalRouteScreen() {
const router = useRouter(); 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 appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const { isLoadingSavedConnection } = useRemoteEnvironmentState(); const { state: workspaceState } = useWorkspaceState();
const params = useLocalSearchParams<{ const params = useLocalSearchParams<{
environmentId?: string | string[]; environmentId?: string | string[];
threadId?: string | string[]; threadId?: string | string[];
@@ -174,6 +174,8 @@ export function ThreadTerminalRouteScreen() {
? EnvironmentId.make(routeEnvironmentIdRaw) ? EnvironmentId.make(routeEnvironmentIdRaw)
: null; : null;
const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : 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 requestedTerminalId = firstRouteParam(params.terminalId);
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID; const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
const cachedFontSize = getCachedTerminalFontSize(); const cachedFontSize = getCachedTerminalFontSize();
@@ -189,6 +191,47 @@ export function ThreadTerminalRouteScreen() {
environmentId: selectedThread?.environmentId ?? null, environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? 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( const [lastGridSize, setLastGridSize] = useState(
cachedRouteGridSize ?? { cachedRouteGridSize ?? {
cols: DEFAULT_TERMINAL_COLS, cols: DEFAULT_TERMINAL_COLS,
@@ -198,11 +241,10 @@ export function ThreadTerminalRouteScreen() {
const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE); const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0); const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false); const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
const hasOpenedRef = useRef(false);
const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null); const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const attachStreamLogCountRef = useRef(0);
const firstNonEmptyBufferLoggedRef = useRef(false); const firstNonEmptyBufferLoggedRef = useRef(false);
const lastBufferReplayKeyRef = useRef<string | null>(null); const lastBufferReplayKeyRef = useRef<string | null>(null);
const sentInitialInputKeyRef = useRef<string | null>(null);
const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null); const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState( const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState(
cachedFontSize !== null, cachedFontSize !== null,
@@ -216,12 +258,78 @@ export function ThreadTerminalRouteScreen() {
terminalId, terminalId,
value: null, 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, environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null, terminal: terminalAttachInput,
terminalId,
}); });
const terminal = useTerminalSession(target);
const terminalKey = selectedThread const terminalKey = selectedThread
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}` ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
: terminalId; : terminalId;
@@ -293,23 +401,6 @@ export function ThreadTerminalRouteScreen() {
() => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null), () => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
[selectedEnvironmentConnection?.environmentLabel], [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 terminalTheme = getPierreTerminalTheme(appearanceScheme);
const pendingModifier = const pendingModifier =
@@ -406,145 +497,88 @@ export function ThreadTerminalRouteScreen() {
], ],
); );
const logAttachStreamEvent = useCallback((event: TerminalAttachStreamEvent) => { useEffect(() => {
const n = ++attachStreamLogCountRef.current; if (pendingLaunchEntry.key === launchTargetKey) {
if (event.type === "output" && n > 32 && n % 64 !== 0) {
return; return;
} }
if (event.type === "snapshot") { setPendingLaunchEntry({
terminalDebugLog("attach:stream", { key: launchTargetKey,
n, launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
type: event.type, });
status: event.snapshot.status, }, [launchTarget, launchTargetKey, pendingLaunchEntry.key]);
historyLen: event.snapshot.history.length,
cwd: event.snapshot.cwd, useEffect(() => {
}); if (initialAttachGridEntry.key === launchTargetKey) {
return; return;
} }
if (event.type === "output") { setInitialAttachGridEntry({
terminalDebugLog("attach:stream", { n, type: event.type, dataLen: event.data.length }); key: launchTargetKey,
return; size: cachedRouteGridSize ?? {
} cols: DEFAULT_TERMINAL_COLS,
terminalDebugLog("attach:stream", { n, type: event.type }); rows: DEFAULT_TERMINAL_ROWS,
}, []); },
});
const attachTerminal = useCallback(() => { }, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
terminalDebugLog("attach:abort", { reason: "no-thread-or-workspace" }); useEffect(() => {
return null; if (
} initialLaunchLocationEntry.key === launchTargetKey &&
initialLaunchLocationEntry.location !== null
const client = getEnvironmentClient(selectedThread.environmentId); ) {
if (!client) { return;
terminalDebugLog("attach:abort", { }
reason: "no-environment-client", if (initialLaunchLocationEntry.key === launchTargetKey && launchLocationCandidate === null) {
environmentId: selectedThread.environmentId, return;
}); }
return null; setInitialLaunchLocationEntry({
} key: launchTargetKey,
location: launchLocationCandidate,
const pendingLaunchTarget = { });
environmentId: selectedThread.environmentId, }, [
threadId: selectedThread.id, initialLaunchLocationEntry.key,
terminalId, initialLaunchLocationEntry.location,
}; launchLocationCandidate,
const pendingLaunch = takePendingTerminalLaunch(pendingLaunchTarget); launchTargetKey,
let initialInputSent = false; ]);
try { useEffect(() => {
const launchLocation = pendingLaunch if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
? { return;
cwd: pendingLaunch.cwd, }
worktreePath: pendingLaunch.worktreePath, router.replace(buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId));
} }, [router, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
: resolveTerminalOpenLocation({
terminalLocation: terminalAttachLaunchHintsRef.current.terminalSummary, useEffect(() => {
activeSessionLocation: terminalAttachLaunchHintsRef.current.activeKnownSummary, const initialInput = pendingLaunch?.initialInput;
workspaceRoot: selectedThreadProject.workspaceRoot, if (
threadShellWorktreePath: selectedThread.worktreePath ?? null, !initialInput ||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null, !selectedThread ||
}); terminal.version === 0 ||
sentInitialInputKeyRef.current === launchTargetKey
terminalDebugLog("attach:start", { ) {
terminalId, return;
threadId: selectedThread.id, }
cols: lastGridSize.cols, sentInitialInputKeyRef.current = launchTargetKey;
rows: lastGridSize.rows, void writeTerminal({
cwd: launchLocation.cwd, environmentId: selectedThread.environmentId,
worktreePath: launchLocation.worktreePath, input: {
}); threadId: selectedThread.id,
terminalId,
return attachTerminalSession({ data: initialInput,
environmentId: selectedThread.environmentId, },
client, });
terminal: { }, [
threadId: selectedThread.id, launchTargetKey,
terminalId, pendingLaunch?.initialInput,
cwd: launchLocation.cwd, selectedThread,
worktreePath: launchLocation.worktreePath, terminal.version,
cols: lastGridSize.cols, terminalId,
rows: lastGridSize.rows, writeTerminal,
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,
};
useEffect(() => { useEffect(() => {
hasOpenedRef.current = false;
attachStreamLogCountRef.current = 0;
firstNonEmptyBufferLoggedRef.current = false; firstNonEmptyBufferLoggedRef.current = false;
sentInitialInputKeyRef.current = null;
}, [terminalKey]); }, [terminalKey]);
const clearBufferReplayTimer = useCallback(() => { const clearBufferReplayTimer = useCallback(() => {
@@ -638,99 +672,22 @@ export function ThreadTerminalRouteScreen() {
}); });
}, [fontSize, hasResolvedFontPreference]); }, [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( const writeInput = useCallback(
(data: string) => { (data: string) => {
if (!selectedThread || !isRunning) { if (!selectedThread || !isRunning) {
return; return;
} }
const client = getEnvironmentClient(selectedThread.environmentId); void writeTerminal({
if (!client) { environmentId: selectedThread.environmentId,
return; input: {
} threadId: selectedThread.id,
terminalId,
void client.terminal.write({ data,
threadId: selectedThread.id, },
terminalId,
data,
}); });
}, },
[isRunning, selectedThread, terminalId], [isRunning, selectedThread, terminalId, writeTerminal],
); );
const handleInput = useCallback( const handleInput = useCallback(
@@ -782,16 +739,14 @@ export function ThreadTerminalRouteScreen() {
return; return;
} }
const client = getEnvironmentClient(selectedThread.environmentId); void resizeTerminal({
if (!client) { environmentId: selectedThread.environmentId,
return; input: {
} threadId: selectedThread.id,
terminalId,
void client.terminal.resize({ cols: size.cols,
threadId: selectedThread.id, rows: size.rows,
terminalId, },
cols: size.cols,
rows: size.rows,
}); });
}, },
[ [
@@ -802,6 +757,7 @@ export function ThreadTerminalRouteScreen() {
readyBufferReplayKey, readyBufferReplayKey,
routeEnvironmentId, routeEnvironmentId,
routeThreadId, routeThreadId,
resizeTerminal,
scheduleBufferReplayReady, scheduleBufferReplayReady,
selectedThread, selectedThread,
terminalId, terminalId,
@@ -855,17 +811,15 @@ export function ThreadTerminalRouteScreen() {
return; return;
} }
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
setPendingModifierState({ terminalId, value: null }); setPendingModifierState({ terminalId, value: null });
void client.terminal.clear({ void clearTerminal({
threadId: selectedThread.id, environmentId: selectedThread.environmentId,
terminalId, input: {
threadId: selectedThread.id,
terminalId,
},
}); });
}, [selectedThread, terminalId]); }, [clearTerminal, selectedThread, terminalId]);
const handleToolbarActionPress = useCallback( const handleToolbarActionPress = useCallback(
(action: TerminalToolbarAction) => { (action: TerminalToolbarAction) => {
@@ -905,9 +859,14 @@ export function ThreadTerminalRouteScreen() {
const handleShowKeyboard = useCallback(() => { const handleShowKeyboard = useCallback(() => {
setKeyboardFocusRequest((current) => current + 1); setKeyboardFocusRequest((current) => current + 1);
}, []); }, []);
const handleRetryEnvironment = useCallback(() => {
if (routeEnvironmentId !== null) {
void retryEnvironment(routeEnvironmentId);
}
}, [retryEnvironment, routeEnvironmentId]);
if (!selectedThread) { if (!selectedThread) {
if (isLoadingSavedConnection) { if (workspaceState.isLoadingConnections) {
return <LoadingScreen message="Opening terminal…" />; return <LoadingScreen message="Opening terminal…" />;
} }
@@ -932,6 +891,10 @@ export function ThreadTerminalRouteScreen() {
); );
} }
if (!environment.isReady && environment.presentation === null) {
return <LoadingScreen message="Opening terminal…" />;
}
return ( return (
<> <>
<Stack.Screen <Stack.Screen
@@ -980,152 +943,178 @@ export function ThreadTerminalRouteScreen() {
}} }}
/> />
<Stack.Toolbar placement="right"> {isEnvironmentReady ? (
<Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground> <Stack.Toolbar placement="right">
<Stack.Toolbar.Label> <Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground>
{getTerminalStatusLabel({ <Stack.Toolbar.Label>
status: terminal.status, {getTerminalStatusLabel({
hasRunningSubprocess: terminal.hasRunningSubprocess, status: terminal.status,
})} hasRunningSubprocess: terminal.hasRunningSubprocess,
</Stack.Toolbar.Label> })}
<Stack.Toolbar.Menu icon="textformat.size" inline title="Text size"> </Stack.Toolbar.Label>
<Stack.Toolbar.Label>Text size</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 <Stack.Toolbar.MenuAction
disabled={fontSize <= MIN_TERMINAL_FONT_SIZE} icon="plus"
discoverabilityLabel="Decrease terminal text size" onPress={handleOpenNewTerminal}
onPress={handleDecreaseFontSize} 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.Label>Open new terminal</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.MenuAction>
</Stack.Toolbar.Menu> </Stack.Toolbar.Menu>
{terminalMenuSessions.map((session) => ( </Stack.Toolbar>
<Stack.Toolbar.MenuAction ) : null}
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>
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}> <View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
<View style={{ flex: 1, paddingBottom: terminalBottomInset }}> {!isEnvironmentReady ? (
<TerminalSurface <EnvironmentConnectionNotice
buffer={terminalSurfaceBuffer} environmentLabel={
fontSize={fontSize} environment.presentation?.entry.target.label ??
isRunning={isRunning} selectedEnvironmentConnection?.environmentLabel ??
keyboardFocusRequest={keyboardFocusRequest} "Environment"
onInput={handleInput} }
onResize={handleResize} connection={
style={{ flex: 1 }} environment.presentation?.connection ?? {
terminalKey={terminalKey} phase: "available",
error: null,
traceId: null,
}
}
resourceName="terminal"
onRetry={handleRetryEnvironment}
/> />
</View> ) : (
<>
{isAccessoryVisible ? ( <View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
<KeyboardStickyView <TerminalSurface
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }} buffer={terminalSurfaceBuffer}
offset={{ closed: 0, opened: 0 }} fontSize={fontSize}
> isRunning={isRunning}
<View keyboardFocusRequest={keyboardFocusRequest}
style={{ onInput={handleInput}
backgroundColor: terminalTheme.background, onResize={handleResize}
borderTopColor: terminalTheme.border, style={{ flex: 1 }}
borderTopWidth: 1, terminalKey={terminalKey}
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> </View>
</Pressable>
) : null} {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> </View>
</> </>
); );
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test"; 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 { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; 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 { DEFAULT_TERMINAL_ID, type ProjectScript } from "@t3tools/contracts";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels"; import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
import * as Arr from "effect/Array"; 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 { Stack, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef } from "react"; 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 { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor"; 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 { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import { import {
@@ -19,27 +23,16 @@ import { ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon"; import { ProviderIcon } from "../../components/ProviderIcon";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { buildThreadRoutePath } from "../../lib/routes"; import { buildThreadRoutePath } from "../../lib/routes";
import { useRemoteCatalog } from "../../state/use-remote-catalog"; import { useProjects } from "../../state/entities";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider"; import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useProjectActions } from "./use-project-actions"; import { useCreateProjectThread } 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)}`;
}
function formatWorkspaceLabel(input: { function formatWorkspaceLabel(input: {
readonly workspaceMode: string; readonly workspaceMode: string;
@@ -59,8 +52,8 @@ export function NewTaskDraftScreen(props: {
readonly projectId?: string; readonly projectId?: string;
}; };
}) { }) {
const { projects } = useRemoteCatalog(); const projects = useProjects();
const { onCreateThreadWithOptions } = useProjectActions(); const createProjectThread = useCreateProjectThread();
const flow = useNewTaskFlow(); const flow = useNewTaskFlow();
const router = useRouter(); const router = useRouter();
const insets = useSafeAreaInsets(); const insets = useSafeAreaInsets();
@@ -169,39 +162,18 @@ export function NewTaskDraftScreen(props: {
})), })),
[flow.providerGroups, flow.selectedModel], [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( const optionsMenuActions = useMemo(
() => [ () => [
{ ...buildProviderOptionMenuActions(providerOptionDescriptors),
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,
})),
},
{ {
id: "options-runtime", id: "options-runtime",
title: "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(() => { const workspaceMenuActions = useMemo(() => {
@@ -302,14 +274,10 @@ export function NewTaskDraftScreen(props: {
flow.availableBranches.find((branch) => branch.current)?.name ?? flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ?? flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null; null;
const configurationLabel = useMemo(() => { const configurationLabel = useMemo(
const parts = [ () => providerOptionsConfigurationLabel(providerOptionDescriptors),
formatTitleCase(flow.effort), [providerOptionDescriptors],
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 workspaceLabel = useMemo( const workspaceLabel = useMemo(
() => () =>
formatWorkspaceLabel({ formatWorkspaceLabel({
@@ -338,16 +306,9 @@ export function NewTaskDraftScreen(props: {
} }
function handleOptionsMenuAction(event: string) { function handleOptionsMenuAction(event: string) {
if (event.startsWith("options:effort:")) { const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
flow.setEffort(event.slice("options:effort:".length) as typeof flow.effort); if (providerOptions) {
return; flow.setSelectedModelOptions(providerOptions);
}
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));
return; return;
} }
if (event.startsWith("options:runtime:")) { if (event.startsWith("options:runtime:")) {
@@ -415,42 +376,33 @@ export function NewTaskDraftScreen(props: {
} }
flow.setSubmitting(true); flow.setSubmitting(true);
try { const result = await createProjectThread({
const modelWithOptions: ModelSelection = project: flow.selectedProject,
flow.selectedModelOption?.providerDriver === "claudeAgent" modelSelection: flow.selectedModel,
? withModelSelectionOption( envMode: flow.workspaceMode,
withModelSelectionOption( branch: flow.selectedBranchName,
withModelSelectionOption(flow.selectedModel, "effort", flow.effort), worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
"fastMode", runtimeMode: flow.runtimeMode,
flow.fastMode || undefined, interactionMode: flow.interactionMode,
), initialMessageText: flow.prompt.trim(),
"contextWindow", initialAttachments: flow.attachments,
flow.contextWindow, });
) flow.setSubmitting(false);
: flow.selectedModelOption?.providerDriver === "codex"
? withModelSelectionOption(flow.selectedModel, "fastMode", flow.fastMode || undefined)
: flow.selectedModel;
const createdThread = await onCreateThreadWithOptions({ if (result._tag === "Failure") {
project: flow.selectedProject, if (!isAtomCommandInterrupted(result)) {
modelSelection: modelWithOptions, const error = squashAtomCommandFailure(result);
envMode: flow.workspaceMode, Alert.alert(
branch: flow.selectedBranchName, "Could not start task",
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath, error instanceof Error ? error.message : "The task could not be started.",
runtimeMode: flow.runtimeMode, );
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
});
if (createdThread) {
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(createdThread));
} }
} finally { return;
flow.setSubmitting(false);
} }
flow.setPrompt("");
flow.clearAttachments();
router.replace(buildThreadRoutePath(result.value));
} }
if (!selectedProject) { if (!selectedProject) {
@@ -10,7 +10,7 @@ export interface PendingApprovalCardProps {
readonly onRespond: ( readonly onRespond: (
requestId: ApprovalRequestId, requestId: ApprovalRequestId,
decision: ProviderApprovalDecision, decision: ProviderApprovalDecision,
) => Promise<void>; ) => Promise<unknown>;
} }
export function PendingApprovalCard(props: PendingApprovalCardProps) { export function PendingApprovalCard(props: PendingApprovalCardProps) {
@@ -20,7 +20,7 @@ export interface PendingUserInputCardProps {
questionId: string, questionId: string,
customAnswer: string, customAnswer: string,
) => void; ) => void;
readonly onSubmit: () => Promise<void>; readonly onSubmit: () => Promise<unknown>;
} }
export function PendingUserInputCard(props: PendingUserInputCardProps) { export function PendingUserInputCard(props: PendingUserInputCardProps) {
@@ -2,7 +2,7 @@ import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass
import type { import type {
EnvironmentId, EnvironmentId,
ModelSelection, ModelSelection,
OrchestrationThread, OrchestrationThreadShell,
ProviderInteractionMode, ProviderInteractionMode,
RuntimeMode, RuntimeMode,
ServerConfig as T3ServerConfig, ServerConfig as T3ServerConfig,
@@ -15,7 +15,14 @@ import {
} from "@t3tools/shared/composerTrigger"; } from "@t3tools/shared/composerTrigger";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } 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 ImageViewing from "react-native-image-viewing";
import { useThemeColor } from "../../lib/useThemeColor"; import { useThemeColor } from "../../lib/useThemeColor";
@@ -43,11 +50,12 @@ import {
scoreQueryMatch, scoreQueryMatch,
} from "@t3tools/shared/searchRanking"; } from "@t3tools/shared/searchRanking";
import { import {
getModelSelectionBooleanOptionValue, applyProviderOptionMenuEvent,
getModelSelectionStringOptionValue, buildProviderOptionMenuActions,
} from "@t3tools/shared/model"; providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search"; import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
/** /**
@@ -68,7 +76,9 @@ export interface ThreadComposerProps {
readonly placeholder: string; readonly placeholder: string;
readonly bottomInset?: number; readonly bottomInset?: number;
readonly connectionState: RemoteClientConnectionState; readonly connectionState: RemoteClientConnectionState;
readonly selectedThread: OrchestrationThread; readonly connectionError: string | null;
readonly environmentLabel: string | null;
readonly selectedThread: OrchestrationThreadShell;
readonly serverConfig: T3ServerConfig | null; readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number; readonly queueCount: number;
readonly activeThreadBusy: boolean; readonly activeThreadBusy: boolean;
@@ -79,11 +89,12 @@ export interface ThreadComposerProps {
readonly onPickDraftImages: () => Promise<void>; readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>; readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void; readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => Promise<void>; readonly onStopThread: () => void;
readonly onSendMessage: () => void; readonly onSendMessage: () => Promise<void>;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => Promise<void>; readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>; readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => Promise<void>; readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onReconnectEnvironment: () => void;
readonly onExpandedChange?: (expanded: boolean) => void; readonly onExpandedChange?: (expanded: boolean) => void;
} }
@@ -126,21 +137,67 @@ function ComposerSurface(props: {
); );
} }
function withModelSelectionOption( function composerConnectionStatus(input: {
selection: ModelSelection, readonly connectionError: string | null;
id: string, readonly connectionState: RemoteClientConnectionState;
value: string | boolean | undefined, readonly environmentLabel: string | null;
): ModelSelection { }): { readonly kind: "unavailable" | "reconnecting"; readonly label: string } | null {
const options = (selection.options ?? []).filter((option) => option.id !== id); const environmentLabel = input.environmentLabel ?? "Environment";
return {
...selection, switch (input.connectionState) {
options: value === undefined ? options : [...options, { id, value }], 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 { const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(props: {
return value.length === 0 ? value : `${value.charAt(0).toUpperCase()}${value.slice(1)}`; 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) { export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
const isDarkMode = useColorScheme() === "dark"; const isDarkMode = useColorScheme() === "dark";
@@ -154,7 +211,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null); const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0; const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const isExpanded = isFocused; const isExpanded = isFocused;
const canSend = props.connectionState === "ready" && hasContent; const canSend = hasContent;
const onPressImage = useCallback( const onPressImage = useCallback(
(uri: string) => { (uri: string) => {
@@ -182,13 +239,20 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}, [onExpandedChange]); }, [onExpandedChange]);
const showStopAction = const showStopAction =
props.selectedThread.session?.status === "running" || props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting" || props.selectedThread.session?.status === "starting";
props.queueCount > 0;
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 currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode; const currentRuntimeMode = props.selectedThread.runtimeMode;
const currentInteractionMode = props.selectedThread.interactionMode ?? "default"; 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 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 toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)";
const selectedProviderStatus = useMemo(() => { const selectedProviderStatus = useMemo(() => {
@@ -200,18 +264,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
); );
}, [props.serverConfig, props.selectedThread.modelSelection.instanceId]); }, [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 ──────────────────────────────────── // ── Trigger detection ────────────────────────────────────
const [composerSelection, setComposerSelection] = useState(() => ({ const [composerSelection, setComposerSelection] = useState(() => ({
start: props.draftMessage.length, start: props.draftMessage.length,
@@ -394,8 +446,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props; const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
const handleSend = useCallback(() => { const handleSend = useCallback(() => {
onSendMessage(); void onSendMessage().then(() => {
inputRef.current?.blur(); inputRef.current?.blur();
});
}, [onSendMessage]); }, [onSendMessage]);
const handleCommandSelect = useCallback( const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => { (item: ComposerCommandItem) => {
@@ -413,7 +466,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
); );
setComposerSelection({ start: result.cursor, end: result.cursor }); setComposerSelection({ start: result.cursor, end: result.cursor });
onChangeDraftMessage(result.text); onChangeDraftMessage(result.text);
void onUpdateInteractionMode(item.command); onUpdateInteractionMode(item.command);
return; return;
} }
@@ -452,14 +505,18 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
option.selection.instanceId === currentModelSelection.instanceId && option.selection.instanceId === currentModelSelection.instanceId &&
option.selection.model === currentModelSelection.model, option.selection.model === currentModelSelection.model,
) ?? null; ) ?? null;
const configurationLabel = useMemo(() => { const providerOptionDescriptors = useMemo(
const parts = [ () =>
formatTitleCase(currentEffort), resolveProviderOptionDescriptors({
currentFastMode ? "Fast" : null, capabilities: currentModelOption?.capabilities,
currentContextWindow !== "1M" ? currentContextWindow : null, selections: currentModelSelection.options,
].filter((part): part is string => Boolean(part)); }),
return parts.length > 0 ? parts.join(" · ") : "Configuration"; [currentModelOption?.capabilities, currentModelSelection.options],
}, [currentContextWindow, currentEffort, currentFastMode]); );
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const modelMenuActions = useMemo( const modelMenuActions = useMemo(
() => () =>
providerGroups.map((group) => ({ providerGroups.map((group) => ({
@@ -486,36 +543,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
// ── Options menu ───────────────────────────────────────── // ── Options menu ─────────────────────────────────────────
const optionsMenuActions = useMemo( const optionsMenuActions = useMemo(
() => [ () => [
{ ...buildProviderOptionMenuActions(providerOptionDescriptors),
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,
})),
},
{ {
id: "options-runtime", id: "options-runtime",
title: "Runtime", title: "Runtime",
@@ -555,13 +583,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}), }),
}, },
], ],
[ [currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
currentEffort,
currentFastMode,
currentContextWindow,
currentRuntimeMode,
currentInteractionMode,
],
); );
// ── Menu handlers ──────────────────────────────────────── // ── Menu handlers ────────────────────────────────────────
@@ -572,51 +594,27 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const modelKey = event.slice("model:".length); const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey); const option = modelOptions.find((o) => o.key === modelKey);
if (option) { if (option) {
void props.onUpdateModelSelection(option.selection); props.onUpdateModelSelection(option.selection);
} }
} }
function handleOptionsMenuAction(event: string) { function handleOptionsMenuAction(event: string) {
if (event.startsWith("options:effort:")) { const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
const effort = event.slice("options:effort:".length); if (providerOptions) {
const updated: ModelSelection = props.onUpdateModelSelection({
selectedProviderDriver === "claudeAgent" ...currentModelSelection,
? withModelSelectionOption( options: providerOptions,
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);
return; return;
} }
if (event.startsWith("options:runtime:")) { if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode; const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
void props.onUpdateRuntimeMode(runtimeMode); props.onUpdateRuntimeMode(runtimeMode);
return; return;
} }
if (event.startsWith("options:interaction:")) { if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode; 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> </View>
) : null} ) : null}
{connectionStatus ? (
<ComposerConnectionStatusPill
status={connectionStatus}
onPress={props.onReconnectEnvironment}
/>
) : null}
<ComposerSurface <ComposerSurface
isDarkMode={isDarkMode} isDarkMode={isDarkMode}
style={ style={
@@ -755,11 +760,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null} ) : null}
{!isExpanded ? ( {!isExpanded ? (
showStopAction ? ( showStopAction ? (
<ControlPill <ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
icon="stop.fill"
variant="danger"
onPress={() => void props.onStopThread()}
/>
) : ( ) : (
<ControlPill <ControlPill
icon="arrow.up" icon="arrow.up"
@@ -809,7 +810,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
<ComposerToolbarButton <ComposerToolbarButton
icon="stop.fill" icon="stop.fill"
variant="danger" variant="danger"
onPress={() => void props.onStopThread()} onPress={props.onStopThread}
showChevron={false} showChevron={false}
/> />
) : null} ) : null}
@@ -1,8 +1,9 @@
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { import type {
ApprovalRequestId, ApprovalRequestId,
EnvironmentId, EnvironmentId,
ModelSelection, ModelSelection,
OrchestrationThread, OrchestrationThreadShell,
ProviderApprovalDecision, ProviderApprovalDecision,
ProviderInteractionMode, ProviderInteractionMode,
RuntimeMode, RuntimeMode,
@@ -23,7 +24,7 @@ import { AppText as Text } from "../../components/AppText";
import type { ComposerEditorHandle } from "../../components/ComposerEditor"; import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill"; import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { MobileLayoutVariant } from "../../lib/mobileLayout"; import type { LayoutVariant } from "../../lib/layout";
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout"; import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
import type { import type {
PendingApproval, PendingApproval,
@@ -39,13 +40,14 @@ import {
ThreadComposer, ThreadComposer,
} from "./ThreadComposer"; } from "./ThreadComposer";
import { ThreadFeed } from "./ThreadFeed"; import { ThreadFeed } from "./ThreadFeed";
import type { ThreadContentPresentation } from "./threadContentPresentation";
export interface ThreadDetailScreenProps { export interface ThreadDetailScreenProps {
readonly selectedThread: OrchestrationThread; readonly selectedThread: OrchestrationThreadShell;
readonly contentPresentation: ThreadContentPresentation;
readonly screenTone: StatusTone; readonly screenTone: StatusTone;
readonly connectionError: string | null; readonly connectionError: string | null;
readonly httpBaseUrl: string | null; readonly environmentLabel: string | null;
readonly bearerToken: string | null;
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>; readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
readonly activeWorkStartedAt: string | null; readonly activeWorkStartedAt: string | null;
readonly activePendingApproval: PendingApproval | null; readonly activePendingApproval: PendingApproval | null;
@@ -56,30 +58,29 @@ export interface ThreadDetailScreenProps {
readonly respondingUserInputId: ApprovalRequestId | null; readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string; readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>; readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: "ready" | "connecting" | "reconnecting" | "disconnected" | "idle"; readonly connectionStateLabel: EnvironmentConnectionPhase;
readonly activeThreadBusy: boolean; readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId; readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null; readonly projectWorkspaceRoot: string | null;
readonly selectedThreadQueueCount: number; readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null; readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: MobileLayoutVariant; readonly layoutVariant?: LayoutVariant;
readonly onOpenDrawer: () => void; readonly onOpenDrawer: () => void;
readonly onOpenConnectionEditor: () => void; readonly onOpenConnectionEditor: () => void;
readonly onChangeDraftMessage: (value: string) => void; readonly onChangeDraftMessage: (value: string) => void;
readonly onPickDraftImages: () => Promise<void>; readonly onPickDraftImages: () => Promise<void>;
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>; readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void; readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => Promise<void>; readonly onStopThread: () => void;
readonly onSendMessage: () => void; readonly onSendMessage: () => Promise<void>;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => Promise<void>; readonly onReconnectEnvironment: () => void;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => Promise<void>; readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateThreadInteractionMode: ( readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
interactionMode: ProviderInteractionMode, readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
) => Promise<void>;
readonly onRespondToApproval: ( readonly onRespondToApproval: (
requestId: ApprovalRequestId, requestId: ApprovalRequestId,
decision: ProviderApprovalDecision, decision: ProviderApprovalDecision,
) => Promise<void>; ) => Promise<unknown>;
readonly onSelectUserInputOption: ( readonly onSelectUserInputOption: (
requestId: ApprovalRequestId, requestId: ApprovalRequestId,
questionId: string, questionId: string,
@@ -90,7 +91,7 @@ export interface ThreadDetailScreenProps {
questionId: string, questionId: string,
customAnswer: string, customAnswer: string,
) => void; ) => void;
readonly onSubmitUserInput: () => Promise<void>; readonly onSubmitUserInput: () => Promise<unknown>;
readonly showContent?: boolean; readonly showContent?: boolean;
} }
@@ -306,10 +307,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
> >
<ThreadFeed <ThreadFeed
key={props.selectedThread.id} key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id} threadId={props.selectedThread.id}
feed={props.selectedThreadFeed} feed={props.selectedThreadFeed}
httpBaseUrl={props.httpBaseUrl} contentPresentation={props.contentPresentation}
bearerToken={props.bearerToken}
agentLabel={agentLabel} agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn} latestTurn={props.selectedThread.latestTurn}
contentTopInset={headerHeight} contentTopInset={headerHeight}
@@ -363,6 +364,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
draftAttachments={props.draftAttachments} draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…" placeholder="Ask the repo agent, or run a command…"
connectionState={props.connectionStateLabel} connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
selectedThread={props.selectedThread} selectedThread={props.selectedThread}
serverConfig={props.serverConfig} serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount} queueCount={props.selectedThreadQueueCount}
@@ -376,6 +379,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onRemoveDraftImage={props.onRemoveDraftImage} onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread} onStopThread={props.onStopThread}
onSendMessage={props.onSendMessage} onSendMessage={props.onSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection} onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode} onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode} onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
+112 -65
View File
@@ -2,7 +2,7 @@ import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics"; import * as Haptics from "expo-haptics";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard"; import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native"; 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 { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { import {
@@ -12,6 +12,7 @@ import {
type PartialMarkdownTheme, type PartialMarkdownTheme,
} from "react-native-nitro-markdown"; } from "react-native-nitro-markdown";
import { import {
ActivityIndicator,
Image, Image,
Linking, Linking,
type NativeScrollEvent, type NativeScrollEvent,
@@ -37,7 +38,6 @@ import {
} from "../../native/SelectableMarkdownText"; } from "../../native/SelectableMarkdownText";
import { AppText as Text } from "../../components/AppText"; import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { CopyTextButton } from "../../components/CopyTextButton"; import { CopyTextButton } from "../../components/CopyTextButton";
import { import {
parseReviewCommentMessageSegments, parseReviewCommentMessageSegments,
@@ -53,7 +53,7 @@ import {
} from "../review/nativeReviewDiffAdapter"; } from "../review/nativeReviewDiffAdapter";
import { buildReviewParsedDiff } from "../review/reviewModel"; import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn"; 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 { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links"; import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
import { import {
@@ -63,7 +63,8 @@ import {
} from "../../lib/threadActivity"; } from "../../lib/threadActivity";
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout"; import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
import { relativeTime } from "../../lib/time"; 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 THREAD_FEED_END_THRESHOLD = 80;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, { const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
@@ -80,19 +81,45 @@ function formatMessageTime(input: string): string {
} }
export interface ThreadFeedProps { export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId; readonly threadId: ThreadId;
readonly feed: ReadonlyArray<ThreadFeedEntry>; readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly httpBaseUrl: string | null; readonly contentPresentation: ThreadContentPresentation;
readonly bearerToken: string | null;
readonly agentLabel: string; readonly agentLabel: string;
readonly latestTurn: ThreadFeedLatestTurn | null; readonly latestTurn: ThreadFeedLatestTurn | null;
readonly contentTopInset?: number; readonly contentTopInset?: number;
readonly contentBottomInset?: number; readonly contentBottomInset?: number;
readonly layoutVariant?: MobileLayoutVariant; readonly layoutVariant?: LayoutVariant;
readonly composerExpanded?: boolean; readonly composerExpanded?: boolean;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>; 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 { function stripShellWrapper(value: string): string {
const trimmed = value.trim(); const trimmed = value.trim();
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/); const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
@@ -654,7 +681,7 @@ function useMarkdownStyles(): MarkdownStyleSets {
function renderFeedEntry( function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number }, info: { item: ThreadFeedEntry; index: number },
props: Pick<ThreadFeedProps, "bearerToken" | "httpBaseUrl" | "skills"> & { props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
readonly copiedRowId: string | null; readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>; readonly expandedWorkGroups: Record<string, boolean>;
readonly expandedWorkRows: Record<string, boolean>; readonly expandedWorkRows: Record<string, boolean>;
@@ -733,26 +760,14 @@ function renderFeedEntry(
/> />
) : null} ) : null}
{attachments.map((attachment) => { {attachments.map((attachment) => {
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
if (!uri) {
return null;
}
const headers = props.bearerToken
? { Authorization: `Bearer ${props.bearerToken}` }
: undefined;
return ( return (
<TouchableOpacity <MessageAttachmentImage
key={attachment.id} key={attachment.id}
activeOpacity={0.7} environmentId={props.environmentId}
onPress={() => props.onPressImage(uri, headers)} attachmentId={attachment.id}
> className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
<Image onPressImage={props.onPressImage}
source={{ uri, ...(headers ? { headers } : {}) }} />
className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
resizeMode="cover"
/>
</TouchableOpacity>
); );
})} })}
</View> </View>
@@ -801,27 +816,14 @@ function renderFeedEntry(
) )
) : null} ) : null}
{attachments.map((attachment) => { {attachments.map((attachment) => {
const uri = messageImageUrl(props.httpBaseUrl, attachment.id);
if (!uri) {
return null;
}
const headers = props.bearerToken
? { Authorization: `Bearer ${props.bearerToken}` }
: undefined;
return ( return (
<TouchableOpacity <MessageAttachmentImage
key={attachment.id} key={attachment.id}
activeOpacity={0.7} environmentId={props.environmentId}
className="mt-1.5" attachmentId={attachment.id}
onPress={() => props.onPressImage(uri, headers)} className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
> onPressImage={props.onPressImage}
<Image />
source={{ uri, ...(headers ? { headers } : {}) }}
className="aspect-[1.3] w-full rounded-[18px] bg-neutral-200 dark:bg-neutral-800"
resizeMode="cover"
/>
</TouchableOpacity>
); );
})} })}
{showAssistantMeta ? ( {showAssistantMeta ? (
@@ -1220,6 +1222,37 @@ function compactFileName(filePath: string): string {
return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized; 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) { export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listRef = useRef<LegendListRef>(null); const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null); const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -1446,9 +1479,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const renderItem = useCallback( const renderItem = useCallback(
(info: { item: ThreadFeedEntry; index: number }) => (info: { item: ThreadFeedEntry; index: number }) =>
renderFeedEntry(info, { renderFeedEntry(info, {
bearerToken: props.bearerToken, environmentId: props.environmentId,
copiedRowId, copiedRowId,
httpBaseUrl: props.httpBaseUrl,
expandedWorkGroups, expandedWorkGroups,
expandedWorkRows, expandedWorkRows,
terminalAssistantMessageIds, terminalAssistantMessageIds,
@@ -1481,30 +1513,45 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleTurnFold, onToggleTurnFold,
onToggleWorkGroup, onToggleWorkGroup,
onToggleWorkRow, onToggleWorkRow,
props.bearerToken, props.environmentId,
props.httpBaseUrl,
props.skills, 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) { if (props.feed.length === 0) {
return ( return (
<ScrollView <ThreadFeedPlaceholder
style={{ flex: 1 }} title="No conversation yet"
contentInsetAdjustmentBehavior="never" detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
contentInset={{ top: topContentInset, bottom: bottomContentInset }} topInset={topContentInset}
contentOffset={{ x: 0, y: -topContentInset }} bottomInset={bottomContentInset}
scrollIndicatorInsets={{ top: topContentInset, bottom: bottomContentInset }} horizontalPadding={horizontalPadding}
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>
); );
} }
@@ -9,7 +9,7 @@ import {
type GitActionRequestInput, type GitActionRequestInput,
requiresDefaultBranchConfirmation, requiresDefaultBranchConfirmation,
resolveQuickAction, resolveQuickAction,
} from "@t3tools/client-runtime"; } from "@t3tools/client-runtime/state/vcs";
import { useLocalSearchParams, useRouter } from "expo-router"; import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack"; import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react"; import { useCallback, useMemo } from "react";
@@ -1,6 +1,13 @@
import { SymbolView } from "expo-symbols"; import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo, useState } from "react"; 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 Arr from "effect/Array";
import * as Order from "effect/Order"; import * as Order from "effect/Order";
import { Gesture, GestureDetector } from "react-native-gesture-handler"; 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 { AppText as Text } from "../../components/AppText";
import { StatusPill } from "../../components/StatusPill"; import { StatusPill } from "../../components/StatusPill";
import { useProjects, useThreadShells } from "../../state/entities";
import { groupProjectsByRepository } from "../../lib/repositoryGroups"; import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedThreadKey } from "../../lib/scopedEntities"; import { scopedThreadKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time"; import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "./threadPresentation"; import { threadStatusTone } from "./threadPresentation";
import { import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
EnvironmentScopedProjectShell,
EnvironmentScopedThreadShell,
} from "@t3tools/client-runtime";
const threadActivityOrder = Order.mapInput( const threadActivityOrder = Order.mapInput(
Order.Struct({ Order.Struct({
activityAt: Order.flip(Order.Number), activityAt: Order.flip(Order.Number),
title: Order.String, title: Order.String,
}), }),
(thread: EnvironmentScopedThreadShell) => ({ (thread: EnvironmentThreadShell) => ({
activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(), activityAt: new Date(thread.updatedAt ?? thread.createdAt).getTime(),
title: thread.title, title: thread.title,
}), }),
@@ -37,11 +42,9 @@ const threadActivityOrder = Order.mapInput(
export function ThreadNavigationDrawer(props: { export function ThreadNavigationDrawer(props: {
readonly visible: boolean; readonly visible: boolean;
readonly projects: ReadonlyArray<EnvironmentScopedProjectShell>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly selectedThreadKey: string | null; readonly selectedThreadKey: string | null;
readonly onClose: () => void; readonly onClose: () => void;
readonly onSelectThread: (thread: EnvironmentScopedThreadShell) => void; readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onStartNewTask: () => void; readonly onStartNewTask: () => void;
}) { }) {
const insets = useSafeAreaInsets(); const insets = useSafeAreaInsets();
@@ -57,26 +60,6 @@ export function ThreadNavigationDrawer(props: {
const primaryForeground = useThemeColor("--color-primary-foreground"); const primaryForeground = useThemeColor("--color-primary-foreground");
const borderSubtleColor = useThemeColor("--color-border-subtle"); 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(() => { useEffect(() => {
if (props.visible) { if (props.visible) {
setMounted(true); setMounted(true);
@@ -186,76 +169,116 @@ export function ThreadNavigationDrawer(props: {
</Pressable> </Pressable>
</View> </View>
<ScrollView <ThreadNavigationDrawerContent
showsVerticalScrollIndicator={false} bottomInset={Math.max(insets.bottom, 18)}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 12 }} borderSubtleColor={borderSubtleColor}
contentContainerStyle={{ selectedThreadKey={props.selectedThreadKey}
gap: 20, onClose={props.onClose}
paddingHorizontal: 14, onSelectThread={props.onSelectThread}
}} />
>
{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>
</Animated.View> </Animated.View>
</GestureDetector> </GestureDetector>
</View> </View>
</Modal> </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 { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react"; import { useCallback, useMemo, useState } from "react";
import * as Arr from "effect/Array";
import * as Option from "effect/Option"; import * as Option from "effect/Option";
import { pipe } from "effect/Function"; import {
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts"; EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native"; import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useWorkspaceState } from "../../state/workspace";
import { useThemeColor } from "../../lib/useThemeColor"; 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 { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
import { vcsEnvironment } from "../../state/vcs";
import { EmptyState } from "../../components/EmptyState"; import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen"; import { LoadingScreen } from "../../components/LoadingScreen";
@@ -16,13 +22,13 @@ import { buildThreadRoutePath, buildThreadTerminalNavigation } from "../../lib/r
import { scopedThreadKey } from "../../lib/scopedEntities"; import { scopedThreadKey } from "../../lib/scopedEntities";
import { connectionTone } from "../connection/connectionTone"; import { connectionTone } from "../connection/connectionTone";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { import {
useRemoteConnections,
useRemoteConnectionStatus, useRemoteConnectionStatus,
useRemoteEnvironmentState, useRemoteEnvironmentRuntime,
} from "../../state/use-remote-environment-registry"; } from "../../state/use-remote-environment-registry";
import { useKnownTerminalSessions } from "../../state/use-terminal-session"; 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 { useThreadSelection } from "../../state/use-thread-selection";
import { GitActionProgressOverlay } from "./GitActionProgressOverlay"; import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
import { import {
@@ -38,12 +44,14 @@ import { terminalDebugLog } from "../terminal/terminalDebugLog";
import { ThreadDetailScreen } from "./ThreadDetailScreen"; import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls"; import { ThreadGitControls } from "./ThreadGitControls";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer"; 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 { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state"; import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests"; import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree"; import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useThreadComposerState } from "../../state/use-thread-composer-state"; 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 { function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) { if (Array.isArray(value)) {
@@ -58,22 +66,31 @@ function OpeningThreadLoadingScreen() {
} }
export function ThreadRouteScreen() { export function ThreadRouteScreen() {
const { isLoadingSavedConnection, environmentStateById, pendingConnectionError } = const { state: workspaceState } = useWorkspaceState();
useRemoteEnvironmentState(); const { connectionState } = useRemoteConnectionStatus();
const { connectionState, connectionError: aggregateConnectionError } = const { onReconnectEnvironment } = useRemoteConnections();
useRemoteConnectionStatus();
const { projects, threads } = useRemoteCatalog();
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } = const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
useThreadSelection(); useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail(); const selectedThreadDetailState = useSelectedThreadDetailState();
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
const { selectedThreadCwd } = useSelectedThreadWorktree(); const { selectedThreadCwd } = useSelectedThreadWorktree();
const composer = useThreadComposerState(); const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState(); const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions(); const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests(); const requests = useSelectedThreadRequests();
const commands = useSelectedThreadCommands({ const updateThreadMetadata = useAtomCommand(
refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus, 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 router = useRouter();
const params = useLocalSearchParams<{ const params = useLocalSearchParams<{
environmentId?: string | string[]; environmentId?: string | string[];
@@ -83,12 +100,10 @@ export function ThreadRouteScreen() {
const environmentIdRaw = firstRouteParam(params.environmentId); const environmentIdRaw = firstRouteParam(params.environmentId);
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null; const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
const threadId = firstRouteParam(params.threadId); const threadId = firstRouteParam(params.threadId);
const routeEnvironmentRuntime = environmentId const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
? (environmentStateById[environmentId] ?? null) const routeConnectionState =
: null; routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? connectionState; const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
const routeConnectionError =
pendingConnectionError ?? routeEnvironmentRuntime?.connectionError ?? aggregateConnectionError;
/* ─── Native header theming ──────────────────────────────────────── */ /* ─── Native header theming ──────────────────────────────────────── */
const iconColor = String(useThemeColor("--color-icon")); const iconColor = String(useThemeColor("--color-icon"));
@@ -96,10 +111,14 @@ export function ThreadRouteScreen() {
const secondaryFg = String(useThemeColor("--color-foreground-secondary")); const secondaryFg = String(useThemeColor("--color-foreground-secondary"));
/* ─── Git status for native header trigger ───────────────────────── */ /* ─── Git status for native header trigger ───────────────────────── */
const gitStatus = useVcsStatus({ const gitStatus = useEnvironmentQuery(
environmentId: selectedThread?.environmentId ?? null, selectedThread !== null && selectedThreadCwd !== null
cwd: selectedThreadCwd, ? vcsEnvironment.status({
}); environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const knownTerminalSessions = useKnownTerminalSessions({ const knownTerminalSessions = useKnownTerminalSessions({
environmentId: selectedThread?.environmentId ?? null, environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null, threadId: selectedThread?.id ?? null,
@@ -113,6 +132,12 @@ export function ThreadRouteScreen() {
[knownTerminalSessions, selectedThreadProject?.workspaceRoot], [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
); );
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null; const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
const handleReconnectEnvironment = useCallback(() => {
if (!environmentId) {
return;
}
onReconnectEnvironment(environmentId);
}, [environmentId, onReconnectEnvironment]);
/* ─── Git action progress (for overlay banner) ──────────────────── */ /* ─── Git action progress (for overlay banner) ──────────────────── */
const gitActionProgressTarget = useMemo( const gitActionProgressTarget = useMemo(
@@ -131,6 +156,69 @@ export function ThreadRouteScreen() {
const handleOpenConnectionEditor = useCallback(() => { const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections"); void router.push("/connections");
}, [router]); }, [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( const handleOpenTerminal = useCallback(
(nextTerminalId?: string | null) => { (nextTerminalId?: string | null) => {
@@ -238,7 +326,7 @@ export function ThreadRouteScreen() {
if (!selectedThread) { if (!selectedThread) {
const stillHydrating = const stillHydrating =
isLoadingSavedConnection || workspaceState.isLoadingConnections ||
routeConnectionState === "connecting" || routeConnectionState === "connecting" ||
routeConnectionState === "reconnecting"; routeConnectionState === "reconnecting";
@@ -265,19 +353,14 @@ export function ThreadRouteScreen() {
); );
} }
if (!selectedThreadDetail) {
return <OpeningThreadLoadingScreen />;
}
const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id); const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
const serverConfig = const contentPresentation = projectThreadContentPresentation({
routeEnvironmentRuntime?.serverConfig ?? hasDetail: selectedThreadDetail !== null,
pipe( detailError: Option.getOrNull(selectedThreadDetailState.error),
Object.values(environmentStateById), detailDeleted: selectedThreadDetailState.status === "deleted",
Arr.map((runtime) => runtime.serverConfig), connectionState: routeConnectionState,
Arr.findFirst((value) => value !== null), });
Option.getOrNull, const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
);
const headerSubtitle = [ const headerSubtitle = [
selectedThreadProject?.title ?? null, selectedThreadProject?.title ?? null,
@@ -313,7 +396,7 @@ export function ThreadRouteScreen() {
letterSpacing: -0.4, letterSpacing: -0.4,
}} }}
> >
{selectedThreadDetail.title} {selectedThread.title}
</RNText> </RNText>
<RNText <RNText
numberOfLines={1} numberOfLines={1}
@@ -333,7 +416,7 @@ export function ThreadRouteScreen() {
/> />
<ThreadGitControls <ThreadGitControls
currentBranch={selectedThreadDetail.branch} currentBranch={selectedThread.branch}
gitStatus={gitStatus.data} gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel} gitOperationLabel={gitState.gitOperationLabel}
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)} canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
@@ -350,11 +433,11 @@ export function ThreadRouteScreen() {
<View className="flex-1 bg-screen"> <View className="flex-1 bg-screen">
<ThreadDetailScreen <ThreadDetailScreen
selectedThread={selectedThreadDetail} selectedThread={selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)} screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError} connectionError={routeConnectionError}
httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null} environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
selectedThreadFeed={composer.selectedThreadFeed} selectedThreadFeed={composer.selectedThreadFeed}
activeWorkStartedAt={composer.activeWorkStartedAt} activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={requests.activePendingApproval} activePendingApproval={requests.activePendingApproval}
@@ -377,11 +460,12 @@ export function ThreadRouteScreen() {
onNativePasteImages={composer.onNativePasteImages} onNativePasteImages={composer.onNativePasteImages}
onRemoveDraftImage={composer.onRemoveDraftImage} onRemoveDraftImage={composer.onRemoveDraftImage}
serverConfig={serverConfig} serverConfig={serverConfig}
onStopThread={commands.onStopThread} onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage} onSendMessage={composer.onSendMessage}
onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection} onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode} onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode} onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onRespondToApproval={requests.onRespondToApproval} onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption} onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer} onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -390,8 +474,6 @@ export function ThreadRouteScreen() {
<ThreadNavigationDrawer <ThreadNavigationDrawer
visible={drawerVisible} visible={drawerVisible}
projects={projects}
threads={threads}
selectedThreadKey={selectedThreadKey} selectedThreadKey={selectedThreadKey}
onClose={() => setDrawerVisible(false)} onClose={() => setDrawerVisible(false)}
onSelectThread={(thread) => { 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 { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText"; 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 { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
import { vcsEnvironment } from "../../../state/vcs";
import { SheetActionButton } from "./gitSheetComponents"; import { SheetActionButton } from "./gitSheetComponents";
export function GitBranchesSheet() { export function GitBranchesSheet() {
@@ -27,10 +28,14 @@ export function GitBranchesSheet() {
const foregroundColor = useThemeColor("--color-foreground"); const foregroundColor = useThemeColor("--color-foreground");
const subtleStrongColor = useThemeColor("--color-subtle-strong"); const subtleStrongColor = useThemeColor("--color-subtle-strong");
const gitStatus = useVcsStatus({ const gitStatus = useEnvironmentQuery(
environmentId: selectedThread?.environmentId ?? null, selectedThread !== null && selectedThreadCwd !== null
cwd: selectedThreadCwd, ? vcsEnvironment.status({
}); environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD"; const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
const currentWorktreePath = selectedThreadWorktreePath; const currentWorktreePath = selectedThreadWorktreePath;
@@ -5,11 +5,12 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../../lib/useThemeColor"; import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText"; 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 { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
import { vcsEnvironment } from "../../../state/vcs";
import { SheetActionButton } from "./gitSheetComponents"; import { SheetActionButton } from "./gitSheetComponents";
export function GitCommitSheet() { export function GitCommitSheet() {
@@ -27,10 +28,14 @@ export function GitCommitSheet() {
const inputBg = useThemeColor("--color-input"); const inputBg = useThemeColor("--color-input");
const foregroundColor = useThemeColor("--color-foreground"); const foregroundColor = useThemeColor("--color-foreground");
const gitStatus = useVcsStatus({ const gitStatus = useEnvironmentQuery(
environmentId: selectedThread?.environmentId ?? null, selectedThread !== null && selectedThreadCwd !== null
cwd: selectedThreadCwd, ? vcsEnvironment.status({
}); environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const busy = gitState.gitOperationLabel !== null; const busy = gitState.gitOperationLabel !== null;
const isDefaultRef = gitStatus.data?.isDefaultRef ?? false; 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 { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
import * as Arr from "effect/Array"; import * as Arr from "effect/Array";
import * as Result from "effect/Result"; import * as Result from "effect/Result";
@@ -3,7 +3,7 @@ import {
buildMenuItems, buildMenuItems,
getGitActionDisabledReason, getGitActionDisabledReason,
requiresDefaultBranchConfirmation, requiresDefaultBranchConfirmation,
} from "@t3tools/client-runtime"; } from "@t3tools/client-runtime/state/vcs";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router"; import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols"; import { SymbolView } from "expo-symbols";
@@ -14,11 +14,12 @@ import { useThemeColor } from "../../../lib/useThemeColor";
import { AppText as Text } from "../../../components/AppText"; import { AppText as Text } from "../../../components/AppText";
import { buildThreadReviewRoutePath } from "../../../lib/routes"; 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 { useThreadSelection } from "../../../state/use-thread-selection";
import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
import { vcsEnvironment } from "../../../state/vcs";
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents"; import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
export function GitOverviewSheet() { export function GitOverviewSheet() {
@@ -36,10 +37,14 @@ export function GitOverviewSheet() {
const iconColor = useThemeColor("--color-icon"); const iconColor = useThemeColor("--color-icon");
const borderColor = useThemeColor("--color-border"); const borderColor = useThemeColor("--color-border");
const gitStatus = useVcsStatus({ const gitStatus = useEnvironmentQuery(
environmentId: selectedThread?.environmentId ?? null, selectedThread !== null && selectedThreadCwd !== null
cwd: selectedThreadCwd, ? vcsEnvironment.status({
}); environmentId: selectedThread.environmentId,
input: { cwd: selectedThreadCwd },
})
: null,
);
const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD"; const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
const currentWorktreePath = selectedThreadWorktreePath; 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 { import type {
EnvironmentId, EnvironmentId,
ModelSelection, ModelSelection,
ProviderInteractionMode, ProviderInteractionMode,
ProviderOptionSelection,
RuntimeMode, RuntimeMode,
ServerProviderSkill, ServerProviderSkill,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
@@ -11,6 +12,7 @@ import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tool
import * as Arr from "effect/Array"; import * as Arr from "effect/Array";
import { pipe } from "effect/Function"; import { pipe } from "effect/Function";
import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";
import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
@@ -23,21 +25,17 @@ import {
setComposerDraftText, setComposerDraftText,
useComposerDraft, useComposerDraft,
} from "../../state/use-composer-drafts"; } from "../../state/use-composer-drafts";
import { vcsRefManager, useVcsRefs } from "../../state/use-vcs-refs"; import { useBranches } from "../../state/queries";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import { import {
setPendingConnectionError, setPendingConnectionError,
useRemoteEnvironmentState, useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry"; } from "../../state/use-remote-environment-registry";
import { EnvironmentScopedProjectShell, type VcsRef } from "@t3tools/client-runtime"; import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import type { ClaudeAgentEffort } from "./claudeEffortOptions"; import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree"; type WorkspaceMode = "local" | "worktree";
function normalizeSelectedWorktreePath( function normalizeSelectedWorktreePath(project: EnvironmentProject, branch: VcsRef): string | null {
project: EnvironmentScopedProjectShell,
branch: VcsRef,
): string | null {
if (!branch.worktreePath) { if (!branch.worktreePath) {
return null; return null;
} }
@@ -47,7 +45,7 @@ function normalizeSelectedWorktreePath(
export function branchBadgeLabel(input: { export function branchBadgeLabel(input: {
readonly branch: VcsRef; readonly branch: VcsRef;
readonly project: EnvironmentScopedProjectShell | null; readonly project: EnvironmentProject | null;
}): string | null { }): string | null {
if (input.branch.current) { if (input.branch.current) {
return "current"; return "current";
@@ -67,7 +65,7 @@ export function branchBadgeLabel(input: {
type NewTaskFlowContextValue = { type NewTaskFlowContextValue = {
readonly logicalProjects: ReadonlyArray<{ readonly logicalProjects: ReadonlyArray<{
readonly key: string; readonly key: string;
readonly project: EnvironmentScopedProjectShell; readonly project: EnvironmentProject;
}>; }>;
readonly selectedEnvironmentId: EnvironmentId | null; readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null; readonly selectedProjectKey: string | null;
@@ -83,15 +81,12 @@ type NewTaskFlowContextValue = {
readonly availableBranches: ReadonlyArray<VcsRef>; readonly availableBranches: ReadonlyArray<VcsRef>;
readonly runtimeMode: RuntimeMode; readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode; readonly interactionMode: ProviderInteractionMode;
readonly effort: ClaudeAgentEffort;
readonly fastMode: boolean;
readonly contextWindow: string;
readonly expandedProvider: string | null; readonly expandedProvider: string | null;
readonly environments: ReadonlyArray<{ readonly environments: ReadonlyArray<{
readonly environmentId: EnvironmentId; readonly environmentId: EnvironmentId;
readonly environmentLabel: string; readonly environmentLabel: string;
}>; }>;
readonly selectedProject: EnvironmentScopedProjectShell | null; readonly selectedProject: EnvironmentProject | null;
readonly modelOptions: ReadonlyArray<ModelOption>; readonly modelOptions: ReadonlyArray<ModelOption>;
readonly selectedModel: ModelSelection | null; readonly selectedModel: ModelSelection | null;
readonly selectedModelOption: ModelOption | null; readonly selectedModelOption: ModelOption | null;
@@ -99,7 +94,7 @@ type NewTaskFlowContextValue = {
readonly providerGroups: ReadonlyArray<ProviderGroup>; readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly filteredBranches: ReadonlyArray<VcsRef>; readonly filteredBranches: ReadonlyArray<VcsRef>;
readonly reset: () => void; readonly reset: () => void;
readonly setProject: (project: EnvironmentScopedProjectShell) => void; readonly setProject: (project: EnvironmentProject) => void;
readonly selectEnvironment: (environmentId: EnvironmentId) => void; readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly setSelectedModelKey: (key: string | null) => void; readonly setSelectedModelKey: (key: string | null) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void; readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
@@ -114,17 +109,18 @@ type NewTaskFlowContextValue = {
readonly loadBranches: () => Promise<void>; readonly loadBranches: () => Promise<void>;
readonly setRuntimeMode: (value: RuntimeMode) => void; readonly setRuntimeMode: (value: RuntimeMode) => void;
readonly setInteractionMode: (value: ProviderInteractionMode) => void; readonly setInteractionMode: (value: ProviderInteractionMode) => void;
readonly setEffort: (value: ClaudeAgentEffort) => void; readonly setSelectedModelOptions: (
readonly setFastMode: (value: boolean) => void; value: ReadonlyArray<ProviderOptionSelection> | undefined,
readonly setContextWindow: (value: string) => void; ) => void;
readonly setExpandedProvider: (value: string | null) => void; readonly setExpandedProvider: (value: string | null) => void;
}; };
const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null); const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
export function NewTaskFlowProvider(props: React.PropsWithChildren) { export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const { projects, serverConfigByEnvironmentId, threads } = useRemoteCatalog(); const projects = useProjects();
const { savedConnectionsById } = useRemoteEnvironmentState(); const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
const repositoryGroups = useMemo( const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }), () => groupProjectsByRepository({ projects, threads }),
@@ -146,16 +142,21 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
entry, entry,
): entry is { ): entry is {
readonly key: string; readonly key: string;
readonly project: EnvironmentScopedProjectShell; readonly project: EnvironmentProject;
} => entry !== null, } => entry !== null,
), ),
), ),
[repositoryGroups], [repositoryGroups],
); );
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>( const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
projects[0]?.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 [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null); const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local"); const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
@@ -168,17 +169,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>( const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_PROVIDER_INTERACTION_MODE,
); );
const [effort, setEffort] = useState<ClaudeAgentEffort>("high"); const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
const [fastMode, setFastMode] = useState(false); Record<string, ModelSelection>
const [contextWindow, setContextWindow] = useState("1M"); >({});
const [expandedProvider, setExpandedProvider] = useState<string | null>(null); const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const reset = useCallback(() => { const reset = useCallback(() => {
console.log("[new task flow] reset", { setSelectedEnvironmentId(null);
defaultEnvironmentId: projects[0]?.environmentId ?? null,
projectCount: projects.length,
});
setSelectedEnvironmentId(projects[0]?.environmentId ?? null);
setSelectedProjectKey(null); setSelectedProjectKey(null);
setSelectedModelKey(null); setSelectedModelKey(null);
setWorkspaceMode("local"); setWorkspaceMode("local");
@@ -188,22 +185,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setBranchQuery(""); setBranchQuery("");
setRuntimeMode(DEFAULT_RUNTIME_MODE); setRuntimeMode(DEFAULT_RUNTIME_MODE);
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE); setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
setEffort("high"); setModelSelectionOverrides({});
setFastMode(false);
setContextWindow("1M");
setExpandedProvider(null); 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( const environments = useMemo(
() => () =>
@@ -254,6 +238,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
) ?? ) ??
projectsForEnvironment[0] ?? projectsForEnvironment[0] ??
null; null;
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
);
const selectedProjectDraftKey = selectedProject const selectedProjectDraftKey = selectedProject
? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}` ? `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`
: null; : null;
@@ -264,19 +251,29 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const modelOptions = useMemo( const modelOptions = useMemo(
() => () =>
buildModelOptions( buildModelOptions(
selectedProject selectedEnvironmentServerConfig,
? (serverConfigByEnvironmentId[selectedProject.environmentId] ?? null)
: null,
selectedProject?.defaultModelSelection ?? null, 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 ?? modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
(defaultModelKey
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
: null) ??
selectedProject?.defaultModelSelection ?? selectedProject?.defaultModelSelection ??
modelOptions[0]?.selection ?? modelOptions[0]?.selection ??
null; null;
const selectedModelIdentity = baseSelectedModel
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
: null;
const selectedModel =
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
baseSelectedModel;
const selectedModelOption = const selectedModelOption =
modelOptions.find( modelOptions.find(
@@ -286,11 +283,27 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.model === selectedModel.model, option.selection.model === selectedModel.model,
) ?? null; ) ?? null;
const selectedProviderSkills = const selectedProviderSkills =
(selectedProject selectedEnvironmentServerConfig?.providers.find(
? serverConfigByEnvironmentId[selectedProject.environmentId] (provider) => provider.instanceId === selectedModel?.instanceId,
: null )?.skills ?? [];
)?.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 providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
const setPrompt = useCallback( const setPrompt = useCallback(
@@ -343,7 +356,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}), }),
[selectedProject?.environmentId, selectedProject?.workspaceRoot], [selectedProject?.environmentId, selectedProject?.workspaceRoot],
); );
const branchState = useVcsRefs(branchTarget); const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending; const branchesLoading = branchState.isPending;
const availableBranches = useMemo( const availableBranches = useMemo(
() => () =>
@@ -366,13 +379,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
); );
}, [availableBranches, branchQuery]); }, [availableBranches, branchQuery]);
const setProject = useCallback((project: EnvironmentScopedProjectShell) => { const setProject = useCallback((project: EnvironmentProject) => {
const nextProjectKey = scopedProjectKey(project.environmentId, project.id); const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
branchLoadVersionRef.current += 1; branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(project.environmentId); setSelectedEnvironmentId(project.environmentId);
setSelectedProjectKey(nextProjectKey); setSelectedProjectKey(nextProjectKey);
setSelectedBranchName(null); setSelectedBranchName(null);
setSelectedWorktreePath(null); setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []); }, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => { const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
@@ -381,6 +395,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setSelectedProjectKey(null); setSelectedProjectKey(null);
setSelectedBranchName(null); setSelectedBranchName(null);
setSelectedWorktreePath(null); setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []); }, []);
const selectBranch = useCallback( const selectBranch = useCallback(
@@ -400,37 +415,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const loadVersion = ++branchLoadVersionRef.current; const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id); const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
try { branchState.refresh();
const result = await vcsRefManager.load({ if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
environmentId: selectedProject.environmentId, return;
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.");
} }
}, [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>( const value = useMemo<NewTaskFlowContextValue>(
() => ({ () => ({
@@ -449,9 +455,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
availableBranches, availableBranches,
runtimeMode, runtimeMode,
interactionMode, interactionMode,
effort,
fastMode,
contextWindow,
expandedProvider, expandedProvider,
environments, environments,
selectedProject, selectedProject,
@@ -477,9 +480,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
loadBranches, loadBranches,
setRuntimeMode, setRuntimeMode,
setInteractionMode, setInteractionMode,
setEffort, setSelectedModelOptions,
setFastMode,
setContextWindow,
setExpandedProvider, setExpandedProvider,
}), }),
[ [
@@ -487,11 +488,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
availableBranches, availableBranches,
branchQuery, branchQuery,
branchesLoading, branchesLoading,
contextWindow,
effort,
environments, environments,
expandedProvider, expandedProvider,
fastMode,
filteredBranches, filteredBranches,
interactionMode, interactionMode,
loadBranches, loadBranches,
@@ -508,6 +506,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModelKey, selectedModelKey,
selectedModelOption, selectedModelOption,
selectedProviderSkills, selectedProviderSkills,
setSelectedModelOptions,
selectedProject, selectedProject,
selectedProjectKey, selectedProjectKey,
selectedWorktreePath, 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>; 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 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); const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
return Number.isNaN(candidate) ? 0 : candidate; return Number.isNaN(candidate) ? 0 : candidate;
} }
export function threadStatusTone(thread: EnvironmentScopedThreadShell): StatusTone { export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
const status = thread.session?.status; const status = thread.session?.status;
if (status === "running") { if (status === "running") {
return { return {
@@ -42,12 +42,3 @@ export function threadStatusTone(thread: EnvironmentScopedThreadShell): StatusTo
textClassName: "text-neutral-600 dark:text-neutral-300", 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 { 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 { import {
CommandId, CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type EnvironmentId,
MessageId, MessageId,
ThreadId, ThreadId,
type ModelSelection, type ModelSelection,
type ProviderInteractionMode, type ProviderInteractionMode,
type RuntimeMode, type RuntimeMode,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { buildTemporaryWorktreeBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { uuidv4 } from "../../lib/uuid"; import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import { threadEnvironment } from "../../state/threads";
import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata"; import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { getEnvironmentClient } from "../../state/environment-session-registry"; import { uuidv4 } from "../../lib/uuid";
import { environmentRuntimeManager } from "../../state/use-environment-runtime"; import { useAtomCommand } from "../../state/use-atom-command";
import { vcsRefManager } from "../../state/use-vcs-refs"; import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
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],
);
}
function deriveThreadTitleFromPrompt(value: string): string { function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim(); const trimmed = value.trim();
@@ -73,13 +32,12 @@ function deriveThreadTitleFromPrompt(value: string): string {
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`; return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
} }
export function useProjectActions() { export function useCreateProjectThread() {
const { threads } = useRemoteCatalog(); const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const refreshRemoteData = useRefreshRemoteData();
const onCreateThreadWithOptions = useCallback( return useCallback(
async (input: { async (input: {
readonly project: EnvironmentScopedProjectShell; readonly project: EnvironmentProject;
readonly modelSelection: ModelSelection; readonly modelSelection: ModelSelection;
readonly envMode: "local" | "worktree"; readonly envMode: "local" | "worktree";
readonly branch: string | null; readonly branch: string | null;
@@ -89,174 +47,76 @@ export function useProjectActions() {
readonly initialMessageText: string; readonly initialMessageText: string;
readonly initialAttachments: ReadonlyArray<DraftComposerImageAttachment>; readonly initialAttachments: ReadonlyArray<DraftComposerImageAttachment>;
}) => { }) => {
const client = getEnvironmentClient(input.project.environmentId);
if (!client) {
return null;
}
const metadata = makeTurnCommandMetadata(); const metadata = makeTurnCommandMetadata();
const threadId = ThreadId.make(metadata.threadId); const threadId = ThreadId.make(metadata.threadId);
const createdAt = metadata.createdAt;
const initialMessageText = input.initialMessageText.trim(); const initialMessageText = input.initialMessageText.trim();
const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText); const nextTitle = deriveThreadTitleFromPrompt(input.initialMessageText);
if (initialMessageText.length === 0) { 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) { 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"; const isWorktree = input.envMode === "worktree";
const result = await startTurn({
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 {
environmentId: input.project.environmentId, environmentId: input.project.environmentId,
threadId, input: {
}; commandId: CommandId.make(metadata.commandId),
}, threadId,
[refreshRemoteData], message: {
); messageId: MessageId.make(metadata.messageId),
role: "user",
const onCreateThread = useCallback( text: initialMessageText,
async (project: EnvironmentScopedProjectShell) => { attachments: input.initialAttachments,
const latestProjectThread = },
threads.find( modelSelection: input.modelSelection,
(thread) => titleSeed: nextTitle,
thread.environmentId === project.environmentId && thread.projectId === project.id, runtimeMode: input.runtimeMode,
) ?? null; interactionMode: input.interactionMode,
const modelSelection = bootstrap: {
project.defaultModelSelection ?? latestProjectThread?.modelSelection ?? null; createThread: {
if (!modelSelection) { projectId: input.project.id,
setPendingConnectionError("This project does not have a default model configured yet."); title: nextTitle,
return null; modelSelection: input.modelSelection,
} runtimeMode: input.runtimeMode,
interactionMode: input.interactionMode,
return await onCreateThreadWithOptions({ branch: input.branch,
project, worktreePath: isWorktree ? null : input.worktreePath,
modelSelection, createdAt: metadata.createdAt,
envMode: "local", },
branch: null, ...(isWorktree
worktreePath: null, ? {
runtimeMode: DEFAULT_RUNTIME_MODE, prepareWorktree: {
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, projectCwd: input.project.workspaceRoot,
initialMessageText: "", baseBranch: input.branch!,
initialAttachments: [], branch: buildTemporaryWorktreeBranchName(uuidv4),
},
runSetupScript: true,
}
: {}),
},
createdAt: metadata.createdAt,
},
}); });
}, if (AsyncResult.isFailure(result)) {
[onCreateThreadWithOptions, threads], const error = Cause.squash(result.cause);
);
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) {
setPendingConnectionError( 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 type { AuthClientPresentationMetadata } from "@t3tools/contracts";
import { Platform } from "react-native"; import { Platform } from "react-native";
export function mobileAuthClientMetadata(): AuthClientPresentationMetadata { export function authClientMetadata(): AuthClientPresentationMetadata {
return { return {
label: "T3 Code Mobile", label: "T3 Code Mobile",
deviceType: "mobile", deviceType: "mobile",
+3 -3
View File
@@ -3,13 +3,13 @@ import { EnvironmentId } from "@t3tools/contracts";
import { import {
isRelayManagedConnection, isRelayManagedConnection,
mobileAuthClientMetadata, authClientMetadata,
redactPairingCredential, redactPairingCredential,
toStableSavedRemoteConnection, toStableSavedRemoteConnection,
} from "./connection"; } from "./connection";
vi.mock("./runtime", () => ({ vi.mock("./runtime", () => ({
mobileRuntime: { runtime: {
runPromise: vi.fn(), runPromise: vi.fn(),
}, },
})); }));
@@ -22,7 +22,7 @@ vi.mock("react-native", () => ({
describe("mobile remote connection records", () => { describe("mobile remote connection records", () => {
it("identifies mobile token exchanges for authorized-client presentation", () => { it("identifies mobile token exchanges for authorized-client presentation", () => {
expect(mobileAuthClientMetadata()).toEqual({ expect(authClientMetadata()).toEqual({
label: "T3 Code Mobile", label: "T3 Code Mobile",
deviceType: "mobile", deviceType: "mobile",
os: "iOS", os: "iOS",
+4 -54
View File
@@ -1,18 +1,8 @@
import { EnvironmentId } from "@t3tools/contracts"; import { EnvironmentId } from "@t3tools/contracts";
import { import { stripPairingTokenFromUrl } from "@t3tools/shared/remote";
bootstrapRemoteBearerSession, import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
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";
export { mobileAuthClientMetadata } from "./authClientMetadata"; export { authClientMetadata } from "./authClientMetadata";
export interface RemoteConnectionInput {
readonly pairingUrl: string;
}
export interface SavedRemoteConnection { export interface SavedRemoteConnection {
readonly environmentId: EnvironmentId; readonly environmentId: EnvironmentId;
@@ -27,12 +17,7 @@ export interface SavedRemoteConnection {
readonly relayManaged?: true; readonly relayManaged?: true;
} }
export type RemoteClientConnectionState = export type RemoteClientConnectionState = EnvironmentConnectionPhase;
| "idle"
| "connecting"
| "ready"
| "reconnecting"
| "disconnected";
export function redactPairingCredential(pairingUrl: string): string { export function redactPairingCredential(pairingUrl: string): string {
const trimmed = pairingUrl.trim(); const trimmed = pairingUrl.trim();
@@ -59,38 +44,3 @@ export function toStableSavedRemoteConnection(
const { dpopAccessToken: _, ...stableConnection } = connection; const { dpopAccessToken: _, ...stableConnection } = connection;
return stableConnection; 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); return Math.min(Math.max(value, min), max);
} }
export type MobileLayoutVariant = "compact" | "split"; export type LayoutVariant = "compact" | "split";
export interface MobileLayout { export interface Layout {
readonly variant: MobileLayoutVariant; readonly variant: LayoutVariant;
readonly usesSplitView: boolean; readonly usesSplitView: boolean;
readonly listPaneWidth: number | null; readonly listPaneWidth: number | null;
readonly shellPadding: number; readonly shellPadding: number;
} }
export function deriveMobileLayout(input: { export function deriveLayout(input: { readonly width: number; readonly height: number }): Layout {
readonly width: number;
readonly height: number;
}): MobileLayout {
const { width, height } = input; const { width, height } = input;
const shortestEdge = Math.min(width, height); const shortestEdge = Math.min(width, height);
const wideEnoughForSplit = width >= 900 || (width >= 700 && shortestEdge >= 700); 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