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