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