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