Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

fakeEnvironment.ts

772 lines25.6 KB

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