diff --git a/CHANGELOG b/CHANGELOG index b0e39d9d..dde62acb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,9 @@ # Changelog +## 0.8.3 - Future + +* Add a client for T3 Code + ## 0.8.2 - 2026-10-03 ### User Interface Customization diff --git a/app/apps/all-apps.ts b/app/apps/all-apps.ts index 864b8536..1ba6d4c5 100644 --- a/app/apps/all-apps.ts +++ b/app/apps/all-apps.ts @@ -4,6 +4,7 @@ import launcherApp from "./launcher"; import timerApp from "./timer"; import calculatorApp from "./calculator"; import terminalApp from "./terminal"; +import t3codeApp from "./t3code"; import filesApp from "./files"; import musicApp from "./music"; import nightscoutApp from "./nightscout"; @@ -37,6 +38,7 @@ export const ALL_APPS: readonly AppDefinition[] = [ timerApp, calculatorApp, terminalApp, + t3codeApp, filesApp, musicApp, nightscoutApp, diff --git a/app/apps/t3code/index.ts b/app/apps/t3code/index.ts new file mode 100644 index 00000000..886b4e81 --- /dev/null +++ b/app/apps/t3code/index.ts @@ -0,0 +1,17 @@ +import { launchWorkerAppWindow, type AppDefinition } from "../app-definition"; + +const t3codeApp: AppDefinition = { + appId: "t3code", + title: "T3 Code", + icon: "t3code", + launch: (ctx) => + launchWorkerAppWindow(ctx, { + createWorker: () => new Worker("./t3code-app.worker"), + windowId: "t3code:main", + title: "T3 Code", + iconLetter: "T3", + icon: "t3code", + }), +}; + +export default t3codeApp; diff --git a/app/apps/t3code/t3-auth.ts b/app/apps/t3code/t3-auth.ts new file mode 100644 index 00000000..908525f5 --- /dev/null +++ b/app/apps/t3code/t3-auth.ts @@ -0,0 +1,174 @@ +/** + * HTTP half of connecting to a T3 Code environment: the unauthenticated + * environment descriptor, the one-time pairing-token exchange (RFC 8693, form + * encoded), and short-lived WebSocket tickets. + * + * Direct pairings use a plain Bearer token: 30 days, no refresh. When it + * expires (or is revoked) the ticket request fails with 401 and the user has + * to pair again with a fresh `t3 pair` link. + */ + +/** The orchestration protocol this client speaks (the server answers 426 to any other). */ +export const T3_ORCHESTRATION_PROTOCOL = 2; + +/** What every ordinary pairing grants; asking for a scope the link doesn't grant burns the token. */ +const STANDARD_SCOPES = "orchestration:read orchestration:operate terminal:operate review:write relay:read"; + +const HTTP_TIMEOUT_MS = 12_000; + +/** The subset of fetch these calls need, so tests and Node scripts can pass their own. */ +export type T3Fetch = ( + url: string, + init: { method: string; headers: Record; body?: string }, +) => Promise<{ status: number; ok: boolean; text(): Promise }>; + +export type EnvironmentDescriptor = { + environmentId: string; + label: string; + serverVersion: string; + orchestrationProtocolVersion: number; + capabilities: Record; +}; + +export type PairedCredential = { + accessToken: string; + /** Epoch ms. */ + expiresAtMs: number; +}; + +/** An HTTP failure; `authFailed` means the stored token is no good (re-pair). */ +export class T3HttpError extends Error { + constructor(message: string, readonly status: number, readonly authFailed = false) { + super(message); + this.name = "T3HttpError"; + } +} + +/** Form/query encoding (not URLSearchParams, which the NativeScript runtime mishandles). */ +function buildQuery(params: Record): string { + return Object.keys(params) + .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key]!)}`) + .join("&"); +} + +async function request( + fetchImpl: T3Fetch, + url: string, + init: { method: string; headers: Record; body?: string }, +): Promise<{ status: number; ok: boolean; body: string }> { + let timer: ReturnType | null = null; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new T3HttpError("Timed out reaching the server.", 0)), HTTP_TIMEOUT_MS); + }); + try { + const response = await Promise.race([fetchImpl(url, init), timeout]); + const body = await Promise.race([response.text(), timeout]); + return { status: response.status, ok: response.ok, body }; + } catch (error) { + if (error instanceof T3HttpError) throw error; + throw new T3HttpError(`Can't reach the server: ${(error as Error)?.message ?? error}`, 0); + } finally { + if (timer) clearTimeout(timer); + } +} + +function parseJson(body: string): any { + try { + return JSON.parse(body); + } catch { + return null; + } +} + +/** Human message for T3's error envelope ({_tag, code, reason, traceId}). */ +function describeFailure(status: number, body: string, what: string): string { + const parsed = parseJson(body); + const reason = typeof parsed?.reason === "string" ? parsed.reason : typeof parsed?.code === "string" ? parsed.code : ""; + switch (reason) { + case "invalid_credential": + return what === "pair" + ? "That pairing link was already used or has expired. Run `t3 pair` for a new one." + : "The server no longer accepts this device's sign-in. Pair it again."; + case "missing_credential": + return "The server asked for a sign-in. Pair this device again."; + case "scope_not_granted": + return "That pairing link doesn't grant enough access. Run `t3 pair` for a new one."; + } + if (status === 426 || parsed?.code === "orchestration_protocol_incompatible") { + return "This T3 Code server speaks a different protocol version. Update T3 Code and Faceclaw."; + } + return `Server error (HTTP ${status}${reason ? `, ${reason}` : ""}).`; +} + +export async function fetchEnvironmentDescriptor(fetchImpl: T3Fetch, httpBaseUrl: string): Promise { + const response = await request(fetchImpl, `${httpBaseUrl}.well-known/t3/environment`, { method: "GET", headers: {} }); + const parsed = parseJson(response.body); + if (!response.ok || !parsed || typeof parsed.environmentId !== "string") { + throw new T3HttpError( + response.ok ? "That address doesn't look like a T3 Code server." : describeFailure(response.status, response.body, "descriptor"), + response.status, + ); + } + return { + environmentId: parsed.environmentId, + label: typeof parsed.label === "string" ? parsed.label : "", + serverVersion: typeof parsed.serverVersion === "string" ? parsed.serverVersion : "", + orchestrationProtocolVersion: typeof parsed.orchestrationProtocolVersion === "number" ? parsed.orchestrationProtocolVersion : 1, + capabilities: parsed.capabilities && typeof parsed.capabilities === "object" ? parsed.capabilities : {}, + }; +} + +/** Trade a one-time pairing credential for a durable bearer token. */ +export async function exchangePairingCredential( + fetchImpl: T3Fetch, + httpBaseUrl: string, + credential: string, + client: { label: string; os: string }, +): Promise { + const body = buildQuery({ + grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", + subject_token: credential, + subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap", + requested_token_type: "urn:ietf:params:oauth:token-type:access_token", + scope: STANDARD_SCOPES, + client_label: client.label, + client_device_type: "mobile", + client_os: client.os, + }); + const response = await request(fetchImpl, `${httpBaseUrl}oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body, + }); + const parsed = parseJson(response.body); + if (!response.ok || typeof parsed?.access_token !== "string") { + throw new T3HttpError(describeFailure(response.status, response.body, "pair"), response.status, response.status === 401); + } + const expiresIn = typeof parsed.expires_in === "number" ? parsed.expires_in : 30 * 24 * 3600; + return { accessToken: parsed.access_token, expiresAtMs: Date.now() + expiresIn * 1000 }; +} + +/** A WebSocket ticket (valid ~5 minutes); fetch a fresh one for every connect. */ +export async function fetchWebSocketTicket(fetchImpl: T3Fetch, httpBaseUrl: string, accessToken: string): Promise { + const response = await request(fetchImpl, `${httpBaseUrl}api/auth/websocket-ticket`, { + method: "POST", + headers: { Authorization: `Bearer ${accessToken}` }, + }); + const parsed = parseJson(response.body); + if (!response.ok || typeof parsed?.ticket !== "string") { + throw new T3HttpError(describeFailure(response.status, response.body, "ticket"), response.status, response.status === 401); + } + return parsed.ticket; +} + +/** The /ws URL for a ticket. */ +export function webSocketUrl(wsBaseUrl: string, ticket: string, clientOs: string): string { + return `${wsBaseUrl}ws?${buildQuery({ + wsTicket: ticket, + clientSurface: "mobile", + clientDeviceType: "phone", + clientOs, + connectionMethod: "direct", + orchestrationProtocol: String(T3_ORCHESTRATION_PROTOCOL), + })}`; +} diff --git a/app/apps/t3code/t3-client.ts b/app/apps/t3code/t3-client.ts new file mode 100644 index 00000000..776475ed --- /dev/null +++ b/app/apps/t3code/t3-client.ts @@ -0,0 +1,425 @@ +/** + * One live connection to a paired T3 Code environment: fetches a WebSocket + * ticket with the stored bearer token, opens the RPC socket, waits for the + * server-config snapshot (checking it is the environment we paired with), + * then keeps the thread list (subscribeShell) and any open threads + * (subscribeThread) live. Owns its own retry loop: dropped connections come + * back with jittered exponential backoff and resume every stream from its + * last sequence. A rejected token stops retrying until the user pairs again. + * + * Transport and HTTP are injected, so this runs unchanged under Node. + */ +import { + fetchWebSocketTicket, + T3HttpError, + webSocketUrl, + type T3Fetch, +} from "./t3-auth"; +import { ShellModel, ThreadDetailModel, type T3ServerProvider } from "./t3-model"; +import { T3RpcConnection, T3RpcError, type RpcSocketFactory, type T3Subscription } from "./t3-rpc"; + +/** A paired environment as stored on the phone. */ +export type StoredEnvironment = { + /** Local id (stable across re-pairing). */ + id: string; + /** The server's own id, checked on every connect. */ + environmentId: string; + /** The server's label (its machine name). */ + label: string; + httpBaseUrl: string; + wsBaseUrl: string; + /** Bearer token from pairing (30-day lifetime, no refresh). */ + accessToken: string; + expiresAtMs: number; + /** Connect while the app is open. */ + enabled: boolean; +}; + +export type EnvironmentPhase = + | "idle" + | "connecting" + | "connected" + /** Waiting to try again after a failure. */ + | "retrying" + /** The token was rejected or expired: pair again. */ + | "auth-failed"; + +export type T3ClientDeps = { + fetch: T3Fetch; + openSocket: RpcSocketFactory; + /** Reported to the server as the client OS ("Android", "iOS"). */ + clientOs: string; + log?: (message: string) => void; +}; + +const RECONNECT_MIN_DELAY_MS = 1_000; +const RECONNECT_MAX_DELAY_MS = 60_000; +/** How long the socket may stay open without delivering the config snapshot. */ +const READY_TIMEOUT_MS = 20_000; +/** Resubscribe delay after a stream fails on a healthy connection (e.g. a server buffer overflow). */ +const STREAM_RETRY_MS = 250; + +export type ThreadHandle = { + readonly model: ThreadDetailModel; + /** The subscription failed for a reason other than the connection dropping. */ + readonly error: () => string; + close(): void; +}; + +type ThreadEntry = { + model: ThreadDetailModel; + subscription: T3Subscription | null; + retryTimer: ReturnType | null; + error: string; + listeners: Set<() => void>; + refs: number; +}; + +export class T3EnvironmentClient { + readonly shell = new ShellModel(); + providers: T3ServerProvider[] = []; + settings: Record | null = null; + private phaseValue: EnvironmentPhase = "idle"; + private statusValue = ""; + private connection: T3RpcConnection | null = null; + private shellSubscription: T3Subscription | null = null; + private shellRetryTimer: ReturnType | null = null; + private readyTimer: ReturnType | null = null; + private reconnectTimer: ReturnType | null = null; + private reconnectDelayMs = RECONNECT_MIN_DELAY_MS; + /** Bumped on every connect attempt and stop, so stale async work can tell it lost. */ + private generation = 0; + private running = false; + private readonly listeners = new Set<() => void>(); + private readonly threads = new Map(); + + constructor( + public config: StoredEnvironment, + private readonly deps: T3ClientDeps, + ) {} + + get phase(): EnvironmentPhase { + return this.phaseValue; + } + + /** Human-readable connection status ("" when connected and healthy). */ + get status(): string { + return this.statusValue; + } + + /** Connected, with the thread list loaded. */ + get ready(): boolean { + return this.phaseValue === "connected" && this.shell.sequence !== null; + } + + get retryScheduled(): boolean { + return this.reconnectTimer !== null; + } + + /** Any change worth repainting for: phase, status, thread list, config. */ + onChange(listener: () => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + /** Start connecting (no-op while already running). */ + start(): void { + if (this.running) return; + this.running = true; + this.reconnectDelayMs = RECONNECT_MIN_DELAY_MS; + void this.connect(); + } + + /** Disconnect and stop retrying. Open thread handles stay registered and resume on the next start. */ + stop(): void { + this.running = false; + this.generation++; + this.clearTimers(); + this.teardownConnection("Disconnected."); + this.setPhase("idle", ""); + } + + /** Retry right away (manual reconnect), resetting backoff. */ + retryNow(): void { + this.stop(); + this.start(); + } + + /** Replace the stored config (e.g. re-paired); reconnects if anything connection-relevant changed. */ + updateConfig(config: StoredEnvironment): void { + const reconnect = + config.accessToken !== this.config.accessToken || + config.httpBaseUrl !== this.config.httpBaseUrl || + config.environmentId !== this.config.environmentId; + this.config = config; + if (reconnect && this.running) this.retryNow(); + else this.emit(); + } + + /** + * Subscribe to a thread's detail stream. Handles are reference counted: + * every openThread needs its own close(). + */ + openThread(threadId: string, onChange: () => void): ThreadHandle { + let entry = this.threads.get(threadId); + if (!entry) { + entry = { model: new ThreadDetailModel(threadId), subscription: null, retryTimer: null, error: "", listeners: new Set(), refs: 0 }; + this.threads.set(threadId, entry); + if (this.phaseValue === "connected") this.subscribeThread(threadId, entry); + } + const current = entry; + current.refs++; + current.listeners.add(onChange); + let closed = false; + return { + model: current.model, + error: () => current.error, + close: () => { + if (closed) return; + closed = true; + current.listeners.delete(onChange); + if (--current.refs > 0) return; + current.subscription?.cancel(); + if (current.retryTimer) clearTimeout(current.retryTimer); + this.threads.delete(threadId); + }, + }; + } + + /** orchestration.dispatchCommand; resolves to the committed event sequence. */ + async dispatch(command: Record): Promise { + const connection = this.requireConnection(); + const result = await connection.call<{ sequence?: number }>("orchestration.dispatchCommand", command); + return typeof result?.sequence === "number" ? result.sequence : 0; + } + + /** orchestration.launchThread; resolves to the new thread's id. */ + async launchThread(payload: Record): Promise { + const connection = this.requireConnection(); + const result = await connection.call<{ threadId?: string }>("orchestration.launchThread", payload); + return String(result?.threadId ?? payload.threadId); + } + + private requireConnection(): T3RpcConnection { + if (this.phaseValue !== "connected" || !this.connection) { + throw new T3RpcError("disconnected", `Not connected to ${this.config.label || "the server"}.`); + } + return this.connection; + } + + // ------------------------------------------------------------------------- + // Connection lifecycle + + private async connect(): Promise { + const generation = ++this.generation; + this.clearTimers(); + this.teardownConnection("Reconnecting."); + if (this.config.expiresAtMs && this.config.expiresAtMs <= Date.now()) { + this.setPhase("auth-failed", "Sign-in expired. Pair this device again."); + return; + } + this.setPhase("connecting", "Connecting..."); + let ticket: string; + try { + ticket = await fetchWebSocketTicket(this.deps.fetch, this.config.httpBaseUrl, this.config.accessToken); + } catch (error) { + if (generation !== this.generation) return; + if (error instanceof T3HttpError && error.authFailed) { + this.setPhase("auth-failed", error.message); + return; + } + this.scheduleReconnect(errorMessage(error)); + return; + } + if (generation !== this.generation) return; + + const connection = new T3RpcConnection({ + url: webSocketUrl(this.config.wsBaseUrl, ticket, this.deps.clientOs), + openSocket: this.deps.openSocket, + }); + this.connection = connection; + connection.onStateChange((state, reason) => { + if (state !== "closed" || generation !== this.generation) return; + this.handleConnectionLost(reason); + }); + this.readyTimer = setTimeout(() => { + if (generation === this.generation) connection.close("The server didn't finish connecting."); + }, READY_TIMEOUT_MS); + + let ready = false; + connection.subscribe( + "subscribeServerConfig", + {}, + (values) => { + if (generation !== this.generation) return; + for (const value of values) { + const event = value as Record; + if (event?.type === "snapshot") { + const config = event.config ?? {}; + const environmentId = config.environment?.environmentId; + if (this.config.environmentId && environmentId && environmentId !== this.config.environmentId) { + this.generation++; + this.teardownConnection("Wrong server."); + this.setPhase("auth-failed", "A different T3 Code server answered at this address. Pair it again."); + return; + } + this.providers = Array.isArray(config.providers) ? config.providers : []; + this.settings = config.settings ?? null; + if (typeof config.environment?.label === "string" && config.environment.label && config.environment.label !== this.config.label) { + this.config = { ...this.config, label: config.environment.label }; + } + if (!ready) { + ready = true; + this.handleReady(generation); + } + } else if (event?.type === "providerStatuses" && Array.isArray(event.payload?.providers)) { + this.providers = event.payload.providers; + } else if (event?.type === "settingsUpdated" && event.payload?.settings) { + this.settings = event.payload.settings; + } + } + this.emit(); + }, + (error) => { + // The session is unusable without its config stream (T3's own client + // treats this as the session closing). + if (generation !== this.generation || error?.kind === "disconnected") return; + connection.close(`Server config stream ended${error ? `: ${error.message}` : "."}`); + }, + ); + } + + private handleReady(generation: number): void { + if (this.readyTimer) clearTimeout(this.readyTimer); + this.readyTimer = null; + this.reconnectDelayMs = RECONNECT_MIN_DELAY_MS; + this.setPhase("connected", ""); + this.deps.log?.(`t3code: connected to ${this.config.label} (${this.config.httpBaseUrl})`); + this.subscribeShell(generation); + for (const [threadId, entry] of this.threads) this.subscribeThread(threadId, entry); + } + + private subscribeShell(generation: number): void { + const connection = this.connection; + if (!connection || generation !== this.generation) return; + this.shell.synchronized = false; + this.shellSubscription?.cancel(); + const payload: Record = { requestCompletionMarker: true }; + if (this.shell.sequence !== null) payload.afterSequence = this.shell.sequence; + this.shellSubscription = connection.subscribe( + "orchestration.subscribeShell", + payload, + (values) => { + if (generation !== this.generation) return; + let changed = false; + for (const value of values) changed = this.shell.apply(value) || changed; + if (changed) this.emit(); + }, + (error) => { + this.shellSubscription = null; + if (generation !== this.generation || error?.kind === "disconnected") return; + this.deps.log?.(`t3code: shell stream ended: ${error?.message ?? "completed"}`); + this.shellRetryTimer = setTimeout(() => { + this.shellRetryTimer = null; + this.subscribeShell(generation); + }, STREAM_RETRY_MS); + }, + ); + } + + private subscribeThread(threadId: string, entry: ThreadEntry): void { + const connection = this.connection; + if (!connection || this.phaseValue !== "connected") return; + const generation = this.generation; + entry.subscription?.cancel(); + entry.model.synchronized = false; + const payload: Record = { threadId, requestCompletionMarker: true, acceptBoundedSnapshot: true }; + if (entry.model.sequence !== null) payload.afterSequence = entry.model.sequence; + const notify = () => { + for (const listener of [...entry.listeners]) listener(); + }; + const subscription = connection.subscribe( + "orchestration.subscribeThread", + payload, + (values) => { + if (generation !== this.generation || this.threads.get(threadId) !== entry) return; + let changed = false; + for (const value of values) changed = entry.model.apply(value) || changed; + if (entry.error) { + entry.error = ""; + changed = true; + } + if (changed) notify(); + }, + (error) => { + if (entry.subscription === subscription) entry.subscription = null; + if (generation !== this.generation || this.threads.get(threadId) !== entry || error?.kind === "disconnected") return; + entry.error = error ? error.message : "The thread stream ended."; + notify(); + if (error?.kind === "fail" || error?.kind === "interrupt") { + entry.retryTimer = setTimeout(() => { + entry.retryTimer = null; + if (this.threads.get(threadId) === entry) this.subscribeThread(threadId, entry); + }, STREAM_RETRY_MS * 4); + } + }, + ); + entry.subscription = subscription; + } + + private handleConnectionLost(reason: string): void { + this.connection = null; + this.shellSubscription = null; + for (const entry of this.threads.values()) entry.subscription = null; + if (!this.running) return; + this.scheduleReconnect(reason); + } + + private scheduleReconnect(reason: string): void { + if (!this.running) return; + const delay = Math.round(this.reconnectDelayMs * (0.75 + Math.random() * 0.5)); + this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS); + this.setPhase("retrying", reason); + this.deps.log?.(`t3code: ${this.config.label}: ${reason} (retrying in ${delay}ms)`); + const generation = this.generation; + this.reconnectTimer = setTimeout(() => { + this.reconnectTimer = null; + if (generation === this.generation && this.running) void this.connect(); + }, delay); + } + + private teardownConnection(reason: string): void { + const connection = this.connection; + this.connection = null; + this.shellSubscription = null; + for (const entry of this.threads.values()) entry.subscription = null; + connection?.close(reason); + } + + private clearTimers(): void { + for (const timer of [this.readyTimer, this.shellRetryTimer]) if (timer) clearTimeout(timer); + if (this.reconnectTimer) clearTimeout(this.reconnectTimer); + this.readyTimer = null; + this.shellRetryTimer = null; + this.reconnectTimer = null; + for (const entry of this.threads.values()) { + if (entry.retryTimer) clearTimeout(entry.retryTimer); + entry.retryTimer = null; + } + } + + private setPhase(phase: EnvironmentPhase, status: string): void { + if (this.phaseValue === phase && this.statusValue === status) return; + this.phaseValue = phase; + this.statusValue = status; + this.emit(); + } + + private emit(): void { + for (const listener of [...this.listeners]) listener(); + } +} + +export function errorMessage(error: unknown): string { + return String((error as Error)?.message ?? error); +} diff --git a/app/apps/t3code/t3-environments.ts b/app/apps/t3code/t3-environments.ts new file mode 100644 index 00000000..48ede549 --- /dev/null +++ b/app/apps/t3code/t3-environments.ts @@ -0,0 +1,49 @@ +import { getStringSetting, setStringSetting } from "../../native/settings-store"; +import type { StoredEnvironment } from "./t3-client"; + +/** + * Paired T3 Code environments, stored as JSON under one settings key (like + * the Terminal app's connections). Each entry holds the bearer token issued + * at pairing; it lasts 30 days and is never shown on screen. + */ +export const T3_ENVIRONMENTS_KEY = "t3code.environments"; + +export function loadEnvironments(): StoredEnvironment[] { + const raw = getStringSetting(T3_ENVIRONMENTS_KEY, ""); + if (!raw) return []; + try { + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed)) return []; + return parsed + .map((item: any): StoredEnvironment => ({ + id: String(item?.id ?? ""), + environmentId: String(item?.environmentId ?? ""), + label: String(item?.label ?? ""), + httpBaseUrl: String(item?.httpBaseUrl ?? ""), + wsBaseUrl: String(item?.wsBaseUrl ?? ""), + accessToken: String(item?.accessToken ?? ""), + expiresAtMs: Number(item?.expiresAtMs) || 0, + enabled: item?.enabled !== false, + })) + .filter((environment) => environment.id && environment.httpBaseUrl && environment.accessToken); + } catch { + return []; + } +} + +export function saveEnvironments(environments: StoredEnvironment[]): void { + setStringSetting(T3_ENVIRONMENTS_KEY, JSON.stringify(environments)); +} + +/** Insert or replace (by local id). */ +export function upsertEnvironment(environment: StoredEnvironment): void { + const environments = loadEnvironments(); + const index = environments.findIndex((candidate) => candidate.id === environment.id); + if (index >= 0) environments[index] = environment; + else environments.push(environment); + saveEnvironments(environments); +} + +export function removeEnvironment(id: string): void { + saveEnvironments(loadEnvironments().filter((environment) => environment.id !== id)); +} diff --git a/app/apps/t3code/t3-model.ts b/app/apps/t3code/t3-model.ts new file mode 100644 index 00000000..86d2a9f4 --- /dev/null +++ b/app/apps/t3code/t3-model.ts @@ -0,0 +1,903 @@ +/** + * Client-side state for T3 Code's orchestration (v2) streams, independent of + * transport and rendering: the shell (projects + thread list) reducer, the + * per-thread detail reducer, thread status / ordering for the glasses list, + * one-line summaries of timeline items, and the dispatch-command builders. + * + * Mirrors T3's own client runtime (packages/client-runtime/src/state/ + * shellReducer.ts, orchestrationV2Projection.ts, models.ts; apps/mobile's + * threadListV2.ts and threadActivity.ts) in reduced form. Wire objects are + * typed loosely: only the fields read here are declared, and everything is + * treated as possibly missing so newer/older servers degrade gracefully. + */ + +// --------------------------------------------------------------------------- +// Wire shapes (subset) + +export type T3ProjectShell = { + id: string; + title: string; + workspaceRoot?: string; + defaultModelSelection?: T3ModelSelection | null; +}; + +export type T3ModelSelection = { instanceId: string; model: string; options?: unknown[] }; + +export type T3ThreadShell = { + id: string; + projectId: string; + title: string; + providerInstanceId?: string | null; + modelSelection?: T3ModelSelection | null; + status?: string; + activityRunStatus?: string | null; + activeRunId?: string | null; + latestRunId?: string | null; + activeProviderThreadId?: string | null; + latestRunRequestedAt?: string | null; + latestRunCompletedAt?: string | null; + lastVisitedAt?: string | null; + pendingRuntimeRequest?: { id: string; kind: string; createdAt?: string } | null; + pendingBackgroundTasks?: Array<{ kind?: string }>; + lastError?: string | null; + lastErrorClass?: string | null; + usageLimitResetAt?: string | null; + latestUserMessageAt?: string | null; + latestUserAuthoredMessageAt?: string | null; + hasActionableProposedPlan?: boolean; + createdAt?: string; + updatedAt?: string; + archivedAt?: string | null; + deletedAt?: string | null; + settledOverride?: string | null; + settledAt?: string | null; + snoozedUntil?: string | null; + snoozedAt?: string | null; + lineage?: { relationshipToParent?: string | null } | null; +}; + +export type T3Run = { + id: string; + status: string; + userMessageId?: string | null; + requestedAt?: string | null; + queuePosition?: number | null; +}; + +export type T3RunAttempt = { id: string; runId: string; rootNodeId?: string | null; status: string }; + +export type T3RuntimeRequest = { + id: string; + kind: string; + status: string; + responseCapability?: { type: string } | null; +}; + +export type T3ConversationMessage = { + id: string; + role?: string; + text?: string; + delegatedCompletion?: unknown; + notification?: unknown; +}; + +export type T3PlanStep = { id?: string; text: string; status: string }; + +export type T3Plan = { + id: string; + kind: string; + runId?: string | null; + status?: string; + steps?: T3PlanStep[]; +}; + +export type T3ApprovalOption = { decision: string; label: string; warning?: string }; + +export type T3Question = { + id: string; + header?: string; + question: string; + options?: Array<{ label: string; description?: string; value?: string }>; + multiSelect?: boolean; + allowCustomAnswer?: boolean; + required?: boolean; +}; + +/** A timeline row. Fields beyond the common ones depend on `type`. */ +export type T3TurnItem = { + id: string; + threadId: string; + runId: string | null; + nodeId?: string | null; + ordinal: number; + status: string; + title?: string | null; + type: string; + // user_message / assistant_message / reasoning + text?: string; + streaming?: boolean; + inputIntent?: string; + // command_execution + input?: unknown; + exitCode?: number; + outputIndicatesFailure?: boolean; + // file_change + fileName?: string; + additions?: number; + deletions?: number; + changes?: unknown[]; + // file_search / web_search + pattern?: string; + patterns?: string[]; + // dynamic_tool + toolName?: string | null; + // approval_request / user_input_request + requestId?: string; + requestKind?: string; + prompt?: string; + appName?: string; + options?: T3ApprovalOption[]; + questions?: T3Question[]; + responseMode?: string; + // notification / system_notice / run_interrupt_result + summary?: string; + detail?: string; + message?: string; + // error + failure?: { class?: string; message?: string; code?: string | null } | null; + // compaction + beforeTokenCount?: number; + afterTokenCount?: number; + // handoff + toModel?: string; + // proposed_plan + markdown?: string; +}; + +type ProjectedTurnItem = { visibility?: string; item: T3TurnItem }; + +// --------------------------------------------------------------------------- +// Shell (projects + thread list) + +export class ShellModel { + readonly projects = new Map(); + readonly threads = new Map(); + /** Last applied sequence (the resume cursor), or null before the first snapshot. */ + sequence: number | null = null; + /** The server finished replaying and the stream is live. */ + synchronized = false; + + /** Apply one subscribeShell stream item; returns whether anything changed. */ + apply(raw: unknown): boolean { + const item = raw as Record; + switch (item?.kind) { + case "synchronized": + this.synchronized = true; + return true; + case "snapshot": { + const snapshot = item.snapshot ?? {}; + if (Array.isArray(item.resolvedRepositoryIdentityRoots)) { + // Metadata-only refresh (carries threads: []): never a replacement. + return false; + } + this.projects.clear(); + this.threads.clear(); + for (const project of snapshot.projects ?? []) this.projects.set(project.id, project); + for (const thread of snapshot.threads ?? []) this.threads.set(thread.id, thread); + this.sequence = typeof snapshot.snapshotSequence === "number" ? snapshot.snapshotSequence : 0; + return true; + } + case "project.updated": + case "project.removed": + case "thread.updated": + case "thread.removed": { + const sequence = typeof item.sequence === "number" ? item.sequence : null; + if (sequence !== null && this.sequence !== null && sequence <= this.sequence) return false; + if (item.kind === "project.updated" && item.project) this.projects.set(item.project.id, item.project); + else if (item.kind === "project.removed") this.projects.delete(item.projectId); + else if (item.kind === "thread.updated" && item.thread) { + if (item.location === "archive") this.threads.delete(item.thread.id); + else this.threads.set(item.thread.id, item.thread); + } else if (item.kind === "thread.removed") this.threads.delete(item.threadId); + if (sequence !== null) this.sequence = sequence; + return true; + } + default: + return false; + } + } +} + +// --------------------------------------------------------------------------- +// Thread status and list ordering (as T3's mobile thread list derives them) + +export type T3ThreadStatus = + /** A provider approval is waiting on the user. */ + | "approval" + /** The provider asked the user a question. */ + | "input" + | "working" + /** Parked on background work (subagent, monitor) that will wake it. */ + | "waiting" + | "failed" + /** Failed on a usage limit. */ + | "limited" + | "ready"; + +const ACTIVE_RUN_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]); +const WAKING_BACKGROUND_KINDS = new Set(["subagent", "monitor", "background_task"]); + +export function threadStatus(thread: T3ThreadShell): T3ThreadStatus { + const request = thread.pendingRuntimeRequest; + if (request && request.kind !== "user_input" && request.kind !== "auth_refresh") return "approval"; + if (request?.kind === "user_input") return "input"; + if (thread.latestRunId == null && thread.activeProviderThreadId == null) return "ready"; + const background = + thread.status !== "failed" && + (thread.pendingBackgroundTasks ?? []).some((task) => WAKING_BACKGROUND_KINDS.has(task.kind ?? "")); + const runStatus = background ? "idle" : (thread.activityRunStatus ?? thread.status ?? "idle"); + if (ACTIVE_RUN_STATUSES.has(runStatus)) return "working"; + if (runStatus === "idle") return "waiting"; + if (runStatus === "failed") return thread.lastErrorClass === "usage_limit" ? "limited" : "failed"; + return "ready"; +} + +export function threadStatusLabel(status: T3ThreadStatus): string { + switch (status) { + case "approval": + return "Needs approval"; + case "input": + return "Has a question"; + case "working": + return "Working"; + case "waiting": + return "Waiting"; + case "failed": + return "Failed"; + case "limited": + return "Usage limit"; + case "ready": + return "Ready"; + } +} + +function timeMs(value: string | null | undefined): number { + if (!value) return 0; + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +/** A run finished since the user (on any client) last looked at the thread. */ +export function isThreadUnread(thread: T3ThreadShell): boolean { + const completed = timeMs(thread.latestRunCompletedAt); + const visited = timeMs(thread.lastVisitedAt); + return completed > 0 && visited > 0 && completed > visited; +} + +export function isThreadSettled(thread: T3ThreadShell): boolean { + return thread.settledOverride === "settled"; +} + +export function isThreadSnoozed(thread: T3ThreadShell, nowMs: number): boolean { + if (timeMs(thread.snoozedUntil) <= nowMs) return false; + // A raised hand (question, approval, failure, or a run finishing after the + // snooze) brings it back. + const status = threadStatus(thread); + if (status === "approval" || status === "input" || status === "failed") return false; + return !(timeMs(thread.latestRunCompletedAt) > timeMs(thread.snoozedAt)); +} + +/** Archived, deleted and provider-run subagent threads stay out of the list. */ +export function isThreadListed(thread: T3ThreadShell): boolean { + return !thread.archivedAt && !thread.deletedAt && thread.lineage?.relationshipToParent !== "subagent"; +} + +/** When the thread last saw activity worth sorting by. */ +export function threadActivityMs(thread: T3ThreadShell): number { + return timeMs(thread.latestUserMessageAt) || timeMs(thread.updatedAt) || timeMs(thread.createdAt); +} + +function settledMs(thread: T3ThreadShell): number { + return timeMs(thread.settledAt) || threadActivityMs(thread); +} + +export type ThreadSection = "attention" | "working" | "recent" | "snoozed" | "settled"; + +export type ThreadSections = Record; + +/** + * The glasses list: threads that need the user first, then running ones + * (ordered by when the user last wrote, so finishing doesn't reshuffle + * them), then everything else by recent activity; snoozed and settled + * threads are kept apart. + */ +export function sectionThreads(threads: Iterable, nowMs: number): ThreadSections { + const sections: ThreadSections = { attention: [], working: [], recent: [], snoozed: [], settled: [] }; + for (const thread of threads) { + if (!isThreadListed(thread)) continue; + const status = threadStatus(thread); + if (status === "approval" || status === "input") sections.attention.push(thread); + else if (isThreadSnoozed(thread, nowMs)) sections.snoozed.push(thread); + else if (isThreadSettled(thread)) sections.settled.push(thread); + else if (status === "working" || status === "waiting") sections.working.push(thread); + else sections.recent.push(thread); + } + const byId = (a: T3ThreadShell, b: T3ThreadShell) => a.id.localeCompare(b.id); + sections.attention.sort((a, b) => timeMs(b.pendingRuntimeRequest?.createdAt) - timeMs(a.pendingRuntimeRequest?.createdAt) || byId(a, b)); + const sentMs = (thread: T3ThreadShell) => timeMs(thread.latestUserAuthoredMessageAt) || timeMs(thread.latestRunRequestedAt); + sections.working.sort((a, b) => sentMs(b) - sentMs(a) || byId(a, b)); + sections.recent.sort((a, b) => threadActivityMs(b) - threadActivityMs(a) || byId(a, b)); + sections.snoozed.sort((a, b) => timeMs(a.snoozedUntil) - timeMs(b.snoozedUntil) || byId(a, b)); + sections.settled.sort((a, b) => settledMs(b) - settledMs(a) || byId(a, b)); + return sections; +} + +/** "now", "5m", "3h", "2d", "Mar 4" style age. */ +export function formatAge(thenMs: number, nowMs: number): string { + if (!thenMs) return ""; + const seconds = Math.max(0, Math.round((nowMs - thenMs) / 1000)); + if (seconds < 60) return "now"; + const minutes = Math.round(seconds / 60); + if (minutes < 60) return `${minutes}m`; + const hours = Math.round(minutes / 60); + if (hours < 24) return `${hours}h`; + const days = Math.round(hours / 24); + if (days < 14) return `${days}d`; + const date = new Date(thenMs); + const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + return `${months[date.getMonth()]} ${date.getDate()}`; +} + +// --------------------------------------------------------------------------- +// Thread detail (subscribeThread) + +const MAX_ITEMS_KEPT = 400; + +export class ThreadDetailModel { + /** Last applied sequence (the resume cursor), or null before the first snapshot. */ + sequence: number | null = null; + synchronized = false; + deleted = false; + thread: Record | null = null; + readonly runs = new Map(); + readonly attempts = new Map(); + readonly runtimeRequests = new Map(); + readonly messages = new Map(); + readonly plans = new Map(); + /** This thread's own timeline rows, by id. */ + readonly items = new Map(); + /** Rows inherited from a forked-from thread: a frozen prefix. */ + private inherited: T3TurnItem[] = []; + /** Bounded-window bookkeeping: older history exists that we didn't load. */ + hasMoreHistory = false; + private historyCursor: string | null = null; + private latestLocalTurnOrdinal: number | null = null; + + constructor(readonly threadId: string) {} + + /** Apply one subscribeThread stream item; returns whether anything changed. */ + apply(raw: unknown): boolean { + const item = raw as Record; + switch (item?.kind) { + case "synchronized": + this.synchronized = true; + return true; + case "snapshot": + this.applySnapshot(item); + return true; + case "event": { + const sequence = typeof item.sequence === "number" ? item.sequence : null; + if (sequence !== null && this.sequence !== null && sequence <= this.sequence) return false; + if (sequence !== null) this.sequence = sequence; + return this.applyEvent(item.event ?? {}); + } + default: + return false; + } + } + + private applySnapshot(item: Record): void { + const projection = item.projection ?? {}; + this.sequence = typeof item.snapshotSequence === "number" ? item.snapshotSequence : 0; + this.thread = projection.thread ?? null; + this.deleted = Boolean(this.thread?.deletedAt); + const fill = (map: Map, values: T[] | undefined) => { + map.clear(); + for (const value of values ?? []) map.set(value.id, value); + }; + fill(this.runs, projection.runs); + fill(this.attempts, projection.attempts); + fill(this.runtimeRequests, projection.runtimeRequests); + fill(this.messages, projection.messages); + fill(this.plans, projection.plans); + this.items.clear(); + this.inherited = []; + for (const row of (projection.visibleTurnItems ?? []) as ProjectedTurnItem[]) { + if (!row?.item) continue; + if (row.visibility === "local") this.items.set(row.item.id, row.item); + else this.inherited.push(row.item); + } + this.hasMoreHistory = Boolean(item.hasMoreHistory); + this.historyCursor = typeof item.historyCursor === "string" ? item.historyCursor : null; + this.latestLocalTurnOrdinal = typeof item.latestLocalTurnOrdinal === "number" ? item.latestLocalTurnOrdinal : null; + } + + private applyEvent(event: Record): boolean { + const payload = event.payload; + const type = String(event.type ?? ""); + if (type === "thread.deleted") { + this.deleted = true; + return true; + } + if (type.startsWith("thread.")) { + if (payload && typeof payload === "object") this.thread = payload; + return true; + } + switch (type) { + case "run.created": + case "run.updated": + this.runs.set(payload.id, payload); + return true; + case "run-attempt.created": + case "run-attempt.updated": + this.attempts.set(payload.id, payload); + return true; + case "runtime-request.updated": + this.runtimeRequests.set(payload.id, payload); + return true; + case "message.updated": + this.messages.set(payload.id, payload); + return true; + case "plan.updated": + this.plans.set(payload.id, payload); + return true; + case "turn-item.updated": + return this.upsertItem(payload as T3TurnItem); + default: + // Unknown and uninteresting events still advance the cursor. + return false; + } + } + + private upsertItem(item: T3TurnItem): boolean { + if (!item?.id || item.threadId !== this.threadId) return false; + const partial = this.hasMoreHistory || this.historyCursor !== null; + if (!this.items.has(item.id) && partial) { + // Updates to rows from history we never loaded. + if (this.latestLocalTurnOrdinal !== null && item.ordinal <= this.latestLocalTurnOrdinal) return false; + const oldest = this.oldestLocalOrdinal(); + if (oldest !== null && item.ordinal < oldest) return false; + } + this.items.set(item.id, item); + if (partial && (this.latestLocalTurnOrdinal === null || item.ordinal > this.latestLocalTurnOrdinal)) { + this.latestLocalTurnOrdinal = item.ordinal; + } + if (this.items.size > MAX_ITEMS_KEPT) this.trimOldest(); + return true; + } + + private oldestLocalOrdinal(): number | null { + let oldest: number | null = null; + for (const item of this.items.values()) if (oldest === null || item.ordinal < oldest) oldest = item.ordinal; + return oldest; + } + + /** A long-lived subscription keeps growing; drop the oldest rows (they're history now). */ + private trimOldest(): void { + const sorted = [...this.items.values()].sort(compareItems); + for (const item of sorted.slice(0, sorted.length - MAX_ITEMS_KEPT)) this.items.delete(item.id); + this.hasMoreHistory = true; + this.inherited = []; + } + + /** Visible rows in display order (inherited fork history first). */ + timeline(): T3TurnItem[] { + const local = [...this.items.values()].filter((item) => this.isVisible(item)).sort(compareItems); + return [...this.inherited, ...local]; + } + + private isVisible(item: T3TurnItem): boolean { + const run = item.runId ? this.runs.get(item.runId) : undefined; + if (run?.status === "rolled_back") return false; + if (item.type === "user_message" && item.inputIntent === "queued_turn" && run?.status === "cancelled") return false; + if (item.type === "run_interrupt_result" && item.runId && item.nodeId) { + const superseded = [...this.attempts.values()].some( + (attempt) => attempt.runId === item.runId && attempt.rootNodeId === item.nodeId && attempt.status === "superseded", + ); + if (superseded) { + const hasRequest = [...this.items.values()].some( + (candidate) => candidate.type === "run_interrupt_request" && candidate.runId === item.runId, + ); + if (!hasRequest) return false; + } + } + return true; + } + + /** The run a Stop should interrupt, if any. */ + activeRunId(): string | null { + let active: T3Run | null = null; + for (const run of this.runs.values()) { + if (["preparing", "starting", "running", "waiting"].includes(run.status)) { + if (!active || timeMs(run.requestedAt) >= timeMs(active.requestedAt)) active = run; + } + } + return active?.id ?? null; + } + + /** Pending approvals and questions, oldest first, paired with their timeline rows. */ + pendingRequests(): PendingRequest[] { + const result: PendingRequest[] = []; + const items = [...this.items.values()].sort(compareItems); + for (const request of this.runtimeRequests.values()) { + if (request.status !== "pending") continue; + if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue; + const type = request.kind === "user_input" ? "user_input_request" : "approval_request"; + const item = [...items].reverse().find((candidate) => candidate.type === type && candidate.requestId === request.id); + if (!item) continue; + const capability = request.responseCapability?.type ?? "live"; + result.push({ + request, + item, + kind: request.kind === "user_input" ? "question" : "approval", + answerable: request.kind === "user_input" ? capability !== "not_resumable" : capability === "live", + messageMode: item.responseMode === "message" || capability === "message", + }); + } + return result.sort((a, b) => compareItems(a.item, b.item)); + } + + /** Follow-ups waiting for the active run to finish (they have no timeline row yet). */ + queuedMessages(): string[] { + return [...this.runs.values()] + .filter((run) => run.status === "queued" && run.userMessageId) + .sort((a, b) => (a.queuePosition ?? 0) - (b.queuePosition ?? 0)) + .map((run) => this.messages.get(run.userMessageId!)) + .filter((message): message is T3ConversationMessage => Boolean(message && !message.delegatedCompletion && !message.notification)) + .map((message) => message.text ?? ""); + } + + /** The current todo list (the latest run's, else the newest one). */ + todoList(): T3Plan | null { + const todos = [...this.plans.values()].filter((plan) => plan.kind === "todo_list" && plan.steps?.length); + if (!todos.length) return null; + const latestRunId = this.thread?.latestRunId ?? null; + return todos.find((plan) => plan.runId === latestRunId) ?? todos[todos.length - 1]!; + } +} + +export type PendingRequest = { + request: T3RuntimeRequest; + item: T3TurnItem; + kind: "approval" | "question"; + /** False when the provider session can't take an answer any more (interrupt instead). */ + answerable: boolean; + /** Message-mode questions: answers must be non-empty strings. */ + messageMode: boolean; +}; + +function compareItems(a: T3TurnItem, b: T3TurnItem): number { + return a.ordinal - b.ordinal || String(a.id).localeCompare(String(b.id)); +} + +// --------------------------------------------------------------------------- +// Timeline presentation + +export type TimelineEntry = + | { kind: "user"; id: string; text: string; queued?: boolean } + | { kind: "assistant"; id: string; text: string; streaming: boolean } + | { kind: "activity"; id: string; label: string; detail: string; state: ActivityState } + | { kind: "request"; id: string; label: string; detail: string; resolved: boolean }; + +export type ActivityState = "running" | "done" | "failed" | "stopped"; + +function activityState(item: T3TurnItem): ActivityState { + switch (item.status) { + case "pending": + case "running": + case "waiting": + return "running"; + case "failed": + return "failed"; + case "cancelled": + case "interrupted": + return "stopped"; + default: + return "done"; + } +} + +function capitalize(text: string): string { + return text ? text[0]!.toUpperCase() + text.slice(1) : text; +} + +function oneLine(text: string | null | undefined): string { + return (text ?? "").replace(/\s+/g, " ").trim(); +} + +function baseName(path: string): string { + return path.split(/[\\/]/).filter(Boolean).pop() ?? path; +} + +/** `bash -lc '