diff --git a/CHANGELOG.md b/CHANGELOG.md index d5724ef..c64b205 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # 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, 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.96 - Feat: **copy what identifies a session.** Right-click a row in the Sessions tab for a menu that copies its title, session ID, transcript path, project path, resume command or a one-line reference (title + full id) — each item shows the value it will copy. `⌘⇧C` copies the reference of the selected row. The menu is drawn inside the window rather than as a native menu, because in Menu Bar mode the window hides when it loses focus diff --git a/docs/claude-session-integration-design.md b/docs/claude-session-integration-design.md index dc60757..c4b5920 100644 --- a/docs/claude-session-integration-design.md +++ b/docs/claude-session-integration-design.md @@ -697,6 +697,102 @@ 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, 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 + ──────── ──────────── ──────── + ① 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, 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, 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 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 | +|---|---| +| `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 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. 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. | +| `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). | +| `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; `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`. `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). | +| `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 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. + +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 [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, 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. | + +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`). 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. +- **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` `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 990f722..9ecc418 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "CodeV", "productName": "CodeV", - "version": "1.0.96", + "version": "1.0.97", "description": "Quick switcher for VS Code, Cursor, and Claude Code sessions", "repository": { "type": "git", @@ -16,6 +16,7 @@ "session": "ts-node src/cli/codev-session.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..5f5c1c7 --- /dev/null +++ b/scripts/switch-timing-summary.js @@ -0,0 +1,643 @@ +#!/usr/bin/env node +/** + * Summarize CodeV's switch timing log (src/switch-timing.ts writes it). + * + * node scripts/switch-timing-summary.js [--redact] [--all] [--sort=n|p90] [file ...] + * + * 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, 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. 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 + * 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'; + +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']; + +/** 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); + +/** + * 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'; + +/** + * 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 (NEEDS_EXIT.has(step) && !completed(r)) 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(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); + 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]) => isNum(x) && isNum(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); +}; + +/** 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', +]; + +/** 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, + * 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') && + 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) => { + const records = []; + let malformed = 0; + for (const line of String(text || '').split('\n')) { + if (!line.trim()) continue; + try { + const r = JSON.parse(line); + if (isRecord(r)) records.push(r); + else malformed++; + } catch { + malformed++; + } + } + 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) out[step] = stat(records, step); + 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) })); +}; + +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 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) ? NO_ACCOUNT : 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 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 total = stat(rs, 'total'); + const run = stat(rs, '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, + totalN: total.n, + totalP50: total.p50, + totalP90: total.p90, + runN: run.n, + runP50: run.p50, + runP90: run.p90, + 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) && 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 }, + { 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, opts = {}) => { + 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) => isNum(run(r)) && isNum(total(r)) && total(r) > 0) + .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.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')), + 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) => { + const rs = records.filter((r) => { + const l = loadPerCore(r); + return l !== null && l >= b.lo && l < b.hi; + }); + // `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) => [load1(r), total(r)])), + rTotalVsCpuPct: pearson(records.map((r) => [r.cpuPct, total(r)])), + rRunVsLoad1: pearson(records.map((r) => [load1(r), run(r)])), + }, + }; +}; + +// --- printing --- + +// C0 controls, DEL, C1 controls, the two Unicode line separators, and the +// 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 + * 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)); + // 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) => { + 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)); + +/** + * `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; + +/** + * `~/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])); + 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]])); + } + return new Map(ids.map((id) => [id, id])); +}; + +const sessionTable = (s, opts) => { + 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'); + // 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( + 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'], + ), + ); + 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.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. run, main and total', + '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 }]), + '', + stepTable('By kind', 'kind', s.byKind), + '', + stepTable('By terminal', 'terminal', s.byTerminal), + '', + stepTable('By branch', 'branch', s.byBranch), + '', + stepTable('By account', '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)}%` + }`, + '', + 'Total vs load (1-minute load average per core)', + 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)}`, + ` 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]; +}; + +/** + * 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 = []; + const unreadable = []; + files.forEach((f, index) => { + try { + text += `${fs.readFileSync(f, 'utf-8')}\n`; + } catch (err) { + if (err && err.code === 'ENOENT') missing.push(index); + else unreadable.push({ index, code: (err && err.code) || 'error' }); + } + }); + 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: [] }; + 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 opts = parseArgs(argv); + if (opts.bad.length > 0) { + 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; + } + const explicit = opts.files.length > 0; + const files = explicit ? opts.files : defaultFiles(); + 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)); +}; + +if (require.main === module) main(process.argv.slice(2)); + +module.exports = { + percentile, + pearson, + parseLines, + summarize, + formatReport, + stepStats, + sessionRows, + sessionLabels, + branchMix, + redactRecords, + readFiles, + parseArgs, + safeText, + clip, + tildePath, + renderTable, + STEPS, +}; diff --git a/src/claude-session-utility.ts b/src/claude-session-utility.ts index 7dfdb8e..e2c60ca 100644 --- a/src/claude-session-utility.ts +++ b/src/claude-session-utility.ts @@ -60,6 +60,7 @@ import { switchOrderFor, } from './terminal-switch'; import { pickSessionByTabTitle } from './cross-ref-title'; +import type { SwitchTiming } from './switch-timing'; export interface ClaudeSession { sessionId: string; @@ -1410,11 +1411,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 }); // The command itself is spelled in ONE place, shared with the CLI. return formatResumeCommand( sessionId, @@ -1435,23 +1440,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; } @@ -1461,6 +1472,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; } @@ -1468,10 +1480,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': @@ -1482,6 +1496,7 @@ export const openSession = async ( activePid, customTitle, accountLabel, + timing, ); case 'ghostty': return openSessionInGhostty( @@ -1492,6 +1507,7 @@ export const openSession = async ( terminalMode, customTitle, accountLabel, + timing, ); case 'terminal': return openSessionInTerminalApp( @@ -1502,6 +1518,7 @@ export const openSession = async ( terminalMode, customTitle, accountLabel, + timing, ); case 'iterm2': default: @@ -1513,6 +1530,7 @@ export const openSession = async ( terminalMode, customTitle, accountLabel, + timing, ); } }; @@ -1604,6 +1622,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 @@ -1614,12 +1633,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(undefined, !!error?.killed); try { fs.unlinkSync(tmpScript); } catch {} @@ -2043,6 +2070,7 @@ export const openSessionInITerm2 = async ( terminalMode: string = 'tab', customTitle?: string, accountLabel?: string, + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); @@ -2053,17 +2081,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, !!error?.killed); 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); + const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath, timing); + return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'iterm2', terminalMode, timing); } }; @@ -2726,6 +2758,7 @@ export const openSessionInGhostty = async ( terminalMode: string = 'tab', customTitle?: string, accountLabel?: string, + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); @@ -2736,11 +2769,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, !!error?.killed); const result = (stdout || '').trim(); console.log('[ghostty] switch result:', result, error?.message || ''); if (result === 'not found') { @@ -2749,8 +2786,8 @@ export const openSessionInGhostty = async ( try { fs.unlinkSync(tmpScript); } catch {} }); } else { - const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath); - return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'ghostty', terminalMode); + const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath, timing); + return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'ghostty', terminalMode, timing); } }; @@ -2767,6 +2804,7 @@ export const openSessionInTerminalApp = async ( terminalMode: string = 'tab', customTitle?: string, accountLabel?: string, + timing?: SwitchTiming, ): Promise => { const { exec } = require('child_process'); @@ -2779,17 +2817,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, !!error?.killed); 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); + const resumeCmd = buildResumeCommand(sessionId, accountLabel, projectPath, timing); + return runCommandInTerminal(`cd "${projectPath}" && ${resumeCmd}`, resumeCmd, projectPath, 'terminal', terminalMode, timing); } }; @@ -2807,6 +2849,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)}`; @@ -2835,6 +2878,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`); @@ -2874,6 +2923,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; } @@ -2889,6 +2939,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; } @@ -2910,6 +2961,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; } @@ -2923,6 +2975,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; } @@ -2931,11 +2984,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'); + 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' }); + 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 51d37a4..908cc3b 100644 --- a/src/electron-api.d.ts +++ b/src/electron-api.d.ts @@ -273,6 +273,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 1070c3e..4ac1fba 100644 --- a/src/main.ts +++ b/src/main.ts @@ -66,6 +66,7 @@ import { SETTINGS_KEY_LEGACY_MODE, SETTINGS_KEY_USER_PROMPT, } from './session-preview'; +import { noteLiveReport, startSwitchTiming } from './switch-timing-log'; import { randomUUID } from 'crypto'; import { installHooks, @@ -2817,7 +2818,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 and ttys 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. @@ -2868,6 +2871,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). @@ -2875,6 +2879,18 @@ 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, + active: !!isActive, + title: customTitle, + 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) { @@ -2883,6 +2899,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. @@ -2890,6 +2908,11 @@ ipcMain.on( typeof accountLabel === 'string' && findAccountByLabel(accountLabel) ? accountLabel : undefined; + // The log starts from the label the launch is given, not the renderer's + // 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, projectPath, @@ -2899,9 +2922,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 31daa91..42547f4 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -121,6 +121,7 @@ contextBridge.exposeInMainWorld('electronAPI', { activePid?: number, customTitle?: string, accountLabel?: string, + stamp?: unknown, ) => ipcRenderer.send( 'open-claude-session', @@ -130,6 +131,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..fb21871 --- /dev/null +++ b/src/switch-timing-log.ts @@ -0,0 +1,280 @@ +/** + * 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. + * The line names the session (id, title, account, project path, pid, tty), + * 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. + * + * 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, 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. + * + * 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, + parseTty, + pidOrNull, + sanitizeStamp, + shouldRotate, + stepDurations, + SWITCH_LOG_MAX_BYTES, + SwitchContext, + 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. +// 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?: { pid?: number; tty?: string | null }[]; measuredAt?: number } + | null + | undefined, +): void => { + try { + if (report && Array.isArray(report.live)) { + 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. + } +}; + +/** For tests. */ +export const resetLiveReportNote = (): void => { + lastLive = null; +}; + +// --- append with rotation --- + +/** + * 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); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException)?.code === 'ENOENT'; + } +}; + +/** + * 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`. + * + * 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, + 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`; + // Before the rename, so the rotated file is already owner-only. + 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`); + } + // 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 }); +}; + +// 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; + /** `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; +} + +/** + * 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 = ( + session: Omit, + rawStamp: unknown, + 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 + origin, + }; + const stamp = sanitizeStamp(rawStamp); + const cpusBefore = os.cpus(); + const cpuUsageBefore = process.cpuUsage(); + 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; + // 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 = { + loadavg: os.loadavg(), + cpuPct: cpuPercentBetween(cpusBefore, os.cpus()), + ncpu: cpusBefore.length, + mainCpuMicros: process.cpuUsage(cpuUsageBefore), + 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, live).catch(() => deps.onWritten?.(null)); + }); + }; + + 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 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 || snap.killed === true) ? 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) } : {}), + }; + 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(), + origin, + onFinish, + deadlineMs: deps.deadlineMs, + }); + } catch { + return undefined; + } +}; diff --git a/src/switch-timing.test.ts b/src/switch-timing.test.ts new file mode 100644 index 0000000..8e85525 --- /dev/null +++ b/src/switch-timing.test.ts @@ -0,0 +1,1297 @@ +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, vi } from 'vitest'; + +import { + branchFromSwitchOutput, + buildSwitchRecord, + cpuPercentBetween, + createSwitchTiming, + isSlowSwitch, + isUntimed, + parseTopCpu, + parseTty, + sanitizeStamp, + shouldRotate, + stepDurations, + SwitchSnapshot, + textOrNull, +} 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(); + // `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); + }); + + 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('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; + 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, + 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, + ); + // 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(); + // Without a stamp the total is main's own span, not a guess. + 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); + 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 }, spawnedAt: 1, exitedAt: 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 SESSION = { + sessionId: '0f1e2d3c-aaaa-bbbb-cccc-123456789abc', + active: true, + title: 'an example title', + projectPath: '/Users/someone/code/example', + pid: 4242, + }; + + const runSwitch = ( + stamp: unknown, + deps: { + 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, killed = false } = {}, + ) => + new Promise | null>((resolve) => { + const timing = startSwitchTiming( + 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, + }, + ); + timing.set({ configured: 'iterm2', terminal: 'ghostty', order: 'tty-first' }); + timing.mark('settings'); + timing.set({ account }); + timing.mark('script'); + timing.spawned(); + timing.settle(true); + if (exits) timing.exited(killed ? '' : 'found-by-title\n', killed); + }); + + it('writes one line per switch, naming the session it was', 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: 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', + 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('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); + // 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('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(); + // 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'); + }); + + 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' }] }); + // 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' }); + }); + + 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 () => { + 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: [ + { 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 }, + { account: 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 () => { + 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('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('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: {}, + 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), + projectPath: '', + pid: 12.5, + }, + undefined, + { ...snap, facts: { account: 42 as unknown as string } }, + 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 }, + 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({ + sessionId: 'abcdefghijkl', + title: null, + 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'); + }); + + // 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: '(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], + ['(none)', 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('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(''); + // 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])), + 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('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: [] }, + // 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], + ]; + 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); + // 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(); + }); + + 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. 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. + 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: 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); + // 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, + 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 new file mode 100644 index 0000000..c64b6fe --- /dev/null +++ b/src/switch-timing.ts @@ -0,0 +1,566 @@ +/** + * 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 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). 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. */ +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 (the row had a title). */ + hasTitle?: boolean; + /** + * 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. 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; +} + +/** 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; + /** + * 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; +} + +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. `killed` is the callback's `error.killed`: the + * command was stopped by its timeout instead of finishing. Passed by the + * `osascript` callbacks only (see `SwitchSnapshot.killed`). + */ + 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). + */ + settle(ok: boolean): void; +} + +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; + 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 = typeof deps.origin === 'number' ? deps.origin : 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 killed = false; + 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, + killed, + }); + }; + + 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, 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) }; + } + 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 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 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. + */ +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; + // 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 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; + 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, 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; + ttySrc?: 'live-report' | 'ps' | null; +} + +export interface SwitchContext { + /** ISO time of the IPC arriving. */ + ts: string; + sessionId: string; + active: boolean; + /** The row's title as the click carried it: `/rename`d, or generated. */ + title?: string | null; + projectPath?: string | null; + /** The process switched to; none for a resume. */ + pid?: number | null; +} + +/** A title is a line of text; anything longer is cut. In code points. */ +export const SWITCH_TITLE_MAX = 200; + +/** + * 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 => + 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 + * 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, + }; +}; + +/** + * 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; + +/** + * Slow enough to also ask what the machine was busy with. A switch whose + * 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, cutShort = false): boolean => + cutShort || (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, + sessionId: textOrNull(ctx.sessionId, 128), + title: textOrNull(ctx.title, SWITCH_TITLE_MAX), + account: textOrNull(snap.facts.account, 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, + 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, + // 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, + 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 59d8ee6..ebaff6b 100644 --- a/src/switcher-ui.tsx +++ b/src/switcher-ui.tsx @@ -363,6 +363,17 @@ 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. 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(), + via, + rows, +}); + function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } @@ -2821,6 +2832,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')) { @@ -3422,6 +3434,7 @@ function SwitcherApp() { session.activePid, customTitles[session.sessionId], session.accountLabel ?? session.__listMember?.accountLabel, + switchStamp('click', displayedSessions.length), ); }} style={{