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