ccdeck 3.82.3 → 4.0.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 (146) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/login-item.js +5 -0
  5. package/bin/cli/tui.js +58 -4
  6. package/bin/deck.js +27 -1
  7. package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
  8. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  9. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  10. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  11. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  12. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  13. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  14. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  15. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  16. package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
  17. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  18. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  19. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  20. package/dist/web/assets/app-40gNTTfq.js +361 -0
  21. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  22. package/dist/web/assets/{index-B4c5MZCc.js → index-XIY3yFiN.js} +1 -1
  23. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  24. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  25. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  26. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  27. package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
  28. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  29. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  30. package/dist/web/index.html +16 -6
  31. package/package.json +13 -1
  32. package/release-notes.json +79 -0
  33. package/src/server/account-client.mjs +196 -0
  34. package/src/server/account-connect.mjs +238 -0
  35. package/src/server/account-flag.mjs +106 -0
  36. package/src/server/account-projects.mjs +1 -1
  37. package/src/server/account-service.mjs +532 -0
  38. package/src/server/account-status.mjs +293 -0
  39. package/src/server/account-store.mjs +137 -0
  40. package/src/server/account-sync.mjs +473 -0
  41. package/src/server/account-token-store.mjs +216 -0
  42. package/src/server/account-ui-fields.mjs +126 -0
  43. package/src/server/account-watch.mjs +1 -1
  44. package/src/server/browser-watch-log.mjs +1 -1
  45. package/src/server/browser-watch-store.mjs +1 -1
  46. package/src/server/ccdeck-account-routes.mjs +252 -0
  47. package/src/server/ccusage-install.mjs +2 -2
  48. package/src/server/ccusage-registry.mjs +4 -4
  49. package/src/server/ccusage-session.mjs +11 -0
  50. package/src/server/claude-accounts.mjs +1 -1
  51. package/src/server/claude-recovery.mjs +9 -4
  52. package/src/server/claude-settings-catalog.mjs +6 -6
  53. package/src/server/claude-settings.mjs +1 -1
  54. package/src/server/codex-auto.mjs +1 -1
  55. package/src/server/codex-cost-usage.mjs +7 -2
  56. package/src/server/codex-live-checkpoint.mjs +24 -9
  57. package/src/server/codex-live-engine.mjs +14 -4
  58. package/src/server/codex-live-handoff.mjs +53 -9
  59. package/src/server/codex-names.mjs +49 -0
  60. package/src/server/codex-translate.mjs +1 -1
  61. package/src/server/codex-ultrafast.d.mts +3 -0
  62. package/src/server/codex-ultrafast.mjs +5 -0
  63. package/src/server/codex-watch.mjs +25 -0
  64. package/src/server/command-panel-engine.mjs +300 -0
  65. package/src/server/command-panel-platform.mjs +99 -0
  66. package/src/server/cswap-auto-choice.mjs +1 -1
  67. package/src/server/cswap-auto-loop.mjs +1 -1
  68. package/src/server/cswap-install.mjs +21 -40
  69. package/src/server/deck-home.mjs +6 -0
  70. package/src/server/deck-prefs.mjs +53 -1
  71. package/src/server/detach.mjs +1 -1
  72. package/src/server/engine-download.mjs +277 -0
  73. package/src/server/engine-install.mjs +378 -0
  74. package/src/server/engine-package.mjs +267 -0
  75. package/src/server/event-log.mjs +7 -1
  76. package/src/server/event-pipeline.mjs +29 -1
  77. package/src/server/ghostty-handoff.mjs +81 -0
  78. package/src/server/index.mjs +143 -5
  79. package/src/server/installer.mjs +4 -1
  80. package/src/server/integrations/jira-write-guard.mjs +14 -208
  81. package/src/server/integrations/store.mjs +37 -19
  82. package/src/server/integrations/write-guard.mjs +223 -0
  83. package/src/server/intel-cpu-temperature.mjs +26 -0
  84. package/src/server/lifecycle.mjs +69 -6
  85. package/src/server/log-replay.mjs +4 -0
  86. package/src/server/login-service.mjs +116 -14
  87. package/src/server/macmon.mjs +1 -1
  88. package/src/server/npm-latest.mjs +1 -1
  89. package/src/server/org-telemetry.mjs +1 -1
  90. package/src/server/output-watch.mjs +4 -1
  91. package/src/server/panel-provenance.mjs +390 -0
  92. package/src/server/pinned-build.mjs +14 -0
  93. package/src/server/prefs-refusal.mjs +8 -1
  94. package/src/server/prefs-routes.mjs +60 -11
  95. package/src/server/pro-engine-client.mjs +339 -0
  96. package/src/server/pro-engine-install.mjs +294 -0
  97. package/src/server/pro-engine-terminal.mjs +308 -0
  98. package/src/server/project-discovery.mjs +139 -0
  99. package/src/server/provider-session-name.mjs +58 -0
  100. package/src/server/quota-closes.mjs +1 -1
  101. package/src/server/quota-history.mjs +1 -1
  102. package/src/server/reports.mjs +86 -21
  103. package/src/server/request-gates.mjs +34 -5
  104. package/src/server/restart-note.mjs +1 -1
  105. package/src/server/seed-boundary.mjs +489 -0
  106. package/src/server/session-counts.mjs +244 -0
  107. package/src/server/session-deck-names.mjs +143 -0
  108. package/src/server/session-enrichment.mjs +43 -6
  109. package/src/server/session-name-route.mjs +73 -0
  110. package/src/server/session-summary.mjs +12 -1
  111. package/src/server/session-transcript-routes.mjs +167 -0
  112. package/src/server/swap-log.mjs +1 -1
  113. package/src/server/system-metrics.mjs +57 -0
  114. package/src/server/terminal-bridge.mjs +485 -0
  115. package/src/server/terminal-folder.mjs +61 -0
  116. package/src/server/terminal-js-routes.mjs +752 -0
  117. package/src/server/terminal-routes.mjs +553 -0
  118. package/src/server/terminal-sessions.mjs +759 -0
  119. package/src/server/terminal-socket.mjs +403 -0
  120. package/src/server/terminal-target.mjs +928 -0
  121. package/src/server/thermal-metrics.mjs +13 -9
  122. package/src/server/tmux-control.mjs +1319 -0
  123. package/src/server/tmux-download.mjs +220 -0
  124. package/src/server/tmux.mjs +542 -0
  125. package/src/server/token-redact.mjs +42 -3
  126. package/src/server/tool-audit-report.mjs +44 -6
  127. package/src/server/tool-audit-routes.mjs +12 -1
  128. package/src/server/tool-audit.mjs +42 -8
  129. package/src/server/traffic-radar-monitor.mjs +1 -1
  130. package/src/server/traffic-radar-permission.mjs +1 -1
  131. package/src/server/transcript-gate.mjs +1 -1
  132. package/src/server/transcript-scan.mjs +15 -7
  133. package/src/server/transcript-turns.mjs +154 -0
  134. package/src/server/tui-network.mjs +1 -0
  135. package/src/server/tui-view.mjs +28 -0
  136. package/src/server/utf8-carry.mjs +159 -0
  137. package/src/server/uv-bootstrap.mjs +2 -2
  138. package/src/server/windows-acl.mjs +158 -0
  139. package/src/server/ws-frames.mjs +690 -0
  140. package/dist/web/assets/BrowserWatchModal-BmRTh_xT.js +0 -1
  141. package/dist/web/assets/IntegrationModal-C_f526aV.js +0 -7
  142. package/dist/web/assets/RadioPanel-D2rkf9cg.js +0 -1
  143. package/dist/web/assets/TrafficRadar-BOgVBLIN.js +0 -8
  144. package/dist/web/assets/UsageHistoryModal-BJPTFwM9.js +0 -1
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
  146. package/dist/web/assets/app-DZdZoqJ6.js +0 -358
@@ -0,0 +1,244 @@
1
+ // How many sessions are working, and how many are waiting on their human,
2
+ // from the hook stream alone — for the account's status frame.
3
+ //
4
+ // WHY THE SERVER KEEPS ITS OWN COPY. The deck's waiting and running counts are
5
+ // computed in the BROWSER, from its reducer (ambient-counts.ts blockedSessions
6
+ // and runningSessionCount), and a machine in a fleet usually has no tab open.
7
+ // So this keeps the smallest version of that reducer, the way activity.mjs does
8
+ // for the away-update: per session, whether its root and its subagents are
9
+ // active, which tool calls are in flight, and the waiting block — enough to give
10
+ // the same two numbers the tab would.
11
+ //
12
+ // THE RULES ARE THE PAGE'S, mirrored, and session-counts-mirror.test.ts runs
13
+ // both over the same recorded event logs and requires the same counts after
14
+ // every event:
15
+ //
16
+ // waiting A `Notification` of `permission_prompt` (the newest in-flight
17
+ // call says which subagent asked) or `agent_needs_input` raises a
18
+ // block; `idle_prompt` raises one that is not an alarm. Any later
19
+ // event of the session that is not one of the transcript scans
20
+ // (WAITING_KEEPERS) may clear it: an idle block by anything, the
21
+ // other two only by the root's own traffic or by the subagent that
22
+ // asked (waiting-block.ts clearsWaiting).
23
+ // running A session with any agent active, the way the page counts it: the
24
+ // root from the first event that creates it, a prompt, a session
25
+ // start or a call it makes, until its `Stop` or `SessionEnd`; a
26
+ // subagent from its `SubagentStart` until its `SubagentStop`. A
27
+ // session that is waiting is counted as waiting, not running.
28
+ //
29
+ // TWO DOCUMENTED DIFFERENCES, both clocks the page does not have: a block with
30
+ // no event from its session for two hours is not counted (nobody is coming
31
+ // back to a prompt that old), and a session silent for 30 minutes is not
32
+ // running (activity.mjs's cap — a CLI that crashed never sends its Stop). The
33
+ // page's own sweep answers the second at 90 minutes; the frame is about now.
34
+ //
35
+ // IT DOES CONSUME A REPLAY, unlike activity.mjs: a block raised before a
36
+ // restart is still a person being waited on after it, and the page counts it
37
+ // from the replayed ring too. So the account seeds this from the ring at the
38
+ // moment it starts (`seed`), and is fed every live event after that.
39
+ //
40
+ // Bounded, because session ids arrive from outside (`/api/event` takes them
41
+ // without a credential): past MAX_SESSIONS the session heard from least
42
+ // recently goes.
43
+
44
+ export const WAITING_EXPIRE_MS = 2 * 60 * 60_000;
45
+ export const RUNNING_CAP_MS = 30 * 60_000;
46
+ export const MAX_SESSIONS = 256;
47
+
48
+ /** waiting-block.ts WAITING_KEEPERS, word for word: events that are not proof
49
+ * the session moved. */
50
+ export const WAITING_KEEPERS = new Set([
51
+ "Notification", "ModelObserved", "ContextObserved", "UsageObserved", "SessionNamed",
52
+ "SessionRecapped", "OutputObserved", "ActivityObserved", "JobObserved",
53
+ ]);
54
+
55
+ /** The server's transcript scans, which the page applies to a card that
56
+ * exists and never let create one (reducer.ts, parked-enrichment.ts). */
57
+ const SCANS = new Set([
58
+ "ModelObserved", "ContextObserved", "UsageObserved", "SessionNamed", "SessionRecapped",
59
+ "OutputObserved", "ActivityObserved", "JobObserved",
60
+ ]);
61
+
62
+ /** waiting-block.ts waitingKind. */
63
+ function waitingKind(type) {
64
+ if (type === "permission_prompt") return "permission";
65
+ if (type === "agent_needs_input") return "asked";
66
+ if (type === "idle_prompt") return "idle";
67
+ return null;
68
+ }
69
+
70
+ /** agent-attribution.ts explicitSubagentKey. */
71
+ function subagentKey(p) {
72
+ if (typeof p.agent_id === "string" && p.agent_id) return p.agent_id;
73
+ if (typeof p.parent_tool_use_id === "string" && p.parent_tool_use_id) return p.parent_tool_use_id;
74
+ return null;
75
+ }
76
+
77
+ const alarming = w => w?.kind === "permission" || w?.kind === "asked";
78
+
79
+ /**
80
+ * The counter. `now` is the clock the two documented expiries read; `capture`
81
+ * answers whether anything feeds this deck at all — false, and the counts are
82
+ * `no-capture` rather than a pair of zeros nobody measured.
83
+ */
84
+ export function createSessionCounts({ capture = () => true } = {}) {
85
+ /** session id → state, least recently heard first. */
86
+ const sessions = new Map();
87
+ let ready = false;
88
+
89
+ function session(id, at, create) {
90
+ let s = sessions.get(id);
91
+ if (!s) {
92
+ if (!create) return null;
93
+ s = { rootActive: true, subs: new Map(), stack: [], keyed: false, calls: new Map(), waiting: null, lastAt: at, provider: null };
94
+ while (sessions.size >= MAX_SESSIONS) sessions.delete(sessions.keys().next().value);
95
+ } else {
96
+ sessions.delete(id);
97
+ }
98
+ sessions.set(id, s);
99
+ return s;
100
+ }
101
+
102
+ /** Who a call or an event naming nobody belongs to, as resolveOwner says:
103
+ * the named subagent if it exists, else the newest live one on the stack
104
+ * (unless this session's subagents name themselves), else the root. */
105
+ function ownerOf(s, key) {
106
+ if (key && s.subs.has(key)) return key;
107
+ if (!s.keyed && s.stack.length) {
108
+ const top = s.stack[s.stack.length - 1];
109
+ if (s.subs.has(top)) return top;
110
+ }
111
+ return null;
112
+ }
113
+
114
+ function clearIfAnswered(s, name, key) {
115
+ if (!s.waiting || WAITING_KEEPERS.has(name)) return;
116
+ if (s.waiting.kind === "idle") { s.waiting = null; return; }
117
+ if (key == null) { s.waiting = null; return; }
118
+ if (s.waiting.subKey != null && s.waiting.subKey === key) s.waiting = null;
119
+ }
120
+
121
+ /** The newest call still in flight on this session, as waiting-block.ts
122
+ * blockedCall reads it. */
123
+ function newestCall(s) {
124
+ let newest = null;
125
+ for (const c of s.calls.values()) if (!newest || c.at > newest.at) newest = c;
126
+ return newest;
127
+ }
128
+
129
+ /** One hook payload, as pushEvent receives it, stamped when it arrived. */
130
+ function note(raw, at) {
131
+ if (!raw || typeof raw !== "object") return;
132
+ const name = typeof raw.hook_event_name === "string" ? raw.hook_event_name : "";
133
+ if (name === "__clear") { sessions.clear(); return; }
134
+ const id = typeof raw.session_id === "string" && raw.session_id ? raw.session_id : "unknown";
135
+ const key = subagentKey(raw);
136
+ if (SCANS.has(name)) {
137
+ // A scan moves nothing and creates nothing; it is still the session's id
138
+ // arriving from a running process, which the clocks below count — except
139
+ // a background job's file, which the page does not count either.
140
+ const s = sessions.get(id);
141
+ if (s && name !== "JobObserved" && at > s.lastAt) s.lastAt = at;
142
+ return;
143
+ }
144
+ const s = session(id, at, true);
145
+ if (at > s.lastAt) s.lastAt = at;
146
+ if (raw.provider === "codex") s.provider = "codex";
147
+ // The block's clear runs first, before the event does anything else.
148
+ clearIfAnswered(s, name, key);
149
+ if (name !== "SubagentStart" && name !== "SubagentStop" && typeof raw.agent_id === "string" && raw.agent_id) s.keyed = true;
150
+
151
+ switch (name) {
152
+ case "SessionStart":
153
+ case "UserPromptSubmit":
154
+ s.rootActive = true;
155
+ break;
156
+ case "SubagentStart":
157
+ if (key) {
158
+ s.subs.set(key, true);
159
+ if (!s.stack.includes(key)) s.stack.push(key);
160
+ }
161
+ break;
162
+ case "SubagentStop":
163
+ if (key && s.subs.has(key)) s.subs.set(key, false);
164
+ if (key) {
165
+ const at2 = s.stack.lastIndexOf(key);
166
+ if (at2 >= 0) s.stack.splice(at2, 1);
167
+ }
168
+ break;
169
+ case "PreToolUse": {
170
+ const owner = ownerOf(s, key);
171
+ if (owner) s.subs.set(owner, true);
172
+ else s.rootActive = true;
173
+ if (typeof raw.tool_use_id === "string" && raw.tool_use_id && !s.calls.has(raw.tool_use_id)) {
174
+ s.calls.set(raw.tool_use_id, { at, key });
175
+ }
176
+ break;
177
+ }
178
+ case "PostToolUse":
179
+ case "PostToolUseFailure":
180
+ if (typeof raw.tool_use_id === "string") s.calls.delete(raw.tool_use_id);
181
+ break;
182
+ case "Stop":
183
+ case "SessionEnd":
184
+ s.rootActive = false;
185
+ // The root's own calls cannot outlive its turn (session-lifecycle.ts);
186
+ // a subagent's can. Codex's missing result is a call parked on a
187
+ // person, and is left alone.
188
+ if (s.provider !== "codex") for (const [cid, c] of s.calls) if (c.key == null) s.calls.delete(cid);
189
+ s.stack.length = 0;
190
+ break;
191
+ case "Notification": {
192
+ const kind = waitingKind(raw.notification_type);
193
+ if (!kind) break;
194
+ const message = typeof raw.message === "string" ? raw.message : "";
195
+ const prev = s.waiting;
196
+ if (prev && prev.kind === kind && prev.message === message) {
197
+ prev.since = Math.min(prev.since, at);
198
+ } else {
199
+ const block = { kind, message, since: at, subKey: null };
200
+ if (kind === "permission") {
201
+ const call = newestCall(s);
202
+ if (call?.key) block.subKey = call.key;
203
+ }
204
+ s.waiting = block;
205
+ }
206
+ break;
207
+ }
208
+ default:
209
+ break;
210
+ }
211
+ }
212
+
213
+ /** Every envelope the ring holds, oldest first: the replayed history and
214
+ * whatever arrived since, so the counts start where the page's would. */
215
+ function seed(envelopes) {
216
+ for (const e of envelopes ?? []) if (e && e.payload) note(e.payload, e.receivedAt);
217
+ }
218
+
219
+ /** The two numbers at `now`, as the status frame carries them — or why they
220
+ * cannot be told. */
221
+ function reading(now = Date.now()) {
222
+ if (!ready) return { unknown: "starting" };
223
+ if (!capture()) return { unknown: "no-capture" };
224
+ let running = 0;
225
+ let waiting = 0;
226
+ for (const s of sessions.values()) {
227
+ const quiet = Math.abs(now - s.lastAt);
228
+ if (alarming(s.waiting) && quiet <= WAITING_EXPIRE_MS) { waiting++; continue; }
229
+ if (quiet > RUNNING_CAP_MS) continue;
230
+ if (s.rootActive || [...s.subs.values()].some(Boolean)) running++;
231
+ }
232
+ return { running, waiting, sampledAt: now };
233
+ }
234
+
235
+ return {
236
+ note,
237
+ seed,
238
+ /** The boot replay is over and the ring has been read: counts are real. */
239
+ markReady: () => { ready = true; },
240
+ reading,
241
+ /** For the suite. */
242
+ size: () => sessions.size,
243
+ };
244
+ }
@@ -0,0 +1,143 @@
1
+ // The names a reader gives sessions in the deck (internal #101).
2
+ //
3
+ // Display overrides keyed by provider and session. The HTTP rename action can
4
+ // first update native provider metadata (provider-session-name.mjs); this store
5
+ // remains independent so replay, clearing and legacy API clients keep working.
6
+ //
7
+ // HOW IT REACHES A PAGE. As the provider's name does, on a `SessionNamed`
8
+ // event, with one more field: `deckName`, the name, or null for "cleared". An
9
+ // absent `deckName` says nothing, so a transcript's own naming, which keeps
10
+ // arriving while the session runs, never overwrites a name typed here. The
11
+ // write is announced at once (session-name-route.mjs) and logged, so a reload
12
+ // and a restart replay it; a session heard from again after a restart is told
13
+ // once more (session-enrichment.mjs, maybeAnnounceDeckName), for the log a
14
+ // rotation took it out of.
15
+ import { readFile, mkdir } from "node:fs/promises";
16
+ import { dirname, join } from "node:path";
17
+ import { deckDataDir } from "./deck-home.mjs";
18
+ import { writeFileAtomic } from "./atomic-write.mjs";
19
+
20
+ /** The longest name kept, in characters (code points). The field holds the
21
+ * same, so a name is never cut where the reader cannot see it. */
22
+ export const DECK_NAME_MAX = 120;
23
+ /** The most names kept. Past it the oldest goes: a name for a session nobody
24
+ * has seen in months is the one nobody misses. */
25
+ export const DECK_NAMES_CAP = 1000;
26
+
27
+ const PROVIDERS = new Set(["claude", "codex"]);
28
+ // A Claude session id is a UUID, a Codex thread id one too; the deck's own
29
+ // ids for a launch are letters, digits and dashes. Nothing here is a path.
30
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
31
+ // What a name may not hold: control characters (a newline would break the
32
+ // row it is drawn on), the zero-width and direction marks that make two names
33
+ // look the same, and the byte-order mark.
34
+ const UNSEEN = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g;
35
+
36
+ export function deckNamesPath(home = deckDataDir()) {
37
+ return join(home, "session-names.json");
38
+ }
39
+
40
+ /** Where a session's name is kept, or null for a provider or id the deck does
41
+ * not name. A missing provider is Claude's, as the reducer reads one. */
42
+ export function deckNameKey(provider, sessionId) {
43
+ const p = provider ?? "claude";
44
+ if (!PROVIDERS.has(p) || typeof sessionId !== "string" || !SESSION_ID.test(sessionId)) return null;
45
+ return `${p}:${sessionId}`;
46
+ }
47
+
48
+ /**
49
+ * A name as it is kept: one line, its spaces collapsed, at most DECK_NAME_MAX
50
+ * characters. Null for one that is empty after that, or for null itself: the
51
+ * name cleared. Undefined for anything that is not a name at all.
52
+ */
53
+ export function cleanDeckName(raw) {
54
+ if (raw === null) return null;
55
+ if (typeof raw !== "string") return undefined;
56
+ const one = raw.replace(UNSEEN, " ").replace(/\s+/g, " ").trim();
57
+ if (!one) return null;
58
+ return [...one].slice(0, DECK_NAME_MAX).join("").trim();
59
+ }
60
+
61
+ /** Whatever is on disk, as a map of key to { name, at }. A file this version
62
+ * cannot read is no names, not an error: the deck still runs. */
63
+ export function normaliseDeckNames(raw) {
64
+ const out = new Map();
65
+ const names = raw && typeof raw === "object" && raw.names && typeof raw.names === "object" ? raw.names : {};
66
+ for (const [key, entry] of Object.entries(names)) {
67
+ const cut = key.indexOf(":");
68
+ if (cut < 0 || deckNameKey(key.slice(0, cut), key.slice(cut + 1)) !== key) continue;
69
+ const name = cleanDeckName(entry && typeof entry === "object" ? entry.name : undefined);
70
+ if (typeof name !== "string") continue;
71
+ out.set(key, { name, at: Number.isFinite(entry.at) ? entry.at : 0 });
72
+ }
73
+ return capDeckNames(out);
74
+ }
75
+
76
+ /** The newest DECK_NAMES_CAP of them. */
77
+ export function capDeckNames(names) {
78
+ if (names.size <= DECK_NAMES_CAP) return names;
79
+ const kept = [...names].sort((a, b) => b[1].at - a[1].at).slice(0, DECK_NAMES_CAP);
80
+ return new Map(kept);
81
+ }
82
+
83
+ // The names as last read or written. This process is the file's only writer,
84
+ // so after the boot read every question is answered from memory.
85
+ let _held = null;
86
+ let _path = null;
87
+
88
+ /** Read the file once, as the deck starts. Later calls answer what is held. */
89
+ export async function loadDeckNames(path = deckNamesPath()) {
90
+ if (_held && _path === path) return _held;
91
+ _path = path;
92
+ try { _held = normaliseDeckNames(JSON.parse(await readFile(path, "utf8"))); } catch { _held = new Map(); }
93
+ return _held;
94
+ }
95
+
96
+ /** A session's name, or undefined for none — or before the boot read. */
97
+ export function deckNameFor(provider, sessionId) {
98
+ const key = deckNameKey(provider, sessionId);
99
+ return key && _held ? _held.get(key)?.name : undefined;
100
+ }
101
+
102
+ /** Every name held, as [provider, sessionId, name] — the boot's announce. */
103
+ export function heldDeckNames() {
104
+ if (!_held) return [];
105
+ return [..._held].map(([key, { name }]) => {
106
+ const cut = key.indexOf(":");
107
+ return [key.slice(0, cut), key.slice(cut + 1), name];
108
+ });
109
+ }
110
+
111
+ let _writes = Promise.resolve();
112
+ /**
113
+ * Keep a session's name, or clear it with null, one write at a time. The file
114
+ * is written whole and atomically before memory changes, so a write that
115
+ * fails leaves both as they were and the caller says so. Answers the name
116
+ * kept (null when cleared).
117
+ */
118
+ export function writeDeckName(provider, sessionId, name, { path = deckNamesPath(), now = Date.now(), writeFile = writeFileAtomic } = {}) {
119
+ const key = deckNameKey(provider, sessionId);
120
+ if (!key) return Promise.reject(new TypeError("not a session the deck names"));
121
+ const clean = cleanDeckName(name);
122
+ if (clean === undefined) return Promise.reject(new TypeError("not a name"));
123
+ const done = _writes.then(async () => {
124
+ const before = await loadDeckNames(path);
125
+ const next = new Map(before);
126
+ if (clean === null) next.delete(key); else next.set(key, { name: clean, at: now });
127
+ const kept = capDeckNames(next);
128
+ const body = { version: 1, names: Object.fromEntries(kept) };
129
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
130
+ await writeFile(path, `${JSON.stringify(body)}\n`);
131
+ _held = kept;
132
+ return clean;
133
+ });
134
+ _writes = done.catch(() => {});
135
+ return done;
136
+ }
137
+
138
+ /** Tests only: forget what is held, as a new process would. */
139
+ export function resetDeckNamesForTest() {
140
+ _held = null;
141
+ _path = null;
142
+ _writes = Promise.resolve();
143
+ }
@@ -32,6 +32,8 @@ import { pushEvent } from "./event-sink.mjs";
32
32
  // One read per session at a time, and none inside the window — the gate each
33
33
  // pass below keeps. See session-read-gate.mjs.
34
34
  import { sessionReadGate } from "./session-read-gate.mjs";
35
+ // The names a reader gave sessions in the deck (internal #101).
36
+ import { deckNameFor } from "./session-deck-names.mjs";
35
37
 
36
38
  /**
37
39
  * The session a hook payload is about and the transcript it names, or null when
@@ -417,7 +419,7 @@ function maybeResolveUsage(payload) {
417
419
  // The emit is what is actually kept rare, and it is gated on a CHANGE: with 685
418
420
  // records carrying 2 distinct values, a per-pass emit would be ~683 events
419
421
  // saying nothing. Sessions that never get named emit nothing at all.
420
- const nameBySession = new Map(); // sid -> `${agentName}\0${aiTitle}`
422
+ const nameBySession = new Map(); // sid -> `${sessionName}\0${aiTitle}`
421
423
  const nameReads = sessionReadGate(MODEL_READ_THROTTLE_MS);
422
424
 
423
425
  /** The naming the cursor has folded so far, or null when the scan has nothing.
@@ -435,8 +437,11 @@ const nameReads = sessionReadGate(MODEL_READ_THROTTLE_MS);
435
437
  async function readSessionNamingFromTranscript(path) {
436
438
  const state = await scanTranscript(path);
437
439
  if (!state) return null;
438
- const naming = (state.agentName || state.aiTitle)
439
- ? { agentName: state.agentName, aiTitle: state.aiTitle }
440
+ // The name the user gave the session (/rename, `--name`) is the one Claude
441
+ // Code prints in its prompt, so it outranks the name CC made up for it.
442
+ const name = state.customTitle || state.agentName;
443
+ const naming = (name || state.aiTitle)
444
+ ? { name: name ?? null, aiTitle: state.aiTitle }
440
445
  : null;
441
446
  return { naming, recap: state.recap ?? null };
442
447
  }
@@ -451,18 +456,47 @@ function maybeResolveSessionName(payload) {
451
456
  noteRecap(sid, read.recap);
452
457
  const naming = read.naming;
453
458
  if (!naming) return;
454
- const sig = `${naming.agentName ?? ""}\u0000${naming.aiTitle ?? ""}`;
459
+ const sig = `${naming.name ?? ""}\u0000${naming.aiTitle ?? ""}`;
455
460
  if (nameBySession.get(sid) === sig) return;
456
461
  nameBySession.set(sid, sig);
457
462
  pushEvent({
458
463
  hook_event_name: "SessionNamed",
459
464
  session_id: sid,
460
- sessionName: naming.agentName ?? null,
465
+ sessionName: naming.name ?? null,
461
466
  sessionTitle: naming.aiTitle ?? null,
462
467
  }, "internal");
463
468
  }));
464
469
  }
465
470
 
471
+ // ─── The deck's own name for a session (internal #101) ──────────────────
472
+ // A name typed in the deck rides SessionNamed as `deckName`
473
+ // (session-deck-names.mjs). The route announces a change as it is kept, and
474
+ // that event is logged, so a reload and a restart replay it. What this adds is
475
+ // the session heard from again after a restart whose log no longer holds the
476
+ // announce (a rotation, a Clear): its first live event tells the pages once.
477
+ // Once per session per run, and again after forgetSession or a Clear — the
478
+ // gate below, which both drop.
479
+ const deckNameAnnounced = new Set(); // sid already told this run
480
+
481
+ /** Tell every page a session's deck name (or that it was cleared, null). */
482
+ function announceDeckName(sid, name, opts) {
483
+ deckNameAnnounced.add(sid);
484
+ pushEvent({ hook_event_name: "SessionNamed", session_id: sid, deckName: name }, "internal", opts);
485
+ }
486
+
487
+ /** On a session's live event: its kept name, once, if it has one. After the
488
+ * event that carried it is in the ring — never inside its push. */
489
+ function maybeAnnounceDeckName(payload, provider) {
490
+ const sid = payload?.session_id;
491
+ if (typeof sid !== "string" || !sid || deckNameAnnounced.has(sid)) return;
492
+ deckNameAnnounced.add(sid);
493
+ const name = deckNameFor(provider, sid);
494
+ if (!name) return;
495
+ // Not logged: the log holds the write that set it, or lost it to a
496
+ // rotation, and this re-announce happens every run.
497
+ queueMicrotask(() => announceDeckName(sid, name, { persist: false }));
498
+ }
499
+
466
500
  // ─── Session recap ───────────────────────────────────────────────────────
467
501
  // Claude Code's "※ recap:" line (see session-recap.mjs). It comes off the
468
502
  // transcript cursor like the naming above, and its emit is gated the same way:
@@ -683,6 +717,8 @@ function forgetEnrichment(sid) {
683
717
  // name. A tab that connects after the event ring has rolled past the
684
718
  // original SessionNamed shows that session unnamed for the rest of its life.
685
719
  nameBySession.delete(sid);
720
+ // And the deck name's: a session heard from again is told its name again.
721
+ deckNameAnnounced.delete(sid);
686
722
  // The recap's gate, for the same reason — see noteRecap.
687
723
  recapBySession.delete(sid);
688
724
  // And the activity fold and the job's gate: a session heard from again
@@ -703,6 +739,7 @@ function forgetEnrichment(sid) {
703
739
  */
704
740
  function clearEnrichmentGates() {
705
741
  nameBySession.clear();
742
+ deckNameAnnounced.clear();
706
743
  recapBySession.clear();
707
744
  activityBySession.clear();
708
745
  jobBySession.clear();
@@ -721,7 +758,7 @@ function clearEnrichmentGates() {
721
758
  // marked at each declaration, so the declarations read as they did where they
722
759
  // came from.
723
760
  export {
724
- clearEnrichmentGates, forgetEnrichment, knownModelId, maybeResolveCodexMemory,
761
+ announceDeckName, clearEnrichmentGates, forgetEnrichment, knownModelId, maybeAnnounceDeckName, maybeResolveCodexMemory,
725
762
  maybeResolveContext, maybeResolveModel, maybeResolveSessionName, maybeResolveUsage,
726
763
  noteJob, onRecapTail, onTranscriptTail,
727
764
  };
@@ -0,0 +1,73 @@
1
+ // POST /api/session-name: a reader names a session in the deck, or clears the
2
+ // name they gave it (internal #101). The name is kept in session-names.json
3
+ // (session-deck-names.mjs) and announced on SessionNamed as `deckName`, so the
4
+ // list, the card, the Workspace header, the Inspector and quick open all read
5
+ // it from the one field they already read a session's name from.
6
+ //
7
+ // { provider: "claude" | "codex", sessionId, name: string | null }
8
+ //
9
+ // An empty name, or null, clears it: the session reads by the provider's name
10
+ // again. Answers { ok: true, name } with the name as kept (cut to
11
+ // DECK_NAME_MAX, one line), or { ok: false, reason } — `bad_request` for a
12
+ // body that names no session or holds no name, `not_saved` when the file could
13
+ // not be written. Nothing is announced unless the write landed, so a page that
14
+ // saw an error still shows the name the deck has.
15
+ //
16
+ // It is behind the same three gates as every other route (index.mjs): a page
17
+ // of this deck, or a caller with its token.
18
+ import { PRODUCT } from "./brand.mjs";
19
+ import { readBody, send } from "./http-io.mjs";
20
+ import { cleanDeckName, deckNameKey, heldDeckNames, writeDeckName } from "./session-deck-names.mjs";
21
+ import { announceDeckName } from "./session-enrichment.mjs";
22
+ import { renameProviderSession } from "./provider-session-name.mjs";
23
+
24
+ /**
25
+ * At boot, after the log's replay: each kept name whose session the replay put
26
+ * back in the ring, announced once and not logged again. The log normally
27
+ * holds the write that set it already; this is for the log a rotation or a
28
+ * size cap cut it out of, where the session's later events survived. A name
29
+ * for a session not in the ring is left for that session's first live event
30
+ * (session-enrichment.mjs, maybeAnnounceDeckName). Answers how many it told.
31
+ */
32
+ export function announceKeptNames(envelopes, announce = announceDeckName) {
33
+ const seen = new Set();
34
+ for (const e of envelopes) {
35
+ const sid = e?.payload?.session_id;
36
+ if (typeof sid === "string" && sid) seen.add(sid);
37
+ }
38
+ let told = 0;
39
+ for (const [, sid, name] of heldDeckNames()) {
40
+ if (!seen.has(sid)) continue;
41
+ announce(sid, name, { persist: false });
42
+ told++;
43
+ }
44
+ return told;
45
+ }
46
+
47
+ export async function handleSessionNameWrite(req, res, { write = writeDeckName, announce = announceDeckName, renameProvider = renameProviderSession } = {}) {
48
+ const raw = await readBody(req, res).catch(() => null);
49
+ let body = null;
50
+ try { body = JSON.parse(raw ?? ""); } catch { /* answered below */ }
51
+ if (!body || typeof body !== "object") return send(res, 400, { ok: false, reason: "bad_request" });
52
+ const provider = body.provider ?? "claude";
53
+ const { sessionId } = body;
54
+ const name = cleanDeckName(body.name === "" ? null : body.name);
55
+ if (!deckNameKey(provider, sessionId) || name === undefined) {
56
+ return send(res, 400, { ok: false, reason: "bad_request" });
57
+ }
58
+ let kept;
59
+ if (body.syncProvider === true && name !== null) {
60
+ try { await renameProvider(provider, sessionId, name); }
61
+ catch { return send(res, 409, { ok: false, reason: "provider_name_not_saved" }); }
62
+ }
63
+ try {
64
+ kept = await write(provider, sessionId, name);
65
+ } catch (err) {
66
+ // A data folder this user cannot write is the machine's to fix. The
67
+ // error's code only: never the path, never the name.
68
+ console.error(`${PRODUCT}: a session name was not saved (${err?.code ?? "error"})`);
69
+ return send(res, 500, { ok: false, reason: "not_saved" });
70
+ }
71
+ announce(sessionId, kept);
72
+ return send(res, 200, { ok: true, name: kept });
73
+ }
@@ -90,7 +90,18 @@ function blankSession(id, at) {
90
90
  function enrichSummary(s, p, name) {
91
91
  if (!s.cwd && typeof p.cwd === "string" && p.cwd) s.cwd = p.cwd;
92
92
  if (typeof p.model === "string" && p.model && !subagentKeyOf(p)) s.model = p.model;
93
- if (name === "SessionNamed") s.name = p.sessionTitle ?? p.sessionName ?? s.name;
93
+ if (name === "SessionNamed") nameSummary(s, p);
94
+ }
95
+
96
+ /** The session's name as its card and rail row say it (sessionDisplay in
97
+ * session-display.ts): the name, the user's or else Claude Code's, over the
98
+ * title. Each is kept until an event says it again, as applySessionNamed in
99
+ * transcript-events.ts keeps them, so a pass carrying only one wipes neither. */
100
+ function nameSummary(s, p) {
101
+ const said = v => (typeof v === "string" ? v.trim() : "");
102
+ if (said(p.sessionName)) s.sessionName = said(p.sessionName);
103
+ if (said(p.sessionTitle)) s.sessionTitle = said(p.sessionTitle);
104
+ s.name = s.sessionName || s.sessionTitle || s.name;
94
105
  }
95
106
 
96
107
  /** Scanned facts can wait for a session, but cannot give it a provider, a