ccdeck 3.82.2 → 3.82.4

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 (31) hide show
  1. package/README.md +9 -1
  2. package/bin/cli/login-item.js +5 -0
  3. package/dist/web/assets/{BrowserWatchModal-2_oD4OEZ.js → BrowserWatchModal-CWVooKxD.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-C5Hg-4qW.js → IntegrationModal-DLX43RIK.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-D_qTIO0G.js → RadioPanel-Cj6PjrvQ.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-Br6HVrU-.js → TrafficRadar-Bq1YcuHB.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-HQY6FX_t.js → UsageHistoryModal-CMSCca5_.js} +1 -1
  8. package/dist/web/assets/{app-BP4tkqfl.js → app-BHxsMz3-.js} +63 -63
  9. package/dist/web/assets/{index-BR00GbtO.js → index-B-l-VxLm.js} +1 -1
  10. package/dist/web/index.html +2 -2
  11. package/package.json +1 -1
  12. package/release-notes.json +36 -1
  13. package/src/server/account-projects.mjs +42 -14
  14. package/src/server/boot-lock.mjs +6 -1
  15. package/src/server/ccusage-runner.mjs +4 -1
  16. package/src/server/codex-engine-rpc.mjs +1 -0
  17. package/src/server/exec-children.mjs +21 -6
  18. package/src/server/exec.mjs +46 -3
  19. package/src/server/http-io.mjs +3 -19
  20. package/src/server/integrations/store.mjs +12 -5
  21. package/src/server/lan-routes.mjs +13 -3
  22. package/src/server/lifecycle.mjs +13 -5
  23. package/src/server/login-service.mjs +109 -13
  24. package/src/server/metrics-history.mjs +17 -8
  25. package/src/server/quota-closes.mjs +5 -2
  26. package/src/server/quota-history.mjs +38 -15
  27. package/src/server/session-summary.mjs +34 -10
  28. package/src/server/swap-log.mjs +9 -4
  29. package/src/server/thermal-metrics.mjs +31 -3
  30. package/src/server/tool-audit.mjs +24 -12
  31. package/src/server/tui-machine.mjs +2 -2
@@ -43,6 +43,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node
43
43
  // from a Mac — the same reason deck-home.mjs and claudeCliCandidates do it, and
44
44
  // the third time this class of bug has been caught here.
45
45
  import { posix as posixPath, win32 as winPath } from "node:path";
46
+ import { writeFileAtomic } from "./atomic-write.mjs";
46
47
 
47
48
  /** The joiner for the platform being ASKED ABOUT, which is not always this one. */
48
49
  const joinFor = (platform) => (platform === "win32" ? winPath.join : posixPath.join);
@@ -95,7 +96,7 @@ export function xmlEscape(s) {
95
96
  * at. The default band is the honest one.
96
97
  */
97
98
  export function plistFor({ execPath, script, logPath, label = SERVICE_LABEL, args = [], env = {} } = {}) {
98
- const argv = [execPath, script, ...args].map(a => ` <string>${xmlEscape(a)}</string>`).join("\n");
99
+ const argv = [...GUARD_WORDS, execPath, script, ...args].map(a => ` <string>${xmlEscape(a)}</string>`).join("\n");
99
100
  const vars = Object.entries({ AGENTS_DECK_DETACHED: "1", ...env })
100
101
  .map(([k, v]) => ` <key>${xmlEscape(k)}</key>\n <string>${xmlEscape(v)}</string>`)
101
102
  .join("\n");
@@ -128,6 +129,27 @@ ${vars}
128
129
  * unit, and `%%` is the literal. */
129
130
  const sdEscape = (s) => String(s).replace(/%/g, "%%");
130
131
 
132
+ /**
133
+ * What a login item runs on Linux and macOS, as the shell's own program text.
134
+ *
135
+ * ONE CONSTANT, with the paths handed over as positional arguments after it,
136
+ * never spliced into the text, so a space, a quote or a `$` in an install path
137
+ * is only ever an argument (the rule NODE_FALLBACK in installer.mjs follows).
138
+ * `$0` is the label, `$1` node, `$2` the deck's script and the rest its
139
+ * arguments. When the script is gone, because `npm uninstall -g ccdeck` took it
140
+ * and nothing took the login item, the job ends 0 and says nothing. Before, it
141
+ * was a node "Cannot find module" stack in deck.log and a failed unit at every
142
+ * login.
143
+ */
144
+ export const LOGIN_GUARD = '[ -f "$2" ] || exit 0; exec "$@"';
145
+ /** The words in front of the old command, which is exactly [node, script, ...args]. */
146
+ const GUARD_WORDS = ["/bin/sh", "-c", LOGIN_GUARD, "ccdeck-login"];
147
+ /** The same words, as they stand in a systemd ExecStart line. */
148
+ const sdWord = (a) => {
149
+ const v = sdEscape(a).replace(/\$/g, "$$$$");
150
+ return /[\s"'\\]/.test(v) ? `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : v;
151
+ };
152
+
131
153
  /**
132
154
  * The systemd --user unit.
133
155
  *
@@ -144,10 +166,7 @@ export function unitFor({ execPath, script, logPath, args = [], env = {}, produc
144
166
  // and the same `%` in an install path made ExecStart a fatal error.
145
167
  // An argument with whitespace, a quote or a backslash is quoted, with the
146
168
  // C escapes systemd's word splitting reads inside the quotes.
147
- const cmd = [execPath, script, ...args].map(a => {
148
- const v = sdEscape(a).replace(/\$/g, "$$$$");
149
- return /[\s"'\\]/.test(v) ? `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : v;
150
- }).join(" ");
169
+ const cmd = [...GUARD_WORDS, execPath, script, ...args].map(sdWord).join(" ");
151
170
  // QUOTED, AND `%` ESCAPED. systemd.exec(5) splits an Environment= assignment
152
171
  // on whitespace unless the whole thing is double-quoted, and it expands `%`
153
172
  // specifiers in the value. ExecStart above quotes its own arguments; this
@@ -188,6 +207,19 @@ WantedBy=default.target
188
207
  `;
189
208
  }
190
209
 
210
+ /**
211
+ * The Windows account this process runs as, in the form a Task Scheduler
212
+ * <UserId> takes: DOMAIN\user (the machine name for a local account), or the
213
+ * bare user name when Windows left USERDOMAIN out. Empty when neither is set,
214
+ * and then the task is written without one, as before.
215
+ */
216
+ export function windowsAccount(env = process.env) {
217
+ const user = String(env?.USERNAME ?? "").trim();
218
+ if (!user) return "";
219
+ const domain = String(env?.USERDOMAIN ?? "").trim();
220
+ return domain ? `${domain}\\${user}` : user;
221
+ }
222
+
191
223
  /**
192
224
  * The Task Scheduler job, as XML.
193
225
  *
@@ -202,11 +234,20 @@ WantedBy=default.target
202
234
  * UTF-16LE with a BOM on disk, which is what schtasks requires and what a file
203
235
  * written as UTF-8 is silently rejected for.
204
236
  *
205
- * No <UserId>: schtasks fills in the account running it, which is the one whose
206
- * login this task is about. Naming it would be a guess that breaks on a renamed
207
- * account, a domain user or a machine in another locale.
237
+ * No <UserId> in the PRINCIPAL: schtasks fills in the account running it, which
238
+ * is the one whose login this task is about.
239
+ *
240
+ * But the LOGON TRIGGER names the account, when the caller knows it. A logon
241
+ * trigger without one fires at ANY user's logon, and Windows lets only an
242
+ * administrator register that: on a real Windows 11 standard account, schtasks
243
+ * answered this file with "ERROR: Access is denied." while the same file with
244
+ * the account in the trigger was accepted (VM check, 2026-11-15). So the login
245
+ * item this deck offers never registered for an ordinary account. The name is
246
+ * the process's own USERDOMAIN\USERNAME (windowsAccount): not a guess, not
247
+ * translated on a localised Windows, the domain form for a domain user, and
248
+ * Task Scheduler resolves it to the account's SID when the task is registered.
208
249
  */
209
- export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } = {}) {
250
+ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck", userId = "" } = {}) {
210
251
  // NO ENVIRONMENT BLOCK, and that is the schema's doing rather than an
211
252
  // omission here: there is nowhere in a Task Scheduler task to put a variable.
212
253
  // Which is the second reason Windows runs the LAUNCHER and lets it detach
@@ -214,7 +255,14 @@ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } =
214
255
  // way to carry it. The launcher writes deck.log either way, so the output
215
256
  // this platform also cannot redirect lands in the same file as everywhere
216
257
  // else.
217
- const argLine = [script, ...args].map(a => (/\s/.test(a) ? `"${a}"` : a)).join(" ");
258
+ // THROUGH cmd.exe, so a deck script that `npm uninstall -g` took away ends the
259
+ // task with exit 0 instead of node's "Cannot find module" window at every
260
+ // logon. `if exist` has no else, so a missing script runs nothing; /s strips
261
+ // the one outer pair of quotes and every path inside is quoted on its own.
262
+ // When the script exists this runs the same node on the same script with the
263
+ // same arguments as before.
264
+ const rest = args.map(a => ` ${/\s/.test(a) ? `"${a}"` : a}`).join("");
265
+ const argLine = `/d /s /c "if exist "${script}" ("${execPath}" "${script}"${rest})"`;
218
266
  return `<?xml version="1.0" encoding="UTF-16"?>
219
267
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
220
268
  <RegistrationInfo>
@@ -222,7 +270,7 @@ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } =
222
270
  </RegistrationInfo>
223
271
  <Triggers>
224
272
  <LogonTrigger>
225
- <Enabled>true</Enabled>
273
+ <Enabled>true</Enabled>${userId ? `\n <UserId>${xmlEscape(userId)}</UserId>` : ""}
226
274
  </LogonTrigger>
227
275
  </Triggers>
228
276
  <Principals>
@@ -252,7 +300,7 @@ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } =
252
300
  </Settings>
253
301
  <Actions Context="Author">
254
302
  <Exec>
255
- <Command>${xmlEscape(execPath)}</Command>
303
+ <Command>cmd.exe</Command>
256
304
  <Arguments>${xmlEscape(argLine)}</Arguments>
257
305
  </Exec>
258
306
  </Actions>
@@ -528,7 +576,7 @@ export function installService({
528
576
  // this deck owns.
529
577
  const xmlPath = joinFor(platform)(logPathDir(logPath), `${SERVICE_LABEL}-task.xml`);
530
578
  // UTF-16LE with a BOM: schtasks rejects UTF-8 with an unhelpful error.
531
- fs.writeFileSync(xmlPath, "\uFEFF" + taskXmlFor({ execPath, script, args, product }), "utf16le");
579
+ fs.writeFileSync(xmlPath, "\uFEFF" + taskXmlFor({ execPath, script, args, product, userId: windowsAccount(env) }), "utf16le");
532
580
  const cmd = registerCommand(platform, xmlPath);
533
581
  const out = run(cmd.file, cmd.args, { encoding: "utf8", windowsHide: true });
534
582
  if (out?.status !== 0) {
@@ -567,6 +615,54 @@ export function installService({
567
615
  }
568
616
  }
569
617
 
618
+ /**
619
+ * A login item written before the guard, as the guarded one. Text in, text
620
+ * out, null when there is nothing to change (already guarded, or not a shape
621
+ * this file writes). The old command was exactly [node, script, ...args], which
622
+ * is what the guard takes as its own positional arguments, so the words are put
623
+ * in front of it and nothing else in the file moves.
624
+ */
625
+ export function guardedItemText(text, platform = process.platform) {
626
+ if (platform === "linux") {
627
+ const m = /^ExecStart=(.*)$/m.exec(text);
628
+ if (!m || m[1].startsWith("/bin/sh -c ") || m[1].trim() === "") return null;
629
+ return text.replace(/^ExecStart=.*$/m, () => `ExecStart=${GUARD_WORDS.map(sdWord).join(" ")} ${m[1]}`);
630
+ }
631
+ if (platform === "darwin") {
632
+ const m = /(<key>ProgramArguments<\/key>\s*<array>\n)(\s*<string>)([^<]*)(<\/string>)/.exec(text);
633
+ if (!m || m[3] === "/bin/sh") return null;
634
+ const words = GUARD_WORDS.map(a => ` <string>${xmlEscape(a)}</string>\n`).join("");
635
+ return text.replace(m[0], () => `${m[1]}${words}${m[2]}${m[3]}${m[4]}`);
636
+ }
637
+ return null;
638
+ }
639
+
640
+ /**
641
+ * Bring the login item of an older deck to the guarded form, on the platform's
642
+ * own file. File content only: no enable, no load, no schtasks, so nothing is
643
+ * started, stopped or registered by it. Windows keeps its task in the scheduler
644
+ * rather than in a file, and rewriting it would take schtasks, so it is not
645
+ * touched here. Answers whether it rewrote the file, never throws.
646
+ */
647
+ export async function refreshLoginItem({
648
+ platform = process.platform,
649
+ home = homedir(),
650
+ env = process.env,
651
+ read = readFileSync,
652
+ } = {}) {
653
+ try {
654
+ if (platform !== "linux" && platform !== "darwin") return false;
655
+ const path = servicePath(platform, home, env);
656
+ const text = read(path, "utf8");
657
+ // Ours: the marker both writers put in every job.
658
+ if (!text.includes("AGENTS_DECK_DETACHED")) return false;
659
+ const next = guardedItemText(text, platform);
660
+ if (next === null || next === text) return false;
661
+ await writeFileAtomic(path, next);
662
+ return true;
663
+ } catch { return false; }
664
+ }
665
+
570
666
  /**
571
667
  * Take it away. Same contract: a verdict, never a throw.
572
668
  *
@@ -47,16 +47,25 @@ export const BUCKET_MS = 60_000;
47
47
  * should be.
48
48
  */
49
49
  export function record(key, value, nowMs = Date.now()) {
50
- if (!Number.isFinite(value)) return;
50
+ if (!Number.isFinite(value) || !Number.isFinite(nowMs)) return;
51
51
  const minute = Math.floor(nowMs / BUCKET_MS);
52
- let last = history[history.length - 1];
53
- if (!last || last.m !== minute) {
54
- last = { m: minute, v: {} };
55
- history.push(last);
56
- while (history.length > HISTORY_MINUTES) history.shift();
52
+ let bucket = history[history.length - 1];
53
+ if (!bucket || bucket.m < minute) {
54
+ bucket = { m: minute, v: {} };
55
+ history.push(bucket);
56
+ } else if (bucket.m > minute) {
57
+ // A clock correction can revisit an existing minute or a gap. Keep one
58
+ // maximum per minute, in time order, without evicting newer data for it.
59
+ const index = history.findIndex(b => b.m >= minute);
60
+ bucket = history[index];
61
+ if (bucket.m !== minute) {
62
+ bucket = { m: minute, v: {} };
63
+ history.splice(index, 0, bucket);
64
+ }
57
65
  }
58
- const prev = last.v[key];
59
- last.v[key] = prev == null ? value : Math.max(prev, value);
66
+ while (history.length > HISTORY_MINUTES) history.shift();
67
+ const prev = bucket.v[key];
68
+ bucket.v[key] = prev == null ? value : Math.max(prev, value);
60
69
  }
61
70
 
62
71
  /** Every reading recorded under `key`, oldest first, one point per minute that
@@ -79,8 +79,11 @@ export function createQuotaCloses({ load = async () => null, save = async () =>
79
79
  const flush = async () => {
80
80
  prune(state, now());
81
81
  if (!dirty) return;
82
- dirty = false;
83
- try { await save({ v: 1, open: state.open, closed: state.closed }); storageOk = true; }
82
+ try {
83
+ await save({ v: 1, open: state.open, closed: state.closed });
84
+ dirty = false;
85
+ storageOk = true;
86
+ }
84
87
  catch { storageOk = false; } // the record cannot fail a quota read
85
88
  };
86
89
  const run = fn => (queue = queue.then(async () => { await ready(); await fn(); await flush(); }).catch(() => { storageOk = false; }));
@@ -64,14 +64,44 @@ export function normalizeHistory(raw, now) {
64
64
  return prune(out, now);
65
65
  }
66
66
 
67
+ /** Keep observations collected during a read failure when the file recovers.
68
+ * The same window match and reset tolerance as record(), without replacing
69
+ * points that were already persisted at the same timestamp. */
70
+ function mergeBufferedHistory(stored, buffered, now) {
71
+ for (const pending of buffered) {
72
+ const row = stored.find(s => s.provider === pending.provider && s.account === pending.account
73
+ && s.id === pending.id && s.windowSec === pending.windowSec && Math.abs(s.resetAt - pending.resetAt) <= 120);
74
+ if (!row) { stored.push(pending); continue; }
75
+ row.resetAt = Math.max(row.resetAt, pending.resetAt);
76
+ const points = new Map([...pending.points, ...row.points].map(p => [p.t, p]));
77
+ row.points = [...points.values()].sort((a, b) => a.t - b.t);
78
+ }
79
+ return prune(stored, now);
80
+ }
81
+
67
82
  export function createQuotaHistory({ load = async () => null, save = async () => {}, now = Date.now } = {}) {
68
- let series = [], loading = null, storageOk = true;
83
+ let series = [], loaded = false, storageOk = true, dirty = false;
69
84
  const active = new Map();
70
85
  let queue = Promise.resolve();
71
- const ready = () => loading ??= (async () => {
72
- try { series = normalizeHistory(await load(), now()); }
86
+ // Every read and write runs in the queue. A failed load is retried by the
87
+ // next operation; buffered readings never authorize replacing unread data.
88
+ const ready = async () => {
89
+ if (loaded) return;
90
+ try {
91
+ const stored = normalizeHistory(await load(), now());
92
+ series = mergeBufferedHistory(stored, series, now());
93
+ loaded = true;
94
+ storageOk = true;
95
+ }
73
96
  catch { storageOk = false; }
74
- })();
97
+ };
98
+ const flush = async () => {
99
+ if (!loaded || !dirty) return;
100
+ try { await save({ v: 1, series }); dirty = false; storageOk = true; }
101
+ catch { storageOk = false; } // history cannot fail a quota request
102
+ };
103
+ const run = fn => (queue = queue.then(async () => { await ready(); await fn(); await flush(); })
104
+ .catch(() => { storageOk = false; }));
75
105
  return {
76
106
  activate(provider, account) {
77
107
  if (!providers.has(provider)) return null;
@@ -80,8 +110,7 @@ export function createQuotaHistory({ load = async () => null, save = async () =>
80
110
  return key;
81
111
  },
82
112
  record(provider, account, reading) {
83
- queue = queue.then(async () => {
84
- await ready();
113
+ return run(() => {
85
114
  if (!providers.has(provider) || !/^[a-f0-9]{64}$/.test(account ?? "") || !reading?.ok || reading.stale
86
115
  || !finite(reading.fetchedAt) || reading.fetchedAt > now() + 60_000) return;
87
116
  let changed = false;
@@ -105,20 +134,14 @@ export function createQuotaHistory({ load = async () => null, save = async () =>
105
134
  changed = true;
106
135
  }
107
136
  series = prune(series, now());
108
- if (changed) {
109
- try { await save({ v: 1, series }); storageOk = true; }
110
- catch { storageOk = false; } // history cannot fail a quota request
111
- }
112
- }).catch(() => { storageOk = false; });
113
- return queue;
137
+ if (changed) dirty = true;
138
+ });
114
139
  },
115
140
  async report(provider, account) {
116
- await queue;
117
- await ready();
141
+ await run(() => { series = prune(series, now()); });
118
142
  // A delayed request for an account that was switched away from cannot
119
143
  // display its history beside the new account's current quota.
120
144
  if (!account || active.get(provider) !== account) return { ok: true, account: null, series: [], storageOk };
121
- series = prune(series, now());
122
145
  return { ok: true, account, storageOk, series: series.filter(s => s.provider === provider && s.account === account)
123
146
  .map(({ account: _account, provider: _provider, ...s }) => ({ ...s, points: s.points.map(p => ({ ...p })) })) };
124
147
  },
@@ -41,6 +41,8 @@ export const WAITING_KEEPERS = new Set([
41
41
  * never the session's own traffic — the reducer's early returns, which stamp
42
42
  * no provider and prove nothing about whether the session is alive. */
43
43
  const SCANS = new Set([...WAITING_KEEPERS].filter(n => n !== "Notification"));
44
+ // Same session budget as parked-enrichment.ts; scans never grow a second ring.
45
+ const PENDING_ENRICHMENT_MAX = 256;
44
46
 
45
47
  /** Two copies of one event inside this are the wire talking twice —
46
48
  * HOOK_REDELIVERY_WINDOW_MS and PROMPT_REDELIVERY_WINDOW_MS in
@@ -85,6 +87,21 @@ function blankSession(id, at) {
85
87
  };
86
88
  }
87
89
 
90
+ function enrichSummary(s, p, name) {
91
+ if (!s.cwd && typeof p.cwd === "string" && p.cwd) s.cwd = p.cwd;
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;
94
+ }
95
+
96
+ /** Scanned facts can wait for a session, but cannot give it a provider, a
97
+ * lifecycle or a start time. Only traffic or active recovery establishes it. */
98
+ function establishSession(sessions, pending, id, at) {
99
+ const s = Object.assign(blankSession(id, at), pending.get(id));
100
+ pending.delete(id);
101
+ sessions.set(id, s);
102
+ return s;
103
+ }
104
+
88
105
  /** A prompt, filed in time order unless it is a copy of one already filed —
89
106
  * recordPrompt in redelivery.ts. Only the newest is ever read, as evidence. */
90
107
  function recordPrompt(s, at, text) {
@@ -99,7 +116,7 @@ function recordPrompt(s, at, text) {
99
116
  }
100
117
 
101
118
  /**
102
- * `Stop` or `SessionEnd`: the root's turn is over — applyTurnEnd in
119
+ * `Stop`, `StopFailure` or `SessionEnd`: the root's turn is over — applyTurnEnd in
103
120
  * session-lifecycle.ts, the parts of it a row can show.
104
121
  *
105
122
  * Refused whole when it is out of order (a boundary older than the prompt that
@@ -130,7 +147,7 @@ function endTurn(s, name, at) {
130
147
  * session's prompt back up, and the scan arrives every second and a half),
131
148
  * and a snapshot older than the session's own newest event says nothing.
132
149
  */
133
- function recover(sessions, p, at) {
150
+ function recover(sessions, pending, p, at) {
134
151
  const id = p.session_id;
135
152
  if ((p.provider !== "codex" && p.provider !== "claude") || typeof id !== "string" || !id) return;
136
153
  const s = sessions.get(id);
@@ -140,8 +157,7 @@ function recover(sessions, p, at) {
140
157
  if (s) endTurn(s, p.recovery_session_closed === true ? "SessionEnd" : "Stop", at);
141
158
  return;
142
159
  }
143
- const r = s ?? blankSession(id, at);
144
- sessions.set(id, r);
160
+ const r = s ?? establishSession(sessions, pending, id, at);
145
161
  r.recoveryLiveAt ??= s?.lastEventAt ?? 0;
146
162
  r.provider = p.provider;
147
163
  r.closed = false;
@@ -168,18 +184,27 @@ function recover(sessions, p, at) {
168
184
  */
169
185
  export function summarizeSessions(envelopes, { now = Date.now(), staleMs = STALE_SESSION_MS } = {}) {
170
186
  let sessions = new Map();
187
+ const pending = new Map();
171
188
  for (const env of Array.isArray(envelopes) ? envelopes : []) {
172
189
  const p = env?.payload;
173
190
  if (!p || typeof p !== "object") continue;
174
191
  const name = p.hook_event_name ?? "Unknown";
175
192
  // POST /api/clear wipes the canvas with this; it wipes the list too.
176
- if (name === "__clear") { sessions = new Map(); continue; }
193
+ if (name === "__clear") { sessions = new Map(); pending.clear(); continue; }
177
194
  const at = Number(env.receivedAt) || now;
178
- if (name === "ClaudeSessionRecovered" || name === "CodexSessionRecovered") { recover(sessions, p, at); continue; }
195
+ if (name === "ClaudeSessionRecovered" || name === "CodexSessionRecovered") { recover(sessions, pending, p, at); continue; }
179
196
  const id = typeof p.session_id === "string" && p.session_id ? p.session_id : null;
180
197
  if (!id) continue;
181
198
  let s = sessions.get(id);
182
- if (!s) { s = blankSession(id, at); sessions.set(id, s); }
199
+ if (!s && SCANS.has(name)) {
200
+ const facts = pending.get(id) ?? { cwd: null, model: null, name: null };
201
+ enrichSummary(facts, p, name);
202
+ pending.delete(id);
203
+ pending.set(id, facts);
204
+ if (pending.size > PENDING_ENRICHMENT_MAX) pending.delete(pending.keys().next().value);
205
+ continue;
206
+ }
207
+ if (!s) s = establishSession(sessions, pending, id, at);
183
208
  // A Codex child thread named by its parent: a session of its own, and
184
209
  // nothing the human did — linkCodexThread, which returns before any block
185
210
  // is read.
@@ -194,9 +219,7 @@ export function summarizeSessions(envelopes, { now = Date.now(), staleMs = STALE
194
219
  s.provider ??= p.provider === "codex" ? "codex" : "claude";
195
220
  if (at >= (s.recoveryLiveAt ?? 0)) s.recoveryLiveAt = at;
196
221
  }
197
- if (!s.cwd && typeof p.cwd === "string" && p.cwd) s.cwd = p.cwd;
198
- if (typeof p.model === "string" && p.model && !subagentKeyOf(p)) s.model = p.model;
199
- if (name === "SessionNamed") s.name = p.sessionTitle ?? p.sessionName ?? s.name;
222
+ enrichSummary(s, p, name);
200
223
 
201
224
  switch (name) {
202
225
  case "SessionStart":
@@ -213,6 +236,7 @@ export function summarizeSessions(envelopes, { now = Date.now(), staleMs = STALE
213
236
  break;
214
237
  }
215
238
  case "Stop":
239
+ case "StopFailure":
216
240
  case "SessionEnd":
217
241
  endTurn(s, name, at);
218
242
  break;
@@ -65,9 +65,14 @@ export async function currentActiveSlot(root = backupRoot()) {
65
65
  }
66
66
 
67
67
  /** Parse the log into swap entries sorted oldest-first. A truncated or garbage
68
- * last line (a crash mid-append) is skipped, never fatal. */
69
- export async function readSwapLog(path = swapLogPath()) {
70
- const text = await readFile(path, "utf8").catch(() => "");
68
+ * last line (a crash mid-append) is skipped, never fatal. Strict readers make
69
+ * irreversible attribution decisions: only ENOENT means an empty timeline;
70
+ * other read failures must defer their work. Display callers stay best-effort. */
71
+ export async function readSwapLog(path = swapLogPath(), { strict = false } = {}) {
72
+ const text = await readFile(path, "utf8").catch(error => {
73
+ if (strict && error?.code !== "ENOENT") throw error;
74
+ return "";
75
+ });
71
76
  const out = [];
72
77
  for (const line of text.split("\n")) {
73
78
  if (!line) continue;
@@ -142,7 +147,7 @@ export async function seedActive({ now = Date.now, root, path, projectsRoot } =
142
147
  if (!slot) return null;
143
148
  const id = await identityForSlot(slot, root ?? backupRoot());
144
149
  if (!id) return null;
145
- const entries = await readSwapLog(logPath);
150
+ const entries = await readSwapLog(logPath, { strict: true });
146
151
  const scope = await swapProjectsRoot(projectsRoot);
147
152
  const scoped = entries.filter(e => e.projectsRoot === scope);
148
153
  const last = scoped[scoped.length - 1];
@@ -79,7 +79,14 @@ import { run } from "./metrics-run.mjs";
79
79
  // for it, and the deck fetches its release binary itself — see
80
80
  // macmon.mjs.
81
81
  //
82
- // Windows The performance counter `\Thermal Zone Information(*)\High
82
+ // Windows CPU performance caps come from the invariant CIM class
83
+ // Win32_PerfFormattedData_Counters_ProcessorInformation. Its
84
+ // PercentPerformanceLimit reports guaranteed performance relative
85
+ // to nominal, including power-policy and firmware constraints.
86
+ // It is not a temperature or a complete hardware thermal detector.
87
+ // The source tag keeps the UI from claiming that every cap is heat.
88
+ //
89
+ // Temperatures use `\Thermal Zone Information(*)\High
83
90
  // Precision Temperature`, in TENTHS OF A KELVIN, read through
84
91
  // Get-Counter.
85
92
  //
@@ -472,6 +479,9 @@ export const WIN_THERMAL_PS = [
472
479
  + "| ForEach-Object { @{ i = $_.InstanceName; v = $_.CookedValue } }) } "
473
480
  + "} catch {} }",
474
481
  "if (-not $r.perf) { try { $r.acpi = @(Get-CimInstance -Namespace root/wmi -ClassName MSAcpi_ThermalZoneTemperature -EA Stop | ForEach-Object { @{ i = $_.InstanceName; v = $_.CurrentTemperature } }) } catch {} }",
482
+ // CIM names are invariant across display languages. This is a performance
483
+ // ceiling, not proof of heat: Windows also applies policy/firmware limits.
484
+ "try { $r.cpuLimit = @(Get-CimInstance -ClassName Win32_PerfFormattedData_Counters_ProcessorInformation -EA Stop | ForEach-Object { @{ v = $_.PercentPerformanceLimit } }) } catch {}",
475
485
  // Depth matters: the default of 2 turns the inner hashtables into the string
476
486
  // "System.Collections.Hashtable" and this parser would see nothing at all.
477
487
  "$r | ConvertTo-Json -Compress -Depth 4",
@@ -634,11 +644,12 @@ export async function readWindowsThermal(since = null, deps = {}) {
634
644
  ?? (async () => (await import("./hwmonitor.mjs")).readHwMonitorTemps());
635
645
 
636
646
  const out = await powershell();
647
+ const throttle = throttleFromWindows(out);
637
648
  const zones = out ? parseWinThermal(out.trim()) : [];
638
649
  const zonesSeen = zonesSeenAfter(zones, since?.zonesSeen);
639
650
  const memory = Object.keys(zonesSeen).length ? { zonesSeen } : {};
640
651
  const moved = zones.filter(z => zonesSeen[z.label].moved);
641
- if (moved.length) return { celsius: moved, throttle: null, ...memory };
652
+ if (moved.length) return { celsius: moved, throttle, ...memory };
642
653
 
643
654
  // Windows had no zone that has moved, which on a modern Intel laptop is
644
655
  // every time: the firmware declares no ACPI thermal zone, or declares one
@@ -651,7 +662,8 @@ export async function readWindowsThermal(since = null, deps = {}) {
651
662
  const rows = [];
652
663
  if (t.cpu != null) rows.push({ label: "CPU", celsius: t.cpu, warnAt: WARN_C, critAt: CRIT_C });
653
664
  if (t.gpu != null) rows.push({ label: "GPU", celsius: t.gpu, warnAt: WARN_C, critAt: CRIT_C });
654
- if (rows.length) return { celsius: rows, throttle: null, ...memory };
665
+ if (rows.length) return { celsius: rows, throttle, ...memory };
666
+ if (throttle) return { celsius: [], throttle, ...memory };
655
667
 
656
668
  // A zone that has not moved yet is still a zone, so this is an answer with
657
669
  // nothing to draw rather than null. Null would let the sampler give up after
@@ -660,6 +672,22 @@ export async function readWindowsThermal(since = null, deps = {}) {
660
672
  return zones.length ? { celsius: [], throttle: null, zonesSeen } : null;
661
673
  }
662
674
 
675
+ /** Windows' guaranteed performance relative to nominal performance. Taking
676
+ * the lowest published processor limit keeps a limited core visible instead
677
+ * of averaging it away. Boost/clock frequency is deliberately not consulted.
678
+ * Values above 100 mean no cap below nominal, not negative throttling.
679
+ * Source: Windows Processor Information / % Performance Limit counter help. */
680
+ export function throttleFromWindows(json) {
681
+ let r;
682
+ try { r = typeof json === "string" ? JSON.parse(json) : json; }
683
+ catch { return null; }
684
+ if (!Array.isArray(r?.cpuLimit)) return null;
685
+ const limits = r.cpuLimit.map(x => x?.v)
686
+ .filter(v => typeof v === "number" && Number.isFinite(v) && v >= 0);
687
+ if (!limits.length) return null;
688
+ return { speedLimit: Math.min(100, ...limits), source: "windows-performance" };
689
+ }
690
+
663
691
  /**
664
692
  * Which Windows zones have been seen to change since the deck started, keyed by
665
693
  * the zone's row label: the first value each one read, and whether it has
@@ -36,18 +36,30 @@ export function createToolAudit({ dir, now = Date.now, runReport = workerReport
36
36
  // they did: that is what tells a wait for approval from hooks starting the tool.
37
37
  const running = new Map();
38
38
  const enqueue = fn => { const task = serial.then(fn); serial = task.catch(() => {}); return task; };
39
- const ready = () => readyPromise ??= (async () => {
40
- await mkdir(dir, { recursive: true });
41
- try { meta = JSON.parse(await readFile(join(dir, 'settings.json'), 'utf8')); }
42
- catch (e) { if (e.code !== 'ENOENT') throw e; }
43
- if (meta && !validMeta(meta)) throw new Error('Unreadable tool history settings');
44
- if (!meta) { meta = { v: 1, deviceId: randomUUID(), epoch: randomUUID(), retentionDays: 90, startedAt: now(), skillsSince: now(), turnsSince: now() }; await saveMeta(); }
45
- // A journal from before skills were counted: its Skill calls never named the skill.
46
- if (!Number.isFinite(meta.skillsSince)) { meta.skillsSince = now(); await saveMeta(); }
47
- // Nor did it hold turns, so the split of the time starts here.
48
- if (!Number.isFinite(meta.turnsSince)) { meta.turnsSince = now(); await saveMeta(); }
49
- await prune();
50
- })();
39
+ const ready = () => {
40
+ if (readyPromise) return readyPromise;
41
+ const attempt = (async () => {
42
+ await mkdir(dir, { recursive: true });
43
+ try { meta = JSON.parse(await readFile(join(dir, 'settings.json'), 'utf8')); }
44
+ catch (e) { if (e.code !== 'ENOENT') throw e; }
45
+ if (meta && !validMeta(meta)) throw new Error('Unreadable tool history settings');
46
+ if (!meta) { meta = { v: 1, deviceId: randomUUID(), epoch: randomUUID(), retentionDays: 90, startedAt: now(), skillsSince: now(), turnsSince: now() }; await saveMeta(); }
47
+ // A journal from before skills were counted: its Skill calls never named the skill.
48
+ if (!Number.isFinite(meta.skillsSince)) { meta.skillsSince = now(); await saveMeta(); }
49
+ // Nor did it hold turns, so the split of the time starts here.
50
+ if (!Number.isFinite(meta.turnsSince)) { meta.turnsSince = now(); await saveMeta(); }
51
+ await prune();
52
+ })();
53
+ readyPromise = attempt;
54
+ void attempt.catch(() => {
55
+ if (readyPromise !== attempt) return;
56
+ readyPromise = null;
57
+ // A failed migration or prune may have populated meta already. The
58
+ // retry must read disk again, never reuse that partial initialization.
59
+ meta = undefined;
60
+ });
61
+ return attempt;
62
+ };
51
63
  const saveMeta = () => writeFileAtomic(join(dir, 'settings.json'), JSON.stringify(meta));
52
64
  const files = async () => (await readdir(dir)).filter(n => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(n)).sort();
53
65
  const prune = async () => {
@@ -66,8 +66,8 @@ export function readingsOf(snap) {
66
66
  warnAt: num(r.warnAt), critAt: num(r.critAt),
67
67
  });
68
68
  }
69
- // Linux and Windows say how long the CPU was held back; a Mac says how much
70
- // speed it still allows. One number either way, the deck's own (heldShare in
69
+ // Linux says how long the CPU was held back; macOS and Windows report a
70
+ // performance ceiling. One number either way, the deck's own (heldShare in
71
71
  // machine-live.ts): the share held back.
72
72
  const throttle = snap.thermal?.throttle;
73
73
  const speed = num(throttle?.speedLimit);