Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

fakeEnvironment.ts

547 lines17.9 KB

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