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 pullRequests?: OrchestrationV2ThreadShell["pullRequests"];
247 readonly runs: ReadonlyArray<OrchestrationV2Run>;
248 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
249 readonly runtimeRequests?: OrchestrationV2ThreadProjection["runtimeRequests"];
250}
251
252/** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */
253export function threadWithHistory(
254 name: string,
255 turns: number,
256 modelSelection: ModelSelection = MODEL,
257): FakeThread {
258 const id = ThreadId.make(name);
259 const runs: OrchestrationV2Run[] = [];
260 const items: OrchestrationV2TurnItem[] = [];
261 for (let turn = 0; turn < turns; turn++) {
262 const runId = RunId.make(`${name}-run-${turn}`);
263 runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`, modelSelection));
264 items.push(
265 userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`),
266 assistantItem(
267 id,
268 runId,
269 `${name}-assistant-${turn}`,
270 turn * 2 + 1,
271 `Answer ${turn} for ${name}.\n\n- checked \`Sidebar.tsx\`\n- ran the tests\n\n` +
272 "The width is now `clamp(next, MIN_WIDTH, MAX_WIDTH)`, so the layout no longer jumps.",
273 ),
274 );
275 }
276 return { id, title: `Thread ${name}`, modelSelection, runs, items };
277}
278
279/** A one-turn thread whose agent waits on an answer to one question. */
280export function threadWithQuestion(name: string, question: string): FakeThread {
281 const thread = threadWithHistory(name, 1);
282 const requestId = RuntimeRequestId.make(`${name}-request`);
283 return {
284 ...thread,
285 items: [
286 ...thread.items,
287 {
288 ...base(thread.id, RunId.make(`${name}-run-0`), `${name}-question`, 2),
289 type: "user_input_request",
290 requestId,
291 responseMode: "message",
292 questions: [
293 {
294 id: "choice",
295 header: "Choice",
296 question,
297 required: true,
298 allowCustomAnswer: false,
299 options: [{ label: "Continue", value: "continue", description: "Resume work" }],
300 },
301 ],
302 },
303 ],
304 runtimeRequests: [
305 {
306 id: requestId,
307 nodeId: NodeId.make(`${name}-node`),
308 providerTurnId: null,
309 nativeRequestRef: null,
310 kind: "user_input",
311 status: "pending",
312 responseCapability: { type: "message" },
313 createdAt: AT,
314 resolvedAt: null,
315 },
316 ],
317 };
318}
319
320const parentOf = (thread: FakeThread) => thread.sideChatOf ?? thread.providerSubagentOf;
321
322function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {
323 const latest = thread.runs.at(-1);
324 const modelSelection = thread.modelSelection ?? MODEL;
325 return {
326 id: thread.id,
327 projectId: PROJECT_ID,
328 title: thread.title,
329 providerInstanceId: modelSelection.instanceId,
330 modelSelection,
331 runtimeMode: "full-access",
332 interactionMode: "default",
333 branch: "main",
334 worktreePath: null,
335 activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null,
336 ...(thread.issues === undefined ? {} : { issues: thread.issues }),
337 ...(thread.pullRequests === undefined ? {} : { pullRequests: thread.pullRequests }),
338 lineage: {
339 rootThreadId: parentOf(thread) ?? thread.id,
340 parentThreadId: parentOf(thread) ?? null,
341 relationshipToParent: thread.providerSubagentOf ? "subagent" : null,
342 ...(thread.sideChatOf ? { sideChat: true } : {}),
343 },
344 forkedFrom: null,
345 createdBy: thread.providerSubagentOf ? "agent" : "user",
346 creationSource: thread.providerSubagentOf ? "provider" : "web",
347 latestRunId: latest?.id ?? null,
348 activeRunId: null,
349 // Idle reads as waiting on the user, which shows a per-second duration in the sidebar.
350 status: latest ? "completed" : "idle",
351 pendingRuntimeRequest: null,
352 latestVisibleMessage: null,
353 latestUserMessageAt: AT,
354 hasActionableProposedPlan: false,
355 itemCount: thread.items.length,
356 visibleItemCount: thread.items.length,
357 createdAt: AT,
358 updatedAt: AT,
359 archivedAt: null,
360 settledOverride: thread.olderSettled ? "settled" : null,
361 settledAt: thread.olderSettled ? AT : null,
362 lastVisitedAt: AT,
363 deletedAt: null,
364 };
365}
366
367function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
368 const shell = shellOf(thread);
369 const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = thread.items.map(
370 (item, position) => ({
371 position,
372 visibility: "local",
373 sourceThreadId: thread.id,
374 sourceItemId: item.id,
375 item,
376 }),
377 );
378 return {
379 thread: {
380 id: shell.id,
381 projectId: shell.projectId,
382 title: shell.title,
383 providerInstanceId: shell.providerInstanceId,
384 modelSelection: shell.modelSelection,
385 runtimeMode: shell.runtimeMode,
386 interactionMode: shell.interactionMode,
387 branch: shell.branch,
388 worktreePath: shell.worktreePath,
389 activeProviderThreadId: shell.activeProviderThreadId,
390 lineage: shell.lineage,
391 forkedFrom: null,
392 createdBy: shell.createdBy,
393 creationSource: shell.creationSource,
394 createdAt: AT,
395 updatedAt: AT,
396 archivedAt: null,
397 settledOverride: shell.settledOverride,
398 settledAt: shell.settledAt,
399 lastVisitedAt: AT,
400 deletedAt: null,
401 },
402 runs: [...thread.runs],
403 attempts: [],
404 nodes: [],
405 subagents: [],
406 providerSessions: [],
407 providerThreads: [...(thread.providerThreads ?? [])],
408 providerTurns: [],
409 runtimeRequests: [...(thread.runtimeRequests ?? [])],
410 messages: [],
411 plans: [],
412 turnItems: [...thread.items],
413 checkpointScopes: [],
414 checkpoints: [],
415 contextHandoffs: [],
416 contextTransfers: [],
417 visibleTurnItems,
418 updatedAt: AT,
419 };
420}
421
422const json = (body: unknown, status = 200) =>
423 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
424
425// Keyed by thread id: a live thread subscription's queue, for pushing events to it.
426const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();
427let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;
428let shellSubscriber: Queue.Queue<OrchestrationV2ShellStreamItem> | null = null;
429let threads: ReadonlyArray<FakeThread> = [];
430let dispatched: OrchestrationV2Command[] = [];
431let acceptCommands = false;
432let projects: ReadonlyArray<OrchestrationProjectShell> = [project];
433let holdCommand: (command: OrchestrationV2Command) => boolean = () => false;
434let pendingDispatches: Array<{
435 readonly command: OrchestrationV2Command;
436 readonly reply: Deferred.Deferred<never, OrchestrationV2DispatchCommandError>;
437}> = [];
438let pendingAssetUrls: Array<Deferred.Deferred<AssetCreateUrlResult>> = [];
439let sequence = 1;
440let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null;
441
442const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>) => () => void) =>
443 Stream.unwrap(
444 Effect.gen(function* () {
445 const queue = yield* Queue.unbounded<A>();
446 yield* Queue.offerAll(queue, first);
447 if (register) {
448 const unregister = register(queue);
449 yield* Effect.addFinalizer(() => Effect.sync(unregister));
450 }
451 return Stream.fromQueue(queue);
452 }),
453 );
454
455const handlers: Record<string, (input: never) => unknown> = {
456 // Recorded, and accepted only when the scenario asks, since a pending command holds every
457 // later command on its thread. Accepted commands' events never arrive.
458 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
459 Effect.suspend(() => {
460 dispatched.push(command);
461 if (acceptCommands && !holdCommand(command)) {
462 if (command.type !== "thread.fork" || !command.sideChat || shellSubscriber === null)
463 return Effect.succeed({ sequence: sequence + 1 });
464 const fork: FakeThread = {
465 id: command.targetThreadId,
466 title: command.title ?? "Side chat",
467 sideChatOf: command.sourceThreadId,
468 runs: [],
469 items: [],
470 };
471 threads = [...threads, fork];
472 sequence += 1;
473 return Queue.offer(shellSubscriber, {
474 kind: "thread.updated",
475 sequence,
476 location: "active",
477 thread: shellOf(fork),
478 }).pipe(Effect.as({ sequence }));
479 }
480 const reply = Deferred.makeUnsafe<never, OrchestrationV2DispatchCommandError>();
481 pendingDispatches.push({ command, reply });
482 return Deferred.await(reply);
483 }),
484 // Held like any other unanswered call, until `answerAssetUrls`.
485 [WS_METHODS.assetsCreateUrl]: () =>
486 Effect.suspend(() => {
487 const reply = Deferred.makeUnsafe<AssetCreateUrlResult>();
488 pendingAssetUrls.push(reply);
489 return Deferred.await(reply);
490 }),
491 [WS_METHODS.subscribeTerminalMetadata]: () =>
492 subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => {
493 terminalMetadataSubscriber = queue;
494 return () => {
495 if (terminalMetadataSubscriber === queue) terminalMetadataSubscriber = null;
496 };
497 }),
498 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
499 subscribe<OrchestrationV2ShellStreamItem>(
500 [
501 {
502 kind: "snapshot",
503 snapshot: {
504 schemaVersion: 1,
505 snapshotSequence: sequence,
506 projects,
507 threads: threads.filter((thread) => !thread.olderSettled).map(shellOf),
508 archivedThreads: [],
509 },
510 },
511 { kind: "synchronized" },
512 ],
513 (queue) => {
514 shellSubscriber = queue;
515 return () => {
516 if (shellSubscriber === queue) shellSubscriber = null;
517 };
518 },
519 ),
520 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly threadId: ThreadId }) => {
521 const thread = threads.find((candidate) => candidate.id === input.threadId);
522 if (!thread) return Stream.never;
523 return subscribe<OrchestrationV2ThreadStreamItem>(
524 [
525 { kind: "snapshot", snapshotSequence: sequence, projection: projectionOf(thread) },
526 { kind: "synchronized" },
527 ],
528 (queue) => {
529 threadSubscribers.set(thread.id, queue);
530
531 // A replaced subscription closes after its successor registers.
532 return () => {
533 if (threadSubscribers.get(thread.id) === queue) threadSubscribers.delete(thread.id);
534 };
535 },
536 );
537 },
538 [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input: { readonly threadId: ThreadId }) => {
539 const rootOf = (thread: FakeThread) => parentOf(thread) ?? thread.id;
540 const requested = threads.find((candidate) => candidate.id === input.threadId);
541 return Effect.succeed({
542 snapshotSequence: sequence,
543 threads: requested
544 ? threads.filter((thread) => rootOf(thread) === rootOf(requested)).map(shellOf)
545 : [],
546 });
547 },
548 [WS_METHODS.subscribeVcsStatus]: () =>
549 subscribe<VcsStatusStreamEvent>([], (queue) => {
550 vcsStatusSubscriber = queue;
551 return () => {
552 if (vcsStatusSubscriber === queue) vcsStatusSubscriber = null;
553 };
554 }),
555 [WS_METHODS.subscribeServerConfig]: () =>
556 subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig() }]),
557};
558
559// Unanswered calls stay pending, like a server that has not replied yet.
560const client = new Proxy(handlers, {
561 get: (target, method: string) =>
562 target[method] ??
563 (() => {
564 const rpc = WsRpcGroup.requests.get(method);
565 return rpc && RpcSchema.isStreamSchema(rpc.successSchema) ? Stream.never : Effect.never;
566 }),
567});
568
569const session: EnvironmentConnectionLease["session"] = {
570 client: client as unknown as WsRpcProtocolClient,
571 initialConfig: Effect.sync(serverConfig),
572 subscribeServerConfig: () =>
573 subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig() }]),
574 ready: Effect.void,
575 probe: Effect.void,
576 inboundFrames: Effect.succeed(0),
577 closed: Effect.never,
578};
579
580/** Stands in for client-runtime's ConnectionDriver: every connection opens the session above. */
581export const fakeDriver = {
582 connect: (
583 entry: ConnectionCatalogEntry,
584 ): Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope> =>
585 Effect.succeed({
586 prepared: {
587 environmentId: ENVIRONMENT_ID,
588 label: descriptor.label,
589 httpBaseUrl: window.location.origin,
590 socketUrl: window.location.origin.replace(/^http/, "ws"),
591 httpAuthorization: null,
592 target: entry.target,
593 },
594 session,
595 refusedRouteIds: [],
596 }),
597 preflight: () => Effect.succeed(true),
598 checkHost: () => Effect.succeed<RouteCheck>("unchecked"),
599};
600export type FakeDriver = typeof fakeDriver;
601
602const realFetch = globalThis.fetch;
603const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(
604 Schema.decodeUnknownSync(ExecutionEnvironmentDescriptor)(descriptor),
605);
606
607/** Serves the environment's HTTP API and these threads until disposed. */
608export function installFakeEnvironment(
609 fixtures: ReadonlyArray<FakeThread>,
610 options?: {
611 readonly acceptCommands?: boolean;
612 readonly keybindings?: ResolvedKeybindingsConfig;
613 readonly extraProjects?: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
614 /** Commands left unanswered even when accepting, until `rejectPendingCommand`. */
615 readonly holdCommand?: (command: OrchestrationV2Command) => boolean;
616 readonly providers?: ReadonlyArray<unknown>;
617 },
618): Disposable {
619 threads = fixtures;
620 baseServerConfig = {
621 ...makeServerConfig(
622 options?.providers ?? [CODEX_PROVIDER],
623 fixtures.some((thread) => (thread.issues?.length ?? 0) > 0),
624 ),
625 keybindings: options?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS,
626 };
627 dispatched = [];
628 acceptCommands = options?.acceptCommands === true;
629 projects = [
630 project,
631 ...(options?.extraProjects ?? []).map((extra) => ({
632 ...project,
633 ...extra,
634 workspaceRoot: `/workspace/${extra.title}`,
635 })),
636 ];
637 holdCommand = options?.holdCommand ?? (() => false);
638 globalThis.fetch = async (input, init) => {
639 const url = new URL(input instanceof Request ? input.url : String(input), window.location.href);
640 if (url.origin !== window.location.origin) return realFetch(input, init);
641 if (url.pathname === "/.well-known/t3/environment") return json(encodedDescriptor);
642 if (url.pathname === "/api/auth/session") {
643 return json({
644 authenticated: true,
645 auth,
646 scopes: AuthStandardClientScopes,
647 sessionMethod: "browser-session-cookie",
648 expiresAt: "2099-01-01T00:00:00.000Z",
649 });
650 }
651 // Snapshot endpoints fall back to the socket, which serves the same fixtures.
652 if (/^\/(api|oauth|\.well-known)\//.test(url.pathname)) return json({}, 404);
653 return realFetch(input, init);
654 };
655 return {
656 [Symbol.dispose]: () => {
657 globalThis.fetch = realFetch;
658 threads = [];
659 baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
660 dispatched = [];
661 acceptCommands = false;
662 projects = [project];
663 holdCommand = () => false;
664 pendingDispatches = [];
665 pendingAssetUrls = [];
666 },
667 };
668}
669
670/** Answers the oldest unanswered command with the server's rejection. */
671export async function rejectPendingCommand(message: string): Promise<void> {
672 const pending = pendingDispatches.shift();
673 if (!pending) throw new Error("No pending command");
674 await Effect.runPromise(
675 Deferred.fail(
676 pending.reply,
677 new OrchestrationV2DispatchCommandError({
678 commandId: pending.command.commandId,
679 commandType: pending.command.type,
680 message,
681 }),
682 ),
683 );
684}
685
686export function hasPendingAssetUrl(): boolean {
687 return pendingAssetUrls.length > 0;
688}
689
690/** Answers every held asset URL request, as a server that still has the file. */
691export async function answerAssetUrls(): Promise<void> {
692 const replies = pendingAssetUrls;
693 pendingAssetUrls = [];
694 for (const reply of replies) {
695 await Effect.runPromise(
696 Deferred.succeed(reply, { relativeUrl: "/api/assets/fake", expiresAt: 4_102_444_800_000 }),
697 );
698 }
699}
700
701/** Commands the app dispatched to the environment, oldest first. */
702export function dispatchedCommands(): ReadonlyArray<OrchestrationV2Command> {
703 return dispatched;
704}
705
706type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"];
707
708/** Answers one RPC method with `handler` until disposed. */
709export function answerRpc(method: string, handler: (input: never) => unknown): Disposable {
710 const previous = handlers[method];
711 handlers[method] = handler;
712 return {
713 [Symbol.dispose]: () => {
714 if (previous) handlers[method] = previous;
715 else delete handlers[method];
716 },
717 };
718}
719
720export async function emitTerminalMetadata(event: TerminalMetadataStreamEvent): Promise<void> {
721 if (terminalMetadataSubscriber === null) throw new Error("No terminal metadata subscription");
722 await Effect.runPromise(Queue.offer(terminalMetadataSubscriber, event));
723}
724
725/** Whether the app holds a live subscription to the thread, so events reach it. */
726export function isThreadSubscribed(threadId: ThreadId): boolean {
727 return threadSubscribers.has(threadId);
728}
729
730/** Delivers one domain event, such as a run or turn-item update, to the thread's subscription. */
731export async function emitThreadEvent(
732 threadId: ThreadId,
733 event: Pick<ThreadEvent, "type" | "payload">,
734): Promise<void> {
735 const queue = threadSubscribers.get(threadId);
736 if (!queue) throw new Error(`No live subscription for ${threadId}`);
737 sequence += 1;
738 await Effect.runPromise(
739 Queue.offer(queue, {
740 kind: "event",
741 sequence,
742 event: { ...event, id: EventId.make(`event-${sequence}`), threadId, occurredAt: AT },
743 } as OrchestrationV2ThreadStreamItem),
744 );
745}
746
747export function runningRun(threadId: ThreadId, id: string, ordinal: number, userMessageId: string) {
748 return {
749 ...run(threadId, RunId.make(id), ordinal, userMessageId),
750 status: "running" as const,
751 completedAt: null,
752 };
753}
754
755export { userItem };
756
757export async function emitVcsStatus(event: VcsStatusStreamEvent): Promise<void> {
758 if (vcsStatusSubscriber === null) throw new Error("No VCS status subscription");
759 await Effect.runPromise(Queue.offer(vcsStatusSubscriber, event));
760}