dsh-bash-terminal-ts 0.7.2-compat.2 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.de.md +3 -2
- package/README.en.md +102 -3
- package/README.es.md +3 -2
- package/README.fr.md +3 -2
- package/README.it.md +3 -2
- package/README.md +198 -4
- package/README.ru.md +3 -2
- package/cordis.patch.yml +66 -0
- package/dist/client.core.js +7888 -79
- package/dist/client.js +7888 -79
- package/dsh.plugin.json +22 -22
- package/lib/browser-i18n.d.ts +4 -0
- package/lib/browser-i18n.js +23 -0
- package/lib/client.js +7888 -79
- package/lib/dsh-types.d.ts +10 -0
- package/lib/dsh.d.ts +2 -0
- package/lib/index.d.ts +43 -0
- package/lib/index.js +176 -91
- package/lib/locales.d.ts +4 -0
- package/lib/locales.js +422 -0
- package/lib/settings-surface.d.ts +20 -0
- package/lib/settings-surface.js +49 -0
- package/lib/shell-id.d.ts +2 -0
- package/lib/shell-id.js +9 -0
- package/lib/shells.d.ts +114 -0
- package/lib/shells.js +187 -0
- package/lib/terminal.d.ts +30 -1
- package/lib/terminal.js +18 -5
- package/lib/webterminals/catalog.d.ts +36 -0
- package/lib/webterminals/catalog.js +93 -0
- package/lib/webterminals/host.d.ts +67 -0
- package/lib/webterminals/host.js +278 -0
- package/lib/webterminals/mount.d.ts +46 -0
- package/lib/webterminals/mount.js +171 -0
- package/lib/webterminals/protocol.d.ts +94 -0
- package/lib/webterminals/protocol.js +9 -0
- package/lib/webterminals/pty.d.ts +42 -0
- package/lib/webterminals/pty.js +64 -0
- package/lib/webterminals/registry.d.ts +139 -0
- package/lib/webterminals/registry.js +353 -0
- package/lib/webterminals/ws.d.ts +54 -0
- package/lib/webterminals/ws.js +140 -0
- package/locale/de.json +4 -0
- package/locale/en.json +4 -0
- package/locale/es.json +4 -0
- package/locale/fr.json +4 -0
- package/locale/it.json +4 -0
- package/locale/ja.json +4 -0
- package/locale/ko.json +4 -0
- package/locale/ru.json +4 -0
- package/locale/zh.json +4 -0
- package/package.json +131 -121
- package/scripts/build-browser-tests.mjs +36 -0
- package/scripts/build-client.mjs +10 -0
- package/scripts/check-artifacts.mjs +93 -0
- package/scripts/link-shells.mjs +75 -0
- package/src/browser-i18n.ts +27 -0
- package/src/client.tsx +539 -134
- package/src/dsh-types.ts +6 -0
- package/src/dsh.ts +2 -0
- package/src/index.ts +146 -35
- package/src/locales.ts +434 -0
- package/src/settings-surface.ts +59 -0
- package/src/shell-id.ts +11 -0
- package/src/shells.ts +250 -0
- package/src/terminal.ts +34 -5
- package/src/webterminals/browser/api.ts +212 -0
- package/src/webterminals/browser/bridge.ts +188 -0
- package/src/webterminals/browser/css.d.ts +16 -0
- package/src/webterminals/browser/face.ts +151 -0
- package/src/webterminals/browser/shell-picker.tsx +98 -0
- package/src/webterminals/browser/store.ts +40 -0
- package/src/webterminals/browser/tab.tsx +136 -0
- package/src/webterminals/browser/testkit.ts +21 -0
- package/src/webterminals/browser/url.ts +70 -0
- package/src/webterminals/browser/view.ts +381 -0
- package/src/webterminals/browser/xterm.ts +269 -0
- package/src/webterminals/catalog.ts +114 -0
- package/src/webterminals/host.ts +361 -0
- package/src/webterminals/mount.ts +227 -0
- package/src/webterminals/protocol.ts +78 -0
- package/src/webterminals/pty.ts +90 -0
- package/src/webterminals/registry.ts +447 -0
- package/src/webterminals/ws.ts +166 -0
- package/tsconfig.client.json +9 -1
- package/tsconfig.json +1 -1
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// The browser terminal's PTY backend: which allocator to use, and one adapter
|
|
2
|
+
// that makes both look the same to the registry.
|
|
3
|
+
//
|
|
4
|
+
// Two backends, chosen the way the model tool already chooses them:
|
|
5
|
+
//
|
|
6
|
+
// - **node-pty** on win32. The official seam's process inspector is POSIX-only
|
|
7
|
+
// (`createProcessInspector` throws on win32), which is why the tool path goes
|
|
8
|
+
// direct here too. This is also the backend that makes the plugin work on a
|
|
9
|
+
// deployment with no terminal controller at all - the whole point of the shim.
|
|
10
|
+
// - **`ctx.subprocess.spawnTerminal`** elsewhere, so the shell runs under the
|
|
11
|
+
// host's own execution provider (remote/ssh deployments included).
|
|
12
|
+
//
|
|
13
|
+
// `UI_PTY_STYLE` (not the tool's `TOOL_PTY_STYLE`) is what keeps colours and
|
|
14
|
+
// cursor control alive; `uiEnv` (not `buildEnv`) is what keeps the user's own
|
|
15
|
+
// environment in the child. Both live in the shared layer on purpose - see
|
|
16
|
+
// findings F2/F3/F4.
|
|
17
|
+
|
|
18
|
+
import { spawnPtyHandle, UI_PTY_STYLE } from "../terminal.js";
|
|
19
|
+
import type { TerminalSpawnSpec } from "../dsh-types.js";
|
|
20
|
+
import type { UiPtyHandle, UiSpawnSpec } from "./registry.js";
|
|
21
|
+
|
|
22
|
+
/** Which allocator a terminal would be created with. */
|
|
23
|
+
export type PtyBackend = "node-pty" | "seam";
|
|
24
|
+
|
|
25
|
+
/** The host seam, narrowed to the one call this module makes. */
|
|
26
|
+
export interface SeamLike {
|
|
27
|
+
spawnTerminal?(spec: TerminalSpawnSpec & { terminalType?: string }): Promise<{
|
|
28
|
+
pid: number;
|
|
29
|
+
output: NodeJS.ReadableStream;
|
|
30
|
+
done: Promise<{ exitCode: number | null; signal?: string | null }>;
|
|
31
|
+
write(data: string): void | Promise<void>;
|
|
32
|
+
resize?(cols: number, rows: number): void | Promise<void>;
|
|
33
|
+
signalForeground?(signal: string): void | Promise<unknown>;
|
|
34
|
+
terminate(): void | Promise<void>;
|
|
35
|
+
}>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What the caller must report about the deployment. */
|
|
39
|
+
export interface SpawnerDeps {
|
|
40
|
+
platform: NodeJS.Platform;
|
|
41
|
+
/** The host seam, or undefined/absent when this build has none. */
|
|
42
|
+
seam: SeamLike | undefined;
|
|
43
|
+
/** TERM->SIGKILL grace handed to the seam on allocation. */
|
|
44
|
+
seamGraceMs?: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Which backend this deployment gets. `undefined` means neither is reachable and
|
|
49
|
+
* the browser must be told `no-pty-backend` rather than shown a dead terminal.
|
|
50
|
+
*/
|
|
51
|
+
export function detectBackend(deps: SpawnerDeps): PtyBackend | undefined {
|
|
52
|
+
if (deps.platform === "win32") return "node-pty";
|
|
53
|
+
return typeof deps.seam?.spawnTerminal === "function" ? "seam" : undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Build the allocator the registry calls.
|
|
58
|
+
* @throws Error when `detectBackend` found nothing (callers must check first).
|
|
59
|
+
*/
|
|
60
|
+
export function createUiSpawner(deps: SpawnerDeps): { backend: PtyBackend; spawn(spec: UiSpawnSpec): Promise<UiPtyHandle> } {
|
|
61
|
+
const backend = detectBackend(deps);
|
|
62
|
+
if (backend === undefined) throw new Error("terminal-bridge: no PTY backend on this host");
|
|
63
|
+
const spawn = async (spec: UiSpawnSpec): Promise<UiPtyHandle> => {
|
|
64
|
+
if (backend === "node-pty") {
|
|
65
|
+
try {
|
|
66
|
+
return await spawnPtyHandle({ argv: [...spec.argv], cwd: spec.cwd, env: spec.env, rows: spec.rows, cols: spec.cols }, UI_PTY_STYLE);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
// The one failure mode a user can act on: node-pty ships as a native
|
|
69
|
+
// module, and pnpm silently skips its build script unless approved.
|
|
70
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
71
|
+
throw new Error(`${message} - if node-pty failed to build, run \`pnpm approve-builds\` in the profile directory`, { cause: error });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const seam = deps.seam?.spawnTerminal;
|
|
75
|
+
if (typeof seam !== "function") throw new Error("terminal-bridge: ctx.subprocess.spawnTerminal disappeared after detection");
|
|
76
|
+
// `terminalType` is honoured on newer host lines and ignored on the build
|
|
77
|
+
// that hardcodes a dumb emulator; `uiEnv`'s `TERM` is what actually reaches
|
|
78
|
+
// the shell on that line, so the two together cover both.
|
|
79
|
+
return await seam.call(deps.seam, {
|
|
80
|
+
argv: [...spec.argv],
|
|
81
|
+
cwd: spec.cwd,
|
|
82
|
+
env: spec.env,
|
|
83
|
+
rows: spec.rows,
|
|
84
|
+
cols: spec.cols,
|
|
85
|
+
terminalType: UI_PTY_STYLE.name,
|
|
86
|
+
graceMs: deps.seamGraceMs ?? 5000,
|
|
87
|
+
});
|
|
88
|
+
};
|
|
89
|
+
return { backend, spawn };
|
|
90
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
// The browser terminal's process pool: allocation, the replay ring, per-terminal
|
|
2
|
+
// attachment fan-out, the idle reaper and the capacity gates.
|
|
3
|
+
//
|
|
4
|
+
// Why this exists separately from the model-tool registry in `src/terminal.ts`:
|
|
5
|
+
// that one buffers output for an agent to read later, names the PTY `dumb`, and
|
|
6
|
+
// drops a session as soon as it goes idle. A browser terminal needs the opposite:
|
|
7
|
+
// a bounded *screen* it can hand a re-attaching emulator, a shell that survives a
|
|
8
|
+
// tab switch or a page reload, and a quota the user can see.
|
|
9
|
+
//
|
|
10
|
+
// The lifecycle rules deliberately mirror the host terminal controller, because
|
|
11
|
+
// that is what the sidebar view documents and what users learned from the
|
|
12
|
+
// built-in terminal:
|
|
13
|
+
//
|
|
14
|
+
// - closing the TAB is the only thing that ends a process;
|
|
15
|
+
// - an EXITED terminal still holds its session quota until closed, and its screen
|
|
16
|
+
// stays replayable;
|
|
17
|
+
// - a DETACHED terminal keeps running for `idleGraceMs` so a reload re-adopts it;
|
|
18
|
+
// - output is buffered into a bounded ring so a late attachment gets a screen.
|
|
19
|
+
//
|
|
20
|
+
// Nothing here reaches the model: no tool is registered, and the only writers are
|
|
21
|
+
// sockets from a loopback peer.
|
|
22
|
+
|
|
23
|
+
import { randomUUID } from "node:crypto";
|
|
24
|
+
import { StringDecoder } from "node:string_decoder";
|
|
25
|
+
import type { ShellId } from "../shell-id.js";
|
|
26
|
+
import type { UiEnvironment, UiShellSpec, UiTerminalInfo } from "./protocol.js";
|
|
27
|
+
|
|
28
|
+
/** The handle shape this pool drives (the seam's handle plus an optional resize). */
|
|
29
|
+
export interface UiPtyHandle {
|
|
30
|
+
readonly pid: number;
|
|
31
|
+
readonly output: NodeJS.ReadableStream;
|
|
32
|
+
readonly done: Promise<{ exitCode: number | null; signal?: string | null }>;
|
|
33
|
+
write(data: string): void | Promise<void>;
|
|
34
|
+
/** Absent on host builds whose seam cannot resize; `resize()` reports false. */
|
|
35
|
+
resize?(cols: number, rows: number): void | Promise<void>;
|
|
36
|
+
signalForeground?(signal: string): void | Promise<unknown>;
|
|
37
|
+
terminate(): void | Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One allocation request, already validated by the caller. */
|
|
41
|
+
export interface UiSpawnSpec {
|
|
42
|
+
readonly argv: readonly string[];
|
|
43
|
+
readonly cwd: string;
|
|
44
|
+
readonly env: Record<string, string | undefined>;
|
|
45
|
+
readonly cols: number;
|
|
46
|
+
readonly rows: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One attached consumer (a socket). */
|
|
50
|
+
export interface UiSink {
|
|
51
|
+
onData(data: string): void;
|
|
52
|
+
onExit(info: UiTerminalInfo): void;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The per-frame input cap; a bigger frame is refused, not truncated. */
|
|
56
|
+
export const MAX_INPUT_BYTES = 64 * 1024;
|
|
57
|
+
export const MAX_COLS = 500;
|
|
58
|
+
export const MAX_ROWS = 200;
|
|
59
|
+
|
|
60
|
+
/** Output coalescing window: keeps a chatty shell from one socket frame per byte. */
|
|
61
|
+
const FLUSH_MS = 16;
|
|
62
|
+
/** Output coalescing byte budget (a big burst flushes early). */
|
|
63
|
+
const FLUSH_BYTES = 32 * 1024;
|
|
64
|
+
|
|
65
|
+
interface Managed {
|
|
66
|
+
readonly id: string;
|
|
67
|
+
readonly sessionId: string;
|
|
68
|
+
readonly shellId: ShellId | "cmd";
|
|
69
|
+
readonly shellSpec: UiShellSpec;
|
|
70
|
+
readonly title: string;
|
|
71
|
+
readonly cwd: string;
|
|
72
|
+
readonly createdAt: number;
|
|
73
|
+
cols: number;
|
|
74
|
+
rows: number;
|
|
75
|
+
state: "running" | "exited" | "failed";
|
|
76
|
+
exitCode: number | null;
|
|
77
|
+
error?: string;
|
|
78
|
+
handle: UiPtyHandle;
|
|
79
|
+
/** The replay ring, oldest first; every entry is one already-decoded chunk. */
|
|
80
|
+
ring: string[];
|
|
81
|
+
ringBytes: number;
|
|
82
|
+
readonly sinks: Set<UiSink>;
|
|
83
|
+
pending: string;
|
|
84
|
+
flushTimer?: ReturnType<typeof setTimeout>;
|
|
85
|
+
idleTimer?: ReturnType<typeof setTimeout>;
|
|
86
|
+
announced: boolean;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The pool's options. */
|
|
90
|
+
export interface UiRegistryOptions {
|
|
91
|
+
spawn(spec: UiSpawnSpec): Promise<UiPtyHandle>;
|
|
92
|
+
maxPerSession: number;
|
|
93
|
+
maxTotal: number;
|
|
94
|
+
/** Detached-shell grace before the reaper terminates it; 0 = reap at once. */
|
|
95
|
+
idleGraceMs: number;
|
|
96
|
+
/** Replayed-screen budget per terminal, in bytes. */
|
|
97
|
+
scrollback: number;
|
|
98
|
+
now?(): number;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A refusal the browser can name (the shim maps these onto its view state). */
|
|
102
|
+
export class UiTerminalError extends Error {
|
|
103
|
+
constructor(
|
|
104
|
+
readonly code:
|
|
105
|
+
| "terminalLimit"
|
|
106
|
+
| "missingTerminal"
|
|
107
|
+
| "inputFull"
|
|
108
|
+
| "bad-request"
|
|
109
|
+
| "shellNotActivated"
|
|
110
|
+
| "spawn-failed"
|
|
111
|
+
| "disabled",
|
|
112
|
+
message: string,
|
|
113
|
+
readonly status = 400,
|
|
114
|
+
) {
|
|
115
|
+
super(message);
|
|
116
|
+
this.name = "UiTerminalError";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The public info projection of one managed terminal. */
|
|
121
|
+
export function infoOf(managed: Managed): UiTerminalInfo {
|
|
122
|
+
const info: UiTerminalInfo = {
|
|
123
|
+
id: managed.id,
|
|
124
|
+
title: managed.title,
|
|
125
|
+
shellId: managed.shellId,
|
|
126
|
+
shell: managed.shellSpec,
|
|
127
|
+
cwd: managed.cwd,
|
|
128
|
+
cols: managed.cols,
|
|
129
|
+
rows: managed.rows,
|
|
130
|
+
state: managed.state,
|
|
131
|
+
exitCode: managed.exitCode,
|
|
132
|
+
};
|
|
133
|
+
return managed.error === undefined ? info : ({ ...info, error: managed.error } as UiTerminalInfo);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A sane 1-based size clamp. */
|
|
137
|
+
function clampSize(value: number, max: number): number {
|
|
138
|
+
if (!Number.isFinite(value)) return 80;
|
|
139
|
+
return Math.max(1, Math.min(max, Math.floor(value)));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The UI terminal table. One instance per plugin activation; `dispose()` ends
|
|
144
|
+
* every process it owns, so disabling the plugin cannot leak shells.
|
|
145
|
+
*/
|
|
146
|
+
export class UiTerminalRegistry {
|
|
147
|
+
private readonly byId = new Map<string, Managed>();
|
|
148
|
+
private readonly opts: {
|
|
149
|
+
spawn(spec: UiSpawnSpec): Promise<UiPtyHandle>;
|
|
150
|
+
maxPerSession: number;
|
|
151
|
+
maxTotal: number;
|
|
152
|
+
idleGraceMs: number;
|
|
153
|
+
scrollback: number;
|
|
154
|
+
now(): number;
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
constructor(options: UiRegistryOptions) {
|
|
158
|
+
this.opts = {
|
|
159
|
+
spawn: options.spawn,
|
|
160
|
+
maxPerSession: options.maxPerSession,
|
|
161
|
+
maxTotal: options.maxTotal,
|
|
162
|
+
idleGraceMs: options.idleGraceMs,
|
|
163
|
+
scrollback: options.scrollback,
|
|
164
|
+
now: options.now ?? ((): number => Date.now()),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The limits one session's terminals launch into. */
|
|
169
|
+
environment(cwd: string): UiEnvironment {
|
|
170
|
+
return { cwd, maxInputBytes: MAX_INPUT_BYTES, maxCols: MAX_COLS, maxRows: MAX_ROWS, scrollback: this.opts.scrollback };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** How many terminals this registry still holds (an exited one still counts). */
|
|
174
|
+
count(sessionId?: string): number {
|
|
175
|
+
if (sessionId === undefined) return this.byId.size;
|
|
176
|
+
let total = 0;
|
|
177
|
+
for (const managed of this.byId.values()) {
|
|
178
|
+
if (managed.sessionId === sessionId) total += 1;
|
|
179
|
+
}
|
|
180
|
+
return total;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The infos of one session, oldest first. */
|
|
184
|
+
list(sessionId: string): UiTerminalInfo[] {
|
|
185
|
+
return Array.from(this.byId.values())
|
|
186
|
+
.filter((managed) => managed.sessionId === sessionId)
|
|
187
|
+
.sort((a, b) => a.createdAt - b.createdAt)
|
|
188
|
+
.map(infoOf);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Look one terminal up. */
|
|
192
|
+
get(id: string): UiTerminalInfo | undefined {
|
|
193
|
+
const managed = this.byId.get(id);
|
|
194
|
+
return managed === undefined ? undefined : infoOf(managed);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** The buffered screen a late attachment replays ('' before any output). */
|
|
198
|
+
screen(id: string): string {
|
|
199
|
+
const managed = this.byId.get(id);
|
|
200
|
+
return managed === undefined ? "" : managed.ring.join("");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Allocate a shell, or adopt an existing terminal by identity.
|
|
205
|
+
* @throws UiTerminalError `terminalLimit` when a quota is full,
|
|
206
|
+
* `missingTerminal` when an adoption target is gone, `spawn-failed` when the
|
|
207
|
+
* backend refused.
|
|
208
|
+
*/
|
|
209
|
+
async open(input: {
|
|
210
|
+
sessionId: string;
|
|
211
|
+
cwd: string;
|
|
212
|
+
shellId: ShellId | "cmd";
|
|
213
|
+
shellSpec: UiShellSpec;
|
|
214
|
+
title: string;
|
|
215
|
+
argv: readonly string[];
|
|
216
|
+
env: Record<string, string | undefined>;
|
|
217
|
+
cols: number;
|
|
218
|
+
rows: number;
|
|
219
|
+
terminalId?: string;
|
|
220
|
+
}): Promise<UiTerminalInfo> {
|
|
221
|
+
if (input.terminalId !== undefined && input.terminalId !== "") {
|
|
222
|
+
const found = this.byId.get(input.terminalId);
|
|
223
|
+
if (found === undefined || found.sessionId !== input.sessionId) {
|
|
224
|
+
throw new UiTerminalError("missingTerminal", "no such terminal in this session (it was closed, or the host restarted)", 404);
|
|
225
|
+
}
|
|
226
|
+
return infoOf(found);
|
|
227
|
+
}
|
|
228
|
+
if (this.count(input.sessionId) >= this.opts.maxPerSession) {
|
|
229
|
+
throw new UiTerminalError("terminalLimit", `this session already holds ${this.opts.maxPerSession} terminals; close one first`, 409);
|
|
230
|
+
}
|
|
231
|
+
if (this.byId.size >= this.opts.maxTotal) {
|
|
232
|
+
throw new UiTerminalError("terminalLimit", `${this.opts.maxTotal} terminals is the host-wide limit; close one first`, 409);
|
|
233
|
+
}
|
|
234
|
+
const cols = clampSize(input.cols, MAX_COLS);
|
|
235
|
+
const rows = clampSize(input.rows, MAX_ROWS);
|
|
236
|
+
const managed: Managed = {
|
|
237
|
+
id: randomUUID(),
|
|
238
|
+
sessionId: input.sessionId,
|
|
239
|
+
shellId: input.shellId,
|
|
240
|
+
shellSpec: input.shellSpec,
|
|
241
|
+
title: input.title,
|
|
242
|
+
cwd: input.cwd,
|
|
243
|
+
createdAt: this.opts.now(),
|
|
244
|
+
cols,
|
|
245
|
+
rows,
|
|
246
|
+
state: "running",
|
|
247
|
+
exitCode: null,
|
|
248
|
+
// Reserved below before the await; the real handle lands with the spawn.
|
|
249
|
+
handle: undefined as unknown as UiPtyHandle,
|
|
250
|
+
ring: [],
|
|
251
|
+
ringBytes: 0,
|
|
252
|
+
sinks: new Set(),
|
|
253
|
+
pending: "",
|
|
254
|
+
announced: false,
|
|
255
|
+
};
|
|
256
|
+
// Reserve the slot BEFORE awaiting the spawn: a slow allocation must not let
|
|
257
|
+
// a second request slip past the quota and end up with two live shells.
|
|
258
|
+
this.byId.set(managed.id, managed);
|
|
259
|
+
try {
|
|
260
|
+
const handle = await this.opts.spawn({ argv: input.argv, cwd: input.cwd, env: input.env, cols, rows });
|
|
261
|
+
managed.handle = handle;
|
|
262
|
+
this.wire(managed, handle);
|
|
263
|
+
} catch (error) {
|
|
264
|
+
this.byId.delete(managed.id);
|
|
265
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
266
|
+
throw new UiTerminalError("spawn-failed", `cannot start ${input.title}: ${message}`, 502);
|
|
267
|
+
}
|
|
268
|
+
return infoOf(managed);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Attach one consumer; the returned detach leaves the process running. */
|
|
272
|
+
attach(id: string, sink: UiSink): () => void {
|
|
273
|
+
const managed = this.byId.get(id);
|
|
274
|
+
if (managed === undefined) return () => {};
|
|
275
|
+
managed.sinks.add(sink);
|
|
276
|
+
if (managed.idleTimer !== undefined) {
|
|
277
|
+
clearTimeout(managed.idleTimer);
|
|
278
|
+
managed.idleTimer = undefined;
|
|
279
|
+
}
|
|
280
|
+
// A terminal that already ended announces once, to the attaching sink only.
|
|
281
|
+
if (managed.state !== "running") sink.onExit(infoOf(managed));
|
|
282
|
+
return () => {
|
|
283
|
+
managed.sinks.delete(sink);
|
|
284
|
+
if (managed.sinks.size === 0 && managed.state === "running") this.scheduleReaper(managed);
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Write one input frame to the shell. */
|
|
289
|
+
async write(id: string, data: string): Promise<void> {
|
|
290
|
+
const managed = this.mustGet(id);
|
|
291
|
+
if (managed.state !== "running") throw new UiTerminalError("bad-request", "the terminal has already ended", 409);
|
|
292
|
+
if (Buffer.byteLength(data) > MAX_INPUT_BYTES) throw new UiTerminalError("inputFull", "input exceeds the per-frame limit", 413);
|
|
293
|
+
await managed.handle.write(data);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Resize the process; false when the backend cannot (older host builds). */
|
|
297
|
+
async resize(id: string, cols: number, rows: number): Promise<boolean> {
|
|
298
|
+
const managed = this.mustGet(id);
|
|
299
|
+
managed.cols = clampSize(cols, MAX_COLS);
|
|
300
|
+
managed.rows = clampSize(rows, MAX_ROWS);
|
|
301
|
+
if (managed.state !== "running" || managed.handle.resize === undefined) return false;
|
|
302
|
+
await managed.handle.resize(managed.cols, managed.rows);
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Send one signal to the shell's foreground group. */
|
|
307
|
+
async signal(id: string, signal: string): Promise<void> {
|
|
308
|
+
const managed = this.mustGet(id);
|
|
309
|
+
if (managed.handle.signalForeground === undefined) throw new UiTerminalError("bad-request", "this host cannot signal a terminal", 503);
|
|
310
|
+
await managed.handle.signalForeground(signal);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** End the process and drop the entry (the only path that frees a quota slot). */
|
|
314
|
+
async close(id: string): Promise<void> {
|
|
315
|
+
const managed = this.byId.get(id);
|
|
316
|
+
if (managed === undefined) return;
|
|
317
|
+
this.byId.delete(id);
|
|
318
|
+
this.clearTimers(managed);
|
|
319
|
+
managed.sinks.clear();
|
|
320
|
+
try {
|
|
321
|
+
await managed.handle.terminate();
|
|
322
|
+
} catch {
|
|
323
|
+
// A process that refuses to die is already off the books; reporting a failed
|
|
324
|
+
// cleanup would only make a closed tab look broken when it is gone anyway.
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Close every terminal this registry owns (plugin teardown). */
|
|
329
|
+
async dispose(): Promise<void> {
|
|
330
|
+
for (const id of Array.from(this.byId.keys())) await this.close(id);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private mustGet(id: string): Managed {
|
|
334
|
+
const managed = this.byId.get(id);
|
|
335
|
+
if (managed === undefined) throw new UiTerminalError("missingTerminal", "no such terminal", 404);
|
|
336
|
+
return managed;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Start the output plumbing for one allocated handle. */
|
|
340
|
+
private wire(managed: Managed, handle: UiPtyHandle): void {
|
|
341
|
+
// A decoder, not `chunk.toString()`: the PTY can split a multi-byte sequence
|
|
342
|
+
// across chunks and the ring must never carry a broken code point.
|
|
343
|
+
const decoder = new StringDecoder("utf8");
|
|
344
|
+
handle.output.on("data", (chunk: Buffer | string) => {
|
|
345
|
+
const text = decoder.write(chunk);
|
|
346
|
+
if (text.length > 0) this.push(managed, text);
|
|
347
|
+
});
|
|
348
|
+
handle.output.on("error", () => {
|
|
349
|
+
/* the exit path below settles the terminal */
|
|
350
|
+
});
|
|
351
|
+
handle.done.then(
|
|
352
|
+
(outcome) => {
|
|
353
|
+
const tail = decoder.end();
|
|
354
|
+
if (tail.length > 0) this.push(managed, tail);
|
|
355
|
+
managed.exitCode = outcome.exitCode;
|
|
356
|
+
managed.state = "exited";
|
|
357
|
+
this.settle(managed);
|
|
358
|
+
},
|
|
359
|
+
(error: unknown) => {
|
|
360
|
+
managed.state = "failed";
|
|
361
|
+
managed.error = error instanceof Error ? error.message : String(error);
|
|
362
|
+
this.settle(managed);
|
|
363
|
+
},
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Buffer one decoded chunk and forward it while a consumer is attached. */
|
|
368
|
+
private push(managed: Managed, text: string): void {
|
|
369
|
+
managed.ring.push(text);
|
|
370
|
+
managed.ringBytes += text.length;
|
|
371
|
+
this.trim(managed);
|
|
372
|
+
if (managed.sinks.size === 0) return;
|
|
373
|
+
managed.pending += text;
|
|
374
|
+
if (managed.pending.length >= FLUSH_BYTES) this.flush(managed);
|
|
375
|
+
else if (managed.flushTimer === undefined) {
|
|
376
|
+
managed.flushTimer = setTimeout(() => {
|
|
377
|
+
this.flush(managed);
|
|
378
|
+
}, FLUSH_MS);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Deliver the coalesced window to every attached consumer. */
|
|
383
|
+
private flush(managed: Managed): void {
|
|
384
|
+
if (managed.flushTimer !== undefined) {
|
|
385
|
+
clearTimeout(managed.flushTimer);
|
|
386
|
+
managed.flushTimer = undefined;
|
|
387
|
+
}
|
|
388
|
+
const data = managed.pending;
|
|
389
|
+
managed.pending = "";
|
|
390
|
+
if (data.length === 0) return;
|
|
391
|
+
for (const sink of Array.from(managed.sinks)) sink.onData(data);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Announce the end: tell every consumer, keep the entry (and its screen). */
|
|
395
|
+
private settle(managed: Managed): void {
|
|
396
|
+
if (!managed.announced) {
|
|
397
|
+
managed.announced = true;
|
|
398
|
+
this.flush(managed);
|
|
399
|
+
const info = infoOf(managed);
|
|
400
|
+
for (const sink of Array.from(managed.sinks)) sink.onExit(info);
|
|
401
|
+
}
|
|
402
|
+
if (managed.idleTimer === undefined) this.scheduleReaper(managed);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Arm the reaper: an ended shell nobody is watching is not worth keeping. */
|
|
406
|
+
private scheduleReaper(managed: Managed): void {
|
|
407
|
+
const grace = this.opts.idleGraceMs;
|
|
408
|
+
if (grace <= 0) {
|
|
409
|
+
if (managed.state !== "running") void this.close(managed.id);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
// A running shell waits for a reload; an ended one is dropped sooner.
|
|
413
|
+
const delay = managed.state === "running" ? grace : Math.min(grace, 60_000);
|
|
414
|
+
managed.idleTimer = setTimeout(() => {
|
|
415
|
+
managed.idleTimer = undefined;
|
|
416
|
+
if (managed.sinks.size === 0) void this.close(managed.id);
|
|
417
|
+
}, delay);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private clearTimers(managed: Managed): void {
|
|
421
|
+
if (managed.flushTimer !== undefined) clearTimeout(managed.flushTimer);
|
|
422
|
+
if (managed.idleTimer !== undefined) clearTimeout(managed.idleTimer);
|
|
423
|
+
managed.flushTimer = undefined;
|
|
424
|
+
managed.idleTimer = undefined;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Keep the ring inside the byte budget, oldest first. */
|
|
428
|
+
private trim(managed: Managed): void {
|
|
429
|
+
const budget = this.opts.scrollback;
|
|
430
|
+
while (managed.ringBytes > budget && managed.ring.length > 0) {
|
|
431
|
+
const oldest = managed.ring[0]!;
|
|
432
|
+
if (managed.ring.length > 1 || oldest.length <= budget) {
|
|
433
|
+
managed.ring.shift();
|
|
434
|
+
managed.ringBytes -= oldest.length;
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
// One huge chunk in a one-entry ring: keep its tail, dropping a leading lone
|
|
438
|
+
// surrogate so the replayed text never carries a broken code point.
|
|
439
|
+
const cut = oldest.length - budget;
|
|
440
|
+
const head = oldest.charCodeAt(cut);
|
|
441
|
+
const start = head >= 0xdc00 && head <= 0xdfff ? cut + 1 : cut;
|
|
442
|
+
const kept = oldest.slice(start);
|
|
443
|
+
managed.ring[0] = kept;
|
|
444
|
+
managed.ringBytes = kept.length;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|