teapot-coding-agent 0.32.5 → 0.33.0
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/dist/agent/agent.js +16 -2
- package/dist/master.js +15 -0
- package/dist/server/api.js +116 -96
- package/dist/server/term-size.js +125 -1
- package/dist/server/terminals.js +335 -0
- package/package.json +1 -1
- package/public/assets/index-BZwTrnYv.css +1 -0
- package/public/assets/{index-BOgKQGMN.js → index-CIPNs6cX.js} +8 -8
- package/public/assets/index-CIPNs6cX.js.map +1 -0
- package/public/assets/{shiki-DtIf71Fx.js → shiki-Dsa6A5rK.js} +2 -2
- package/public/assets/{shiki-DtIf71Fx.js.map → shiki-Dsa6A5rK.js.map} +1 -1
- package/public/index.html +2 -2
- package/public/assets/index-BOgKQGMN.js.map +0 -1
- package/public/assets/index-vPfJBPu7.css +0 -1
package/dist/agent/agent.js
CHANGED
|
@@ -693,8 +693,21 @@ export class Agent {
|
|
|
693
693
|
get workspace() {
|
|
694
694
|
return this.opts.workspace;
|
|
695
695
|
}
|
|
696
|
-
/**
|
|
696
|
+
/**
|
|
697
|
+
* True while the workspace directory does not exist on disk.
|
|
698
|
+
*
|
|
699
|
+
* Re-checked here rather than trusting the flag set at `init()`: the directory can come BACK
|
|
700
|
+
* (the operator recreates it, another agent in the same project makes it, a new session is
|
|
701
|
+
* created in it), and a boot-time snapshot then leaves every older session flagged 👻 forever.
|
|
702
|
+
* That is the reported symptom: a recreated directory shows its session count, but the sidebar
|
|
703
|
+
* lists only the session that was just created, because all the older ones still say "ghost".
|
|
704
|
+
*/
|
|
697
705
|
get isGhost() {
|
|
706
|
+
const exists = existsSync(this.workspace);
|
|
707
|
+
// only ever CLEAR from here: a sync getter must not claim a directory exists when it does
|
|
708
|
+
// not, but it can safely notice that it does again
|
|
709
|
+
if (exists)
|
|
710
|
+
this.workspaceMissing = false;
|
|
698
711
|
return this.workspaceMissing;
|
|
699
712
|
}
|
|
700
713
|
/** Create the workspace on demand — before any tool touches the fs. */
|
|
@@ -1557,7 +1570,8 @@ export class Agent {
|
|
|
1557
1570
|
*/
|
|
1558
1571
|
live: this.isLive(),
|
|
1559
1572
|
workspace: this.workspace,
|
|
1560
|
-
|
|
1573
|
+
// through the getter, so a workspace that came back stops being reported as 👻
|
|
1574
|
+
workspaceMissing: this.isGhost,
|
|
1561
1575
|
session: this.currentSession,
|
|
1562
1576
|
// #155: a human label for this session, so the sidebar does not ask the
|
|
1563
1577
|
// operator to read `teapot-10-16854917`. Absent when the first prompt had
|
package/dist/master.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Agents are in-process async loops (I/O bound only); all CPU-heavy work is
|
|
4
4
|
* delegated to subprocesses managed by the bash tool with hard timeouts.
|
|
5
5
|
*/
|
|
6
|
+
import { closeAllTerminals, closeTerminalsFor } from "./server/terminals.js";
|
|
6
7
|
import { readFileSync, existsSync, mkdirSync, writeFileSync, readdirSync, statSync, lstatSync, renameSync, unlinkSync, openSync, closeSync, readSync, fsyncSync, rmSync, } from "node:fs";
|
|
7
8
|
import { randomUUID } from "node:crypto";
|
|
8
9
|
import { currentKey, makeKeyPool, resetPool } from "./agent/key-pool.js";
|
|
@@ -1962,6 +1963,9 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
|
|
|
1962
1963
|
this.agents.delete(one);
|
|
1963
1964
|
await live.dispose();
|
|
1964
1965
|
}
|
|
1966
|
+
// an archived agent's shells are unreachable from the UI (its tabs go with it), so
|
|
1967
|
+
// leaving the ptys running would strand them until the idle reaper noticed
|
|
1968
|
+
closeTerminalsFor(one);
|
|
1965
1969
|
const ac = this.config.agents.find((a) => a.id === one);
|
|
1966
1970
|
if (!ac)
|
|
1967
1971
|
continue;
|
|
@@ -2267,6 +2271,17 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
|
|
|
2267
2271
|
finally {
|
|
2268
2272
|
if (timer)
|
|
2269
2273
|
clearTimeout(timer);
|
|
2274
|
+
/**
|
|
2275
|
+
* Close the human terminals too.
|
|
2276
|
+
*
|
|
2277
|
+
* Their ptys are spawned `detached` so one close can signal the whole process group (see
|
|
2278
|
+
* terminals.ts). The cost of that is that they do NOT die with this process — a restart
|
|
2279
|
+
* would leave every open shell orphaned and unreachable, still holding the operator's
|
|
2280
|
+
* workspace. Closing here is what makes `detached` safe.
|
|
2281
|
+
*/
|
|
2282
|
+
const n = closeAllTerminals();
|
|
2283
|
+
if (n)
|
|
2284
|
+
console.log(`[teapot] ⌨ closed ${n} terminal(s)`);
|
|
2270
2285
|
}
|
|
2271
2286
|
}
|
|
2272
2287
|
/** Restart the server process (spawns a new master, keeps this one alive until ready). */
|
package/dist/server/api.js
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
import { Hono } from "hono";
|
|
5
5
|
import { serve, upgradeWebSocket } from "@hono/node-server";
|
|
6
6
|
import { WebSocketServer } from "ws";
|
|
7
|
-
import { readFileSync
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
8
|
import { currentSkills } from "../agent/tools.js";
|
|
9
|
-
import { spawn } from "node:child_process";
|
|
10
9
|
import { promises as fs } from "node:fs";
|
|
11
10
|
import { fileURLToPath } from "node:url";
|
|
12
11
|
import { parseSchedule } from "../scheduler/cron.js";
|
|
13
|
-
import {
|
|
12
|
+
import { attachTerminal, closeTerminal, closeTerminalsFor, createTerminal, detachTerminal, forgetTerminalSize, listTerminals, reapIdleTerminals, resizeTerminal, setTerminalResize, writeTerminal, } from "./terminals.js";
|
|
13
|
+
import { applyPtySize, TermSizeTracker, resolvePtySlave } from "./term-size.js";
|
|
14
14
|
import { expandTilde, homeDir } from "../home.js";
|
|
15
15
|
import { SUB_PERSONAS, resolveWorkspace } from "../master.js";
|
|
16
16
|
import { ConfigPatchSchema, formatZodError } from "../config-schema.js";
|
|
@@ -143,8 +143,9 @@ export function buildApp(master) {
|
|
|
143
143
|
}
|
|
144
144
|
return c.json({ error: "unauthorized" }, 401);
|
|
145
145
|
});
|
|
146
|
-
// per-agent terminal
|
|
147
|
-
|
|
146
|
+
// The per-agent terminal cap lives in `terminals.ts` now, next to the registry that owns the
|
|
147
|
+
// shells — a counter here could drift from the shells it was meant to bound (it did once:
|
|
148
|
+
// #70, where a refused connection decremented a slot it never took).
|
|
148
149
|
/**
|
|
149
150
|
* Live `/api/ws` event-stream connections (#79).
|
|
150
151
|
*
|
|
@@ -181,31 +182,15 @@ export function buildApp(master) {
|
|
|
181
182
|
//
|
|
182
183
|
// The slave is resolved per call rather than cached: `script` may have exited
|
|
183
184
|
// and been replaced, and a stale device path would resize someone else's pty.
|
|
184
|
-
//
|
|
185
|
-
//
|
|
185
|
+
//
|
|
186
|
+
// There is deliberately NO stdin fallback. Writing `stty rows R cols C` into the child's
|
|
187
|
+
// stdin is the bug that was reported twice: when a full-screen program owns the tty it
|
|
188
|
+
// receives that line as KEYSTROKES, so it lands in the operator's document. A resize that
|
|
189
|
+
// cannot be applied is better than one that types into vim — so this does nothing instead.
|
|
190
|
+
// Hosts without /proc are covered by `resolvePtySlave`'s `ps` path.
|
|
186
191
|
const setTermSize = (child, rows, cols) => termSizes.request(child, rows, cols, (r, c) => {
|
|
187
|
-
|
|
188
|
-
if (slave) {
|
|
189
|
-
const r2 = spawn("stty", ["-F", slave, "rows", String(r), "cols", String(c)], {
|
|
190
|
-
stdio: "ignore",
|
|
191
|
-
});
|
|
192
|
-
// a failed ioctl must fall through to the stdin path, not silently drop
|
|
193
|
-
// the resize: `stty` exits non-zero when the device is not a tty
|
|
194
|
-
r2.on("error", () => writeSizeViaStdin(child, r, c));
|
|
195
|
-
r2.on("close", (code) => {
|
|
196
|
-
if (code !== 0)
|
|
197
|
-
writeSizeViaStdin(child, r, c);
|
|
198
|
-
});
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
|
-
writeSizeViaStdin(child, r, c);
|
|
192
|
+
applyPtySize(child, r, c);
|
|
202
193
|
});
|
|
203
|
-
/** last-resort resize for a host with no /proc: type it into the shell */
|
|
204
|
-
const writeSizeViaStdin = (child, r, c) => {
|
|
205
|
-
if (!child.stdin?.writable)
|
|
206
|
-
return;
|
|
207
|
-
child.stdin.write(`stty rows ${r} cols ${c} >/dev/null 2>&1\n`);
|
|
208
|
-
};
|
|
209
194
|
// ---- realtime events over WebSocket (replaces SSE for the web UI) ----
|
|
210
195
|
app.get("/api/ws", upgradeWebSocket(() => {
|
|
211
196
|
let onUpdate = null;
|
|
@@ -301,76 +286,119 @@ export function buildApp(master) {
|
|
|
301
286
|
// ---- human terminal: interactive shell in the agent's workspace ----
|
|
302
287
|
// Uses util-linux `script` as a zero-dependency PTY when available (colors,
|
|
303
288
|
// line editing, ctrl+c); falls back to plain pipes otherwise.
|
|
289
|
+
/*
|
|
290
|
+
* Terminals are SERVER state now (#term-shared): the list survives a reload and several
|
|
291
|
+
* clients see the same shells. These REST routes own creation and closing; the WebSocket
|
|
292
|
+
* below only ATTACHES to an existing terminal (or creates one when asked).
|
|
293
|
+
*/
|
|
294
|
+
setTerminalResize(setTermSize, resolvePtySlave);
|
|
295
|
+
// Terminals outlive a disconnect on purpose, but a CLOSED tab never re-attaches. Sweep the
|
|
296
|
+
// ones nobody has held for hours so an abandoned shell does not live as long as the process.
|
|
297
|
+
{
|
|
298
|
+
const t = setInterval(() => {
|
|
299
|
+
const n = reapIdleTerminals();
|
|
300
|
+
if (n)
|
|
301
|
+
console.log(`[teapot] ⌨ reaped ${n} idle terminal(s)`);
|
|
302
|
+
}, 30 * 60_000);
|
|
303
|
+
t.unref?.();
|
|
304
|
+
}
|
|
305
|
+
/** every live terminal, so a fresh page can rebuild the tab strip */
|
|
306
|
+
app.get("/api/terminals", (c) => c.json({ terminals: listTerminals() }));
|
|
307
|
+
app.post("/api/terminals", async (c) => {
|
|
308
|
+
const body = (await c.req.json().catch(() => null));
|
|
309
|
+
if (!body)
|
|
310
|
+
return c.json({ error: "a JSON body is required" }, 400);
|
|
311
|
+
const agentId = String(body.agentId ?? "").trim();
|
|
312
|
+
const agent = agentId ? master.agents.get(agentId) : undefined;
|
|
313
|
+
if (!agent)
|
|
314
|
+
return c.json({ error: `no such agent: ${agentId}` }, 404);
|
|
315
|
+
const r = createTerminal(agentId, agent.workspace, body.title);
|
|
316
|
+
if (!r.ok)
|
|
317
|
+
return c.json({ error: r.error }, 409);
|
|
318
|
+
return c.json({ terminal: r.terminal });
|
|
319
|
+
});
|
|
320
|
+
app.delete("/api/terminals/:tid", (c) => {
|
|
321
|
+
const closed = closeTerminal(c.req.param("tid") ?? "");
|
|
322
|
+
return c.json({ closed });
|
|
323
|
+
});
|
|
324
|
+
// every terminal of one agent (the UI groups tabs by agent)
|
|
325
|
+
app.delete("/api/agents/:id/terminals", (c) => {
|
|
326
|
+
const n = closeTerminalsFor(c.req.param("id") ?? "");
|
|
327
|
+
return c.json({ closed: n });
|
|
328
|
+
});
|
|
304
329
|
app.get("/api/agents/:id/term", upgradeWebSocket((c) => {
|
|
305
330
|
const agentId = c.req.param("id") ?? "";
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
331
|
+
/**
|
|
332
|
+
* `?terminal=<id>` ATTACHES to an existing shell; without it a new one is created.
|
|
333
|
+
*
|
|
334
|
+
* The distinction is the whole point of moving terminals server-side: a reload sends the
|
|
335
|
+
* id it already knows and gets its screen back, while a new tab sends nothing and gets a
|
|
336
|
+
* fresh shell.
|
|
337
|
+
*/
|
|
338
|
+
const wanted = c.req.query("terminal") ?? "";
|
|
339
|
+
let attachedId = "";
|
|
340
|
+
// the sink is a stable identity for THIS connection, so the registry can key per-client
|
|
341
|
+
// sizes by it and detach exactly this one
|
|
342
|
+
const sink = (msg) => {
|
|
316
343
|
try {
|
|
317
|
-
|
|
344
|
+
ws.send(JSON.stringify(msg));
|
|
318
345
|
}
|
|
319
346
|
catch {
|
|
320
|
-
/*
|
|
347
|
+
/* client gone; onClose detaches */
|
|
321
348
|
}
|
|
322
|
-
child = null;
|
|
323
349
|
};
|
|
350
|
+
let ws;
|
|
324
351
|
return {
|
|
325
|
-
onOpen(_evt,
|
|
352
|
+
onOpen(_evt, socket) {
|
|
353
|
+
ws = socket;
|
|
326
354
|
const agent = master.agents.get(agentId);
|
|
327
|
-
|
|
355
|
+
if (!agent) {
|
|
356
|
+
sink({ kind: "exit", code: null });
|
|
328
357
|
try {
|
|
329
|
-
|
|
358
|
+
socket.send(JSON.stringify({ kind: "exit", error: `no such agent: ${agentId}` }));
|
|
330
359
|
}
|
|
331
360
|
catch {
|
|
332
|
-
/*
|
|
361
|
+
/* ignore */
|
|
333
362
|
}
|
|
334
|
-
};
|
|
335
|
-
const cur = termCounts.get(agentId) ?? 0;
|
|
336
|
-
if (cur >= 10) {
|
|
337
|
-
// soft safeguard only — the UI allows up to 10 tabs per agent
|
|
338
|
-
send({ kind: "exit", error: "too many terminals for this agent (max 10)" });
|
|
339
363
|
return;
|
|
340
364
|
}
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
365
|
+
let id = wanted;
|
|
366
|
+
if (!id) {
|
|
367
|
+
const created = createTerminal(agentId, agent.workspace);
|
|
368
|
+
if (!created.ok) {
|
|
369
|
+
try {
|
|
370
|
+
socket.send(JSON.stringify({ kind: "exit", error: created.error }));
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
/* ignore */
|
|
374
|
+
}
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
id = created.terminal.id;
|
|
378
|
+
}
|
|
379
|
+
const r = attachTerminal(id, sink);
|
|
380
|
+
if (!r.ok) {
|
|
381
|
+
try {
|
|
382
|
+
socket.send(JSON.stringify({ kind: "exit", error: r.error }));
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
/* ignore */
|
|
386
|
+
}
|
|
349
387
|
return;
|
|
350
388
|
}
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
//
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
}
|
|
362
|
-
child.stderr?.on("data", (b) => {
|
|
363
|
-
send({ kind: "data", data: b.toString("utf8") });
|
|
364
|
-
});
|
|
365
|
-
child.on("close", (code) => {
|
|
366
|
-
send({ kind: "exit", code });
|
|
367
|
-
console.log(`[teapot] ⌨ terminal exit: ${agentId} (${code ?? "signal"})`);
|
|
368
|
-
child = null;
|
|
369
|
-
});
|
|
389
|
+
attachedId = id;
|
|
390
|
+
// tell the client WHICH terminal this connection is for, then REPLAY the backlog so
|
|
391
|
+
// the screen is correct before live output starts arriving
|
|
392
|
+
try {
|
|
393
|
+
socket.send(JSON.stringify({ kind: "attach", terminal: r.terminal }));
|
|
394
|
+
if (r.replay)
|
|
395
|
+
socket.send(JSON.stringify({ kind: "data", data: r.replay }));
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
/* ignore */
|
|
399
|
+
}
|
|
370
400
|
},
|
|
371
401
|
onMessage(evt) {
|
|
372
|
-
if (!child?.stdin?.writable)
|
|
373
|
-
return;
|
|
374
402
|
let m;
|
|
375
403
|
try {
|
|
376
404
|
m = JSON.parse(String(evt.data));
|
|
@@ -378,32 +406,24 @@ export function buildApp(master) {
|
|
|
378
406
|
catch {
|
|
379
407
|
return;
|
|
380
408
|
}
|
|
409
|
+
if (!attachedId)
|
|
410
|
+
return;
|
|
381
411
|
if (m.kind === "input")
|
|
382
|
-
|
|
412
|
+
writeTerminal(attachedId, String(m.data ?? ""));
|
|
383
413
|
else if (m.kind === "resize") {
|
|
384
414
|
const r = Number(m.rows) | 0;
|
|
385
415
|
const cl = Number(m.cols) | 0;
|
|
386
416
|
if (r > 0 && cl > 0)
|
|
387
|
-
|
|
417
|
+
resizeTerminal(attachedId, sink, r, cl);
|
|
388
418
|
}
|
|
389
419
|
},
|
|
390
420
|
onClose() {
|
|
391
|
-
//
|
|
392
|
-
|
|
393
|
-
// drop the pending resize timer so we can't write into a dead child
|
|
394
|
-
if (dead)
|
|
395
|
-
termSizes.forget(dead);
|
|
396
|
-
cleanup();
|
|
397
|
-
// #70: only an ADMITTED connection owns a slot. A connection refused
|
|
398
|
-
// at the cap never incremented, so decrementing for it is exactly
|
|
399
|
-
// what drove the counter negative and disabled the limit.
|
|
400
|
-
if (!admitted)
|
|
421
|
+
// DETACH, do not kill: a reload must not destroy the shell (#term-shared)
|
|
422
|
+
if (!attachedId)
|
|
401
423
|
return;
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
else
|
|
406
|
-
termCounts.set(agentId, n);
|
|
424
|
+
detachTerminal(attachedId, sink);
|
|
425
|
+
// the pty outlives us; drop this client's size so it stops constraining the others
|
|
426
|
+
forgetTerminalSize(attachedId, sink);
|
|
407
427
|
},
|
|
408
428
|
};
|
|
409
429
|
}));
|
package/dist/server/term-size.js
CHANGED
|
@@ -1,4 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal resize plumbing for the web terminal (#20).
|
|
3
|
+
*
|
|
4
|
+
* A resize is a property of the TTY, not a command. `TermSizeTracker` decides
|
|
5
|
+
* WHEN to apply one; `resolvePtySlave` finds the device to apply it TO.
|
|
6
|
+
*
|
|
7
|
+
* ## How the size is applied now
|
|
8
|
+
*
|
|
9
|
+
* `stty -F <pty-slave> rows R cols C` — an ioctl(TIOCSWINSZ) on the pty DEVICE.
|
|
10
|
+
* Nothing is written to the child's stdin, so nothing can be typed into a
|
|
11
|
+
* foreground program. MEASURED with `script -qec`:
|
|
12
|
+
*
|
|
13
|
+
* stty -F /dev/pts/0 rows 55 cols 190
|
|
14
|
+
* readback: 55 190
|
|
15
|
+
* foreground trap: WINCH fired, no command text in the output stream
|
|
16
|
+
*
|
|
17
|
+
* which is the same mechanism VS Code (node-pty, native ioctl) and Alacritty
|
|
18
|
+
* (owns the pty) use — neither ever issues `stty` as TEXT.
|
|
19
|
+
*
|
|
20
|
+
* Before this, the size was applied by WRITING `stty rows R cols C\n` into the
|
|
21
|
+
* child's stdin. That is only safe when a shell is reading: when an interactive
|
|
22
|
+
* program owns the tty (vim, less, a python REPL) stdin belongs to the PROGRAM,
|
|
23
|
+
* so the line arrived as keystrokes and landed in the operator's document. With
|
|
24
|
+
* the device ioctl that text is gone entirely, so the machinery here is only
|
|
25
|
+
* about avoiding redundant syscalls on a drag — a debounce and a no-op skip.
|
|
26
|
+
*
|
|
27
|
+
* It used to ALSO defer while the child was producing output (`markBusy`). That
|
|
28
|
+
* existed solely to make the text path rarer, and it became a bug once the ioctl
|
|
29
|
+
* removed the hazard: a full-screen program redraws continuously, so the busy
|
|
30
|
+
* window never expired and the resize never applied at all (#172 — "nanoとか
|
|
31
|
+
* 開いたらリサイズ効いてない"). Deferring is now wrong for every path.
|
|
32
|
+
*
|
|
33
|
+
* ## Why the slave path has to be discovered
|
|
34
|
+
*
|
|
35
|
+
* `script` is spawned by us, so we hold a pipe to its stdin/stdout, not the pty
|
|
36
|
+
* master. The pty slave it created is reachable as our CHILD's fd 0 on Linux
|
|
37
|
+
* (/proc/<pid>/fd/0 → /dev/pts/N). Where that cannot be resolved — macOS has no
|
|
38
|
+
* /proc — the caller falls back to the stdin write, so no platform loses resize;
|
|
39
|
+
* it only loses the improvement.
|
|
40
|
+
*
|
|
41
|
+
* `TermSizeTracker` still:
|
|
42
|
+
* - debounces to the trailing edge of a drag (one ioctl per drag, not per pixel)
|
|
43
|
+
* - remembers the applied size and skips no-op resizes entirely
|
|
44
|
+
* - keys state by CHILD, not agent: one agent may hold up to 10 terminals,
|
|
45
|
+
* each with its own size and its own foreground program
|
|
46
|
+
*/
|
|
1
47
|
import { readFileSync, readdirSync, readlinkSync } from "node:fs";
|
|
48
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
49
|
/**
|
|
3
50
|
* The pty slave device behind a child, or null when it cannot be determined.
|
|
4
51
|
*
|
|
@@ -30,7 +77,60 @@ export function resolvePtySlave(child) {
|
|
|
30
77
|
if (found)
|
|
31
78
|
return found;
|
|
32
79
|
}
|
|
33
|
-
|
|
80
|
+
// No /proc (macOS): ask `ps` which tty the child's descendants are on. This is what makes
|
|
81
|
+
// it safe to drop the old "type `stty` into stdin" fallback — that path put a command line
|
|
82
|
+
// into the terminal itself, so a foreground program (vim, less, a REPL) received it as
|
|
83
|
+
// KEYSTROKES and it landed in the operator's buffer. A tty name from `ps` can be resized
|
|
84
|
+
// with `stty -F`, which emits nothing into the stream.
|
|
85
|
+
return ptySlaveViaPs(pid);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The controlling tty of `pid` or any descendant, via `ps` (for hosts without /proc).
|
|
89
|
+
*
|
|
90
|
+
* `ps -o tty=` prints "ttys003" or "pts/3"; both name a device under /dev. A process with no
|
|
91
|
+
* controlling terminal prints "??" (Linux) or "-", and those are skipped.
|
|
92
|
+
*/
|
|
93
|
+
function ptySlaveViaPs(pid) {
|
|
94
|
+
try {
|
|
95
|
+
/**
|
|
96
|
+
* Only the child's OWN tty, never one inherited from our process.
|
|
97
|
+
*
|
|
98
|
+
* `ps -o tty=` reports the CONTROLLING terminal, which a plain-pipe child still inherits
|
|
99
|
+
* from whoever started the server — so naively taking it returns the tty of the shell that
|
|
100
|
+
* launched teapot, and a resize would then ioctl THAT. Measured: a piped `/bin/sh` "resolved"
|
|
101
|
+
* to the test runner's own tty. So require that the process has a tty which is NOT ours and
|
|
102
|
+
* NOT our parent's, or report nothing.
|
|
103
|
+
*/
|
|
104
|
+
const self = process.pid;
|
|
105
|
+
const out = spawnSync("ps", ["-e", "-o", "pid=,ppid=,tty="], { encoding: "utf8" }).stdout ?? "";
|
|
106
|
+
const rows = out
|
|
107
|
+
.split("\n")
|
|
108
|
+
.map((l) => l.trim().split(/\s+/))
|
|
109
|
+
.filter((c) => c.length >= 3 && Number.isInteger(Number(c[0])))
|
|
110
|
+
.map((c) => ({ pid: Number(c[0]), ppid: Number(c[1]), tty: c[2] }));
|
|
111
|
+
const ttyOf = (p) => rows.find((r) => r.pid === p)?.tty;
|
|
112
|
+
// the tty we and our own shell are on is inherited by children and proves nothing
|
|
113
|
+
const inherited = new Set([ttyOf(self), ttyOf(process.ppid)].filter(Boolean));
|
|
114
|
+
const seen = new Set();
|
|
115
|
+
const stack = [pid];
|
|
116
|
+
let found = null;
|
|
117
|
+
while (stack.length) {
|
|
118
|
+
const cur = stack.pop();
|
|
119
|
+
if (seen.has(cur))
|
|
120
|
+
continue;
|
|
121
|
+
seen.add(cur);
|
|
122
|
+
const tty = ttyOf(cur);
|
|
123
|
+
if (tty && tty !== "??" && tty !== "-" && !inherited.has(tty))
|
|
124
|
+
found = tty;
|
|
125
|
+
for (const r of rows)
|
|
126
|
+
if (r.ppid === cur)
|
|
127
|
+
stack.push(r.pid);
|
|
128
|
+
}
|
|
129
|
+
return found ? `/dev/${found}` : null;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
34
134
|
}
|
|
35
135
|
/** pids whose parent is `pid` (empty on a host without /proc) */
|
|
36
136
|
function childrenOf(pid) {
|
|
@@ -118,3 +218,27 @@ export class TermSizeTracker {
|
|
|
118
218
|
this.states.clear();
|
|
119
219
|
}
|
|
120
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Apply a size to a child's pty — the ONLY way this codebase resizes a terminal.
|
|
223
|
+
*
|
|
224
|
+
* It shells out to `stty -F <slave>`, which is ioctl(TIOCSWINSZ) on the pty DEVICE. Nothing is
|
|
225
|
+
* written to the child's stdin, so nothing can be typed into a foreground program.
|
|
226
|
+
*
|
|
227
|
+
* That distinction is the whole point (reported twice): writing `stty rows R cols C\n` into
|
|
228
|
+
* stdin only works while a SHELL is reading it. When vim, less or a REPL owns the tty, the
|
|
229
|
+
* PROGRAM reads, so the line arrives as KEYSTROKES and lands in the operator's document.
|
|
230
|
+
*
|
|
231
|
+
* When the slave cannot be resolved this does NOTHING. A resize that cannot be applied is
|
|
232
|
+
* strictly better than one that types into somebody's buffer.
|
|
233
|
+
*
|
|
234
|
+
* `spawnFn` is injectable so a test can observe what would have been executed.
|
|
235
|
+
*/
|
|
236
|
+
export function applyPtySize(child, rows, cols, spawnFn = spawn) {
|
|
237
|
+
if (!child || rows <= 0 || cols <= 0)
|
|
238
|
+
return false;
|
|
239
|
+
const slave = resolvePtySlave(child);
|
|
240
|
+
if (!slave)
|
|
241
|
+
return false;
|
|
242
|
+
spawnFn("stty", ["-F", slave, "rows", String(rows), "cols", String(cols)], { stdio: "ignore" });
|
|
243
|
+
return true;
|
|
244
|
+
}
|