townmouse 0.2.1 → 0.4.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +72 -2
  2. package/DESIGN.md +26 -42
  3. package/README.md +286 -54
  4. package/SECURITY.md +3 -0
  5. package/TOWNMOUSE.md +1 -1
  6. package/bin/townmouse +2 -2
  7. package/docs/PACKAGING.md +104 -8
  8. package/docs/browser-workspace.md +62 -9
  9. package/docs/panes.md +199 -9
  10. package/native/TownmouseApp.swift +5 -5
  11. package/npm-shrinkwrap.json +1282 -0
  12. package/package.json +11 -7
  13. package/public/browser-picture.mjs +159 -0
  14. package/public/features/app-version.mjs +35 -0
  15. package/public/features/autosave.mjs +5 -1
  16. package/public/features/multi-window-sync.mjs +3 -1
  17. package/public/features/osc-bridge.mjs +8 -3
  18. package/public/features/session-manager.mjs +202 -100
  19. package/public/features/status-metrics.mjs +23 -0
  20. package/public/features/tab-reorder.mjs +8 -0
  21. package/public/features/window-title.mjs +10 -3
  22. package/public/index.html +617 -78
  23. package/public/input-guard.mjs +10 -2
  24. package/public/panes.css +189 -13
  25. package/public/panes.html +4 -1
  26. package/public/panes.mjs +667 -109
  27. package/public/workspace.css +198 -24
  28. package/public/workspace.mjs +346 -106
  29. package/scripts/install-service.sh +97 -63
  30. package/scripts/panes +134 -5
  31. package/scripts/retire-legacy-service.sh +76 -0
  32. package/scripts/{t1.sh → townmouse.sh} +60 -21
  33. package/scripts/uninstall-service.sh +31 -15
  34. package/src/agent-guide.js +72 -3
  35. package/src/attachments.js +2 -2
  36. package/src/browser-dom.js +5 -2
  37. package/src/browser-workspace.js +549 -62
  38. package/src/owner-page.js +43 -0
  39. package/src/request-boundary.js +1 -1
  40. package/src/server.js +588 -128
  41. package/src/workspace-panes.js +423 -91
package/src/server.js CHANGED
@@ -30,7 +30,9 @@ try {
30
30
 
31
31
  // ─── Constants ────────────────────────────────────────────────────────────────
32
32
 
33
- const PORT = process.env.PORT || 11001;
33
+ // Port 11001 belongs to TerminalOne, the engine Townmouse embeds, so the two
34
+ // products can run on one machine.
35
+ const PORT = process.env.PORT || 11002;
34
36
  // Loopback by default. Docker sets HOST=0.0.0.0 because a container's
35
37
  // loopback is not reachable from the host; publish that port to loopback only.
36
38
  const HOST = process.env.HOST || '127.0.0.1';
@@ -38,6 +40,8 @@ const { createRequestBoundary } = require('./request-boundary');
38
40
  const { installStaticDependencies } = require('./static-deps');
39
41
  const isTrustedRequest = createRequestBoundary(PORT, process.env.TERMINALONE_TRUSTED_ORIGINS || '');
40
42
  const MAX_CONCURRENT_SESSIONS = 10;
43
+ // Reported by the health check, so a running copy can say which version it is.
44
+ const APP_VERSION = require('../package.json').version;
41
45
 
42
46
  // Input typed in the moment between the socket opening and the shell existing
43
47
  // used to be discarded without a word, which read as "my typing does not work"
@@ -60,10 +64,17 @@ const VOICE_TMP_BASE = path.join(os.homedir(), '.cache', 'terminalone');
60
64
  const VOICE_DEFAULT_ARGS = '{audio} --model {model} --language {language} --output_format txt --output_dir {dir} --verbose False --fp16 False';
61
65
  const VOICE_PLACEHOLDERS = new Set(['audio', 'model', 'language', 'dir', 'base', 'output']);
62
66
 
63
- // Resume: when a WS drops unexpectedly, keep the PTY alive this long so the
64
- // client can reconnect to the same session. Output produced while detached
65
- // (and while attached) is buffered in a ring and replayed on resume.
66
- const RESUME_GRACE_MS = 5 * 60 * 1000;
67
+ // A session is a shell the person or an agent opened on purpose. It keeps
68
+ // running while nobody views it (output is buffered in a ring and replayed on
69
+ // resume) until it is closed, its shell exits, or the app stops. It used to be
70
+ // killed five minutes after the last viewer left, which silently destroyed
71
+ // every shell the person had merely switched away from.
72
+ const SESSION_NAME_MAX = 40;
73
+ // An agent's "show this session" request only counts as fresh for this long.
74
+ const ACTIVATION_TTL_MS = 60 * 1000;
75
+ // Minted per process. A page that reconnects to a different epoch knows the
76
+ // app was restarted, which is not the same thing as one session being closed.
77
+ const SESSION_EPOCH = crypto.randomUUID();
67
78
 
68
79
  // A shell that cannot start exits immediately. Respawning it without a limit
69
80
  // produced roughly 26 respawns per second, indefinitely, and looked like a
@@ -72,7 +83,23 @@ const RAPID_EXIT_MS = 1500;
72
83
  const MAX_RAPID_RESPAWNS = 5;
73
84
  const RESPAWN_BASE_MS = 100;
74
85
  const RESPAWN_MAX_MS = 5000;
86
+ // The shell's recent output is kept so that every rejoin can show it: the
87
+ // most recent RESUME_BUFFER_MAX characters (measured 2026-11-29: rebuilding a
88
+ // replay from that much costs about 20 ms on the server). Eviction is done in
89
+ // batches of about RESUME_BUFFER_EVICTION so it runs once per that much output
90
+ // rather than on every piece the terminal engine delivers. Small pieces are
91
+ // gathered into blocks of about RESUME_BLOCK.
75
92
  const RESUME_BUFFER_MAX = 512 * 1024;
93
+ const RESUME_BUFFER_EVICTION = 64 * 1024;
94
+ const RESUME_BLOCK = 16 * 1024;
95
+ // When eviction cuts a line, the rest of that line is dropped, up to this far.
96
+ const RESUME_LINE_TRIM_MAX = 4096;
97
+ // Instructions in a shell's output that do something on the page as soon as
98
+ // they are shown: OSC 52 sets the clipboard, OSC 777 raises a notification.
99
+ // They act the first time their output is shown. Output is now replayed at
100
+ // every rejoin, so a replay of output shown before must not carry them, or
101
+ // every rejoin would overwrite the clipboard with something old.
102
+ const SIDE_EFFECT_SEQUENCE = /\x1b\](?:52;[cCsS];[A-Za-z0-9+/=]*|777;[^\x07\x1b]*)(?:\x07|\x1b\\)/g;
76
103
 
77
104
  // ─── In-memory state ──────────────────────────────────────────────────────────
78
105
 
@@ -85,8 +112,16 @@ const pingTimers = new Map();
85
112
  /** @type {Map<string, NodeJS.Timeout>} */
86
113
  const pongTimers = new Map();
87
114
 
88
- /** @type {Map<string, NodeJS.Timeout>} */
89
- const graceTimers = new Map();
115
+ // Session registry. `activeSessions` also holds the short-lived placeholder a
116
+ // connection starts as; only sessions with `listed` set ever had a shell and
117
+ // only those are counted, listed or closed.
118
+ /** The session a viewer attached to most recently. */
119
+ let activeSessionId = null;
120
+ /** Creation order, for the default "Shell N" names. Never reused in one run. */
121
+ let sessionCounter = 0;
122
+ /** The newest explicit "show this session" request, if it is still fresh. */
123
+ let activation = null;
124
+ let activationSeq = 0;
90
125
 
91
126
  // ─── Structured logger ───────────────────────────────────────────────────────
92
127
 
@@ -121,6 +156,172 @@ function countRealShells(excludeId) {
121
156
  return n;
122
157
  }
123
158
 
159
+ // ─── Session registry ────────────────────────────────────────────────────────
160
+ // One description of "which shells exist". The page's row, its Sessions list,
161
+ // /health and the agent API are all read from here, so they cannot disagree.
162
+
163
+ /** The record every connection and every agent-created session starts from. */
164
+ function newSessionRecord(ws, createdBy = 'human') {
165
+ return {
166
+ id: uuidv4(),
167
+ command: resolveShell(),
168
+ ptyProcess: undefined,
169
+ sessionActive: true,
170
+ processExited: false,
171
+ ws,
172
+ startedAt: null,
173
+ // The shell's recent output, kept for every rejoin (see bufferOutput).
174
+ // `outputChars` counts all of it ever, so the retained part starts at
175
+ // outputChars - outputBuffered.
176
+ outputBlocks: [],
177
+ outputPieces: [],
178
+ outputPending: 0,
179
+ outputBuffered: 0,
180
+ // Output before this offset, counted like `outputChars`, has been shown
181
+ // to a viewer, live or in a replay. See withoutRepeatedEffects.
182
+ shownUpTo: 0,
183
+ lastCols: 120,
184
+ lastRows: 40,
185
+ lastDataCols: null,
186
+ lastDataRows: null,
187
+ widthChanged: false,
188
+ outputChars: 0,
189
+ resizeMarkers: [],
190
+ sockets: ws ? new Set([ws]) : new Set(),
191
+ userClosed: false,
192
+ // Set the first time a shell starts; only then is the session listed.
193
+ listed: false,
194
+ name: '',
195
+ createdBy,
196
+ createdAt: null,
197
+ lastViewedAt: null
198
+ };
199
+ }
200
+
201
+ /** @returns {{ ok: true, value: string } | { ok: false, error: string }} */
202
+ function validSessionName(value) {
203
+ if (typeof value !== 'string') return { ok: false, error: 'name must be a string' };
204
+ const name = value.trim();
205
+ if (!name) return { ok: false, error: 'name must not be empty' };
206
+ if (name.length > SESSION_NAME_MAX) return { ok: false, error: `name must be at most ${SESSION_NAME_MAX} characters` };
207
+ if (/[\u0000-\u001f\u007f]/.test(name)) return { ok: false, error: 'name must not contain control characters' };
208
+ return { ok: true, value: name };
209
+ }
210
+
211
+ function nameInUse(name, exceptId) {
212
+ for (const s of activeSessions.values()) {
213
+ if (s.listed && s.id !== exceptId && s.name === name) return true;
214
+ }
215
+ return false;
216
+ }
217
+
218
+ function listedSessions() {
219
+ return [...activeSessions.values()].filter((s) => s.listed);
220
+ }
221
+
222
+ function openSockets(session) {
223
+ return [...(session.sockets || [])].filter((socket) => socket.readyState === WebSocket.OPEN);
224
+ }
225
+
226
+ /** The session a viewer looked at most recently, other than `exceptId`. */
227
+ function mostRecentlyViewed(exceptId) {
228
+ let best = null;
229
+ for (const s of listedSessions()) {
230
+ if (s.id === exceptId) continue;
231
+ if (!best || (s.lastViewedAt || 0) > (best.lastViewedAt || 0)) best = s;
232
+ }
233
+ return best;
234
+ }
235
+
236
+ function serializeSession(s) {
237
+ return {
238
+ id: s.id,
239
+ name: s.name,
240
+ command: s.command || resolveShell(),
241
+ cwd: s.shellCwd || null,
242
+ createdBy: s.createdBy,
243
+ createdAt: s.createdAt,
244
+ startedAt: s.startedAt || null,
245
+ lastViewedAt: s.lastViewedAt,
246
+ viewers: openSockets(s).length,
247
+ active: s.id === activeSessionId,
248
+ status: s.processExited ? 'restarting' : 'running'
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Everything a client needs to draw the row. Who is asking decides how much
254
+ * of it they see, as with panes. The owner's page sees every shell. An agent
255
+ * sees the shells agents started, in row order, and of the owner's shells only
256
+ * how many there are (`ownerStarted`): no id, name or folder. `activeSessionId`
257
+ * and `activation` refer to a shell the caller may see, or are null.
258
+ * `activation` is an explicit request to show a shell, while it is still fresh.
259
+ * @param {'owner'|'agent'} viewer
260
+ */
261
+ function sessionState(viewer = 'owner') {
262
+ const all = listedSessions();
263
+ const shown = viewer === 'agent' ? all.filter((s) => s.createdBy === 'agent') : all;
264
+ const seen = new Set(shown.map((s) => s.id));
265
+ const state = {
266
+ epoch: SESSION_EPOCH,
267
+ sessions: shown.map(serializeSession),
268
+ activeSessionId: activeSessionId && seen.has(activeSessionId) ? activeSessionId : null,
269
+ max: MAX_CONCURRENT_SESSIONS
270
+ };
271
+ if (viewer === 'agent') state.ownerStarted = all.length - shown.length;
272
+ const current = activation && Date.now() - activation.at <= ACTIVATION_TTL_MS && seen.has(activation.id)
273
+ ? activation
274
+ : null;
275
+ state.activation = current ? { seq: current.seq, id: current.id, at: current.at } : null;
276
+ return state;
277
+ }
278
+
279
+ /** Tell every attached page what exists now. `except` just received its own copy. */
280
+ function broadcastSessions(except) {
281
+ const data = JSON.stringify({ type: 'sessions', ...sessionState() });
282
+ let reached = 0;
283
+ for (const s of activeSessions.values()) {
284
+ for (const socket of s.sockets || []) {
285
+ if (socket === except || socket.readyState !== WebSocket.OPEN) continue;
286
+ try { socket.send(data); reached += 1; } catch (_) { /* its close handler cleans up */ }
287
+ }
288
+ }
289
+ return reached;
290
+ }
291
+
292
+ function sendSessionState(ws) {
293
+ sendToSocket(ws, { type: 'sessions', ...sessionState() });
294
+ }
295
+
296
+ /**
297
+ * Start a session nobody is viewing yet: an agent opening a shell for the
298
+ * person, or a fresh shell with a chosen name.
299
+ * @param {{ cwd?: string, name?: string, createdBy: 'human'|'agent', activate?: boolean }} options
300
+ * @returns {Session}
301
+ */
302
+ function createSession({ cwd, name, createdBy, activate }) {
303
+ const session = newSessionRecord(null, createdBy);
304
+ session.sessionActive = false;
305
+ session.name = name || '';
306
+ activeSessions.set(session.id, session);
307
+ if (!spawnShell(session, cwd)) {
308
+ activeSessions.delete(session.id);
309
+ throw Object.assign(new Error('The shell could not be started.'), { status: 500 });
310
+ }
311
+ info(session.id, 'Session created', { createdBy, name: session.name });
312
+ if (activate) activateSession(session);
313
+ broadcastSessions();
314
+ return session;
315
+ }
316
+
317
+ // An explicit "show this session" request. Every open terminal page follows
318
+ // it once, while it is fresh; the person asked for it.
319
+ function activateSession(session) {
320
+ activationSeq += 1;
321
+ activation = { seq: activationSeq, id: session.id, at: Date.now() };
322
+ activeSessionId = session.id;
323
+ }
324
+
124
325
  /** @param {import('ws').WebSocket} ws @param {string} code @param {string} message @param {string|null} id */
125
326
  function wsError(ws, code, message, id) {
126
327
  if (ws.readyState === WebSocket.OPEN) {
@@ -153,14 +354,107 @@ function sendToSession(session, payload) {
153
354
 
154
355
  // ─── Output ring buffer ──────────────────────────────────────────────────────
155
356
 
156
- /** Append PTY output to the session ring, evicting from the head when capped. */
357
+ /** Where the next line starts at or after `from`; `from` when no line ends
358
+ * within RESUME_LINE_TRIM_MAX. */
359
+ function lineStartAt(text, from) {
360
+ const end = text.indexOf('\n', from);
361
+ return end >= 0 && end < from + RESUME_LINE_TRIM_MAX ? end + 1 : from;
362
+ }
363
+
364
+ /**
365
+ * Forget the resize markers that fell out of the ring. Of those before the
366
+ * retained output only the last still matters: it is the width that output
367
+ * starts at. Markers are recorded in order, so this stops at that one.
368
+ * @param {Session} session
369
+ * @param {number} start Offset, from the shell's first character, of the
370
+ * first retained character.
371
+ */
372
+ function pruneResizeMarkers(session, start) {
373
+ const markers = session.resizeMarkers;
374
+ let drop = 0;
375
+ while (drop < markers.length - 1 && markers[drop + 1].at <= start) drop += 1;
376
+ if (drop > 0) markers.splice(0, drop);
377
+ }
378
+
379
+ /**
380
+ * Append PTY output to the session's ring: the most recent output, at most
381
+ * RESUME_BUFFER_MAX characters, kept for every rejoin.
382
+ *
383
+ * The terminal engine delivers small pieces (measured 2026-11-29: 30 to 60
384
+ * characters is typical and none is longer than 1024), so pieces are gathered
385
+ * into blocks and blocks are evicted in batches. Buffering is then a
386
+ * constant-time append per piece. The ring used to be one string cut on every
387
+ * append once full, about a tenth of a millisecond a time, which held a busy
388
+ * shell nobody was watching to about ten thousand pieces a second; and a rejoin
389
+ * used to empty it, so a second rejoin showed only what was printed since.
390
+ *
391
+ * Offsets in `outputChars` and `resizeMarkers` count from the shell's first
392
+ * character and never reset. The retained output is the tail that ends at
393
+ * `outputChars` and is `outputBuffered` long, and always begins at a line
394
+ * start.
395
+ * @param {Session} session
396
+ * @param {string} data
397
+ */
157
398
  function bufferOutput(session, data) {
158
- session.outputBuffer += data;
159
- if (session.outputBuffer.length > RESUME_BUFFER_MAX) {
160
- // Keep only the tail beyond the cap so the most recent output survives.
161
- const over = session.outputBuffer.length - RESUME_BUFFER_MAX;
162
- session.outputBuffer = session.outputBuffer.slice(over);
399
+ const buffered = session.outputBuffered + data.length;
400
+ session.outputBuffered = buffered;
401
+ session.outputPieces.push(data);
402
+ session.outputPending += data.length;
403
+ if (session.outputPending >= RESUME_BLOCK || buffered > RESUME_BUFFER_MAX) {
404
+ session.outputBlocks.push(session.outputPieces.join(''));
405
+ session.outputPieces.length = 0;
406
+ session.outputPending = 0;
407
+ }
408
+ if (buffered <= RESUME_BUFFER_MAX) return;
409
+
410
+ // Over the cap. Whole blocks go first, until less than a block above the low
411
+ // mark, so the next eviction is that far away. One block is always kept.
412
+ const low = RESUME_BUFFER_MAX - RESUME_BUFFER_EVICTION;
413
+ const blocks = session.outputBlocks;
414
+ let kept = buffered;
415
+ while (blocks.length > 1 && kept - blocks[0].length >= low) {
416
+ kept -= blocks[0].length;
417
+ blocks.shift();
163
418
  }
419
+ // The head block now begins part way through a line. Start where the next
420
+ // one begins, so a rejoin does not open on a fragment of a line or inside an
421
+ // escape sequence. A lone low surrogate is never left at the head.
422
+ const head = blocks[0];
423
+ const from = Math.min(head.length, Math.max(0, kept - low));
424
+ let cut = Math.min(head.length, lineStartAt(head, from));
425
+ if (cut < head.length) {
426
+ const code = head.charCodeAt(cut);
427
+ if (code >= 0xDC00 && code <= 0xDFFF) cut += 1;
428
+ }
429
+ if (cut > 0) {
430
+ blocks[0] = head.slice(cut);
431
+ kept -= cut;
432
+ }
433
+ session.outputBuffered = kept;
434
+ pruneResizeMarkers(session, session.outputChars - kept);
435
+ }
436
+
437
+ /** The retained output of `session` as one string: the tail of what it printed. */
438
+ function bufferedOutput(session) {
439
+ const blocks = session.outputPieces.length
440
+ ? session.outputBlocks.concat([session.outputPieces.join('')])
441
+ : session.outputBlocks;
442
+ return blocks.length === 1 ? blocks[0] : blocks.join('');
443
+ }
444
+
445
+ /**
446
+ * `raw` without the side-effecting instructions (see SIDE_EFFECT_SEQUENCE) of
447
+ * the part that was shown before. The rest is replayed as it was, so an
448
+ * instruction in output nobody has seen yet still acts when it is first shown.
449
+ * @param {Session} session
450
+ * @param {string} raw The retained output
451
+ * @param {number} rawStart Where `raw` begins, counted like `outputChars`
452
+ * @returns {string}
453
+ */
454
+ function withoutRepeatedEffects(session, raw, rawStart) {
455
+ const shown = session.shownUpTo - rawStart;
456
+ if (shown <= 0) return raw;
457
+ return raw.replace(SIDE_EFFECT_SEQUENCE, (sequence, at) => (at < shown ? '' : sequence));
164
458
  }
165
459
 
166
460
  // ─── PTY helpers ────────────────────────────────────────────────────────────
@@ -179,33 +473,62 @@ function killPty(ptyProcess, id) {
179
473
 
180
474
  // ─── Session lifecycle ───────────────────────────────────────────────────────
181
475
 
182
- /** Clear the resume grace timer for a session, if any. */
183
- function clearGraceTimer(session) {
184
- const gt = graceTimers.get(session.id);
185
- if (gt) { clearTimeout(gt); graceTimers.delete(session.id); }
476
+ /**
477
+ * A viewer stopped looking at `session`. The shell is the person's, not the
478
+ * window's: it keeps running with nobody attached until it is closed. Only
479
+ * when a session has no viewer at all does the heartbeat stop.
480
+ * @returns {boolean} true once no viewer is left
481
+ */
482
+ function releaseSocket(session, ws) {
483
+ if (!session.sockets) session.sockets = new Set(session.ws ? [session.ws] : []);
484
+ session.sockets.delete(ws);
485
+ if (session.sockets.size > 0) {
486
+ // Other windows still hold this shell: hand ownership to one of them.
487
+ if (session.ws === ws || !session.ws) {
488
+ session.ws = [...session.sockets].find((socket) => socket.readyState === WebSocket.OPEN) || null;
489
+ }
490
+ return false;
491
+ }
492
+ session.ws = null;
493
+ session.sessionActive = false;
494
+ stopHeartbeat(session);
495
+ return true;
186
496
  }
187
497
 
188
- function cleanupSession(session) {
498
+ /**
499
+ * End a session for good: tell its viewers why, stop the shell, forget it,
500
+ * and tell every other page the list changed. Safe to call more than once.
501
+ * @param {Session} session
502
+ * @param {'closed'|'exited'|'error'} reason Who ended it: a person or agent,
503
+ * the shell itself, or a shell that would not start.
504
+ */
505
+ function cleanupSession(session, reason = 'closed') {
189
506
  const { id, ptyProcess } = session;
190
- info(id, 'Cleaning up session');
507
+ if (!activeSessions.has(id)) return;
508
+ info(id, 'Cleaning up session', { reason });
191
509
 
192
510
  for (const socket of session.sockets || []) socket.voice = null;
193
- clearGraceTimer(session);
511
+ // Said before the socket closes, so a page can tell "this session was
512
+ // ended" from "the connection dropped" and never reconnect into a new shell.
513
+ // The list still includes this session; the page knows which one ended.
514
+ sendToSession(session, { type: 'session-ended', sessionId: id, reason, ...sessionState() });
194
515
 
195
- const pt = pingTimers.get(id);
196
- clearInterval(pt);
197
- pingTimers.delete(id);
198
- const po = pongTimers.get(id);
199
- clearTimeout(po);
200
- pongTimers.delete(id);
516
+ stopHeartbeat(session);
201
517
 
518
+ session.sessionActive = false;
202
519
  if (ptyProcess) { killPty(ptyProcess, id); session.ptyProcess = undefined; }
203
520
  for (const socket of session.sockets || []) {
204
521
  try { socket.close(1000, 'session ended'); } catch (_) { /* already gone */ }
205
522
  }
206
523
  if (session.sockets) session.sockets.clear();
524
+ session.ws = null;
207
525
  activeSessions.delete(id);
208
- info(id, 'Session cleaned up');
526
+ if (activeSessionId === id) {
527
+ const next = mostRecentlyViewed(id);
528
+ activeSessionId = next ? next.id : null;
529
+ }
530
+ info(id, 'Session cleaned up', { reason });
531
+ if (session.listed) broadcastSessions();
209
532
  }
210
533
 
211
534
  /** @param {Session} session */
@@ -256,7 +579,10 @@ function wirePtyToSession(ptyProcess, session) {
256
579
  // Always buffer so a subsequent resume can replay this output.
257
580
  bufferOutput(session, data);
258
581
  if (!session.sessionActive) return;
259
- sendToSession(session, { type: 'output', data });
582
+ if (sendToSession(session, { type: 'output', data })) {
583
+ // Shown live, so whatever it instructs the page to do has been done.
584
+ session.shownUpTo = session.outputChars;
585
+ }
260
586
  });
261
587
 
262
588
  ptyProcess.once('exit', (code) => {
@@ -270,10 +596,10 @@ function wirePtyToSession(ptyProcess, session) {
270
596
  // If detached when the shell exits, there is nobody to receive a respawn —
271
597
  // tear the session down.
272
598
  if (!session.ws || session.ws.readyState !== WebSocket.OPEN) {
273
- cleanupSession(session);
599
+ cleanupSession(session, 'exited');
274
600
  return;
275
601
  }
276
- if (!session.sessionActive) { cleanupSession(session); return; }
602
+ if (!session.sessionActive) { cleanupSession(session, 'exited'); return; }
277
603
 
278
604
  // Stop rather than loop. Say what happened and what to check.
279
605
  if (session.rapidExits >= MAX_RAPID_RESPAWNS) {
@@ -281,7 +607,7 @@ function wirePtyToSession(ptyProcess, session) {
281
607
  'The shell exited immediately ' + session.rapidExits + ' times in a row, so it was '
282
608
  + 'not restarted again. Check $SHELL (currently ' + resolveShell()
283
609
  + ') and your shell profile.', id);
284
- cleanupSession(session);
610
+ cleanupSession(session, 'error');
285
611
  return;
286
612
  }
287
613
 
@@ -293,7 +619,7 @@ function wirePtyToSession(ptyProcess, session) {
293
619
  if (session.sessionActive && session.ws && session.ws.readyState === WebSocket.OPEN) {
294
620
  spawnShell(session, session.shellCwd);
295
621
  } else {
296
- cleanupSession(session);
622
+ cleanupSession(session, 'exited');
297
623
  }
298
624
  }, delay);
299
625
  });
@@ -301,16 +627,18 @@ function wirePtyToSession(ptyProcess, session) {
301
627
  ptyProcess.on('error', (err) => {
302
628
  error(id, 'PTY error', { err: err.message || String(err) });
303
629
  if (session.ws) wsError(session.ws, 'PROCESS_ERROR', `Process error: ${err.message || String(err)}`, id);
304
- cleanupSession(session);
630
+ cleanupSession(session, 'error');
305
631
  });
306
632
  }
307
633
 
308
634
  // ─── Shell spawn helper ─────────────────────────────────────────────────────
309
635
 
310
636
  /**
311
- * Spawn the user's default shell into the session and wire it up.
637
+ * Spawn the user's default shell into the session and wire it up. The first
638
+ * shell is what makes a session real: it is listed and named from then on.
312
639
  * @param {Session} session
313
640
  * @param {string} [cwd]
641
+ * @returns {boolean} false when the shell could not be started
314
642
  */
315
643
  function spawnShell(session, cwd) {
316
644
  const { id } = session;
@@ -324,13 +652,21 @@ function spawnShell(session, cwd) {
324
652
  const shell = resolveShell();
325
653
 
326
654
  session.shellCwd = workingDir;
655
+ session.command = session.command || shell;
327
656
 
328
657
  let ptyProcess;
329
658
  try {
330
659
  ptyProcess = pty.spawn(shell, ['-l'], { name: 'xterm-256color', cols, rows, cwd: workingDir, env: ptyEnv });
331
660
  } catch (e) {
332
661
  error(id, 'shell spawn failed', { err: e.message });
333
- return;
662
+ return false;
663
+ }
664
+
665
+ if (!session.listed) {
666
+ session.listed = true;
667
+ sessionCounter += 1;
668
+ session.createdAt = Date.now();
669
+ if (!session.name) session.name = `Shell ${sessionCounter}`;
334
670
  }
335
671
 
336
672
  session.ptyProcess = ptyProcess;
@@ -347,6 +683,7 @@ function spawnShell(session, cwd) {
347
683
  try { ptyProcess.write(queued); }
348
684
  catch (e) { error(id, 'pending input flush failed', { err: e.message }); }
349
685
  }
686
+ return true;
350
687
  }
351
688
 
352
689
  // ─── Resume: re-attach a new WebSocket to an existing session ────────────────
@@ -362,11 +699,18 @@ function spawnShell(session, cwd) {
362
699
  * @param {Session} target
363
700
  * @param {import('ws').WebSocket} ws
364
701
  * @param {{ cols: number, rows: number }} dims
365
- * @param {Session} placeholder The throwaway connection session to retire.
702
+ * @param {Session} previous What this socket was attached to: the throwaway
703
+ * record a connection starts as, or a real session it is being re-pointed
704
+ * away from (whose shell must keep running).
366
705
  */
367
- function resumeSession(target, ws, dims, placeholder) {
706
+ function resumeSession(target, ws, dims, previous) {
368
707
  const { id } = target;
369
- const bufferedBytes = target.outputBuffer ? target.outputBuffer.length : 0;
708
+ // The recent output is replayed to this page and kept. The shell will be
709
+ // rejoined again (a switch, a reload, a window opened anew) and must show the
710
+ // same thing each time. It used to be handed over and cleared here, so the
711
+ // second rejoin found nothing but what was printed since the first, which
712
+ // read as "my session is gone".
713
+ const raw = bufferedOutput(target);
370
714
  // The buffer was produced at the old PTY width. Replay it into an xterm set
371
715
  // to those dimensions, then fit the client to the new viewport. Replaying
372
716
  // old cursor-addressed output at a new width splits words and loses lines.
@@ -377,9 +721,14 @@ function resumeSession(target, ws, dims, placeholder) {
377
721
  // Use a control-code-free transcript of the final screen text instead.
378
722
  const transcript = target.widthChanged || replayCols !== dims.cols || replayRows !== dims.rows;
379
723
 
380
- // Retire the placeholder connection session (the one created at connect).
381
- activeSessions.delete(placeholder.id);
382
- stopHeartbeat(placeholder);
724
+ // Retire what the socket was attached to. A placeholder is simply dropped;
725
+ // a real session only loses this viewer and keeps its shell.
726
+ if (previous.listed) {
727
+ releaseSocket(previous, ws);
728
+ } else {
729
+ activeSessions.delete(previous.id);
730
+ stopHeartbeat(previous);
731
+ }
383
732
 
384
733
  // Adopt the new connection onto the target session.
385
734
  target.ws = ws;
@@ -388,9 +737,6 @@ function resumeSession(target, ws, dims, placeholder) {
388
737
  target.sockets.add(ws);
389
738
  ws.__sessionRef = target; // re-point handlers at the resumed session
390
739
 
391
- // Cancel the resume grace countdown — we're live again.
392
- clearGraceTimer(target);
393
-
394
740
  // Restart heartbeat for the new socket.
395
741
  startHeartbeat(target);
396
742
 
@@ -402,18 +748,20 @@ function resumeSession(target, ws, dims, placeholder) {
402
748
  sessionId: id,
403
749
  command: target.command || resolveShell(),
404
750
  cwd: target.shellCwd,
751
+ name: target.name,
752
+ epoch: SESSION_EPOCH,
405
753
  resumed: true,
406
754
  transcript,
407
755
  cols: replayCols,
408
756
  rows: replayRows
409
757
  });
410
758
 
411
- if (target.outputBuffer) {
412
- const raw = target.outputBuffer;
413
- target.outputBuffer = '';
759
+ if (raw) {
760
+ // Markers count from the shell's first character; the retained output
761
+ // begins this far in.
762
+ const rawStart = target.outputChars - raw.length;
414
763
  let buf = raw;
415
764
  if (transcript) {
416
- const rawStart = Math.max(0, target.outputChars - raw.length);
417
765
  let initial = { cols: replayCols };
418
766
  const segments = [];
419
767
  for (const marker of target.resizeMarkers) {
@@ -424,7 +772,14 @@ function resumeSession(target, ws, dims, placeholder) {
424
772
  }
425
773
  segments.unshift({ at: 0, cols: initial.cols });
426
774
  buf = replayTranscript(raw, segments).replace(/\n/g, '\r\n');
775
+ } else {
776
+ // A transcript has no control codes. A raw replay keeps the colours and
777
+ // cursor addressing, and with them any instruction to set the clipboard
778
+ // or raise a notification, which must not act a second time.
779
+ buf = withoutRepeatedEffects(target, raw, rawStart);
427
780
  }
781
+ // Shown now, either way.
782
+ target.shownUpTo = target.outputChars;
428
783
  // Send in chunks to avoid a single oversized WS frame.
429
784
  const CHUNK = 16 * 1024;
430
785
  for (let i = 0; i < buf.length; i += CHUNK) {
@@ -453,7 +808,7 @@ function resumeSession(target, ws, dims, placeholder) {
453
808
  catch (e) { warn(id, 'resume resize failed', { err: e.message }); }
454
809
  }
455
810
 
456
- info(id, 'Session resumed', { bufferedBytes, replayCols, replayRows, cols: dims.cols, rows: dims.rows });
811
+ info(id, 'Session resumed', { replayChars: raw.length, transcript, replayCols, replayRows, cols: dims.cols, rows: dims.rows });
457
812
  }
458
813
 
459
814
  // ─── Speech-to-text helpers ─────────────────────────────────────────────────
@@ -697,6 +1052,15 @@ function finalizeVoice(session, ws) {
697
1052
 
698
1053
  // ─── Message dispatcher ─────────────────────────────────────────────────────
699
1054
 
1055
+ /** Answer a page command that carried a requestId, so it can show the outcome where it was asked. */
1056
+ function commandResult(ws, data, outcome) {
1057
+ if (!data || data.requestId == null) return;
1058
+ const reply = { type: 'result', requestId: data.requestId, ok: outcome.ok };
1059
+ if (!outcome.ok) { reply.code = outcome.code; reply.error = outcome.error; }
1060
+ else if (outcome.name !== undefined) reply.name = outcome.name;
1061
+ sendToSocket(ws, reply);
1062
+ }
1063
+
700
1064
  /** @param {Session} session @param {import('ws').WebSocket} ws @param {object} data */
701
1065
  function handleMessage(session, ws, data) {
702
1066
  if (!session.sessionActive && data.type !== 'resume' && data.type !== 'shell') return;
@@ -719,26 +1083,62 @@ function handleMessage(session, ws, data) {
719
1083
  wsError(ws, 'SESSION_LIMIT', 'Maximum concurrent sessions reached', session.id);
720
1084
  break;
721
1085
  }
722
- spawnShell(session, data.cwd || process.env.HOME || os.homedir());
1086
+ if (!session.listed) session.createdBy = data.createdBy === 'agent' ? 'agent' : 'human';
1087
+ if (!spawnShell(session, data.cwd || process.env.HOME || os.homedir())) {
1088
+ wsError(ws, 'SHELL_SPAWN_FAILED', 'The shell could not be started.', session.id);
1089
+ break;
1090
+ }
1091
+ session.lastViewedAt = Date.now();
1092
+ activeSessionId = session.id;
723
1093
  if (ws.readyState === WebSocket.OPEN) {
724
- ws.send(JSON.stringify({ type: 'ready', sessionId: session.id, command: resolveShell(), cwd: session.shellCwd }));
1094
+ ws.send(JSON.stringify({
1095
+ type: 'ready', sessionId: session.id, command: resolveShell(), cwd: session.shellCwd,
1096
+ name: session.name, epoch: SESSION_EPOCH
1097
+ }));
1098
+ sendSessionState(ws);
725
1099
  }
1100
+ broadcastSessions(ws);
726
1101
  break;
727
1102
  }
728
1103
  case 'resume': {
729
1104
  // Look up the requested session and adopt it onto this connection.
730
1105
  const targetId = String(data.sessionId || '');
731
1106
  const target = activeSessions.get(targetId);
732
- if (target && target.ptyProcess && !target.processExited) {
1107
+ if (target && target.listed) {
733
1108
  resumeSession(target, ws, clampDims(data.cols, data.rows), session);
1109
+ target.lastViewedAt = Date.now();
1110
+ activeSessionId = target.id;
1111
+ sendSessionState(ws);
1112
+ broadcastSessions(ws);
734
1113
  } else {
735
1114
  info(session.id, 'Resume failed — target not resumable', { targetId });
1115
+ // The page decides what to do next from the real list, and says so.
736
1116
  if (ws.readyState === WebSocket.OPEN) {
737
- ws.send(JSON.stringify({ type: 'resume-failed', sessionId: targetId, reason: 'not-found' }));
1117
+ ws.send(JSON.stringify({ type: 'resume-failed', sessionId: targetId, reason: 'not-found', ...sessionState() }));
738
1118
  }
739
1119
  }
740
1120
  break;
741
1121
  }
1122
+ case 'sessions': {
1123
+ sendSessionState(ws);
1124
+ break;
1125
+ }
1126
+ case 'rename': {
1127
+ const target = data.sessionId ? activeSessions.get(String(data.sessionId)) : session;
1128
+ const refused = (code, error) => commandResult(ws, data, { ok: false, code, error });
1129
+ if (!target || !target.listed) { refused('SESSION_NOT_FOUND', 'That session is no longer available.'); break; }
1130
+ const checked = validSessionName(data.name);
1131
+ if (!checked.ok) { refused('INVALID_NAME', `That name cannot be used: ${checked.error}.`); break; }
1132
+ if (nameInUse(checked.value, target.id)) {
1133
+ refused('NAME_IN_USE', `Another session is already named “${checked.value}”.`);
1134
+ break;
1135
+ }
1136
+ target.name = checked.value;
1137
+ info(target.id, 'Session renamed', { name: target.name });
1138
+ commandResult(ws, data, { ok: true, name: target.name });
1139
+ broadcastSessions();
1140
+ break;
1141
+ }
742
1142
  case 'input': {
743
1143
  if (typeof data.data !== 'string') break;
744
1144
  if (session.ptyProcess && !session.processExited) {
@@ -813,9 +1213,16 @@ function handleMessage(session, ws, data) {
813
1213
  break;
814
1214
  }
815
1215
  case 'close': {
816
- // Explicit user-initiated close → full teardown of this session.
817
- session.userClosed = true;
818
- if (session.ptyProcess && !session.processExited) cleanupSession(session);
1216
+ // Explicit close → full teardown. With a sessionId it ends another
1217
+ // session this page is not viewing; without one it ends its own.
1218
+ const target = data.sessionId ? activeSessions.get(String(data.sessionId)) : session;
1219
+ if (!target || !target.listed) {
1220
+ commandResult(ws, data, { ok: false, code: 'SESSION_NOT_FOUND', error: 'That session is no longer available.' });
1221
+ break;
1222
+ }
1223
+ target.userClosed = true;
1224
+ commandResult(ws, data, { ok: true });
1225
+ cleanupSession(target, 'closed');
819
1226
  break;
820
1227
  }
821
1228
  case 'ping': {
@@ -880,36 +1287,19 @@ function bindWsToSession(ws, session) {
880
1287
  activeSessions.delete(s.id);
881
1288
  return;
882
1289
  }
883
- if (!s.sockets) s.sockets = new Set(s.ws ? [s.ws] : []);
884
- s.sockets.delete(ws);
885
1290
  // Other windows still hold this shell: keep it live and hand ownership to
886
1291
  // one of them. Closing one window must not detach the rest.
887
- if (s.sockets.size > 0) {
888
- if (s.ws === ws || !s.ws) {
889
- s.ws = [...s.sockets].find((socket) => socket.readyState === WebSocket.OPEN) || null;
890
- }
891
- return;
892
- }
893
- // A socket that was superseded by a newer resume must not detach the new
894
- // window or start a grace timer underneath it.
895
- if (s.ws && s.ws !== ws) return;
896
- // Unexpected drop: keep the PTY alive and start the resume grace window.
1292
+ if (!releaseSocket(s, ws)) return;
897
1293
  if (s.ptyProcess && !s.processExited) {
898
- s.ws = null;
899
- s.sessionActive = false;
900
- stopHeartbeat(s);
901
- if (!graceTimers.has(s.id)) {
902
- info(s.id, 'Session entering resume grace', { graceMs: RESUME_GRACE_MS });
903
- const gt = setTimeout(() => {
904
- warn(s.id, 'Resume grace expired — cleaning up detached session');
905
- cleanupSession(s);
906
- }, RESUME_GRACE_MS);
907
- graceTimers.set(s.id, gt);
908
- }
1294
+ // The window went away, not the session. The shell keeps running, listed,
1295
+ // until it is closed or the app stops.
1296
+ info(s.id, 'Session detached; shell keeps running');
909
1297
  } else {
910
- // No live PTY to preserve — just drop the placeholder.
1298
+ // No live shell to preserve — just drop the placeholder.
911
1299
  activeSessions.delete(s.id);
1300
+ return;
912
1301
  }
1302
+ if (s.listed) broadcastSessions();
913
1303
  });
914
1304
 
915
1305
  ws.on('error', (err) => {
@@ -943,10 +1333,14 @@ const OWNER_CAPABILITY = crypto.randomBytes(32).toString('hex');
943
1333
  app.use((req, res, next) => {
944
1334
  const ownerPage = req.method === 'GET' &&
945
1335
  (req.path === '/' || req.path === '/index.html' || req.path === '/panes' || req.path === '/panes.html');
946
- // Node's fetch (used by the integration tests) cannot send Sec-Fetch-Mode;
947
- // a document navigation also identifies itself with Accept: text/html.
948
- const navigates = req.get('Sec-Fetch-Mode') === 'navigate' ||
949
- String(req.get('Accept') || '').includes('text/html');
1336
+ // A navigation is known by the one detail a browser sets on every request
1337
+ // and nothing else sends unless it sets it on purpose: Sec-Fetch-Mode.
1338
+ // A plain HTTP client that merely asks for the page with "Accept: text/html"
1339
+ // gets the page and no cookie. Sec-Fetch-Dest is deliberately not required:
1340
+ // a document opened through a service worker's fetch() arrives as a
1341
+ // navigation with dest "empty" (measured in Chrome on the terminal surface's
1342
+ // second load), and requiring "document" would lock the person out of it.
1343
+ const navigates = req.get('Sec-Fetch-Mode') === 'navigate';
950
1344
  if (ownerPage && !req.get('Authorization') && navigates) {
951
1345
  res.cookie(OWNER_COOKIE, OWNER_CAPABILITY, {
952
1346
  httpOnly: true,
@@ -1009,7 +1403,9 @@ app.get('/health', (req, res) => {
1009
1403
  // cannot start instead of failing later with a stack trace.
1010
1404
  let browser = { engine: 'unknown' };
1011
1405
  try { browser = browserWorkspace.engineStatus(); } catch (_) { /* reported as unknown */ }
1012
- res.json({ status: 'ok', sessions: activeSessions.size, browser });
1406
+ // The shells a person can see in the row, not the short-lived record every
1407
+ // connection starts as.
1408
+ res.json({ status: 'ok', version: APP_VERSION, sessions: listedSessions().length, browser });
1013
1409
  });
1014
1410
  app.get('/api/voice/settings', (req, res) => {
1015
1411
  res.json(voiceSettingsPayload());
@@ -1026,27 +1422,110 @@ app.put('/api/voice/settings', (req, res) => {
1026
1422
  }
1027
1423
  res.json({ ...checked.value, resolved: resolveVoiceCommand(checked.value.command) });
1028
1424
  });
1029
- app.get('/admin/sessions', (req, res) => {
1030
- const sessions = Array.from(activeSessions.values()).map((s) => {
1031
- const resumable = !s.ws && !!s.ptyProcess && !s.processExited && graceTimers.has(s.id);
1032
- return {
1033
- id: s.id, command: s.command || resolveShell(),
1034
- startedAt: s.startedAt || null, durationMs: s.startedAt ? Date.now() - s.startedAt : null,
1035
- processExited: s.processExited,
1036
- attached: !!s.ws,
1037
- resumable,
1038
- bufferedBytes: s.outputBuffer ? s.outputBuffer.length : 0
1039
- };
1425
+ // ── Shell sessions for agents ────────────────────────────────────────────────
1426
+ // Same token, caller and error shapes as /api/panes. `auth` has already read
1427
+ // who is asking from the key: 'owner' is the person's page with its own key,
1428
+ // 'agent' is anything holding the workspace token. The person's page drives
1429
+ // the same actions over its own WebSocket; this is the agent's door.
1430
+ const sessionAuth = paneWorkspace.auth;
1431
+ const sessionRoute = paneWorkspace.route;
1432
+ // The owner is the owner's page; anything else is an agent.
1433
+ const sessionViewer = (req) => (req.caller === 'owner' ? 'owner' : 'agent');
1434
+ const refuse = (status, code, message, extra = {}) => {
1435
+ throw Object.assign(new Error(message), { status, body: { error: message, code, ...extra } });
1436
+ };
1437
+ function liveSession(id) {
1438
+ const session = activeSessions.get(String(id || ''));
1439
+ if (!session || !session.listed) refuse(404, 'SESSION_NOT_FOUND', 'Session not found.');
1440
+ return session;
1441
+ }
1442
+ // A shell belongs to whoever started it, as a pane does. Renaming, showing
1443
+ // and ending a shell the owner started are the owner's alone, whatever an
1444
+ // agent has been given; on a shell an agent started, any agent may.
1445
+ function requireSessionOwner(session, caller, verb) {
1446
+ if (caller === 'owner' || session.createdBy === 'agent') return;
1447
+ refuse(403, 'OWNER_ONLY', `The owner started this shell, so only the owner can ${verb} it.`);
1448
+ }
1449
+ function checkedName(value, exceptId) {
1450
+ const checked = validSessionName(value);
1451
+ if (!checked.ok) refuse(400, 'INVALID_NAME', `name cannot be used: ${checked.error}.`);
1452
+ if (nameInUse(checked.value, exceptId)) {
1453
+ refuse(409, 'NAME_IN_USE', `Another session is already named “${checked.value}”.`);
1454
+ }
1455
+ return checked.value;
1456
+ }
1457
+
1458
+ // The shells that exist right now, in row order, as the caller may see them.
1459
+ app.get('/api/sessions', sessionAuth, sessionRoute(async (req, res) => {
1460
+ res.json(sessionState(sessionViewer(req)));
1461
+ }));
1462
+
1463
+ // Start a shell nobody is viewing yet. It appears in the person's row and
1464
+ // does not change which shell the person is looking at, unless `activate` is
1465
+ // asked for.
1466
+ app.post('/api/sessions', sessionAuth, sessionRoute(async (req, res) => {
1467
+ const body = req.body || {};
1468
+ // The key that asks decides whose shell it is. createdBy in the body is
1469
+ // ignored, as it is for panes: it was how a client described itself, and
1470
+ // trusting it let an agent label a shell as the owner's.
1471
+ const createdBy = sessionViewer(req) === 'owner' ? 'human' : 'agent';
1472
+ if (countRealShells() >= MAX_CONCURRENT_SESSIONS) {
1473
+ // An agent that holds no shell it may close cannot make room itself, and
1474
+ // must be told why rather than be sent looking for something to close.
1475
+ if (createdBy === 'agent' && !listedSessions().some((s) => s.createdBy === 'agent')) {
1476
+ const ownerStarted = listedSessions().length;
1477
+ refuse(409, 'SESSION_LIMIT',
1478
+ `All ${MAX_CONCURRENT_SESSIONS} sessions are in use and the owner started all ${ownerStarted} of them, so there is none an agent may close. Ask the owner to close one.`,
1479
+ { max: MAX_CONCURRENT_SESSIONS, ownerStarted });
1480
+ }
1481
+ refuse(409, 'SESSION_LIMIT', 'Close a session before opening another.', { max: MAX_CONCURRENT_SESSIONS });
1482
+ }
1483
+ const name = body.name === undefined || body.name === null || body.name === '' ? '' : checkedName(body.name);
1484
+ let cwd;
1485
+ if (body.cwd !== undefined && body.cwd !== null && body.cwd !== '') {
1486
+ cwd = String(body.cwd);
1487
+ let stat = null;
1488
+ try { stat = fs.statSync(cwd); } catch (_) { /* refused below */ }
1489
+ if (!stat || !stat.isDirectory()) refuse(400, 'INVALID_CWD', 'cwd must be an existing directory.');
1490
+ }
1491
+ const session = createSession({
1492
+ cwd, name,
1493
+ createdBy,
1494
+ activate: body.activate === true
1040
1495
  });
1041
- const resumableCount = sessions.filter((s) => s.resumable).length;
1042
- res.json({ active: activeSessions.size, max: MAX_CONCURRENT_SESSIONS, resumableCount, sessions });
1043
- });
1044
- app.post('/admin/sessions/:id/kill', (req, res) => {
1045
- const s = activeSessions.get(req.params.id);
1046
- if (!s) { res.status(404).json({ error: 'Session not found' }); return; }
1047
- cleanupSession(s);
1048
- res.json({ ok: true, id: req.params.id });
1049
- });
1496
+ res.json(serializeSession(session));
1497
+ }));
1498
+
1499
+ // Give a shell a name the person can read. Names are unique.
1500
+ app.patch('/api/sessions/:id', sessionAuth, sessionRoute(async (req, res) => {
1501
+ const session = liveSession(req.params.id);
1502
+ requireSessionOwner(session, req.caller, 'rename');
1503
+ session.name = checkedName((req.body || {}).name, session.id);
1504
+ info(session.id, 'Session renamed', { name: session.name, by: sessionViewer(req) });
1505
+ broadcastSessions();
1506
+ res.json(serializeSession(session));
1507
+ }));
1508
+
1509
+ // The one action that moves the person's view: every open terminal page shows
1510
+ // this shell. An agent uses it only when the person asked to see that shell.
1511
+ app.post('/api/sessions/:id/activate', sessionAuth, sessionRoute(async (req, res) => {
1512
+ const session = liveSession(req.params.id);
1513
+ requireSessionOwner(session, req.caller, 'show');
1514
+ activateSession(session);
1515
+ const windows = broadcastSessions();
1516
+ info(session.id, 'Session activated', { by: sessionViewer(req), windows });
1517
+ res.json({ activated: windows > 0, windows, session: serializeSession(session) });
1518
+ }));
1519
+
1520
+ // End a shell and its shell process. A page that was viewing it moves to
1521
+ // another one. It cannot be taken back.
1522
+ app.delete('/api/sessions/:id', sessionAuth, sessionRoute(async (req, res) => {
1523
+ const session = liveSession(req.params.id);
1524
+ requireSessionOwner(session, req.caller, 'close');
1525
+ session.userClosed = true;
1526
+ cleanupSession(session, 'closed');
1527
+ res.json({ closed: true, ...sessionState(sessionViewer(req)) });
1528
+ }));
1050
1529
 
1051
1530
  // ─── HTTP + WebSocket server ────────────────────────────────────────────────
1052
1531
 
@@ -1056,28 +1535,9 @@ const wss = new WebSocket.Server({ server, verifyClient: ({ req }) => isTrustedR
1056
1535
  wss.on('connection', (ws) => {
1057
1536
  // Each connection starts as a fresh placeholder session. It becomes "real"
1058
1537
  // when the client sends `shell`, or it adopts an existing session via `resume`.
1059
- const sessionId = uuidv4();
1060
- /** @type {Session} */
1061
- const session = {
1062
- id: sessionId,
1063
- command: null,
1064
- ptyProcess: undefined,
1065
- sessionActive: true,
1066
- processExited: false,
1067
- ws,
1068
- startedAt: Date.now(),
1069
- outputBuffer: '',
1070
- lastCols: 120,
1071
- lastRows: 40,
1072
- lastDataCols: null,
1073
- lastDataRows: null,
1074
- widthChanged: false,
1075
- outputChars: 0,
1076
- resizeMarkers: [],
1077
- sockets: new Set([ws]),
1078
- userClosed: false
1079
- };
1080
- activeSessions.set(sessionId, session);
1538
+ const session = newSessionRecord(ws);
1539
+ session.startedAt = Date.now();
1540
+ activeSessions.set(session.id, session);
1081
1541
 
1082
1542
  bindWsToSession(ws, session);
1083
1543
  startHeartbeat(session);
@@ -1092,7 +1552,7 @@ async function shutdown(signal, exitCode = 0) {
1092
1552
  await paneWorkspace.closeAll().catch(err => error(null, 'Pane shutdown failed', {err:err.message}));
1093
1553
  await closeBrowsers().catch(err => error(null, 'Browser shutdown failed', {err:err.message}));
1094
1554
  const promises = Array.from(activeSessions.values()).map((s) => {
1095
- clearGraceTimer(s);
1555
+ // A stopped app ends every shell; none of them survives the process.
1096
1556
  if (s.ptyProcess) killPty(s.ptyProcess, s.id);
1097
1557
  activeSessions.delete(s.id);
1098
1558
  return new Promise((r) => setTimeout(r, KILL_GRACE_MS + 100));