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

terminal.ts

476 lines17.0 KB

1import {
2 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
3 type EnvironmentId,
4 type TerminalAttachInput,
5 type TerminalCloseInput,
6 type TerminalOpenInput,
7 type TerminalResizeInput,
8 type TerminalSummary,
9 type TerminalWriteInput,
10 type ThreadId,
11 WS_METHODS,
12} from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Stream from "effect/Stream";
15import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
16​
17import {
18 type AtomCommand,
19 createAtomCommandScheduler,
20 createEnvironmentRpcCommand,
21 createEnvironmentSubscriptionAtomFamily,
22 isAtomCommandInterrupted,
23 runAtomCommand,
24} from "./runtime.ts";
25import type { EnvironmentRegistry } from "../connection/registry.ts";
26import { subscribe, subscribeDynamic, type EnvironmentRpcInput } from "../rpc/client.ts";
27import {
28 applyTerminalAttachStreamEvent,
29 applyTerminalMetadataStreamEvent,
30 EMPTY_TERMINAL_BUFFER_STATE,
31 nextTerminalAttachSeedState,
32 type TerminalBufferState,
33} from "./terminalSession.ts";
34import { terminalOutputText } from "./terminalOutput.ts";
35​
36interface TerminalMetadataFeed {
37 readonly terminals: ReadonlyArray<TerminalSummary>;
38 readonly snapshotId: string | symbol;
40​
41export function createTerminalEnvironmentAtoms<R, E>(
42 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
43) {
44 const lifecycleScheduler = createAtomCommandScheduler();
45 const resizeScheduler = createAtomCommandScheduler();
46 const terminalThreadKey = ({
47 environmentId,
48 input,
49 }: {
50 readonly environmentId: string;
51 readonly input: { readonly threadId: string; readonly terminalId?: string | undefined };
52 }) => JSON.stringify([environmentId, input.threadId]);
53 const terminalSessionKey = ({
54 environmentId,
55 input,
56 }: {
57 readonly environmentId: string;
58 readonly input: { readonly threadId: string; readonly terminalId?: string | undefined };
59 }) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]);
60 const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey };
61 const metadataFeed = createEnvironmentSubscriptionAtomFamily(runtime, {
62 label: "environment-data:terminal:metadata",
63 subscribe: (_input: null) =>
64 subscribe(WS_METHODS.subscribeTerminalMetadata, {}).pipe(
65 Stream.scan(
66 (): TerminalMetadataFeed => ({ terminals: [], snapshotId: Symbol() }),
67 (feed, event): TerminalMetadataFeed => ({
68 terminals: applyTerminalMetadataStreamEvent(feed.terminals, event),
69 snapshotId: event.type === "snapshot" ? (event.managerId ?? Symbol()) : feed.snapshotId,
70 }),
71 ),
72 // The scan seed is not an authoritative empty server snapshot.
73 Stream.drop(1),
74 ),
75 });
76 const terminalMetadataSummaries = Atom.family((feed: ReturnType<typeof metadataFeed>) =>
77 Atom.mapResult(feed, ({ terminals }) => terminals),
78 );
79 const atoms = {
80 observe: createEnvironmentSubscriptionAtomFamily(runtime, {
81 label: "environment-data:terminal:observe",
82 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalObserve>) =>
83 Stream.suspend(() =>
84 subscribe(WS_METHODS.terminalObserve, {
85 ...input,
86 supportsSnapshotSequenceState: true,
87 }).pipe(Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent)),
88 ),
89 }),
90 attach: createEnvironmentSubscriptionAtomFamily(runtime, {
91 label: "environment-data:terminal:attach",
92 // The server sizes the PTY to every attached viewer, so a closed view must detach now.
93 idleTtlMs: 0,
94 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) => {
95 // Retry an unanswered first attach unchanged so it can still open the shell.
96 let replied = false;
97 return subscribeDynamic(WS_METHODS.terminalAttach, () =>
98 Effect.sync(() => ({
99 ...input,
100 ...(replied ? { resume: true } : {}),
101 maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
102 supportsSnapshotSequenceState: true,
103 })),
104 ).pipe(
105 Stream.onFirst(() =>
106 Effect.sync(() => {
107 replied = true;
108 }),
109 ),
110 Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),
111 );
112 },
113 }),
114 metadataFeed,
115 metadata: (target: { readonly environmentId: EnvironmentId; readonly input: null }) =>
116 terminalMetadataSummaries(metadataFeed(target)),
117 open: createEnvironmentRpcCommand(runtime, {
118 label: "environment-data:terminal:open",
119 tag: WS_METHODS.terminalOpen,
120 scheduler: lifecycleScheduler,
121 concurrency: lifecycleConcurrency,
122 }),
123 write: createEnvironmentRpcCommand(runtime, {
124 label: "environment-data:terminal:write",
125 tag: WS_METHODS.terminalWrite,
126 }),
127 resize: createEnvironmentRpcCommand(runtime, {
128 label: "environment-data:terminal:resize",
129 tag: WS_METHODS.terminalResize,
130 scheduler: resizeScheduler,
131 concurrency: { mode: "latest", key: terminalSessionKey },
132 }),
133 clear: createEnvironmentRpcCommand(runtime, {
134 label: "environment-data:terminal:clear",
135 tag: WS_METHODS.terminalClear,
136 scheduler: lifecycleScheduler,
137 concurrency: lifecycleConcurrency,
138 }),
139 close: createEnvironmentRpcCommand(runtime, {
140 label: "environment-data:terminal:close",
141 tag: WS_METHODS.terminalClose,
142 scheduler: lifecycleScheduler,
143 concurrency: lifecycleConcurrency,
144 }),
145 };
146 return {
147 ...atoms,
148 createSession: (options: TerminalSessionOptions) => createTerminalSession(atoms, options),
149 };
151​
152export interface TerminalLifecycleState {
153 readonly wasRunning: boolean;
154 /** The user has seen this terminal without operate permission. */
155 readonly observed: boolean;
156 readonly reopened: boolean;
158​
159export const INITIAL_TERMINAL_LIFECYCLE: TerminalLifecycleState = {
160 wasRunning: false,
161 observed: false,
162 reopened: false,
163};
164​
165export type TerminalLifecycleEvent =
166 /** A viewer without operate permission is following this terminal. */
167 | { readonly type: "observed" }
168 | { readonly type: "detached"; readonly canOperate: boolean }
169 | {
170 readonly type: "status";
171 readonly status: TerminalBufferState["status"];
172 readonly version: number;
173 }
174 | { readonly type: "reopen-failed" };
175​
176export type TerminalLifecycleCommand = "exit" | "reopen" | null;
177​
178export function transitionTerminalLifecycle(
179 state: TerminalLifecycleState,
180 event: TerminalLifecycleEvent,
181): { readonly state: TerminalLifecycleState; readonly command: TerminalLifecycleCommand } {
182 switch (event.type) {
183 case "observed":
184 return { state: { ...state, observed: true }, command: null };
185 case "detached":
186 return {
187 state: {
188 ...state,
189 // Losing operate while the shell runs leaves the viewer reading its history.
190 observed: state.observed || (!event.canOperate && state.wasRunning),
191 wasRunning: false,
192 },
193 command: null,
194 };
195 case "reopen-failed":
196 return { state: { ...state, reopened: false }, command: null };
197 case "status": {
198 if (event.version === 0) return { state, command: null };
199 if (event.status === "running" || event.status === "starting") {
200 return { state: { ...state, wasRunning: true, reopened: false }, command: null };
201 }
202 if (event.status !== "closed" && event.status !== "exited") return { state, command: null };
203 if (state.wasRunning) {
204 return { state: { ...state, wasRunning: false, reopened: true }, command: "exit" };
205 }
206 // An explicit visit can reopen a cached ended session. Granting a viewer
207 // operate permission must leave the history they were reading intact.
208 if (state.observed || state.reopened) return { state, command: null };
209 return { state: { ...state, reopened: true }, command: "reopen" };
210 }
211 }
213​
214export interface TerminalGridSize {
215 readonly cols: number;
216 readonly rows: number;
218​
219export type TerminalSessionMode =
220 | { readonly kind: "observing" }
221 | { readonly kind: "attached"; readonly input: TerminalAttachInput };
222​
223type EnvironmentCommand<Input> = AtomCommand<
224 { readonly environmentId: EnvironmentId; readonly input: Input },
225 unknown,
226 unknown
227>;
228​
229export interface TerminalSessionAtoms {
230 readonly attach: (target: {
231 readonly environmentId: EnvironmentId;
232 readonly input: TerminalAttachInput;
233 }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;
234 readonly observe: (target: {
235 readonly environmentId: EnvironmentId;
236 readonly input: { readonly threadId: ThreadId; readonly terminalId: string };
237 }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;
238 readonly open: EnvironmentCommand<TerminalOpenInput>;
239 readonly resize: EnvironmentCommand<TerminalResizeInput>;
240 readonly write: EnvironmentCommand<TerminalWriteInput>;
241 readonly close: EnvironmentCommand<TerminalCloseInput>;
243​
244export interface TerminalSessionOptions {
245 readonly target: {
246 readonly environmentId: EnvironmentId;
247 readonly threadId: ThreadId;
248 readonly terminalId: string;
249 };
250 readonly gridSize: TerminalGridSize;
251 /** Written once, after the first attachment snapshot lands and the shell has the measured grid. */
252 readonly initialInput?: string | undefined;
253 /** Read right before every command, so revoking operate stops them at once. */
254 readonly canOperate: () => boolean;
255 /** The shell ended while attached; the store has already closed it. */
256 readonly onExit: () => void;
257 /** Fires when the shell starts or stops accepting input, and on every restart. */
258 readonly onLiveChange?: (live: boolean) => void;
259 readonly debugLog?: (message: string, data: Record<string, unknown>) => void;
261​
262export interface TerminalSession {
263 /**
264 * Mount while the session follows a terminal: attached to operate it, or
265 * observing it read-only. `null` follows nothing. A session keeps the first
266 * attach input it is given; a different input needs a new session.
267 */
268 readonly driver: (mode: TerminalSessionMode | null) => Atom.Atom<void>;
269 /** The surface measured a new grid; the shell is resized while it runs. */
270 readonly reportGridSize: (size: TerminalGridSize) => void;
272​
273/**
274 * Owns one shown terminal's lifecycle: it reopens an ended shell on an explicit
275 * visit, closes and reports a shell that exits while attached, replays the
276 * measured grid whenever the server starts a new output generation, and writes
277 * the launch's initial input once that grid has reached the shell.
278 */
279export function createTerminalSession(
280 atoms: TerminalSessionAtoms,
281 options: TerminalSessionOptions,
282): TerminalSession {
283 const { environmentId, threadId, terminalId } = options.target;
284 let lifecycle = INITIAL_TERMINAL_LIFECYCLE;
285 let gridSize = options.gridSize;
286 // The seeded grid is a cache or default guess; launch input waits for the surface's own measurement.
287 let gridMeasured = false;
288 let generation: number | null = null;
289 let liveLifecycleVersion: number | null = null;
290 let initialInputPending = Boolean(options.initialInput);
291 let lastStatus: TerminalBufferState["status"] | null = null;
292 let loggedFirstOutput = false;
293 let commandRegistry: AtomRegistry.AtomRegistry | null = null;
294 // Only a successful resize of the current measured grid may release initial input.
295 let shellResized: ReturnType<typeof runAtomCommand> | null = null;
296​
297 const sendResize = (retry = false) => {
298 const registry = commandRegistry;
299 if (generation === null || registry === null || !options.canOperate()) return;
300 const resized = runAtomCommand(registry, atoms.resize, {
301 environmentId,
302 input: { threadId, terminalId, cols: gridSize.cols, rows: gridSize.rows },
303 });
304 shellResized = resized;
305 void resized.then((result) => {
306 // Only a new grid or generation sends again, so retry a failure once, unless a newer
307 // resize already replaced this one.
308 if (
309 !retry &&
310 resized === shellResized &&
311 result._tag === "Failure" &&
312 !isAtomCommandInterrupted(result)
313 ) {
314 sendResize(true);
315 return;
316 }
317 const data = options.initialInput;
318 if (
319 result._tag !== "Success" ||
320 resized !== shellResized ||
321 !gridMeasured ||
322 generation === null ||
323 !initialInputPending ||
324 !data ||
325 !options.canOperate()
326 )
327 return;
328 initialInputPending = false;
329 void runAtomCommand(registry, atoms.write, {
330 environmentId,
331 input: { threadId, terminalId, data },
332 });
333 });
334 };
335​
336 const setLive = (next: number | null) => {
337 if (next === liveLifecycleVersion) return;
338 liveLifecycleVersion = next;
339 options.onLiveChange?.(next !== null);
340 };
341​
342 const apply = (
343 event: TerminalLifecycleEvent,
344 registry: AtomRegistry.AtomRegistry,
345 input: TerminalAttachInput,
346 ) => {
347 const step = transitionTerminalLifecycle(lifecycle, event);
348 lifecycle = step.state;
349 if (step.command === "exit") {
350 if (!options.canOperate()) return;
351 void runAtomCommand(registry, atoms.close, {
352 environmentId,
353 input: { threadId, terminalId },
354 });
355 options.onExit();
356 return;
357 }
358 if (step.command !== "reopen") return;
359 const reopen = async () => {
360 if (input.cwd === undefined || !options.canOperate()) return false;
361 const result = await runAtomCommand(registry, atoms.open, {
362 environmentId,
363 input: {
364 threadId,
365 terminalId,
366 cwd: input.cwd,
367 worktreePath: input.worktreePath,
368 cols: input.cols,
369 rows: input.rows,
370 ...(input.env ? { env: input.env } : {}),
371 },
372 });
373 return result._tag === "Success";
374 };
375 void reopen().then((succeeded) => {
376 if (!succeeded)
377 lifecycle = transitionTerminalLifecycle(lifecycle, { type: "reopen-failed" }).state;
378 });
379 };
380​
381 const onAttachment = (
382 registry: AtomRegistry.AtomRegistry,
383 input: TerminalAttachInput,
384 result: AsyncResult.AsyncResult<TerminalBufferState, unknown>,
385 ) => {
386 commandRegistry = registry;
387 const buffer = AsyncResult.getOrElse(result, () => EMPTY_TERMINAL_BUFFER_STATE);
388 const status = result._tag === "Failure" ? "error" : buffer.status;
389 if (status !== lastStatus) {
390 lastStatus = status;
391 options.debugLog?.("session:status", {
392 terminalId,
393 status,
394 error: buffer.error,
395 version: buffer.version,
396 });
397 }
398 if (!loggedFirstOutput && options.debugLog) {
399 const text = terminalOutputText(buffer.output);
400 if (text.length > 0) {
401 loggedFirstOutput = true;
402 options.debugLog("session:first-nonempty-buffer", {
403 terminalId,
404 length: text.length,
405 preview: text.slice(0, 160),
406 });
407 }
408 }
409​
410 setLive(status === "running" || status === "starting" ? buffer.lifecycleVersion : null);
411​
412 // Resize before the initial input so a launched command starts at the measured grid.
413 const nextGeneration =
414 buffer.version > 0 && status === "running" ? buffer.output.generation : null;
415 if (nextGeneration !== generation) {
416 generation = nextGeneration;
417 shellResized = null;
418 sendResize();
419 }
420​
421 apply({ type: "status", status, version: buffer.version }, registry, input);
422 };
423​
424 const label = `terminal-session:${environmentId}:${threadId}:${terminalId}`;
425 const idle = Atom.make<void>(undefined);
426 // Viewing read-only counts as observed before the first snapshot lands, so a
427 // grant that arrives early still leaves the ended shell's history alone.
428 const observing = Atom.make((get) => {
429 // `subscribe`, not `get`: a rebuild would resubscribe on every output chunk.
430 get.subscribe(
431 atoms.observe({ environmentId, input: { threadId, terminalId } }),
432 () => {
433 if (options.canOperate()) return;
434 lifecycle = transitionTerminalLifecycle(lifecycle, { type: "observed" }).state;
435 },
436 { immediate: true },
437 );
438 }).pipe(Atom.withLabel(`${label}:observing`));
439 const makeAttached = (input: TerminalAttachInput) =>
440 Atom.make((get) => {
441 const registry = get.registry;
442 get.addFinalizer(() => {
443 generation = null;
444 shellResized = null;
445 lastStatus = null;
446 setLive(null);
447 lifecycle = transitionTerminalLifecycle(lifecycle, {
448 type: "detached",
449 canOperate: options.canOperate(),
450 }).state;
451 });
452 get.subscribe(
453 atoms.attach({ environmentId, input }),
454 (result) => onAttachment(registry, input, result),
455 { immediate: true },
456 );
457 }).pipe(Atom.withLabel(`${label}:attached`));
458 let attached: Atom.Atom<void> | null = null;
459​
460 return {
461 driver: (mode) => {
462 if (mode === null) return idle;
463 if (mode.kind === "observing") return observing;
464 attached ??= makeAttached(mode.input);
465 return attached;
466 },
467 reportGridSize: (size) => {
468 if (gridMeasured && size.cols === gridSize.cols && size.rows === gridSize.rows) return;
469 gridMeasured = true;
470 gridSize = size;
471 sendResize();
472 },
473 };
475​
476export * from "./terminalSession.ts";