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

fakeEnvironment.ts

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