From e97be1cb165953864549af72c3a0047ff90fdf51 Mon Sep 17 00:00:00 2001 From: Grimmer Kang Date: Fri, 20 Nov 2026 21:50:28 +0900 Subject: [PATCH 1/7] feat(sessions): a timing log for session switches Record where a switch spends its time, before rewriting any of it for speed: one JSON line per switch in ~/.config/codev/switch-timing.jsonl, from the click in the renderer to the terminal's command exiting. - Steps: click to IPC, settings read, terminal detection, script build, command start, command exit; plus the branch that found the tab, read from what the switch scripts already return on stdout (cmux matches in JS, so each layer names itself). No script and no matching order changed. - Machine state around it: load average, CPU % from two os.cpus() samples, the main process's own CPU time, memory pressure and swap, the claude process count from the last live-sessions report; the three busiest processes only for a switch over 1 s. - Timings and counts only: no title, prompt or path, just the first 8 characters of the session id. Capped at ~1 MB, one rotated file. - The collector is an optional last argument down the switch path and every use is `timing?.`; sysctl, ps and the append run after the switch, and a failure in any of it is swallowed. - scripts/switch-timing-summary.js (yarn switch-timing): p50/p90 per step by kind, terminal and branch, and the total against load. Version 1.0.97. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 + docs/claude-session-integration-design.md | 59 +++ package.json | 3 +- scripts/switch-timing-summary.js | 220 +++++++++ src/claude-session-utility.ts | 66 ++- src/electron-api.d.ts | 2 + src/main.ts | 21 +- src/preload.ts | 2 + src/switch-timing-log.ts | 194 ++++++++ src/switch-timing.test.ts | 523 ++++++++++++++++++++++ src/switch-timing.ts | 439 ++++++++++++++++++ src/switcher-ui.tsx | 12 + 12 files changed, 1535 insertions(+), 10 deletions(-) create mode 100644 scripts/switch-timing-summary.js create mode 100644 src/switch-timing-log.ts create mode 100644 src/switch-timing.test.ts create mode 100644 src/switch-timing.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dc1cfb..b1c91e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 1.0.97 + +- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s, the three busiest processes). **It holds timings and counts, no session content** — no title, prompt or path, only the first 8 characters of the session id. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch, and a failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal and by branch, and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" + ## 1.0.94 - Feat: **Ghostty switches to the right tab when several sessions share a directory** ([#63](https://github.com/grimmerk/codev/issues/63)). Ghostty's tip builds expose each terminal's `tty` (ghostty-org/ghostty#11922), so switching now works the way it does in iTerm2 and Terminal.app: by tty and by `/rename` title, in the order the session's process provenance calls for, and only then by working directory. Before, a session without a custom title went to the first tab in its directory — measured on one machine with 16 sessions sharing `~/git`, every one of them landed on the same tab. Detection's fallback cross-reference uses the tty the same way. **Stable Ghostty (1.3.1 and earlier) has no `tty`**, so there CodeV behaves exactly as before — title, then directory — until a release ships it diff --git a/docs/claude-session-integration-design.md b/docs/claude-session-integration-design.md index 345c960..4c7854d 100644 --- a/docs/claude-session-integration-design.md +++ b/docs/claude-session-integration-design.md @@ -665,6 +665,65 @@ TypeScript is sufficient for MVP. `history.jsonl` reading (~40ms) and session li **Rust native module justified for:** full JSONL parsing (last assistant response, full-text search across 771MB), where the 5-10x speedup matters. claude-history achieves <1s for 170 files using Rust + rayon parallel. +### Measuring a switch: the timing log + +Before rewriting any part of the switch path for speed, measure where a switch spends its time. Since 1.0.97 every switch started from the Sessions tab (Enter or a click) appends one JSON line to `~/.config/codev/switch-timing.jsonl`. The question it is meant to answer: is the time in CodeV's own JavaScript, which a rewrite could shorten, or in the external command (`osascript`, or the cmux CLI) and a loaded machine, which it could not? + +**What a line holds: timings and counts only.** No title, prompt or path; the only trace of the session is the first 8 characters of its id. The file is capped at about 1 MB: at the cap it is renamed to `switch-timing.jsonl.1` (one old file is kept) and a new one starts. Logging is always on; there is no setting. + +``` + renderer main process terminal + ──────── ──────────── ──────── + ① click / Enter + │ IPC + └──────────► ② IPC arrives + ③ settings read (ms.settings) + ④ detectTerminalApp (ms.detect; running sessions only) + ⑤ script text built (ms.build) + ⑥ file written, command started (ms.spawn) + └──────────────────────────────────► osascript runs + ⑦ command exits (ms.run) ◄────────── prints the branch + ⑧ afterwards: sysctl, ps (slow switches only), append the line +``` + +Steps ① to ⑦ are the switch. Step ⑧ runs only after it, so nothing that spawns a process or touches the disk for the log sits on the switch's path; what the log adds to the path itself is one `os.cpus()` read, one `process.cpuUsage()` and a few clock reads. Any failure in the timing code is swallowed and the switch runs as before. + +| Field | Meaning | +|---|---| +| `v` | Record version (1). | +| `ts` | ISO time the IPC arrived in the main process. | +| `sid` | First 8 characters of the session id. | +| `via` | `enter` or `click`. | +| `kind` | `switch` (the session was running) or `resume` (it was not; a new tab runs `claude --resume`). | +| `terminal`, `configured` | Where the switch went after auto-detection, and the terminal named in Settings. | +| `tool` | What ran the switch: `osascript`, `cmux-cli`, `open` (VS Code, Claude Desktop) or `pty` (the embedded terminal). | +| `branch` | Which key found the tab: `tty`, `title`, `cwd`, `project-name` (cmux), `none` (the script ran and matched nothing); for a resume `new-tab`, `new-window` or `new-workspace`; `deep-link`, `embedded`. `null` means unknown, for example a script that failed. | +| `order`, `hasTitle` | Which key the script tried first (`tty-first` or `title-first`), and whether it had a title block at all. | +| `ok`, `timedOut` | `ok` is false when the launch was rejected; `timedOut` is true when the command had not reported an exit after 15 s (then `ms.run` and `ms.total` are `null`). | +| `ms.clickToIpc`, `ms.clickToIpcHr` | ① to ②, on the wall clock (whole ms) and on the two processes' high-resolution clocks. | +| `ms.settings`, `ms.detect`, `ms.build`, `ms.spawn`, `ms.run` | The steps in the diagram. A step a path skips is `null`, and its time counts in the next one. | +| `ms.returned` | ② to `openSession` returning. For a running session this is before the script exits. | +| `ms.main`, `ms.total` | ② to ⑦, and ① to ⑦ (what the user waited). | +| `load`, `ncpu` | `os.loadavg()` at the end of the switch, and the core count. | +| `cpuPct` | Whole-machine CPU busy % over the span, from two `os.cpus()` samples. `null` for a span too short to measure (the counters tick every 10 ms). | +| `mainCpuMs` | CPU time CodeV's main process itself used over the span (`process.cpuUsage()` delta). | +| `mem` | macOS memory-pressure level (1 normal, 2 warn, 4 critical) and swap in MB — the same `sysctl` reading as the memory chip, taken after the switch. | +| `claudeProcs`, `liveAgeMs` | Running `claude` processes in the last live-sessions report the window asked for, and how old that report was. No extra `ps` is run for it. | +| `rows` | Rows in the session list when the switch was started. | +| `top` | Only when `ms.total` is over 1 s: the three busiest processes (`%CPU`, executable name) right after the switch. | + +The branch costs nothing to record: the switch scripts already end in `return "found-by-tty"` and the like, and `osascript` prints that value. cmux matches in JavaScript, so each layer names itself. No script and no matching order changed. + +Not recorded: the number of terminal tabs (only the terminal knows, and asking would cost a second script), and opening a whole saved list (several staggered launches, not one switch). + +To summarize the log: + +```bash +yarn switch-timing # or: node scripts/switch-timing-summary.js [file ...] +``` + +It prints p50/p90 (50th and 90th percentile) per step and for the total — for all switches, and grouped by kind, terminal and branch — then the share of the total spent inside the external command, and the total against load: buckets of 1-minute load per core, and Pearson correlations of the total with load and with CPU %. Malformed lines are counted and skipped; a missing or empty log prints "No switch records." + ### `history.jsonl` vs `session-metadata.db` `session-metadata.db` has richer data but is a stale cache. `history.jsonl` is always up to date. Same approach used by c9watch's history page. diff --git a/package.json b/package.json index 575c096..a8906d8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "CodeV", "productName": "CodeV", - "version": "1.0.94", + "version": "1.0.97", "description": "Quick switcher for VS Code, Cursor, and Claude Code sessions", "repository": { "type": "git", @@ -15,6 +15,7 @@ "account": "ts-node src/cli/codev-account.ts", "test": "vitest run", "test:watch": "vitest", + "switch-timing": "node scripts/switch-timing-summary.js", "package": "electron-forge package", "package_mas": "npm run prebuild && cross-env BUILD_TYPE=prod electron-forge package --platform=mas && npm run postbuild", "prebuild": "sh prebuild.sh", diff --git a/scripts/switch-timing-summary.js b/scripts/switch-timing-summary.js new file mode 100644 index 0000000..6382276 --- /dev/null +++ b/scripts/switch-timing-summary.js @@ -0,0 +1,220 @@ +#!/usr/bin/env node +/** + * Summarize CodeV's switch timing log (src/switch-timing.ts writes it). + * + * node scripts/switch-timing-summary.js [file ...] + * + * With no argument it reads ~/.config/codev/switch-timing.jsonl.1 (the + * rotated file, if any) and then ~/.config/codev/switch-timing.jsonl. + * + * Prints p50 / p90 per step and for the total, for all switches and grouped + * by kind, terminal and branch; then the total against machine load. Plain + * Node, no dependencies. A line that is not a record is counted and skipped; + * a missing or empty file is reported, not an error. + */ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +/** Steps in path order; `total` is what the user waited. */ +const STEPS = ['clickToIpc', 'settings', 'detect', 'build', 'spawn', 'run', 'main', 'total']; + +/** + * The p-th percentile (0–100) by linear interpolation between the two + * nearest ranks — the same definition as numpy's default. Null for no data. + */ +const percentile = (values, p) => { + const xs = values.filter((v) => typeof v === 'number' && Number.isFinite(v)).sort((a, b) => a - b); + if (xs.length === 0) return null; + const rank = (Math.min(100, Math.max(0, p)) / 100) * (xs.length - 1); + const lo = Math.floor(rank); + const hi = Math.ceil(rank); + return xs[lo] + (xs[hi] - xs[lo]) * (rank - lo); +}; + +/** Pearson's r over the pairs where both values are numbers; null under 3 pairs or no variance. */ +const pearson = (pairs) => { + const ps = pairs.filter( + ([x, y]) => typeof x === 'number' && Number.isFinite(x) && typeof y === 'number' && Number.isFinite(y), + ); + const n = ps.length; + if (n < 3) return null; + const mx = ps.reduce((s, [x]) => s + x, 0) / n; + const my = ps.reduce((s, [, y]) => s + y, 0) / n; + let sxy = 0; + let sxx = 0; + let syy = 0; + for (const [x, y] of ps) { + sxy += (x - mx) * (y - my); + sxx += (x - mx) ** 2; + syy += (y - my) ** 2; + } + if (sxx === 0 || syy === 0) return null; + return sxy / Math.sqrt(sxx * syy); +}; + +/** Records from JSONL text. Anything that is not an object with an `ms` object is skipped and counted. */ +const parseLines = (text) => { + const records = []; + let malformed = 0; + for (const line of String(text || '').split('\n')) { + if (!line.trim()) continue; + try { + const r = JSON.parse(line); + if (r && typeof r === 'object' && r.ms && typeof r.ms === 'object') records.push(r); + else malformed++; + } catch { + malformed++; + } + } + return { records, malformed }; +}; + +const stepStats = (records) => { + const out = {}; + for (const step of STEPS) { + const xs = records.map((r) => r.ms[step]).filter((v) => typeof v === 'number' && Number.isFinite(v)); + out[step] = { n: xs.length, p50: percentile(xs, 50), p90: percentile(xs, 90) }; + } + return out; +}; + +const groupBy = (records, keyOf) => { + const groups = new Map(); + for (const r of records) { + const k = keyOf(r); + if (!groups.has(k)) groups.set(k, []); + groups.get(k).push(r); + } + return [...groups.entries()] + .sort((a, b) => b[1].length - a[1].length) + .map(([key, rs]) => ({ key, n: rs.length, steps: stepStats(rs) })); +}; + +/** 1-minute load per core: comparable across machines. */ +const loadPerCore = (r) => + Array.isArray(r.load) && typeof r.load[0] === 'number' && typeof r.ncpu === 'number' && r.ncpu > 0 + ? r.load[0] / r.ncpu + : null; + +const LOAD_BUCKETS = [ + { label: 'load/core < 0.5', lo: 0, hi: 0.5 }, + { label: 'load/core 0.5–1', lo: 0.5, hi: 1 }, + { label: 'load/core 1–2', lo: 1, hi: 2 }, + { label: 'load/core ≥ 2', lo: 2, hi: Infinity }, +]; + +const summarize = (records) => { + const total = (r) => r.ms.total; + // Of each switch's total, the part spent inside the external command. + const runShare = records + .filter((r) => typeof r.ms.run === 'number' && typeof r.ms.total === 'number' && r.ms.total > 0) + .map((r) => r.ms.run / r.ms.total); + return { + count: records.length, + timedOut: records.filter((r) => r.timedOut === true).length, + failed: records.filter((r) => r.ok === false).length, + slow: records.filter((r) => typeof r.ms.total === 'number' && r.ms.total > 1000).length, + all: stepStats(records), + byKind: groupBy(records, (r) => String(r.kind ?? 'unknown')), + byTerminal: groupBy(records, (r) => String(r.terminal ?? 'unknown')), + byBranch: groupBy(records, (r) => String(r.branch ?? 'unknown')), + runShareP50: percentile(runShare, 50), + load: { + buckets: LOAD_BUCKETS.map((b) => { + const rs = records.filter((r) => { + const l = loadPerCore(r); + return l !== null && l >= b.lo && l < b.hi; + }); + const xs = rs.map(total); + return { label: b.label, n: rs.length, p50: percentile(xs, 50), p90: percentile(xs, 90) }; + }), + rTotalVsLoad1: pearson(records.map((r) => [Array.isArray(r.load) ? r.load[0] : null, total(r)])), + rTotalVsCpuPct: pearson(records.map((r) => [r.cpuPct, total(r)])), + rRunVsLoad1: pearson(records.map((r) => [Array.isArray(r.load) ? r.load[0] : null, r.ms.run])), + }, + }; +}; + +const fmt = (v) => (v === null || v === undefined ? '—' : v.toFixed(v < 10 ? 1 : 0)); +const pad = (s, w) => String(s).padEnd(w); +const padL = (s, w) => String(s).padStart(w); + +const stepTable = (title, groups) => { + const lines = [title]; + lines.push(` ${pad('', 16)}${padL('n', 5)} ${STEPS.map((s) => padL(s, 13)).join('')}`); + for (const g of groups) { + const cells = STEPS.map((s) => padL(`${fmt(g.steps[s].p50)}/${fmt(g.steps[s].p90)}`, 13)).join(''); + lines.push(` ${pad(g.key, 16)}${padL(g.n, 5)} ${cells}`); + } + return lines.join('\n'); +}; + +const formatReport = (summary, malformed = 0) => { + if (summary.count === 0) { + return `No switch records${malformed ? ` (${malformed} malformed line(s) skipped)` : ''}.`; + } + const s = summary; + const r = (v) => (v === null ? '— (too few records, or no variance)' : v.toFixed(2)); + return [ + `${s.count} switches · ${s.slow} over 1 s · ${s.timedOut} timed out · ${s.failed} failed` + + (malformed ? ` · ${malformed} malformed line(s) skipped` : ''), + 'Cells are p50/p90 in ms. Steps: clickToIpc (renderer → main), settings, detect', + '(which terminal), build (script text), spawn (write + start), run (the external', + 'command), main (IPC → done), total (click → done).', + '', + stepTable('All', [{ key: 'all', n: s.count, steps: s.all }]), + '', + stepTable('By kind', s.byKind), + '', + stepTable('By terminal', s.byTerminal), + '', + stepTable('By branch', s.byBranch), + '', + `Share of the total spent inside the external command (run / total), p50: ${ + s.runShareP50 === null ? '—' : `${(s.runShareP50 * 100).toFixed(0)}%` + }`, + '', + 'Total vs load (1-minute load average per core)', + ...s.load.buckets.map( + (b) => ` ${pad(b.label, 18)}${padL(b.n, 5)} p50 ${padL(fmt(b.p50), 6)} p90 ${padL(fmt(b.p90), 6)}`, + ), + ` Pearson r, total vs 1-min load: ${r(s.load.rTotalVsLoad1)}`, + ` Pearson r, run vs 1-min load: ${r(s.load.rRunVsLoad1)}`, + ` Pearson r, total vs CPU % : ${r(s.load.rTotalVsCpuPct)}`, + ].join('\n'); +}; + +const defaultFiles = () => { + const base = path.join(os.homedir(), '.config', 'codev', 'switch-timing.jsonl'); + return [`${base}.1`, base]; +}; + +const readFiles = (files) => { + let text = ''; + const missing = []; + for (const f of files) { + try { + text += `${fs.readFileSync(f, 'utf-8')}\n`; + } catch { + missing.push(f); + } + } + return { text, missing }; +}; + +const main = (argv) => { + const explicit = argv.length > 0; + const files = explicit ? argv : defaultFiles(); + const { text, missing } = readFiles(files); + // The rotated file is optional; only a file the user named is worth a note. + if (explicit) for (const f of missing) console.error(`cannot read ${f}`); + const { records, malformed } = parseLines(text); + console.log(formatReport(summarize(records), malformed)); +}; + +if (require.main === module) main(process.argv.slice(2)); + +module.exports = { percentile, pearson, parseLines, summarize, formatReport, stepStats, STEPS }; diff --git a/src/claude-session-utility.ts b/src/claude-session-utility.ts index e2b5166..fe14b29 100644 --- a/src/claude-session-utility.ts +++ b/src/claude-session-utility.ts @@ -48,6 +48,7 @@ import { switchOrderFor, } from './terminal-switch'; import { pickSessionByTabTitle } from './cross-ref-title'; +import type { SwitchTiming } from './switch-timing'; export interface ClaudeSession { sessionId: string; @@ -1522,23 +1523,29 @@ export const openSession = async ( terminalMode: string = 'tab', customTitle?: string, accountLabel?: string, + // Optional timing collector (switch-timing.ts). Absent for every caller + // but the click path; every use is `timing?.…`, which never throws. + timing?: SwitchTiming, ): Promise => { let effectiveTerminal = terminalApp; // For active sessions, auto-detect which terminal they're running in if (isActive && activePid) { const detected = await detectTerminalApp(activePid); + timing?.mark('detect'); if (detected !== 'unknown') { effectiveTerminal = detected; console.log(`[openSession] auto-detected terminal: ${detected} for pid ${activePid}`); } } + timing?.set({ terminal: effectiveTerminal }); // Check if this is an active VS Code session — switch via URI handler // Always pass projectPath so the correct VS Code window gets focused first const entrypoint = cachedEntrypoints?.get(sessionId) ?? knownTranscriptOnlyEntrypoints.get(sessionId); if (isActive && entrypoint === 'claude-vscode') { + timing?.set({ terminal: 'vscode', tool: 'open', branch: 'deep-link' }); openSessionInVSCode(sessionId, projectPath, true); return; } @@ -1548,6 +1555,7 @@ export const openSession = async ( // way its own sidebar does. Resuming it in a terminal instead moved the // conversation out of Desktop. if (entrypoint === 'claude-desktop') { + timing?.set({ terminal: 'claude-desktop', tool: 'open', branch: 'deep-link' }); openSessionInClaudeDesktop(sessionId); return; } @@ -1555,10 +1563,12 @@ export const openSession = async ( switch (effectiveTerminal) { case 'vscode': // User selected VS Code as launch terminal — open project first, then resume + timing?.set({ tool: 'open', branch: 'deep-link' }); openSessionInVSCode(sessionId, projectPath); return; case 'codev': // Session is in CodeV's embedded terminal — notify renderer to switch to Term tab + timing?.set({ tool: 'pty', branch: 'embedded' }); openSessionInCodeV(sessionId); break; case 'cmux': @@ -1569,6 +1579,7 @@ export const openSession = async ( activePid, customTitle, accountLabel, + timing, ); case 'ghostty': return openSessionInGhostty( @@ -1579,6 +1590,7 @@ export const openSession = async ( terminalMode, customTitle, accountLabel, + timing, ); case 'terminal': return openSessionInTerminalApp( @@ -1589,6 +1601,7 @@ export const openSession = async ( terminalMode, customTitle, accountLabel, + timing, ); case 'iterm2': default: @@ -1600,6 +1613,7 @@ export const openSession = async ( terminalMode, customTitle, accountLabel, + timing, ); } }; @@ -1691,6 +1705,7 @@ export const runCommandInTerminal = ( projectPath: string, terminalApp: string = 'iterm2', terminalMode: string = 'tab', + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); // One osascript launch as a promise: the script file is removed either @@ -1701,12 +1716,20 @@ export const runCommandInTerminal = ( script: string, label: string, ): Promise => { + // The launch scripts return nothing, so the branch is what was asked for. + timing?.mark('script'); + timing?.set({ + tool: 'osascript', + branch: terminalMode === 'window' ? 'new-window' : 'new-tab', + }); fs.writeFileSync(tmpScript, script); return new Promise((resolve, reject) => { + timing?.spawned(); exec( `osascript ${tmpScript}`, { encoding: 'utf-8', timeout: 5000 }, (error: any) => { + timing?.exited(); try { fs.unlinkSync(tmpScript); } catch {} @@ -2130,6 +2153,7 @@ export const openSessionInITerm2 = async ( terminalMode: string = 'tab', customTitle?: string, accountLabel?: string, + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); @@ -2140,17 +2164,21 @@ export const openSessionInITerm2 = async ( const order = switchOrderFor(!isGuessedPid(activePid)); const tmpScript = '/tmp/codev-iterm-switch.scpt'; const switchScript = buildITerm2SwitchScript(activePid, customTitle, order); + timing?.mark('script'); + timing?.set({ tool: 'osascript', order, hasTitle: !!customTitle }); console.log( `[iTerm2] switch: pid=${activePid}, order=${order}, customTitle=${customTitle || 'none'}`, ); fs.writeFileSync(tmpScript, switchScript); + timing?.spawned(); exec(`osascript ${tmpScript}`, { encoding: 'utf-8' }, (error: any, stdout: string) => { + timing?.exited(stdout); console.log(`[iTerm2] switch result: ${(stdout || '').trim()}`, error?.message || ''); try { fs.unlinkSync(tmpScript); } catch {} }); } else { const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); - return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'iterm2', terminalMode); + return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'iterm2', terminalMode, timing); } }; @@ -2777,6 +2805,7 @@ export const openSessionInGhostty = async ( terminalMode: string = 'tab', customTitle?: string, accountLabel?: string, + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); @@ -2787,11 +2816,15 @@ export const openSessionInGhostty = async ( const order = switchOrderFor(!!activePid && !isGuessedPid(activePid)); const tmpScript = '/tmp/codev-ghostty-switch.scpt'; const switchScript = buildGhosttySwitchScript(activePid, customTitle, order, projectPath); + timing?.mark('script'); + timing?.set({ tool: 'osascript', order, hasTitle: !!customTitle }); console.log( `[ghostty] switch: pid=${activePid ?? 'none'}, order=${order}, customTitle=${customTitle || 'none'}`, ); fs.writeFileSync(tmpScript, switchScript); + timing?.spawned(); exec(`osascript ${tmpScript}`, { encoding: 'utf-8', timeout: 5000 }, (error: any, stdout: string) => { + timing?.exited(stdout); const result = (stdout || '').trim(); console.log('[ghostty] switch result:', result, error?.message || ''); if (result === 'not found') { @@ -2801,7 +2834,7 @@ export const openSessionInGhostty = async ( }); } else { const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); - return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'ghostty', terminalMode); + return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'ghostty', terminalMode, timing); } }; @@ -2818,6 +2851,7 @@ export const openSessionInTerminalApp = async ( terminalMode: string = 'tab', customTitle?: string, accountLabel?: string, + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); @@ -2830,17 +2864,21 @@ export const openSessionInTerminalApp = async ( customTitle, order, ); + timing?.mark('script'); + timing?.set({ tool: 'osascript', order, hasTitle: !!customTitle }); console.log( `[Terminal.app] switch: pid=${activePid}, order=${order}, customTitle=${customTitle || 'none'}`, ); fs.writeFileSync(tmpScript, switchScript); + timing?.spawned(); exec(`osascript ${tmpScript}`, { encoding: 'utf-8', timeout: 5000 }, (error: any, stdout: string) => { + timing?.exited(stdout); console.log(`[Terminal.app] switch result: ${(stdout || '').trim()}`, error?.message || ''); try { fs.unlinkSync(tmpScript); } catch {} }); } else { const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); - return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'terminal', terminalMode); + return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'terminal', terminalMode, timing); } }; @@ -2858,6 +2896,7 @@ export const openSessionInCmux = async ( activePid?: number, customTitle?: string, accountLabel?: string, + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); const command = `cd "${projectPath}" && ${buildResumeCommand(sessionId, accountLabel, projectPath)}`; @@ -2886,6 +2925,12 @@ export const openSessionInCmux = async ( exec('osascript -e \'tell application "cmux" to activate\''); }; + // cmux is driven through its CLI, not a script: the matching below runs + // in JS, so each layer names itself, and "exited" is the last awaited + // CLI call (the closing `activate` is fired and not waited for). + timing?.mark('script'); + timing?.set({ tool: 'cmux-cli', hasTitle: !!customTitle }); + timing?.spawned(); (async () => { // Single tree --all call for title matching, project name fallback, and workspace ID extraction. const treeOutput = await execPromise(`${CMUX_CLI} tree --all 2>/dev/null`); @@ -2925,6 +2970,7 @@ export const openSessionInCmux = async ( for (const surface of ws.surfaces) { if (surface.title.toLowerCase().includes(titleLower)) { console.log('[cmux] matched surface by title:', surface.surfaceId, 'in', ws.wsId); + timing?.set({ branch: 'title' }); await selectAndActivate(ws.wsId, surface.surfaceId); return; } @@ -2940,6 +2986,7 @@ export const openSessionInCmux = async ( for (const surface of ws.surfaces) { if (surface.tty && surface.tty.endsWith(ttyOutput)) { console.log('[cmux] matched surface by TTY:', surface.surfaceId, 'in', ws.wsId, 'tty=', surface.tty); + timing?.set({ branch: 'tty' }); await selectAndActivate(ws.wsId, surface.surfaceId); return; } @@ -2961,6 +3008,7 @@ export const openSessionInCmux = async ( const cwdHit = cwdResults.find((r: any) => r.cwd === projectPath || r.focusedCwd === projectPath); if (cwdHit) { console.log('[cmux] matched workspace by cwd:', cwdHit.wsId); + timing?.set({ branch: 'cwd' }); await selectAndActivate(cwdHit.wsId); return; } @@ -2974,6 +3022,7 @@ export const openSessionInCmux = async ( for (const surface of ws.surfaces) { if (surface.title.toLowerCase().includes(projectNameLower)) { console.log('[cmux] matched by surface title (project name):', surface.surfaceId, 'in', ws.wsId); + timing?.set({ branch: 'project-name' }); await selectAndActivate(ws.wsId, surface.surfaceId); return; } @@ -2982,11 +3031,18 @@ export const openSessionInCmux = async ( } console.log('[cmux] no match found, activating cmux'); + timing?.set({ branch: 'none' }); exec('osascript -e \'tell application "cmux" to activate\''); - })(); + })().finally(() => timing?.exited()); } else { const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); - return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'cmux'); + // The cmux launch is several CLI calls behind one promise; time it whole. + timing?.mark('script'); + timing?.set({ tool: 'cmux-cli', branch: 'new-workspace' }); + timing?.spawned(); + return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'cmux').finally( + () => timing?.exited(), + ); } }; diff --git a/src/electron-api.d.ts b/src/electron-api.d.ts index aec6d95..38c1293 100644 --- a/src/electron-api.d.ts +++ b/src/electron-api.d.ts @@ -271,6 +271,8 @@ interface IElectronAPI { activePid?: number, customTitle?: string, accountLabel?: string, + /** When the switch was asked for; feeds the switch timing log only. */ + stamp?: { wallMs: number; perfEpochMs: number; via: 'enter' | 'click'; rows: number }, ) => void; /** Resume the given saved-list members that are not running; staggered, skips report why. */ openSessionListMembers: ( diff --git a/src/main.ts b/src/main.ts index 53f4eb9..35c287d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -57,6 +57,7 @@ import { withRenamedList, } from './session-lists'; import { collectLiveSessions } from './live-sessions'; +import { noteLiveReport, startSwitchTiming } from './switch-timing-log'; import { randomUUID } from 'crypto'; import { installHooks, @@ -2792,7 +2793,9 @@ ipcMain.handle('rename-session-list', (_event, id: string, name: string) => { ipcMain.handle('get-live-sessions', async () => { try { - return await collectLiveSessions(); + const report = await collectLiveSessions(); + noteLiveReport(report); // the process count the switch timing log reuses + return report; } catch (err) { // null, not an empty report: "we could not look" must never render as // "nothing is running" — the renderer keeps its last good report. @@ -2843,6 +2846,7 @@ ipcMain.on( activePid?: number, customTitle?: string, accountLabel?: string, + stamp?: unknown, ) => { // The path is embedded in shell and AppleScript strings by every // launcher; refuse one that could end either literal (see isSafeLaunchPath). @@ -2850,6 +2854,9 @@ ipcMain.on( console.warn('[open-claude-session] refusing unsafe project path:', projectPath); return; } + // Timing only (switch-timing.ts): undefined if it cannot start, and no + // call on it can throw, so the switch below runs the same either way. + const timing = startSwitchTiming(sessionId, !!isActive, stamp); // Switching to a running session never needs the path (iTerm2 matches by // tty); a resume does — `cd ""` would start the session in the wrong place. if (!isActive && !projectPath) { @@ -2858,6 +2865,8 @@ ipcMain.on( } const terminalApp = ((await settings.get('session-terminal-app')) || 'iterm2') as string; const terminalMode = ((await settings.get('session-terminal-mode')) || 'tab') as string; + timing?.mark('settings'); + timing?.set({ configured: terminalApp }); // A label no account carries is dropped, not trusted: history decides the // account for any session it knows, and the anchor is the documented // fallback for one it does not. @@ -2874,9 +2883,13 @@ ipcMain.on( terminalMode, customTitle, label, - ).catch((err) => { - console.error('[open-claude-session] launch failed:', err); - }); + timing, + ) + .then(() => timing?.settle(true)) + .catch((err) => { + timing?.settle(false); + console.error('[open-claude-session] launch failed:', err); + }); }, ); diff --git a/src/preload.ts b/src/preload.ts index f0a6605..9148008 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -120,6 +120,7 @@ contextBridge.exposeInMainWorld('electronAPI', { activePid?: number, customTitle?: string, accountLabel?: string, + stamp?: unknown, ) => ipcRenderer.send( 'open-claude-session', @@ -129,6 +130,7 @@ contextBridge.exposeInMainWorld('electronAPI', { activePid, customTitle, accountLabel, + stamp, ), openSessionListMembers: ( members: { diff --git a/src/switch-timing-log.ts b/src/switch-timing-log.ts new file mode 100644 index 0000000..11fbff6 --- /dev/null +++ b/src/switch-timing-log.ts @@ -0,0 +1,194 @@ +/** + * The impure half of the switch timing log (see switch-timing.ts for what + * is measured and why): start a collector when a switch's IPC arrives, and + * when the switch is over, sample the machine and append one JSON line to + * `~/.config/codev/switch-timing.jsonl`, beside the marks and lists stores. + * + * On the switch's path this costs one `os.cpus()` read, one + * `process.cpuUsage()` and a few clock reads. Everything that spawns or + * touches the disk — `sysctl` for memory pressure, `ps` for a slow switch, + * the append itself — runs after the switch has finished, and a failure in + * any of it is dropped: the switch has already happened. + * + * No Electron imports, so the whole path runs under vitest. + */ +import { execFile } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { parseMemoryPressure } from './live-sessions'; +import { + buildSwitchRecord, + cpuPercentBetween, + createSwitchTiming, + isSlowSwitch, + parseTopCpu, + sanitizeStamp, + shouldRotate, + stepDurations, + SWITCH_LOG_MAX_BYTES, + SwitchSnapshot, + SwitchSystemSample, + SwitchTiming, +} from './switch-timing'; + +export const SWITCH_LOG_FILENAME = 'switch-timing.jsonl'; + +export const defaultSwitchLogPath = (): string => + path.join(os.homedir(), '.config', 'codev', SWITCH_LOG_FILENAME); + +// --- the running-process count the app already has --- + +// The Sessions tab asks main for a live-sessions report (a `ps`) each time +// the window opens. Remembering that report's size gives every switch a +// process count without a `ps` of its own; the age says how stale it is. +let lastLive: { count: number; at: number } | null = null; + +export const noteLiveReport = ( + report: { live?: unknown[]; measuredAt?: number } | null | undefined, +): void => { + try { + if (report && Array.isArray(report.live)) { + lastLive = { count: report.live.length, at: Date.now() }; + } + } catch { + // Not worth a failed report. + } +}; + +/** For tests. */ +export const resetLiveReportNote = (): void => { + lastLive = null; +}; + +// --- append with rotation --- + +/** + * Append one line, moving the file to `.1` first when the line would + * take it past the cap. One old file is kept; the one before it is replaced. + */ +export const appendSwitchLogLine = async ( + filePath: string, + line: string, + maxBytes: number = SWITCH_LOG_MAX_BYTES, +): Promise => { + await fs.promises.mkdir(path.dirname(filePath), { recursive: true }); + let size = 0; + try { + size = (await fs.promises.stat(filePath)).size; + } catch { + // No file yet. + } + const data = line.endsWith('\n') ? line : `${line}\n`; + if (shouldRotate(size, Buffer.byteLength(data), maxBytes)) { + await fs.promises.rename(filePath, `${filePath}.1`); + } + await fs.promises.appendFile(filePath, data, 'utf-8'); +}; + +// One append at a time: two switches finishing together must not both +// decide to rotate, or the second rename would replace the file the first +// had just kept. +let appendQueue: Promise = Promise.resolve(); + +const run = (cmd: string, args: string[], timeoutMs: number): Promise => + new Promise((resolve) => { + try { + execFile( + cmd, + args, + { encoding: 'utf-8', timeout: timeoutMs, maxBuffer: 1024 * 1024 }, + (_err, stdout) => resolve(typeof stdout === 'string' ? stdout : ''), + ); + } catch { + resolve(''); + } + }); + +export interface SwitchLogDeps { + filePath?: string; + /** `sysctl -n vm.swapusage kern.memorystatus_vm_pressure_level`; empty on failure. */ + sysctl?: () => Promise; + /** `ps -A -o %cpu=,comm=`; empty on failure. */ + psTop?: () => Promise; + maxBytes?: number; + /** Called after the line is written (or dropped). For tests. */ + onWritten?: (record: Record | null) => void; +} + +/** + * Begin timing one switch. Call it when the IPC arrives; pass the result + * down the switch path and `settle()` it when `openSession` settles. + * Returns `undefined` when anything at all goes wrong setting up — every + * caller uses `timing?.…`, so the switch then runs untimed. + */ +export const startSwitchTiming = ( + sessionId: string, + active: boolean, + rawStamp: unknown, + deps: SwitchLogDeps = {}, +): SwitchTiming | undefined => { + try { + const ipc = { + wallMs: Date.now(), + perfEpochMs: performance.timeOrigin + performance.now(), + }; + const stamp = sanitizeStamp(rawStamp); + const cpusBefore = os.cpus(); + const cpuUsageBefore = process.cpuUsage(); + const ctx = { ts: new Date(ipc.wallMs).toISOString(), sessionId, active }; + + const onFinish = (snap: SwitchSnapshot) => { + // The samples that describe the span are taken at its end, at once; + // the rest waits for the event loop to be free of the switch. + let sys: SwitchSystemSample = {}; + try { + sys = { + loadavg: os.loadavg(), + cpuPct: cpuPercentBetween(cpusBefore, os.cpus()), + ncpu: cpusBefore.length, + mainCpuMicros: process.cpuUsage(cpuUsageBefore), + claudeProcs: lastLive ? lastLive.count : null, + liveAgeMs: lastLive ? Date.now() - lastLive.at : null, + }; + } catch { + // A record without system figures is still a record. + } + setImmediate(() => { + void writeRecord(snap, sys).catch(() => deps.onWritten?.(null)); + }); + }; + + const writeRecord = async (snap: SwitchSnapshot, sys: SwitchSystemSample) => { + const ms = stepDurations(snap, stamp, ipc); + const sysctl = + deps.sysctl ?? + (() => + run('sysctl', ['-n', 'vm.swapusage', 'kern.memorystatus_vm_pressure_level'], 2000)); + const psTop = deps.psTop ?? (() => run('ps', ['-A', '-o', '%cpu=,comm='], 3000)); + const [sysctlOut, psOut] = await Promise.all([ + sysctl().catch(() => ''), + isSlowSwitch(ms) ? psTop().catch(() => '') : Promise.resolve(null), + ]); + const full: SwitchSystemSample = { + ...sys, + memory: parseMemoryPressure(sysctlOut), + ...(psOut !== null ? { top: parseTopCpu(psOut) } : {}), + }; + const record = buildSwitchRecord(ctx, stamp, snap, ms, full); + const line = JSON.stringify(record); + const filePath = deps.filePath ?? defaultSwitchLogPath(); + const next = appendQueue.then(() => + appendSwitchLogLine(filePath, line, deps.maxBytes), + ); + appendQueue = next.catch(() => undefined); + await next; + deps.onWritten?.(record); + }; + + return createSwitchTiming({ now: () => performance.now(), onFinish }); + } catch { + return undefined; + } +}; diff --git a/src/switch-timing.test.ts b/src/switch-timing.test.ts new file mode 100644 index 0000000..a63ad97 --- /dev/null +++ b/src/switch-timing.test.ts @@ -0,0 +1,523 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + branchFromSwitchOutput, + buildSwitchRecord, + cpuPercentBetween, + createSwitchTiming, + isSlowSwitch, + parseTopCpu, + sanitizeStamp, + shouldRotate, + stepDurations, + SwitchSnapshot, +} from './switch-timing'; +import { + appendSwitchLogLine, + noteLiveReport, + resetLiveReportNote, + startSwitchTiming, +} from './switch-timing-log'; +import { + buildGhosttySwitchScript, + buildITerm2SwitchScript, + buildTerminalAppSwitchScript, +} from './terminal-switch'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const summary = require('../scripts/switch-timing-summary.js'); + +/** A collector on a hand-driven clock, with its timers captured. */ +const harness = (deadlineMs = 1000) => { + let now = 100; + const finished: SwitchSnapshot[] = []; + const timers: { fn: () => void; ms: number; cleared: boolean }[] = []; + const timing = createSwitchTiming({ + now: () => now, + onFinish: (s) => finished.push(s), + deadlineMs, + setTimer: (fn, ms) => { + const t = { fn, ms, cleared: false }; + timers.push(t); + return t; + }, + clearTimer: (h) => { + (h as { cleared: boolean }).cleared = true; + }, + }); + return { timing, finished, timers, advance: (ms: number) => (now += ms) }; +}; + +describe('createSwitchTiming', () => { + it('waits for the script when openSession returns before it exits', () => { + // The running-session paths fire osascript and return at once. + const h = harness(); + h.advance(2); + h.timing.mark('settings'); + h.advance(30); + h.timing.mark('detect'); + h.advance(1); + h.timing.mark('script'); + h.timing.spawned(); + h.advance(1); + h.timing.settle(true); + expect(h.finished).toHaveLength(0); + h.advance(400); + h.timing.exited('found-by-tty\n'); + expect(h.finished).toHaveLength(1); + const snap = h.finished[0]; + expect(snap.marks).toEqual({ settings: 2, detect: 32, script: 33, returned: 34 }); + expect(snap.spawnedAt).toBe(33); + expect(snap.exitedAt).toBe(434); + expect(snap.facts.branch).toBe('tty'); + expect(snap.timedOut).toBe(false); + expect(h.timers[0].cleared).toBe(true); + }); + + it('closes on settle when the command already exited (the resume paths await it)', () => { + const h = harness(); + h.timing.set({ branch: 'new-tab' }); + h.timing.spawned(); + h.advance(250); + h.timing.exited(); + expect(h.finished).toHaveLength(0); + h.timing.settle(true); + expect(h.finished).toHaveLength(1); + // A launch script prints nothing; the branch set beforehand stands. + expect(h.finished[0].facts.branch).toBe('new-tab'); + expect(h.timers).toHaveLength(0); + }); + + it('closes at the deadline, flagged, when the command never reports back', () => { + const h = harness(5000); + h.timing.spawned(); + h.timing.settle(true); + expect(h.timers[0].ms).toBe(5000); + h.advance(5000); + h.timers[0].fn(); + expect(h.finished).toHaveLength(1); + expect(h.finished[0].timedOut).toBe(true); + expect(h.finished[0].exitedAt).toBeNull(); + // A late exit does not produce a second record. + h.timing.exited('found-by-tty'); + expect(h.finished).toHaveLength(1); + }); + + it('records a rejected openSession as not ok, once', () => { + const h = harness(); + h.timing.settle(false); + h.timing.settle(true); + expect(h.finished).toHaveLength(1); + expect(h.finished[0].ok).toBe(false); + }); + + it('never throws into the switch, even when the sink does', () => { + const timing = createSwitchTiming({ + now: () => 0, + onFinish: () => { + throw new Error('disk full'); + }, + }); + expect(() => { + timing.mark('script'); + timing.spawned(); + timing.exited('found-by-title'); + timing.settle(true); + }).not.toThrow(); + }); +}); + +describe('branchFromSwitchOutput', () => { + it('names a branch for every value the real switch scripts can return', () => { + // The contract is with terminal-switch.ts: if a script grows a new + // return value, this fails instead of the log quietly saying null. + const scripts = [ + buildITerm2SwitchScript(1, 'a title', 'tty-first'), + buildTerminalAppSwitchScript(1, 'a title', 'title-first'), + buildGhosttySwitchScript(1, 'a title', 'tty-first', '/tmp/proj'), + ]; + const returned = new Set(); + for (const s of scripts) { + for (const m of s.matchAll(/return "([^"]+)"/g)) returned.add(m[1]); + } + expect([...returned].sort()).toEqual( + ['found-by-cwd', 'found-by-title', 'found-by-tty', 'not found'].sort(), + ); + expect([...returned].map((r) => branchFromSwitchOutput(`${r}\n`)).sort()).toEqual( + ['cwd', 'none', 'title', 'tty'].sort(), + ); + }); + + it('is null — unknown, not "none" — for a failed or silent script', () => { + expect(branchFromSwitchOutput('')).toBeNull(); + expect(branchFromSwitchOutput(undefined)).toBeNull(); + expect(branchFromSwitchOutput('execution error: not allowed (-1743)')).toBeNull(); + }); +}); + +describe('cpuPercentBetween', () => { + const core = (user: number, sys: number, idle: number) => ({ + times: { user, nice: 0, sys, idle, irq: 0 }, + }); + + it('is the non-idle share across all cores', () => { + const before = [core(1000, 500, 8000), core(2000, 500, 7000)]; + // Core 0: +300 busy, +100 idle. Core 1: +0 busy, +400 idle. 300 of 800. + const after = [core(1200, 600, 8100), core(2000, 500, 7400)]; + expect(cpuPercentBetween(before, after)).toBe(37.5); + }); + + it('is null when no time passed or the samples do not line up', () => { + const a = [core(1, 1, 1)]; + expect(cpuPercentBetween(a, a)).toBeNull(); + expect(cpuPercentBetween(a, [core(2, 2, 2), core(1, 1, 1)])).toBeNull(); + expect(cpuPercentBetween(undefined, a)).toBeNull(); + }); +}); + +describe('stepDurations', () => { + const snap = (over: Partial): SwitchSnapshot => ({ + marks: {}, + spawnedAt: null, + exitedAt: null, + endedAt: 0, + facts: {}, + ok: true, + timedOut: false, + ...over, + }); + const ipc = { wallMs: 1_000_010, perfEpochMs: 1_000_010.4 }; + const stamp = { wallMs: 1_000_000, perfEpochMs: 1_000_001.2, via: 'enter' as const, rows: 3 }; + + it('splits a running-session switch into its steps, ending at the exit', () => { + const ms = stepDurations( + snap({ + marks: { settings: 2, detect: 32, script: 33, returned: 34.5 }, + spawnedAt: 33.6, + exitedAt: 434, + endedAt: 434, + }), + stamp, + ipc, + ); + expect(ms).toEqual({ + clickToIpc: 10, + clickToIpcHr: 9.2, + settings: 2, + detect: 30, + build: 1, + spawn: 0.6, + run: 400.4, + returned: 34.5, + main: 434, + total: 444, + }); + }); + + it('leaves detect null for a resume and counts that time in build', () => { + const ms = stepDurations( + snap({ marks: { settings: 2, script: 5, returned: 300 }, spawnedAt: 6, exitedAt: 299 }), + stamp, + ipc, + ); + expect(ms.detect).toBeNull(); + expect(ms.build).toBe(3); + expect(ms.run).toBe(293); + }); + + it('has no total for a command that timed out, and no click time without a stamp', () => { + const timedOut = stepDurations( + snap({ marks: { returned: 5 }, spawnedAt: 4, endedAt: 15000, timedOut: true }), + undefined, + ipc, + ); + expect(timedOut.total).toBeNull(); + expect(timedOut.run).toBeNull(); + expect(timedOut.clickToIpc).toBeNull(); + expect(isSlowSwitch(timedOut)).toBe(false); + // Without a stamp the total is main's own span, not a guess. + const noStamp = stepDurations(snap({ marks: { returned: 5 }, endedAt: 5 }), undefined, ipc); + expect(noStamp.total).toBe(5); + }); + + it('does not let a renderer clock that runs ahead shorten the total', () => { + const ahead = { ...stamp, wallMs: ipc.wallMs + 50 }; + const ms = stepDurations(snap({ marks: { returned: 20 }, endedAt: 20 }), ahead, ipc); + expect(ms.clickToIpc).toBe(-50); // kept as measured + expect(ms.total).toBe(20); + }); +}); + +describe('sanitizeStamp', () => { + it('keeps a well-formed stamp and drops what it cannot trust', () => { + expect(sanitizeStamp({ wallMs: 1, perfEpochMs: 2, via: 'enter', rows: 9 })).toEqual({ + wallMs: 1, + perfEpochMs: 2, + via: 'enter', + rows: 9, + }); + expect(sanitizeStamp({ wallMs: 1, perfEpochMs: 2, via: 'rm -rf', rows: 'many' })).toEqual({ + wallMs: 1, + perfEpochMs: 2, + via: undefined, + rows: undefined, + }); + expect(sanitizeStamp({ wallMs: '1', perfEpochMs: 2 })).toBeUndefined(); + expect(sanitizeStamp('2026')).toBeUndefined(); + expect(sanitizeStamp(undefined)).toBeUndefined(); + }); +}); + +describe('parseTopCpu', () => { + it('returns the busiest processes by name, without their paths', () => { + const out = [ + ' 0.0 /sbin/launchd', + ' 88.1 /System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer', + ' 12.5 /Users/someone/Applications/My App.app/Contents/MacOS/My App', + '140.2 claude', + 'garbage line', + '', + ].join('\n'); + expect(parseTopCpu(out)).toEqual([ + { cpu: 140.2, comm: 'claude' }, + { cpu: 88.1, comm: 'WindowServer' }, + { cpu: 12.5, comm: 'My App' }, + ]); + }); + + it('reads a comma decimal (ps follows the locale)', () => { + expect(parseTopCpu(' 3,5 /bin/zsh\n 12,0 /usr/bin/top', 1)).toEqual([ + { cpu: 12, comm: 'top' }, + ]); + }); +}); + +describe('shouldRotate', () => { + it('rotates when the line would cross the cap, never an empty file', () => { + expect(shouldRotate(900, 100, 1000)).toBe(false); // lands exactly on the cap + expect(shouldRotate(900, 101, 1000)).toBe(true); + expect(shouldRotate(0, 5000, 1000)).toBe(false); + }); +}); + +describe('the log file', () => { + let dir: string; + let file: string; + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'switch-timing-')); + file = path.join(dir, 'nested', 'switch-timing.jsonl'); + resetLiveReportNote(); + }); + afterEach(() => fs.rmSync(dir, { recursive: true, force: true })); + + it('rotates to .1 at the cap and keeps exactly one old file', async () => { + const line = 'x'.repeat(40); + await appendSwitchLogLine(file, line, 100); + await appendSwitchLogLine(file, line, 100); // 82 bytes + expect(fs.existsSync(`${file}.1`)).toBe(false); + await appendSwitchLogLine(file, 'second', 100); // would be 89: fits + await appendSwitchLogLine(file, line, 100); // would be 130: rotate + expect(fs.readFileSync(`${file}.1`, 'utf-8')).toBe(`${line}\n${line}\nsecond\n`); + expect(fs.readFileSync(file, 'utf-8')).toBe(`${line}\n`); + await appendSwitchLogLine(file, 'y'.repeat(80), 100); // rotate again + expect(fs.readFileSync(`${file}.1`, 'utf-8')).toBe(`${line}\n`); + expect(fs.readdirSync(path.dirname(file)).sort()).toEqual([ + 'switch-timing.jsonl', + 'switch-timing.jsonl.1', + ]); + }); + + const runSwitch = ( + stamp: unknown, + deps: { sysctl?: () => Promise; psTop?: () => Promise } = {}, + ) => + new Promise | null>((resolve) => { + const timing = startSwitchTiming( + '0f1e2d3c-aaaa-bbbb-cccc-123456789abc', + true, + stamp, + { + filePath: file, + sysctl: async () => + 'total = 2048.00M used = 512.50M free = 1535.50M (encrypted)\n2\n', + psTop: async () => ' 91.0 /usr/libexec/somed\n 1.0 /bin/zsh\n', + ...deps, + onWritten: resolve, + }, + ); + timing.set({ configured: 'iterm2', terminal: 'ghostty', order: 'tty-first' }); + timing.mark('settings'); + timing.mark('script'); + timing.spawned(); + timing.settle(true); + timing.exited('found-by-title\n'); + }); + + it('writes one line per switch, with no trace of the session beyond an id prefix', async () => { + noteLiveReport({ live: [{}, {}, {}] }); + let psCalls = 0; + const record = await runSwitch( + { wallMs: Date.now(), perfEpochMs: performance.timeOrigin + performance.now(), via: 'click', rows: 42 }, + { + psTop: async () => { + psCalls++; + return ''; + }, + }, + ); + const lines = fs.readFileSync(file, 'utf-8').trim().split('\n'); + expect(lines).toHaveLength(1); + const onDisk = JSON.parse(lines[0]); + expect(onDisk).toEqual(record); + expect(onDisk).toMatchObject({ + v: 1, + sid: '0f1e2d3c', + via: 'click', + kind: 'switch', + terminal: 'ghostty', + configured: 'iterm2', + tool: null, + branch: 'title', + order: 'tty-first', + ok: true, + timedOut: false, + mem: { level: 2, swapUsedMb: 512.5, swapTotalMb: 2048 }, + claudeProcs: 3, + rows: 42, + }); + expect(lines[0]).not.toContain('aaaa-bbbb'); + expect(onDisk.ms.total).toBeGreaterThanOrEqual(0); + expect(onDisk.load).toHaveLength(3); + expect(onDisk.ncpu).toBe(os.cpus().length); + // A fast switch does not pay for `ps`, and has no `top`. + expect(psCalls).toBe(0); + expect('top' in onDisk).toBe(false); + }); + + it('adds the busiest processes only when the switch was slow', async () => { + const record = await runSwitch({ + wallMs: Date.now() - 1500, // the click was 1.5 s before the IPC arrived + perfEpochMs: performance.timeOrigin + performance.now() - 1500, + via: 'enter', + rows: 1, + }); + expect((record.ms as { total: number }).total).toBeGreaterThan(1000); + expect(record.top).toEqual([ + { cpu: 91, comm: 'somed' }, + { cpu: 1, comm: 'zsh' }, + ]); + }); + + it('still writes the record when sysctl and the live count are unavailable', async () => { + const record = await runSwitch(undefined, { + sysctl: async () => { + throw new Error('no sysctl'); + }, + }); + expect(record).toMatchObject({ mem: null, claudeProcs: null, via: null, rows: null }); + expect((record.ms as { clickToIpc: unknown }).clickToIpc).toBeNull(); + expect(fs.readFileSync(file, 'utf-8').trim().split('\n')).toHaveLength(1); + }); + + it('drops the record, without throwing, when the file cannot be written', async () => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.mkdirSync(file); // a directory where the log should be + expect(await runSwitch(undefined)).toBeNull(); + }); +}); + +describe('buildSwitchRecord', () => { + it('marks a resume and keeps unknowns as null rather than guessing', () => { + const snap: SwitchSnapshot = { + marks: { returned: 5 }, + spawnedAt: null, + exitedAt: null, + endedAt: 5, + facts: {}, + ok: false, + timedOut: false, + }; + const ms = stepDurations(snap, undefined, { wallMs: 0, perfEpochMs: 0 }); + const r = buildSwitchRecord( + { ts: '2026-01-02T03:04:05.000Z', sessionId: 'abcdefghijkl', active: false }, + undefined, + snap, + ms, + { mainCpuMicros: { user: 12345, system: 678 } }, + ); + expect(r).toMatchObject({ + sid: 'abcdefgh', + kind: 'resume', + terminal: null, + branch: null, + tool: null, + ok: false, + cpuPct: null, + mainCpuMs: { user: 12.3, system: 0.7 }, + load: [], + }); + }); +}); + +describe('scripts/switch-timing-summary.js', () => { + it('interpolates percentiles and ignores non-numbers', () => { + expect(summary.percentile([10, 20, 30, 40], 50)).toBe(25); + expect(summary.percentile([40, 10, 30, 20, null, NaN, 'x'], 90)).toBeCloseTo(37, 10); + expect(summary.percentile([7], 90)).toBe(7); + expect(summary.percentile([], 50)).toBeNull(); + }); + + it('computes a correlation only when there is something to correlate', () => { + expect(summary.pearson([[1, 2], [2, 4], [3, 6]])).toBeCloseTo(1, 10); + expect(summary.pearson([[1, 6], [2, 4], [3, 2]])).toBeCloseTo(-1, 10); + expect(summary.pearson([[1, 2], [2, 4]])).toBeNull(); // too few + expect(summary.pearson([[1, 5], [2, 5], [3, 5]])).toBeNull(); // no variance + expect(summary.pearson([[1, 2], [null, 4], [3, 6], [4, 8]])).toBeCloseTo(1, 10); + }); + + it('skips malformed lines and groups what is left', () => { + const rec = (terminal: string, branch: string | null, run: number, load1: number) => + JSON.stringify({ + v: 1, + kind: 'switch', + terminal, + branch, + ncpu: 10, + load: [load1, 0, 0], + ms: { run, total: run + 10 }, + }); + const text = [ + rec('iterm2', 'tty', 100, 2), + '{"truncated": ', + rec('iterm2', 'title', 300, 12), + '', + '"a string"', + '{"v":1}', + rec('ghostty', null, 900, 25), + ].join('\n'); + const { records, malformed } = summary.parseLines(text); + expect(records).toHaveLength(3); + expect(malformed).toBe(3); + const s = summary.summarize(records); + expect(s.all.total).toEqual({ n: 3, p50: 310, p90: 790 }); + expect(s.all.detect.n).toBe(0); + expect(s.byTerminal.map((g: { key: string; n: number }) => [g.key, g.n])).toEqual([ + ['iterm2', 2], + ['ghostty', 1], + ]); + expect(s.byBranch.map((g: { key: string }) => g.key).sort()).toEqual(['title', 'tty', 'unknown']); + expect(s.load.buckets.map((b: { n: number }) => b.n)).toEqual([1, 0, 1, 1]); + expect(s.load.rTotalVsLoad1).toBeGreaterThan(0.9); + const report = summary.formatReport(s, malformed); + expect(report).toContain('3 switches'); + expect(report).toContain('3 malformed line(s) skipped'); + }); + + it('reports an empty log instead of failing', () => { + const { records, malformed } = summary.parseLines(''); + expect(summary.formatReport(summary.summarize(records), malformed)).toBe('No switch records.'); + }); +}); diff --git a/src/switch-timing.ts b/src/switch-timing.ts new file mode 100644 index 0000000..c895810 --- /dev/null +++ b/src/switch-timing.ts @@ -0,0 +1,439 @@ +/** + * Where does a session switch spend its time? One record per switch, from + * the click in the renderer to the terminal's script exiting, so the cost of + * CodeV's own code can be told apart from the cost of `osascript` and of a + * loaded machine before anything is rewritten for speed. + * + * This file is the pure half: the collector that the switch path marks as + * it goes, and the arithmetic that turns marks and samples into a record. + * No Electron, no fs, no child processes — `switch-timing-log.ts` does the + * reading and writing, after the switch. + * + * Two rules the callers rely on: + * + * - **Nothing here throws into a switch.** Every collector method swallows + * its own errors, and every call site uses `timing?.…`, so a switch with + * no collector, or with a broken one, runs exactly as it did before. + * - **A record holds timings and counts, never content**: no title, prompt + * or path. The only trace of the session is the first 8 characters of its + * id, enough to tell two switches to one session from two sessions. + */ + +/** Points on the path, in the order a terminal switch passes them. */ +export type SwitchMark = + /** Main read its two settings (terminal app, tab/window). */ + | 'settings' + /** `detectTerminalApp` answered (running sessions only). */ + | 'detect' + /** The AppleScript text (or the command line) is built. */ + | 'script' + /** `openSession` returned to the IPC handler. */ + | 'returned'; + +/** + * Which key found the tab. `none` — the script ran and matched nothing; + * `null` on a record — the path cannot say (see `branchFromSwitchOutput`). + */ +export type SwitchBranch = + | 'tty' + | 'title' + | 'cwd' + | 'project-name' + | 'none' + | 'new-tab' + | 'new-window' + | 'new-workspace' + | 'embedded' + | 'deep-link'; + +/** What ran the switch: the thing whose exit ends the measurement. */ +export type SwitchTool = 'osascript' | 'cmux-cli' | 'open' | 'pty'; + +/** Facts a step learns about the switch. All optional: a path sets what it knows. */ +export interface SwitchFacts { + /** The terminal named in Settings. */ + configured?: string; + /** The terminal the switch went to, after auto-detection. */ + terminal?: string; + tool?: SwitchTool; + branch?: SwitchBranch | null; + /** Which key the script tried first. */ + order?: 'tty-first' | 'title-first'; + /** Whether the script carried a title block at all (a `/rename`d session). */ + hasTitle?: boolean; +} + +/** What the renderer stamps on the click that starts a switch. */ +export interface RendererStamp { + /** `Date.now()` at the keypress or click. */ + wallMs: number; + /** `performance.timeOrigin + performance.now()` at the same moment. */ + perfEpochMs: number; + /** How the switch was started. */ + via?: 'enter' | 'click'; + /** Rows in the session list at that moment. */ + rows?: number; +} + +/** The marks and facts of one finished switch, before any system sample. */ +export interface SwitchSnapshot { + /** Monotonic ms since the IPC arrived, per mark. */ + marks: Partial>; + /** Monotonic ms since the IPC arrived: the external command started / exited. */ + spawnedAt: number | null; + exitedAt: number | null; + /** When the record was closed, on the same clock. */ + endedAt: number; + facts: SwitchFacts; + /** False when `openSession` rejected. */ + ok: boolean; + /** True when the external command had not exited by the safety deadline. */ + timedOut: boolean; +} + +export interface SwitchTiming { + mark(step: SwitchMark): void; + set(facts: SwitchFacts): void; + /** The external command (osascript, the cmux CLI) was started. */ + spawned(): void; + /** + * It exited. `stdout`, when the command is a switch script, names the + * branch that matched. + */ + exited(stdout?: string): void; + /** + * `openSession` settled. The record closes now if nothing is still + * running, otherwise when it exits (or at the safety deadline). + */ + settle(ok: boolean): void; +} + +export interface SwitchTimingDeps { + /** A monotonic clock in ms. */ + now: () => number; + onFinish: (snapshot: SwitchSnapshot) => void; + /** How long to wait for a command that never reports its exit. */ + deadlineMs?: number; + setTimer?: (fn: () => void, ms: number) => { unref?: () => void } | unknown; + clearTimer?: (handle: unknown) => void; +} + +/** A command that outlives this has been killed by its own timeout or is hung. */ +export const SWITCH_DEADLINE_MS = 15000; + +/** + * The switch scripts end in `return "found-by-tty"` and the like (see + * terminal-switch.ts); osascript prints that value. Reading it costs + * nothing and changes no script. Anything else — an empty stdout from a + * script that failed, a launch script, which returns nothing — is `null`: + * unknown, which is not the same as "matched nothing". + */ +export const branchFromSwitchOutput = ( + stdout: string | undefined, +): SwitchBranch | null => { + const out = (stdout || '').trim(); + if (out === 'found-by-tty') return 'tty'; + if (out === 'found-by-title') return 'title'; + if (out === 'found-by-cwd') return 'cwd'; + if (out === 'not found') return 'none'; + return null; +}; + +export const createSwitchTiming = (deps: SwitchTimingDeps): SwitchTiming => { + const t0 = deps.now(); + const marks: Partial> = {}; + let facts: SwitchFacts = {}; + let spawnedAt: number | null = null; + let exitedAt: number | null = null; + let running = 0; + let settled = false; + let ok = true; + let finished = false; + let timer: unknown = null; + const since = () => deps.now() - t0; + const guard = (fn: () => void) => { + try { + fn(); + } catch { + // A broken measurement must never reach the switch. + } + }; + + const finish = (timedOut: boolean) => { + if (finished) return; + finished = true; + if (timer !== null) (deps.clearTimer ?? clearTimeout)(timer as any); + deps.onFinish({ + marks: { ...marks }, + spawnedAt, + exitedAt, + endedAt: since(), + facts: { ...facts }, + ok, + timedOut, + }); + }; + + return { + mark: (step) => + guard(() => { + // First write wins: a step reached twice keeps its first time. + if (!finished && marks[step] === undefined) marks[step] = since(); + }), + set: (more) => + guard(() => { + if (!finished) facts = { ...facts, ...more }; + }), + spawned: () => + guard(() => { + if (finished) return; + running++; + if (spawnedAt === null) spawnedAt = since(); + }), + exited: (stdout) => + guard(() => { + if (finished) return; + running = Math.max(0, running - 1); + exitedAt = since(); + if (stdout !== undefined && facts.branch === undefined) { + facts = { ...facts, branch: branchFromSwitchOutput(stdout) }; + } + if (settled && running === 0) finish(false); + }), + settle: (succeeded) => + guard(() => { + if (finished || settled) return; + settled = true; + ok = succeeded; + if (marks.returned === undefined) marks.returned = since(); + if (running === 0) { + finish(false); + return; + } + // The active-session paths return before their script exits, so the + // record waits for it — but not forever. + timer = (deps.setTimer ?? setTimeout)( + () => guard(() => finish(true)), + deps.deadlineMs ?? SWITCH_DEADLINE_MS, + ); + (timer as { unref?: () => void })?.unref?.(); + }), + }; +}; + +// --- arithmetic --- + +/** The fields of `os.cpus()[n].times` this needs. */ +export interface CpuTimes { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; +} + +/** + * Whole-machine CPU busy % between two `os.cpus()` samples: 100 × (1 − idle + * share), over every core. Null when the samples cannot be compared — no + * time passed between them (the counters tick at 10 ms), or the core count + * changed. + */ +export const cpuPercentBetween = ( + before: { times: CpuTimes }[] | null | undefined, + after: { times: CpuTimes }[] | null | undefined, +): number | null => { + if (!before || !after || before.length === 0 || before.length !== after.length) { + return null; + } + const sum = (t: CpuTimes) => t.user + t.nice + t.sys + t.idle + t.irq; + let total = 0; + let idle = 0; + for (let i = 0; i < before.length; i++) { + total += sum(after[i].times) - sum(before[i].times); + idle += after[i].times.idle - before[i].times.idle; + } + if (!(total > 0)) return null; + const pct = 100 * (1 - idle / total); + return round1(Math.min(100, Math.max(0, pct))); +}; + +const round1 = (n: number): number => Math.round(n * 10) / 10; + +/** `b − a` to a tenth of a ms; null when either end was never reached. */ +const span = (a: number | null | undefined, b: number | null | undefined): number | null => + typeof a === 'number' && typeof b === 'number' ? round1(b - a) : null; + +export interface SwitchStepMs { + /** Click to the IPC arriving in main, on the wall clock (whole ms). */ + clickToIpc: number | null; + /** The same on the two processes' high-resolution clocks. */ + clickToIpcHr: number | null; + /** IPC arrival to the two settings read. */ + settings: number | null; + /** `detectTerminalApp`. Null for a resume, which does not detect. */ + detect: number | null; + /** Building the script text, plus whatever JS precedes it. */ + build: number | null; + /** Writing the script file and starting the command. */ + spawn: number | null; + /** The command itself: started to exited. */ + run: number | null; + /** IPC arrival to `openSession` returning. */ + returned: number | null; + /** IPC arrival to the end: the command's exit, else `openSession` returning. */ + main: number | null; + /** `clickToIpc + main`: what the user waited. */ + total: number | null; +} + +/** + * Step durations from one snapshot. Each step is measured from the step + * before it that this path actually reached, so a path that skips one + * (a resume skips `detect`) does not lose the time: it lands in the next. + */ +export const stepDurations = ( + snap: SwitchSnapshot, + stamp: RendererStamp | undefined, + ipc: { wallMs: number; perfEpochMs: number }, +): SwitchStepMs => { + const { marks, spawnedAt, exitedAt } = snap; + const afterSettings = marks.settings ?? 0; + const beforeScript = marks.detect ?? afterSettings; + // A command that timed out never reported an exit; the record's end is + // then the deadline, which is not a duration of anything. + const end = snap.timedOut ? null : exitedAt ?? marks.returned ?? snap.endedAt; + const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n); + const clickToIpc = stamp && finite(stamp.wallMs) ? ipc.wallMs - stamp.wallMs : null; + const clickToIpcHr = + stamp && finite(stamp.perfEpochMs) ? round1(ipc.perfEpochMs - stamp.perfEpochMs) : null; + const main = span(0, end); + return { + clickToIpc, + clickToIpcHr, + settings: span(0, marks.settings), + detect: span(afterSettings, marks.detect), + build: span(beforeScript, marks.script), + spawn: span(marks.script ?? beforeScript, spawnedAt), + run: span(spawnedAt, exitedAt), + returned: span(0, marks.returned), + main, + total: main === null ? null : round1(main + Math.max(0, clickToIpc ?? 0)), + }; +}; + +/** System state around one switch. Every field may be missing. */ +export interface SwitchSystemSample { + loadavg?: number[]; + cpuPct?: number | null; + ncpu?: number; + /** `process.cpuUsage(start)` of the main process, in microseconds. */ + mainCpuMicros?: { user: number; system: number }; + memory?: { level: number; swapUsedMb: number; swapTotalMb: number } | null; + /** Running `claude` processes in the last live-sessions report, and its age. */ + claudeProcs?: number | null; + liveAgeMs?: number | null; + /** Only for a slow switch: the busiest processes right after it. */ + top?: { cpu: number; comm: string }[]; +} + +export interface SwitchContext { + /** ISO time of the IPC arriving. */ + ts: string; + sessionId: string; + active: boolean; +} + +/** + * The stamp crosses an IPC boundary, so it is checked rather than trusted: + * anything not shaped like one is dropped, and the record simply has no + * click time. + */ +export const sanitizeStamp = (raw: unknown): RendererStamp | undefined => { + if (!raw || typeof raw !== 'object') return undefined; + const r = raw as Record; + const num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); + if (!num(r.wallMs) || !num(r.perfEpochMs)) return undefined; + return { + wallMs: r.wallMs, + perfEpochMs: r.perfEpochMs, + via: r.via === 'enter' || r.via === 'click' ? r.via : undefined, + rows: num(r.rows) ? r.rows : undefined, + }; +}; + +export const SWITCH_RECORD_VERSION = 1; + +/** A switch slower than this also records the busiest processes. */ +export const SLOW_SWITCH_MS = 1000; + +export const isSlowSwitch = (ms: SwitchStepMs): boolean => + typeof ms.total === 'number' && ms.total > SLOW_SWITCH_MS; + +export const buildSwitchRecord = ( + ctx: SwitchContext, + stamp: RendererStamp | undefined, + snap: SwitchSnapshot, + ms: SwitchStepMs, + sys: SwitchSystemSample, +): Record => ({ + v: SWITCH_RECORD_VERSION, + ts: ctx.ts, + sid: String(ctx.sessionId || '').slice(0, 8), + via: stamp?.via ?? null, + kind: ctx.active ? 'switch' : 'resume', + terminal: snap.facts.terminal ?? snap.facts.configured ?? null, + configured: snap.facts.configured ?? null, + tool: snap.facts.tool ?? null, + branch: snap.facts.branch ?? null, + order: snap.facts.order ?? null, + hasTitle: snap.facts.hasTitle ?? null, + ok: snap.ok, + timedOut: snap.timedOut, + ms, + load: (sys.loadavg ?? []).map((n) => Math.round(n * 100) / 100), + cpuPct: sys.cpuPct ?? null, + ncpu: sys.ncpu ?? null, + mainCpuMs: sys.mainCpuMicros + ? { + user: round1(sys.mainCpuMicros.user / 1000), + system: round1(sys.mainCpuMicros.system / 1000), + } + : null, + mem: sys.memory ?? null, + claudeProcs: sys.claudeProcs ?? null, + liveAgeMs: sys.liveAgeMs ?? null, + rows: stamp?.rows ?? null, + ...(sys.top ? { top: sys.top } : {}), +}); + +/** + * The busiest `n` processes from `ps -A -o %cpu=,comm=`. `comm` is a full + * path on macOS, and a path under a home directory names its user, so only + * the executable's own name is kept. + */ +export const parseTopCpu = (psOut: string, n = 3): { cpu: number; comm: string }[] => + psOut + .split('\n') + .map((line) => /^\s*([0-9]+(?:[.,][0-9]+)?)\s+(.+?)\s*$/.exec(line)) + .filter((m): m is RegExpExecArray => !!m) + .map((m) => ({ + cpu: Number(m[1].replace(',', '.')), + comm: m[2].slice(m[2].lastIndexOf('/') + 1), + })) + .filter((p) => Number.isFinite(p.cpu) && p.comm) + .sort((a, b) => b.cpu - a.cpu) + .slice(0, n); + +/** The log is capped: at this size it moves to `.1`, replacing the last one. */ +export const SWITCH_LOG_MAX_BYTES = 1024 * 1024; + +/** + * Rotate before this append? Yes when the line would take the file past the + * cap — but never for an empty file, or one oversized line would rotate on + * every write and keep nothing. + */ +export const shouldRotate = ( + currentBytes: number, + incomingBytes: number, + maxBytes: number = SWITCH_LOG_MAX_BYTES, +): boolean => currentBytes > 0 && currentBytes + incomingBytes > maxBytes; diff --git a/src/switcher-ui.tsx b/src/switcher-ui.tsx index 754af36..9a0dfa0 100644 --- a/src/switcher-ui.tsx +++ b/src/switcher-ui.tsx @@ -350,6 +350,16 @@ export function deleteVSCodeBasedIDESqliteRecord(path: string) { window.electronAPI.deleteVSCodeBasedIDESqliteRecord(path); } +// When a switch was asked for, for main's switch timing log (switch-timing.ts): +// the wall clock, and this process's high-resolution clock as epoch ms so main +// can subtract its own. Counts only — nothing about the session. +const switchStamp = (via: 'enter' | 'click', rows: number) => ({ + wallMs: Date.now(), + perfEpochMs: performance.timeOrigin + performance.now(), + via, + rows, +}); + function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } @@ -2787,6 +2797,7 @@ function SwitcherApp() { customTitles[s.sessionId], // A list member's captured account, when the row itself has none. s.accountLabel ?? s.__listMember?.accountLabel, + switchStamp('enter', displayedSessions.length), ); } } else if ((e.metaKey || e.ctrlKey) && (e.key === 'd' || e.key === 'D')) { @@ -3387,6 +3398,7 @@ function SwitcherApp() { session.activePid, customTitles[session.sessionId], session.accountLabel ?? session.__listMember?.accountLabel, + switchStamp('click', displayedSessions.length), ); }} style={{ From d20c488244a299f9bfa840aee5ddbfcb81a0df95 Mon Sep 17 00:00:00 2001 From: Grimmer Kang Date: Fri, 20 Nov 2026 21:53:24 +0900 Subject: [PATCH 2/7] fix(sessions): create the switch timing log owner-only The marks and lists stores beside it are 0600; the log now matches. Co-Authored-By: Claude Fable 5.2 --- src/switch-timing-log.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/switch-timing-log.ts b/src/switch-timing-log.ts index 11fbff6..ef52219 100644 --- a/src/switch-timing-log.ts +++ b/src/switch-timing-log.ts @@ -84,7 +84,8 @@ export const appendSwitchLogLine = async ( if (shouldRotate(size, Buffer.byteLength(data), maxBytes)) { await fs.promises.rename(filePath, `${filePath}.1`); } - await fs.promises.appendFile(filePath, data, 'utf-8'); + // Owner-only when created, like the marks and lists stores beside it. + await fs.promises.appendFile(filePath, data, { encoding: 'utf-8', mode: 0o600 }); }; // One append at a time: two switches finishing together must not both From 679726ee40903355beeb00bea67f2239728b914e Mon Sep 17 00:00:00 2001 From: Grimmer Kang Date: Fri, 20 Nov 2026 22:06:49 +0900 Subject: [PATCH 3/7] feat(sessions): the switch timing log names its session Reverses the first version's "no session content" rule: per-session patterns (a crowded window, one account, a session that always falls back to cwd) cannot be seen without knowing which session a line was. - Record v2: sessionId (full; the 8-char sid is dropped), title, account, project, pid and tty. The tty comes from the last live-sessions report when it lists the pid, else from one `ps -o tty= -p ` after the switch; a failure is null. Nothing new on the switch's path, and no script or matching order changed. - Prompts and transcript text are still not recorded. The file is local and owner-only (0600). - Summary: by account, a per-session table (n, p50/p90 total and run, branch mix, terminal, account; top 20, --all, --sort=p90), and --redact, which swaps ids, titles, account labels and paths for placeholders that are stable for a given log. v1 lines still count everywhere except the per-session table. - CHANGELOG, the docs section and the code comments that said the log held no title or path are rewritten to say what it holds now. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- docs/claude-session-integration-design.md | 24 +- scripts/switch-timing-summary.js | 216 +++++++++++++++++- src/main.ts | 12 +- src/switch-timing-log.ts | 43 +++- src/switch-timing.test.ts | 264 +++++++++++++++++++++- src/switch-timing.ts | 55 ++++- src/switcher-ui.tsx | 3 +- 8 files changed, 579 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1c91e1..0fda485 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 1.0.97 -- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s, the three busiest processes). **It holds timings and counts, no session content** — no title, prompt or path, only the first 8 characters of the session id. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch, and a failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal and by branch, and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" +- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s, the three busiest processes). **Each line names its session** — the session id, title, account label, project path, the pid switched to and its tty — so per-session patterns show (a crowded window, one account, a session that always falls back to cwd); **prompts and transcript text are not recorded**. The file is local and owner-only (0600); when quoting results in public, replace titles and paths with placeholders — `yarn switch-timing --redact` does it. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch, and a failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal, branch and account, a per-session table (`--all`, `--sort=p90`), and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" ## 1.0.94 diff --git a/docs/claude-session-integration-design.md b/docs/claude-session-integration-design.md index 4c7854d..456e03f 100644 --- a/docs/claude-session-integration-design.md +++ b/docs/claude-session-integration-design.md @@ -669,7 +669,7 @@ TypeScript is sufficient for MVP. `history.jsonl` reading (~40ms) and session li Before rewriting any part of the switch path for speed, measure where a switch spends its time. Since 1.0.97 every switch started from the Sessions tab (Enter or a click) appends one JSON line to `~/.config/codev/switch-timing.jsonl`. The question it is meant to answer: is the time in CodeV's own JavaScript, which a rewrite could shorten, or in the external command (`osascript`, or the cmux CLI) and a loaded machine, which it could not? -**What a line holds: timings and counts only.** No title, prompt or path; the only trace of the session is the first 8 characters of its id. The file is capped at about 1 MB: at the cap it is renamed to `switch-timing.jsonl.1` (one old file is kept) and a new one starts. Logging is always on; there is no setting. +**What a line holds: timings, counts, and which session it was.** Each line names its session — the session id, its title, account label, project path, the pid switched to and that process's tty — so that per-session patterns show up: one crowded terminal window, one account, a session that always falls back to cwd. **Prompts and transcript text are not recorded.** The file stays on this machine and is created owner-only (mode 0600), like the stores beside it. Titles and paths are the owner's own words and directories, so anyone quoting results in public (an issue, a pull request) should replace them with placeholders; the summary script's `--redact` does that. The file is capped at about 1 MB: at the cap it is renamed to `switch-timing.jsonl.1` (one old file is kept) and a new one starts. Logging is always on; there is no setting. ``` renderer main process terminal @@ -690,9 +690,14 @@ Steps ① to ⑦ are the switch. Step ⑧ runs only after it, so nothing that sp | Field | Meaning | |---|---| -| `v` | Record version (1). | +| `v` | Record version. 2 names the session (the six fields below); version 1 lines, written by the first build of this log, carry only `sid`, the first 8 characters of the id. | | `ts` | ISO time the IPC arrived in the main process. | -| `sid` | First 8 characters of the session id. | +| `sessionId` | The full session id. | +| `title` | The session's `/rename` title when the switch was started; `null` when it has none. | +| `account` | The account label the row carried; `null` for the anchor account. | +| `project` | The session's project path. | +| `pid` | The process switched to; `null` for a resume, which has none yet. | +| `tty`, `ttySrc` | That process's controlling terminal (for example `ttys004`), and where the value came from: `live-report` (the last live-sessions report already listed it) or `ps` (one `ps -o tty= -p `, run after the switch). `null` when there is no pid, the process has no tty, or the lookup failed. | | `via` | `enter` or `click`. | | `kind` | `switch` (the session was running) or `resume` (it was not; a new tab runs `claude --resume`). | | `terminal`, `configured` | Where the switch went after auto-detection, and the terminal named in Settings. | @@ -719,10 +724,19 @@ Not recorded: the number of terminal tabs (only the terminal knows, and asking w To summarize the log: ```bash -yarn switch-timing # or: node scripts/switch-timing-summary.js [file ...] +yarn switch-timing # or: node scripts/switch-timing-summary.js [options] [file ...] +yarn switch-timing --redact # for anything that will be pasted somewhere public ``` -It prints p50/p90 (50th and 90th percentile) per step and for the total — for all switches, and grouped by kind, terminal and branch — then the share of the total spent inside the external command, and the total against load: buckets of 1-minute load per core, and Pearson correlations of the total with load and with CPU %. Malformed lines are counted and skipped; a missing or empty log prints "No switch records." +It prints p50/p90 (50th and 90th percentile) per step and for the total — for all switches, and grouped by kind, terminal, branch and account. Then a per-session table: the number of switches, p50/p90 of the total and of the external command, the terminal, the account, the branch mix (for example `tty×5 cwd×2`), the title and the project path. Then the share of the total spent inside the external command, and the total against load: buckets of 1-minute load per core, and Pearson correlations of the total with load and with CPU %. + +| Option | Effect | +|---|---| +| `--redact` | Replaces every session id, title, account label and project path with a placeholder (`session-1`, `title of session-1`, `account-1`, `~/project-1`). The numbering follows first appearance in the log, so the same log always gives the same names. Timings, branches, terminals, pids and ttys are kept. | +| `--all` | Lists every session; the default is the first 20. | +| `--sort=p90` | Sorts sessions by p90 total, slowest first; the default, `--sort=n`, is by number of switches. | + +Malformed lines are counted and skipped; a missing or empty log prints "No switch records." Version 1 lines still count in every grouping except the per-session table (they do not name a session), and fall under `(unknown)` in the account table. ### `history.jsonl` vs `session-metadata.db` diff --git a/scripts/switch-timing-summary.js b/scripts/switch-timing-summary.js index 6382276..e328b73 100644 --- a/scripts/switch-timing-summary.js +++ b/scripts/switch-timing-summary.js @@ -2,15 +2,24 @@ /** * Summarize CodeV's switch timing log (src/switch-timing.ts writes it). * - * node scripts/switch-timing-summary.js [file ...] + * node scripts/switch-timing-summary.js [--redact] [--all] [--sort=n|p90] [file ...] * - * With no argument it reads ~/.config/codev/switch-timing.jsonl.1 (the - * rotated file, if any) and then ~/.config/codev/switch-timing.jsonl. + * With no file it reads ~/.config/codev/switch-timing.jsonl.1 (the rotated + * file, if any) and then ~/.config/codev/switch-timing.jsonl. * * Prints p50 / p90 per step and for the total, for all switches and grouped - * by kind, terminal and branch; then the total against machine load. Plain - * Node, no dependencies. A line that is not a record is counted and skipped; - * a missing or empty file is reported, not an error. + * by kind, terminal, branch and account; a per-session table (the 20 with + * the most switches; `--all` for every one, `--sort=p90` for the slowest + * first); then the total against machine load. Plain Node, no dependencies. + * A line that is not a record is counted and skipped; a missing or empty + * file is reported, not an error. Version 1 lines, which did not name their + * session, count everywhere except the per-session table. + * + * The log names sessions: id, title, account label and project path. That + * is the owner's own data on the owner's machine — but the output of this + * script gets pasted into issues. `--redact` replaces every one of those + * with a placeholder (session-1, account-1, ~/project-1) that is stable + * for a given log, so two runs over the same file can be compared. */ 'use strict'; @@ -93,6 +102,110 @@ const groupBy = (records, keyOf) => { .map(([key, rs]) => ({ key, n: rs.length, steps: stepStats(rs) })); }; +const UNKNOWN = '(unknown)'; + +/** A record that names its session (version 2 on). */ +const namesSession = (r) => typeof r.sessionId === 'string' && r.sessionId !== ''; + +/** + * The account a record belongs to. A v2 record with no label is the anchor + * account (it carries none); a v1 record never said. + */ +const accountOf = (r) => + typeof r.account === 'string' && r.account ? r.account : namesSession(r) ? '(anchor)' : UNKNOWN; + +/** `tty×5 cwd×2`: how often each branch found the tab, most frequent first. */ +const branchMix = (records) => { + const counts = new Map(); + for (const r of records) { + const b = typeof r.branch === 'string' && r.branch ? r.branch : 'unknown'; + counts.set(b, (counts.get(b) || 0) + 1); + } + return [...counts.entries()] + .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) + .map(([b, n]) => `${b}×${n}`) + .join(' '); +}; + +const distinct = (values) => [...new Set(values.filter((v) => typeof v === 'string' && v))]; + +/** + * One row per session, from the records that name one. Title, account and + * project are the latest seen (a session can be renamed); terminals are + * every one it was switched to. + */ +const sessionRows = (records, sort = 'n') => { + const groups = new Map(); + for (const r of records) { + if (!namesSession(r)) continue; + if (!groups.has(r.sessionId)) groups.set(r.sessionId, []); + groups.get(r.sessionId).push(r); + } + const num = (xs) => xs.filter((v) => typeof v === 'number' && Number.isFinite(v)); + const rows = [...groups.entries()].map(([sessionId, rs]) => { + const last = (key) => { + for (let i = rs.length - 1; i >= 0; i--) { + if (typeof rs[i][key] === 'string' && rs[i][key]) return rs[i][key]; + } + return null; + }; + const totals = num(rs.map((r) => r.ms.total)); + const runs = num(rs.map((r) => r.ms.run)); + return { + sessionId, + title: last('title'), + account: accountOf(rs[rs.length - 1]), + project: last('project'), + terminals: distinct(rs.map((r) => r.terminal)), + ttys: distinct(rs.map((r) => r.tty)), + n: rs.length, + totalP50: percentile(totals, 50), + totalP90: percentile(totals, 90), + runP50: percentile(runs, 50), + runP90: percentile(runs, 90), + branches: branchMix(rs), + }; + }); + const byN = (a, b) => b.n - a.n || (b.totalP90 ?? -1) - (a.totalP90 ?? -1); + const byP90 = (a, b) => (b.totalP90 ?? -1) - (a.totalP90 ?? -1) || b.n - a.n; + return rows.sort(sort === 'p90' ? byP90 : byN); +}; + +/** + * The same records with every session id, title, account label and project + * path replaced by a placeholder. Numbered in order of first appearance, so + * the same log always gives the same names, and one session, account or + * path keeps one name across all its lines. A missing value stays missing: + * "this session had no title" is a finding, not content. + */ +const redactRecords = (records) => { + const namer = (prefix) => { + const seen = new Map(); + return (v) => { + if (typeof v !== 'string' || v === '') return v ?? null; + if (!seen.has(v)) seen.set(v, `${prefix}${seen.size + 1}`); + return seen.get(v); + }; + }; + const session = namer('session-'); + const account = namer('account-'); + const project = namer('~/project-'); + return records.map((r) => { + const out = { ...r }; + if ('sessionId' in r) out.sessionId = session(r.sessionId); + if ('sid' in r) out.sid = typeof r.sid === 'string' && r.sid ? 'redacted' : r.sid; + if ('title' in r) { + out.title = + typeof r.title === 'string' && r.title + ? `title of ${namesSession(r) ? out.sessionId : 'a session'}` + : null; + } + if ('account' in r) out.account = account(r.account); + if ('project' in r) out.project = project(r.project); + return out; + }); +}; + /** 1-minute load per core: comparable across machines. */ const loadPerCore = (r) => Array.isArray(r.load) && typeof r.load[0] === 'number' && typeof r.ncpu === 'number' && r.ncpu > 0 @@ -106,7 +219,7 @@ const LOAD_BUCKETS = [ { label: 'load/core ≥ 2', lo: 2, hi: Infinity }, ]; -const summarize = (records) => { +const summarize = (records, opts = {}) => { const total = (r) => r.ms.total; // Of each switch's total, the part spent inside the external command. const runShare = records @@ -121,6 +234,9 @@ const summarize = (records) => { byKind: groupBy(records, (r) => String(r.kind ?? 'unknown')), byTerminal: groupBy(records, (r) => String(r.terminal ?? 'unknown')), byBranch: groupBy(records, (r) => String(r.branch ?? 'unknown')), + byAccount: groupBy(records, accountOf), + sessions: sessionRows(records, opts.sort), + unnamed: records.filter((r) => !namesSession(r)).length, runShareP50: percentile(runShare, 50), load: { buckets: LOAD_BUCKETS.map((b) => { @@ -152,13 +268,52 @@ const stepTable = (title, groups) => { return lines.join('\n'); }; -const formatReport = (summary, malformed = 0) => { +/** Sessions shown unless `--all`. */ +const SESSION_ROWS_DEFAULT = 20; + +const clip = (s, w) => (s.length > w ? `${s.slice(0, w - 1)}…` : s); + +const sessionTable = (s, opts) => { + const home = os.homedir(); + const shown = opts.all ? s.sessions : s.sessions.slice(0, SESSION_ROWS_DEFAULT); + const lines = [ + `By session (${shown.length} of ${s.sessions.length}, sorted by ${ + opts.sort === 'p90' ? 'p90 total' : 'switches' + }${s.unnamed ? `; ${s.unnamed} older record(s) do not name a session` : ''})`, + ]; + if (shown.length === 0) return lines.concat(' (no record names its session)').join('\n'); + lines.push( + ` ${pad('session', 10)}${padL('n', 4)} ${padL('total p50/p90', 14)} ${padL('run p50/p90', 12)} ${pad('terminal', 10)}${pad('account', 12)}${pad('branches', 24)}title · project`, + ); + for (const row of shown) { + const id = /^session-\d+$/.test(row.sessionId) ? row.sessionId : row.sessionId.slice(0, 8); + const project = row.project + ? row.project.startsWith(home) ? `~${row.project.slice(home.length)}` : row.project + : '—'; + lines.push( + ` ${pad(clip(id, 9), 10)}${padL(row.n, 4)} ${padL(`${fmt(row.totalP50)}/${fmt(row.totalP90)}`, 14)} ${padL( + `${fmt(row.runP50)}/${fmt(row.runP90)}`, + 12, + )} ${pad(clip(row.terminals.join(',') || '—', 9), 10)}${pad(clip(row.account, 11), 12)}${pad( + clip(row.branches, 23), + 24, + )}${clip(row.title || '(no title)', 40)} · ${project}`, + ); + } + if (shown.length < s.sessions.length) lines.push(' … --all lists every session'); + return lines.join('\n'); +}; + +const formatReport = (summary, malformed = 0, opts = {}) => { if (summary.count === 0) { return `No switch records${malformed ? ` (${malformed} malformed line(s) skipped)` : ''}.`; } const s = summary; const r = (v) => (v === null ? '— (too few records, or no variance)' : v.toFixed(2)); return [ + ...(opts.redact + ? ['Redacted: session ids, titles, account labels and project paths are placeholders.'] + : []), `${s.count} switches · ${s.slow} over 1 s · ${s.timedOut} timed out · ${s.failed} failed` + (malformed ? ` · ${malformed} malformed line(s) skipped` : ''), 'Cells are p50/p90 in ms. Steps: clickToIpc (renderer → main), settings, detect', @@ -173,6 +328,10 @@ const formatReport = (summary, malformed = 0) => { '', stepTable('By branch', s.byBranch), '', + stepTable('By account', s.byAccount), + '', + sessionTable(s, opts), + '', `Share of the total spent inside the external command (run / total), p50: ${ s.runShareP50 === null ? '—' : `${(s.runShareP50 * 100).toFixed(0)}%` }`, @@ -205,16 +364,49 @@ const readFiles = (files) => { return { text, missing }; }; +/** Flags and files from the command line; an unknown flag is an error, not a file name. */ +const parseArgs = (argv) => { + const opts = { redact: false, all: false, sort: 'n', files: [], bad: [] }; + for (const a of argv) { + if (a === '--redact') opts.redact = true; + else if (a === '--all') opts.all = true; + else if (a === '--sort=n' || a === '--sort=p90') opts.sort = a.slice('--sort='.length); + else if (a.startsWith('--')) opts.bad.push(a); + else opts.files.push(a); + } + return opts; +}; + const main = (argv) => { - const explicit = argv.length > 0; - const files = explicit ? argv : defaultFiles(); + const opts = parseArgs(argv); + if (opts.bad.length > 0) { + console.error(`unknown option: ${opts.bad.join(' ')}`); + console.error('usage: switch-timing-summary.js [--redact] [--all] [--sort=n|p90] [file ...]'); + process.exitCode = 2; + return; + } + const explicit = opts.files.length > 0; + const files = explicit ? opts.files : defaultFiles(); const { text, missing } = readFiles(files); // The rotated file is optional; only a file the user named is worth a note. if (explicit) for (const f of missing) console.error(`cannot read ${f}`); const { records, malformed } = parseLines(text); - console.log(formatReport(summarize(records), malformed)); + const shown = opts.redact ? redactRecords(records) : records; + console.log(formatReport(summarize(shown, opts), malformed, opts)); }; if (require.main === module) main(process.argv.slice(2)); -module.exports = { percentile, pearson, parseLines, summarize, formatReport, stepStats, STEPS }; +module.exports = { + percentile, + pearson, + parseLines, + summarize, + formatReport, + stepStats, + sessionRows, + branchMix, + redactRecords, + parseArgs, + STEPS, +}; diff --git a/src/main.ts b/src/main.ts index 35c287d..45f15e2 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2856,7 +2856,17 @@ ipcMain.on( } // Timing only (switch-timing.ts): undefined if it cannot start, and no // call on it can throw, so the switch below runs the same either way. - const timing = startSwitchTiming(sessionId, !!isActive, stamp); + const timing = startSwitchTiming( + { + sessionId, + active: !!isActive, + title: customTitle, + accountLabel, + projectPath, + pid: isActive ? activePid : null, + }, + stamp, + ); // Switching to a running session never needs the path (iTerm2 matches by // tty); a resume does — `cd ""` would start the session in the wrong place. if (!isActive && !projectPath) { diff --git a/src/switch-timing-log.ts b/src/switch-timing-log.ts index ef52219..eafa303 100644 --- a/src/switch-timing-log.ts +++ b/src/switch-timing-log.ts @@ -3,6 +3,9 @@ * is measured and why): start a collector when a switch's IPC arrives, and * when the switch is over, sample the machine and append one JSON line to * `~/.config/codev/switch-timing.jsonl`, beside the marks and lists stores. + * The line names the session (id, title, account, project path, pid, tty), + * so the file is created owner-only; it never holds prompts or transcript + * text. * * On the switch's path this costs one `os.cpus()` read, one * `process.cpuUsage()` and a few clock reads. Everything that spawns or @@ -24,10 +27,13 @@ import { createSwitchTiming, isSlowSwitch, parseTopCpu, + parseTty, + pidOrNull, sanitizeStamp, shouldRotate, stepDurations, SWITCH_LOG_MAX_BYTES, + SwitchContext, SwitchSnapshot, SwitchSystemSample, SwitchTiming, @@ -43,14 +49,25 @@ export const defaultSwitchLogPath = (): string => // The Sessions tab asks main for a live-sessions report (a `ps`) each time // the window opens. Remembering that report's size gives every switch a // process count without a `ps` of its own; the age says how stale it is. -let lastLive: { count: number; at: number } | null = null; +// The same report lists each process's tty, which saves the record a `ps` +// for the session it switched to. +let lastLive: { count: number; at: number; ttys: Map } | null = null; export const noteLiveReport = ( - report: { live?: unknown[]; measuredAt?: number } | null | undefined, + report: + | { live?: { pid?: number; tty?: string | null }[]; measuredAt?: number } + | null + | undefined, ): void => { try { if (report && Array.isArray(report.live)) { - lastLive = { count: report.live.length, at: Date.now() }; + const ttys = new Map(); + for (const p of report.live) { + if (p && typeof p.pid === 'number' && typeof p.tty === 'string' && p.tty) { + ttys.set(p.pid, p.tty); + } + } + lastLive = { count: report.live.length, at: Date.now(), ttys }; } } catch { // Not worth a failed report. @@ -113,6 +130,8 @@ export interface SwitchLogDeps { sysctl?: () => Promise; /** `ps -A -o %cpu=,comm=`; empty on failure. */ psTop?: () => Promise; + /** `ps -o tty= -p `; empty on failure. */ + psTty?: (pid: number) => Promise; maxBytes?: number; /** Called after the line is written (or dropped). For tests. */ onWritten?: (record: Record | null) => void; @@ -125,8 +144,7 @@ export interface SwitchLogDeps { * caller uses `timing?.…`, so the switch then runs untimed. */ export const startSwitchTiming = ( - sessionId: string, - active: boolean, + session: Omit, rawStamp: unknown, deps: SwitchLogDeps = {}, ): SwitchTiming | undefined => { @@ -138,7 +156,8 @@ export const startSwitchTiming = ( const stamp = sanitizeStamp(rawStamp); const cpusBefore = os.cpus(); const cpuUsageBefore = process.cpuUsage(); - const ctx = { ts: new Date(ipc.wallMs).toISOString(), sessionId, active }; + const ctx: SwitchContext = { ...session, ts: new Date(ipc.wallMs).toISOString() }; + const pid = pidOrNull(session.pid); const onFinish = (snap: SwitchSnapshot) => { // The samples that describe the span are taken at its end, at once; @@ -168,12 +187,22 @@ export const startSwitchTiming = ( (() => run('sysctl', ['-n', 'vm.swapusage', 'kern.memorystatus_vm_pressure_level'], 2000)); const psTop = deps.psTop ?? (() => run('ps', ['-A', '-o', '%cpu=,comm='], 3000)); - const [sysctlOut, psOut] = await Promise.all([ + // The tty the last live-sessions report gave this pid, when it has + // one; otherwise one `ps`, here, after the switch. + const knownTty = pid !== null ? lastLive?.ttys.get(pid) ?? null : null; + const psTty = + deps.psTty ?? + ((p: number) => run('ps', ['-o', 'tty=', '-p', String(p)], 1000)); + const [sysctlOut, psOut, ttyOut] = await Promise.all([ sysctl().catch(() => ''), isSlowSwitch(ms) ? psTop().catch(() => '') : Promise.resolve(null), + pid !== null && !knownTty ? psTty(pid).catch(() => '') : Promise.resolve(null), ]); + const tty = knownTty ?? parseTty(ttyOut); const full: SwitchSystemSample = { ...sys, + tty, + ttySrc: tty ? (knownTty ? 'live-report' : 'ps') : null, memory: parseMemoryPressure(sysctlOut), ...(psOut !== null ? { top: parseTopCpu(psOut) } : {}), }; diff --git a/src/switch-timing.test.ts b/src/switch-timing.test.ts index a63ad97..fa681ba 100644 --- a/src/switch-timing.test.ts +++ b/src/switch-timing.test.ts @@ -10,6 +10,7 @@ import { createSwitchTiming, isSlowSwitch, parseTopCpu, + parseTty, sanitizeStamp, shouldRotate, stepDurations, @@ -330,20 +331,34 @@ describe('the log file', () => { ]); }); + const SESSION = { + sessionId: '0f1e2d3c-aaaa-bbbb-cccc-123456789abc', + active: true, + title: 'an example title', + accountLabel: 'second', + projectPath: '/Users/someone/code/example', + pid: 4242, + }; + const runSwitch = ( stamp: unknown, - deps: { sysctl?: () => Promise; psTop?: () => Promise } = {}, + deps: { + sysctl?: () => Promise; + psTop?: () => Promise; + psTty?: (pid: number) => Promise; + } = {}, + session: Parameters[0] = SESSION, ) => new Promise | null>((resolve) => { const timing = startSwitchTiming( - '0f1e2d3c-aaaa-bbbb-cccc-123456789abc', - true, + session, stamp, { filePath: file, sysctl: async () => 'total = 2048.00M used = 512.50M free = 1535.50M (encrypted)\n2\n', psTop: async () => ' 91.0 /usr/libexec/somed\n 1.0 /bin/zsh\n', + psTty: async () => 'ttys007\n', ...deps, onWritten: resolve, }, @@ -356,7 +371,7 @@ describe('the log file', () => { timing.exited('found-by-title\n'); }); - it('writes one line per switch, with no trace of the session beyond an id prefix', async () => { + it('writes one line per switch, naming the session it was', async () => { noteLiveReport({ live: [{}, {}, {}] }); let psCalls = 0; const record = await runSwitch( @@ -373,8 +388,14 @@ describe('the log file', () => { const onDisk = JSON.parse(lines[0]); expect(onDisk).toEqual(record); expect(onDisk).toMatchObject({ - v: 1, - sid: '0f1e2d3c', + v: 2, + sessionId: '0f1e2d3c-aaaa-bbbb-cccc-123456789abc', + title: 'an example title', + account: 'second', + project: '/Users/someone/code/example', + pid: 4242, + tty: 'ttys007', + ttySrc: 'ps', via: 'click', kind: 'switch', terminal: 'ghostty', @@ -388,7 +409,9 @@ describe('the log file', () => { claudeProcs: 3, rows: 42, }); - expect(lines[0]).not.toContain('aaaa-bbbb'); + expect('sid' in onDisk).toBe(false); + // Owner-only: the line names a session, a title and a path. + expect(fs.statSync(file).mode & 0o777).toBe(0o600); expect(onDisk.ms.total).toBeGreaterThanOrEqual(0); expect(onDisk.load).toHaveLength(3); expect(onDisk.ncpu).toBe(os.cpus().length); @@ -411,6 +434,64 @@ describe('the log file', () => { ]); }); + it('takes the tty from the last live-sessions report instead of spawning ps', async () => { + noteLiveReport({ + live: [ + { pid: 4242, tty: 'ttys011' }, + { pid: 77, tty: null }, + ], + }); + let psCalls = 0; + const psTty = async () => { + psCalls++; + return 'ttys099\n'; + }; + const known = await runSwitch(undefined, { psTty }); + expect(known).toMatchObject({ pid: 4242, tty: 'ttys011', ttySrc: 'live-report' }); + expect(psCalls).toBe(0); + // A pid the report listed without a tty still gets the one lookup. + const unknown = await runSwitch(undefined, { psTty }, { ...SESSION, pid: 77 }); + expect(unknown).toMatchObject({ pid: 77, tty: 'ttys099', ttySrc: 'ps' }); + expect(psCalls).toBe(1); + }); + + it('records a resume with no pid, no tty and no lookup; missing optionals are null', async () => { + let psCalls = 0; + const record = await runSwitch( + undefined, + { + psTty: async () => { + psCalls++; + return 'ttys001'; + }, + }, + { sessionId: 'abc', active: false, pid: null }, + ); + expect(record).toMatchObject({ + v: 2, + kind: 'resume', + sessionId: 'abc', + title: null, + account: null, + project: null, + pid: null, + tty: null, + ttySrc: null, + }); + expect(psCalls).toBe(0); + }); + + it('records a null tty when the lookup fails or the process has none', async () => { + const failed = await runSwitch(undefined, { + psTty: async () => { + throw new Error('ps failed'); + }, + }); + expect(failed).toMatchObject({ pid: 4242, tty: null, ttySrc: null }); + const none = await runSwitch(undefined, { psTty: async () => '??\n' }); + expect(none).toMatchObject({ tty: null, ttySrc: null }); + }); + it('still writes the record when sysctl and the live count are unavailable', async () => { const record = await runSwitch(undefined, { sysctl: async () => { @@ -429,7 +510,48 @@ describe('the log file', () => { }); }); +describe('parseTty', () => { + it('reads a tty and treats every kind of absence as null', () => { + expect(parseTty('ttys004\n')).toBe('ttys004'); + expect(parseTty('??\n')).toBeNull(); // no controlling terminal + expect(parseTty('')).toBeNull(); // the process is gone + expect(parseTty(null)).toBeNull(); + expect(parseTty('ps: illegal option -- x')).toBeNull(); + }); +}); + describe('buildSwitchRecord', () => { + it('drops values of the wrong shape and cuts an overlong title', () => { + const snap: SwitchSnapshot = { + marks: {}, + spawnedAt: null, + exitedAt: null, + endedAt: 1, + facts: {}, + ok: true, + timedOut: false, + }; + const ms = stepDurations(snap, undefined, { wallMs: 0, perfEpochMs: 0 }); + const r = buildSwitchRecord( + { + ts: '2026-01-02T03:04:05.000Z', + sessionId: 'id-1', + active: true, + title: 't'.repeat(500), + accountLabel: 42 as unknown as string, + projectPath: '', + pid: 12.5, + }, + undefined, + snap, + ms, + // A source without a tty is not a source. + { tty: null, ttySrc: 'ps' }, + ); + expect((r.title as string).length).toBe(200); + expect(r).toMatchObject({ account: null, project: null, pid: null, tty: null, ttySrc: null }); + }); + it('marks a resume and keeps unknowns as null rather than guessing', () => { const snap: SwitchSnapshot = { marks: { returned: 5 }, @@ -449,7 +571,8 @@ describe('buildSwitchRecord', () => { { mainCpuMicros: { user: 12345, system: 678 } }, ); expect(r).toMatchObject({ - sid: 'abcdefgh', + sessionId: 'abcdefghijkl', + title: null, kind: 'resume', terminal: null, branch: null, @@ -516,6 +639,131 @@ describe('scripts/switch-timing-summary.js', () => { expect(report).toContain('3 malformed line(s) skipped'); }); + // Two v2 sessions and one v1 line, as a log that spans the version change. + const mixed = () => { + const v2 = ( + sessionId: string, + title: string | null, + account: string | null, + project: string, + branch: string, + total: number, + ) => ({ + v: 2, + kind: 'switch', + terminal: 'iterm2', + sessionId, + title, + account, + project, + pid: 1, + tty: 'ttys001', + branch, + ms: { run: total - 20, total }, + }); + return [ + { v: 1, sid: 'deadbeef', kind: 'switch', terminal: 'ghostty', branch: 'cwd', ms: { run: 50, total: 60 } }, + v2('aaaa1111-0000', 'first title', 'second', '/home/u/code/alpha', 'tty', 100), + v2('bbbb2222-0000', null, null, '/home/u/code/beta', 'cwd', 2000), + v2('aaaa1111-0000', 'renamed title', 'second', '/home/u/code/alpha', 'tty', 300), + v2('aaaa1111-0000', 'renamed title', 'second', '/home/u/code/alpha', 'cwd', 200), + ]; + }; + + it('groups per session from v2 lines and keeps v1 lines in every other grouping', () => { + const s = summary.summarize(mixed()); + expect(s.count).toBe(5); + expect(s.unnamed).toBe(1); + expect(s.sessions).toHaveLength(2); + expect(s.sessions[0]).toMatchObject({ + sessionId: 'aaaa1111-0000', + title: 'renamed title', // the latest one + account: 'second', + project: '/home/u/code/alpha', + terminals: ['iterm2'], + n: 3, + totalP50: 200, + totalP90: 280, + runP50: 180, + branches: 'tty×2 cwd×1', + }); + expect(s.sessions[1]).toMatchObject({ sessionId: 'bbbb2222-0000', title: null, account: '(anchor)', n: 1 }); + // The v1 line has no account: unknown, which is not the anchor. + expect(s.byAccount.map((g: { key: string; n: number }) => [g.key, g.n])).toEqual([ + ['second', 3], + ['(unknown)', 1], + ['(anchor)', 1], + ]); + expect(s.byTerminal.find((g: { key: string }) => g.key === 'ghostty').n).toBe(1); + const report = summary.formatReport(s); + expect(report).toContain('By session (2 of 2, sorted by switches; 1 older record(s) do not name a session)'); + expect(report).toContain('(no title)'); + }); + + it('sorts sessions by p90 total on request, and caps the table unless --all', () => { + const byP90 = summary.summarize(mixed(), { sort: 'p90' }); + expect(byP90.sessions.map((r: { sessionId: string }) => r.sessionId)).toEqual([ + 'bbbb2222-0000', + 'aaaa1111-0000', + ]); + const many = Array.from({ length: 25 }, (_, i) => ({ + v: 2, + sessionId: `id-${String(i).padStart(2, '0')}`, + terminal: 'iterm2', + branch: 'tty', + ms: { total: i }, + })); + const s = summary.summarize(many); + const capped = summary.formatReport(s, 0, {}); + expect(capped).toContain('By session (20 of 25'); + expect(capped).toContain('--all lists every session'); + expect(summary.formatReport(s, 0, { all: true })).toContain('By session (25 of 25'); + }); + + it('redacts ids, titles, accounts and paths to placeholders that are stable for a log', () => { + const once = summary.redactRecords(mixed()); + expect(once).toEqual(summary.redactRecords(mixed())); // same log, same names + expect(once.map((r: { sessionId?: string }) => r.sessionId)).toEqual([ + undefined, + 'session-1', + 'session-2', + 'session-1', + 'session-1', + ]); + expect(once[1]).toMatchObject({ + title: 'title of session-1', + account: 'account-1', + project: '~/project-1', + tty: 'ttys001', + branch: 'tty', + ms: { total: 100 }, + }); + // One session keeps one name through a rename; "no title" stays visible. + expect(once[3].title).toBe('title of session-1'); + expect(once[2]).toMatchObject({ title: null, account: null, project: '~/project-2' }); + expect(once[0].sid).toBe('redacted'); + const report = summary.formatReport(summary.summarize(once), 0, { redact: true }); + for (const secret of ['aaaa1111', 'bbbb2222', 'deadbeef', 'renamed', 'first title', 'alpha', 'beta', 'second']) { + expect(report).not.toContain(secret); + } + expect(report).toContain('Redacted:'); + expect(report).toContain('session-1'); + expect(report).toContain('~/project-2'); + // Same grouping as the unredacted log: redaction renames, it does not merge. + expect(summary.summarize(once).sessions.map((r: { n: number }) => r.n)).toEqual([3, 1]); + }); + + it('parses flags apart from files and rejects an unknown one', () => { + expect(summary.parseArgs(['--redact', 'a.jsonl', '--sort=p90', '--all'])).toMatchObject({ + redact: true, + all: true, + sort: 'p90', + files: ['a.jsonl'], + bad: [], + }); + expect(summary.parseArgs(['--redacted']).bad).toEqual(['--redacted']); + }); + it('reports an empty log instead of failing', () => { const { records, malformed } = summary.parseLines(''); expect(summary.formatReport(summary.summarize(records), malformed)).toBe('No switch records.'); diff --git a/src/switch-timing.ts b/src/switch-timing.ts index c895810..ae7ea23 100644 --- a/src/switch-timing.ts +++ b/src/switch-timing.ts @@ -14,9 +14,14 @@ * - **Nothing here throws into a switch.** Every collector method swallows * its own errors, and every call site uses `timing?.…`, so a switch with * no collector, or with a broken one, runs exactly as it did before. - * - **A record holds timings and counts, never content**: no title, prompt - * or path. The only trace of the session is the first 8 characters of its - * id, enough to tell two switches to one session from two sessions. + * - **A record says which session it was, and nothing a session said.** + * It holds the session id, its title, account label, project path, pid + * and tty, so that per-session patterns show (one crowded window, one + * account, a session that always falls back to cwd). Prompts and + * transcript text are never recorded. The log stays on this machine in an + * owner-only (0600) file; titles and paths are the owner's, so results + * quoted anywhere public should carry placeholders instead (the summary + * script's `--redact`). */ /** Points on the path, in the order a terminal switch passes them. */ @@ -334,6 +339,9 @@ export interface SwitchSystemSample { liveAgeMs?: number | null; /** Only for a slow switch: the busiest processes right after it. */ top?: { cpu: number; comm: string }[]; + /** The target process's controlling terminal, and where the value came from. */ + tty?: string | null; + ttySrc?: 'live-report' | 'ps' | null; } export interface SwitchContext { @@ -341,8 +349,34 @@ export interface SwitchContext { ts: string; sessionId: string; active: boolean; + /** The session's `/rename` title, as the click carried it. */ + title?: string | null; + /** The account label the row carried; none for the anchor account. */ + accountLabel?: string | null; + projectPath?: string | null; + /** The process switched to; none for a resume. */ + pid?: number | null; } +/** A title is one line of the user's own text; anything longer is cut. */ +export const SWITCH_TITLE_MAX = 200; + +const textOrNull = (v: unknown, max = 4096): string | null => + typeof v === 'string' && v !== '' ? v.slice(0, max) : null; + +/** A usable pid, else null: the value crossed an IPC boundary. */ +export const pidOrNull = (v: unknown): number | null => + typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : null; + +/** + * The tty from `ps -o tty= -p `: `ttys004`, or null when the process + * has none (`??`), is gone (empty output), or `ps` failed. + */ +export const parseTty = (psOut: string | null | undefined): string | null => { + const t = (psOut || '').trim(); + return t && t !== '??' && /^[\w/.-]+$/.test(t) ? t : null; +}; + /** * The stamp crosses an IPC boundary, so it is checked rather than trusted: * anything not shaped like one is dropped, and the record simply has no @@ -361,7 +395,12 @@ export const sanitizeStamp = (raw: unknown): RendererStamp | undefined => { }; }; -export const SWITCH_RECORD_VERSION = 1; +/** + * 2: the record names its session (`sessionId`, `title`, `account`, + * `project`, `pid`, `tty`, `ttySrc`); version 1 had only `sid`, the first 8 + * characters of the id. + */ +export const SWITCH_RECORD_VERSION = 2; /** A switch slower than this also records the busiest processes. */ export const SLOW_SWITCH_MS = 1000; @@ -378,7 +417,13 @@ export const buildSwitchRecord = ( ): Record => ({ v: SWITCH_RECORD_VERSION, ts: ctx.ts, - sid: String(ctx.sessionId || '').slice(0, 8), + sessionId: textOrNull(ctx.sessionId, 128), + title: textOrNull(ctx.title, SWITCH_TITLE_MAX), + account: textOrNull(ctx.accountLabel, 128), + project: textOrNull(ctx.projectPath), + pid: pidOrNull(ctx.pid), + tty: sys.tty ?? null, + ttySrc: sys.tty ? sys.ttySrc ?? null : null, via: stamp?.via ?? null, kind: ctx.active ? 'switch' : 'resume', terminal: snap.facts.terminal ?? snap.facts.configured ?? null, diff --git a/src/switcher-ui.tsx b/src/switcher-ui.tsx index 9a0dfa0..0a0a9ec 100644 --- a/src/switcher-ui.tsx +++ b/src/switcher-ui.tsx @@ -352,7 +352,8 @@ export function deleteVSCodeBasedIDESqliteRecord(path: string) { // When a switch was asked for, for main's switch timing log (switch-timing.ts): // the wall clock, and this process's high-resolution clock as epoch ms so main -// can subtract its own. Counts only — nothing about the session. +// can subtract its own. The stamp itself carries a time and a row count; +// which session it was, main already knows from the call's other arguments. const switchStamp = (via: 'enter' | 'click', rows: number) => ({ wallMs: Date.now(), perfEpochMs: performance.timeOrigin + performance.now(), From f8b5e47bae2b161898789688774d5e8007c18110 Mon Sep 17 00:00:00 2001 From: Grimmer Kang Date: Fri, 20 Nov 2026 22:28:47 +0900 Subject: [PATCH 4/7] fix(sessions): switch timing log, review round 1 Twelve findings from the first review of the log, all confirmed against the code. Log: - A timed-out switch now gets the busiest-processes sample: it is the hung-command case the sample exists for, and it has no total to compare. Its run, main and total stay null (the 15 s deadline is not a duration); the steps before it and `returned` are kept. The unreachable `endedAt` fallback is gone. - The log and its rotated copy are set to 0600 on every append, not only when created, so a looser file from an earlier build is fixed and rotation cannot carry its mode to `.1`. - `account` is the label main validated, the one the launch is given, not the renderer's raw value. It has one source (the facts). - Time zero is read before the timing code's own setup. - The title cap cuts by code point, not UTF-16 unit. Summary script: - Every printed value passes through one helper that removes control characters (C0, DEL, C1, line separators, bidi overrides). - One table renderer with columns as wide as their content: redacted placeholders past session-9 are no longer clipped into one label, and real id labels grow until unique. - A cell says `(k)` when its percentile covers fewer records than n. - Timed-out switches are excluded from run, main and total. - A record without an account is `(none)`: every account has a label, the anchor included, so it was never "(anchor)". - `~` only at a path boundary; clipping by code point. Wording: a title can be the one Claude Code generated, a model-written summary of the conversation. The docs, changelog and headers now say so, and that the prompts and transcript text themselves are not recorded. Docs also fix the `mainCpuMs` shape and tell the two `ps` calls apart. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- docs/claude-session-integration-design.md | 33 ++- scripts/switch-timing-summary.js | 271 ++++++++++++++++------ src/main.ts | 5 +- src/switch-timing-log.ts | 47 +++- src/switch-timing.test.ts | 264 ++++++++++++++++++++- src/switch-timing.ts | 77 ++++-- 7 files changed, 575 insertions(+), 124 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fda485..8166e25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 1.0.97 -- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s, the three busiest processes). **Each line names its session** — the session id, title, account label, project path, the pid switched to and its tty — so per-session patterns show (a crowded window, one account, a session that always falls back to cwd); **prompts and transcript text are not recorded**. The file is local and owner-only (0600); when quoting results in public, replace titles and paths with placeholders — `yarn switch-timing --redact` does it. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch, and a failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal, branch and account, a per-session table (`--all`, `--sort=p90`), and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" +- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s or one whose command never reported back, the three busiest processes). **Each line names its session** — the session id, title, account label, project path, the pid switched to and its tty — so per-session patterns show (a crowded window, one account, a session that always falls back to cwd); the title is the `/rename` name or, without one, the title Claude Code generated, which is a model-written summary of the conversation; **the prompts and the transcript text themselves are not recorded**. The file is local and kept owner-only (0600, set again on every write, the rotated copy included); when quoting results in public, replace titles and paths with placeholders — `yarn switch-timing --redact` does it. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch, and a failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal, branch and account, a per-session table (`--all`, `--sort=p90`), and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" ## 1.0.94 diff --git a/docs/claude-session-integration-design.md b/docs/claude-session-integration-design.md index 456e03f..56b29f5 100644 --- a/docs/claude-session-integration-design.md +++ b/docs/claude-session-integration-design.md @@ -669,7 +669,7 @@ TypeScript is sufficient for MVP. `history.jsonl` reading (~40ms) and session li Before rewriting any part of the switch path for speed, measure where a switch spends its time. Since 1.0.97 every switch started from the Sessions tab (Enter or a click) appends one JSON line to `~/.config/codev/switch-timing.jsonl`. The question it is meant to answer: is the time in CodeV's own JavaScript, which a rewrite could shorten, or in the external command (`osascript`, or the cmux CLI) and a loaded machine, which it could not? -**What a line holds: timings, counts, and which session it was.** Each line names its session — the session id, its title, account label, project path, the pid switched to and that process's tty — so that per-session patterns show up: one crowded terminal window, one account, a session that always falls back to cwd. **Prompts and transcript text are not recorded.** The file stays on this machine and is created owner-only (mode 0600), like the stores beside it. Titles and paths are the owner's own words and directories, so anyone quoting results in public (an issue, a pull request) should replace them with placeholders; the summary script's `--redact` does that. The file is capped at about 1 MB: at the cap it is renamed to `switch-timing.jsonl.1` (one old file is kept) and a new one starts. Logging is always on; there is no setting. +**What a line holds: timings, counts, and which session it was.** Each line names its session — the session id, its title, account label, project path, the pid switched to and that process's tty — so that per-session patterns show up: one crowded terminal window, one account, a session that always falls back to cwd. **The title is the one the Sessions tab shows for the row**: the name the user gave with `/rename`, or, for a session never renamed, the title Claude Code generated — a few words written by the model that summarize the conversation. So a line can carry a summary of what a session was about. **The prompts and the transcript text themselves are not recorded.** The file stays on this machine and is kept owner-only (mode 0600), like the stores beside it: the mode is set again on every write, on the log and on its rotated copy, so a file that was created looser does not stay that way. Titles and paths describe the owner's work, so anyone quoting results in public (an issue, a pull request) should replace them with placeholders; the summary script's `--redact` does that. The file is capped at about 1 MB: at the cap it is renamed to `switch-timing.jsonl.1` (one old file is kept) and a new one starts. Logging is always on; there is no setting. ``` renderer main process terminal @@ -683,18 +683,24 @@ Before rewriting any part of the switch path for speed, measure where a switch s ⑥ file written, command started (ms.spawn) └──────────────────────────────────► osascript runs ⑦ command exits (ms.run) ◄────────── prints the branch - ⑧ afterwards: sysctl, ps (slow switches only), append the line + ⑧ afterwards, off the switch's path: + ⑧a sysctl memory pressure and swap — every switch + ⑧b ps -o tty= -p PID the tty — only when the last + live-sessions report did not list the pid + ⑧c ps -A (%CPU) the three busiest processes — only when + the switch took over 1 s or timed out + ⑧d append the line ``` -Steps ① to ⑦ are the switch. Step ⑧ runs only after it, so nothing that spawns a process or touches the disk for the log sits on the switch's path; what the log adds to the path itself is one `os.cpus()` read, one `process.cpuUsage()` and a few clock reads. Any failure in the timing code is swallowed and the switch runs as before. +Steps ① to ⑦ are the switch. The two `ps` calls in step ⑧ are different commands with different conditions (⑧b looks up one process's tty, ⑧c lists every process's CPU share); a fast switch to a session the live report already knows runs neither. Step ⑧ runs only after the switch, so nothing that spawns a process or touches the disk for the log sits on the switch's path; what the log adds to the path itself is one `os.cpus()` read, one `process.cpuUsage()` and a few clock reads. Any failure in the timing code is swallowed and the switch runs as before. | Field | Meaning | |---|---| | `v` | Record version. 2 names the session (the six fields below); version 1 lines, written by the first build of this log, carry only `sid`, the first 8 characters of the id. | | `ts` | ISO time the IPC arrived in the main process. | | `sessionId` | The full session id. | -| `title` | The session's `/rename` title when the switch was started; `null` when it has none. | -| `account` | The account label the row carried; `null` for the anchor account. | +| `title` | The row's title when the switch was started: the `/rename` name, else the title Claude Code generated (a model-written summary of the conversation); `null` when the session has neither. Cut at 200 characters. | +| `account` | The row's account label, after the main process has checked that an account with that label exists — the same value the launch is given. Every account has a label, the anchor included. `null` means the row carried no label, or one that no account has any more; it does not mean the anchor. | | `project` | The session's project path. | | `pid` | The process switched to; `null` for a resume, which has none yet. | | `tty`, `ttySrc` | That process's controlling terminal (for example `ttys004`), and where the value came from: `live-report` (the last live-sessions report already listed it) or `ps` (one `ps -o tty= -p `, run after the switch). `null` when there is no pid, the process has no tty, or the lookup failed. | @@ -704,18 +710,18 @@ Steps ① to ⑦ are the switch. Step ⑧ runs only after it, so nothing that sp | `tool` | What ran the switch: `osascript`, `cmux-cli`, `open` (VS Code, Claude Desktop) or `pty` (the embedded terminal). | | `branch` | Which key found the tab: `tty`, `title`, `cwd`, `project-name` (cmux), `none` (the script ran and matched nothing); for a resume `new-tab`, `new-window` or `new-workspace`; `deep-link`, `embedded`. `null` means unknown, for example a script that failed. | | `order`, `hasTitle` | Which key the script tried first (`tty-first` or `title-first`), and whether it had a title block at all. | -| `ok`, `timedOut` | `ok` is false when the launch was rejected; `timedOut` is true when the command had not reported an exit after 15 s (then `ms.run` and `ms.total` are `null`). | +| `ok`, `timedOut` | `ok` is false when the launch was rejected. `timedOut` is true when the command had not reported an exit after 15 s. The record then says only what was measured: `ms.run`, `ms.main` and `ms.total` are `null` (15 s is when the record was closed, not how long anything took), the earlier steps and `ms.returned` are kept, and `top` is recorded as for a slow switch. | | `ms.clickToIpc`, `ms.clickToIpcHr` | ① to ②, on the wall clock (whole ms) and on the two processes' high-resolution clocks. | | `ms.settings`, `ms.detect`, `ms.build`, `ms.spawn`, `ms.run` | The steps in the diagram. A step a path skips is `null`, and its time counts in the next one. | | `ms.returned` | ② to `openSession` returning. For a running session this is before the script exits. | -| `ms.main`, `ms.total` | ② to ⑦, and ① to ⑦ (what the user waited). | +| `ms.main`, `ms.total` | ② to ⑦, and ① to ⑦ (what the user waited). On a path that runs no command (VS Code, Claude Desktop, the embedded terminal) the end is `openSession` returning. Time zero for every `ms` value except the two `clickToIpc` ones is the first thing the handler does, before the timing code's own setup, so that setup is inside `ms.settings` and `ms.main`. | | `load`, `ncpu` | `os.loadavg()` at the end of the switch, and the core count. | | `cpuPct` | Whole-machine CPU busy % over the span, from two `os.cpus()` samples. `null` for a span too short to measure (the counters tick every 10 ms). | -| `mainCpuMs` | CPU time CodeV's main process itself used over the span (`process.cpuUsage()` delta). | +| `mainCpuMs` | An object, `{ "user": …, "system": … }`: the CPU time in ms that CodeV's main process itself used over the span, in user mode and in system mode (`process.cpuUsage()` delta). | | `mem` | macOS memory-pressure level (1 normal, 2 warn, 4 critical) and swap in MB — the same `sysctl` reading as the memory chip, taken after the switch. | | `claudeProcs`, `liveAgeMs` | Running `claude` processes in the last live-sessions report the window asked for, and how old that report was. No extra `ps` is run for it. | | `rows` | Rows in the session list when the switch was started. | -| `top` | Only when `ms.total` is over 1 s: the three busiest processes (`%CPU`, executable name) right after the switch. | +| `top` | Only when `ms.total` is over 1 s, or the switch timed out: the three busiest processes (`%CPU`, executable name) right after it. | The branch costs nothing to record: the switch scripts already end in `return "found-by-tty"` and the like, and `osascript` prints that value. cmux matches in JavaScript, so each layer names itself. No script and no matching order changed. @@ -736,7 +742,14 @@ It prints p50/p90 (50th and 90th percentile) per step and for the total — for | `--all` | Lists every session; the default is the first 20. | | `--sort=p90` | Sorts sessions by p90 total, slowest first; the default, `--sort=n`, is by number of switches. | -Malformed lines are counted and skipped; a missing or empty log prints "No switch records." Version 1 lines still count in every grouping except the per-session table (they do not name a session), and fall under `(unknown)` in the account table. +How to read the tables: + +- **`n` is the number of records in the row; a cell ending in `(k)` covers only `k` of them.** Not every record has every step: a resume has no `detect`, and a timed-out switch has no `run`, `main` or `total`. Timed-out switches are counted in the first line of the report and are never part of those three percentiles. +- **Accounts.** `(none)` is a record whose row had no account label; `(unknown)` is a version 1 line, which did not record one. +- **Session labels** are the first 8 characters of the id, or more when two sessions would otherwise share a label. Under `--redact` they are the placeholders, never shortened. Only the title is cut (40 characters). +- **Control characters are removed from everything printed**, with or without `--redact`: a title is free text, and an escape sequence or a line break in one could otherwise drive the terminal or forge a row. + +Malformed lines are counted and skipped; a missing or empty log prints "No switch records." Version 1 lines still count in every grouping except the per-session table (they do not name a session). ### `history.jsonl` vs `session-metadata.db` diff --git a/scripts/switch-timing-summary.js b/scripts/switch-timing-summary.js index e328b73..3ac6920 100644 --- a/scripts/switch-timing-summary.js +++ b/scripts/switch-timing-summary.js @@ -13,13 +13,21 @@ * first); then the total against machine load. Plain Node, no dependencies. * A line that is not a record is counted and skipped; a missing or empty * file is reported, not an error. Version 1 lines, which did not name their - * session, count everywhere except the per-session table. + * session, count everywhere except the per-session table. A switch whose + * command timed out is counted, and left out of the percentiles of the + * steps it never finished. * - * The log names sessions: id, title, account label and project path. That - * is the owner's own data on the owner's machine — but the output of this - * script gets pasted into issues. `--redact` replaces every one of those - * with a placeholder (session-1, account-1, ~/project-1) that is stable - * for a given log, so two runs over the same file can be compared. + * The log names sessions: id, title, account label and project path. A + * title is the user's `/rename` name or, without one, the summary of the + * conversation that Claude Code generated. That is the owner's own data on + * the owner's machine — but the output of this script gets pasted into + * issues. `--redact` replaces every one of those with a placeholder + * (session-1, account-1, ~/project-1) that is stable for a given log, so + * two runs over the same file can be compared. + * + * Everything printed that came from the log or the command line passes + * through `safeText` first: a title is free text, and a terminal obeys + * escape sequences. */ 'use strict'; @@ -30,12 +38,28 @@ const path = require('path'); /** Steps in path order; `total` is what the user waited. */ const STEPS = ['clickToIpc', 'settings', 'detect', 'build', 'spawn', 'run', 'main', 'total']; +/** Steps that end at the command's exit, which a timed-out switch never reached. */ +const NEEDS_EXIT = new Set(['run', 'main', 'total']); + +const isNum = (v) => typeof v === 'number' && Number.isFinite(v); + +/** + * One step of one record, or null when it has no measured value. A + * timed-out switch has none for the steps that end at the exit — whatever + * the line says: a deadline is not a duration. + */ +const stepValue = (r, step) => { + if (r.timedOut === true && NEEDS_EXIT.has(step)) return null; + const v = r.ms ? r.ms[step] : null; + return isNum(v) ? v : null; +}; + /** * The p-th percentile (0–100) by linear interpolation between the two * nearest ranks — the same definition as numpy's default. Null for no data. */ const percentile = (values, p) => { - const xs = values.filter((v) => typeof v === 'number' && Number.isFinite(v)).sort((a, b) => a - b); + const xs = values.filter(isNum).sort((a, b) => a - b); if (xs.length === 0) return null; const rank = (Math.min(100, Math.max(0, p)) / 100) * (xs.length - 1); const lo = Math.floor(rank); @@ -45,9 +69,7 @@ const percentile = (values, p) => { /** Pearson's r over the pairs where both values are numbers; null under 3 pairs or no variance. */ const pearson = (pairs) => { - const ps = pairs.filter( - ([x, y]) => typeof x === 'number' && Number.isFinite(x) && typeof y === 'number' && Number.isFinite(y), - ); + const ps = pairs.filter(([x, y]) => isNum(x) && isNum(y)); const n = ps.length; if (n < 3) return null; const mx = ps.reduce((s, [x]) => s + x, 0) / n; @@ -81,12 +103,15 @@ const parseLines = (text) => { return { records, malformed }; }; +/** `n` is how many records had the step: it can be fewer than the group. */ +const stat = (records, step) => { + const xs = records.map((r) => stepValue(r, step)).filter(isNum); + return { n: xs.length, p50: percentile(xs, 50), p90: percentile(xs, 90) }; +}; + const stepStats = (records) => { const out = {}; - for (const step of STEPS) { - const xs = records.map((r) => r.ms[step]).filter((v) => typeof v === 'number' && Number.isFinite(v)); - out[step] = { n: xs.length, p50: percentile(xs, 50), p90: percentile(xs, 90) }; - } + for (const step of STEPS) out[step] = stat(records, step); return out; }; @@ -103,16 +128,18 @@ const groupBy = (records, keyOf) => { }; const UNKNOWN = '(unknown)'; +const NO_ACCOUNT = '(none)'; /** A record that names its session (version 2 on). */ const namesSession = (r) => typeof r.sessionId === 'string' && r.sessionId !== ''; /** - * The account a record belongs to. A v2 record with no label is the anchor - * account (it carries none); a v1 record never said. + * The account a record carries. Every account has a label, the anchor + * included, so a v2 record without one is a row that had no account (or + * named one that no longer exists) — not the anchor. A v1 record never said. */ const accountOf = (r) => - typeof r.account === 'string' && r.account ? r.account : namesSession(r) ? '(anchor)' : UNKNOWN; + typeof r.account === 'string' && r.account ? r.account : namesSession(r) ? NO_ACCOUNT : UNKNOWN; /** `tty×5 cwd×2`: how often each branch found the tab, most frequent first. */ const branchMix = (records) => { @@ -141,7 +168,6 @@ const sessionRows = (records, sort = 'n') => { if (!groups.has(r.sessionId)) groups.set(r.sessionId, []); groups.get(r.sessionId).push(r); } - const num = (xs) => xs.filter((v) => typeof v === 'number' && Number.isFinite(v)); const rows = [...groups.entries()].map(([sessionId, rs]) => { const last = (key) => { for (let i = rs.length - 1; i >= 0; i--) { @@ -149,8 +175,8 @@ const sessionRows = (records, sort = 'n') => { } return null; }; - const totals = num(rs.map((r) => r.ms.total)); - const runs = num(rs.map((r) => r.ms.run)); + const total = stat(rs, 'total'); + const run = stat(rs, 'run'); return { sessionId, title: last('title'), @@ -159,10 +185,12 @@ const sessionRows = (records, sort = 'n') => { terminals: distinct(rs.map((r) => r.terminal)), ttys: distinct(rs.map((r) => r.tty)), n: rs.length, - totalP50: percentile(totals, 50), - totalP90: percentile(totals, 90), - runP50: percentile(runs, 50), - runP90: percentile(runs, 90), + totalN: total.n, + totalP50: total.p50, + totalP90: total.p90, + runN: run.n, + runP50: run.p50, + runP90: run.p90, branches: branchMix(rs), }; }); @@ -208,9 +236,7 @@ const redactRecords = (records) => { /** 1-minute load per core: comparable across machines. */ const loadPerCore = (r) => - Array.isArray(r.load) && typeof r.load[0] === 'number' && typeof r.ncpu === 'number' && r.ncpu > 0 - ? r.load[0] / r.ncpu - : null; + Array.isArray(r.load) && isNum(r.load[0]) && isNum(r.ncpu) && r.ncpu > 0 ? r.load[0] / r.ncpu : null; const LOAD_BUCKETS = [ { label: 'load/core < 0.5', lo: 0, hi: 0.5 }, @@ -220,16 +246,18 @@ const LOAD_BUCKETS = [ ]; const summarize = (records, opts = {}) => { - const total = (r) => r.ms.total; + const total = (r) => stepValue(r, 'total'); + const run = (r) => stepValue(r, 'run'); + const load1 = (r) => (Array.isArray(r.load) ? r.load[0] : null); // Of each switch's total, the part spent inside the external command. const runShare = records - .filter((r) => typeof r.ms.run === 'number' && typeof r.ms.total === 'number' && r.ms.total > 0) - .map((r) => r.ms.run / r.ms.total); + .filter((r) => isNum(run(r)) && isNum(total(r)) && total(r) > 0) + .map((r) => run(r) / total(r)); return { count: records.length, timedOut: records.filter((r) => r.timedOut === true).length, failed: records.filter((r) => r.ok === false).length, - slow: records.filter((r) => typeof r.ms.total === 'number' && r.ms.total > 1000).length, + slow: records.filter((r) => isNum(total(r)) && total(r) > 1000).length, all: stepStats(records), byKind: groupBy(records, (r) => String(r.kind ?? 'unknown')), byTerminal: groupBy(records, (r) => String(r.terminal ?? 'unknown')), @@ -244,37 +272,117 @@ const summarize = (records, opts = {}) => { const l = loadPerCore(r); return l !== null && l >= b.lo && l < b.hi; }); - const xs = rs.map(total); - return { label: b.label, n: rs.length, p50: percentile(xs, 50), p90: percentile(xs, 90) }; + // `records` is the bucket's size; `n` (from `stat`) is how many had a total. + return { label: b.label, records: rs.length, ...stat(rs, 'total') }; }), - rTotalVsLoad1: pearson(records.map((r) => [Array.isArray(r.load) ? r.load[0] : null, total(r)])), + rTotalVsLoad1: pearson(records.map((r) => [load1(r), total(r)])), rTotalVsCpuPct: pearson(records.map((r) => [r.cpuPct, total(r)])), - rRunVsLoad1: pearson(records.map((r) => [Array.isArray(r.load) ? r.load[0] : null, r.ms.run])), + rRunVsLoad1: pearson(records.map((r) => [load1(r), run(r)])), }, }; }; +// --- printing --- + +// C0 controls, DEL, C1 controls, the two Unicode line separators, and the +// bidirectional overrides and isolates. ESC and CSI start the sequences a +// terminal obeys (move the cursor, set the window title, write the +// clipboard); a line break forges a row; a bidi override reorders one. +const UNSAFE_CHARS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g; + +/** + * Any value as text that is safe to print: the characters above are + * removed. The one way a value from the log or the command line reaches + * the terminal — `renderTable` applies it to every cell, and the few lines + * printed outside a table use it directly. + */ +const safeText = (v) => String(v ?? '').replace(UNSAFE_CHARS, ''); + +/** Length in code points: what `clip` and the column widths count. */ +const textLength = (s) => Array.from(s).length; + +/** At most `w` code points, the last an ellipsis when cut. Never splits a surrogate pair. */ +const clip = (s, w) => { + const chars = Array.from(String(s)); + return chars.length > w ? `${chars.slice(0, Math.max(0, w - 1)).join('')}…` : chars.join(''); +}; + +/** + * Rows of cells as aligned text. Each column is as wide as its widest cell, + * so nothing is cut to fit: a cell that must be short is clipped by its + * caller, on purpose. `align[i]` is 'r' for a right-aligned column. The last + * column is not padded. + */ +const renderTable = (headers, rows, align = []) => { + const all = [headers, ...rows].map((row) => row.map(safeText)); + const widths = headers.map((_, i) => Math.max(...all.map((row) => textLength(row[i] ?? '')))); + return all + .map((row) => { + const cells = row.map((cell, i) => { + const gap = ' '.repeat(Math.max(0, widths[i] - textLength(cell))); + if (align[i] === 'r') return gap + cell; + return i === row.length - 1 ? cell : cell + gap; + }); + return ` ${cells.join(' ')}`.replace(/\s+$/, ''); + }) + .join('\n'); +}; + const fmt = (v) => (v === null || v === undefined ? '—' : v.toFixed(v < 10 ? 1 : 0)); -const pad = (s, w) => String(s).padEnd(w); -const padL = (s, w) => String(s).padStart(w); - -const stepTable = (title, groups) => { - const lines = [title]; - lines.push(` ${pad('', 16)}${padL('n', 5)} ${STEPS.map((s) => padL(s, 13)).join('')}`); - for (const g of groups) { - const cells = STEPS.map((s) => padL(`${fmt(g.steps[s].p50)}/${fmt(g.steps[s].p90)}`, 13)).join(''); - lines.push(` ${pad(g.key, 16)}${padL(g.n, 5)} ${cells}`); - } - return lines.join('\n'); + +/** + * `p50/p90`, followed by `(k)` when only k of the group's n records had the + * step — a resume has no `detect`, a timed-out switch no `total` — so a + * percentile is never read as covering records it does not. + */ +const statCell = (s, groupN) => { + if (s.n === 0) return '—'; + return `${fmt(s.p50)}/${fmt(s.p90)}${s.n !== groupN ? ` (${s.n})` : ''}`; }; +const stepTable = (title, label, groups) => + [ + title, + renderTable( + [label, 'n', ...STEPS], + groups.map((g) => [g.key, String(g.n), ...STEPS.map((s) => statCell(g.steps[s], g.n))]), + ['l', 'r', ...STEPS.map(() => 'r')], + ), + ].join('\n'); + /** Sessions shown unless `--all`. */ const SESSION_ROWS_DEFAULT = 20; +const SESSION_ID_MIN = 8; +const TITLE_MAX = 40; -const clip = (s, w) => (s.length > w ? `${s.slice(0, w - 1)}…` : s); +/** + * `~/rest` for a path at or under the home directory. Under means past a + * separator: `/Users/al-work` is not inside `/Users/al`. + */ +const tildePath = (p, home) => { + const h = String(home || '').replace(/\/+$/, ''); + if (!h) return p; + if (p === h) return '~'; + return p.startsWith(`${h}/`) ? `~${p.slice(h.length)}` : p; +}; + +/** + * A short label per session id: the first 8 characters, or as many more as + * it takes for no two of the given ids to share a label. A placeholder from + * `--redact` is already short and is its own label — `session-10` and + * `session-11` must not be cut to the same thing. + */ +const sessionLabels = (ids, redacted) => { + if (redacted) return new Map(ids.map((id) => [id, id])); + const longest = Math.max(SESSION_ID_MIN, ...ids.map((id) => id.length)); + for (let len = SESSION_ID_MIN; len <= longest; len++) { + const labels = ids.map((id) => id.slice(0, len)); + if (new Set(labels).size === new Set(ids).size) return new Map(ids.map((id, i) => [id, labels[i]])); + } + return new Map(ids.map((id) => [id, id])); +}; const sessionTable = (s, opts) => { - const home = os.homedir(); const shown = opts.all ? s.sessions : s.sessions.slice(0, SESSION_ROWS_DEFAULT); const lines = [ `By session (${shown.length} of ${s.sessions.length}, sorted by ${ @@ -282,24 +390,31 @@ const sessionTable = (s, opts) => { }${s.unnamed ? `; ${s.unnamed} older record(s) do not name a session` : ''})`, ]; if (shown.length === 0) return lines.concat(' (no record names its session)').join('\n'); + // Labels are unique among ALL sessions, so a row means the same with and without --all. + const labels = sessionLabels( + s.sessions.map((row) => row.sessionId), + !!opts.redact, + ); + const home = opts.home ?? os.homedir(); lines.push( - ` ${pad('session', 10)}${padL('n', 4)} ${padL('total p50/p90', 14)} ${padL('run p50/p90', 12)} ${pad('terminal', 10)}${pad('account', 12)}${pad('branches', 24)}title · project`, + renderTable( + ['session', 'n', 'total p50/p90', 'run p50/p90', 'terminal', 'account', 'branches', 'title · project'], + shown.map((row) => [ + labels.get(row.sessionId), + String(row.n), + statCell({ n: row.totalN, p50: row.totalP50, p90: row.totalP90 }, row.n), + statCell({ n: row.runN, p50: row.runP50, p90: row.runP90 }, row.n), + row.terminals.join(',') || '—', + row.account, + row.branches, + // Cleaned before it is clipped, so the 40 are 40 visible characters. + `${clip(safeText(row.title || '(no title)'), TITLE_MAX)} · ${ + row.project ? tildePath(safeText(row.project), home) : '—' + }`, + ]), + ['l', 'r', 'r', 'r'], + ), ); - for (const row of shown) { - const id = /^session-\d+$/.test(row.sessionId) ? row.sessionId : row.sessionId.slice(0, 8); - const project = row.project - ? row.project.startsWith(home) ? `~${row.project.slice(home.length)}` : row.project - : '—'; - lines.push( - ` ${pad(clip(id, 9), 10)}${padL(row.n, 4)} ${padL(`${fmt(row.totalP50)}/${fmt(row.totalP90)}`, 14)} ${padL( - `${fmt(row.runP50)}/${fmt(row.runP90)}`, - 12, - )} ${pad(clip(row.terminals.join(',') || '—', 9), 10)}${pad(clip(row.account, 11), 12)}${pad( - clip(row.branches, 23), - 24, - )}${clip(row.title || '(no title)', 40)} · ${project}`, - ); - } if (shown.length < s.sessions.length) lines.push(' … --all lists every session'); return lines.join('\n'); }; @@ -319,16 +434,19 @@ const formatReport = (summary, malformed = 0, opts = {}) => { 'Cells are p50/p90 in ms. Steps: clickToIpc (renderer → main), settings, detect', '(which terminal), build (script text), spawn (write + start), run (the external', 'command), main (IPC → done), total (click → done).', + 'n is the records in the row. A cell ending in (k) is over only k of them: the', + 'rest have no value for that step (a resume does not detect; a timed-out switch', + 'has no run, main or total).', '', - stepTable('All', [{ key: 'all', n: s.count, steps: s.all }]), + stepTable('All', '', [{ key: 'all', n: s.count, steps: s.all }]), '', - stepTable('By kind', s.byKind), + stepTable('By kind', 'kind', s.byKind), '', - stepTable('By terminal', s.byTerminal), + stepTable('By terminal', 'terminal', s.byTerminal), '', - stepTable('By branch', s.byBranch), + stepTable('By branch', 'branch', s.byBranch), '', - stepTable('By account', s.byAccount), + stepTable('By account', 'account', s.byAccount), '', sessionTable(s, opts), '', @@ -337,8 +455,10 @@ const formatReport = (summary, malformed = 0, opts = {}) => { }`, '', 'Total vs load (1-minute load average per core)', - ...s.load.buckets.map( - (b) => ` ${pad(b.label, 18)}${padL(b.n, 5)} p50 ${padL(fmt(b.p50), 6)} p90 ${padL(fmt(b.p90), 6)}`, + renderTable( + ['', 'n', 'total p50/p90'], + s.load.buckets.map((b) => [b.label, String(b.records), statCell(b, b.records)]), + ['l', 'r', 'r'], ), ` Pearson r, total vs 1-min load: ${r(s.load.rTotalVsLoad1)}`, ` Pearson r, run vs 1-min load: ${r(s.load.rRunVsLoad1)}`, @@ -380,7 +500,7 @@ const parseArgs = (argv) => { const main = (argv) => { const opts = parseArgs(argv); if (opts.bad.length > 0) { - console.error(`unknown option: ${opts.bad.join(' ')}`); + console.error(`unknown option: ${safeText(opts.bad.join(' '))}`); console.error('usage: switch-timing-summary.js [--redact] [--all] [--sort=n|p90] [file ...]'); process.exitCode = 2; return; @@ -389,7 +509,7 @@ const main = (argv) => { const files = explicit ? opts.files : defaultFiles(); const { text, missing } = readFiles(files); // The rotated file is optional; only a file the user named is worth a note. - if (explicit) for (const f of missing) console.error(`cannot read ${f}`); + if (explicit) for (const f of missing) console.error(`cannot read ${safeText(f)}`); const { records, malformed } = parseLines(text); const shown = opts.redact ? redactRecords(records) : records; console.log(formatReport(summarize(shown, opts), malformed, opts)); @@ -405,8 +525,13 @@ module.exports = { formatReport, stepStats, sessionRows, + sessionLabels, branchMix, redactRecords, parseArgs, + safeText, + clip, + tildePath, + renderTable, STEPS, }; diff --git a/src/main.ts b/src/main.ts index 45f15e2..7dac7d1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2794,7 +2794,7 @@ ipcMain.handle('rename-session-list', (_event, id: string, name: string) => { ipcMain.handle('get-live-sessions', async () => { try { const report = await collectLiveSessions(); - noteLiveReport(report); // the process count the switch timing log reuses + noteLiveReport(report); // the process count and ttys the switch timing log reuses return report; } catch (err) { // null, not an empty report: "we could not look" must never render as @@ -2861,7 +2861,6 @@ ipcMain.on( sessionId, active: !!isActive, title: customTitle, - accountLabel, projectPath, pid: isActive ? activePid : null, }, @@ -2884,6 +2883,8 @@ ipcMain.on( typeof accountLabel === 'string' && findAccountByLabel(accountLabel) ? accountLabel : undefined; + // The log gets the label the launch gets, not the renderer's raw one. + timing?.set({ account: label ?? null }); openSession( sessionId, projectPath, diff --git a/src/switch-timing-log.ts b/src/switch-timing-log.ts index eafa303..70901d5 100644 --- a/src/switch-timing-log.ts +++ b/src/switch-timing-log.ts @@ -4,14 +4,17 @@ * when the switch is over, sample the machine and append one JSON line to * `~/.config/codev/switch-timing.jsonl`, beside the marks and lists stores. * The line names the session (id, title, account, project path, pid, tty), - * so the file is created owner-only; it never holds prompts or transcript - * text. + * so the file and its rotated copy are kept owner-only. A title can be a + * summary of the conversation that Claude Code generated; the prompts and + * the transcript text themselves are not written. * * On the switch's path this costs one `os.cpus()` read, one * `process.cpuUsage()` and a few clock reads. Everything that spawns or - * touches the disk — `sysctl` for memory pressure, `ps` for a slow switch, - * the append itself — runs after the switch has finished, and a failure in - * any of it is dropped: the switch has already happened. + * touches the disk — `sysctl` for memory pressure, a `ps` for the tty when + * the last live-sessions report did not have it, another `ps` for the + * busiest processes after a slow or timed-out switch, the append itself — + * runs after the switch has finished, and a failure in any of it is + * dropped: the switch has already happened. * * No Electron imports, so the whole path runs under vitest. */ @@ -81,9 +84,23 @@ export const resetLiveReportNote = (): void => { // --- append with rotation --- +/** Owner-only, whatever the file was created as. A missing file is fine. */ +const makeOwnerOnly = async (filePath: string): Promise => { + try { + await fs.promises.chmod(filePath, 0o600); + } catch { + // Not there, or not ours to change: the append below decides. + } +}; + /** * Append one line, moving the file to `.1` first when the line would * take it past the cap. One old file is kept; the one before it is replaced. + * + * Both files are set to 0600 on every append, not only when created: the + * `mode` of an append applies to a new file only, so a log that an earlier + * build (or anything else) left group- or world-readable would stay so, and + * rotation would carry that mode over to `.1`. */ export const appendSwitchLogLine = async ( filePath: string, @@ -98,9 +115,13 @@ export const appendSwitchLogLine = async ( // No file yet. } const data = line.endsWith('\n') ? line : `${line}\n`; + // Before the rename, so the rotated file is already owner-only. + await makeOwnerOnly(filePath); if (shouldRotate(size, Buffer.byteLength(data), maxBytes)) { await fs.promises.rename(filePath, `${filePath}.1`); } + // A `.1` this append did not just create may predate the rule. + await makeOwnerOnly(`${filePath}.1`); // Owner-only when created, like the marks and lists stores beside it. await fs.promises.appendFile(filePath, data, { encoding: 'utf-8', mode: 0o600 }); }; @@ -133,6 +154,8 @@ export interface SwitchLogDeps { /** `ps -o tty= -p `; empty on failure. */ psTty?: (pid: number) => Promise; maxBytes?: number; + /** How long to wait for a command that never reports its exit. For tests. */ + deadlineMs?: number; /** Called after the line is written (or dropped). For tests. */ onWritten?: (record: Record | null) => void; } @@ -149,9 +172,12 @@ export const startSwitchTiming = ( deps: SwitchLogDeps = {}, ): SwitchTiming | undefined => { try { + // The clock first: everything below, the CPU snapshots included, is + // part of what main spends on a switch and belongs inside `main`. + const origin = performance.now(); const ipc = { wallMs: Date.now(), - perfEpochMs: performance.timeOrigin + performance.now(), + perfEpochMs: performance.timeOrigin + origin, }; const stamp = sanitizeStamp(rawStamp); const cpusBefore = os.cpus(); @@ -195,7 +221,7 @@ export const startSwitchTiming = ( ((p: number) => run('ps', ['-o', 'tty=', '-p', String(p)], 1000)); const [sysctlOut, psOut, ttyOut] = await Promise.all([ sysctl().catch(() => ''), - isSlowSwitch(ms) ? psTop().catch(() => '') : Promise.resolve(null), + isSlowSwitch(ms, snap.timedOut) ? psTop().catch(() => '') : Promise.resolve(null), pid !== null && !knownTty ? psTty(pid).catch(() => '') : Promise.resolve(null), ]); const tty = knownTty ?? parseTty(ttyOut); @@ -217,7 +243,12 @@ export const startSwitchTiming = ( deps.onWritten?.(record); }; - return createSwitchTiming({ now: () => performance.now(), onFinish }); + return createSwitchTiming({ + now: () => performance.now(), + origin, + onFinish, + deadlineMs: deps.deadlineMs, + }); } catch { return undefined; } diff --git a/src/switch-timing.test.ts b/src/switch-timing.test.ts index fa681ba..1fbda51 100644 --- a/src/switch-timing.test.ts +++ b/src/switch-timing.test.ts @@ -15,6 +15,7 @@ import { shouldRotate, stepDurations, SwitchSnapshot, + textOrNull, } from './switch-timing'; import { appendSwitchLogLine, @@ -115,6 +116,22 @@ describe('createSwitchTiming', () => { expect(h.finished[0].ok).toBe(false); }); + it('measures from the origin it is given, not from its own creation', () => { + // The caller read the clock at 90, then spent 10 ms setting up. + let now = 100; + const finished: SwitchSnapshot[] = []; + const timing = createSwitchTiming({ + now: () => now, + origin: 90, + onFinish: (s) => finished.push(s), + }); + now = 103; + timing.mark('settings'); + now = 120; + timing.settle(true); + expect(finished[0].marks).toEqual({ settings: 13, returned: 30 }); + }); + it('never throws into the switch, even when the sink does', () => { const timing = createSwitchTiming({ now: () => 0, @@ -235,15 +252,33 @@ describe('stepDurations', () => { undefined, ipc, ); + // The 15 s deadline is when the record closed, not how long anything took. expect(timedOut.total).toBeNull(); + expect(timedOut.main).toBeNull(); expect(timedOut.run).toBeNull(); + // What was measured stays: main got its answer back after 5 ms. + expect(timedOut.returned).toBe(5); + expect(timedOut.spawn).toBe(4); expect(timedOut.clickToIpc).toBeNull(); - expect(isSlowSwitch(timedOut)).toBe(false); // Without a stamp the total is main's own span, not a guess. const noStamp = stepDurations(snap({ marks: { returned: 5 }, endedAt: 5 }), undefined, ipc); expect(noStamp.total).toBe(5); }); + it('counts a timed-out switch as slow although it has no total', () => { + const fast = stepDurations(snap({ marks: { returned: 5 }, endedAt: 5 }), undefined, ipc); + expect(isSlowSwitch(fast)).toBe(false); + expect(isSlowSwitch(fast, true)).toBe(true); + const slow = stepDurations( + snap({ marks: { returned: 5 }, spawnedAt: 5, exitedAt: 1001 }), + undefined, + ipc, + ); + expect(slow.total).toBe(1001); + expect(isSlowSwitch(slow)).toBe(true); + expect(isSlowSwitch({ ...slow, total: 1000 })).toBe(false); + }); + it('does not let a renderer clock that runs ahead shorten the total', () => { const ahead = { ...stamp, wallMs: ipc.wallMs + 50 }; const ms = stepDurations(snap({ marks: { returned: 20 }, endedAt: 20 }), ahead, ipc); @@ -335,7 +370,6 @@ describe('the log file', () => { sessionId: '0f1e2d3c-aaaa-bbbb-cccc-123456789abc', active: true, title: 'an example title', - accountLabel: 'second', projectPath: '/Users/someone/code/example', pid: 4242, }; @@ -346,8 +380,11 @@ describe('the log file', () => { sysctl?: () => Promise; psTop?: () => Promise; psTty?: (pid: number) => Promise; + deadlineMs?: number; } = {}, session: Parameters[0] = SESSION, + // What main does once it has validated the row's label; `never` hangs the command. + { account = 'second' as string | null, exits = true } = {}, ) => new Promise | null>((resolve) => { const timing = startSwitchTiming( @@ -365,10 +402,11 @@ describe('the log file', () => { ); timing.set({ configured: 'iterm2', terminal: 'ghostty', order: 'tty-first' }); timing.mark('settings'); + timing.set({ account }); timing.mark('script'); timing.spawned(); timing.settle(true); - timing.exited('found-by-title\n'); + if (exits) timing.exited('found-by-title\n'); }); it('writes one line per switch, naming the session it was', async () => { @@ -434,6 +472,57 @@ describe('the log file', () => { ]); }); + it('samples the busiest processes for a command that never reports back', async () => { + // The hung command is the case the sample exists for, and it has no total. + let psCalls = 0; + const record = await runSwitch( + { wallMs: Date.now(), perfEpochMs: performance.timeOrigin + performance.now(), via: 'click', rows: 1 }, + { + deadlineMs: 20, + psTop: async () => { + psCalls++; + return ' 97.5 /usr/libexec/stuckd\n'; + }, + }, + SESSION, + { exits: false }, + ); + expect(psCalls).toBe(1); + expect(record).toMatchObject({ + timedOut: true, + branch: null, + top: [{ cpu: 97.5, comm: 'stuckd' }], + }); + const ms = record.ms as Record; + expect(ms.run).toBeNull(); + expect(ms.main).toBeNull(); + expect(ms.total).toBeNull(); + expect(ms.returned).toBeGreaterThanOrEqual(0); + expect(ms.returned).toBeLessThan(20); // measured, not the deadline + }); + + it('makes an existing log and its rotated copy owner-only, not just a new one', async () => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, 'old line\n', { mode: 0o644 }); + fs.writeFileSync(`${file}.1`, 'older line\n', { mode: 0o644 }); + fs.chmodSync(file, 0o644); // past the umask + fs.chmodSync(`${file}.1`, 0o644); + const mode = (f: string) => fs.statSync(f).mode & 0o777; + + // An append that does not rotate fixes both files. + await appendSwitchLogLine(file, 'new line', 1000); + expect(mode(file)).toBe(0o600); + expect(mode(`${file}.1`)).toBe(0o600); + expect(fs.readFileSync(file, 'utf-8')).toBe('old line\nnew line\n'); + + // A rotation carries no loose mode over to `.1`. + fs.chmodSync(file, 0o644); + await appendSwitchLogLine(file, 'x'.repeat(40), 30); + expect(fs.readFileSync(`${file}.1`, 'utf-8')).toBe('old line\nnew line\n'); + expect(mode(`${file}.1`)).toBe(0o600); + expect(mode(file)).toBe(0o600); + }); + it('takes the tty from the last live-sessions report instead of spawning ps', async () => { noteLiveReport({ live: [ @@ -466,6 +555,7 @@ describe('the log file', () => { }, }, { sessionId: 'abc', active: false, pid: null }, + { account: null }, ); expect(record).toMatchObject({ v: 2, @@ -520,7 +610,40 @@ describe('parseTty', () => { }); }); +describe('textOrNull', () => { + it('cuts by code point, so a cut never leaves half a character', () => { + const emoji = '\u{1F600}'; // two UTF-16 units + const cut = textOrNull(`${'a'.repeat(199)}${emoji}${emoji}`, 200); + expect(Array.from(cut)).toHaveLength(200); + expect(cut.endsWith(emoji)).toBe(true); + // Every character whole: no lone surrogate at the cut. + expect(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(cut)).toBe(false); + // 150 emoji are 300 units but only 150 code points: under the cap, kept whole. + expect(textOrNull(emoji.repeat(150), 200)).toBe(emoji.repeat(150)); + expect(textOrNull('', 200)).toBeNull(); + expect(textOrNull(7, 200)).toBeNull(); + }); +}); + describe('buildSwitchRecord', () => { + it('records the account main validated, from the facts', () => { + const snap: SwitchSnapshot = { + marks: { returned: 1 }, + spawnedAt: null, + exitedAt: null, + endedAt: 1, + facts: { account: 'second' }, + ok: true, + timedOut: false, + }; + const ms = stepDurations(snap, undefined, { wallMs: 0, perfEpochMs: 0 }); + const ctx = { ts: '2026-01-02T03:04:05.000Z', sessionId: 'id-1', active: true }; + expect(buildSwitchRecord(ctx, undefined, snap, ms, {}).account).toBe('second'); + // A label main dropped (no such account) is null, never the raw string. + const dropped = { ...snap, facts: { account: null } }; + expect(buildSwitchRecord(ctx, undefined, dropped, ms, {}).account).toBeNull(); + }); + it('drops values of the wrong shape and cuts an overlong title', () => { const snap: SwitchSnapshot = { marks: {}, @@ -538,12 +661,11 @@ describe('buildSwitchRecord', () => { sessionId: 'id-1', active: true, title: 't'.repeat(500), - accountLabel: 42 as unknown as string, projectPath: '', pid: 12.5, }, undefined, - snap, + { ...snap, facts: { account: 42 as unknown as string } }, ms, // A source without a tty is not a source. { tty: null, ttySrc: 'ps' }, @@ -687,12 +809,13 @@ describe('scripts/switch-timing-summary.js', () => { runP50: 180, branches: 'tty×2 cwd×1', }); - expect(s.sessions[1]).toMatchObject({ sessionId: 'bbbb2222-0000', title: null, account: '(anchor)', n: 1 }); - // The v1 line has no account: unknown, which is not the anchor. + expect(s.sessions[1]).toMatchObject({ sessionId: 'bbbb2222-0000', title: null, account: '(none)', n: 1 }); + // A v2 line without a label had no account; the v1 line never said. + // Neither is "the anchor", which has a label like every account. expect(s.byAccount.map((g: { key: string; n: number }) => [g.key, g.n])).toEqual([ ['second', 3], ['(unknown)', 1], - ['(anchor)', 1], + ['(none)', 1], ]); expect(s.byTerminal.find((g: { key: string }) => g.key === 'ghostty').n).toBe(1); const report = summary.formatReport(s); @@ -753,6 +876,131 @@ describe('scripts/switch-timing-summary.js', () => { expect(summary.summarize(once).sessions.map((r: { n: number }) => r.n)).toEqual([3, 1]); }); + it('keeps every redacted placeholder distinct past session-9', () => { + // `session-10` … `session-12` used to be clipped to one label. + const many = Array.from({ length: 12 }, (_, i) => ({ + v: 2, + sessionId: `real-id-${i}`, + title: `private ${i}`, + account: `acct-${i}`, + project: `/home/u/code/p${i}`, + terminal: 'iterm2', + branch: 'tty', + ms: { total: 100 + i, run: 90 }, + })); + const report: string = summary.formatReport( + summary.summarize(summary.redactRecords(many)), + 0, + { redact: true, all: true }, + ); + const rows = report.split('\n').filter((l) => /^ {2}session-\d+ /.test(l)); + const labels = rows.map((l) => l.trim().split(/\s+/)[0]); + expect(labels).toHaveLength(12); + expect(new Set(labels).size).toBe(12); + expect(labels).toContain('session-10'); + expect(labels).toContain('session-12'); + for (const n of [10, 11, 12]) { + expect(report).toContain(`account-${n}`); + expect(report).toContain(`~/project-${n}`); + } + expect(report).not.toContain('…'); + }); + + it('lengthens real id labels until no two sessions share one', () => { + const labels = summary.sessionLabels(['abcdefgh-1111', 'abcdefgh-1222', 'zzzzzzzz-9999'], false); + expect([...labels.values()]).toEqual(['abcdefgh-11', 'abcdefgh-12', 'zzzzzzzz-99']); + expect([...summary.sessionLabels(['abcdefgh-1111', 'zzzzzzzz-9999'], false).values()]).toEqual([ + 'abcdefgh', + 'zzzzzzzz', + ]); + }); + + it('strips control characters from every field it prints', () => { + const ESC = '\u001b'; + const hostile = { + v: 2, + sessionId: `id${ESC}[2J-0001`, + // An OSC title-set, a forged row via newline, a C1 CSI, a bidi override. + title: `ok${ESC}]0;pwned\u0007\n forged-row 99\u009b31m\u202e`, + account: `acc\rount`, + project: `/home/u/co\u0000de${ESC}[31m`, + terminal: `iterm2${ESC}[1m`, + branch: `tty\n fake`, + kind: `switch\u007f`, + ms: { total: 100, run: 90 }, + }; + const clean = { ...hostile, sessionId: 'id-0002', title: 'fine', branch: 'tty', kind: 'switch' }; + const report: string = summary.formatReport(summary.summarize([hostile, clean]), 0, { all: true }); + // eslint-disable-next-line no-control-regex + expect(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/.test(report)).toBe(false); + // The newline in the title did not become a line of its own. + expect(report.split('\n').filter((l) => l.includes('forged-row'))).toHaveLength(1); + expect(report.split('\n').some((l) => /^\s*forged-row/.test(l))).toBe(false); + expect(report.split('\n').some((l) => /^\s*fake/.test(l))).toBe(false); + expect(summary.safeText(`a${ESC}[31mb\u009b\u007fc\n`)).toBe('a[31mbc'); + expect(summary.safeText(null)).toBe(''); + // Same for --redact, whose placeholders are safe but whose other fields are the log's. + const redacted: string = summary.formatReport( + summary.summarize(summary.redactRecords([hostile, clean])), + 0, + { redact: true }, + ); + // eslint-disable-next-line no-control-regex + expect(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/.test(redacted)).toBe(false); + }); + + it('clips by code point and never through a character', () => { + const emoji = '\u{1F600}'; + expect(summary.clip(emoji.repeat(5), 5)).toBe(emoji.repeat(5)); + expect(summary.clip(emoji.repeat(6), 5)).toBe(`${emoji.repeat(4)}…`); + expect(summary.clip('abcdef', 4)).toBe('abc…'); + }); + + it('abbreviates the home directory only at a path boundary', () => { + expect(summary.tildePath('/Users/al/code/x', '/Users/al')).toBe('~/code/x'); + expect(summary.tildePath('/Users/al', '/Users/al')).toBe('~'); + expect(summary.tildePath('/Users/al-work/code/x', '/Users/al')).toBe('/Users/al-work/code/x'); + expect(summary.tildePath('/Users/al/code/x', '/Users/al/')).toBe('~/code/x'); + expect(summary.tildePath('/srv/x', '')).toBe('/srv/x'); + }); + + it('says how many records a percentile covers when it is not all of them', () => { + const rec = (kind: string, ms: Record, timedOut = false) => ({ + v: 2, + sessionId: 'one', + kind, + terminal: 'iterm2', + branch: 'tty', + timedOut, + ms, + }); + const records = [ + rec('switch', { detect: 20, run: 100, total: 130 }), + rec('switch', { detect: 40, run: 300, total: 350 }), + rec('resume', { run: 500, total: 520 }), + // A hung command: only what main measured. A stray total must not count. + rec('switch', { detect: 30, returned: 35, total: 15000 }, true), + ]; + const s = summary.summarize(records); + expect(s.timedOut).toBe(1); + expect(s.slow).toBe(0); + expect(s.all.total).toEqual({ n: 3, p50: 350, p90: 486 }); + expect(s.all.detect.n).toBe(3); + expect(s.sessions[0]).toMatchObject({ n: 4, totalN: 3, runN: 3, totalP50: 350 }); + const report: string = summary.formatReport(s, 0, {}); + const all = report.split('\n').find((l) => /^ {2}all\s/.test(l)); + // n is 4; detect and total each cover 3 and say so. + expect(all).toMatch(/^ {2}all\s+4\s/); + expect(all).toContain('30/38 (3)'); + expect(all).toContain('350/486 (3)'); + // The resume group's one record has every step it could: no marker, and no detect at all. + const resume = report.split('\n').find((l) => /^ {2}resume\s/.test(l)); + expect(resume).not.toContain('('); + expect(resume).toContain('520/520'); + const session = report.split('\n').find((l) => /^ {2}one\s/.test(l)); + expect(session).toContain('350/486 (3)'); + }); + it('parses flags apart from files and rejects an unknown one', () => { expect(summary.parseArgs(['--redact', 'a.jsonl', '--sort=p90', '--all'])).toMatchObject({ redact: true, diff --git a/src/switch-timing.ts b/src/switch-timing.ts index ae7ea23..7177ea6 100644 --- a/src/switch-timing.ts +++ b/src/switch-timing.ts @@ -17,11 +17,14 @@ * - **A record says which session it was, and nothing a session said.** * It holds the session id, its title, account label, project path, pid * and tty, so that per-session patterns show (one crowded window, one - * account, a session that always falls back to cwd). Prompts and - * transcript text are never recorded. The log stays on this machine in an - * owner-only (0600) file; titles and paths are the owner's, so results - * quoted anywhere public should carry placeholders instead (the summary - * script's `--redact`). + * account, a session that always falls back to cwd). The title is + * whatever the Sessions tab shows for the row: the name the user gave + * with `/rename`, or else the one Claude Code generated — a model-written + * summary of the conversation in a few words. The prompts and the + * transcript text themselves are not recorded. The log stays on this + * machine in an owner-only (0600) file; titles and paths describe the + * owner's work, so results quoted anywhere public should carry + * placeholders instead (the summary script's `--redact`). */ /** Points on the path, in the order a terminal switch passes them. */ @@ -64,8 +67,14 @@ export interface SwitchFacts { branch?: SwitchBranch | null; /** Which key the script tried first. */ order?: 'tty-first' | 'title-first'; - /** Whether the script carried a title block at all (a `/rename`d session). */ + /** Whether the script carried a title block at all (the row had a title). */ hasTitle?: boolean; + /** + * The row's account label once main has checked that an account carries + * it — the same value the launch is given. Null: the row had none, or + * named an account that does not exist. + */ + account?: string | null; } /** What the renderer stamps on the click that starts a switch. */ @@ -116,6 +125,12 @@ export interface SwitchTiming { export interface SwitchTimingDeps { /** A monotonic clock in ms. */ now: () => number; + /** + * The reading of `now` that is time zero — the IPC's arrival. Given when + * the caller read the clock before doing anything else, so that its own + * setup is inside the measurement; otherwise the clock is read here. + */ + origin?: number; onFinish: (snapshot: SwitchSnapshot) => void; /** How long to wait for a command that never reports its exit. */ deadlineMs?: number; @@ -145,7 +160,7 @@ export const branchFromSwitchOutput = ( }; export const createSwitchTiming = (deps: SwitchTimingDeps): SwitchTiming => { - const t0 = deps.now(); + const t0 = typeof deps.origin === 'number' ? deps.origin : deps.now(); const marks: Partial> = {}; let facts: SwitchFacts = {}; let spawnedAt: number | null = null; @@ -285,9 +300,12 @@ export interface SwitchStepMs { run: number | null; /** IPC arrival to `openSession` returning. */ returned: number | null; - /** IPC arrival to the end: the command's exit, else `openSession` returning. */ + /** + * IPC arrival to the end: the command's exit, else `openSession` + * returning. Null when the command timed out. + */ main: number | null; - /** `clickToIpc + main`: what the user waited. */ + /** `clickToIpc + main`: what the user waited. Null when the command timed out. */ total: number | null; } @@ -304,9 +322,12 @@ export const stepDurations = ( const { marks, spawnedAt, exitedAt } = snap; const afterSettings = marks.settings ?? 0; const beforeScript = marks.detect ?? afterSettings; - // A command that timed out never reported an exit; the record's end is - // then the deadline, which is not a duration of anything. - const end = snap.timedOut ? null : exitedAt ?? marks.returned ?? snap.endedAt; + // The end is the command's exit, or `openSession` returning on a path + // that runs no command (the collector always marks `returned` before it + // closes). A command that timed out never reported an exit: the record + // then closed at the deadline, which is not a duration of anything, so + // `run`, `main` and `total` stay null and `returned` is what is known. + const end = snap.timedOut ? null : exitedAt ?? marks.returned ?? null; const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n); const clickToIpc = stamp && finite(stamp.wallMs) ? ipc.wallMs - stamp.wallMs : null; const clickToIpcHr = @@ -337,7 +358,7 @@ export interface SwitchSystemSample { /** Running `claude` processes in the last live-sessions report, and its age. */ claudeProcs?: number | null; liveAgeMs?: number | null; - /** Only for a slow switch: the busiest processes right after it. */ + /** Only for a slow or timed-out switch: the busiest processes right after it. */ top?: { cpu: number; comm: string }[]; /** The target process's controlling terminal, and where the value came from. */ tty?: string | null; @@ -349,20 +370,27 @@ export interface SwitchContext { ts: string; sessionId: string; active: boolean; - /** The session's `/rename` title, as the click carried it. */ + /** The row's title as the click carried it: `/rename`d, or generated. */ title?: string | null; - /** The account label the row carried; none for the anchor account. */ - accountLabel?: string | null; projectPath?: string | null; /** The process switched to; none for a resume. */ pid?: number | null; } -/** A title is one line of the user's own text; anything longer is cut. */ +/** A title is a line of text; anything longer is cut. In code points. */ export const SWITCH_TITLE_MAX = 200; -const textOrNull = (v: unknown, max = 4096): string | null => - typeof v === 'string' && v !== '' ? v.slice(0, max) : null; +/** + * A non-empty string of at most `max` code points, else null. Cut by code + * point, not by UTF-16 unit: a cut through the middle of an emoji would + * leave half a character at the end of the value. + */ +export const textOrNull = (v: unknown, max = 4096): string | null => { + if (typeof v !== 'string' || v === '') return null; + // `length` counts UTF-16 units, never fewer than the code points. + if (v.length <= max) return v; + return Array.from(v).slice(0, max).join(''); +}; /** A usable pid, else null: the value crossed an IPC boundary. */ export const pidOrNull = (v: unknown): number | null => @@ -405,8 +433,13 @@ export const SWITCH_RECORD_VERSION = 2; /** A switch slower than this also records the busiest processes. */ export const SLOW_SWITCH_MS = 1000; -export const isSlowSwitch = (ms: SwitchStepMs): boolean => - typeof ms.total === 'number' && ms.total > SLOW_SWITCH_MS; +/** + * Slow enough to also ask what the machine was busy with. A switch whose + * command never reported back has no total to compare — and is the slowest + * kind there is, so it always counts. + */ +export const isSlowSwitch = (ms: SwitchStepMs, timedOut = false): boolean => + timedOut || (typeof ms.total === 'number' && ms.total > SLOW_SWITCH_MS); export const buildSwitchRecord = ( ctx: SwitchContext, @@ -419,7 +452,7 @@ export const buildSwitchRecord = ( ts: ctx.ts, sessionId: textOrNull(ctx.sessionId, 128), title: textOrNull(ctx.title, SWITCH_TITLE_MAX), - account: textOrNull(ctx.accountLabel, 128), + account: textOrNull(snap.facts.account, 128), project: textOrNull(ctx.projectPath), pid: pidOrNull(ctx.pid), tty: sys.tty ?? null, From 0d9a4aec9f5f9c5ecb34c784910be0d2055901ff Mon Sep 17 00:00:00 2001 From: Grimmer Kang Date: Fri, 20 Nov 2026 22:49:54 +0900 Subject: [PATCH 5/7] fix(sessions): switch timing log, review round 2 Thirteen findings from the second review; one more is declined on the pull request (a retry protocol for a rotation between two reads). A record now says when it is not the time of a completed switch: - `killed`: the command exited because its 5 s timeout killed it. The wait is real and stays numeric, `ok` is false, and the busiest-processes sample is taken. - `untimed`: the paths handed to VS Code, Claude Desktop or the embedded terminal start no command, so run, main and total are null and `returned` is kept. They are counted, not timed. The summary keeps both, with timeouts and failed launches, out of the run, main and total percentiles and counts each kind. Log: - A resume records the account it runs under, set where that is decided (buildResumeCommand); a switch to a running session keeps the row's validated label. - An existing log that cannot be made owner-only gets no record. A missing one is still created 0600. - The process count, its age and the tty come from one live report. - The cost in the main process is described as it is: samples when the IPC arrives and again when the record closes. Summary script: - A line with a wrong-typed text field, or an `ms` that is not a plain object, is malformed: one rule, in one place. - No spread of a data-sized array into a call. - An input that exists and cannot be read is reported, marks the report incomplete and exits 1; a missing one stays quiet. Under --redact an input is named by position, not by path. - Three more direction marks are stripped (U+061C, U+200E, U+200F). Tests: no real-time upper bound. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- docs/claude-session-integration-design.md | 28 ++- scripts/switch-timing-summary.js | 147 +++++++++--- src/claude-session-utility.ts | 20 +- src/main.ts | 3 +- src/switch-timing-log.ts | 57 +++-- src/switch-timing.test.ts | 263 +++++++++++++++++++++- src/switch-timing.ts | 70 ++++-- 8 files changed, 500 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8166e25..e443d38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 1.0.97 -- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s or one whose command never reported back, the three busiest processes). **Each line names its session** — the session id, title, account label, project path, the pid switched to and its tty — so per-session patterns show (a crowded window, one account, a session that always falls back to cwd); the title is the `/rename` name or, without one, the title Claude Code generated, which is a model-written summary of the conversation; **the prompts and the transcript text themselves are not recorded**. The file is local and kept owner-only (0600, set again on every write, the rotated copy included); when quoting results in public, replace titles and paths with placeholders — `yarn switch-timing --redact` does it. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch, and a failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal, branch and account, a per-session table (`--all`, `--sort=p90`), and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" +- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s, or one whose command never reported back or was killed by its timeout, the three busiest processes). A record says when it is not the time of a completed switch: `timedOut`, `killed`, or `untimed` for the paths handed to VS Code, Claude Desktop or the embedded terminal, which the log counts but does not time. **Each line names its session** — the session id, title, account label, project path, the pid switched to and its tty — so per-session patterns show (a crowded window, one account, a session that always falls back to cwd); the title is the `/rename` name or, without one, the title Claude Code generated, which is a model-written summary of the conversation; **the prompts and the transcript text themselves are not recorded**. The file is local and kept owner-only (0600, set again on every write, the rotated copy included); when quoting results in public, replace titles and paths with placeholders — `yarn switch-timing --redact` does it. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch; what remains in the main process is a few synchronous reads (`os.cpus()`, `process.cpuUsage()`, the clock) when the IPC arrives and again (plus `os.loadavg()`) when the record closes. A failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal, branch and account, a per-session table (`--all`, `--sort=p90`), and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" ## 1.0.94 diff --git a/docs/claude-session-integration-design.md b/docs/claude-session-integration-design.md index 56b29f5..93ee551 100644 --- a/docs/claude-session-integration-design.md +++ b/docs/claude-session-integration-design.md @@ -669,7 +669,7 @@ TypeScript is sufficient for MVP. `history.jsonl` reading (~40ms) and session li Before rewriting any part of the switch path for speed, measure where a switch spends its time. Since 1.0.97 every switch started from the Sessions tab (Enter or a click) appends one JSON line to `~/.config/codev/switch-timing.jsonl`. The question it is meant to answer: is the time in CodeV's own JavaScript, which a rewrite could shorten, or in the external command (`osascript`, or the cmux CLI) and a loaded machine, which it could not? -**What a line holds: timings, counts, and which session it was.** Each line names its session — the session id, its title, account label, project path, the pid switched to and that process's tty — so that per-session patterns show up: one crowded terminal window, one account, a session that always falls back to cwd. **The title is the one the Sessions tab shows for the row**: the name the user gave with `/rename`, or, for a session never renamed, the title Claude Code generated — a few words written by the model that summarize the conversation. So a line can carry a summary of what a session was about. **The prompts and the transcript text themselves are not recorded.** The file stays on this machine and is kept owner-only (mode 0600), like the stores beside it: the mode is set again on every write, on the log and on its rotated copy, so a file that was created looser does not stay that way. Titles and paths describe the owner's work, so anyone quoting results in public (an issue, a pull request) should replace them with placeholders; the summary script's `--redact` does that. The file is capped at about 1 MB: at the cap it is renamed to `switch-timing.jsonl.1` (one old file is kept) and a new one starts. Logging is always on; there is no setting. +**What a line holds: timings, counts, and which session it was.** Each line names its session — the session id, its title, account label, project path, the pid switched to and that process's tty — so that per-session patterns show up: one crowded terminal window, one account, a session that always falls back to cwd. **The title is the one the Sessions tab shows for the row**: the name the user gave with `/rename`, or, for a session never renamed, the title Claude Code generated — a few words written by the model that summarize the conversation. So a line can carry a summary of what a session was about. **The prompts and the transcript text themselves are not recorded.** The file stays on this machine and is kept owner-only (mode 0600), like the stores beside it: the mode is set again on every write, on the log and on its rotated copy, so a file that was created looser does not stay that way. If an existing log cannot be made owner-only, the record is dropped, not appended. Titles and paths describe the owner's work, so anyone quoting results in public (an issue, a pull request) should replace them with placeholders; the summary script's `--redact` does that. The file is capped at about 1 MB: at the cap it is renamed to `switch-timing.jsonl.1` (one old file is kept) and a new one starts. Logging is always on; there is no setting. ``` renderer main process terminal @@ -688,11 +688,17 @@ Before rewriting any part of the switch path for speed, measure where a switch s ⑧b ps -o tty= -p PID the tty — only when the last live-sessions report did not list the pid ⑧c ps -A (%CPU) the three busiest processes — only when - the switch took over 1 s or timed out + the switch took over 1 s, timed out + or was killed ⑧d append the line ``` -Steps ① to ⑦ are the switch. The two `ps` calls in step ⑧ are different commands with different conditions (⑧b looks up one process's tty, ⑧c lists every process's CPU share); a fast switch to a session the live report already knows runs neither. Step ⑧ runs only after the switch, so nothing that spawns a process or touches the disk for the log sits on the switch's path; what the log adds to the path itself is one `os.cpus()` read, one `process.cpuUsage()` and a few clock reads. Any failure in the timing code is swallowed and the switch runs as before. +Steps ① to ⑦ are the switch. The two `ps` calls in step ⑧ are different commands with different conditions (⑧b looks up one process's tty, ⑧c lists every process's CPU share); a fast switch to a session the live report already knows runs neither. Step ⑧ runs only after the switch, so nothing that spawns a process or touches the disk for the log sits on the switch's path. What the log does add to the main process is synchronous and small, at two moments: + +- **When the IPC arrives (②):** one `os.cpus()`, one `process.cpuUsage()` and two clock reads; then one clock read per step. +- **When the record closes:** one more `os.cpus()`, one `os.loadavg()` and one `process.cpuUsage()`. This runs in the callback of the command's exit (⑦), or as `openSession` settles on a path where the exit came first — after the terminal has switched, but still in the main process before step ⑧ is deferred. + +Any failure in the timing code is swallowed and the switch runs as before. | Field | Meaning | |---|---| @@ -700,7 +706,7 @@ Steps ① to ⑦ are the switch. The two `ps` calls in step ⑧ are different co | `ts` | ISO time the IPC arrived in the main process. | | `sessionId` | The full session id. | | `title` | The row's title when the switch was started: the `/rename` name, else the title Claude Code generated (a model-written summary of the conversation); `null` when the session has neither. Cut at 200 characters. | -| `account` | The row's account label, after the main process has checked that an account with that label exists — the same value the launch is given. Every account has a label, the anchor included. `null` means the row carried no label, or one that no account has any more; it does not mean the anchor. | +| `account` | The account of the switch. For a `resume` it is the account the launch actually runs under, recorded where that is decided: the account history has for the session, or, for a session history does not know, the row's label. For a `switch` to a running session nothing is launched, so it is the row's label, after the main process has checked that an account with that label exists. Every account has a label, the anchor included. `null` means no account was resolved (no label, or one that no account has any more); it does not mean the anchor. | | `project` | The session's project path. | | `pid` | The process switched to; `null` for a resume, which has none yet. | | `tty`, `ttySrc` | That process's controlling terminal (for example `ttys004`), and where the value came from: `live-report` (the last live-sessions report already listed it) or `ps` (one `ps -o tty= -p `, run after the switch). `null` when there is no pid, the process has no tty, or the lookup failed. | @@ -708,20 +714,22 @@ Steps ① to ⑦ are the switch. The two `ps` calls in step ⑧ are different co | `kind` | `switch` (the session was running) or `resume` (it was not; a new tab runs `claude --resume`). | | `terminal`, `configured` | Where the switch went after auto-detection, and the terminal named in Settings. | | `tool` | What ran the switch: `osascript`, `cmux-cli`, `open` (VS Code, Claude Desktop) or `pty` (the embedded terminal). | +| `untimed` | True for a switch this log cannot time end to end: the paths with tool `open` or `pty`, which hand the switch over and return at once (VS Code, for one, then waits 500 ms before its own command). No command is started and awaited, so `ms.run`, `ms.main` and `ms.total` are `null`; `ms.returned` and the earlier steps are kept. The log exists to measure terminal switching; these records are there to be counted, not timed. | | `branch` | Which key found the tab: `tty`, `title`, `cwd`, `project-name` (cmux), `none` (the script ran and matched nothing); for a resume `new-tab`, `new-window` or `new-workspace`; `deep-link`, `embedded`. `null` means unknown, for example a script that failed. | | `order`, `hasTitle` | Which key the script tried first (`tty-first` or `title-first`), and whether it had a title block at all. | -| `ok`, `timedOut` | `ok` is false when the launch was rejected. `timedOut` is true when the command had not reported an exit after 15 s. The record then says only what was measured: `ms.run`, `ms.main` and `ms.total` are `null` (15 s is when the record was closed, not how long anything took), the earlier steps and `ms.returned` are kept, and `top` is recorded as for a slow switch. | +| `killed` | True when the command exited only because its 5 s timeout killed it (`error.killed` in the callback). `ms.run`, `ms.main` and `ms.total` are then real waits and stay numeric, but they are not the time of a switch: `ok` is false, `branch` is `null`, and `top` is recorded as for a slow switch. Not seen on two paths: the iTerm2 switch runs without a timeout (a hang there ends as `timedOut`), and the cmux switch does not report its CLI errors. | +| `ok`, `timedOut` | `ok` is false when the launch was rejected or its command was killed. `timedOut` is true when the command had not reported an exit after 15 s. The record then says only what was measured: `ms.run`, `ms.main` and `ms.total` are `null` (15 s is when the record was closed, not how long anything took), the earlier steps and `ms.returned` are kept, and `top` is recorded as for a slow switch. | | `ms.clickToIpc`, `ms.clickToIpcHr` | ① to ②, on the wall clock (whole ms) and on the two processes' high-resolution clocks. | | `ms.settings`, `ms.detect`, `ms.build`, `ms.spawn`, `ms.run` | The steps in the diagram. A step a path skips is `null`, and its time counts in the next one. | | `ms.returned` | ② to `openSession` returning. For a running session this is before the script exits. | -| `ms.main`, `ms.total` | ② to ⑦, and ① to ⑦ (what the user waited). On a path that runs no command (VS Code, Claude Desktop, the embedded terminal) the end is `openSession` returning. Time zero for every `ms` value except the two `clickToIpc` ones is the first thing the handler does, before the timing code's own setup, so that setup is inside `ms.settings` and `ms.main`. | +| `ms.main`, `ms.total` | ② to ⑦, and ① to ⑦ (what the user waited). `null` when no exit was seen: `timedOut`, or `untimed`. Time zero for every `ms` value except the two `clickToIpc` ones is the first thing the handler does, before the timing code's own setup, so that setup is inside `ms.settings` and `ms.main`. | | `load`, `ncpu` | `os.loadavg()` at the end of the switch, and the core count. | | `cpuPct` | Whole-machine CPU busy % over the span, from two `os.cpus()` samples. `null` for a span too short to measure (the counters tick every 10 ms). | | `mainCpuMs` | An object, `{ "user": …, "system": … }`: the CPU time in ms that CodeV's main process itself used over the span, in user mode and in system mode (`process.cpuUsage()` delta). | | `mem` | macOS memory-pressure level (1 normal, 2 warn, 4 critical) and swap in MB — the same `sysctl` reading as the memory chip, taken after the switch. | | `claudeProcs`, `liveAgeMs` | Running `claude` processes in the last live-sessions report the window asked for, and how old that report was. No extra `ps` is run for it. | | `rows` | Rows in the session list when the switch was started. | -| `top` | Only when `ms.total` is over 1 s, or the switch timed out: the three busiest processes (`%CPU`, executable name) right after it. | +| `top` | Only when `ms.total` is over 1 s, or the switch timed out or was killed: the three busiest processes (`%CPU`, executable name) right after it. | The branch costs nothing to record: the switch scripts already end in `return "found-by-tty"` and the like, and `osascript` prints that value. cmux matches in JavaScript, so each layer names itself. No script and no matching order changed. @@ -744,8 +752,10 @@ It prints p50/p90 (50th and 90th percentile) per step and for the total — for How to read the tables: -- **`n` is the number of records in the row; a cell ending in `(k)` covers only `k` of them.** Not every record has every step: a resume has no `detect`, and a timed-out switch has no `run`, `main` or `total`. Timed-out switches are counted in the first line of the report and are never part of those three percentiles. -- **Accounts.** `(none)` is a record whose row had no account label; `(unknown)` is a version 1 line, which did not record one. +- **`n` is the number of records in the row; a cell ending in `(k)` covers only `k` of them.** Not every record has every step: a resume has no `detect`. And `run`, `main` and `total` are over completed switches only. Four kinds of record are left out of those three percentiles and counted in the first line of the report instead: timed out, killed by their timeout, failed (`ok` false), and not timed end to end (`untimed`). +- **Accounts.** `(none)` is a record for which no account was resolved; `(unknown)` is a version 1 line, which did not record one. +- **Lines of the wrong shape are malformed.** A line counts as a record only if it is an object, its `ms` is an object, and every text field (`kind`, `terminal`, `branch`, `account`, `sessionId`, `title`, `project` and the like) is a string, `null` or absent. One wrong-typed field makes the whole line malformed. +- **A log that exists but cannot be read makes the report incomplete**, and the script says so on stderr and in the report's first line, and exits 1. A log that does not exist is not an error: the rotated file is optional. Under `--redact` an input is named by its position (`input 2`), never by its path. - **Session labels** are the first 8 characters of the id, or more when two sessions would otherwise share a label. Under `--redact` they are the placeholders, never shortened. Only the title is cut (40 characters). - **Control characters are removed from everything printed**, with or without `--redact`: a title is free text, and an escape sequence or a line break in one could otherwise drive the terminal or forge a row. diff --git a/scripts/switch-timing-summary.js b/scripts/switch-timing-summary.js index 3ac6920..b12e67d 100644 --- a/scripts/switch-timing-summary.js +++ b/scripts/switch-timing-summary.js @@ -13,9 +13,10 @@ * first); then the total against machine load. Plain Node, no dependencies. * A line that is not a record is counted and skipped; a missing or empty * file is reported, not an error. Version 1 lines, which did not name their - * session, count everywhere except the per-session table. A switch whose - * command timed out is counted, and left out of the percentiles of the - * steps it never finished. + * session, count everywhere except the per-session table. A switch that + * did not complete — its command timed out, was killed by its timeout or + * failed — and one handed to an app the log does not follow are counted, + * and left out of the percentiles of the steps that end at the exit. * * The log names sessions: id, title, account label and project path. A * title is the user's `/rename` name or, without one, the summary of the @@ -38,18 +39,33 @@ const path = require('path'); /** Steps in path order; `total` is what the user waited. */ const STEPS = ['clickToIpc', 'settings', 'detect', 'build', 'spawn', 'run', 'main', 'total']; -/** Steps that end at the command's exit, which a timed-out switch never reached. */ +/** Steps that end at the command's exit: they mean something only for a switch that completed. */ const NEEDS_EXIT = new Set(['run', 'main', 'total']); const isNum = (v) => typeof v === 'number' && Number.isFinite(v); /** - * One step of one record, or null when it has no measured value. A - * timed-out switch has none for the steps that end at the exit — whatever - * the line says: a deadline is not a duration. + * A path the log does not follow to the end (VS Code, Claude Desktop, the + * embedded terminal): flagged `untimed`, or, on a line written before the + * flag existed, recognisable by its tool. + */ +const isUntimed = (r) => r.untimed === true || r.tool === 'open' || r.tool === 'pty'; + +/** + * Did the switch complete, with its command seen to exit normally? Not when + * it timed out (no exit was seen), was killed by its timeout (the wait is + * real, the switch did not happen), failed, or is untimed. + */ +const completed = (r) => + r.timedOut !== true && r.killed !== true && r.ok !== false && !isUntimed(r); + +/** + * One step of one record, or null when it has no measured value. Only a + * completed switch has one for the steps that end at the exit — whatever + * the line says: a deadline or a kill is not the duration of a switch. */ const stepValue = (r, step) => { - if (r.timedOut === true && NEEDS_EXIT.has(step)) return null; + if (NEEDS_EXIT.has(step) && !completed(r)) return null; const v = r.ms ? r.ms[step] : null; return isNum(v) ? v : null; }; @@ -86,7 +102,41 @@ const pearson = (pairs) => { return sxy / Math.sqrt(sxx * syy); }; -/** Records from JSONL text. Anything that is not an object with an `ms` object is skipped and counted. */ +/** Fields read as text: grouped on, compared, or printed. */ +const TEXT_FIELDS = [ + 'ts', + 'via', + 'kind', + 'terminal', + 'configured', + 'tool', + 'branch', + 'order', + 'sessionId', + 'sid', + 'title', + 'account', + 'project', + 'tty', + 'ttySrc', +]; + +const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); + +/** + * A line this script can summarize: an object whose `ms` is an object, and + * whose text fields are each a string, null or absent. One rule for all of + * them: a field of the wrong type makes the whole line malformed, rather + * than each use having to defend itself (`String()` of an object with a + * broken `toString` throws). Numbers need no such rule: every numeric read + * goes through `isNum`. + */ +const isRecord = (r) => + isPlainObject(r) && + isPlainObject(r.ms) && + TEXT_FIELDS.every((k) => r[k] === undefined || r[k] === null || typeof r[k] === 'string'); + +/** Records from JSONL text. A line that is not a record (see `isRecord`) is skipped and counted. */ const parseLines = (text) => { const records = []; let malformed = 0; @@ -94,7 +144,7 @@ const parseLines = (text) => { if (!line.trim()) continue; try { const r = JSON.parse(line); - if (r && typeof r === 'object' && r.ms && typeof r.ms === 'object') records.push(r); + if (isRecord(r)) records.push(r); else malformed++; } catch { malformed++; @@ -256,7 +306,9 @@ const summarize = (records, opts = {}) => { return { count: records.length, timedOut: records.filter((r) => r.timedOut === true).length, + killed: records.filter((r) => r.killed === true).length, failed: records.filter((r) => r.ok === false).length, + untimed: records.filter(isUntimed).length, slow: records.filter((r) => isNum(total(r)) && total(r) > 1000).length, all: stepStats(records), byKind: groupBy(records, (r) => String(r.kind ?? 'unknown')), @@ -285,10 +337,13 @@ const summarize = (records, opts = {}) => { // --- printing --- // C0 controls, DEL, C1 controls, the two Unicode line separators, and the -// bidirectional overrides and isolates. ESC and CSI start the sequences a -// terminal obeys (move the cursor, set the window title, write the -// clipboard); a line break forges a row; a bidi override reorders one. -const UNSAFE_CHARS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g; +// bidirectional controls: the overrides and isolates, and the three marks +// (Arabic letter mark U+061C, left-to-right U+200E, right-to-left U+200F). +// ESC and CSI start the sequences a terminal obeys (move the cursor, set +// the window title, write the clipboard); a line break forges a row; a +// bidi control reorders one. +const UNSAFE_CHARS = + /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g; /** * Any value as text that is safe to print: the characters above are @@ -315,7 +370,14 @@ const clip = (s, w) => { */ const renderTable = (headers, rows, align = []) => { const all = [headers, ...rows].map((row) => row.map(safeText)); - const widths = headers.map((_, i) => Math.max(...all.map((row) => textLength(row[i] ?? '')))); + // A loop, not `Math.max(...)`: the rows are as many as the log has + // sessions, and a call takes only so many arguments. + const widths = headers.map(() => 0); + for (const row of all) { + for (let i = 0; i < widths.length; i++) { + widths[i] = Math.max(widths[i], textLength(row[i] ?? '')); + } + } return all .map((row) => { const cells = row.map((cell, i) => { @@ -374,7 +436,8 @@ const tildePath = (p, home) => { */ const sessionLabels = (ids, redacted) => { if (redacted) return new Map(ids.map((id) => [id, id])); - const longest = Math.max(SESSION_ID_MIN, ...ids.map((id) => id.length)); + let longest = SESSION_ID_MIN; + for (const id of ids) longest = Math.max(longest, id.length); for (let len = SESSION_ID_MIN; len <= longest; len++) { const labels = ids.map((id) => id.slice(0, len)); if (new Set(labels).size === new Set(ids).size) return new Map(ids.map((id, i) => [id, labels[i]])); @@ -429,14 +492,16 @@ const formatReport = (summary, malformed = 0, opts = {}) => { ...(opts.redact ? ['Redacted: session ids, titles, account labels and project paths are placeholders.'] : []), - `${s.count} switches · ${s.slow} over 1 s · ${s.timedOut} timed out · ${s.failed} failed` + + `${s.count} switches · ${s.slow} over 1 s · ${s.timedOut} timed out · ${s.killed} killed by their timeout · ${s.failed} failed · ${s.untimed} not timed end to end` + (malformed ? ` · ${malformed} malformed line(s) skipped` : ''), 'Cells are p50/p90 in ms. Steps: clickToIpc (renderer → main), settings, detect', '(which terminal), build (script text), spawn (write + start), run (the external', 'command), main (IPC → done), total (click → done).', 'n is the records in the row. A cell ending in (k) is over only k of them: the', - 'rest have no value for that step (a resume does not detect; a timed-out switch', - 'has no run, main or total).', + 'rest have no value for that step. A resume does not detect. run, main and total', + 'are over completed switches only: not one that timed out, was killed by its', + 'timeout or failed, and not one handed to VS Code, Claude Desktop or the embedded', + 'terminal (not timed end to end).', '', stepTable('All', '', [{ key: 'all', n: s.count, steps: s.all }]), '', @@ -471,19 +536,34 @@ const defaultFiles = () => { return [`${base}.1`, base]; }; +/** + * The files' text, and the inputs that gave none, by position in `files`: + * `missing` do not exist; `unreadable` exist and could not be read (no + * permission, a directory), with the error code. The two are different + * findings: a log that is not there has nothing to add, one that could not + * be read makes the report incomplete. + */ const readFiles = (files) => { let text = ''; const missing = []; - for (const f of files) { + const unreadable = []; + files.forEach((f, index) => { try { text += `${fs.readFileSync(f, 'utf-8')}\n`; - } catch { - missing.push(f); + } catch (err) { + if (err && err.code === 'ENOENT') missing.push(index); + else unreadable.push({ index, code: (err && err.code) || 'error' }); } - } - return { text, missing }; + }); + return { text, missing, unreadable }; }; +/** A line on the report itself, so a pasted copy says it too. */ +const incompleteNote = (unreadable) => + unreadable.length > 0 + ? `Incomplete: ${unreadable.length} input file(s) exist but could not be read.` + : null; + /** Flags and files from the command line; an unknown flag is an error, not a file name. */ const parseArgs = (argv) => { const opts = { redact: false, all: false, sort: 'n', files: [], bad: [] }; @@ -507,9 +587,21 @@ const main = (argv) => { } const explicit = opts.files.length > 0; const files = explicit ? opts.files : defaultFiles(); - const { text, missing } = readFiles(files); - // The rotated file is optional; only a file the user named is worth a note. - if (explicit) for (const f of missing) console.error(`cannot read ${safeText(f)}`); + const { text, missing, unreadable } = readFiles(files); + // A path can name a project or a user: a redacted run says which input, not where it is. + const nameOf = (index) => (opts.redact ? `input ${index + 1}` : safeText(files[index])); + // The rotated file is optional; only a file the user named is worth a note when absent. + if (explicit) for (const i of missing) console.error(`cannot read ${nameOf(i)}: no such file`); + // A file that is there and cannot be read is always worth one: the default + // run would otherwise print one half of the log as if it were all of it. + for (const u of unreadable) { + console.error(`cannot read ${nameOf(u.index)} (${safeText(u.code)}): the report is incomplete`); + } + const note = incompleteNote(unreadable); + if (note) { + console.log(note); + process.exitCode = 1; + } const { records, malformed } = parseLines(text); const shown = opts.redact ? redactRecords(records) : records; console.log(formatReport(summarize(shown, opts), malformed, opts)); @@ -528,6 +620,7 @@ module.exports = { sessionLabels, branchMix, redactRecords, + readFiles, parseArgs, safeText, clip, diff --git a/src/claude-session-utility.ts b/src/claude-session-utility.ts index fe14b29..edd8d42 100644 --- a/src/claude-session-utility.ts +++ b/src/claude-session-utility.ts @@ -1489,11 +1489,15 @@ const buildResumeCommand = ( // call site that forgot to pass it must be a type error rather than a // session that silently keeps writing to the wrong memory directory. projectPath: string, + // Timing log only: this is where a resume's account is decided, so this + // is where the log learns it (it can differ from the label passed in). + timing?: SwitchTiming, ): string => { const { configDirEnv: configDir, account } = resumeAccountFor( sessionId, accountLabel, ); + timing?.set({ account: account?.label ?? null }); // Single-quote the value: some terminal injections (Ghostty `initial input`) // don't escape the command, so a double-quoted prefix would break their // AppleScript string. Single quotes are safe across all terminals + handle spaces. @@ -1729,7 +1733,7 @@ export const runCommandInTerminal = ( `osascript ${tmpScript}`, { encoding: 'utf-8', timeout: 5000 }, (error: any) => { - timing?.exited(); + timing?.exited(undefined, !!error?.killed); try { fs.unlinkSync(tmpScript); } catch {} @@ -2172,12 +2176,12 @@ export const openSessionInITerm2 = async ( fs.writeFileSync(tmpScript, switchScript); timing?.spawned(); exec(`osascript ${tmpScript}`, { encoding: 'utf-8' }, (error: any, stdout: string) => { - timing?.exited(stdout); + timing?.exited(stdout, !!error?.killed); console.log(`[iTerm2] switch result: ${(stdout || '').trim()}`, error?.message || ''); try { fs.unlinkSync(tmpScript); } catch {} }); } else { - const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); + const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath, timing); return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'iterm2', terminalMode, timing); } }; @@ -2824,7 +2828,7 @@ export const openSessionInGhostty = async ( fs.writeFileSync(tmpScript, switchScript); timing?.spawned(); exec(`osascript ${tmpScript}`, { encoding: 'utf-8', timeout: 5000 }, (error: any, stdout: string) => { - timing?.exited(stdout); + timing?.exited(stdout, !!error?.killed); const result = (stdout || '').trim(); console.log('[ghostty] switch result:', result, error?.message || ''); if (result === 'not found') { @@ -2833,7 +2837,7 @@ export const openSessionInGhostty = async ( try { fs.unlinkSync(tmpScript); } catch {} }); } else { - const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); + const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath, timing); return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'ghostty', terminalMode, timing); } }; @@ -2872,12 +2876,12 @@ export const openSessionInTerminalApp = async ( fs.writeFileSync(tmpScript, switchScript); timing?.spawned(); exec(`osascript ${tmpScript}`, { encoding: 'utf-8', timeout: 5000 }, (error: any, stdout: string) => { - timing?.exited(stdout); + timing?.exited(stdout, !!error?.killed); console.log(`[Terminal.app] switch result: ${(stdout || '').trim()}`, error?.message || ''); try { fs.unlinkSync(tmpScript); } catch {} }); } else { - const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); + const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath, timing); return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'terminal', terminalMode, timing); } }; @@ -3035,7 +3039,7 @@ export const openSessionInCmux = async ( exec('osascript -e \'tell application "cmux" to activate\''); })().finally(() => timing?.exited()); } else { - const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); + const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath, timing); // The cmux launch is several CLI calls behind one promise; time it whole. timing?.mark('script'); timing?.set({ tool: 'cmux-cli', branch: 'new-workspace' }); diff --git a/src/main.ts b/src/main.ts index 7dac7d1..54b976d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2883,7 +2883,8 @@ ipcMain.on( typeof accountLabel === 'string' && findAccountByLabel(accountLabel) ? accountLabel : undefined; - // The log gets the label the launch gets, not the renderer's raw one. + // The log starts from the label the launch is given, not the renderer's + // raw one; a resume replaces it with the account it actually runs under. timing?.set({ account: label ?? null }); openSession( sessionId, diff --git a/src/switch-timing-log.ts b/src/switch-timing-log.ts index 70901d5..fb21871 100644 --- a/src/switch-timing-log.ts +++ b/src/switch-timing-log.ts @@ -8,11 +8,16 @@ * summary of the conversation that Claude Code generated; the prompts and * the transcript text themselves are not written. * - * On the switch's path this costs one `os.cpus()` read, one - * `process.cpuUsage()` and a few clock reads. Everything that spawns or + * What this costs in the main process, all of it synchronous and none of + * it a spawn or a disk access: when the IPC arrives, one `os.cpus()`, one + * `process.cpuUsage()` and two clock reads; a clock read per mark along the + * way; and when the record closes — in the callback of the command's exit, + * or as `openSession` settles — one more `os.cpus()`, one `os.loadavg()` + * and one `process.cpuUsage()`. Everything that spawns or * touches the disk — `sysctl` for memory pressure, a `ps` for the tty when * the last live-sessions report did not have it, another `ps` for the - * busiest processes after a slow or timed-out switch, the append itself — + * busiest processes after a slow, timed-out or killed switch, the append + * itself — * runs after the switch has finished, and a failure in any of it is * dropped: the switch has already happened. * @@ -84,12 +89,17 @@ export const resetLiveReportNote = (): void => { // --- append with rotation --- -/** Owner-only, whatever the file was created as. A missing file is fine. */ -const makeOwnerOnly = async (filePath: string): Promise => { +/** + * Owner-only, whatever the file was created as. A missing file is fine: + * there is nothing to fix. Any other failure is returned as false — the + * file exists and could not be made owner-only. + */ +const makeOwnerOnly = async (filePath: string): Promise => { try { await fs.promises.chmod(filePath, 0o600); - } catch { - // Not there, or not ours to change: the append below decides. + return true; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code === 'ENOENT'; } }; @@ -101,6 +111,11 @@ const makeOwnerOnly = async (filePath: string): Promise => { * `mode` of an append applies to a new file only, so a log that an earlier * build (or anything else) left group- or world-readable would stay so, and * rotation would carry that mode over to `.1`. + * + * If the log exists and cannot be made owner-only, this throws and the + * line is not written: a record names a session, and the rule is that it + * goes into an owner-only file or nowhere. (A `.1` that cannot be fixed + * does not stop the append: nothing is being written to it.) */ export const appendSwitchLogLine = async ( filePath: string, @@ -116,7 +131,9 @@ export const appendSwitchLogLine = async ( } const data = line.endsWith('\n') ? line : `${line}\n`; // Before the rename, so the rotated file is already owner-only. - await makeOwnerOnly(filePath); + if (!(await makeOwnerOnly(filePath))) { + throw new Error('switch timing log is not owner-only and could not be made so'); + } if (shouldRotate(size, Buffer.byteLength(data), maxBytes)) { await fs.promises.rename(filePath, `${filePath}.1`); } @@ -188,6 +205,10 @@ export const startSwitchTiming = ( const onFinish = (snap: SwitchSnapshot) => { // The samples that describe the span are taken at its end, at once; // the rest waits for the event loop to be free of the switch. + // One reference to the live report: the count, its age and (in the + // deferred write) the tty must all come from the same report, and a + // newer one may replace `lastLive` before that write runs. + const live = lastLive; let sys: SwitchSystemSample = {}; try { sys = { @@ -195,33 +216,37 @@ export const startSwitchTiming = ( cpuPct: cpuPercentBetween(cpusBefore, os.cpus()), ncpu: cpusBefore.length, mainCpuMicros: process.cpuUsage(cpuUsageBefore), - claudeProcs: lastLive ? lastLive.count : null, - liveAgeMs: lastLive ? Date.now() - lastLive.at : null, + claudeProcs: live ? live.count : null, + liveAgeMs: live ? Date.now() - live.at : null, }; } catch { // A record without system figures is still a record. } setImmediate(() => { - void writeRecord(snap, sys).catch(() => deps.onWritten?.(null)); + void writeRecord(snap, sys, live).catch(() => deps.onWritten?.(null)); }); }; - const writeRecord = async (snap: SwitchSnapshot, sys: SwitchSystemSample) => { + const writeRecord = async ( + snap: SwitchSnapshot, + sys: SwitchSystemSample, + live: typeof lastLive, + ) => { const ms = stepDurations(snap, stamp, ipc); const sysctl = deps.sysctl ?? (() => run('sysctl', ['-n', 'vm.swapusage', 'kern.memorystatus_vm_pressure_level'], 2000)); const psTop = deps.psTop ?? (() => run('ps', ['-A', '-o', '%cpu=,comm='], 3000)); - // The tty the last live-sessions report gave this pid, when it has - // one; otherwise one `ps`, here, after the switch. - const knownTty = pid !== null ? lastLive?.ttys.get(pid) ?? null : null; + // The tty that live-sessions report gave this pid, when it has one; + // otherwise one `ps`, here, after the switch. + const knownTty = pid !== null ? live?.ttys.get(pid) ?? null : null; const psTty = deps.psTty ?? ((p: number) => run('ps', ['-o', 'tty=', '-p', String(p)], 1000)); const [sysctlOut, psOut, ttyOut] = await Promise.all([ sysctl().catch(() => ''), - isSlowSwitch(ms, snap.timedOut) ? psTop().catch(() => '') : Promise.resolve(null), + isSlowSwitch(ms, snap.timedOut || snap.killed === true) ? psTop().catch(() => '') : Promise.resolve(null), pid !== null && !knownTty ? psTty(pid).catch(() => '') : Promise.resolve(null), ]); const tty = knownTty ?? parseTty(ttyOut); diff --git a/src/switch-timing.test.ts b/src/switch-timing.test.ts index 1fbda51..1204409 100644 --- a/src/switch-timing.test.ts +++ b/src/switch-timing.test.ts @@ -1,7 +1,8 @@ +import { spawnSync } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { branchFromSwitchOutput, @@ -9,6 +10,7 @@ import { cpuPercentBetween, createSwitchTiming, isSlowSwitch, + isUntimed, parseTopCpu, parseTty, sanitizeStamp, @@ -116,6 +118,30 @@ describe('createSwitchTiming', () => { expect(h.finished[0].ok).toBe(false); }); + it('carries the kill of a command stopped by its timeout, and only that', () => { + const killed = harness(); + killed.timing.spawned(); + killed.timing.settle(true); + killed.advance(5000); + killed.timing.exited('', true); + expect(killed.finished[0]).toMatchObject({ killed: true, timedOut: false, exitedAt: 5000 }); + // An ordinary exit, with or without the argument, is not a kill. + const normal = harness(); + normal.timing.spawned(); + normal.timing.exited('found-by-tty', false); + normal.timing.settle(true); + expect(normal.finished[0].killed).toBe(false); + }); + + it('lets the launch replace the account main set first', () => { + // main sets the row's label; a resume then sets the account it runs under. + const h = harness(); + h.timing.set({ account: 'from-the-row', configured: 'iterm2' }); + h.timing.set({ account: 'from-history' }); + h.timing.settle(true); + expect(h.finished[0].facts).toMatchObject({ account: 'from-history', configured: 'iterm2' }); + }); + it('measures from the origin it is given, not from its own creation', () => { // The caller read the clock at 90, then spent 10 ms setting up. let now = 100; @@ -261,10 +287,36 @@ describe('stepDurations', () => { expect(timedOut.spawn).toBe(4); expect(timedOut.clickToIpc).toBeNull(); // Without a stamp the total is main's own span, not a guess. - const noStamp = stepDurations(snap({ marks: { returned: 5 }, endedAt: 5 }), undefined, ipc); + const noStamp = stepDurations( + snap({ marks: { returned: 5 }, spawnedAt: 1, exitedAt: 5, endedAt: 5 }), + undefined, + ipc, + ); expect(noStamp.total).toBe(5); }); + it('gives no end-to-end time to a path that starts no command', () => { + // VS Code, Claude Desktop, the embedded terminal: `openSession` returns + // after handing over, long before anything is switched. + const handedOver = snap({ marks: { settings: 2, returned: 6 }, endedAt: 6 }); + expect(isUntimed(handedOver)).toBe(true); + const ms = stepDurations(handedOver, stamp, ipc); + expect(ms).toMatchObject({ run: null, main: null, total: null, returned: 6, settings: 2 }); + expect(ms.clickToIpc).toBe(10); + expect(isSlowSwitch(ms)).toBe(false); + expect(isUntimed(snap({ spawnedAt: 3, exitedAt: 9 }))).toBe(false); + }); + + it('keeps the measured wait of a killed command', () => { + // Unlike the no-exit deadline, the ~5 s here was really waited. + const ms = stepDurations( + snap({ marks: { returned: 4 }, spawnedAt: 3, exitedAt: 5003, killed: true }), + undefined, + ipc, + ); + expect(ms).toMatchObject({ run: 5000, main: 5003, total: 5003 }); + }); + it('counts a timed-out switch as slow although it has no total', () => { const fast = stepDurations(snap({ marks: { returned: 5 }, endedAt: 5 }), undefined, ipc); expect(isSlowSwitch(fast)).toBe(false); @@ -281,7 +333,11 @@ describe('stepDurations', () => { it('does not let a renderer clock that runs ahead shorten the total', () => { const ahead = { ...stamp, wallMs: ipc.wallMs + 50 }; - const ms = stepDurations(snap({ marks: { returned: 20 }, endedAt: 20 }), ahead, ipc); + const ms = stepDurations( + snap({ marks: { returned: 20 }, spawnedAt: 1, exitedAt: 20, endedAt: 20 }), + ahead, + ipc, + ); expect(ms.clickToIpc).toBe(-50); // kept as measured expect(ms.total).toBe(20); }); @@ -384,7 +440,7 @@ describe('the log file', () => { } = {}, session: Parameters[0] = SESSION, // What main does once it has validated the row's label; `never` hangs the command. - { account = 'second' as string | null, exits = true } = {}, + { account = 'second' as string | null, exits = true, killed = false } = {}, ) => new Promise | null>((resolve) => { const timing = startSwitchTiming( @@ -406,7 +462,7 @@ describe('the log file', () => { timing.mark('script'); timing.spawned(); timing.settle(true); - if (exits) timing.exited('found-by-title\n'); + if (exits) timing.exited(killed ? '' : 'found-by-title\n', killed); }); it('writes one line per switch, naming the session it was', async () => { @@ -497,8 +553,92 @@ describe('the log file', () => { expect(ms.run).toBeNull(); expect(ms.main).toBeNull(); expect(ms.total).toBeNull(); - expect(ms.returned).toBeGreaterThanOrEqual(0); - expect(ms.returned).toBeLessThan(20); // measured, not the deadline + // Measured (the collector's own clock decides how long; see the + // controlled-clock test of `stepDurations` for the exact value). + expect(typeof ms.returned).toBe('number'); + }); + + it('marks a killed command: not ok, sampled as slow, however short the wait', async () => { + let psCalls = 0; + const record = await runSwitch( + undefined, + { + psTop: async () => { + psCalls++; + return ' 55.0 /usr/bin/osascript\n'; + }, + }, + SESSION, + { killed: true }, + ); + // `openSession` had resolved (the running-session paths return at once). + expect(record).toMatchObject({ killed: true, ok: false, timedOut: false, untimed: false, branch: null }); + expect(psCalls).toBe(1); + expect(record.top).toEqual([{ cpu: 55, comm: 'osascript' }]); + expect(typeof (record.ms as { run: unknown }).run).toBe('number'); + }); + + it('marks a normal switch as neither killed nor untimed', async () => { + const record = await runSwitch(undefined); + expect(record).toMatchObject({ killed: false, untimed: false, ok: true }); + }); + + it('takes the count, its age and the tty from one live report, even if a newer one arrives', async () => { + noteLiveReport({ live: [{ pid: 4242, tty: 'ttys011' }, { pid: 1, tty: 'ttys001' }] }); + const record = await runSwitch(undefined, { + // A newer report lands while the deferred write is waiting on sysctl. + sysctl: async () => { + noteLiveReport({ live: [{ pid: 4242, tty: 'ttys099' }] }); + return ''; + }, + psTty: async () => 'ttys077\n', + }); + expect(record).toMatchObject({ claudeProcs: 2, tty: 'ttys011', ttySrc: 'live-report' }); + }); + + it('drops the record when an existing log cannot be made owner-only', async () => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, 'old line\n'); + const eperm = Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); + const chmod = vi.spyOn(fs.promises, 'chmod').mockRejectedValue(eperm); + try { + await expect(appendSwitchLogLine(file, 'new line', 1000)).rejects.toThrow(/owner-only/); + // Through the whole path too: the write is reported as dropped, not thrown. + expect(await runSwitch(undefined)).toBeNull(); + } finally { + chmod.mockRestore(); + } + expect(fs.readFileSync(file, 'utf-8')).toBe('old line\n'); + }); + + it('still creates a missing log, owner-only: nothing to fix is not a failure', async () => { + const chmod = vi.spyOn(fs.promises, 'chmod'); + try { + await appendSwitchLogLine(file, 'first line', 1000); + // The chmod of the absent file failed with ENOENT, and that was fine. + await expect(chmod.mock.results[0].value).rejects.toMatchObject({ code: 'ENOENT' }); + } finally { + chmod.mockRestore(); + } + expect(fs.readFileSync(file, 'utf-8')).toBe('first line\n'); + expect(fs.statSync(file).mode & 0o777).toBe(0o600); + }); + + it('writes on when only the rotated copy cannot be fixed', async () => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, 'old line\n'); + fs.writeFileSync(`${file}.1`, 'older\n'); + const real = fs.promises.chmod.bind(fs.promises); + const eperm = Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); + const chmod = vi + .spyOn(fs.promises, 'chmod') + .mockImplementation((p, mode) => (String(p).endsWith('.1') ? Promise.reject(eperm) : real(p, mode))); + try { + await appendSwitchLogLine(file, 'new line', 1000); + } finally { + chmod.mockRestore(); + } + expect(fs.readFileSync(file, 'utf-8')).toBe('old line\nnew line\n'); }); it('makes an existing log and its rotated copy owner-only, not just a new one', async () => { @@ -939,6 +1079,9 @@ describe('scripts/switch-timing-summary.js', () => { expect(report.split('\n').some((l) => /^\s*fake/.test(l))).toBe(false); expect(summary.safeText(`a${ESC}[31mb\u009b\u007fc\n`)).toBe('a[31mbc'); expect(summary.safeText(null)).toBe(''); + // The three direction marks: invisible, and they reorder what follows. + const marks = [0x061c, 0x200e, 0x200f].map((c) => String.fromCharCode(c)).join(''); + expect(summary.safeText(`a${marks}b`)).toBe('ab'); // Same for --redact, whose placeholders are safe but whose other fields are the log's. const redacted: string = summary.formatReport( summary.summarize(summary.redactRecords([hostile, clean])), @@ -1001,6 +1144,112 @@ describe('scripts/switch-timing-summary.js', () => { expect(session).toContain('350/486 (3)'); }); + it('counts a line with a wrong-typed field as malformed, by one rule for every text field', () => { + const good = { v: 2, kind: 'switch', terminal: 'iterm2', branch: null, ms: { total: 5, run: 4 } }; + const bad = [ + { ...good, kind: { toString: null } }, // String() of this throws + { ...good, terminal: 7 }, + { ...good, branch: ['tty'] }, + { ...good, account: {} }, + { ...good, sessionId: 12345 }, + { ...good, title: true }, + { ...good, project: { path: '/x' } }, + { ...good, tty: 4 }, + { ...good, sid: [] }, + { ...good, ms: [] }, // an array is not a set of steps + { ...good, ms: 'fast' }, + [good], + ]; + const text = [good, ...bad].map((r) => JSON.stringify(r)).join('\n'); + const { records, malformed } = summary.parseLines(text); + expect(records).toEqual([good]); + expect(malformed).toBe(bad.length); + // And what is accepted cannot make the report throw. + expect(() => summary.formatReport(summary.summarize(records), malformed, {})).not.toThrow(); + }); + + it('keeps switches that did not complete out of run, main and total, and counts each kind', () => { + const rec = (over: Record, ms: Record) => ({ + v: 2, + sessionId: 'one', + kind: 'switch', + terminal: 'ghostty', + tool: 'osascript', + branch: 'tty', + ms: { settings: 1, ...ms }, + ...over, + }); + const records = [ + rec({}, { run: 100, main: 110, total: 120 }), + rec({}, { run: 300, main: 310, total: 320 }), + // Killed at the 5 s limit: a real wait, not a switch. + rec({ killed: true, ok: false, branch: null }, { run: 5000, main: 5010, total: 5020 }), + // A launch that failed. + rec({ ok: false }, { run: 900, main: 910, total: 920 }), + // Handed to another app: flagged, and an older line recognised by its tool. + rec({ untimed: true, tool: 'open', terminal: 'vscode' }, { returned: 3, main: null, total: null }), + rec({ tool: 'pty', terminal: 'codev' }, { returned: 2, main: 2, total: 4 }), + ]; + const s = summary.summarize(records); + expect(s).toMatchObject({ count: 6, killed: 1, failed: 2, untimed: 2, timedOut: 0, slow: 0 }); + expect(s.all.total).toEqual({ n: 2, p50: 220, p90: 300 }); + expect(s.all.run).toEqual({ n: 2, p50: 200, p90: 280 }); + expect(s.all.main.n).toBe(2); + // Steps before the exit are still everyone's. + expect(s.all.settings.n).toBe(6); + expect(s.runShareP50).toBeCloseTo((100 / 120 + 300 / 320) / 2, 10); + const report: string = summary.formatReport(s, 0, {}); + expect(report).toContain('1 killed by their timeout'); + expect(report).toContain('2 not timed end to end'); + }); + + it('survives a log with more sessions than a call takes arguments', () => { + // `Math.max(...rows)` throws RangeError somewhere past 100k arguments. + const n = 300_000; + const ids = Array.from({ length: n }, (_, i) => `id-${String(i).padStart(8, '0')}`); + const labels = summary.sessionLabels(ids, false); + expect(labels.size).toBe(n); + expect(labels.get(ids[n - 1])).toBe(ids[n - 1]); + const table: string = summary.renderTable( + ['a', 'b'], + ids.map((id) => [id, 'x']), + ); + expect(table.split('\n')).toHaveLength(n + 1); + }); + + it('tells a missing input from one that exists and cannot be read', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'switch-summary-')); + try { + const good = path.join(dir, 'good.jsonl'); + fs.writeFileSync(good, '{"ms":{"total":5}}\n'); + const missing = path.join(dir, 'nope.jsonl'); + const unreadable = path.join(dir, 'a-directory'); // reading it fails with EISDIR + fs.mkdirSync(unreadable); + const r = summary.readFiles([missing, unreadable, good]); + expect(r.missing).toEqual([0]); + expect(r.unreadable).toEqual([{ index: 1, code: 'EISDIR' }]); + expect(summary.parseLines(r.text).records).toHaveLength(1); + + // The default run: `.1` readable, the live log not. It must say so. + const script = path.join(__dirname, '..', 'scripts', 'switch-timing-summary.js'); + const plain = spawnSync(process.execPath, [script, good, unreadable], { encoding: 'utf-8' }); + expect(plain.status).toBe(1); + expect(plain.stderr).toContain(`cannot read ${unreadable} (EISDIR): the report is incomplete`); + expect(plain.stdout).toContain('Incomplete: 1 input file(s) exist but could not be read.'); + expect(plain.stdout).toContain('1 switches'); + + // Redacted: the input is named by position, never by path. + const redacted = spawnSync(process.execPath, [script, '--redact', good, unreadable, missing], { + encoding: 'utf-8', + }); + expect(redacted.stderr).toContain('cannot read input 2 (EISDIR)'); + expect(redacted.stderr).toContain('cannot read input 3: no such file'); + expect(redacted.stderr + redacted.stdout).not.toContain(dir); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + it('parses flags apart from files and rejects an unknown one', () => { expect(summary.parseArgs(['--redact', 'a.jsonl', '--sort=p90', '--all'])).toMatchObject({ redact: true, diff --git a/src/switch-timing.ts b/src/switch-timing.ts index 7177ea6..2dc2c09 100644 --- a/src/switch-timing.ts +++ b/src/switch-timing.ts @@ -70,9 +70,12 @@ export interface SwitchFacts { /** Whether the script carried a title block at all (the row had a title). */ hasTitle?: boolean; /** - * The row's account label once main has checked that an account carries - * it — the same value the launch is given. Null: the row had none, or - * named an account that does not exist. + * The account of this switch. For a resume it is the account the launch + * runs under, set where that is decided (`buildResumeCommand`): history's + * account for a session history knows, else the row's label. A switch to + * a running session launches nothing, so it keeps what main set: the + * row's label, once checked that an account carries it. Null: no account + * was resolved. */ account?: string | null; } @@ -103,6 +106,11 @@ export interface SwitchSnapshot { ok: boolean; /** True when the external command had not exited by the safety deadline. */ timedOut: boolean; + /** + * True when the command did exit, but only because its caller's own + * timeout killed it. Its times are real waits, not a completed switch. + */ + killed?: boolean; } export interface SwitchTiming { @@ -112,9 +120,10 @@ export interface SwitchTiming { spawned(): void; /** * It exited. `stdout`, when the command is a switch script, names the - * branch that matched. + * branch that matched. `killed` is the callback's `error.killed`: the + * command was stopped by its timeout instead of finishing. */ - exited(stdout?: string): void; + exited(stdout?: string, killed?: boolean): void; /** * `openSession` settled. The record closes now if nothing is still * running, otherwise when it exits (or at the safety deadline). @@ -168,6 +177,7 @@ export const createSwitchTiming = (deps: SwitchTimingDeps): SwitchTiming => { let running = 0; let settled = false; let ok = true; + let killed = false; let finished = false; let timer: unknown = null; const since = () => deps.now() - t0; @@ -191,6 +201,7 @@ export const createSwitchTiming = (deps: SwitchTimingDeps): SwitchTiming => { facts: { ...facts }, ok, timedOut, + killed, }); }; @@ -210,11 +221,12 @@ export const createSwitchTiming = (deps: SwitchTimingDeps): SwitchTiming => { running++; if (spawnedAt === null) spawnedAt = since(); }), - exited: (stdout) => + exited: (stdout, wasKilled) => guard(() => { if (finished) return; running = Math.max(0, running - 1); exitedAt = since(); + if (wasKilled === true) killed = true; if (stdout !== undefined && facts.branch === undefined) { facts = { ...facts, branch: branchFromSwitchOutput(stdout) }; } @@ -301,11 +313,11 @@ export interface SwitchStepMs { /** IPC arrival to `openSession` returning. */ returned: number | null; /** - * IPC arrival to the end: the command's exit, else `openSession` - * returning. Null when the command timed out. + * IPC arrival to the command's exit. Null when there was none to see: + * the command timed out, or the path starts no command (`untimed`). */ main: number | null; - /** `clickToIpc + main`: what the user waited. Null when the command timed out. */ + /** `clickToIpc + main`: what the user waited. Null whenever `main` is. */ total: number | null; } @@ -314,6 +326,15 @@ export interface SwitchStepMs { * before it that this path actually reached, so a path that skips one * (a resume skips `detect`) does not lose the time: it lands in the next. */ +/** + * True for a switch this log cannot time end to end: no command was ever + * started and awaited, so there is no exit to measure to. Those are the + * paths that hand over with a fire-and-forget `open` or a message to the + * renderer; what they do next (VS Code waits 500 ms before its URI + * command, for one) happens out of sight. + */ +export const isUntimed = (snap: SwitchSnapshot): boolean => snap.spawnedAt === null; + export const stepDurations = ( snap: SwitchSnapshot, stamp: RendererStamp | undefined, @@ -322,12 +343,15 @@ export const stepDurations = ( const { marks, spawnedAt, exitedAt } = snap; const afterSettings = marks.settings ?? 0; const beforeScript = marks.detect ?? afterSettings; - // The end is the command's exit, or `openSession` returning on a path - // that runs no command (the collector always marks `returned` before it - // closes). A command that timed out never reported an exit: the record - // then closed at the deadline, which is not a duration of anything, so - // `run`, `main` and `total` stay null and `returned` is what is known. - const end = snap.timedOut ? null : exitedAt ?? marks.returned ?? null; + // The end is the command's exit and nothing else. Two kinds of record + // have none, and for both `run`, `main` and `total` stay null while + // `returned` is what is known: + // - a command that timed out never reported one (the record closed at + // the deadline, which is not a duration of anything); + // - a path that hands the switch to something this log does not follow + // (VS Code, Claude Desktop, the embedded terminal) starts no command, + // so `openSession` returning is not "switched" (see `isUntimed`). + const end = snap.timedOut || isUntimed(snap) ? null : exitedAt; const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n); const clickToIpc = stamp && finite(stamp.wallMs) ? ipc.wallMs - stamp.wallMs : null; const clickToIpcHr = @@ -358,7 +382,7 @@ export interface SwitchSystemSample { /** Running `claude` processes in the last live-sessions report, and its age. */ claudeProcs?: number | null; liveAgeMs?: number | null; - /** Only for a slow or timed-out switch: the busiest processes right after it. */ + /** Only for a slow, timed-out or killed switch: the busiest processes right after it. */ top?: { cpu: number; comm: string }[]; /** The target process's controlling terminal, and where the value came from. */ tty?: string | null; @@ -435,11 +459,12 @@ export const SLOW_SWITCH_MS = 1000; /** * Slow enough to also ask what the machine was busy with. A switch whose - * command never reported back has no total to compare — and is the slowest - * kind there is, so it always counts. + * command never reported back (`timedOut`) has no total to compare, and + * one whose command was killed by its timeout did not finish either: both + * are the slowest kind there is, so `cutShort` always counts. */ -export const isSlowSwitch = (ms: SwitchStepMs, timedOut = false): boolean => - timedOut || (typeof ms.total === 'number' && ms.total > SLOW_SWITCH_MS); +export const isSlowSwitch = (ms: SwitchStepMs, cutShort = false): boolean => + cutShort || (typeof ms.total === 'number' && ms.total > SLOW_SWITCH_MS); export const buildSwitchRecord = ( ctx: SwitchContext, @@ -465,8 +490,11 @@ export const buildSwitchRecord = ( branch: snap.facts.branch ?? null, order: snap.facts.order ?? null, hasTitle: snap.facts.hasTitle ?? null, - ok: snap.ok, + // A command killed by its timeout did not switch, whatever `openSession` returned. + ok: snap.ok && snap.killed !== true, timedOut: snap.timedOut, + killed: snap.killed === true, + untimed: isUntimed(snap), ms, load: (sys.loadavg ?? []).map((n) => Math.round(n * 100) / 100), cpuPct: sys.cpuPct ?? null, From 9d3178bba212d90e0180b1e067a328fe033da461 Mon Sep 17 00:00:00 2001 From: Grimmer Kang Date: Fri, 20 Nov 2026 22:50:41 +0900 Subject: [PATCH 6/7] test(sessions): make two switch timing tests able to fail Mutation checks after the round 2 fix found two tests that passed with their guard removed: the live-report test replaced the report after the tty had already been read, and the summary's killed record was also marked failed, so either rule alone excluded it. Co-Authored-By: Claude Fable 5.2 --- src/switch-timing.test.ts | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/switch-timing.test.ts b/src/switch-timing.test.ts index 1204409..b244283 100644 --- a/src/switch-timing.test.ts +++ b/src/switch-timing.test.ts @@ -585,14 +585,11 @@ describe('the log file', () => { it('takes the count, its age and the tty from one live report, even if a newer one arrives', async () => { noteLiveReport({ live: [{ pid: 4242, tty: 'ttys011' }, { pid: 1, tty: 'ttys001' }] }); - const record = await runSwitch(undefined, { - // A newer report lands while the deferred write is waiting on sysctl. - sysctl: async () => { - noteLiveReport({ live: [{ pid: 4242, tty: 'ttys099' }] }); - return ''; - }, - psTty: async () => 'ttys077\n', - }); + // The record closes synchronously inside runSwitch; its write is deferred. + const pending = runSwitch(undefined, { psTty: async () => 'ttys077\n' }); + // A newer report lands in between: after the count was taken, before the tty is. + noteLiveReport({ live: [{ pid: 4242, tty: 'ttys099' }] }); + const record = await pending; expect(record).toMatchObject({ claudeProcs: 2, tty: 'ttys011', ttySrc: 'live-report' }); }); @@ -1182,8 +1179,9 @@ describe('scripts/switch-timing-summary.js', () => { const records = [ rec({}, { run: 100, main: 110, total: 120 }), rec({}, { run: 300, main: 310, total: 320 }), - // Killed at the 5 s limit: a real wait, not a switch. - rec({ killed: true, ok: false, branch: null }, { run: 5000, main: 5010, total: 5020 }), + // Killed at the 5 s limit: a real wait, not a switch. Excluded for + // being killed, whatever `ok` says. + rec({ killed: true, branch: null }, { run: 5000, main: 5010, total: 5020 }), // A launch that failed. rec({ ok: false }, { run: 900, main: 910, total: 920 }), // Handed to another app: flagged, and an older line recognised by its tool. @@ -1191,7 +1189,7 @@ describe('scripts/switch-timing-summary.js', () => { rec({ tool: 'pty', terminal: 'codev' }, { returned: 2, main: 2, total: 4 }), ]; const s = summary.summarize(records); - expect(s).toMatchObject({ count: 6, killed: 1, failed: 2, untimed: 2, timedOut: 0, slow: 0 }); + expect(s).toMatchObject({ count: 6, killed: 1, failed: 1, untimed: 2, timedOut: 0, slow: 0 }); expect(s.all.total).toEqual({ n: 2, p50: 220, p90: 300 }); expect(s.all.run).toEqual({ n: 2, p50: 200, p90: 280 }); expect(s.all.main.n).toBe(2); From 324488dadf3134f8f87e67b937682bf032170008 Mon Sep 17 00:00:00 2001 From: Grimmer Kang Date: Sat, 21 Nov 2026 00:19:24 +0900 Subject: [PATCH 7/7] docs(sessions): switch timing log, say what the fields do Final review round. Documentation and comments are brought in line with the code; the only code changes are two in the summary script. - killed: set only by the osascript paths that run with a timeout (the iTerm2, Ghostty and Terminal.app resumes, the Ghostty and Terminal.app switches). The cmux paths never set it. A killed record's branch depends on the path. - untimed: the rule is "no command was started and awaited", which also covers a terminal launch that failed before its command started, not only the open and pty paths. - account: only the terminal paths that build a resume command replace the row's validated label. - total: a missing click stamp counts as zero, so total equals main. - The deadline test asserts on a controlled clock that `returned` is the settle time; the real-clock test says why it has no upper bound. Summary script: - The first line's counts are disjoint (timed out, else killed, else failed, else not timed end to end) and add up with the completed switches to the total. - A status flag that is present must be a boolean, by the same rule as the text fields, or the line is malformed. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- docs/claude-session-integration-design.md | 12 ++--- scripts/switch-timing-summary.js | 45 +++++++++++------- src/main.ts | 4 +- src/switch-timing.test.ts | 35 +++++++++++++- src/switch-timing.ts | 57 ++++++++++++++++------- 6 files changed, 111 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e443d38..67a2a69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 1.0.97 -- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s, or one whose command never reported back or was killed by its timeout, the three busiest processes). A record says when it is not the time of a completed switch: `timedOut`, `killed`, or `untimed` for the paths handed to VS Code, Claude Desktop or the embedded terminal, which the log counts but does not time. **Each line names its session** — the session id, title, account label, project path, the pid switched to and its tty — so per-session patterns show (a crowded window, one account, a session that always falls back to cwd); the title is the `/rename` name or, without one, the title Claude Code generated, which is a model-written summary of the conversation; **the prompts and the transcript text themselves are not recorded**. The file is local and kept owner-only (0600, set again on every write, the rotated copy included); when quoting results in public, replace titles and paths with placeholders — `yarn switch-timing --redact` does it. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch; what remains in the main process is a few synchronous reads (`os.cpus()`, `process.cpuUsage()`, the clock) when the IPC arrives and again (plus `os.loadavg()`) when the record closes. A failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal, branch and account, a per-session table (`--all`, `--sort=p90`), and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" +- Dev: **a timing log for session switches**, to find out where a slow switch spends its time before anything is rewritten for speed. Each switch started from the Sessions tab appends one line to `~/.config/codev/switch-timing.jsonl`: the time from the click to the IPC, the settings read, terminal detection, building the script, starting `osascript` (or the cmux CLI) and its exit; which key found the tab (tty, title, cwd, or a new tab for a resume), read from what the switch scripts already return; and the machine's state around it (load average, CPU %, memory pressure and swap, the number of running `claude` processes; for a switch over 1 s, or one whose command never reported back or was killed by its timeout, the three busiest processes). A record says when it is not the time of a completed switch: `timedOut`; `killed` (set by the `osascript` paths that run with a timeout, not by cmux); or `untimed` when no command was started and awaited, which in practice is mostly the switches handed to VS Code, Claude Desktop or the embedded terminal — the log counts those but does not time them. **Each line names its session** — the session id, title, account label, project path, the pid switched to and its tty — so per-session patterns show (a crowded window, one account, a session that always falls back to cwd); the title is the `/rename` name or, without one, the title Claude Code generated, which is a model-written summary of the conversation; **the prompts and the transcript text themselves are not recorded**. The file is local and kept owner-only (0600, set again on every write, the rotated copy included); when quoting results in public, replace titles and paths with placeholders — `yarn switch-timing --redact` does it. Capped at about 1 MB with one rotated file. Everything that spawns a process or writes the file runs after the switch; what remains in the main process is a few synchronous reads (`os.cpus()`, `process.cpuUsage()`, the clock) when the IPC arrives and again (plus `os.loadavg()`) when the record closes. A failure in the timing code leaves the switch as it was. `yarn switch-timing` prints p50/p90 per step by terminal, branch and account, a per-session table (`--all`, `--sort=p90`), and the total against load. Fields: `docs/claude-session-integration-design.md`, "Measuring a switch" ## 1.0.94 diff --git a/docs/claude-session-integration-design.md b/docs/claude-session-integration-design.md index 93ee551..7fc6b98 100644 --- a/docs/claude-session-integration-design.md +++ b/docs/claude-session-integration-design.md @@ -706,7 +706,7 @@ Any failure in the timing code is swallowed and the switch runs as before. | `ts` | ISO time the IPC arrived in the main process. | | `sessionId` | The full session id. | | `title` | The row's title when the switch was started: the `/rename` name, else the title Claude Code generated (a model-written summary of the conversation); `null` when the session has neither. Cut at 200 characters. | -| `account` | The account of the switch. For a `resume` it is the account the launch actually runs under, recorded where that is decided: the account history has for the session, or, for a session history does not know, the row's label. For a `switch` to a running session nothing is launched, so it is the row's label, after the main process has checked that an account with that label exists. Every account has a label, the anchor included. `null` means no account was resolved (no label, or one that no account has any more); it does not mean the anchor. | +| `account` | The account of the switch. On the terminal paths that build a resume command (iTerm2, Ghostty, Terminal.app, cmux) it is the account that command runs under, recorded where that is decided: the account history has for the session, or, for a session history does not know, the row's label. On every other path it is the row's label, after the main process has checked that an account with that label exists: a `switch` to a running session, where nothing is launched, and a resume through VS Code, Claude Desktop or the embedded terminal. (On iTerm2 and Terminal.app a running session whose row has no pid is opened with a resume command, so that record follows the first rule.) Every account has a label, the anchor included. `null` means no account was resolved (no label, or one that no account has any more); it does not mean the anchor. | | `project` | The session's project path. | | `pid` | The process switched to; `null` for a resume, which has none yet. | | `tty`, `ttySrc` | That process's controlling terminal (for example `ttys004`), and where the value came from: `live-report` (the last live-sessions report already listed it) or `ps` (one `ps -o tty= -p `, run after the switch). `null` when there is no pid, the process has no tty, or the lookup failed. | @@ -714,15 +714,15 @@ Any failure in the timing code is swallowed and the switch runs as before. | `kind` | `switch` (the session was running) or `resume` (it was not; a new tab runs `claude --resume`). | | `terminal`, `configured` | Where the switch went after auto-detection, and the terminal named in Settings. | | `tool` | What ran the switch: `osascript`, `cmux-cli`, `open` (VS Code, Claude Desktop) or `pty` (the embedded terminal). | -| `untimed` | True for a switch this log cannot time end to end: the paths with tool `open` or `pty`, which hand the switch over and return at once (VS Code, for one, then waits 500 ms before its own command). No command is started and awaited, so `ms.run`, `ms.main` and `ms.total` are `null`; `ms.returned` and the earlier steps are kept. The log exists to measure terminal switching; these records are there to be counted, not timed. | +| `untimed` | True when no command was started and awaited, so there is no exit to time to: `ms.run`, `ms.main` and `ms.total` are `null`; `ms.returned` and the earlier steps are kept. That is the whole rule. In practice it is mostly the paths with tool `open` or `pty`, which hand the switch over and return at once (VS Code, for one, then waits 500 ms before its own command). It is also a terminal launch that failed before its command started, for example when the script file could not be written; such a record is `untimed` with tool `osascript` and `ok` false. The log exists to measure terminal switching; these records are there to be counted, not timed. | | `branch` | Which key found the tab: `tty`, `title`, `cwd`, `project-name` (cmux), `none` (the script ran and matched nothing); for a resume `new-tab`, `new-window` or `new-workspace`; `deep-link`, `embedded`. `null` means unknown, for example a script that failed. | | `order`, `hasTitle` | Which key the script tried first (`tty-first` or `title-first`), and whether it had a title block at all. | -| `killed` | True when the command exited only because its 5 s timeout killed it (`error.killed` in the callback). `ms.run`, `ms.main` and `ms.total` are then real waits and stay numeric, but they are not the time of a switch: `ok` is false, `branch` is `null`, and `top` is recorded as for a slow switch. Not seen on two paths: the iTerm2 switch runs without a timeout (a hang there ends as `timedOut`), and the cmux switch does not report its CLI errors. | -| `ok`, `timedOut` | `ok` is false when the launch was rejected or its command was killed. `timedOut` is true when the command had not reported an exit after 15 s. The record then says only what was measured: `ms.run`, `ms.main` and `ms.total` are `null` (15 s is when the record was closed, not how long anything took), the earlier steps and `ms.returned` are kept, and `top` is recorded as for a slow switch. | +| `killed` | True when the command exited only because its 5 s timeout killed it (`error.killed` in the callback). `ms.run`, `ms.main` and `ms.total` are then real waits and stay numeric, but they are not the time of a switch; `top` is recorded as for a slow switch. **Only the `osascript` paths that run with a timeout set it**: the resume launches of iTerm2, Ghostty and Terminal.app, and the Ghostty and Terminal.app switches. The iTerm2 switch runs without a timeout (a hang there ends as `timedOut`). **The cmux switch and the cmux resume never set it**, so `killed: false` on a cmux record does not mean its command was not killed; a cmux resume whose launch command was killed shows as `ok` false with a `ms.run` of about 5 s or more. The other fields of a killed record depend on the path: `branch` is `null` for a killed switch (the script printed nothing), but a killed resume keeps the `new-tab` or `new-window` it was asked for. The summary leaves a killed record out of its percentiles because of `killed` itself, not because of `ok` or `branch`. | +| `ok`, `timedOut` | `ok` is false when the launch was rejected, and on a record with `killed` true (the writer sets it so, also when `openSession` had already returned successfully, as it does on a switch to a running session). `timedOut` is true when the command had not reported an exit after 15 s. The record then says only what was measured: `ms.run`, `ms.main` and `ms.total` are `null` (15 s is when the record was closed, not how long anything took), the earlier steps and `ms.returned` are kept, and `top` is recorded as for a slow switch. | | `ms.clickToIpc`, `ms.clickToIpcHr` | ① to ②, on the wall clock (whole ms) and on the two processes' high-resolution clocks. | | `ms.settings`, `ms.detect`, `ms.build`, `ms.spawn`, `ms.run` | The steps in the diagram. A step a path skips is `null`, and its time counts in the next one. | | `ms.returned` | ② to `openSession` returning. For a running session this is before the script exits. | -| `ms.main`, `ms.total` | ② to ⑦, and ① to ⑦ (what the user waited). `null` when no exit was seen: `timedOut`, or `untimed`. Time zero for every `ms` value except the two `clickToIpc` ones is the first thing the handler does, before the timing code's own setup, so that setup is inside `ms.settings` and `ms.main`. | +| `ms.main`, `ms.total` | ② to ⑦, and ① to ⑦ (what the user waited). `null` when no exit was seen: `timedOut`, or `untimed`. `ms.total` is `ms.clickToIpc` plus `ms.main`; when a record has no click stamp, `ms.clickToIpc` is `null`, the click-to-IPC part counts as zero, and `ms.total` equals `ms.main`. Time zero for every `ms` value except the two `clickToIpc` ones is the first thing the handler does, before the timing code's own setup, so that setup is inside `ms.settings` and `ms.main`. | | `load`, `ncpu` | `os.loadavg()` at the end of the switch, and the core count. | | `cpuPct` | Whole-machine CPU busy % over the span, from two `os.cpus()` samples. `null` for a span too short to measure (the counters tick every 10 ms). | | `mainCpuMs` | An object, `{ "user": …, "system": … }`: the CPU time in ms that CodeV's main process itself used over the span, in user mode and in system mode (`process.cpuUsage()` delta). | @@ -752,7 +752,7 @@ It prints p50/p90 (50th and 90th percentile) per step and for the total — for How to read the tables: -- **`n` is the number of records in the row; a cell ending in `(k)` covers only `k` of them.** Not every record has every step: a resume has no `detect`. And `run`, `main` and `total` are over completed switches only. Four kinds of record are left out of those three percentiles and counted in the first line of the report instead: timed out, killed by their timeout, failed (`ok` false), and not timed end to end (`untimed`). +- **`n` is the number of records in the row; a cell ending in `(k)` covers only `k` of them.** Not every record has every step: a resume has no `detect`. And `run`, `main` and `total` are over completed switches only. Four kinds of record are left out of those three percentiles and counted in the first line of the report instead: timed out, killed by their timeout, failed (`ok` false), and not timed end to end (`untimed`). A record can be more than one of these (a killed switch is also `ok` false; a launch that failed before its command started is also `untimed`), so the first line counts each record once, as the first that applies in that order; the four counts and the completed switches add up to the total. A status flag (`ok`, `timedOut`, `killed`, `untimed`) that is present must be a boolean, or the line is malformed. - **Accounts.** `(none)` is a record for which no account was resolved; `(unknown)` is a version 1 line, which did not record one. - **Lines of the wrong shape are malformed.** A line counts as a record only if it is an object, its `ms` is an object, and every text field (`kind`, `terminal`, `branch`, `account`, `sessionId`, `title`, `project` and the like) is a string, `null` or absent. One wrong-typed field makes the whole line malformed. - **A log that exists but cannot be read makes the report incomplete**, and the script says so on stderr and in the report's first line, and exits 1. A log that does not exist is not an error: the rotated file is optional. Under `--redact` an input is named by its position (`input 2`), never by its path. diff --git a/scripts/switch-timing-summary.js b/scripts/switch-timing-summary.js index b12e67d..5f5c1c7 100644 --- a/scripts/switch-timing-summary.js +++ b/scripts/switch-timing-summary.js @@ -45,9 +45,10 @@ const NEEDS_EXIT = new Set(['run', 'main', 'total']); const isNum = (v) => typeof v === 'number' && Number.isFinite(v); /** - * A path the log does not follow to the end (VS Code, Claude Desktop, the - * embedded terminal): flagged `untimed`, or, on a line written before the - * flag existed, recognisable by its tool. + * A record with no end-to-end time: flagged `untimed` by the writer (no + * command was started and awaited — mostly the paths handed to VS Code, + * Claude Desktop or the embedded terminal), or, on a line written before + * the flag existed, recognisable by the tool of those paths. */ const isUntimed = (r) => r.untimed === true || r.tool === 'open' || r.tool === 'pty'; @@ -121,20 +122,25 @@ const TEXT_FIELDS = [ 'ttySrc', ]; +/** Status flags: compared with `=== true` / `=== false`, so they must be booleans. */ +const FLAG_FIELDS = ['ok', 'timedOut', 'killed', 'untimed']; + const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); /** - * A line this script can summarize: an object whose `ms` is an object, and - * whose text fields are each a string, null or absent. One rule for all of - * them: a field of the wrong type makes the whole line malformed, rather - * than each use having to defend itself (`String()` of an object with a - * broken `toString` throws). Numbers need no such rule: every numeric read - * goes through `isNum`. + * A line this script can summarize: an object whose `ms` is an object, + * whose text fields are each a string, null or absent, and whose status + * flags are each a boolean, null or absent. One rule for all of them: a + * field of the wrong type makes the whole line malformed, rather than each + * use having to defend itself (`String()` of an object with a broken + * `toString` throws; `killed: "true"` would read as "not killed"). Numbers + * need no such rule: every numeric read goes through `isNum`. */ const isRecord = (r) => isPlainObject(r) && isPlainObject(r.ms) && - TEXT_FIELDS.every((k) => r[k] === undefined || r[k] === null || typeof r[k] === 'string'); + TEXT_FIELDS.every((k) => r[k] === undefined || r[k] === null || typeof r[k] === 'string') && + FLAG_FIELDS.every((k) => r[k] === undefined || r[k] === null || typeof r[k] === 'boolean'); /** Records from JSONL text. A line that is not a record (see `isRecord`) is skipped and counted. */ const parseLines = (text) => { @@ -305,10 +311,16 @@ const summarize = (records, opts = {}) => { .map((r) => run(r) / total(r)); return { count: records.length, + // Disjoint, in this order of precedence, so the four counts and the + // completed switches add up to `count`: the writer marks a killed + // switch `ok: false` too, and a launch that failed before its command + // started is also untimed. timedOut: records.filter((r) => r.timedOut === true).length, - killed: records.filter((r) => r.killed === true).length, - failed: records.filter((r) => r.ok === false).length, - untimed: records.filter(isUntimed).length, + killed: records.filter((r) => r.timedOut !== true && r.killed === true).length, + failed: records.filter((r) => r.timedOut !== true && r.killed !== true && r.ok === false).length, + untimed: records.filter( + (r) => r.timedOut !== true && r.killed !== true && r.ok !== false && isUntimed(r), + ).length, slow: records.filter((r) => isNum(total(r)) && total(r) > 1000).length, all: stepStats(records), byKind: groupBy(records, (r) => String(r.kind ?? 'unknown')), @@ -499,9 +511,10 @@ const formatReport = (summary, malformed = 0, opts = {}) => { 'command), main (IPC → done), total (click → done).', 'n is the records in the row. A cell ending in (k) is over only k of them: the', 'rest have no value for that step. A resume does not detect. run, main and total', - 'are over completed switches only: not one that timed out, was killed by its', - 'timeout or failed, and not one handed to VS Code, Claude Desktop or the embedded', - 'terminal (not timed end to end).', + 'are over completed switches only. The other four kinds in the first line are left', + 'out, and each switch is counted in one of them at most: timed out, else killed,', + 'else failed, else not timed end to end (no command was started and awaited:', + 'mostly switches handed to VS Code, Claude Desktop or the embedded terminal).', '', stepTable('All', '', [{ key: 'all', n: s.count, steps: s.all }]), '', diff --git a/src/main.ts b/src/main.ts index 54b976d..2ef007f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2884,7 +2884,9 @@ ipcMain.on( ? accountLabel : undefined; // The log starts from the label the launch is given, not the renderer's - // raw one; a resume replaces it with the account it actually runs under. + // raw one. The terminal paths that build a resume command (iTerm2, + // Ghostty, Terminal.app, cmux) replace it with the account that command + // runs under; every other path keeps this value. timing?.set({ account: label ?? null }); openSession( sessionId, diff --git a/src/switch-timing.test.ts b/src/switch-timing.test.ts index b244283..8e85525 100644 --- a/src/switch-timing.test.ts +++ b/src/switch-timing.test.ts @@ -105,6 +105,10 @@ describe('createSwitchTiming', () => { expect(h.finished).toHaveLength(1); expect(h.finished[0].timedOut).toBe(true); expect(h.finished[0].exitedAt).toBeNull(); + // `returned` is when `openSession` settled (here, at once), not the + // deadline 5000 ms later at which the record closed. + expect(h.finished[0].marks.returned).toBe(0); + expect(h.finished[0].endedAt).toBe(5000); // A late exit does not produce a second record. h.timing.exited('found-by-tty'); expect(h.finished).toHaveLength(1); @@ -553,8 +557,12 @@ describe('the log file', () => { expect(ms.run).toBeNull(); expect(ms.main).toBeNull(); expect(ms.total).toBeNull(); - // Measured (the collector's own clock decides how long; see the - // controlled-clock test of `stepDurations` for the exact value). + // No upper bound on purpose: this run is on the real clock, and the time + // before `settle()` can legitimately exceed any small limit on a busy + // machine. That `returned` is the settle time and not the deadline is + // asserted on a controlled clock in 'closes at the deadline, flagged, + // when the command never reports back' (`marks.returned` 0 against a + // 5000 ms deadline) and in the `stepDurations` timed-out case. expect(typeof ms.returned).toBe('number'); }); @@ -1153,6 +1161,12 @@ describe('scripts/switch-timing-summary.js', () => { { ...good, project: { path: '/x' } }, { ...good, tty: 4 }, { ...good, sid: [] }, + // A status flag that is not a boolean: `"true"` is not `true`, and + // reading it as "not killed" would put the row among the completed. + { ...good, killed: 'true' }, + { ...good, ok: 0 }, + { ...good, timedOut: 'false' }, + { ...good, untimed: 1 }, { ...good, ms: [] }, // an array is not a set of steps { ...good, ms: 'fast' }, [good], @@ -1161,6 +1175,9 @@ describe('scripts/switch-timing-summary.js', () => { const { records, malformed } = summary.parseLines(text); expect(records).toEqual([good]); expect(malformed).toBe(bad.length); + // Real booleans, and an absent or null flag, are fine. + const flagged = { ...good, ok: false, timedOut: false, killed: true, untimed: null }; + expect(summary.parseLines(JSON.stringify(flagged)).records).toEqual([flagged]); // And what is accepted cannot make the report throw. expect(() => summary.formatReport(summary.summarize(records), malformed, {})).not.toThrow(); }); @@ -1190,6 +1207,20 @@ describe('scripts/switch-timing-summary.js', () => { ]; const s = summary.summarize(records); expect(s).toMatchObject({ count: 6, killed: 1, failed: 1, untimed: 2, timedOut: 0, slow: 0 }); + // The writer marks a killed switch `ok: false`, and a launch that failed + // before its command started is untimed as well as failed. Each switch + // is still counted once: timed out, else killed, else failed, else untimed. + const overlapping = [ + ...records, + rec({ killed: true, ok: false }, { run: 5000, main: 5010, total: 5020 }), + rec({ timedOut: true, ok: false }, { returned: 3 }), + rec({ untimed: true, ok: false }, { returned: 3 }), + ]; + const o = summary.summarize(overlapping); + expect(o).toMatchObject({ count: 9, timedOut: 1, killed: 2, failed: 2, untimed: 2 }); + const completedCount = o.all.total.n; + expect(completedCount).toBe(2); + expect(o.timedOut + o.killed + o.failed + o.untimed + completedCount).toBe(o.count); expect(s.all.total).toEqual({ n: 2, p50: 220, p90: 300 }); expect(s.all.run).toEqual({ n: 2, p50: 200, p90: 280 }); expect(s.all.main.n).toBe(2); diff --git a/src/switch-timing.ts b/src/switch-timing.ts index 2dc2c09..c64b6fe 100644 --- a/src/switch-timing.ts +++ b/src/switch-timing.ts @@ -72,10 +72,12 @@ export interface SwitchFacts { /** * The account of this switch. For a resume it is the account the launch * runs under, set where that is decided (`buildResumeCommand`): history's - * account for a session history knows, else the row's label. A switch to - * a running session launches nothing, so it keeps what main set: the - * row's label, once checked that an account carries it. Null: no account - * was resolved. + * account for a session history knows, else the row's label. Only the + * terminal paths that build a resume command do this (iTerm2, Ghostty, + * Terminal.app, cmux). Everything else keeps what main set — the row's + * label, once checked that an account carries it: a switch to a running + * session, which launches nothing, and a resume through VS Code, Claude + * Desktop or the embedded terminal. Null: no account was resolved. */ account?: string | null; } @@ -109,6 +111,14 @@ export interface SwitchSnapshot { /** * True when the command did exit, but only because its caller's own * timeout killed it. Its times are real waits, not a completed switch. + * + * Only the `osascript` callbacks report this (`error.killed`): the + * resume launches of iTerm2, Ghostty and Terminal.app, and the Ghostty + * and Terminal.app switches, which run with a 5 s timeout. The iTerm2 + * switch has no timeout to be killed by. The cmux paths never set it: + * the cmux resume is timed around a promise that does not hand over its + * error, and the cmux switch discards its CLI errors. So `false` on a + * cmux record does not say its command was not killed. */ killed?: boolean; } @@ -121,7 +131,8 @@ export interface SwitchTiming { /** * It exited. `stdout`, when the command is a switch script, names the * branch that matched. `killed` is the callback's `error.killed`: the - * command was stopped by its timeout instead of finishing. + * command was stopped by its timeout instead of finishing. Passed by the + * `osascript` callbacks only (see `SwitchSnapshot.killed`). */ exited(stdout?: string, killed?: boolean): void; /** @@ -317,24 +328,34 @@ export interface SwitchStepMs { * the command timed out, or the path starts no command (`untimed`). */ main: number | null; - /** `clickToIpc + main`: what the user waited. Null whenever `main` is. */ + /** + * `clickToIpc + main`: what the user waited. Null whenever `main` is. + * Without a click stamp the click-to-IPC part counts as zero, so `total` + * then equals `main`; `clickToIpc` is null on such a record, which is how + * a reader can tell. (A negative `clickToIpc` — the two clocks disagreeing + * — also counts as zero here, and is recorded as measured.) + */ total: number | null; } +/** + * True for a switch this log cannot time end to end: no command was + * started and awaited (`spawned()` was never called), so there is no exit + * to measure to. That is the rule, whatever the path. In practice it is + * mostly the paths that hand over with a fire-and-forget `open` or a + * message to the renderer (VS Code, Claude Desktop, the embedded terminal; + * what they do next, such as VS Code's 500 ms wait before its URI command, + * happens out of sight). It is also a terminal launch that failed before + * its command started, for example when the script file could not be + * written: such a record is untimed with tool `osascript`. + */ +export const isUntimed = (snap: SwitchSnapshot): boolean => snap.spawnedAt === null; + /** * Step durations from one snapshot. Each step is measured from the step * before it that this path actually reached, so a path that skips one * (a resume skips `detect`) does not lose the time: it lands in the next. */ -/** - * True for a switch this log cannot time end to end: no command was ever - * started and awaited, so there is no exit to measure to. Those are the - * paths that hand over with a fire-and-forget `open` or a message to the - * renderer; what they do next (VS Code waits 500 ms before its URI - * command, for one) happens out of sight. - */ -export const isUntimed = (snap: SwitchSnapshot): boolean => snap.spawnedAt === null; - export const stepDurations = ( snap: SwitchSnapshot, stamp: RendererStamp | undefined, @@ -348,9 +369,9 @@ export const stepDurations = ( // `returned` is what is known: // - a command that timed out never reported one (the record closed at // the deadline, which is not a duration of anything); - // - a path that hands the switch to something this log does not follow - // (VS Code, Claude Desktop, the embedded terminal) starts no command, - // so `openSession` returning is not "switched" (see `isUntimed`). + // - a record on which no command was started and awaited (mostly the + // paths handed to VS Code, Claude Desktop or the embedded terminal), + // where `openSession` returning is not "switched" (see `isUntimed`). const end = snap.timedOut || isUntimed(snap) ? null : exitedAt; const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n); const clickToIpc = stamp && finite(stamp.wallMs) ? ipc.wallMs - stamp.wallMs : null;