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