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 AuthStandardClientScopes,
6 EnvironmentId,
7 EventId,
8 ExecutionEnvironmentDescriptor,
9 MessageId,
10 ORCHESTRATION_PROTOCOL_VERSION,
11 ORCHESTRATION_V2_WS_METHODS,
12 ProjectId,
13 ProviderInstanceId,
14 RunId,
15 ServerConfig,
16 ThreadId,
17 TurnItemId,
18 WS_METHODS,
19 WsRpcGroup,
20 type VcsStatusStreamEvent,
21 type OrchestrationProjectShell,
22 type OrchestrationV2Command,
23 type OrchestrationV2ProjectedTurnItem,
24 type OrchestrationV2Run,
25 type OrchestrationV2ShellStreamItem,
26 type OrchestrationV2ThreadProjection,
27 type OrchestrationV2ThreadShell,
28 type OrchestrationV2ThreadStreamItem,
29 type OrchestrationV2TurnItem,
30 type TerminalMetadataStreamEvent,
31} from "@t3tools/contracts";
32import type {
33 ConnectionAttemptError,
34 ConnectionCatalogEntry,
35 EnvironmentConnectionLease,
36 RouteCheck,
37} from "@t3tools/client-runtime/connection";
38import type { WsRpcProtocolClient } from "@t3tools/client-runtime/rpc";
39import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
40import { APP_VERSION } from "~/branding";
41import * as DateTime from "effect/DateTime";
42import * as Effect from "effect/Effect";
43import * as Queue from "effect/Queue";
44import type * as Scope from "effect/Scope";
45import * as Schema from "effect/Schema";
46import * as Stream from "effect/Stream";
47import { RpcSchema } from "effect/rpc";
48
49export const ENVIRONMENT_ID = EnvironmentId.make("environment-render");
50export const PROJECT_ID = ProjectId.make("project-render");
51const CODEX = ProviderInstanceId.make("codex");
52const MODEL = { instanceId: CODEX, model: "gpt-5.4" };
53const AT = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z");
54
55const descriptor = {
56 environmentId: ENVIRONMENT_ID,
57 label: "Render scenarios",
58 platform: { os: "linux", arch: "x64" },
59 // A matching version, since a mismatch adds an update banner a typical user never sees.
60 serverVersion: APP_VERSION,
61 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
62 capabilities: { repositoryIdentity: true },
63};
64const auth = {
65 policy: "loopback-browser",
66 bootstrapMethods: ["one-time-token"],
67 sessionMethods: ["browser-session-cookie"],
68 sessionCookieName: "t3_session",
69};
70
71const serverConfig: ServerConfig = {
72 ...Schema.decodeUnknownSync(ServerConfig)({
73 environment: descriptor,
74 auth,
75 cwd: "/workspace/render",
76 keybindingsConfigPath: "/workspace/.t3/keybindings.json",
77 keybindings: [],
78 issues: [],
79 providers: [
80 {
81 instanceId: CODEX,
82 driver: "codex",
83 enabled: true,
84 installed: true,
85 version: "1.0.0",
86 status: "ready",
87 auth: { status: "authenticated" },
88 checkedAt: "2026-03-17T19:12:28.000Z",
89 models: [
90 { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null },
91 { slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
92 ],
93 },
94 ],
95 availableEditors: [],
96 observability: {
97 logsDirectoryPath: "/workspace/.t3/logs",
98 localTracingEnabled: false,
99 otlpTracesEnabled: false,
100 otlpMetricsEnabled: false,
101 },
102 settings: {},
103 threadSnapshotPagination: true,
104 threadResumeCompletionMarker: true,
105 shellResumeCompletionMarker: true,
106 }),
107 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
108};
109
110const project: OrchestrationProjectShell = {
111 id: PROJECT_ID,
112 title: "render",
113 workspaceRoot: "/workspace/render",
114 repositoryIdentity: null,
115 defaultModelSelection: null,
116 scripts: [],
117 createdAt: "2026-03-17T19:12:28.000Z",
118 updatedAt: "2026-03-17T19:12:28.000Z",
119};
120
121const base = (threadId: ThreadId, runId: RunId, id: string, ordinal: number) => ({
122 id: TurnItemId.make(id),
123 threadId,
124 runId,
125 nodeId: null,
126 providerThreadId: null,
127 providerTurnId: null,
128 nativeItemRef: null,
129 parentItemId: null,
130 ordinal,
131 status: "completed" as const,
132 title: null,
133 startedAt: AT,
134 completedAt: AT,
135 updatedAt: AT,
136});
137
138function userItem(threadId: ThreadId, runId: RunId, id: string, ordinal: number, text: string) {
139 return {
140 ...base(threadId, runId, id, ordinal),
141 type: "user_message",
142 messageId: MessageId.make(id),
143 text,
144 attachments: [],
145 inputIntent: "turn_start",
146 createdBy: "user",
147 creationSource: "web",
148 } satisfies OrchestrationV2TurnItem;
149}
150
151export function assistantItem(
152 threadId: ThreadId,
153 runId: RunId,
154 id: string,
155 ordinal: number,
156 text: string,
157 streaming = false,
158) {
159 return {
160 ...base(threadId, runId, id, ordinal),
161 type: "assistant_message",
162 messageId: MessageId.make(id),
163 text,
164 streaming,
165 ...(streaming ? { status: "running" as const, completedAt: null } : {}),
166 } satisfies OrchestrationV2TurnItem;
167}
168
169function run(threadId: ThreadId, id: RunId, ordinal: number, userMessageId: string) {
170 return {
171 id,
172 threadId,
173 ordinal,
174 providerInstanceId: CODEX,
175 modelSelection: MODEL,
176 providerThreadId: null,
177 userMessageId: MessageId.make(userMessageId),
178 rootNodeId: null,
179 activeAttemptId: null,
180 status: "completed",
181 requestedAt: AT,
182 startedAt: AT,
183 completedAt: AT,
184 checkpointId: null,
185 contextHandoffId: null,
186 } satisfies OrchestrationV2Run;
187}
188
189export interface FakeThread {
190 /** Makes this a side chat of that thread. */
191 readonly sideChatOf?: ThreadId;
192 readonly id: ThreadId;
193 readonly title: string;
194 readonly runs: ReadonlyArray<OrchestrationV2Run>;
195 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
196}
197
198/** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */
199export function threadWithHistory(name: string, turns: number): FakeThread {
200 const id = ThreadId.make(name);
201 const runs: OrchestrationV2Run[] = [];
202 const items: OrchestrationV2TurnItem[] = [];
203 for (let turn = 0; turn < turns; turn++) {
204 const runId = RunId.make(`${name}-run-${turn}`);
205 runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`));
206 items.push(
207 userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`),
208 assistantItem(
209 id,
210 runId,
211 `${name}-assistant-${turn}`,
212 turn * 2 + 1,
213 `Answer ${turn} for ${name}.\n\n- checked \`Sidebar.tsx\`\n- ran the tests\n\n` +
214 "The width is now `clamp(next, MIN_WIDTH, MAX_WIDTH)`, so the layout no longer jumps.",
215 ),
216 );
217 }
218 return { id, title: `Thread ${name}`, runs, items };
219}
220
221function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {
222 const latest = thread.runs.at(-1);
223 return {
224 id: thread.id,
225 projectId: PROJECT_ID,
226 title: thread.title,
227 providerInstanceId: CODEX,
228 modelSelection: MODEL,
229 runtimeMode: "full-access",
230 interactionMode: "default",
231 branch: "main",
232 worktreePath: null,
233 activeProviderThreadId: null,
234 lineage: {
235 rootThreadId: thread.sideChatOf ?? thread.id,
236 parentThreadId: thread.sideChatOf ?? null,
237 relationshipToParent: null,
238 ...(thread.sideChatOf ? { sideChat: true } : {}),
239 },
240 forkedFrom: null,
241 createdBy: "user",
242 creationSource: "web",
243 latestRunId: latest?.id ?? null,
244 activeRunId: null,
245 // Idle reads as waiting on the user, which shows a per-second duration in the sidebar.
246 status: latest ? "completed" : "idle",
247 pendingRuntimeRequest: null,
248 latestVisibleMessage: null,
249 latestUserMessageAt: AT,
250 hasActionableProposedPlan: false,
251 itemCount: thread.items.length,
252 visibleItemCount: thread.items.length,
253 createdAt: AT,
254 updatedAt: AT,
255 archivedAt: null,
256 settledOverride: null,
257 settledAt: null,
258 lastVisitedAt: AT,
259 deletedAt: null,
260 };
261}
262
263function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
264 const shell = shellOf(thread);
265 const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = thread.items.map(
266 (item, position) => ({
267 position,
268 visibility: "local",
269 sourceThreadId: thread.id,
270 sourceItemId: item.id,
271 item,
272 }),
273 );
274 return {
275 thread: {
276 id: shell.id,
277 projectId: shell.projectId,
278 title: shell.title,
279 providerInstanceId: shell.providerInstanceId,
280 modelSelection: shell.modelSelection,
281 runtimeMode: shell.runtimeMode,
282 interactionMode: shell.interactionMode,
283 branch: shell.branch,
284 worktreePath: shell.worktreePath,
285 activeProviderThreadId: null,
286 lineage: shell.lineage,
287 forkedFrom: null,
288 createdBy: "user",
289 creationSource: "web",
290 createdAt: AT,
291 updatedAt: AT,
292 archivedAt: null,
293 settledOverride: null,
294 settledAt: null,
295 lastVisitedAt: AT,
296 deletedAt: null,
297 },
298 runs: [...thread.runs],
299 attempts: [],
300 nodes: [],
301 subagents: [],
302 providerSessions: [],
303 providerThreads: [],
304 providerTurns: [],
305 runtimeRequests: [],
306 messages: [],
307 plans: [],
308 turnItems: [...thread.items],
309 checkpointScopes: [],
310 checkpoints: [],
311 contextHandoffs: [],
312 contextTransfers: [],
313 visibleTurnItems,
314 updatedAt: AT,
315 };
316}
317
318const json = (body: unknown, status = 200) =>
319 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
320
321// Keyed by thread id: a live thread subscription's queue, for pushing events to it.
322const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();
323let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;
324let threads: ReadonlyArray<FakeThread> = [];
325let dispatched: OrchestrationV2Command[] = [];
326let acceptCommands = false;
327let sequence = 1;
328let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null;
329
330const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>) => () => void) =>
331 Stream.unwrap(
332 Effect.gen(function* () {
333 const queue = yield* Queue.unbounded<A>();
334 yield* Queue.offerAll(queue, first);
335 if (register) {
336 const unregister = register(queue);
337 yield* Effect.addFinalizer(() => Effect.sync(unregister));
338 }
339 return Stream.fromQueue(queue);
340 }),
341 );
342
343const handlers: Record<string, (input: never) => unknown> = {
344 // Recorded, and accepted only when the scenario asks, since a pending command holds every
345 // later command on its thread. Accepted commands' events never arrive.
346 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
347 Effect.suspend(() => {
348 dispatched.push(command);
349 return acceptCommands ? Effect.succeed({ sequence: sequence + 1 }) : Effect.never;
350 }),
351 [WS_METHODS.subscribeTerminalMetadata]: () =>
352 subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => {
353 terminalMetadataSubscriber = queue;
354 return () => {
355 if (terminalMetadataSubscriber === queue) terminalMetadataSubscriber = null;
356 };
357 }),
358 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
359 subscribe<OrchestrationV2ShellStreamItem>([
360 {
361 kind: "snapshot",
362 snapshot: {
363 schemaVersion: 1,
364 snapshotSequence: sequence,
365 projects: [project],
366 threads: threads.map(shellOf),
367 archivedThreads: [],
368 },
369 },
370 { kind: "synchronized" },
371 ]),
372 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly threadId: ThreadId }) => {
373 const thread = threads.find((candidate) => candidate.id === input.threadId);
374 if (!thread) return Stream.never;
375 return subscribe<OrchestrationV2ThreadStreamItem>(
376 [
377 { kind: "snapshot", snapshotSequence: sequence, projection: projectionOf(thread) },
378 { kind: "synchronized" },
379 ],
380 (queue) => {
381 threadSubscribers.set(thread.id, queue);
382
383 // A replaced subscription closes after its successor registers.
384 return () => {
385 if (threadSubscribers.get(thread.id) === queue) threadSubscribers.delete(thread.id);
386 };
387 },
388 );
389 },
390 [WS_METHODS.subscribeVcsStatus]: () =>
391 subscribe<VcsStatusStreamEvent>([], (queue) => {
392 vcsStatusSubscriber = queue;
393 return () => {
394 if (vcsStatusSubscriber === queue) vcsStatusSubscriber = null;
395 };
396 }),
397 [WS_METHODS.subscribeServerConfig]: () =>
398 subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]),
399};
400
401// Unanswered calls stay pending, like a server that has not replied yet.
402const client = new Proxy(handlers, {
403 get: (target, method: string) =>
404 target[method] ??
405 (() => {
406 const rpc = WsRpcGroup.requests.get(method);
407 return rpc && RpcSchema.isStreamSchema(rpc.successSchema) ? Stream.never : Effect.never;
408 }),
409});
410
411const session: EnvironmentConnectionLease["session"] = {
412 client: client as unknown as WsRpcProtocolClient,
413 initialConfig: Effect.succeed(serverConfig),
414 subscribeServerConfig: () =>
415 subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]),
416 ready: Effect.void,
417 probe: Effect.void,
418 inboundFrames: Effect.succeed(0),
419 closed: Effect.never,
420};
421
422/** Stands in for client-runtime's ConnectionDriver: every connection opens the session above. */
423export const fakeDriver = {
424 connect: (
425 entry: ConnectionCatalogEntry,
426 ): Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope> =>
427 Effect.succeed({
428 prepared: {
429 environmentId: ENVIRONMENT_ID,
430 label: descriptor.label,
431 httpBaseUrl: window.location.origin,
432 socketUrl: window.location.origin.replace(/^http/, "ws"),
433 httpAuthorization: null,
434 target: entry.target,
435 },
436 session,
437 }),
438 preflight: () => Effect.succeed(true),
439 checkHost: () => Effect.succeed<RouteCheck>("unchecked"),
440};
441export type FakeDriver = typeof fakeDriver;
442
443const realFetch = globalThis.fetch;
444const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(
445 Schema.decodeUnknownSync(ExecutionEnvironmentDescriptor)(descriptor),
446);
447
448/** Serves the environment's HTTP API and these threads until disposed. */
449export function installFakeEnvironment(
450 fixtures: ReadonlyArray<FakeThread>,
451 options?: { readonly acceptCommands?: boolean },
452): Disposable {
453 threads = fixtures;
454 dispatched = [];
455 acceptCommands = options?.acceptCommands === true;
456 globalThis.fetch = async (input, init) => {
457 const url = new URL(input instanceof Request ? input.url : String(input), window.location.href);
458 if (url.origin !== window.location.origin) return realFetch(input, init);
459 if (url.pathname === "/.well-known/t3/environment") return json(encodedDescriptor);
460 if (url.pathname === "/api/auth/session") {
461 return json({
462 authenticated: true,
463 auth,
464 scopes: AuthStandardClientScopes,
465 sessionMethod: "browser-session-cookie",
466 expiresAt: "2099-01-01T00:00:00.000Z",
467 });
468 }
469 // Snapshot endpoints fall back to the socket, which serves the same fixtures.
470 if (/^\/(api|oauth|\.well-known)\//.test(url.pathname)) return json({}, 404);
471 return realFetch(input, init);
472 };
473 return {
474 [Symbol.dispose]: () => {
475 globalThis.fetch = realFetch;
476 threads = [];
477 dispatched = [];
478 acceptCommands = false;
479 },
480 };
481}
482
483/** Commands the app dispatched to the environment, oldest first. */
484export function dispatchedCommands(): ReadonlyArray<OrchestrationV2Command> {
485 return dispatched;
486}
487
488type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"];
489
490export async function emitTerminalMetadata(event: TerminalMetadataStreamEvent): Promise<void> {
491 if (terminalMetadataSubscriber === null) throw new Error("No terminal metadata subscription");
492 await Effect.runPromise(Queue.offer(terminalMetadataSubscriber, event));
493}
494
495/** Whether the app holds a live subscription to the thread, so events reach it. */
496export function isThreadSubscribed(threadId: ThreadId): boolean {
497 return threadSubscribers.has(threadId);
498}
499
500/** Delivers one domain event, such as a run or turn-item update, to the thread's subscription. */
501export async function emitThreadEvent(
502 threadId: ThreadId,
503 event: Pick<ThreadEvent, "type" | "payload">,
504): Promise<void> {
505 const queue = threadSubscribers.get(threadId);
506 if (!queue) throw new Error(`No live subscription for ${threadId}`);
507 sequence += 1;
508 await Effect.runPromise(
509 Queue.offer(queue, {
510 kind: "event",
511 sequence,
512 event: { ...event, id: EventId.make(`event-${sequence}`), threadId, occurredAt: AT },
513 } as OrchestrationV2ThreadStreamItem),
514 );
515}
516
517export function runningRun(threadId: ThreadId, id: string, ordinal: number, userMessageId: string) {
518 return {
519 ...run(threadId, RunId.make(id), ordinal, userMessageId),
520 status: "running" as const,
521 completedAt: null,
522 };
523}
524
525export { userItem };
526
527export async function emitVcsStatus(event: VcsStatusStreamEvent): Promise<void> {
528 if (vcsStatusSubscriber === null) throw new Error("No VCS status subscription");
529 await Effect.runPromise(Queue.offer(vcsStatusSubscriber, event));
530}