The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | // An in-process environment for app render scenarios: a fetch stub for its HTTP API and a |
| 2 | // session that answers the shell, thread and config subscriptions from fixtures. Other RPCs |
| 3 | // stay pending so nothing retries on timers. Everything above the wire is the app's own. |
| 4 | import { |
| 5 | type AssetCreateUrlResult, |
| 6 | AuthStandardClientScopes, |
| 7 | EnvironmentId, |
| 8 | EventId, |
| 9 | ExecutionEnvironmentDescriptor, |
| 10 | MessageId, |
| 11 | NodeId, |
| 12 | OrchestrationV2DispatchCommandError, |
| 13 | ORCHESTRATION_PROTOCOL_VERSION, |
| 14 | ORCHESTRATION_V2_WS_METHODS, |
| 15 | ProjectId, |
| 16 | ProviderInstanceId, |
| 17 | RunId, |
| 18 | RuntimeRequestId, |
| 19 | ServerConfig, |
| 20 | ThreadId, |
| 21 | TurnItemId, |
| 22 | WS_METHODS, |
| 23 | WsRpcGroup, |
| 24 | type VcsStatusStreamEvent, |
| 25 | type ModelSelection, |
| 26 | type OrchestrationProjectShell, |
| 27 | type OrchestrationV2Command, |
| 28 | type OrchestrationV2ProjectedTurnItem, |
| 29 | type OrchestrationV2ProviderThread, |
| 30 | type OrchestrationV2Run, |
| 31 | type OrchestrationV2ShellStreamItem, |
| 32 | type OrchestrationV2ThreadProjection, |
| 33 | type OrchestrationV2ThreadShell, |
| 34 | type OrchestrationV2ThreadStreamItem, |
| 35 | type OrchestrationV2TurnItem, |
| 36 | type TerminalMetadataStreamEvent, |
| 37 | type ResolvedKeybindingsConfig, |
| 38 | } from "@t3tools/contracts"; |
| 39 | import type { |
| 40 | ConnectionAttemptError, |
| 41 | ConnectionCatalogEntry, |
| 42 | EnvironmentConnectionLease, |
| 43 | RouteCheck, |
| 44 | } from "@t3tools/client-runtime/connection"; |
| 45 | import type { WsRpcProtocolClient } from "@t3tools/client-runtime/rpc"; |
| 46 | import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; |
| 47 | import { APP_VERSION } from "~/branding"; |
| 48 | import * as DateTime from "effect/DateTime"; |
| 49 | import * as Deferred from "effect/Deferred"; |
| 50 | import * as Effect from "effect/Effect"; |
| 51 | import * as Queue from "effect/Queue"; |
| 52 | import type * as Scope from "effect/Scope"; |
| 53 | import * as Schema from "effect/Schema"; |
| 54 | import * as Stream from "effect/Stream"; |
| 55 | import { RpcSchema } from "effect/rpc"; |
| 56 | |
| 57 | export const ENVIRONMENT_ID = EnvironmentId.make("environment-render"); |
| 58 | export const PROJECT_ID = ProjectId.make("project-render"); |
| 59 | const CODEX = ProviderInstanceId.make("codex"); |
| 60 | const MODEL = { instanceId: CODEX, model: "gpt-5.4" }; |
| 61 | const AT = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z"); |
| 62 | |
| 63 | const descriptor = { |
| 64 | environmentId: ENVIRONMENT_ID, |
| 65 | label: "Render scenarios", |
| 66 | platform: { os: "linux", arch: "x64" }, |
| 67 | // A matching version, since a mismatch adds an update banner a typical user never sees. |
| 68 | serverVersion: APP_VERSION, |
| 69 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, |
| 70 | capabilities: { repositoryIdentity: true, sideChats: true, freshContext: true }, |
| 71 | }; |
| 72 | const auth = { |
| 73 | policy: "loopback-browser", |
| 74 | bootstrapMethods: ["one-time-token"], |
| 75 | sessionMethods: ["browser-session-cookie"], |
| 76 | sessionCookieName: "t3_session", |
| 77 | }; |
| 78 | |
| 79 | const readyProvider = ( |
| 80 | instanceId: string, |
| 81 | driver: string, |
| 82 | models: ReadonlyArray<{ readonly slug: string; readonly name: string }>, |
| 83 | ) => ({ |
| 84 | instanceId, |
| 85 | driver, |
| 86 | enabled: true, |
| 87 | installed: true, |
| 88 | version: "1.0.0", |
| 89 | status: "ready", |
| 90 | auth: { status: "authenticated" }, |
| 91 | checkedAt: "2026-03-17T19:12:28.000Z", |
| 92 | models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })), |
| 93 | }); |
| 94 | export const CODEX_PROVIDER = readyProvider(CODEX, "codex", [ |
| 95 | { slug: "gpt-5.4", name: "GPT-5.4" }, |
| 96 | { slug: "gpt-5.5", name: "GPT-5.5" }, |
| 97 | ]); |
| 98 | export const CLAUDE_PROVIDER = { |
| 99 | ...readyProvider("claudeAgent", "claudeAgent", [ |
| 100 | { slug: "claude-opus-4-6", name: "Claude Opus 4.6" }, |
| 101 | ]), |
| 102 | slashCommands: [{ name: "compact" }], |
| 103 | }; |
| 104 | |
| 105 | const decodeServerConfig = Schema.decodeUnknownSync(ServerConfig); |
| 106 | const makeServerConfig = ( |
| 107 | providers: ReadonlyArray<unknown>, |
| 108 | supportsIssues = false, |
| 109 | ): ServerConfig => ({ |
| 110 | ...decodeServerConfig({ |
| 111 | environment: { |
| 112 | ...descriptor, |
| 113 | capabilities: { ...descriptor.capabilities, issues: supportsIssues }, |
| 114 | }, |
| 115 | auth, |
| 116 | cwd: "/workspace/render", |
| 117 | keybindingsConfigPath: "/workspace/.t3/keybindings.json", |
| 118 | keybindings: [], |
| 119 | issues: [], |
| 120 | providers, |
| 121 | availableEditors: [], |
| 122 | observability: { |
| 123 | logsDirectoryPath: "/workspace/.t3/logs", |
| 124 | localTracingEnabled: false, |
| 125 | otlpTracesEnabled: false, |
| 126 | otlpMetricsEnabled: false, |
| 127 | }, |
| 128 | settings: {}, |
| 129 | threadSnapshotPagination: true, |
| 130 | threadResumeCompletionMarker: true, |
| 131 | shellResumeCompletionMarker: true, |
| 132 | }), |
| 133 | keybindings: DEFAULT_RESOLVED_KEYBINDINGS, |
| 134 | }); |
| 135 | let baseServerConfig = makeServerConfig([CODEX_PROVIDER]); |
| 136 | // A server only leaves threads out of the shell when it serves their families. |
| 137 | const serverConfig = (): ServerConfig => |
| 138 | threads.some((thread) => thread.olderSettled) |
| 139 | ? { ...baseServerConfig, shellThreadFamilies: true } |
| 140 | : baseServerConfig; |
| 141 | |
| 142 | const project: OrchestrationProjectShell = { |
| 143 | id: PROJECT_ID, |
| 144 | title: "render", |
| 145 | workspaceRoot: "/workspace/render", |
| 146 | repositoryIdentity: null, |
| 147 | defaultModelSelection: null, |
| 148 | scripts: [], |
| 149 | createdAt: "2026-03-17T19:12:28.000Z", |
| 150 | updatedAt: "2026-03-17T19:12:28.000Z", |
| 151 | }; |
| 152 | |
| 153 | const base = (threadId: ThreadId, runId: RunId, id: string, ordinal: number) => ({ |
| 154 | id: TurnItemId.make(id), |
| 155 | threadId, |
| 156 | runId, |
| 157 | nodeId: null, |
| 158 | providerThreadId: null, |
| 159 | providerTurnId: null, |
| 160 | nativeItemRef: null, |
| 161 | parentItemId: null, |
| 162 | ordinal, |
| 163 | status: "completed" as const, |
| 164 | title: null, |
| 165 | startedAt: AT, |
| 166 | completedAt: AT, |
| 167 | updatedAt: AT, |
| 168 | }); |
| 169 | |
| 170 | function userItem(threadId: ThreadId, runId: RunId, id: string, ordinal: number, text: string) { |
| 171 | return { |
| 172 | ...base(threadId, runId, id, ordinal), |
| 173 | type: "user_message", |
| 174 | messageId: MessageId.make(id), |
| 175 | text, |
| 176 | attachments: [], |
| 177 | inputIntent: "turn_start", |
| 178 | createdBy: "user", |
| 179 | creationSource: "web", |
| 180 | } satisfies OrchestrationV2TurnItem; |
| 181 | } |
| 182 | |
| 183 | export function assistantItem( |
| 184 | threadId: ThreadId, |
| 185 | runId: RunId, |
| 186 | id: string, |
| 187 | ordinal: number, |
| 188 | text: string, |
| 189 | streaming = false, |
| 190 | ) { |
| 191 | return { |
| 192 | ...base(threadId, runId, id, ordinal), |
| 193 | type: "assistant_message", |
| 194 | messageId: MessageId.make(id), |
| 195 | text, |
| 196 | streaming, |
| 197 | ...(streaming ? { status: "running" as const, completedAt: null } : {}), |
| 198 | } satisfies OrchestrationV2TurnItem; |
| 199 | } |
| 200 | |
| 201 | function run( |
| 202 | threadId: ThreadId, |
| 203 | id: RunId, |
| 204 | ordinal: number, |
| 205 | userMessageId: string, |
| 206 | modelSelection: ModelSelection = MODEL, |
| 207 | ) { |
| 208 | return { |
| 209 | id, |
| 210 | threadId, |
| 211 | ordinal, |
| 212 | providerInstanceId: modelSelection.instanceId, |
| 213 | modelSelection, |
| 214 | providerThreadId: null, |
| 215 | userMessageId: MessageId.make(userMessageId), |
| 216 | rootNodeId: null, |
| 217 | activeAttemptId: null, |
| 218 | status: "completed", |
| 219 | requestedAt: AT, |
| 220 | startedAt: AT, |
| 221 | completedAt: AT, |
| 222 | checkpointId: null, |
| 223 | contextHandoffId: null, |
| 224 | } satisfies OrchestrationV2Run; |
| 225 | } |
| 226 | |
| 227 | export interface FakeThread { |
| 228 | /** Makes this a side chat of that thread. */ |
| 229 | readonly sideChatOf?: ThreadId; |
| 230 | /** Makes this a subagent the provider started under that thread, which takes no messages. */ |
| 231 | readonly providerSubagentOf?: ThreadId; |
| 232 | /** Makes this an older settled thread the shell leaves out; only its family read returns it. */ |
| 233 | readonly olderSettled?: true; |
| 234 | readonly id: ThreadId; |
| 235 | readonly title: string; |
| 236 | /** Defaults to GPT-5.4 on Codex. */ |
| 237 | readonly modelSelection?: ModelSelection; |
| 238 | /** The first is the thread's active provider thread. */ |
| 239 | readonly providerThreads?: ReadonlyArray<OrchestrationV2ProviderThread>; |
| 240 | readonly issues?: OrchestrationV2ThreadShell["issues"]; |
| 241 | readonly runs: ReadonlyArray<OrchestrationV2Run>; |
| 242 | readonly items: ReadonlyArray<OrchestrationV2TurnItem>; |
| 243 | readonly runtimeRequests?: OrchestrationV2ThreadProjection["runtimeRequests"]; |
| 244 | } |
| 245 | |
| 246 | /** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */ |
| 247 | export function threadWithHistory( |
| 248 | name: string, |
| 249 | turns: number, |
| 250 | modelSelection: ModelSelection = MODEL, |
| 251 | ): FakeThread { |
| 252 | const id = ThreadId.make(name); |
| 253 | const runs: OrchestrationV2Run[] = []; |
| 254 | const items: OrchestrationV2TurnItem[] = []; |
| 255 | for (let turn = 0; turn < turns; turn++) { |
| 256 | const runId = RunId.make(`${name}-run-${turn}`); |
| 257 | runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`, modelSelection)); |
| 258 | items.push( |
| 259 | userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`), |
| 260 | assistantItem( |
| 261 | id, |
| 262 | runId, |
| 263 | `${name}-assistant-${turn}`, |
| 264 | turn * 2 + 1, |
| 265 | `Answer ${turn} for ${name}.\n\n- checked \`Sidebar.tsx\`\n- ran the tests\n\n` + |
| 266 | "The width is now `clamp(next, MIN_WIDTH, MAX_WIDTH)`, so the layout no longer jumps.", |
| 267 | ), |
| 268 | ); |
| 269 | } |
| 270 | return { id, title: `Thread ${name}`, modelSelection, runs, items }; |
| 271 | } |
| 272 | |
| 273 | /** A one-turn thread whose agent waits on an answer to one question. */ |
| 274 | export function threadWithQuestion(name: string, question: string): FakeThread { |
| 275 | const thread = threadWithHistory(name, 1); |
| 276 | const requestId = RuntimeRequestId.make(`${name}-request`); |
| 277 | return { |
| 278 | ...thread, |
| 279 | items: [ |
| 280 | ...thread.items, |
| 281 | { |
| 282 | ...base(thread.id, RunId.make(`${name}-run-0`), `${name}-question`, 2), |
| 283 | type: "user_input_request", |
| 284 | requestId, |
| 285 | responseMode: "message", |
| 286 | questions: [ |
| 287 | { |
| 288 | id: "choice", |
| 289 | header: "Choice", |
| 290 | question, |
| 291 | required: true, |
| 292 | allowCustomAnswer: false, |
| 293 | options: [{ label: "Continue", value: "continue", description: "Resume work" }], |
| 294 | }, |
| 295 | ], |
| 296 | }, |
| 297 | ], |
| 298 | runtimeRequests: [ |
| 299 | { |
| 300 | id: requestId, |
| 301 | nodeId: NodeId.make(`${name}-node`), |
| 302 | providerTurnId: null, |
| 303 | nativeRequestRef: null, |
| 304 | kind: "user_input", |
| 305 | status: "pending", |
| 306 | responseCapability: { type: "message" }, |
| 307 | createdAt: AT, |
| 308 | resolvedAt: null, |
| 309 | }, |
| 310 | ], |
| 311 | }; |
| 312 | } |
| 313 | |
| 314 | const parentOf = (thread: FakeThread) => thread.sideChatOf ?? thread.providerSubagentOf; |
| 315 | |
| 316 | function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { |
| 317 | const latest = thread.runs.at(-1); |
| 318 | const modelSelection = thread.modelSelection ?? MODEL; |
| 319 | return { |
| 320 | id: thread.id, |
| 321 | projectId: PROJECT_ID, |
| 322 | title: thread.title, |
| 323 | providerInstanceId: modelSelection.instanceId, |
| 324 | modelSelection, |
| 325 | runtimeMode: "full-access", |
| 326 | interactionMode: "default", |
| 327 | branch: "main", |
| 328 | worktreePath: null, |
| 329 | activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null, |
| 330 | ...(thread.issues === undefined ? {} : { issues: thread.issues }), |
| 331 | lineage: { |
| 332 | rootThreadId: parentOf(thread) ?? thread.id, |
| 333 | parentThreadId: parentOf(thread) ?? null, |
| 334 | relationshipToParent: thread.providerSubagentOf ? "subagent" : null, |
| 335 | ...(thread.sideChatOf ? { sideChat: true } : {}), |
| 336 | }, |
| 337 | forkedFrom: null, |
| 338 | createdBy: thread.providerSubagentOf ? "agent" : "user", |
| 339 | creationSource: thread.providerSubagentOf ? "provider" : "web", |
| 340 | latestRunId: latest?.id ?? null, |
| 341 | activeRunId: null, |
| 342 | // Idle reads as waiting on the user, which shows a per-second duration in the sidebar. |
| 343 | status: latest ? "completed" : "idle", |
| 344 | pendingRuntimeRequest: null, |
| 345 | latestVisibleMessage: null, |
| 346 | latestUserMessageAt: AT, |
| 347 | hasActionableProposedPlan: false, |
| 348 | itemCount: thread.items.length, |
| 349 | visibleItemCount: thread.items.length, |
| 350 | createdAt: AT, |
| 351 | updatedAt: AT, |
| 352 | archivedAt: null, |
| 353 | settledOverride: thread.olderSettled ? "settled" : null, |
| 354 | settledAt: thread.olderSettled ? AT : null, |
| 355 | lastVisitedAt: AT, |
| 356 | deletedAt: null, |
| 357 | }; |
| 358 | } |
| 359 | |
| 360 | function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { |
| 361 | const shell = shellOf(thread); |
| 362 | const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = thread.items.map( |
| 363 | (item, position) => ({ |
| 364 | position, |
| 365 | visibility: "local", |
| 366 | sourceThreadId: thread.id, |
| 367 | sourceItemId: item.id, |
| 368 | item, |
| 369 | }), |
| 370 | ); |
| 371 | return { |
| 372 | thread: { |
| 373 | id: shell.id, |
| 374 | projectId: shell.projectId, |
| 375 | title: shell.title, |
| 376 | providerInstanceId: shell.providerInstanceId, |
| 377 | modelSelection: shell.modelSelection, |
| 378 | runtimeMode: shell.runtimeMode, |
| 379 | interactionMode: shell.interactionMode, |
| 380 | branch: shell.branch, |
| 381 | worktreePath: shell.worktreePath, |
| 382 | activeProviderThreadId: shell.activeProviderThreadId, |
| 383 | lineage: shell.lineage, |
| 384 | forkedFrom: null, |
| 385 | createdBy: shell.createdBy, |
| 386 | creationSource: shell.creationSource, |
| 387 | createdAt: AT, |
| 388 | updatedAt: AT, |
| 389 | archivedAt: null, |
| 390 | settledOverride: shell.settledOverride, |
| 391 | settledAt: shell.settledAt, |
| 392 | lastVisitedAt: AT, |
| 393 | deletedAt: null, |
| 394 | }, |
| 395 | runs: [...thread.runs], |
| 396 | attempts: [], |
| 397 | nodes: [], |
| 398 | subagents: [], |
| 399 | providerSessions: [], |
| 400 | providerThreads: [...(thread.providerThreads ?? [])], |
| 401 | providerTurns: [], |
| 402 | runtimeRequests: [...(thread.runtimeRequests ?? [])], |
| 403 | messages: [], |
| 404 | plans: [], |
| 405 | turnItems: [...thread.items], |
| 406 | checkpointScopes: [], |
| 407 | checkpoints: [], |
| 408 | contextHandoffs: [], |
| 409 | contextTransfers: [], |
| 410 | visibleTurnItems, |
| 411 | updatedAt: AT, |
| 412 | }; |
| 413 | } |
| 414 | |
| 415 | const json = (body: unknown, status = 200) => |
| 416 | new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); |
| 417 | |
| 418 | // Keyed by thread id: a live thread subscription's queue, for pushing events to it. |
| 419 | const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>(); |
| 420 | let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null; |
| 421 | let shellSubscriber: Queue.Queue<OrchestrationV2ShellStreamItem> | null = null; |
| 422 | let threads: ReadonlyArray<FakeThread> = []; |
| 423 | let dispatched: OrchestrationV2Command[] = []; |
| 424 | let acceptCommands = false; |
| 425 | let projects: ReadonlyArray<OrchestrationProjectShell> = [project]; |
| 426 | let holdCommand: (command: OrchestrationV2Command) => boolean = () => false; |
| 427 | let pendingDispatches: Array<{ |
| 428 | readonly command: OrchestrationV2Command; |
| 429 | readonly reply: Deferred.Deferred<never, OrchestrationV2DispatchCommandError>; |
| 430 | }> = []; |
| 431 | let pendingAssetUrls: Array<Deferred.Deferred<AssetCreateUrlResult>> = []; |
| 432 | let sequence = 1; |
| 433 | let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null; |
| 434 | |
| 435 | const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>) => () => void) => |
| 436 | Stream.unwrap( |
| 437 | Effect.gen(function* () { |
| 438 | const queue = yield* Queue.unbounded<A>(); |
| 439 | yield* Queue.offerAll(queue, first); |
| 440 | if (register) { |
| 441 | const unregister = register(queue); |
| 442 | yield* Effect.addFinalizer(() => Effect.sync(unregister)); |
| 443 | } |
| 444 | return Stream.fromQueue(queue); |
| 445 | }), |
| 446 | ); |
| 447 | |
| 448 | const handlers: Record<string, (input: never) => unknown> = { |
| 449 | // Recorded, and accepted only when the scenario asks, since a pending command holds every |
| 450 | // later command on its thread. Accepted commands' events never arrive. |
| 451 | [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) => |
| 452 | Effect.suspend(() => { |
| 453 | dispatched.push(command); |
| 454 | if (acceptCommands && !holdCommand(command)) { |
| 455 | if (command.type !== "thread.fork" || !command.sideChat || shellSubscriber === null) |
| 456 | return Effect.succeed({ sequence: sequence + 1 }); |
| 457 | const fork: FakeThread = { |
| 458 | id: command.targetThreadId, |
| 459 | title: command.title ?? "Side chat", |
| 460 | sideChatOf: command.sourceThreadId, |
| 461 | runs: [], |
| 462 | items: [], |
| 463 | }; |
| 464 | threads = [...threads, fork]; |
| 465 | sequence += 1; |
| 466 | return Queue.offer(shellSubscriber, { |
| 467 | kind: "thread.updated", |
| 468 | sequence, |
| 469 | location: "active", |
| 470 | thread: shellOf(fork), |
| 471 | }).pipe(Effect.as({ sequence })); |
| 472 | } |
| 473 | const reply = Deferred.makeUnsafe<never, OrchestrationV2DispatchCommandError>(); |
| 474 | pendingDispatches.push({ command, reply }); |
| 475 | return Deferred.await(reply); |
| 476 | }), |
| 477 | // Held like any other unanswered call, until `answerAssetUrls`. |
| 478 | [WS_METHODS.assetsCreateUrl]: () => |
| 479 | Effect.suspend(() => { |
| 480 | const reply = Deferred.makeUnsafe<AssetCreateUrlResult>(); |
| 481 | pendingAssetUrls.push(reply); |
| 482 | return Deferred.await(reply); |
| 483 | }), |
| 484 | [WS_METHODS.subscribeTerminalMetadata]: () => |
| 485 | subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => { |
| 486 | terminalMetadataSubscriber = queue; |
| 487 | return () => { |
| 488 | if (terminalMetadataSubscriber === queue) terminalMetadataSubscriber = null; |
| 489 | }; |
| 490 | }), |
| 491 | [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => |
| 492 | subscribe<OrchestrationV2ShellStreamItem>( |
| 493 | [ |
| 494 | { |
| 495 | kind: "snapshot", |
| 496 | snapshot: { |
| 497 | schemaVersion: 1, |
| 498 | snapshotSequence: sequence, |
| 499 | projects, |
| 500 | threads: threads.filter((thread) => !thread.olderSettled).map(shellOf), |
| 501 | archivedThreads: [], |
| 502 | }, |
| 503 | }, |
| 504 | { kind: "synchronized" }, |
| 505 | ], |
| 506 | (queue) => { |
| 507 | shellSubscriber = queue; |
| 508 | return () => { |
| 509 | if (shellSubscriber === queue) shellSubscriber = null; |
| 510 | }; |
| 511 | }, |
| 512 | ), |
| 513 | [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly threadId: ThreadId }) => { |
| 514 | const thread = threads.find((candidate) => candidate.id === input.threadId); |
| 515 | if (!thread) return Stream.never; |
| 516 | return subscribe<OrchestrationV2ThreadStreamItem>( |
| 517 | [ |
| 518 | { kind: "snapshot", snapshotSequence: sequence, projection: projectionOf(thread) }, |
| 519 | { kind: "synchronized" }, |
| 520 | ], |
| 521 | (queue) => { |
| 522 | threadSubscribers.set(thread.id, queue); |
| 523 | |
| 524 | // A replaced subscription closes after its successor registers. |
| 525 | return () => { |
| 526 | if (threadSubscribers.get(thread.id) === queue) threadSubscribers.delete(thread.id); |
| 527 | }; |
| 528 | }, |
| 529 | ); |
| 530 | }, |
| 531 | [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input: { readonly threadId: ThreadId }) => { |
| 532 | const rootOf = (thread: FakeThread) => parentOf(thread) ?? thread.id; |
| 533 | const requested = threads.find((candidate) => candidate.id === input.threadId); |
| 534 | return Effect.succeed({ |
| 535 | snapshotSequence: sequence, |
| 536 | threads: requested |
| 537 | ? threads.filter((thread) => rootOf(thread) === rootOf(requested)).map(shellOf) |
| 538 | : [], |
| 539 | }); |
| 540 | }, |
| 541 | [WS_METHODS.subscribeVcsStatus]: () => |
| 542 | subscribe<VcsStatusStreamEvent>([], (queue) => { |
| 543 | vcsStatusSubscriber = queue; |
| 544 | return () => { |
| 545 | if (vcsStatusSubscriber === queue) vcsStatusSubscriber = null; |
| 546 | }; |
| 547 | }), |
| 548 | [WS_METHODS.subscribeServerConfig]: () => |
| 549 | subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig() }]), |
| 550 | }; |
| 551 | |
| 552 | // Unanswered calls stay pending, like a server that has not replied yet. |
| 553 | const client = new Proxy(handlers, { |
| 554 | get: (target, method: string) => |
| 555 | target[method] ?? |
| 556 | (() => { |
| 557 | const rpc = WsRpcGroup.requests.get(method); |
| 558 | return rpc && RpcSchema.isStreamSchema(rpc.successSchema) ? Stream.never : Effect.never; |
| 559 | }), |
| 560 | }); |
| 561 | |
| 562 | const session: EnvironmentConnectionLease["session"] = { |
| 563 | client: client as unknown as WsRpcProtocolClient, |
| 564 | initialConfig: Effect.sync(serverConfig), |
| 565 | subscribeServerConfig: () => |
| 566 | subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig() }]), |
| 567 | ready: Effect.void, |
| 568 | probe: Effect.void, |
| 569 | inboundFrames: Effect.succeed(0), |
| 570 | closed: Effect.never, |
| 571 | }; |
| 572 | |
| 573 | /** Stands in for client-runtime's ConnectionDriver: every connection opens the session above. */ |
| 574 | export const fakeDriver = { |
| 575 | connect: ( |
| 576 | entry: ConnectionCatalogEntry, |
| 577 | ): Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope> => |
| 578 | Effect.succeed({ |
| 579 | prepared: { |
| 580 | environmentId: ENVIRONMENT_ID, |
| 581 | label: descriptor.label, |
| 582 | httpBaseUrl: window.location.origin, |
| 583 | socketUrl: window.location.origin.replace(/^http/, "ws"), |
| 584 | httpAuthorization: null, |
| 585 | target: entry.target, |
| 586 | }, |
| 587 | session, |
| 588 | refusedRouteIds: [], |
| 589 | }), |
| 590 | preflight: () => Effect.succeed(true), |
| 591 | checkHost: () => Effect.succeed<RouteCheck>("unchecked"), |
| 592 | }; |
| 593 | export type FakeDriver = typeof fakeDriver; |
| 594 | |
| 595 | const realFetch = globalThis.fetch; |
| 596 | const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)( |
| 597 | Schema.decodeUnknownSync(ExecutionEnvironmentDescriptor)(descriptor), |
| 598 | ); |
| 599 | |
| 600 | /** Serves the environment's HTTP API and these threads until disposed. */ |
| 601 | export function installFakeEnvironment( |
| 602 | fixtures: ReadonlyArray<FakeThread>, |
| 603 | options?: { |
| 604 | readonly acceptCommands?: boolean; |
| 605 | readonly keybindings?: ResolvedKeybindingsConfig; |
| 606 | readonly extraProjects?: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>; |
| 607 | /** Commands left unanswered even when accepting, until `rejectPendingCommand`. */ |
| 608 | readonly holdCommand?: (command: OrchestrationV2Command) => boolean; |
| 609 | readonly providers?: ReadonlyArray<unknown>; |
| 610 | }, |
| 611 | ): Disposable { |
| 612 | threads = fixtures; |
| 613 | baseServerConfig = { |
| 614 | ...makeServerConfig( |
| 615 | options?.providers ?? [CODEX_PROVIDER], |
| 616 | fixtures.some((thread) => (thread.issues?.length ?? 0) > 0), |
| 617 | ), |
| 618 | keybindings: options?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS, |
| 619 | }; |
| 620 | dispatched = []; |
| 621 | acceptCommands = options?.acceptCommands === true; |
| 622 | projects = [ |
| 623 | project, |
| 624 | ...(options?.extraProjects ?? []).map((extra) => ({ |
| 625 | ...project, |
| 626 | ...extra, |
| 627 | workspaceRoot: `/workspace/${extra.title}`, |
| 628 | })), |
| 629 | ]; |
| 630 | holdCommand = options?.holdCommand ?? (() => false); |
| 631 | globalThis.fetch = async (input, init) => { |
| 632 | const url = new URL(input instanceof Request ? input.url : String(input), window.location.href); |
| 633 | if (url.origin !== window.location.origin) return realFetch(input, init); |
| 634 | if (url.pathname === "/.well-known/t3/environment") return json(encodedDescriptor); |
| 635 | if (url.pathname === "/api/auth/session") { |
| 636 | return json({ |
| 637 | authenticated: true, |
| 638 | auth, |
| 639 | scopes: AuthStandardClientScopes, |
| 640 | sessionMethod: "browser-session-cookie", |
| 641 | expiresAt: "2099-01-01T00:00:00.000Z", |
| 642 | }); |
| 643 | } |
| 644 | // Snapshot endpoints fall back to the socket, which serves the same fixtures. |
| 645 | if (/^\/(api|oauth|\.well-known)\//.test(url.pathname)) return json({}, 404); |
| 646 | return realFetch(input, init); |
| 647 | }; |
| 648 | return { |
| 649 | [Symbol.dispose]: () => { |
| 650 | globalThis.fetch = realFetch; |
| 651 | threads = []; |
| 652 | baseServerConfig = makeServerConfig([CODEX_PROVIDER]); |
| 653 | dispatched = []; |
| 654 | acceptCommands = false; |
| 655 | projects = [project]; |
| 656 | holdCommand = () => false; |
| 657 | pendingDispatches = []; |
| 658 | pendingAssetUrls = []; |
| 659 | }, |
| 660 | }; |
| 661 | } |
| 662 | |
| 663 | /** Answers the oldest unanswered command with the server's rejection. */ |
| 664 | export async function rejectPendingCommand(message: string): Promise<void> { |
| 665 | const pending = pendingDispatches.shift(); |
| 666 | if (!pending) throw new Error("No pending command"); |
| 667 | await Effect.runPromise( |
| 668 | Deferred.fail( |
| 669 | pending.reply, |
| 670 | new OrchestrationV2DispatchCommandError({ |
| 671 | commandId: pending.command.commandId, |
| 672 | commandType: pending.command.type, |
| 673 | message, |
| 674 | }), |
| 675 | ), |
| 676 | ); |
| 677 | } |
| 678 | |
| 679 | export function hasPendingAssetUrl(): boolean { |
| 680 | return pendingAssetUrls.length > 0; |
| 681 | } |
| 682 | |
| 683 | /** Answers every held asset URL request, as a server that still has the file. */ |
| 684 | export async function answerAssetUrls(): Promise<void> { |
| 685 | const replies = pendingAssetUrls; |
| 686 | pendingAssetUrls = []; |
| 687 | for (const reply of replies) { |
| 688 | await Effect.runPromise( |
| 689 | Deferred.succeed(reply, { relativeUrl: "/api/assets/fake", expiresAt: 4_102_444_800_000 }), |
| 690 | ); |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | /** Commands the app dispatched to the environment, oldest first. */ |
| 695 | export function dispatchedCommands(): ReadonlyArray<OrchestrationV2Command> { |
| 696 | return dispatched; |
| 697 | } |
| 698 | |
| 699 | type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"]; |
| 700 | |
| 701 | /** Answers one RPC method with `handler` until disposed. */ |
| 702 | export function answerRpc(method: string, handler: (input: never) => unknown): Disposable { |
| 703 | const previous = handlers[method]; |
| 704 | handlers[method] = handler; |
| 705 | return { |
| 706 | [Symbol.dispose]: () => { |
| 707 | if (previous) handlers[method] = previous; |
| 708 | else delete handlers[method]; |
| 709 | }, |
| 710 | }; |
| 711 | } |
| 712 | |
| 713 | export async function emitTerminalMetadata(event: TerminalMetadataStreamEvent): Promise<void> { |
| 714 | if (terminalMetadataSubscriber === null) throw new Error("No terminal metadata subscription"); |
| 715 | await Effect.runPromise(Queue.offer(terminalMetadataSubscriber, event)); |
| 716 | } |
| 717 | |
| 718 | /** Whether the app holds a live subscription to the thread, so events reach it. */ |
| 719 | export function isThreadSubscribed(threadId: ThreadId): boolean { |
| 720 | return threadSubscribers.has(threadId); |
| 721 | } |
| 722 | |
| 723 | /** Delivers one domain event, such as a run or turn-item update, to the thread's subscription. */ |
| 724 | export async function emitThreadEvent( |
| 725 | threadId: ThreadId, |
| 726 | event: Pick<ThreadEvent, "type" | "payload">, |
| 727 | ): Promise<void> { |
| 728 | const queue = threadSubscribers.get(threadId); |
| 729 | if (!queue) throw new Error(`No live subscription for ${threadId}`); |
| 730 | sequence += 1; |
| 731 | await Effect.runPromise( |
| 732 | Queue.offer(queue, { |
| 733 | kind: "event", |
| 734 | sequence, |
| 735 | event: { ...event, id: EventId.make(`event-${sequence}`), threadId, occurredAt: AT }, |
| 736 | } as OrchestrationV2ThreadStreamItem), |
| 737 | ); |
| 738 | } |
| 739 | |
| 740 | export function runningRun(threadId: ThreadId, id: string, ordinal: number, userMessageId: string) { |
| 741 | return { |
| 742 | ...run(threadId, RunId.make(id), ordinal, userMessageId), |
| 743 | status: "running" as const, |
| 744 | completedAt: null, |
| 745 | }; |
| 746 | } |
| 747 | |
| 748 | export { userItem }; |
| 749 | |
| 750 | export async function emitVcsStatus(event: VcsStatusStreamEvent): Promise<void> { |
| 751 | if (vcsStatusSubscriber === null) throw new Error("No VCS status subscription"); |
| 752 | await Effect.runPromise(Queue.offer(vcsStatusSubscriber, event)); |
| 753 | } |