tmux-ide 2.9.23 → 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 (83) hide show
  1. package/bin/cli.js +1636 -385
  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/command-center/tmux-servers.js +11 -0
  7. package/packages/daemon/dist/doctor.js +46 -10
  8. package/packages/daemon/dist/lib/canonical-daemon-bootstrap.js +20 -2
  9. package/packages/daemon/dist/lib/daemon-crash-snapshot.js +118 -0
  10. package/packages/daemon/dist/lib/daemon-embed.js +22 -8
  11. package/packages/daemon/dist/lib/headless-daemon.js +63 -6
  12. package/packages/daemon/dist/lib/home-agent-observer.js +50 -0
  13. package/packages/daemon/dist/lib/invocation-directory.js +20 -0
  14. package/packages/daemon/dist/lib/machine-agents.js +18 -1
  15. package/packages/daemon/dist/lib/orphaned-control-clients.js +162 -0
  16. package/packages/daemon/dist/lib/runtime-namespace.js +22 -6
  17. package/packages/daemon/dist/lib/tmux-client-execution.js +12 -3
  18. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +32 -9
  19. package/packages/daemon/dist/lib/tmux-server-owner.js +26 -4
  20. package/packages/daemon/dist/lib/update-check.js +18 -0
  21. package/packages/daemon/dist/lib/update-daemon-outcome.js +31 -0
  22. package/packages/daemon/dist/lib/update.js +39 -14
  23. package/packages/daemon/dist/lib/workspace-promotion.js +24 -3
  24. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  25. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  26. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  27. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  28. package/packages/daemon/dist/terminal/attachments/native-runtime.js +17 -2
  29. package/packages/daemon/dist/terminal/graphics/kitty-graphics.js +16 -4
  30. package/packages/daemon/dist/terminal/mirror/mirror-service.js +26 -0
  31. package/packages/daemon/dist/terminal/mirror/session-channel.js +27 -2
  32. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +749 -208
  33. package/packages/daemon/dist/terminal/session-runtime/registry.js +24 -2
  34. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +77 -2
  35. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +24 -2
  36. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +38 -0
  37. package/packages/daemon/dist/tui/chrome/snapshot.js +36 -1
  38. package/packages/daemon/dist/tui/chrome/statusline.js +8 -5
  39. package/packages/daemon/dist/tui/chrome/updater.js +2 -0
  40. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +57 -4
  41. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +18 -7
  42. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +17 -0
  43. package/packages/daemon/dist/tui/mirror/runtime/application-machine-navigation.js +4 -2
  44. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +55 -14
  45. package/packages/daemon/src/command-center/discovery.ts +24 -4
  46. package/packages/daemon/src/command-center/server.ts +67 -67
  47. package/packages/daemon/src/command-center/tmux-servers.ts +11 -0
  48. package/packages/daemon/src/doctor.ts +50 -9
  49. package/packages/daemon/src/lib/canonical-daemon-bootstrap.ts +31 -5
  50. package/packages/daemon/src/lib/daemon-crash-snapshot.ts +175 -0
  51. package/packages/daemon/src/lib/daemon-embed.ts +74 -7
  52. package/packages/daemon/src/lib/headless-daemon.ts +88 -7
  53. package/packages/daemon/src/lib/home-agent-observer.ts +53 -0
  54. package/packages/daemon/src/lib/invocation-directory.ts +21 -0
  55. package/packages/daemon/src/lib/machine-agents.ts +25 -1
  56. package/packages/daemon/src/lib/orphaned-control-clients.ts +215 -0
  57. package/packages/daemon/src/lib/runtime-namespace.ts +25 -7
  58. package/packages/daemon/src/lib/tmux-client-execution.ts +14 -5
  59. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +32 -8
  60. package/packages/daemon/src/lib/tmux-server-owner.ts +28 -3
  61. package/packages/daemon/src/lib/update-check.ts +34 -0
  62. package/packages/daemon/src/lib/update-daemon-outcome.ts +42 -0
  63. package/packages/daemon/src/lib/update.ts +58 -16
  64. package/packages/daemon/src/lib/workspace-promotion.ts +26 -3
  65. package/packages/daemon/src/terminal/attachments/native-runtime.ts +21 -2
  66. package/packages/daemon/src/terminal/graphics/kitty-graphics.ts +22 -6
  67. package/packages/daemon/src/terminal/mirror/mirror-service.ts +27 -0
  68. package/packages/daemon/src/terminal/mirror/session-channel.ts +32 -2
  69. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +819 -223
  70. package/packages/daemon/src/terminal/session-runtime/registry.ts +35 -2
  71. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +74 -2
  72. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +21 -1
  73. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +42 -2
  74. package/packages/daemon/src/tui/chrome/snapshot.ts +47 -1
  75. package/packages/daemon/src/tui/chrome/statusline.ts +7 -4
  76. package/packages/daemon/src/tui/chrome/updater.ts +3 -0
  77. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +69 -4
  78. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +30 -13
  79. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +38 -1
  80. package/packages/daemon/src/tui/mirror/runtime/application-machine-navigation.ts +7 -2
  81. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +4 -4
  82. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +71 -17
  83. package/packages/daemon-client/src/pane-stream-client.ts +47 -5
@@ -10,6 +10,13 @@ import { TerminalPaneInputRouter } from "./terminal-pane-input-router.js";
10
10
  import { resizeTerminalPane, } from "./resize-terminal-pane.js";
11
11
  import { ResizeTransactionController } from "@tmux-ide/core";
12
12
  import { nativePaneResizeCells } from "./pane-resize-geometry.js";
13
+ /**
14
+ * Waits between tries of a selection the daemon refused as
15
+ * `pane_inventory_not_ready`: it refuses, before any effect, a pane its
16
+ * inventory has not adopted yet, which is the case for a moment after a pane
17
+ * is created (#764). About 3 s in all.
18
+ */
19
+ export const PANE_INVENTORY_RETRY_DELAYS_MS = [100, 200, 400, 800, 1500];
13
20
  function paneForWindow(layout) {
14
21
  return (layout.panes.find((pane) => pane.active && pane.pane)?.pane ??
15
22
  layout.panes.find((pane) => pane.pane)?.pane ??
@@ -527,7 +534,29 @@ export function createApplicationTerminalInteractionController(options) {
527
534
  };
528
535
  // The one way a pane selection reaches the runtime (#764: also used once an
529
536
  // admitted agent selection settles).
537
+ const selectionRetryDelaysMs = options.selectionRetryDelaysMs ?? PANE_INVENTORY_RETRY_DELAYS_MS;
538
+ /**
539
+ * A refusal for an inventory that is not ready happened before any effect,
540
+ * so the same selection may be sent again while it is still the current one.
541
+ * Any other failure is final.
542
+ */
530
543
  const selectInRuntime = async (paneId) => {
544
+ const version = paneInput.selectionVersion;
545
+ for (let attempt = 0;; attempt++) {
546
+ const failure = { current: null };
547
+ if (await selectInRuntimeOnce(paneId, failure))
548
+ return true;
549
+ const delayMs = selectionRetryDelaysMs[attempt];
550
+ if (delayMs === undefined ||
551
+ failure.current?.backendReason !== "pane_inventory_not_ready" ||
552
+ paneInput.selectionVersion !== version)
553
+ return false;
554
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
555
+ if (paneInput.selectionVersion !== version)
556
+ return false;
557
+ }
558
+ };
559
+ const selectInRuntimeOnce = async (paneId, selectionFailure) => {
531
560
  finishLinkSelection(false);
532
561
  const initial = options.generation();
533
562
  const selectionControl = controlIdentity(initial);
@@ -553,7 +582,6 @@ export function createApplicationTerminalInteractionController(options) {
553
582
  let dispatchedRendererEpoch;
554
583
  const selecting = pendingWindowSwitch;
555
584
  const operationId = selecting?.traceId;
556
- const selectionFailure = { current: null };
557
585
  const receipt = expected
558
586
  ? await selectTerminalPane(expected, () => {
559
587
  if (!selectionControl)
@@ -916,22 +944,35 @@ export function createApplicationTerminalInteractionController(options) {
916
944
  maybeRequestWindowSwitchFrame();
917
945
  maybeRequestPaneResizeFrame();
918
946
  },
919
- selectPane: (paneId, admission) => {
947
+ selectPane: ((paneId, admission) => {
920
948
  finishLinkSelection(false);
921
- if (admission)
922
- // Ordered now; selected only once admitted, otherwise held input drops.
923
- paneInput.selectPane(paneId, {
924
- presentOptimistically: false,
925
- selection: () => {
926
- // A later selection supersedes this one: never select it after all.
927
- const version = paneInput.selectionVersion;
928
- return admission.then((admitted) => admitted && paneInput.selectionVersion === version ? selectInRuntime(paneId) : false);
929
- },
930
- });
931
- else
949
+ if (!admission) {
932
950
  paneInput.selectPane(paneId);
951
+ selectionWaiter.reconcile();
952
+ return;
953
+ }
954
+ let outcome;
955
+ // Ordered now; selected only once admitted, otherwise held input drops.
956
+ paneInput.selectPane(paneId, {
957
+ presentOptimistically: false,
958
+ selection: () => {
959
+ // A later selection supersedes this one: never select it after all.
960
+ const version = paneInput.selectionVersion;
961
+ outcome = admission.then(async (admitted) => {
962
+ if (!admitted)
963
+ return "not-admitted";
964
+ if (paneInput.selectionVersion !== version)
965
+ return "superseded";
966
+ if (await selectInRuntime(paneId))
967
+ return "selected";
968
+ return paneInput.selectionVersion === version ? "failed" : "superseded";
969
+ });
970
+ return outcome.then((result) => result === "selected");
971
+ },
972
+ });
933
973
  selectionWaiter.reconcile();
934
- },
974
+ return outcome;
975
+ }),
935
976
  async unlinkWindowLink(target) {
936
977
  const expected = liveSelectionTarget();
937
978
  const observed = windowLinkTarget(options.layout(), target.linkId);
@@ -40,7 +40,9 @@ let _tmuxRunner: TmuxRunner = (args) =>
40
40
  execFileSync("tmux", ["-u", ...runtimeTmuxArgs(args)], {
41
41
  encoding: "utf-8",
42
42
  maxBuffer: 1024 * 1024,
43
- stdio: ["ignore", "pipe", "ignore"],
43
+ // Keep stderr on the error: it is how a caller tells "no server running"
44
+ // from a server it could not reach. Nothing is printed either way.
45
+ stdio: ["ignore", "pipe", "pipe"],
44
46
  }).trim();
45
47
 
46
48
  export function _setTmuxRunner(fn: TmuxRunner): () => void {
@@ -75,8 +77,20 @@ function semanticPaneIds(session: string): ReadonlyMap<string, string> {
75
77
  }
76
78
 
77
79
  export function listTmuxSessions(): string[] {
78
- const raw = tmuxSilent(["list-sessions", "-F", "#{session_name}"]);
79
- if (!raw) return [];
80
+ return readTmuxSessions() ?? [];
81
+ }
82
+
83
+ /**
84
+ * {@link listTmuxSessions}, but null when tmux could not be asked. Only a
85
+ * server that is not running has no sessions (#753).
86
+ */
87
+ export function readTmuxSessions(): string[] | null {
88
+ let raw: string;
89
+ try {
90
+ raw = _tmuxRunner(["list-sessions", "-F", "#{session_name}"]);
91
+ } catch (error) {
92
+ return serverNotRunning(error) ? [] : null;
93
+ }
80
94
  return raw.split("\n").filter(Boolean);
81
95
  }
82
96
 
@@ -478,7 +492,13 @@ function assembleAdoptedFleet(
478
492
  }
479
493
 
480
494
  export function discoverSessions(): SessionInfo[] {
481
- const sessionNames = listTmuxSessions();
495
+ return readSessions() ?? [];
496
+ }
497
+
498
+ /** {@link discoverSessions}, but null when tmux could not be asked (#753). */
499
+ export function readSessions(): SessionInfo[] | null {
500
+ const sessionNames = readTmuxSessions();
501
+ if (sessionNames === null) return null;
482
502
  const results: SessionInfo[] = [];
483
503
 
484
504
  // Once the workspace registry is loaded (post daemon-embed startup),
@@ -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));
@@ -38,6 +38,7 @@ import { createSessionFaviconResolver, type SessionFavicon } from "../lib/sessio
38
38
  import { WorkspaceMultiplexerError } from "../lib/workspace-multiplexer-verbs.ts";
39
39
  import { WorkspacePaneCreationError } from "../lib/workspace-pane-creation.ts";
40
40
  import { ownerBearerMatches } from "./owner-authority.ts";
41
+ import { logger } from "../lib/log.ts";
41
42
  import { mountPaneStreamIssueRoute } from "./pane-stream-issue.ts";
42
43
  import { projectTerminalRuntimeInventory } from "./resources/terminal-runtime-inventory.ts";
43
44
 
@@ -96,6 +97,16 @@ function failure(c: Context, error: unknown): Response {
96
97
  return c.json({ error: { code: error.code } }, 409);
97
98
  if (error instanceof z.ZodError || error instanceof SyntaxError || error instanceof TypeError)
98
99
  return c.json({ error: { code: "invalid-request" } }, 400);
100
+ // Everything above tells the client its cause. This answer does not, and a
101
+ // client can only retry it: the cause goes to the daemon's own log.
102
+ const code = (error as { code?: unknown } | null)?.code;
103
+ logger.warn("tmux-server-routes", "request failed as server-unavailable", {
104
+ method: c.req.method,
105
+ route: c.req.routePath,
106
+ errorName: error instanceof Error ? error.name : typeof error,
107
+ ...(typeof code === "string" ? { errorCode: code.slice(0, 80) } : {}),
108
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 300),
109
+ });
99
110
  return c.json({ error: { code: "server-unavailable" } }, 503);
100
111
  }
101
112
  /** Owner capability is mandatory even when the ordinary local HTTP surface is open. */
@@ -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,