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