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