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