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