tmux-ide 2.9.24 → 2.9.25

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 (56) hide show
  1. package/bin/cli.js +1352 -350
  2. package/package.json +4 -2
  3. package/packages/contracts/src/pane-stream.ts +53 -0
  4. package/packages/daemon/dist/command-center/discovery.js +24 -5
  5. package/packages/daemon/dist/command-center/server.js +81 -75
  6. package/packages/daemon/dist/doctor.js +46 -10
  7. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  8. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  9. package/packages/daemon/dist/lib/daemon-embed.js +6 -0
  10. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  11. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  12. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  13. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  14. package/packages/daemon/dist/lib/update-check.js +18 -0
  15. package/packages/daemon/dist/lib/update-daemon-outcome.js +31 -0
  16. package/packages/daemon/dist/lib/update.js +39 -14
  17. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  19. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  20. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  21. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  22. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  23. package/packages/daemon/dist/terminal/mirror/session-channel.js +25 -1
  24. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +741 -208
  25. package/packages/daemon/dist/terminal/session-runtime/registry.js +24 -2
  26. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +77 -2
  27. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  28. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  29. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  30. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  31. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  32. package/packages/daemon/src/command-center/discovery.ts +24 -4
  33. package/packages/daemon/src/command-center/server.ts +67 -67
  34. package/packages/daemon/src/doctor.ts +50 -9
  35. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  36. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  37. package/packages/daemon/src/lib/daemon-embed.ts +22 -0
  38. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  39. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  40. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  41. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  42. package/packages/daemon/src/lib/update-check.ts +34 -0
  43. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  44. package/packages/daemon/src/lib/update.ts +58 -16
  45. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  46. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  47. package/packages/daemon/src/terminal/mirror/session-channel.ts +30 -1
  48. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +811 -223
  49. package/packages/daemon/src/terminal/session-runtime/registry.ts +35 -2
  50. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +74 -2
  51. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  52. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  53. package/packages/daemon/src/tui/chrome/snapshot.ts +47 -1
  54. package/packages/daemon/src/tui/chrome/statusline.ts +7 -4
  55. package/packages/daemon/src/tui/chrome/updater.ts +3 -0
  56. package/packages/daemon-client/src/pane-stream-client.ts +47 -5
@@ -11,11 +11,12 @@ import { promisify } from "node:util";
11
11
  import { existsSync, readdirSync } from "node:fs";
12
12
  import { join, dirname, basename } from "node:path";
13
13
  import { fileURLToPath } from "node:url";
14
- import { Hono, type MiddlewareHandler } from "hono";
14
+ import { Hono, type Context, type MiddlewareHandler } from "hono";
15
15
  import { streamSSE } from "hono/streaming";
16
16
  import { cors } from "hono/cors";
17
17
  import {
18
18
  discoverSessions,
19
+ readSessions,
19
20
  readLiveSessionSummaries,
20
21
  buildOverviews,
21
22
  buildProjectDetail,
@@ -537,6 +538,20 @@ function sandboxResolveDir(rawDir: string): SandboxResolveOk | SandboxResolveErr
537
538
  }
538
539
 
539
540
  export function createApp(options: CreateAppOptions = {}): Hono {
541
+ /**
542
+ * The running session a /api/project/:name route acts on. "unavailable" when
543
+ * tmux could not be asked: the session may well still run, so the routes
544
+ * answer 503 tmux-unavailable, not 404 (#753).
545
+ */
546
+ const lookupSession = (name: string): DiscoveredSession | "not-found" | "unavailable" => {
547
+ const sessions = readSessions();
548
+ if (sessions === null) return "unavailable";
549
+ return sessions.find((session) => session.name === name) ?? "not-found";
550
+ };
551
+ const sessionMissing = (c: Context, missing: "not-found" | "unavailable") =>
552
+ missing === "unavailable"
553
+ ? c.json({ error: "Tmux session discovery is unavailable", code: "tmux-unavailable" }, 503)
554
+ : c.json({ error: "Session not found" }, 404);
540
555
  const authConfig: AuthConfig = options.authConfig ?? { method: "none", token_expiry: 86400 };
541
556
  const authService = options.authService ?? new AuthService();
542
557
  const daemonIdentity = options.daemonIdentity ?? {
@@ -830,7 +845,13 @@ export function createApp(options: CreateAppOptions = {}): Hono {
830
845
  });
831
846
 
832
847
  app.get("/api/sessions", (c) => {
833
- const sessions = discoverSessions();
848
+ const sessions = readSessions();
849
+ // An empty list would tell the TUI the sessions are gone while they run (#753).
850
+ if (sessions === null)
851
+ return c.json(
852
+ { error: "Tmux session discovery is unavailable", code: "tmux-unavailable" },
853
+ 503,
854
+ );
834
855
  const overviews = buildOverviews(sessions);
835
856
  return c.json({ sessions: overviews } satisfies DaemonSessionsResponse);
836
857
  });
@@ -986,11 +1007,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
986
1007
 
987
1008
  app.get("/api/project/:name", (c) => {
988
1009
  const name = c.req.param("name");
989
- const sessions = discoverSessions();
990
- const session = sessions.find((s) => s.name === name);
991
- if (!session) {
992
- return c.json({ error: "Session not found" }, 404);
993
- }
1010
+ const session = lookupSession(name);
1011
+ if (typeof session === "string") return sessionMissing(c, session);
994
1012
  const detail = buildProjectDetail(session);
995
1013
  return c.json({ ...detail } satisfies DaemonProjectResponse);
996
1014
  });
@@ -1121,8 +1139,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1121
1139
  const backend = options.applicationShellInventoryBackend;
1122
1140
  if (!backend) {
1123
1141
  if (requestedVersion === String(APPLICATION_SHELL_RESOURCE_V1_VERSION)) {
1124
- const standaloneSession = discoverSessions().find((candidate) => candidate.name === name);
1125
- if (!standaloneSession) return c.json({ error: "Session not found" }, 404);
1142
+ const standaloneSession = lookupSession(name);
1143
+ if (typeof standaloneSession === "string") return sessionMissing(c, standaloneSession);
1126
1144
  markV1Compatibility();
1127
1145
  return c.json({
1128
1146
  version: APPLICATION_SHELL_RESOURCE_V1_VERSION,
@@ -1219,14 +1237,14 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1219
1237
  try {
1220
1238
  panes = listSessionPanes(name);
1221
1239
  } catch {
1222
- return c.json({ error: "Session not found" }, 404);
1240
+ // A missing session, or a tmux that could not be asked (#753).
1241
+ const session = lookupSession(name);
1242
+ return sessionMissing(c, typeof session === "string" ? session : "not-found");
1223
1243
  }
1224
1244
  if (panes.length === 0) {
1225
1245
  // Verify the session actually exists before returning empty
1226
- const sessions = discoverSessions();
1227
- if (!sessions.find((s) => s.name === name)) {
1228
- return c.json({ error: "Session not found" }, 404);
1229
- }
1246
+ const session = lookupSession(name);
1247
+ if (typeof session === "string") return sessionMissing(c, session);
1230
1248
  }
1231
1249
  return c.json({
1232
1250
  panes: panes.map((p) => ({
@@ -1246,9 +1264,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1246
1264
 
1247
1265
  app.get("/api/project/:name/terminals", async (c) => {
1248
1266
  const name = c.req.param("name");
1249
- const sessions = discoverSessions();
1250
- const session = sessions.find((s) => s.name === name);
1251
- if (!session) return c.json({ error: "Session not found" }, 404);
1267
+ const session = lookupSession(name);
1268
+ if (typeof session === "string") return sessionMissing(c, session);
1252
1269
  const records = loadTerminals(session.dir);
1253
1270
  const terminals = records.map((t) => {
1254
1271
  const bridge = defaultPtyBridgeRegistry.peek(t.id) as
@@ -1285,9 +1302,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1285
1302
  zValidator("json", terminalCreateRequestSchema),
1286
1303
  async (c) => {
1287
1304
  const name = c.req.param("name");
1288
- const sessions = discoverSessions();
1289
- const session = sessions.find((s) => s.name === name);
1290
- if (!session) return c.json({ error: "Session not found" }, 404);
1305
+ const session = lookupSession(name);
1306
+ if (typeof session === "string") return sessionMissing(c, session);
1291
1307
  const body = c.req.valid("json");
1292
1308
  // Pick the id: explicit > deterministic (when script provided) >
1293
1309
  // UUID. The script-derived id collapse is the load-bearing bit
@@ -1330,9 +1346,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1330
1346
  async (c) => {
1331
1347
  const name = c.req.param("name");
1332
1348
  const id = c.req.param("id");
1333
- const sessions = discoverSessions();
1334
- const session = sessions.find((s) => s.name === name);
1335
- if (!session) return c.json({ error: "Session not found" }, 404);
1349
+ const session = lookupSession(name);
1350
+ if (typeof session === "string") return sessionMissing(c, session);
1336
1351
  try {
1337
1352
  const record = renameTerminalRecord(session.dir, id, c.req.valid("json").name);
1338
1353
  if (!record) return c.json({ error: "Terminal not found" }, 404);
@@ -1347,9 +1362,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1347
1362
  app.delete("/api/project/:name/terminals/:id", async (c) => {
1348
1363
  const name = c.req.param("name");
1349
1364
  const id = c.req.param("id");
1350
- const sessions = discoverSessions();
1351
- const session = sessions.find((s) => s.name === name);
1352
- if (!session) return c.json({ error: "Session not found" }, 404);
1365
+ const session = lookupSession(name);
1366
+ if (typeof session === "string") return sessionMissing(c, session);
1353
1367
  const removedRecord = deleteTerminalRecord(session.dir, id);
1354
1368
  // Kill the live bridge too — keep store + registry consistent.
1355
1369
  const killed = defaultPtyBridgeRegistry.delete(id);
@@ -1366,19 +1380,15 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1366
1380
 
1367
1381
  app.get("/api/project/:name/events", (c) => {
1368
1382
  const name = c.req.param("name");
1369
- const session = discoverSessions().find((s) => s.name === name);
1370
- if (!session) {
1371
- return c.json({ error: "Session not found" }, 404);
1372
- }
1383
+ const session = lookupSession(name);
1384
+ if (typeof session === "string") return sessionMissing(c, session);
1373
1385
  return c.json({ events: [] });
1374
1386
  });
1375
1387
 
1376
1388
  app.get("/api/project/:name/stream", (c) => {
1377
1389
  const name = c.req.param("name");
1378
- const session = discoverSessions().find((s) => s.name === name);
1379
- if (!session) {
1380
- return c.json({ error: "Session not found" }, 404);
1381
- }
1390
+ const session = lookupSession(name);
1391
+ if (typeof session === "string") return sessionMissing(c, session);
1382
1392
 
1383
1393
  return streamSSE(c, async (stream) => {
1384
1394
  projectStreamConnections += 1;
@@ -1408,9 +1418,10 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1408
1418
  writeChanges(session);
1409
1419
  while (!closed) {
1410
1420
  await stream.sleep(250);
1411
- const current = discoverSessions().find((candidate) => candidate.name === name);
1412
- if (!current) break;
1413
- writeChanges(current);
1421
+ const current = lookupSession(name);
1422
+ if (current === "not-found") break;
1423
+ // tmux could not be asked: the session may still run; ask again (#753).
1424
+ if (current !== "unavailable") writeChanges(current);
1414
1425
  const now = Date.now();
1415
1426
  if (now - lastPing >= 25_000) {
1416
1427
  writeSse("ping", { at: new Date().toISOString() });
@@ -1426,11 +1437,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1426
1437
 
1427
1438
  app.post("/api/project/:name/inject", async (c) => {
1428
1439
  const name = c.req.param("name");
1429
- const sessions = discoverSessions();
1430
- const session = sessions.find((s) => s.name === name);
1431
- if (!session) {
1432
- return c.json({ error: "Session not found" }, 404);
1433
- }
1440
+ const session = lookupSession(name);
1441
+ if (typeof session === "string") return sessionMissing(c, session);
1434
1442
 
1435
1443
  let body: unknown;
1436
1444
  try {
@@ -1474,11 +1482,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1474
1482
  // Send message to a pane by name/title/role/ID
1475
1483
  app.post("/api/project/:name/send", zValidator("json", sendCommandSchema), async (c) => {
1476
1484
  const name = c.req.param("name");
1477
- const sessions = discoverSessions();
1478
- const session = sessions.find((s) => s.name === name);
1479
- if (!session) {
1480
- return c.json({ error: "Session not found" }, 404);
1481
- }
1485
+ const session = lookupSession(name);
1486
+ if (typeof session === "string") return sessionMissing(c, session);
1482
1487
 
1483
1488
  const { target, message, noEnter } = c.req.valid("json");
1484
1489
 
@@ -1522,9 +1527,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1522
1527
  // the v2 Config editor to hydrate the form.
1523
1528
  app.get("/api/project/:name/config", async (c) => {
1524
1529
  const name = c.req.param("name");
1525
- const sessions = discoverSessions();
1526
- const session = sessions.find((s) => s.name === name);
1527
- if (!session) return c.json({ error: "Session not found" }, 404);
1530
+ const session = lookupSession(name);
1531
+ if (typeof session === "string") return sessionMissing(c, session);
1528
1532
  try {
1529
1533
  const resolved = await resolveConfig(session.dir);
1530
1534
  if (!resolved.launchConfig || !resolved.path) {
@@ -1550,9 +1554,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1550
1554
  // config so the client can re-hydrate without a follow-up GET.
1551
1555
  app.post("/api/project/:name/config", async (c) => {
1552
1556
  const name = c.req.param("name");
1553
- const sessions = discoverSessions();
1554
- const session = sessions.find((s) => s.name === name);
1555
- if (!session) return c.json({ error: "Session not found" }, 404);
1557
+ const session = lookupSession(name);
1558
+ if (typeof session === "string") return sessionMissing(c, session);
1556
1559
  let body: unknown;
1557
1560
  try {
1558
1561
  body = await c.req.json();
@@ -1590,9 +1593,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1590
1593
  // 30s timeout so the client can retry on its own.
1591
1594
  app.post("/api/project/:name/restart", async (c) => {
1592
1595
  const name = c.req.param("name");
1593
- const sessions = discoverSessions();
1594
- const session = sessions.find((s) => s.name === name);
1595
- if (!session) return c.json({ error: "Session not found" }, 404);
1596
+ const session = lookupSession(name);
1597
+ if (typeof session === "string") return sessionMissing(c, session);
1596
1598
  try {
1597
1599
  await execFileAsync("tmux-ide", ["restart", "--json"], {
1598
1600
  cwd: session.dir,
@@ -1608,11 +1610,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1608
1610
 
1609
1611
  app.post("/api/project/:name/launch", async (c) => {
1610
1612
  const name = c.req.param("name");
1611
- const sessions = discoverSessions();
1612
- const session = sessions.find((s) => s.name === name);
1613
- if (!session) {
1614
- return c.json({ error: "Session not found" }, 404);
1615
- }
1613
+ const session = lookupSession(name);
1614
+ if (typeof session === "string") return sessionMissing(c, session);
1616
1615
 
1617
1616
  // Check if already running
1618
1617
  const state = getSessionState(name);
@@ -1636,11 +1635,8 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1636
1635
  // Stop a tmux-ide session
1637
1636
  app.post("/api/project/:name/stop", async (c) => {
1638
1637
  const name = c.req.param("name");
1639
- const sessions = discoverSessions();
1640
- const session = sessions.find((s) => s.name === name);
1641
- if (!session) {
1642
- return c.json({ error: "Session not found" }, 404);
1643
- }
1638
+ const session = lookupSession(name);
1639
+ if (typeof session === "string") return sessionMissing(c, session);
1644
1640
 
1645
1641
  const state = getSessionState(name);
1646
1642
  if (!state.running) {
@@ -1661,7 +1657,11 @@ export function createApp(options: CreateAppOptions = {}): Hono {
1661
1657
  let prevOverviews: SessionOverview[] = [];
1662
1658
 
1663
1659
  const poll = () => {
1664
- const sessions = discoverSessions();
1660
+ const sessions = readSessions();
1661
+ // tmux could not be asked: the sessions may well still run. Diffing an
1662
+ // empty list would announce every one as removed, then added (#753).
1663
+ // Keep the last answer and wait for the next poll.
1664
+ if (sessions === null) return;
1665
1665
  const overviews = buildOverviews(sessions);
1666
1666
 
1667
1667
  const prevNames = new Set(prevOverviews.map((s) => s.name));
@@ -6,7 +6,7 @@ import { accessSync, constants, existsSync, mkdtempSync, realpathSync, rmSync }
6
6
  import { tmpdir } from "node:os";
7
7
  import { delimiter, resolve, dirname, join } from "node:path";
8
8
  import { resolveBundledTmux } from "./lib/bundled-tmux.ts";
9
- import { readSnapshot } from "./tui/chrome/snapshot.ts";
9
+ import { readSnapshot, snapshotIsRestorePoint } from "./tui/chrome/snapshot.ts";
10
10
  import { isListableSession } from "./tui/team/sessions.ts";
11
11
  import { nativeCommands, type NativeAnswer, type TmuxProbe } from "./lib/tmux-server-features.ts";
12
12
  import { fileURLToPath } from "node:url";
@@ -194,7 +194,7 @@ export function tmuxFeaturesRow(probeServer: TmuxProbe, probeBinary: TmuxProbe):
194
194
  : "";
195
195
  const details: Record<NativeAnswer, string> = {
196
196
  full: "bundled tmux: full features",
197
- stock: `stock tmux: reduced features${upgrade}`,
197
+ stock: `stock tmux: reduced features (tab positions in saved output are reconstructed)${upgrade}`,
198
198
  older: `older tmux-ide tmux: reduced features${upgrade}`,
199
199
  partial: "this tmux has only some tmux-ide commands: no pane dividers",
200
200
  "no-server": "could not read the tmux server's features",
@@ -235,17 +235,20 @@ const DAY_MS = 24 * 60 * 60 * 1000;
235
235
 
236
236
  /**
237
237
  * PURE — is the crash snapshot fresh enough to restore from? It fails when it
238
- * is missing a live session, or is over a day old while sessions run. Only the
239
- * chrome updater writes it, and that runs only while a session is adopted.
238
+ * is missing a live session, or is over a day old while sessions run. The
239
+ * chrome updater writes it while a session is adopted; otherwise the background
240
+ * service does, for its default server (lib/daemon-crash-snapshot.ts).
240
241
  */
241
242
  export function snapshotRow(
242
243
  snapshot: { savedAt: string; sessions: readonly { name: string }[] } | null,
243
244
  liveSessions: readonly string[] | null,
244
245
  nowMs: number,
246
+ /** When the running tmux server started, if known. */
247
+ serverStartMs: number | null = null,
245
248
  ): CheckResult {
246
249
  const label = "crash snapshot (restore)";
247
250
  const hint =
248
- "Only the chrome updater writes it, while a session is adopted: `tmux-ide adopt --all` starts it";
251
+ "The background service writes it within a minute while it runs; without the service, `tmux-ide adopt --all` starts a writer";
249
252
  if (!snapshot) {
250
253
  return liveSessions?.length
251
254
  ? { label, pass: false, detail: `none yet. ${hint}`, optional: true }
@@ -256,6 +259,22 @@ export function snapshotRow(
256
259
  ageMs >= DAY_MS
257
260
  ? `${Math.floor(ageMs / DAY_MS)} days old`
258
261
  : `${Math.max(0, Math.round(ageMs / 60_000))} min old`;
262
+ if (
263
+ liveSessions &&
264
+ serverStartMs !== null &&
265
+ snapshotIsRestorePoint(snapshot, { serverStartMs, sessions: liveSessions })
266
+ ) {
267
+ // No writer replaces this file: it is the only record of the server that died.
268
+ const gone = snapshot.sessions
269
+ .map((session) => session.name)
270
+ .filter((name) => !liveSessions.includes(name));
271
+ return {
272
+ label,
273
+ pass: false,
274
+ detail: `restore point kept: saved ${age}, before this tmux server started; ${gone.length} of its sessions ${gone.length === 1 ? "is" : "are"} not running (${gone.slice(0, 5).join(", ")}${gone.length > 5 ? ", …" : ""}). \`tmux-ide restore\` brings them back; delete snapshot.json to let a new snapshot replace it`,
275
+ optional: true,
276
+ };
277
+ }
259
278
  const saved = new Set(snapshot.sessions.map((session) => session.name));
260
279
  const missing = (liveSessions ?? []).filter((name) => !saved.has(name));
261
280
  if (missing.length)
@@ -291,12 +310,34 @@ function safeBundledTmux(): string | null {
291
310
  }
292
311
  }
293
312
 
313
+ /** The `-S`/`-L` arguments that name the server doctor reads. */
314
+ function doctorTmuxServer(): string[] {
315
+ const socketPath = process.env[TMUX_SOCKET_PATH_ENV];
316
+ const socketName = process.env.TMUX_IDE_TMUX_SOCKET_NAME;
317
+ return socketPath ? ["-S", socketPath] : socketName ? ["-L", socketName] : [];
318
+ }
319
+
320
+ /** `#{start_time}` of the server doctor reads, or null when it cannot be asked. */
321
+ function liveServerStartMs(): number | null {
322
+ try {
323
+ const server = doctorTmuxServer();
324
+ const seconds = Number(
325
+ execFileSync(resolveTmuxExecutable(), [...server, "display-message", "-p", "#{start_time}"], {
326
+ encoding: "utf8",
327
+ stdio: ["ignore", "pipe", "pipe"],
328
+ timeout: 3000,
329
+ }).trim(),
330
+ );
331
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null;
332
+ } catch {
333
+ return null;
334
+ }
335
+ }
336
+
294
337
  /** The sessions the snapshot should hold, on the server doctor reads; null when unreadable. */
295
338
  function liveListableSessions(): string[] | null {
296
339
  try {
297
- const socketPath = process.env[TMUX_SOCKET_PATH_ENV];
298
- const socketName = process.env.TMUX_IDE_TMUX_SOCKET_NAME;
299
- const server = socketPath ? ["-S", socketPath] : socketName ? ["-L", socketName] : [];
340
+ const server = doctorTmuxServer();
300
341
  return execFileSync(
301
342
  resolveTmuxExecutable(),
302
343
  [...server, "list-sessions", "-F", "#{session_name}"],
@@ -451,7 +492,7 @@ export async function doctor({
451
492
  // The tmux version row above already reports a missing executable.
452
493
  }
453
494
  checks.push(plainTmuxRow(firstOnPath("tmux"), safeBundledTmux()));
454
- checks.push(snapshotRow(readSnapshot(), liveListableSessions(), Date.now()));
495
+ checks.push(snapshotRow(readSnapshot(), liveListableSessions(), Date.now(), liveServerStartMs()));
455
496
 
456
497
  checks.push(nodeVersionRow(process.versions.node));
457
498
 
@@ -3,6 +3,7 @@ import {
3
3
  captureUnboundTmuxSelectorProof,
4
4
  type TmuxServerProof,
5
5
  } from "./tmux-server-proof.ts";
6
+ import { invocationDirectory } from "./invocation-directory.ts";
6
7
  import {
7
8
  createPinnedWorkspaceTmuxRunner,
8
9
  resolveWorkspacePaneTmuxAuthority,
@@ -282,6 +283,22 @@ async function replaceOlderCanonicalDaemon(
282
283
  );
283
284
  }
284
285
 
286
+ const DAEMON_PROOF_PENDING = Symbol("daemon-server-proof-pending");
287
+
288
+ /**
289
+ * The daemon supports server proofs, but its identity or this side's own probe
290
+ * has no proof yet: a generation that just started on a replaced tmux server,
291
+ * or a slow tmux answer. Waiting can resolve it; an unsupported proof or a
292
+ * positive mismatch cannot.
293
+ */
294
+ export function daemonServerProofPending(error: unknown): boolean {
295
+ return (
296
+ error instanceof DaemonBootstrapError &&
297
+ (error as DaemonBootstrapError & { [DAEMON_PROOF_PENDING]?: boolean })[DAEMON_PROOF_PENDING] ===
298
+ true
299
+ );
300
+ }
301
+
285
302
  async function assertServerIntent(
286
303
  deps: CanonicalDaemonBootstrapDependencies,
287
304
  info: CanonicalDaemonInfo,
@@ -320,10 +337,17 @@ async function assertServerIntent(
320
337
  }
321
338
  }
322
339
  if (info.tmuxServerProofVersion !== 1 || !identity.tmuxServerProof || !proof)
323
- throw new DaemonBootstrapError(
324
- "incompatible",
325
- `Cannot prove the requested tmux server for this daemon. Its server identity is unavailable or unsupported; the existing daemon was left running. Proof availability: capability=${info.tmuxServerProofVersion === 1}, daemon=${Boolean(identity.tmuxServerProof)}, client=${Boolean(proof)}.`,
326
- { reason: "tmux-server-unproven" },
340
+ throw Object.assign(
341
+ new DaemonBootstrapError<CanonicalDaemonBootstrapFailure>(
342
+ "incompatible",
343
+ `Cannot prove the requested tmux server for this daemon. Its server identity is unavailable or unsupported; the existing daemon was left running. Proof availability: capability=${info.tmuxServerProofVersion === 1}, daemon=${Boolean(identity.tmuxServerProof)}, client=${Boolean(proof)}.`,
344
+ { reason: "tmux-server-unproven" },
345
+ ),
346
+ {
347
+ // Either side's proof can be late (a slow tmux answer); only a daemon
348
+ // without the capability can never prove it.
349
+ [DAEMON_PROOF_PENDING]: info.tmuxServerProofVersion === 1,
350
+ },
327
351
  );
328
352
  if (
329
353
  identity.tmuxServerProof.kind !== proof.kind ||
@@ -460,7 +484,9 @@ export function createCanonicalDaemonBootstrapCoordinator(
460
484
  ? resolveTmuxServerIntent()
461
485
  : options.tmuxServerIntent,
462
486
  ),
463
- spawn: () => deps.spawnOwner(resolve(options.entryPath), resolve(options.cwd ?? process.cwd())),
487
+ // A deleted current directory starts the daemon from home (#585).
488
+ spawn: () =>
489
+ deps.spawnOwner(resolve(options.entryPath), resolve(options.cwd ?? invocationDirectory())),
464
490
  timeoutMs: options.timeoutMs,
465
491
  onPhaseChanged: options.onPhaseChanged,
466
492
  now: deps.now,
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The crash snapshot (`snapshot.json`, read by `tmux-ide restore`) written by
3
+ * the daemon for its default tmux server.
4
+ *
5
+ * The chrome updater writes that file, but it runs only while a session is
6
+ * adopted. A server started by plain `tmux` then has no snapshot, silently
7
+ * (#783). The daemon fills the gap: it writes the same file, with the same
8
+ * builder, whenever the updater's own session is not running. One writer at a
9
+ * time, so the two never rotate each other's generation away. Neither replaces
10
+ * a restore point: the snapshot of a server that is gone and whose sessions
11
+ * have not come back (`snapshotIsRestorePoint`).
12
+ */
13
+ import { UPDATER_SESSION } from "./chrome-front-door.ts";
14
+
15
+ /** How often the daemon looks. A new server has its snapshot within a minute. */
16
+ export const DAEMON_CRASH_SNAPSHOT_INTERVAL_MS = 30_000;
17
+
18
+ /** What the rule below needs to know of a snapshot. */
19
+ export interface CrashSnapshotSummary {
20
+ readonly savedAt: string;
21
+ readonly sessions: readonly { readonly name: string }[];
22
+ }
23
+
24
+ /**
25
+ * The snapshot file and its builder. They belong to the chrome adapter
26
+ * (tui/chrome/snapshot.ts, `fleetCrashSnapshotSource`), which the engine may
27
+ * not import; the process that owns the daemon passes them in.
28
+ */
29
+ export interface CrashSnapshotSource<S extends CrashSnapshotSummary = CrashSnapshotSummary> {
30
+ readonly sessionFormat: string;
31
+ readonly paneFormat: string;
32
+ /** Build a snapshot from `list-panes -a` and `list-sessions` rows; reads the process table. */
33
+ readonly build: (panes: string[], sessions: string[]) => Promise<S>;
34
+ readonly read: () => S | null;
35
+ // Method syntax on purpose: a source of a richer snapshot type is accepted
36
+ // where the daemon options name the summary type.
37
+ write(snapshot: S): void;
38
+ fingerprint(snapshot: S): string;
39
+ }
40
+
41
+ /**
42
+ * Is `existing` a restore point: the snapshot of a tmux server that is gone,
43
+ * naming at least one session the running server lacks? That file is what
44
+ * `tmux-ide restore` rebuilds from, so no writer may replace it. It stops
45
+ * being one when its sessions run again (after a restore) or the user deletes
46
+ * the file. A server's own snapshot is never one: it was saved after the
47
+ * server started.
48
+ */
49
+ export function snapshotIsRestorePoint(
50
+ existing: CrashSnapshotSummary | null,
51
+ live: { readonly serverStartMs: number; readonly sessions: readonly string[] },
52
+ ): boolean {
53
+ if (!existing || !(live.serverStartMs > Date.parse(existing.savedAt))) return false;
54
+ const running = new Set(live.sessions);
55
+ return existing.sessions.some((session) => !running.has(session.name));
56
+ }
57
+
58
+ export interface DaemonCrashSnapshotDeps<S extends CrashSnapshotSummary = CrashSnapshotSummary> {
59
+ /** A tmux client pinned to the daemon's default server. Throws when it cannot ask. */
60
+ readonly run: (args: readonly string[]) => Promise<string>;
61
+ readonly source: CrashSnapshotSource<S>;
62
+ }
63
+
64
+ export type DaemonCrashSnapshotPulse =
65
+ | "written"
66
+ | "unchanged"
67
+ | "updater-writes"
68
+ | "restore-point-kept"
69
+ | "tmux-unavailable";
70
+
71
+ export function createDaemonCrashSnapshot<S extends CrashSnapshotSummary>(
72
+ deps: DaemonCrashSnapshotDeps<S>,
73
+ ) {
74
+ const { source } = deps;
75
+ /** The tmux answers of the last pulse that built a snapshot. */
76
+ let seen: string | null = null;
77
+ return {
78
+ async pulse(): Promise<DaemonCrashSnapshotPulse> {
79
+ let sessions: string;
80
+ let panes: string;
81
+ let existing: S | null;
82
+ let serverStartMs = Number.NaN;
83
+ try {
84
+ sessions = await deps.run(["list-sessions", "-F", source.sessionFormat]);
85
+ if (sessions.split("\n").some((line) => line.split("\t")[0] === UPDATER_SESSION)) {
86
+ // The updater owns the file now; start over from the file when it stops.
87
+ seen = null;
88
+ return "updater-writes";
89
+ }
90
+ panes = await deps.run(["list-panes", "-a", "-F", source.paneFormat]);
91
+ if (`${sessions}\n\n${panes}` === seen) return "unchanged";
92
+ existing = source.read();
93
+ if (existing)
94
+ serverStartMs =
95
+ Number((await deps.run(["display-message", "-p", "#{start_time}"])).trim()) * 1000;
96
+ } catch {
97
+ // A server that is gone or unreachable must not replace the snapshot
98
+ // that restores it.
99
+ return "tmux-unavailable";
100
+ }
101
+ const running = sessions.split("\n").map((line) => line.split("\t")[0]!);
102
+ if (snapshotIsRestorePoint(existing, { serverStartMs, sessions: running })) {
103
+ // Look again next time: a restore or a deleted file changes no tmux
104
+ // answer this pulse could remember.
105
+ seen = null;
106
+ return "restore-point-kept";
107
+ }
108
+ const snapshot = await source.build(
109
+ panes.split("\n").filter(Boolean),
110
+ sessions.split("\n").filter(Boolean),
111
+ );
112
+ seen = `${sessions}\n\n${panes}`;
113
+ if (existing && source.fingerprint(existing) === source.fingerprint(snapshot))
114
+ return "unchanged";
115
+ source.write(snapshot);
116
+ return "written";
117
+ },
118
+ };
119
+ }
120
+
121
+ /**
122
+ * What a daemon generation passes to {@link startDaemonCrashSnapshot}: its
123
+ * launcher and the source its owner injected. A pure function so a test can pin
124
+ * that the source reaches the writer without starting a daemon.
125
+ */
126
+ export function daemonCrashSnapshotStart(
127
+ opts: {
128
+ readonly launcher?: "headless" | "embedded";
129
+ readonly crashSnapshotSource?: CrashSnapshotSource;
130
+ },
131
+ run: (args: readonly string[]) => Promise<string>,
132
+ retired: () => boolean,
133
+ ): Parameters<typeof startDaemonCrashSnapshot<CrashSnapshotSummary>>[0] {
134
+ return {
135
+ launcher: opts.launcher ?? "embedded",
136
+ source: opts.crashSnapshotSource,
137
+ run,
138
+ retired,
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Pulse on a timer until `retired` says the daemon generation is gone; the
144
+ * timer then clears itself, so no stop step has to know about it. Returns a
145
+ * stop function for callers that have one. Only the background service
146
+ * ("headless") writes: a daemon embedded in an app lives only as long as its
147
+ * window, and gets null. So does a daemon started without a snapshot source.
148
+ */
149
+ export function startDaemonCrashSnapshot<S extends CrashSnapshotSummary>(
150
+ deps: Omit<DaemonCrashSnapshotDeps<S>, "source"> & {
151
+ readonly source: CrashSnapshotSource<S> | undefined;
152
+ readonly launcher: "headless" | "embedded";
153
+ readonly retired: () => boolean;
154
+ },
155
+ ): (() => void) | null {
156
+ if (deps.launcher !== "headless" || !deps.source) return null;
157
+ const snapshot = createDaemonCrashSnapshot({ run: deps.run, source: deps.source });
158
+ let busy = false;
159
+ const timer = setInterval(() => {
160
+ if (deps.retired()) {
161
+ clearInterval(timer);
162
+ return;
163
+ }
164
+ if (busy) return;
165
+ busy = true;
166
+ void snapshot
167
+ .pulse()
168
+ .catch(() => undefined)
169
+ .finally(() => {
170
+ busy = false;
171
+ });
172
+ }, DAEMON_CRASH_SNAPSHOT_INTERVAL_MS);
173
+ timer.unref?.();
174
+ return () => clearInterval(timer);
175
+ }