diff --git a/CHANGELOG.md b/CHANGELOG.md index 47899acb5..6c89c3331 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 > `src/renderer/changelog.ts`. After editing that file, run `npm run changelog` > (CI enforces that this file is in sync via `npm run changelog:check`). +## [2.1.3-beta.28] - 2026-12-04 + +### Warnings +- The update onto this version still asks you to resume your sessions, once, because 2.1.3-beta.27 and earlier do not mark the tabs they save for an update. You see the resume prompt and, with Settings, Accounts, Resuming sessions set to Ask each time, the account question for each tab. On Windows, if the update kept Claude Code or Codex sessions running, answer the resume prompt within five minutes of this version opening, and each tab's account question within five minutes of that tab first showing, or those sessions are ended. From the update you make from this version on, Save sessions reopens your tabs by itself, with nothing asked. +- A Claude Code tab over SSH is matched to one of your accounts by the email in the .claude.json file in your home folder on that machine. If you run Claude Code there with a CLAUDE_CONFIG_DIR of your own, signed in as another account, the tab's status line still names the account in that .claude.json file, so the Accounts page shows the tab's figures on that account's line and counts it In use. Leave CLAUDE_CONFIG_DIR unset on that machine for the tabs the app opens. +- This beta series begins moving the app's background services, and over the next betas your sessions, onto one helper per machine. If you want a quiet build, stay on the stable release. +- The app no longer renews a Claude Code account's sign-in. Claude Code renews it when you next open a session on that account. Until then an idle account whose sign-in has lapsed shows its last reading, marked as an estimate, and use made elsewhere on it does not show. +- On Windows, choosing Save sessions at an update keeps the terminals and the Claude Code and Codex sessions the session helper holds running only if the new version opens within two minutes of the old one closing. The installer's pages count toward those two minutes, so finish the installer promptly. The update dialog says how many of your tabs it keeps running. +- On Windows, Snap takes its picture with the app's own capture and overlay by default. If a press cannot take a picture, the earlier Snap opens for that press; to use the earlier Snap every time, choose Settings, Custom Commands, Snap, Snap on Windows: Previous. +- A picture you paste or Snap now goes through your clipboard. Snap leaves its picture there, and an image file you copied and paste into Claude Code is replaced on the clipboard by its picture. It is an ordinary clipboard item, so Windows clipboard history and sync follow your own Windows settings. +- Signing a Claude Code or Codex account in on a Linux machine (a preview on Windows, off by default) keeps that sign-in on that machine, in a folder only your user there can read. Nothing is copied from this computer. Sign out on the Machines page ends it, and Remove signs the accounts out first. +- If you later install a stable release and want stable releases only, open Settings, General, Update Channel and choose Stable. A beta build can leave Beta saved, and a stable release would then keep offering betas. +- To go back to 2.1.3-beta.27, download its installer from the GitHub releases page and run it over this version. + +> The close and update dialogs now say what Save sessions and Close sessions do to each kind of tab you have open, with a count for each. After an app update where you chose Save sessions, the new version reopens your tabs by itself, with nothing asked, starting with the update you make from this version. On the Accounts page, several lines can be open at once, every closed line has one shape, and a Claude Code tab over SSH now counts toward its account. + +### Changed +- After an app update where you chose Save sessions, the new version reopens your tabs by itself, with nothing asked, once you close the pages it opens with (such as the release notes). There is no resume prompt, and no account question for each tab, even with Settings, Accounts, Resuming sessions set to Ask each time: each tab carries on on the account it was on. On Windows, a session the update kept running waits for its tab however long those pages stay open. This starts with the update you make from this version on. A quit, a crash, the same version starting again, and an update made while the resume prompt was still unanswered still ask with the resume prompt. +- The close and update dialogs now say what each button does to the tabs you have open, with a count for each kind. Under With Save sessions, the update dialog says how many keep running through the update and come back in the same tabs, how many SSH sessions keep running on their hosts and reconnect, how many restart and pick up their conversations, how many SSH sessions restart, and how many terminals restart as new terminals. The quit dialog does the same for the next launch. A tab that has not started (it reads Not started) comes back as it is, and a tab the app opened to sign in on a machine you added, or to install or update a program, closes and does not come back. The last line says what Close sessions does. A line with a count of none is left out. +- The help text under Resuming sessions in Settings, Accounts now says the choice applies when you open the app again and resume your sessions, and that after an app update where you chose Save sessions each session keeps the account it was on, with no question. +- On a slow PC, a session that starts while the app is still starting can start a little sooner: the start-up checks it waits for now run side by side instead of one after another. It still waits up to 5 seconds for the check that brings its status line and resume list. If that check takes longer, the session starts without them: restart the tab once the app has started. +- On the Accounts page, lines open and close on their own: any number can be open at once, and Escape closes the open line you are in. +- Every closed line on the Accounts page has one shape: the name and plan, then the email and the account's roles, with the email shortened first when there is not room. How many tabs run on an account is on its open line, in a Running row. A per-model limit at 90% or more is named in place of a reset time, for example Opus 92% used. A stronger rule now parts one account from the next. +- A figure on the Accounts page that is an estimate is marked ~, for example ~36% used, on its line and in the Most room now summary. The open line's Readings row is now called Usage read. It holds where the figures come from, the sentence that says an estimate is in use, and the age of any figure kept from an older reading. How readings work says what ~ means. +- When Anthropic's rate limit makes the app's background check wait, the Usage heading now says so once for the page: Background check rate limited, with a countdown to when it retries. An open line says Rate limited and the countdown on its Usage read row. A closed line no longer says it. +- What account isolation changed for your sessions is now said once, at the foot of the Accounts page behind What account isolation changed, with each change under the names of the accounts it was made for. An account's own line now shows only a launch that was refused or that started with something unchecked. +- A name, email, role, reset time or note on an account's line that does not fit shows its whole words as a tooltip, and only while it is cut. + +### Fixed +- The close and update dialogs said that sessions you close are gone. An SSH Persistent session keeps running on its host when you choose Close sessions, and the dialog now says so. +- A Claude Code tab over SSH, on the usual SSH path rather than through the session helper, now counts toward its account on the Accounts page: the account shows In use with the tab's live figures. Before, an account you used only that way kept its last background reading and read Not in use while the tab showed live figures. + ## [2.1.3-beta.27] - 2026-12-03 ### Warnings @@ -2538,6 +2570,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Tab attention indicators for waiting prompts - Context usage tracking via statusline API +[2.1.3-beta.28]: https://github.com/nubbymong/ai-code-conductor/releases/tag/v2.1.3-beta.28 [2.1.3-beta.27]: https://github.com/nubbymong/ai-code-conductor/releases/tag/v2.1.3-beta.27 [2.1.3-beta.26]: https://github.com/nubbymong/ai-code-conductor/releases/tag/v2.1.3-beta.26 [2.1.3-beta.25]: https://github.com/nubbymong/ai-code-conductor/releases/tag/v2.1.3-beta.25 diff --git a/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md new file mode 100644 index 000000000..128d9691d --- /dev/null +++ b/CONTEXT.d/2026-12-03-b28-snap-d1-holds.md @@ -0,0 +1,292 @@ +## 2026-12-03 -- Snap e2e D1: the first tab waited out the scripts folders' 5 s bound (aicc_planning#513, step 2) + +Branch `fix/b28-snap-d1-evidence`, from beta at 591eb8fb (2.1.3-beta.27). Step 1 +(the evidence capture in the Snap e2e's part one) is the `test(snap)` commits +before this entry; this is step 2, the fix at the cause, and its review rounds. + +### What this step changes, and what it does not + +A first tab's holds now run side by side, so it waits for the longest of +them, not their sum. Its wait for the scripts folders' check is as on +591eb8fb: up to 5 s from its own ask. What follows a wait that ran out is +not: pty-manager reads the scripts at the spawn, and the spawn now comes +sooner. A check that ends in the time saved gave the tab its scripts on +591eb8fb, by chance, and now does not (a Codex launch's later wait for its +hook folders aside): the tab starts without them. That trade is decided +below. This step does not remove the D1 red, and #513 stays open. + +- Expected saving, not measured: in the evidence below the tab waited its + full 5 s for the scripts check, then 0.4 to 0.5 s more. Only the part of + that which was other holds run after it is saved; the IPC, and the walk of + PATH asked again after the holds (one after the other by design), are not. + So the first tab is expected to spawn up to about 0.4 s sooner here. Where + several holds each take long (the session folders' work took 1.15 to + 1.36 s under load on CI), the saving is the sum less the longest. The time + saved is also the trade's window (decided below). +- What will measure it: the next Snap e2e dispatch of this head writes one + `[spawn] Session : held N ms for (...)` line per hold that took + 1 s or more or ended still pending, and `readings.promptSeenAt`. Record the + measured figure here once that run exists. +- In the failing run (47192226861) the spawn did happen: the tab showed + Windows PowerShell's banner. Its own Windows PowerShell then did not reach + its prompt in the rest of D1's 30 s, about 24 s or more if its holds took + 5.4 s as they did here. That share is the runner's cold Windows PowerShell + start (plan branch 2 of #513), outside every hold, and this step does not + touch it. +- So a run like 47192226861 is expected to stay red. A red D1 whose time went + to the shell's start is not a regression of this step, and it is not re-run + to green. +- What to do about that share is the owner's decision (below). + +D1 now keeps `readings.promptSeenAt`: the first time it saw the tab's +Windows PowerShell prompt. The next red can then be split into main's part +(to the spawn), the shell's start (to its prompt) and the stand-in's (to its +`at`). + +### Evidence + +Two dispatches of the Snap e2e (windows-2025) with the capture: 47213031983 +(green) and 47213083589 (forced red). Times are the runner's clock. + +| | green 47213031983 | forced red 47213083589 | +|---|---|---| +| main's first line to the Claude Code tab asked for (submit) | 2.9 s | 2.8 s | +| submit to `[pty] Spawning PTY` | 5502 ms | 5400 ms | +| spawn to the launch line's hold released (`Replaying 1 buffered write`) | 401 ms | 335 ms | +| spawn to the stand-in Claude Code started | 5232 ms | (forced red) | + +`[claude-version]` was logged before the submit in both runs, so the start's +look for Claude Code was over. In the forced red's terminal the launch line +was the direct one (`& '...claude.cmd'`), though the launch asked for the +resume list (`resumePicker=true`), and no line said the list was skipped. +`getResumePickerPath` (pty-manager.ts) returns null without a word only when +`resume-picker.js` is not there: the deploys had not run yet. + +### Cause + +The scripts folders' hold (`awaitScriptFolders`, script-folders.ts) holds a +local launch until the start's owner-only check of the scripts folders and the +deploys after it have run (index.ts), at most `SCRIPT_FOLDERS_LAUNCH_WAIT_MS` +(5 s), counted from each launch's own ask. Only `scriptFoldersDeployed()`, at +the end of that chain, ends it early. The check is one Windows PowerShell call; +on a runner's first app it takes 8.8 to 13.6 s (2026-11-27-b20-snap-d1.md), and +the tab is asked for about 3 s after main starts. In both runs here the hold +ran out its full 5 s. The forced red's tab is shown to have started without +the scripts (its launch line was the direct one); the green run's script +state at its spawn was not recorded. +The other holds ran after it, one after another; with the IPC they took the +remaining 0.4 to 0.5 s (not split: no line said them). + +Who meets it: a tab asked for while the check runs (tabs restored at start, or +one opened in the first seconds). Where Windows PowerShell is warm the check +took 1.0 to 1.6 s on the runner (2.6 to 3.5 s with the disk cache purged); the +tab waits that long and gets its status line and resume list. A check that +ends within 5 s of a tab's ask is waited for, and the tab gets them; one that +ends later costs that tab 5 s, and, unless another of its holds still holds +it then, it starts without them: a Claude Code tab with no status line of the +app's for the session's whole life, and the direct line, not the resume list. +On 591eb8fb such a tab still waited for its other holds, one after another, +before its spawn, and a check that ended in that time gave it its scripts by +chance. With this branch a check that ends there costs the tab them too: the +trade decided below, as wide as the time saved (up to about 0.4 s in the +evidence). It meets a tab whose check ends just past the tab's own 5 s, as +with a check of 8.2 s and the tab asked 3 s into it (the probe below); no +measured check ended there. A Codex launch then waits for its hook folders, +only while the Hooks gateway listens. The start wires those only after the +check and the deploys, so that wait (5 s, from its own call) usually brings +its scripts back. Without the gateway it starts without the Codex resume list +too. A tab asked for once the check is over waits for nothing. + +### Fix + +- pty-handlers.ts: the holds a launch is held for run side by side + (`Promise.all`), so it waits for the longest, not the sum. The start's look + for Claude Code and the launch's walk of PATH stay one after the other. The + session folders' owner-only step and the walk are asked again once every + hold is over, as before. With nothing to hold, the launch still goes on in + the same tick (the one-at-a-time rule relies on that). +- The scripts folders' hold is one of them, bounded as on 591eb8fb: 5 s from + each launch's own ask. Round 2 had counted it from the check's start, one + deadline for the run; round 3 dropped that (decided below). The time after + a wait that ran out is not as on 591eb8fb: the other holds no longer come + after it, and a check that ended while they ran no longer reaches the tab + (the trade, decided below). +- A sign-in tab is not held for the scripts. Its line runs none of them, as + the code shows: pty-manager's shell-only branch types `localSignInLine` + (local-sign-in-tab.ts), which is `buildClaudeSignInLine` + (spawn-claude-command.ts) with no options, no `--settings` (so no status + line of the app's: that rides the per-session settings file a Claude Code + session's own launch writes, never a shell-only tab's), no resume list and + no picker script. +- The session folders have one bound for the whole launch + (`SPAWN_FOLDERS_WAIT_MS`, 10 s, across its hold and the ask again). The + review found that running them side by side made a launch whose folders work + did not answer wait twice: its hold ended at 10 s with the work still + wanted, and the ask again joined the same icacls runs with a fresh 10 s, so + the spawn ran at 20 s with two "ran out" lines. Now `hardenSpawnFoldersAhead` + takes the time left and answers whether its work ended in time. A launch + whose wait ran out is not asked again; one whose folders were done in time + and came to want doing again while it waited for a longer hold waits at + most what is left. That is counted as time spent waiting for the folders, + not from the first wait's start: before this step the folders' one wait + came after every other hold, so folders wanted by then were still done off + the main thread, and they still are. A launch held only by other holds gets + the whole bound on the ask again, as before. +- Logging: `[spawn] Session : held ms for (no longer pending | + still pending when the wait ended)`, one line per hold, written only when + the hold took 1 s or more, or when what it waited for was still pending as + the wait ended. A warm start's holds write none. "No longer pending" is all + the line claims: the hold answered, failed, or passed a deadline of its own. + The resume list's script state rides the `[pty-manager] Launching Claude via + shell` line every local launch already writes (`pickerScript=ready | not + ready`), only for a launch that asked for the list; no line of its own. All + carry the session id and nothing else. +- pty-handlers.ts's comment on the Codex hook folders now says what holds: + when the scripts wait saw the check and deploys end, the hook folders' wait + covers its own work alone; when it ran out its bound first, the hook + folders' wait covers what is left of the check and the deploys too. + +Safety is unchanged. The scripts hold guards nothing: a launch takes a script +only through `checkDeployedScript` / `scriptFolderRefusal` at launch time, and +a folder not yet checked fails closed (the feature is skipped). The session +folders are still made owner-only before the spawn, and each writer still +makes its own folder owner-only before it writes. + +User-facing surfaces: the known issue "A tab restored at start opened without +the status line or the resume list" (src/shared/app-knowledge.ts) needs +nothing. With the deadline dropped, a session that starts while the check +runs waits up to 5 seconds from its own start for it, which is what the entry +says, and its workaround stands. The side-by-side holds shorten a first tab's +wait. Their trade (decided below) is a case the entry already describes, a +check that takes longer than a session's 5 seconds, and its workaround brings +the scripts back. The `[spawn]` lines are log only. No tip, tour card or README +text names these holds. + +### Decided, and still open + +Decided by the orchestrator, with the owner away (2026-12-03), under the +owner's standing rules (decide, no option rounds; the status line is a top +priority): the run-wide scripts deadline is dropped. The scripts hold is +bounded again from each launch's own ask. Reason: under that deadline a tab +asked late into a slow check (one ending 5 s or more after it began, but +within 5 s of the tab's ask) started without the app's status line for the +session's whole life, and without the resume list. That costs more than up +to about 2.5 s of wait on a slow cold start, and the side-by-side holds +already keep the holds from adding up. + +Decided by the orchestrator in round 5 (2026-12-04), with the owner away, on +the review's finding that the side-by-side holds cost some tabs their +scripts: the holds stay side by side, and that trade is accepted. So this +branch does not keep every tab's scripts as 591eb8fb did. + +- The trade. pty-manager reads the scripts at the spawn, not when the + scripts wait ends. On 591eb8fb a tab whose 5 s ran out still waited for its + other holds, one after another, before its spawn, and a check that ended + in that time gave it its scripts by chance. Side by side, that time is the + saving, and a check that ends in it now costs a Claude Code tab the app's + status line for the session's whole life, and the resume list (it gets the + direct line). A Codex launch's wait for its hook folders still comes after + the holds and, while the Hooks gateway listens, can still cover it. +- The window's bounds. It opens when the tab's side-by-side holds end: its + own 5 s from the ask where the scripts wait is the longest of them, as in + the evidence. It closes where the same holds one after another would have + ended. Its width is the saving, exactly: up to about 0.4 s in the evidence + (the part of the 0.4 to 0.5 s after the scripts wait that was other holds; + not split), up to about 1.4 s where the session folders' work runs after + the scripts wait (1.15 to 1.36 s under load on CI), and more only where + the other holds run longer (the saving grows with it). +- No check is known to have ended in it. The forced red's tab is shown to + have started without its scripts (its launch line was the direct one), so + its check, with its deploys, had not ended by the spawn, 5.4 s after the + submit: past the window's end. The green run's script state at its spawn + was not recorded; for it the reading rests on the b20 first-app check + times. On a runner's first app the check takes 8.8 to 13.6 s + (2026-11-27-b20-snap-d1.md) and the tab is asked about 3 s after main + starts, so the check ends about 5.8 s or more after the ask, about 0.3 to + 0.5 s past the evidence's window. A run whose other holds take longer (the + up to about 1.4 s case above) would put the fastest measured first-app + check inside the window. Where + Windows PowerShell is warm it took 1.0 to 1.6 s (2.6 to 3.5 s with the disk + cache purged): inside the tab's 5 s, and waited for. +- The recheck's probe (round 5's review, on the holds test's harness): a + check begun 3 s before the ask and ended 5.2 s after it, beside a 1.3 s + session folders' hold and a 0.4 s look for Claude Code. On 83a90ab0 the + spawn ran 5000 ms after the ask with the resume list's script not ready + (`checkDeployedScript` ok=false); with the holds one after another, as on + 591eb8fb, it ran 5400 ms after the ask with the script ready (ok=true). + This round keeps it as a test (below). +- Why accepted. A first tab must wait for its slowest hold, not their sum: + one after another the holds' bounds add up (5 s for the scripts, 15 s for + the start's look for Claude Code, 10 s for the session folders, each from + its own call), and a slow first start paid them in turn. The window is the + same time as the saving, so getting it back means waiting as long as + before; the nearest other order (the scripts wait first, the other holds + side by side after it) narrows the window only by giving back as much of + the saving. No check is known to have ended in it, and a check that ends past it + was lost on 591eb8fb too. + +Still open, an owner decision: the runner's cold Windows PowerShell share of +D1. A warm-up step before the Snap step would change what D1 measures; +TAB_MS stays. #513 stays open on this. + +### Tests + +- `tests/unit/main/pty-spawn-holds-side-by-side.test.ts` (new, 17): the real + pty:spawn handler over the real script-folders module, on fake timers, with + a folders stand-in shaped as the real module (one work for every caller, + each wait bounded by what it is given). Covers the evidence case (a check + that never answers, the tab asked 3 s in, beside a 1.3 s folders hold and a + 0.4 s look: the spawn runs 5 s after the ask, not 5.4 s), a check that ends + 6 s after it began with the tab asked 3 s in (waited for; at its spawn the + resume list's script may be run), the trade (the review's probe: a check + that ends 5.2 s after the ask, beside the same holds: the spawn runs 5 s + after the ask with the resume list's script not there, not 5.4 s after it + with the script ready), seven 5 s + 8 s pairs that spawn at 8 s, + sign-in tabs, a check that answers in its usual time, the log rule (1 s, or + still pending), and the folders' one bound: work that never answers spawns + at 10 s with one call and one line (20 s and two calls before the review + round, 10 s on the base); done in time then wanted again spawns at 15 s, + not 18 s; held only by another hold keeps the whole bound. +- `tests/unit/main/spawn-folders-off-main-thread.test.ts` (+1, 1 changed): a + wait waits what it is given and answers whether the work ended in time. +- `tests/unit/main/script-folders.test.ts`: as on the base (round 2's three + deadline tests are gone with the deadline). +- `tests/unit/main/pty-claude-picker-plain.test.ts` (+3): the script state in + the launch's line, only for a resume-list launch, in no line of its own. +- `tests/unit/e2e-launch-evidence.test.ts` (+2): the prompt D1 looks for, not + the banner, wrapped rows included. +- `tests/unit/main/account-profiles-owner-only-wiring.test.ts`: reads the steps + as one of the holds, all awaited before the closed-or-superseded check; + `pty-spawn-waits-for-spawn-folders.test.ts`: its stand-in answers as the + real module does. +- Each new or changed test fails without its fix (source restored from the + commit before, or the helper taken out, then put back and sha-checked), but + one: the "held only by another hold" test guards kept behaviour and is + proven by mutants. Mutants each turn the matching tests red: bound from the + ask, holds one after another, the look and the walk side by side, sign-in + tabs held, the steps held but not awaited, an await with nothing to hold; + the ask again whenever the folders are wanted, with the whole bound, after + a wait that ran out, from the launch's ask, or only for launches held for + the folders; the module ignoring the time it is given or answering wrongly; + logging every hold, only by time, from 250 ms, with the old words; the script + state dropped, said for every launch, or in a line of its own; the prompt + test matching the banner or missing a wrapped location. +- Round 3 (the deadline dropped): the evidence case and the 6 s case are red + on round 2's source (the run's deadline: the tab spawns 2 s after its ask) + and under a deadline from the check's start put back into the fixed code. + The evidence case is red with the holds one after another too (5.4 s), and + the 6 s case with the scripts hold taken out. Its check of the script at the + spawn is red on its own under the deadline (the script not yet deployed), + with the test's earlier checks taken out. The short still-pending line, now + read from a 500 ms look, is red when a hold is said only by its time. +- Round 5 (the trade, accepted): the trade test is red with the holds one + after another (11 of 17 red; it spawns 5.4 s after the ask), and on + 591eb8fb's pty-handlers.ts and script-folders.ts (16 of 17 red; 5.4 s too). + With its spawn-time and log checks taken out it is red on what the launch + finds at its spawn alone (the script ready, `{ ok: true }`). Each run put + the files back and sha-checked them. + +Not measured: the split of the remaining 0.4 to 0.5 s, and the check's start +time at boot (it begins in a microtask after the start's synchronous setup, +index.ts). The tab's own Windows PowerShell start (5.2 s from spawn to the +stand-in in the green run) is the runner's cold start, outside these holds. diff --git a/CONTEXT.d/2026-12-04-b28-accounts-followups.md b/CONTEXT.d/2026-12-04-b28-accounts-followups.md new file mode 100644 index 000000000..a1ab5f9fd --- /dev/null +++ b/CONTEXT.d/2026-12-04-b28-accounts-followups.md @@ -0,0 +1,119 @@ +## 2026-12-04 -- beta.28: a plain SSH tab's usage reaches its account (planning #516), and the Accounts page's rows (planning #517) + +Premise: after beta.27 shipped the Accounts page, two faults were open. (1) An account used only +from another machine over plain SSH read "Not in use" at its last background reading, while the +tab's own status line showed live figures (#516). (2) The page's closed lines came in two heights, +said the same thing several times, and opened one at a time (#517). Both are built on one branch +(fix/b28-accounts-followups, from beta 591eb8fb) and go to beta as one PR. + +What changed, #516: + +- **Cause.** The usage sink's no-local-profile branch (account-usage.ts, recordLiveUsageForSession) + returned when a report carried no transcript path, before it read the email or marked the session + open. The SSH status line shim never sends a transcript path (only the local bridge does), so + every plain SSH report was dropped. The gate was there to keep a session helper tab's frames out, + whose bars are this computer's own reading. Evidence: every plain SSH tab logged the usual SSH + path and no refused status post, and the account's snapshot was not rewritten while its tab + reported. The drop left no log line. +- **Fix.** The check that tells a helper frame apart is fixed, not the shim (a shim change would + need every remote's shim pushed again, would feed a remote path to the local transcript binder, + and lands inside the SSH blast radius). deliverStatus (session-signals/status.ts) takes an + optional { usageIsThisComputers }; both helper delivery points in statusline-watcher.ts pass it, + so a helper tab's joined bars never loop back as its live reading (its own windows still come in + by noteHelperReading / recordHelperTabUsage). The transcript-path gate in account-usage.ts is + gone; the email check, the profile match by email and noteRemoteSessionProfile stay. + ssh-shim.ts and pty-manager.ts are unchanged. +- **The not-filed log line.** A report that is not filed now logs one line per session, saying why + ("its status line names no account email", or "no account profile on this computer has the email + its status line names"). It carries neither the email nor a path, and later reports of the same + session are not logged, so a session reporting every few seconds cannot fill the log. +- **Not security-sensitive (ADR-009).** No IPC, preload, MCP server, PTY argv, credential or + updater code is touched. The removed gate never stopped a hostile remote: the transcript path + came from the same remote-controlled payload and any short string passed it. The reading is + display only. statusline-watcher.ts is on the SSH live-matrix list, which the owner retired on + 2026-11-22, so unit tests cover it. +- **Follow-up owed: CLAUDE_CONFIG_DIR.** A tab over SSH is matched by the email in the .claude.json + file in the remote home folder (the gather reads it; the shim is unchanged by decision). A + CLAUDE_CONFIG_DIR set there, signed in as another account, files that tab's figures under the home + folder's account and counts it In use. #516 made this visible, because those reports used to be + dropped. For now it is a known issue with a workaround in app-knowledge (leave CLAUDE_CONFIG_DIR + unset for the tabs the app opens). The follow-up makes the statusline gather prefer + CLAUDE_CONFIG_DIR. Also open: the gather reads .claude.json only under 5 MB, and above that no + email is sent, so such a tab is still not filed (the new log line names it). + +What changed, #517: + +- Lines open and close on their own; Escape closes only the open line that holds the keyboard + focus. Every closed line is one shape (64 px, two lines); "N running" is on the open line's + Running row only; a per-model window at 90% or more is named on the last account-wide line; an + estimate's figures read "~"; every note is on the open line's Usage read row; the background + check's rate limit is said once, in the Usage heading; a strong rule between lines + (ROW_RULE); what isolation changed is one entry at the page's foot (AccountIsolationChanges), + grouped only where id, title and detail are all equal. + +Where the build departs from the spec (517-spec.json) on purpose, and why: + +- **The heading's words.** The spec said "Rate limited", a middle dot, "next check in 9:32" beside + "Usage". That read as the usage being limited, which is false and alarming: only the app's + background check of idle accounts waits and no session stops. The heading is now "Usage" alone at + the left and, at the column's right end over the reset times, "Background check rate limited", a + middle dot, "retries in 9:32" ("background check" is the page's own term). An open line's Usage + read row keeps "Rate limited", a middle dot, "next check in 9:32", since its label gives the + subject. The countdown sits in a child with aria-live off, so a screen reader does not announce + it every second for a wait of up to 4 hours. +- **Line 2 is a flex row of three items, not one span cut at its end.** At the wide layout's own + threshold the single span lost "Reviewer", and the roles are said nowhere else. The email + truncates first (shrink-[1000], down to 4 characters), the separator is its own shrink-0 item, + the roles truncate last. +- **The hot per-model phrase is a name and a figure.** A long name ("GPT-5.3-Codex-Spark Weekly") + pushed its figure out of the reset track, so the name truncates and the figure (" 92% used") is + shrink-0. +- **Tooltips under the toggle are data-cut with titleOfCutUnder, not titleWhenCut.** The toggle is + stretched over the whole line (after:inset-0) and takes every pointer event there, so a + titleWhenCut handler under it never ran. The line's text that can be cut is marked data-cut, + holding its whole words, and the toggle's onMouseMove gives the toggle that text as its title + while it is cut. Its onMouseLeave takes the title away, because a fast exit can skip the move + that would have cleared it and a stale title is read out as the toggle's description. + titleWhenCut stays on the open part, which the toggle does not cover. +- **The open part's region has tabIndex -1 (the Expand wrapper in LedgerRow).** A click on its + plain text moved the focus to the page body, so Escape, which closes the line holding the focus, + closed nothing. It is never a tab stop, and a mouse focus shows no ring. +- **The summary marks its estimate with "~" too.** "Most room now: Family, 0% of 5h and 18% of + the week used." sat over a line reading "~0% used". One rule, figuresAreEstimate in usage-parts, + is shared by the line and the summary. How readings work also says what "~" means. +- **pausedUntil leaves out parked, off, pending and sign-in lines as well as lines in use.** Spec + 2.7 says only "not in use". Those lines never drew the countdown before #517 and no check of + theirs waits, so the heading does not count down for them. +- **READINGS_NOTE_ROOM_PX is 240 (was 220).** The note gained the "~" sentence and is one 20 px + line taller. +- **With no account-wide window, the one per-model window used most is shown, not "the one at 90% + or more".** The spec's own aim is that the cell is never empty, and a reading whose only windows + are lower per-model ones would otherwise be empty. +- **Smaller additions from the UX review.** The first note of a Usage read row with no source line + is the row's value in the row's own 12 px style (a note after a source line stays quiet); its + container is a div, since a paragraph is not phrasing content; the isolation list scrolls into + view when opened at the page's foot and its sentences are capped at 720 px; the lead note and the + window-ages span take a title while they are cut. + +Tests retired, each replaced by one that holds the new behaviour: + +- #516: "a frame with no transcript path ... is never filed" (it encoded the bug; the shape a real + shim sends, with no transcript path, is now filed and the account is in use), and the helper + test's assertion that the sink is offered the tab's bars with no transcript path (the sink is now + offered nothing). +- #517: "keeps info findings behind a toggle rather than dropping them" (the row notice keeps only + a refused or unchecked launch; the foot's grouping tests hold the info findings); "one line open + at a time" (independent opening and focus-scoped Escape); the three-line Account cell tests (the + email alone on line 2 with the roles on line 3, no roles and nothing running: no third line, no + email: the roles are line 2), the third-line per-model test, and the "quiet notes: at most one on + the closed line" group (every note is on the open line now); and the e2e layout spec's 64 or + 84 px lines (every line is 64 px). + +The review-round commits (d08ffc1f1 to a58e51194) name each mutant that turned its assertion +red, and each file was restored byte for byte. 2ec39cfea names the delivery-point mutant. +d40240bb9's mutants are not recorded. The e2e layout spec is not run locally; it runs in the Snap e2e job on +a dispatch. + +Changelog: the user-facing lines for both go into src/renderer/changelog.ts and CHANGELOG.md with +the beta.28 release commit, as for beta.27, not on this branch. The other surfaces (app-knowledge, +the tips, the tour, README, USER_GUIDE) are already updated here. diff --git a/CONTEXT.d/2026-12-04-b28-helper-stdin-deadline.md b/CONTEXT.d/2026-12-04-b28-helper-stdin-deadline.md new file mode 100644 index 000000000..d79621795 --- /dev/null +++ b/CONTEXT.d/2026-12-04-b28-helper-stdin-deadline.md @@ -0,0 +1,55 @@ +## 2026-12-04 -- beta.28: the helper's hook and status modes stop waiting for standard input at their deadline + +Premise: the macOS Helper job of the beta.28 aggregate (PR #772) failed +helper/tests/status.rs a_status_run_whose_standard_input_never_ends_ends_within_2_s: the run exited +0 after 3.006 s, against a 2.5 s bound and a 2 s deadline. Nothing under helper/ changed in beta.28. + +Diagnosis, from the job logs (measurements, not a settled cause): + +- In both modes the work read standard input with a plain blocking read: the one wait in the work + that the deadline did not bound (connecting to the holder, its hello and its reply all wait at most + the time left). A run whose input never ends was therefore ended only by the main thread's single + 2 s wait, with the work still asleep in the read. +- On macOS that shape measured 2.1 to 2.4 s in the status mode in six earlier passing jobs, 3.0 s in + the failing one, and 2.12 to 2.23 s in the hook mode's identical test. Runs whose work stops waiting + at the deadline by itself (a holder that never answers, no hello) measured 2.01 to 2.04 s each on + macOS. Linux and Windows measured at most 2.05 s for both shapes. +- Not start-up: two whole helper runs took 20 ms together on the same runner. +- Open: the late runs are timed by the tests' polling of the process (try_wait every 20 ms), the + on-time ones by a blocking wait for it, so the logs alone do not tell lateness in the helper from + lateness in that polling on macOS. If the next macOS Helper job still shows the never-ends tests at + 2.1 s or more, the tests' polling is the next suspect. The bound is not widened. + +Fix (helper/src/hook.rs, status.rs, transport/): + +- `hook::read_stdin_by(deadline)`, used by both modes: on macOS and Linux each read of standard input + first waits in poll, at most 100 ms at a time, and gives up once the deadline has passed, so the + work stops at the deadline by itself. A descriptor poll cannot watch (POLLNVAL; the poll(2) manual + of macOS says so of devices, a terminal among them) is read as before. EAGAIN after a positive poll + goes back to the poll. Windows reads as before. +- The main thread of both modes waits for the work in waits of at most 100 ms until the deadline: + the main thread's wait is no longer one long timer, so the run ends by the deadline whatever the + work is blocked in. +- The poll loop is shared with the macOS socket read (`transport::poll_readable`); that read keeps + its 1 s slices and its timeout error. +- Tests: unit tests over a pipe (input that ends in time, input still open at the deadline, input + over the 4 MiB cap), one for the main thread's wait, and both never-ends tests now also assert the + run did not end before its deadline. The code was not compiled where it was written; the Helper + jobs in CI are its first build and run. + +Open, not fixed: nothing tests that the macOS and Linux `read_stdin_by` reads descriptor 0 through +the deadline-bound reader. The unit tests call `read_fd_by` on a pipe of their own, and in the +never-ends tests the main thread ends the run at the deadline whatever the work is blocked in. So +changing only that `read_stdin_by` back to a blocking read of standard input keeps every test green +on Linux; on macOS only the timing of the never-ends tests could show it. Closing it takes a child +test: an `#[ignore]`d test that calls `read_stdin_by` with a deadline 300 ms ahead and returns, +started by a parent test through the test binary with `--exact --ignored` and a standard input pipe +the parent holds open, the parent asserting the child exits within about 1.5 s. It is not added here +because the crate has no such pattern to copy: it has no `#[ignore]`d test, and the two files that +start the test binary again (store.rs, pids.rs) give it a filter that matches no test, so the child +exits at once. A child test would be new, uncompiled machinery, and a child filter that matched +nothing would exit 0 at once and pass without running the check. Add it where it can be built and +shown to fail against a blocking read. + +No user-facing change: hook events and status updates whose input has not ended by the 2 s deadline +were lost before and are lost now; only when the helper stops waiting changes. No changelog line. diff --git a/README.md b/README.md index fa0616cb9..634e3255f 100644 --- a/README.md +++ b/README.md @@ -93,8 +93,8 @@ On-demand reports over your own usage, Claude Code's and Codex's, runnable acros - **Feature Guide** — a searchable in-app reference with a card for every feature (what it does, how to open it, a tip) plus the complete What's New history, a click away from the sidebar's help button. - **Browser pane** — every session has a browser beside its terminal: an address bar (type `localhost:5173` and press Enter), working history, a home page per config, saved favourites, and a button to open the page in your real browser. Pages load in a sandbox with every permission off. A command button can point it at a dev server as it starts ("watch for a page") or simply open a page; freeze the page to annotate a snapshot in Excalidraw. - **Partner terminal and scratchpad** — every session carries a partner shell in the same tab (on the host, for an SSH session), and a per-session Excalidraw whiteboard that persists with the config; export the drawing straight into the session. -- **Machines and the session helper**: the Machines page on the left rail shows This computer, led by the mark and name of its system, with its session helper's state, version and self-test and the terminals the helper holds, each with Re-attach and End. The helper is a small program that comes with the app. With **Settings → General → Plain terminals through the session helper** on (a preview, off by default), local Terminal only tabs and the partner terminals of local sessions run inside it, so on Windows they keep running if the app crashes and come back in their tabs when you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, and the new version shows them again. A second preview switch, **Settings → General → Claude Code and Codex sessions through the session helper** (also off by default), starts local Claude Code and Codex sessions inside it too, launched exactly as before, and the Machines page lists them with End; they do not survive a crash yet, and after one each tab resumes its conversation. If the app only freezes for a while, what the helper holds keeps running and each tab shows it again once the app answers, and a tab whose terminal or session was lost all the same starts it again by itself, at most once a minute. On Windows they do survive an app update when you choose Save sessions: each restored tab takes over the same running session, with no resume, even a tab you open later. A third preview on Windows: the Machines page adds a Linux x86-64 or arm64 machine you reach over SSH with a key or a saved password (one file uploaded with your consent, its SHA-256 checked, a self-test; a later Check installs the new helper after an update and removes the earlier copies that no session there still uses and the files of ended sessions, saying how many); each machine's card leads with the mark of its system (Ubuntu, Rocky Linux, Debian, Fedora, a Raspberry Pi, or the Linux penguin), names the system and its version, and says when the machine was last seen or that it is not reachable, and the list filters and sorts when there are many. With **Settings → General → Remote sessions through the session helper** on (off by default) a Claude Code SSH tab to it runs through the helper there with nothing typed into the host's shell, and so does a Codex config (through the helper only), on Linux x86-64 so far; Codex on an arm64 machine has not been tried yet. An SSH Persistent tab there is kept until you end it: choose Leave running when you close it, or quit or update the app, and the next start brings it back where it was; the Machines page lists the sessions each machine keeps, with Re-attach and End. A Terminal only SSH tab and the partner terminal beside an SSH tab go through the helper too, with a config's After connecting, run command (a saved sudo password answers a sudo that command calls by name); a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you add, check or remove a machine or open a tab there, and held in memory only. On a machine that ends your processes when you log out, an SSH Persistent tab goes through the helper too and is held by its connection, not kept. A Claude Code or Codex session there has a Restart menu: Restart Claude Code (or Codex) on the machine ends that program there and starts it again on the same conversation, so an update applies. Its status line, hooks and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) go through the helper too: a picture goes to the machine over the tab's own connection and Claude Code there pastes it with its own paste key (a Codex session there takes pictures the same way, reading the picture from a private socket the helper makes for that session), and a Codex review asked for from the tab runs on that machine, as does a Claude review asked for from a Codex session there (Linux x86-64 so far); its status line names the account Claude Code is signed in as on that machine, and when this computer holds that account, the Accounts page counts it In use, takes the 5-hour and weekly figures the tab reports as its reading, and the tab shows the reading this computer holds (the weekly limits by model and extra usage among them until the tab first reports, and the limits by model while a Claude Code session on this computer runs on that account too); otherwise it says they are not available. In the same preview, each of your Claude Code and Codex accounts can sign in once on a Linux machine you added: the machine's card lists them under **Accounts**, folded to one line until you open it, with **Sign in** on each account's row (the assistant's own sign-in runs in a tab there, Codex's as its device sign-in, and the sign-in stays on that machine, in a folder of its own that only your user there can read), **Sign out**, and a **Remove** that signs the accounts out first. A Claude Code tab or Codex session through the helper starts on its config's account (a Codex config with no account runs on the machine's own Codex sign-in), and when that account is not signed in there a notice offers to sign in on the machine, use another account or cancel. **Switch Account** works on such a tab. There is no Lend from this computer yet. -- **Multi-account usage strip** — every signed-in account's usage along the bottom of the window, one pill per person, grouped by provider so Claude Code and Codex figures are never merged, and a minimal mode that shows just the account name and two traffic-light dots (green under 70 %, amber to 89 %, red from 90 %) so the strip stays readable with many accounts. The **Accounts** page shows every Claude and Codex account's 5-hour and weekly allowance at once, one line each: each bar fills with what is used, the lines are grouped In use, Not in use and Not usable now, you sort by Room, Weekly or Name, and with both assistants on you can show one of them. The **Most room now** line above the groups names the free account with the most room, and a line says when it is out of its limit until a time, inactive, or must sign in again. Click a line to open it for its sign-ins: Claude Code's or Codex's, and the account's claude.ai or chatgpt.com sign-in, who it is signed in as and since when. There is no Refresh, and the page never asks for a reading itself: an account in use reads live from its session, an idle one keeps its last reading (a window past its reset reads 0% used), and the app checks the usage of idle accounts still signed in, Claude Code's and Codex's, in the background, one at a time, at least 10 minutes apart and each account at most every 3 hours; while Anthropic rate-limits those checks, the lines count down to the next one. Sign-ins on a machine you added (remote sessions preview) are on that machine's card on the Machines page. +- **Machines and the session helper**: the Machines page on the left rail shows This computer, led by the mark and name of its system, with its session helper's state, version and self-test and the terminals the helper holds, each with Re-attach and End. The helper is a small program that comes with the app. With **Settings → General → Plain terminals through the session helper** on (a preview, off by default), local Terminal only tabs and the partner terminals of local sessions run inside it, so on Windows they keep running if the app crashes and come back in their tabs when you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, and the new version shows them again. A second preview switch, **Settings → General → Claude Code and Codex sessions through the session helper** (also off by default), starts local Claude Code and Codex sessions inside it too, launched exactly as before, and the Machines page lists them with End; they do not survive a crash yet, and after one each tab resumes its conversation. If the app only freezes for a while, what the helper holds keeps running and each tab shows it again once the app answers, and a tab whose terminal or session was lost all the same starts it again by itself, at most once a minute. On Windows they do survive an app update when you choose Save sessions: the new version reopens your tabs with nothing asked (no resume prompt, no account picker), and each restored tab takes over the same running session, with no resume, even a tab you open later. An update from 2.1.3-beta.27 or earlier still asks, once, as opening the app again does. A third preview on Windows: the Machines page adds a Linux x86-64 or arm64 machine you reach over SSH with a key or a saved password (one file uploaded with your consent, its SHA-256 checked, a self-test; a later Check installs the new helper after an update and removes the earlier copies that no session there still uses and the files of ended sessions, saying how many); each machine's card leads with the mark of its system (Ubuntu, Rocky Linux, Debian, Fedora, a Raspberry Pi, or the Linux penguin), names the system and its version, and says when the machine was last seen or that it is not reachable, and the list filters and sorts when there are many. With **Settings → General → Remote sessions through the session helper** on (off by default) a Claude Code SSH tab to it runs through the helper there with nothing typed into the host's shell, and so does a Codex config (through the helper only), on Linux x86-64 so far; Codex on an arm64 machine has not been tried yet. An SSH Persistent tab there is kept until you end it: choose Leave running when you close it, or quit or update the app, and the next start brings it back where it was; the Machines page lists the sessions each machine keeps, with Re-attach and End. A Terminal only SSH tab and the partner terminal beside an SSH tab go through the helper too, with a config's After connecting, run command (a saved sudo password answers a sudo that command calls by name); a key passphrase, or a password no config of the machine keeps, is asked for in a dialog when you add, check or remove a machine or open a tab there, and held in memory only. On a machine that ends your processes when you log out, an SSH Persistent tab goes through the helper too and is held by its connection, not kept. A Claude Code or Codex session there has a Restart menu: Restart Claude Code (or Codex) on the machine ends that program there and starts it again on the same conversation, so an update applies. Its status line, hooks and the Conductor's tools (the Agent Canvas, the browser, and image paste and Snap) go through the helper too: a picture goes to the machine over the tab's own connection and Claude Code there pastes it with its own paste key (a Codex session there takes pictures the same way, reading the picture from a private socket the helper makes for that session), and a Codex review asked for from the tab runs on that machine, as does a Claude review asked for from a Codex session there (Linux x86-64 so far); its status line names the account Claude Code is signed in as on that machine, and when this computer holds that account, the Accounts page counts it In use, takes the 5-hour and weekly figures the tab reports as its reading, and the tab shows the reading this computer holds (the weekly limits by model and extra usage among them until the tab first reports, and the limits by model while a Claude Code session on this computer runs on that account too); otherwise it says they are not available. In the same preview, each of your Claude Code and Codex accounts can sign in once on a Linux machine you added: the machine's card lists them under **Accounts**, folded to one line until you open it, with **Sign in** on each account's row (the assistant's own sign-in runs in a tab there, Codex's as its device sign-in, and the sign-in stays on that machine, in a folder of its own that only your user there can read), **Sign out**, and a **Remove** that signs the accounts out first. A Claude Code tab or Codex session through the helper starts on its config's account (a Codex config with no account runs on the machine's own Codex sign-in), and when that account is not signed in there a notice offers to sign in on the machine, use another account or cancel. **Switch Account** works on such a tab. There is no Lend from this computer yet. +- **Multi-account usage strip** — every signed-in account's usage along the bottom of the window, one pill per person, grouped by provider so Claude Code and Codex figures are never merged, and a minimal mode that shows just the account name and two traffic-light dots (green under 70 %, amber to 89 %, red from 90 %) so the strip stays readable with many accounts. The **Accounts** page shows every Claude and Codex account's 5-hour and weekly allowance at once, one line each: each bar fills with what is used, the lines are grouped In use, Not in use and Not usable now, you sort by Room, Weekly or Name, and with both assistants on you can show one of them. The **Most room now** line above the groups names the free account with the most room, and a line says when it is out of its limit until a time, inactive, or must sign in again. Click a line to open it for its sign-ins: Claude Code's or Codex's, and the account's claude.ai or chatgpt.com sign-in, who it is signed in as and since when. There is no Refresh, and the page never asks for a reading itself: an account in use reads live from its session, an idle one keeps its last reading (a window past its reset reads 0% used), and the app checks the usage of idle accounts still signed in, Claude Code's and Codex's, in the background, one at a time, at least 10 minutes apart and each account at most every 3 hours; while Anthropic rate-limits those checks, the page's Usage heading counts down to the next one, once for the whole page. Sign-ins on a machine you added (remote sessions preview) are on that machine's card on the Machines page. - **Snap and Vision capture** — region or window capture from any screen, capped at 1920px, with a JPEG copy saved. Snap puts the picture on your clipboard and presses the assistant's own paste key, so a Claude Code or Codex session gets it as its own pasted image with a short sentence, and no file path is typed; the picture stays on your clipboard afterwards. An SSH tab on the usual path fetches it over the tunnel. `Alt+V` (`Option+V` on a Mac) pastes a clipboard image the same way, and `Ctrl+V` (`Cmd+V`) does too when the clipboard holds only a picture; in a plain terminal, `Alt+V` goes to the program there as a key. On Linux, Claude Code reads the clipboard with `xclip` or `wl-paste`, and the hint names them when the one your desktop needs (`xclip` under X11, `wl-paste` under Wayland) is not installed. On a Mac, Snap checks the Screen Recording permission first and, without it, offers to open System Settings instead of capturing. On Windows, Snap's region capture uses the app's own overlay (a rectangle or the whole screen, no drawing tools); the earlier Snap is a setting away and opens by itself for any press the new one cannot take. - **A first-run tour and What's New that know where you came from**: a fresh install gets the tour; an update shows what is new since the version you came from (every prerelease of a release shows that release's whole story, and release notes can open with warnings, shown first, including those of any release you skipped), and an update across a release line also walks the tour again. diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index fa1046e0c..bf171ea9a 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -252,10 +252,12 @@ promised: settings edited after a session has started; settings your organisation manages, which Claude Code fetches for a signed-in account; and a program running as you on this machine, which can change what a session sees. A project on a network path is not checked at all — reading it could freeze CCC -— so such a session starts with a warning instead of a check. Settings → -*Accounts* shows what was left out for each account, says when a session was -refused and why, and says when a session started with something unchecked, -rather than pretending otherwise. +— so such a session starts with a warning instead of a check. The +**Accounts** page says, under an account's line, when a session was refused +and why, or started with something unchecked; and **What account isolation +changed**, at the foot of the page, shows what was left out, each change once +under the names of the accounts it was left out for, rather than pretending +otherwise. **What it is not.** It is not a sandbox. Hooks, status line commands and everything else in your settings still run, and a session can read and write @@ -362,9 +364,11 @@ Claude and Codex. it). The name, colour and group show on every linked account, and the colour on the account's chips everywhere. (This computer's own sign-in has no name field and cannot be linked.) -- An account's line says how many tabs run on it (*2 running*). When an - account cannot be made inactive, archived or removed because tabs use it, - its line opens and names each one with **Go to**. +- An account's open line names the tabs running on it, on its **Running** + row. Lines open and close on their own, so several can be open at once, and + Escape closes the one you are in. When an account cannot be made inactive, + archived or removed because tabs use it, its line opens and names each one + with **Go to**. - If an account's name or colour is changed both in CCC and in Claude's own account list, the top of the Accounts page shows both and lets you pick one (**Keep this app's** or **Use Claude Code's**). diff --git a/docs/wp1/legacy-codex-manifest.json b/docs/wp1/legacy-codex-manifest.json index 33f615377..7ca390967 100644 --- a/docs/wp1/legacy-codex-manifest.json +++ b/docs/wp1/legacy-codex-manifest.json @@ -1,9 +1,9 @@ { "schema": "wp1-legacy-codex-manifest/3", - "generatedAt": "2026-12-03T20:05:11.321Z", - "head": "24b5a8e91bfcb3bc40cab91d78753b8ace8007ca", - "tree": "b262ccbc44e14aa955b663afd798b7864eeb2452", - "scannedWorkingTree": false, + "generatedAt": "2026-12-04T03:39:00.053Z", + "head": "9985f2293a2a817b97dae11dc37870f6af436501", + "tree": "a2f8481b5b7cbfca05d18fba7bdda7db38c64b2b", + "scannedWorkingTree": true, "predicateDigest": "100a1233edebdc39a5f9004d3fba980a89ebb15b25872e52076386bc84b03153", "predicates": [ { @@ -116,9 +116,9 @@ "\\.(png|jpg|jpeg|gif|ico|icns|webp|svg|woff2?|ttf|otf|mp4|zip|asar|node|exe|dll|dylib|so|pdf)$", "^package-lock\\.json$" ], - "trackedFileCount": 4326, - "excludedFileCount": 725, - "scannedFileCount": 3601, + "trackedFileCount": 4339, + "excludedFileCount": 727, + "scannedFileCount": 3612, "unscopedFileCount": 15, "unscoped": [ ".claude/settings.json", @@ -139,8 +139,8 @@ ], "unscopedMentions": [], "unreadable": [], - "matchedPathCount": 1290, - "pathDigest": "968553bf40dc14d49e73abdc00b181f83e2e32ade85da4b0cebd194941e80ed3", + "matchedPathCount": 1293, + "pathDigest": "a468efd3b01139459cc2215f89be5fb827407a42141015fe9ff18b1ddafbe65b", "entries": [ { "path": ".github/workflows/ci.yml", @@ -4093,6 +4093,13 @@ ], "lineCount": 29 }, + { + "path": "src/renderer/utils/closeDialogText.ts", + "predicates": [ + "P11" + ], + "lineCount": 3 + }, { "path": "src/renderer/utils/heldTerminalLost.ts", "predicates": [ @@ -4183,7 +4190,7 @@ "P12", "P14" ], - "lineCount": 220 + "lineCount": 224 }, { "path": "src/shared/ask-conductor-provider.ts", @@ -4364,6 +4371,13 @@ ], "lineCount": 60 }, + { + "path": "src/shared/update-keep.ts", + "predicates": [ + "P14" + ], + "lineCount": 1 + }, { "path": "tests/e2e/cloud-agents.spec.ts", "predicates": [ @@ -7034,7 +7048,7 @@ "predicates": [ "P13" ], - "lineCount": 32 + "lineCount": 33 }, { "path": "tests/unit/main/session-helper-update-keep.test.ts", @@ -8331,7 +8345,7 @@ "predicates": [ "P13" ], - "lineCount": 10 + "lineCount": 12 }, { "path": "tests/unit/renderer/accounts-row-actions.test.tsx", @@ -8362,7 +8376,7 @@ "predicates": [ "P13" ], - "lineCount": 17 + "lineCount": 21 }, { "path": "tests/unit/renderer/active-indicator.test.tsx", @@ -8477,6 +8491,13 @@ ], "lineCount": 15 }, + { + "path": "tests/unit/renderer/beta28-release-copy.test.ts", + "predicates": [ + "P13" + ], + "lineCount": 5 + }, { "path": "tests/unit/renderer/boot-gates.test.ts", "predicates": [ @@ -9445,7 +9466,7 @@ "P07", "P13" ], - "lineCount": 44 + "lineCount": 48 }, { "path": "tests/unit/renderer/session-persistence-resume.test.ts", @@ -10071,7 +10092,7 @@ "P04", "P13" ], - "lineCount": 625, + "lineCount": 628, "truncated": true }, { diff --git a/helper/src/hook.rs b/helper/src/hook.rs index 8a34f7d7c..a72f18331 100644 --- a/helper/src/hook.rs +++ b/helper/src/hook.rs @@ -67,10 +67,21 @@ const EVENT_ID: u64 = 2; /// more, whatever else a holder offers (`serve::HOLDER_CAPS`), so every /// holder from 2.1.3-beta.8 on takes it. pub const ACK_CAPS: [&str; 3] = ["core", "local", HOOKS_CAP]; +/// The longest any one wait of the hook and status modes lasts: the main +/// thread's wait for the work (`wait_for_work`) and, on macOS and Linux, +/// each wait for standard input (`StdinBy`). Each then looks at the +/// deadline, and the input, afresh: a wakeup that is lost costs at most +/// this, and no wait is one long timer. Why: `read_stdin_by`. +pub(crate) const RECHECK: Duration = Duration::from_millis(100); /// Run the hook mode on `args` (what follows `hook`). It returns by the /// deadline whatever the work is still waiting on (standard input that never -/// ends, a holder that never answers); the process then exits with it. +/// ends, a holder that never answers), in short waits (`wait_for_work`); the +/// process then exits with it. The work's own waits end by the deadline too: +/// for the holder's connection, hello and reply on every system, and for +/// standard input on macOS and Linux (`read_stdin_by`), except an input poll +/// cannot watch (POLLNVAL; the poll(2) manual of macOS says so of devices, a +/// terminal among them), which is read as before. pub fn run(args: &[String]) { let deadline = Instant::now() + DEADLINE; let args = args.to_vec(); @@ -80,8 +91,20 @@ pub fn run(args: &[String]) { let _ = done_tx.send(()); }); if worker.is_ok() { - // Done, failed, panicked (the sender is dropped) or out of time. - let _ = done.recv_timeout(deadline.saturating_duration_since(Instant::now())); + wait_for_work(&done, deadline); + } +} + +/// The hook and status modes' main thread: wait for the work (`done`) until +/// `deadline`, in waits of at most `RECHECK`. It returns once the work is +/// done, failed or panicked (its sender is dropped), or the deadline has +/// passed, whatever the work is still waiting on. +pub(crate) fn wait_for_work(done: &mpsc::Receiver<()>, deadline: Instant) { + while let Some(rest) = left(deadline) { + match done.recv_timeout(rest.min(RECHECK)) { + Err(mpsc::RecvTimeoutError::Timeout) => {} + Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => return, + } } } @@ -92,7 +115,7 @@ pub fn run(args: &[String]) { /// (`codex_status`, `status::post`); losing one loses nothing of the other. fn deliver(args: &[String], deadline: Instant) -> Option<()> { let (store_dir, sid) = parse_args_or_env(args, from_env)?; - let input = read_stdin()?; + let input = read_stdin_by(deadline)?; let (kind, payload) = event_from(&input)?; let status = crate::codex_status::status_for_event(&payload, from_env); let rec = store::read(&store_dir, &sid)?.ok()?; @@ -184,11 +207,78 @@ fn finish(store_dir: Option<&str>, sid: Option<&str>) -> Option<(PathBuf, String Some((PathBuf::from(store_dir), sid.to_string())) } -/// Standard input to its end, at most `MAX_STDIN` bytes of it kept. -pub(crate) fn read_stdin() -> Option> { +/// Standard input to its end, at most `MAX_STDIN` bytes of it kept +/// (`read_capped`): the hook and status modes' input. On macOS and Linux it +/// is not waited for past `deadline` (`read_fd_by`): input that has not +/// ended by then loses the event or the update, and the work stops there by +/// itself, as it does waiting on a holder that never answers. +/// +/// What this rests on, measured in CI while the read was a plain blocking +/// one and only the main thread's single 2 s wait ended such a run. On +/// macOS a run whose input never ended measured 2.1 to 2.4 s in the status +/// mode (once 3.0 s) and 2.12 to 2.23 s in the hook mode; Linux and Windows +/// measured at most 2.05 s. On macOS, runs whose work stopped waiting at +/// the deadline by itself (a holder that never answers, no hello) measured +/// 2.01 to 2.04 s each. The late runs were timed by the tests' polling of the +/// process (`try_wait` every 20 ms), the on-time ones by a blocking wait for +/// it, so these numbers alone do not tell lateness in the helper from +/// lateness in that polling on macOS. +#[cfg(unix)] +pub(crate) fn read_stdin_by(deadline: Instant) -> Option> { + read_fd_by(libc::STDIN_FILENO, deadline) +} + +/// On Windows standard input has no deadline of its own: a read still +/// waiting at the deadline ends with the process. +#[cfg(not(unix))] +pub(crate) fn read_stdin_by(_deadline: Instant) -> Option> { read_capped(std::io::stdin().lock(), MAX_STDIN) } +/// `fd` read as standard input is (`read_stdin_by`): to its end, at most +/// `MAX_STDIN` bytes of it kept, and not waited for past `deadline` +/// (`StdinBy`). +#[cfg(unix)] +fn read_fd_by(fd: std::os::fd::RawFd, deadline: Instant) -> Option> { + read_capped(StdinBy { fd, deadline }, MAX_STDIN) +} + +/// A descriptor read straight, as the hook and status modes read standard +/// input on macOS and Linux (nothing else in the process reads it). Each +/// read first waits in poll (`transport::poll_readable`), at most `RECHECK` +/// at a time, and once `deadline` has passed fails as timed out instead, so +/// `read_capped` gives None. A descriptor poll cannot watch (POLLNVAL; the +/// poll(2) manual of macOS says so of devices, a terminal among them) is +/// read at once, and so waited for as before, with no deadline of its own. +/// A read that finds nothing on a descriptor set not to wait (EAGAIN: bytes +/// poll saw were taken by another process sharing it) waits in poll again; +/// on a descriptor poll cannot watch it fails, as such a read did before. +#[cfg(unix)] +struct StdinBy { + fd: std::os::fd::RawFd, + deadline: Instant, +} + +#[cfg(unix)] +#[allow(unsafe_code)] +impl Read for StdinBy { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + loop { + let Some(seen) = crate::transport::poll_readable(self.fd, Some(self.deadline), RECHECK)? else { + return Err(std::io::Error::from(std::io::ErrorKind::TimedOut)); + }; + let n = unsafe { libc::read(self.fd, buf.as_mut_ptr().cast(), buf.len()) }; + if n >= 0 { + return Ok(n as usize); + } + let e = std::io::Error::last_os_error(); + if e.kind() != std::io::ErrorKind::WouldBlock || (seen & libc::POLLNVAL) != 0 { + return Err(e); + } + } + } +} + /// `r` to its end. None when it could not be read, or held more than `max` /// bytes: the rest is still read, so the writer is not cut off, and nothing /// of it is kept. @@ -518,6 +608,30 @@ mod tests { assert_eq!(read_capped(Interrupted(false), 10), Some(Vec::new())); } + #[test] + fn the_main_thread_waits_for_the_work_until_its_deadline_and_no_longer() { + // Nothing comes: it waits, in short waits, until the deadline. + let (_held, rx) = mpsc::channel::<()>(); + let started = Instant::now(); + let deadline = started + Duration::from_millis(350); + wait_for_work(&rx, deadline); + let took = started.elapsed(); + assert!(Instant::now() >= deadline, "returned before the deadline, after {took:?}"); + assert!(took < Duration::from_secs(2), "waited on past the deadline: {took:?}"); + // The work done: at once. + let (tx, rx) = mpsc::channel::<()>(); + tx.send(()).expect("sent"); + let started = Instant::now(); + wait_for_work(&rx, started + Duration::from_secs(10)); + assert!(started.elapsed() < Duration::from_secs(5), "waited on after the work was done: {:?}", started.elapsed()); + // The work failed or panicked (its sender is dropped): at once. + let (tx, rx) = mpsc::channel::<()>(); + drop(tx); + let started = Instant::now(); + wait_for_work(&rx, started + Duration::from_secs(10)); + assert!(started.elapsed() < Duration::from_secs(5), "waited on after the work had gone: {:?}", started.elapsed()); + } + #[test] fn only_a_json_object_naming_a_plain_word_kind_is_an_event() { // The nine, and any other plain word: which kinds a session takes is @@ -763,5 +877,103 @@ mod tests { assert_eq!(MAX_PAYLOAD_DEPTH, 31); // Five strings of at most 4 KiB, their names and "cut": well under 48 KiB. assert!(5 * (MAX_STRING + 20) + 11 < CUT_OVER); + // One wait of the hook and status modes: a twentieth of the deadline, + // so a wakeup that is lost costs little of it, and no wait is one + // long timer. No test can lose a wakeup on demand, so this holds it. + assert_eq!(RECHECK, Duration::from_millis(100)); + } +} + +/// The hook and status modes' standard input on macOS and Linux +/// (`read_fd_by`, `StdinBy`), read from a pipe of the test's own in place +/// of descriptor 0, which a test cannot hand the reader. +#[cfg(all(test, unix))] +mod stdin_by_tests { + use super::*; + use std::fs::File; + use std::io::Write; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + + /// A new pipe: its read end, and its write end as a file. Both are set + /// to close on exec, so a process another test starts does not keep the + /// write end open (set just after, as the transport sets it on macOS, + /// which has no pipe2). + #[allow(unsafe_code)] + fn pipe() -> (OwnedFd, File) { + let mut fds = [0 as libc::c_int; 2]; + assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0, "a pipe"); + let (r, w) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }; + for fd in [r.as_raw_fd(), w.as_raw_fd()] { + assert_ne!(unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) }, -1, "close on exec"); + } + (r, File::from(w)) + } + + /// Input that ends in time is read whole, as soon as it ends: from a + /// pipe, empty or not, and from /dev/null, a device, which the poll(2) + /// manual of macOS says poll does not support (POLLNVAL): it is then + /// read at once, and its end is still the end. + #[test] + fn input_that_ends_before_the_deadline_is_read_whole_when_it_ends() { + for input in [&b"{\"model\":{\"id\":\"m\"}}"[..], &b""[..]] { + let (r, mut w) = pipe(); + w.write_all(input).expect("write"); + drop(w); + let started = Instant::now(); + let got = read_fd_by(r.as_raw_fd(), started + Duration::from_secs(10)); + assert_eq!(got.as_deref(), Some(input)); + assert!(started.elapsed() < Duration::from_secs(5), "waited on an input that had ended: {:?}", started.elapsed()); + } + let null = File::open("/dev/null").expect("/dev/null"); + let started = Instant::now(); + assert_eq!(read_fd_by(null.as_raw_fd(), started + Duration::from_secs(10)), Some(Vec::new()), "/dev/null"); + assert!(started.elapsed() < Duration::from_secs(5), "waited on /dev/null: {:?}", started.elapsed()); + } + + /// Input still open at the deadline is given up at the deadline, not + /// waited for until it ends: part of a status, then a writer that hangs + /// and ends its input only 3 s later (or once the reader has returned). + #[test] + fn input_still_open_at_the_deadline_is_given_up_at_the_deadline() { + let (r, mut w) = pipe(); + w.write_all(b"{\"model\":").expect("write"); + let ends_after = Duration::from_secs(3); + let (stop, stopped) = mpsc::channel::<()>(); + let started = Instant::now(); + let writer = std::thread::spawn(move || { + let _ = stopped.recv_timeout(ends_after); + drop(w); + }); + let deadline = started + Duration::from_millis(300); + let got = read_fd_by(r.as_raw_fd(), deadline); + let returned = Instant::now(); + let _ = stop.send(()); + writer.join().expect("the writer"); + assert_eq!(got, None, "kept an input that had not ended by the deadline"); + assert!(returned >= deadline, "gave up {:?} before the deadline", deadline - returned); + assert!(returned - started < ends_after, "waited {:?}, until the input ended", returned - started); + } + + /// Input over `MAX_STDIN` is read to its end, so its writer is not cut + /// off, and kept not at all. The writer sends a further `MAX_STDIN` past + /// the cap, more than a pipe holds even with 64 KiB pages (1 MiB): a + /// reader that stopped at the cap, or failed part way, would leave it + /// blocked in the write. + #[test] + fn input_over_the_cap_is_read_to_its_end_and_kept_not_at_all() { + let (r, mut w) = pipe(); + let writer = std::thread::spawn(move || w.write_all(&vec![b' '; MAX_STDIN * 2])); + let got = read_fd_by(r.as_raw_fd(), Instant::now() + Duration::from_secs(20)); + // The read end is closed before the writer is waited for. After a + // read to the end the writer is done already: its write_all returned + // Ok and its end closed, which is what ended the read. After a read + // that stopped sooner it is still blocked in the write, and closing + // the read end makes that write fail (the Rust runtime ignores + // SIGPIPE, so it is an error, BrokenPipe, not a signal), rather than + // leave the writer waiting. + drop(r); + let wrote = writer.join().expect("the writer"); + assert_eq!(got.map(|kept| kept.len()), None, "kept an input over the cap"); + assert!(wrote.is_ok(), "the input was not read to its end: {wrote:?}"); } } diff --git a/helper/src/status.rs b/helper/src/status.rs index 9b5f182c3..b56873797 100644 --- a/helper/src/status.rs +++ b/helper/src/status.rs @@ -27,7 +27,7 @@ use crate::client::Client; use crate::frame::Body; use crate::hello; -use crate::hook::{self, from_env, left, mend_surrogates, parse_args_or_env, read_stdin, MAX_PAYLOAD_DEPTH}; +use crate::hook::{self, from_env, left, mend_surrogates, parse_args_or_env, MAX_PAYLOAD_DEPTH}; use crate::json::{self, Value}; use crate::request::{repeats_a_name, MAX_STATUS_PAYLOAD}; use crate::serve::STATUS_CAP; @@ -48,7 +48,13 @@ pub const ACK_CAPS: [&str; 2] = ["core", STATUS_CAP]; /// Run the status mode on `args` (what follows `status`). It returns by the /// deadline whatever the work is still waiting on (standard input that never -/// ends, a holder that never answers); the process then exits with it. +/// ends, a holder that never answers), in short waits +/// (`hook::wait_for_work`); the process then exits with it. The work's own +/// waits end by the deadline too: for the holder's connection, hello and +/// reply on every system, and for standard input on macOS and Linux +/// (`hook::read_stdin_by`), except an input poll cannot watch (POLLNVAL; the +/// poll(2) manual of macOS says so of devices, a terminal among them), which +/// is read as before. pub fn run(args: &[String]) { let deadline = Instant::now() + DEADLINE; let args = args.to_vec(); @@ -58,15 +64,14 @@ pub fn run(args: &[String]) { let _ = done_tx.send(()); }); if worker.is_ok() { - // Done, failed, panicked (the sender is dropped) or out of time. - let _ = done.recv_timeout(deadline.saturating_duration_since(Instant::now())); + hook::wait_for_work(&done, deadline); } } /// The work; None wherever it stops, and the update is lost. fn deliver(args: &[String], deadline: Instant) -> Option<()> { let (store_dir, sid) = parse_args_or_env(args, from_env)?; - let input = read_stdin()?; + let input = hook::read_stdin_by(deadline)?; let payload = payload_from(&input)?; let rec = store::read(&store_dir, &sid)?.ok()?; post(&rec, payload, deadline) diff --git a/helper/src/transport/mod.rs b/helper/src/transport/mod.rs index d82992ee2..aa8565e6e 100644 --- a/helper/src/transport/mod.rs +++ b/helper/src/transport/mod.rs @@ -28,6 +28,8 @@ mod unix; pub use unix::{connect, peer_allowed, prepare_run_dir, remove_stale_endpoint, run_dir, Listener, Stream}; #[cfg(target_os = "linux")] pub(crate) use unix::{check_dir, peer_uid}; +#[cfg(unix)] +pub(crate) use unix::poll_readable; #[cfg(windows)] mod windows; diff --git a/helper/src/transport/unix.rs b/helper/src/transport/unix.rs index 6f34bf486..81d4f4617 100644 --- a/helper/src/transport/unix.rs +++ b/helper/src/transport/unix.rs @@ -313,23 +313,36 @@ const WAKE_RECHECK: Duration = Duration::from_secs(1); /// does (EAGAIN, a timeout to `is_timeout`). #[cfg(target_vendor = "apple")] fn wait_readable(fd: RawFd, limit: Option) -> io::Result<()> { - let deadline = limit.map(|l| Instant::now() + l); + match poll_readable(fd, limit.map(|l| Instant::now() + l), WAKE_RECHECK)? { + Some(_) => Ok(()), + None => Err(io::Error::from_raw_os_error(libc::EAGAIN)), + } +} + +/// Wait in poll until a read on `fd` would not wait there: bytes, the end of +/// the stream, an error, a hang-up, or a descriptor poll cannot watch +/// (POLLNVAL), each a result above 0. Each poll lasts at most `recheck`, so +/// a wakeup that is lost costs at most that. What poll reported (`revents`), +/// or None once `deadline` (None: never) has passed first. A poll a signal +/// interrupts is polled again. `wait_readable` (a socket's read on macOS), +/// and the hook and status modes' standard input (`hook::read_stdin_by`). +pub(crate) fn poll_readable(fd: RawFd, deadline: Option, recheck: Duration) -> io::Result> { loop { let slice = match deadline { Some(d) => { let left = d.saturating_duration_since(Instant::now()); if left.is_zero() { - return Err(io::Error::from_raw_os_error(libc::EAGAIN)); + return Ok(None); } - left.min(WAKE_RECHECK) + left.min(recheck) } - None => WAKE_RECHECK, + None => recheck, }; let mut p = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; let ms = slice.as_millis().clamp(1, i32::MAX as u128) as libc::c_int; let n = unsafe { libc::poll(&mut p, 1, ms) }; if n > 0 { - return Ok(()); + return Ok(Some(p.revents)); } if n < 0 { let e = io::Error::last_os_error(); diff --git a/helper/tests/hooks.rs b/helper/tests/hooks.rs index 8bf5b1301..710a0fe5d 100644 --- a/helper/tests/hooks.rs +++ b/helper/tests/hooks.rs @@ -8,7 +8,7 @@ use aicc_helper::client::Client; use aicc_helper::frame::{self, Body, Direction, Frame}; use aicc_helper::hello::{self, Hello, LOCAL_CAPS}; -use aicc_helper::hook::{ACK_CAPS, SESSION_ENV, STORE_ENV}; +use aicc_helper::hook::{ACK_CAPS, DEADLINE, SESSION_ENV, STORE_ENV}; use aicc_helper::json::{self, Value}; use aicc_helper::pids; use aicc_helper::serve::HOLDER_CAPS; @@ -756,6 +756,9 @@ fn a_hook_run_whose_standard_input_never_ends_ends_by_its_deadline() { let ran = Ran { code: out.status.code(), stdout: out.stdout, stderr: out.stderr, took }; assert!(ran.quiet(), "{}", ran.say()); assert!(ran.took < HOOK_BOUND, "{}", ran.say()); + // Not before its deadline either: it waited for the rest of its input + // until then, and no longer. + assert!(ran.took >= DEADLINE, "ended before its deadline: {}", ran.say()); } /// An argument that is not Unicode: bytes that are not UTF-8 on macOS and diff --git a/helper/tests/status.rs b/helper/tests/status.rs index 859238a62..26d81810a 100644 --- a/helper/tests/status.rs +++ b/helper/tests/status.rs @@ -12,7 +12,7 @@ use aicc_helper::hook::{SESSION_ENV, STORE_ENV}; use aicc_helper::json::{self, Value}; use aicc_helper::pids; use aicc_helper::serve::{HOLDER_CAPS, STATUS_EVERY}; -use aicc_helper::status::ACK_CAPS; +use aicc_helper::status::{ACK_CAPS, DEADLINE}; use aicc_helper::store::{self, Record}; use aicc_helper::transport::{self, Listener}; use std::fs; @@ -646,6 +646,9 @@ fn a_status_run_whose_standard_input_never_ends_ends_within_2_s() { drop(stdin); let ran = Ran { code: out.status.code(), stdout: out.stdout, stderr: out.stderr, took }; assert!(ran.quiet() && ran.took < STATUS_BOUND, "{}", ran.say()); + // Not before its deadline either: it waited for the rest of its input + // until then, and no longer. + assert!(ran.took >= DEADLINE, "ended before its deadline: {}", ran.say()); } #[test] diff --git a/package-lock.json b/package-lock.json index 7aee12775..8d955486d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-conductor", - "version": "2.1.3-beta.27", + "version": "2.1.3-beta.28", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-conductor", - "version": "2.1.3-beta.27", + "version": "2.1.3-beta.28", "hasInstallScript": true, "dependencies": { "@excalidraw/excalidraw": "^0.18.1", diff --git a/package.json b/package.json index ba024c941..43e26a8ae 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-conductor", - "version": "2.1.3-beta.27", + "version": "2.1.3-beta.28", "description": "Multi-session Claude Code and Codex terminal orchestrator", "author": "Nicholas Moger", "main": "./out/main/index.js", diff --git a/scripts/ci/pr-numbers.mjs b/scripts/ci/pr-numbers.mjs index 609fc7d5d..9172043cf 100644 --- a/scripts/ci/pr-numbers.mjs +++ b/scripts/ci/pr-numbers.mjs @@ -41,15 +41,16 @@ export const PTY_MANAGER = 'src/main/pty-manager.ts' /** * The most lines pty-manager.ts may have. It started at the file's length on * beta when this check was added (ADR-030 states that starting value) and was - * last lowered by the 2.1.3-beta.25 release copy, to the file's length then: - * the beta.25 aggregate left it 3 lines under the 7479 the 2.1.3-beta.22 + * last lowered by the 2.1.3-beta.28 release copy, to the file's length then: + * the beta.28 aggregate left it 1 line under the 7476 the 2.1.3-beta.25 + * release copy had set. That was 3 lines under the 7479 the 2.1.3-beta.22 * aggregate had set (which moved the sign-in tab's account refusal and line * into local-sign-in-tab.ts and the resume picker's worktree list into * resume-picker-worktrees.ts; before it, the 2.1.3-beta.19 fix round moved a * Restart's resume-target read into restart-resume-target.ts). Lower it, * never raise it, whenever a PR shortens the file. */ -export const PTY_MANAGER_LINE_CAP = 7476 +export const PTY_MANAGER_LINE_CAP = 7475 /** The PR label that lets pty-manager.ts grow past the cap. */ export const OVERRIDE_LABEL = 'cap-override' diff --git a/src/main/ipc/pty-handlers.ts b/src/main/ipc/pty-handlers.ts index 31aae276b..78042436f 100644 --- a/src/main/ipc/pty-handlers.ts +++ b/src/main/ipc/pty-handlers.ts @@ -29,7 +29,7 @@ import { bindSshToSavedConfig, argSecretAllowed, findSavedConfig } from '../spaw import { logWarn } from '../debug-logger' import { IPC, ptyReplayAtHolderSizeChannel } from '../../shared/ipc-channels' import { setHeldTerminalLostNotice, setReplayAtHolderSizeNotice } from '../session-helper/helper-pty' -import { keptTabClosed, keptTabShown, keptTabsRestored } from '../sessions/kept-launches' +import { keptTabClosed, keptTabShown, keptTabsComingBack, keptTabsRestored } from '../sessions/kept-launches' import { getPtyIntegrityMonitor } from '../services/pty-integrity-monitor' import type { PtyIntegrityReport } from '../../shared/service-health' import type { SshRuntime, DetachedRemoteLiveness, HostPingResult, DetachedRemote, SshEndRemoteResult, SubmitTextResult, PromptButtonResult } from '../../shared/types' @@ -59,7 +59,7 @@ import { claudeStartLookupPending, awaitClaudeStartLookup } from '../claude-star import { claudeLaunchWalkPending, awaitClaudeLaunchWalk } from '../claude-launch-walk' import { gsudoAnswerKept, gsudoLookAnswered } from '../gsudo-lookup' import { launchLookupsArmed } from '../launch-lookups-armed' -import { spawnFoldersWantHardeningAhead, hardenSpawnFoldersAhead } from '../spawn-folders-ahead' +import { spawnFoldersWantHardeningAhead, hardenSpawnFoldersAhead, SPAWN_FOLDERS_WAIT_MS } from '../spawn-folders-ahead' import { startSshProgramLookup } from '../ssh-program' /** SSH options as received from the renderer (no passwords — only configId) */ @@ -746,6 +746,36 @@ function codexAccountOwnership(service: AccountsService, accountId: string): 'co } } +/** aicc_planning#513: a hold on the way to a spawn that takes this long or + * longer is said in one line, so a slow first tab can be read from the + * app's log. Longer than a warm start's usual holds (the scripts folders' + * check takes 1.0 to 1.6 s from its start, and a tab restored at start asks + * part way into it), so a usual start writes none. */ +export const SPAWN_HOLD_LOG_MS = 1000 + +/** One hold on the way to a spawn (pty:spawn), timed. Once `wait` has + * settled, one line says the hold's name, how long it took, and whether + * what it waited for was still pending then (`stillWaiting()`: the wait ran + * out its bound, or ended with no answer kept): only when it was, or when + * the hold took SPAWN_HOLD_LOG_MS or longer. The words say no more than + * that: a hold no longer pending may have answered, failed, or passed a + * deadline of its own. The line carries the session id and the hold's + * name, nothing else. Rejects only when `wait` does (no hold here does). */ +async function heldFor(sessionId: string, hold: string, wait: Promise, stillWaiting: () => boolean): Promise { + const began = performance.now() + try { + await wait + } finally { + const ms = Math.round(performance.now() - began) + try { + const pending = stillWaiting() + if (pending || ms >= SPAWN_HOLD_LOG_MS) { + logInfo(`[spawn] Session ${sessionId}: held ${ms} ms for ${hold} (${pending ? 'still pending when the wait ended' : 'no longer pending'})`) + } + } catch { /* the launch goes on all the same */ } + } +} + /** WP2 PR 4, P4.1: `canvas:sessionGuidance`'s payload: one session id. */ const sessionGuidanceSchema = z.object({ sessionId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/) }).strict() @@ -758,6 +788,12 @@ const sessionGuidanceSchema = z.object({ sessionId: z.string().regex(/^[A-Za-z0- * spawns (remote-helper/index.ts noteRestoredRemoteTabs). */ const tabsRestoredSchema = z.array(z.object({ id: sessionIdSchema, cwd: z.string().min(1).max(4096).optional(), tmuxConfigId: configIdSchema.optional() }).strict()).max(1000) +/** aicc_planning#515: `pty:tabsComingBack`'s payload: the ids of the tabs an + * after-update restore brings back, named at the startup load, bounded as + * pty:tabsRestored's list is. Ids alone: it only takes a kept session's time + * limit off; the restore's own pty:tabsRestored brings the rest. */ +const tabsComingBackSchema = z.array(sessionIdSchema).max(1000) + /** WP2 PR 4, P4.3: `askConductor:handOff`'s payload: the Ask session and the * question, bounded as the pty:spawn schema bounds askPrompt. */ const askHandOffSchema = z.object({ @@ -1068,8 +1104,12 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // resources folder's scripts folders, and the deploys into them, still // run (script-folders.ts) waits for them, bounded, as a prepared spawn, // so a tab restored at start gets its status line, resume list and hooks; - // past the bound it starts without them. - const holdForScripts = launchProvider !== null && !options?.ssh && scriptFoldersPending() + // past the bound (SCRIPT_FOLDERS_LAUNCH_WAIT_MS, counted from this + // launch's own ask) it starts without them. A sign-in tab is not held for + // them: its line runs no script of the app's (local-sign-in-tab.ts + // localSignInLine: no --settings, so no status line of the app's, and no + // resume list). + const holdForScripts = launchProvider !== null && !options?.shellOnly && !options?.ssh && scriptFoldersPending() // On Windows, while the start still looks for Claude Code // (claude-start-lookup.ts: its walk of PATH and, when that finds none, // the PATH refresh, the first Claude Code lookup and the version probe): @@ -1224,11 +1264,69 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void if (Object.keys(secrets).length > 0) resolvedOptions = { ...resolvedOptions, commandSecrets: secrets } } - // The scripts folders (holdForScripts above). Waited for before a Codex - // launch's own wait for its hook folders below: the start wires those - // only after the scripts folders' check and the deploys (index.ts), so - // each wait's bound then covers its own work alone. - if (holdForScripts) await awaitScriptFolders() + // The holds decided above, side by side (aicc_planning#513), so a launch + // waits for the longest of them, not for their sum: each waits for work + // of its own that none of the others reads or writes (the scripts + // folders, the start's profile steps, the start's look for Claude Code, + // the spawn's folders, the look for gsudo.exe). One after another, a + // first tab at start paid every bound in turn. The price, decided in + // #513 (CONTEXT.d/2026-12-03-b28-snap-d1-holds.md): pty-manager reads + // the scripts at the spawn, not when their wait ends. One after + // another, the other holds came after a scripts wait that ran out its + // bound, and a check that ended while they ran still reached the + // launch. Side by side, that time is the saving: a check that ends in + // it no longer reaches the launch, which starts without its scripts + // unless the hook folders' wait below covers it. + // The start's look and the launch's own walk of PATH stay one after the + // other (the start can bring PATH up to date, and the walk is for the + // PATH it leaves). What can have changed while they ran is asked again + // below, once all of them are over (the spawn's folders, the walk of + // PATH). Each is timed (heldFor). The scripts folders come before a + // Codex launch's own wait for its hook folders below: the start wires + // those only after the scripts folders' check and the deploys + // (index.ts). When the scripts wait saw them end, the hook folders' wait + // covers its own work alone; when it ran out its bound first, the hook + // folders' wait, bounded from its own call, covers what is left of the + // check and the deploys too. + // + // The session folders have one bound for the whole launch, + // SPAWN_FOLDERS_WAIT_MS across every wait it makes for them (its hold + // here and the ask again below), never a fresh one per ask: the ask + // again joins the same work (the same icacls runs, the same rebuild of + // the plugin), so a fresh bound would hold a start whose work did not + // answer twice as long for it. A launch whose wait ran out its bound is + // not held for them again; one whose folders were done in time, and + // came to want doing again while it waited for a longer hold, waits at + // most what is left. Counted as time spent waiting for the folders, not + // from the first wait's start: before #513 the folders' one wait came + // after every other hold, so a launch held for a longer one still had + // folders wanted by then done off the main thread, and it still does. + let spawnFoldersWaitLeftMs = SPAWN_FOLDERS_WAIT_MS + const waitForSpawnFolders = async (): Promise => { + const began = performance.now() + let inTime = false + await heldFor(sessionId, "the session folders' owner-only step", + hardenSpawnFoldersAhead(spawnFoldersWaitLeftMs).then((ended) => { inTime = ended }), () => !inTime) + spawnFoldersWaitLeftMs = inTime ? Math.max(0, spawnFoldersWaitLeftMs - (performance.now() - began)) : 0 + } + const holds: Array> = [] + if (holdForScripts) holds.push(heldFor(sessionId, "the scripts folders' check", awaitScriptFolders(), scriptFoldersPending)) + if (holdForStartSteps) holds.push(heldFor(sessionId, "the start's profile steps", startProfileStepsSettled(), startProfileStepsPending)) + if (holdForClaudeLookup) { + holds.push((async () => { + await heldFor(sessionId, "the start's look for Claude Code", awaitClaudeStartLookup(), claudeStartLookupPending) + await heldFor(sessionId, 'the walk of PATH', awaitClaudeLaunchWalk(opensResumeList), () => claudeLaunchWalkPending(opensResumeList)) + })()) + } + if (holdForSpawnFolders) holds.push(waitForSpawnFolders()) + // The elevated terminal's look for gsudo.exe (holdForGsudo above), + // bounded by its own deadline; past it the launch is refused by + // buildClaudeLocalSpawn, never by a walk in place. + if (holdForGsudo) holds.push(heldFor(sessionId, 'the look for gsudo.exe', gsudoLookAnswered(), () => !gsudoAnswerKept())) + // Only when something holds: a launch held for nothing goes on in the + // same tick, as before, so a copy asked for in the same tick finds it + // started (the one-at-a-time rule, launch-one-at-a-time.ts). + if (holds.length > 0) await Promise.all(holds) // WP2 (plan A10): a Codex session runs in its account's realm -- the // account the request names, else the provider default -- validated, @@ -1308,14 +1406,9 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void } } - // The start's profile steps (holdForStartSteps above), and the scripts - // folders before them, waited for before the check below, so nothing - // starts for a tab closed meanwhile. - if (holdForStartSteps) await startProfileStepsSettled() - // The start's walk of PATH and, when that found no Claude Code, its - // PATH refresh, first lookup and version probe (holdForClaudeLookup - // above). - if (holdForClaudeLookup) await awaitClaudeStartLookup() + // Every hold above is over by here, so nothing starts for a tab closed + // meanwhile (the check below). + // // The spawn's folders (holdForSpawnFolders above), made owner-only off // the main thread before the spawn writes into them. Asked again here, // as the walk below is, for a session start held for any wait above, @@ -1323,25 +1416,22 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // can have changed while the launch waited for something else (a // folder's ten minutes as proven have run out, or another start has // begun the plugin's rebuild, which this one then joins rather than - // wiping the tree under it at its spawn). hardenSpawnFoldersAhead does - // only what is still wanted, and nothing once all of it is done. It - // waits at most SPAWN_FOLDERS_WAIT_MS (one icacls run's time limit and - // as long again); past that the launch goes on, and the spawn's writers - // do their folders themselves, as before. Before the walk below, not - // after it, so the walk is asked once this wait is over too. - if (preparation && startWritesSpawnFolders) await hardenSpawnFoldersAhead() + // wiping the tree under it at its spawn). Only what is still wanted is + // done, and nothing once all of it is done. It waits at most what is + // left of the launch's one bound for its folders (spawnFoldersWaitLeftMs + // above: SPAWN_FOLDERS_WAIT_MS, one icacls run's time limit and as long + // again, less what its hold above waited), and not at all when that + // hold ran out the bound; past it the launch goes on, and the spawn's + // writers do their folders themselves, as before. Before the walk + // below, not after it, so the walk is asked once this wait is over too. + if (preparation && startWritesSpawnFolders && spawnFoldersWaitLeftMs > 0 && spawnFoldersWantHardeningAhead()) await waitForSpawnFolders() // Then the launch's own walk of PATH, when it has one to make by now: // an answer the start kept meanwhile is read, and nothing is walked. // Asked again here, after every wait above, for any launch held for // any of them: an answer that was recent when the hold was decided - // can have run out while the launch waited for something else. One - // wait after the other, never side by side: the start's own first, - // then this. - if (preparation && localClaudeLaunch) await awaitClaudeLaunchWalk(opensResumeList) - // The elevated terminal's look for gsudo.exe (holdForGsudo above), - // bounded by its own deadline; past it the launch is refused by - // buildClaudeLocalSpawn, never by a walk in place. - if (holdForGsudo) await gsudoLookAnswered() + // can have run out while the launch waited for something else. Never + // side by side with the start's own look: that one first, then this. + if (preparation && localClaudeLaunch) await heldFor(sessionId, 'the walk of PATH', awaitClaudeLaunchWalk(opensResumeList), () => claudeLaunchWalkPending(opensResumeList)) // Closed, swept or superseded while it was prepared: start nothing, and // SAY so. The renderer holds any pty:exit that arrives while its own @@ -1554,6 +1644,17 @@ export function registerPtyHandlers(getWindow: () => BrowserWindow | null): void // tmux, and so does its config, from now on (not only once it spawns). if (parsed.success) noteRestoredRemoteTabs(parsed.data) }) + // aicc_planning#515: the start after an update the user chose Save sessions + // for names at its startup load the tabs its restore brings back once the + // release notes close. A session the update kept for one of them is taken + // off its time limit now, and nothing more: its serving starts at the + // restore's own pty:tabsRestored, when the tab is in the renderer's store + // (session-helper/manager.ts tabsComingBack). The app's window only. + ipcMain.on(IPC.PTY_TABS_COMING_BACK, (e, ids: unknown) => { + if (!fromApp(e)) return + const parsed = tabsComingBackSchema.safeParse(ids) + if (parsed.success) keptTabsComingBack(parsed.data) + }) ipcMain.on(IPC.PTY_TAB_SHOWN, (e, id: unknown) => { if (!fromApp(e)) return const parsed = sessionIdSchema.safeParse(id) diff --git a/src/main/ipc/update-handlers.ts b/src/main/ipc/update-handlers.ts index 84a8998ad..1880dadfc 100644 --- a/src/main/ipc/update-handlers.ts +++ b/src/main/ipc/update-handlers.ts @@ -6,7 +6,9 @@ import { checkForUpdatesOnDemand, markUpdateInstalled, getProjectRootPath, setSo import { checkGitHubRelease, downloadGitHubRelease, prepareLinuxAppImageUpdate, isPathOnNoexecMount, InstallerIntegrityError, stillMatchesDigest, createInstallerDir } from '../github-update' import { killAllPty } from '../pty-manager' import { noteUpdateHandOver } from '../conductor-mcp-server' -import { releaseHeldTerminalsForUpdate, reclaimReleasedTerminals } from '../session-helper/app-wiring' +import { releaseHeldTerminalsForUpdate, reclaimReleasedTerminals, sessionsKeptThroughUpdate } from '../session-helper/app-wiring' +import { IPC } from '../../shared/ipc-channels' +import { NOTHING_KEPT, updateKeepTabsFrom, type UpdateKeepCounts } from '../../shared/update-keep' import { hardExitTeardown } from '../hard-exit' import { expandArtifactName } from '../artifact-name' import { logInfo, logError } from '../debug-logger' @@ -54,6 +56,11 @@ async function checkInOrder(): Promise { /** Reentrancy latch for update:installAndRestart — see the handler. */ let updateInProgress = false +/** Whether an update lets go of the held sessions before its kill (plan + * section B2): Windows only; macOS and Linux end them. The install path and + * the update dialog's count (aicc_planning#514) both ask this. */ +const releasesHeldSessions = (): boolean => process.platform === 'win32' + export function registerUpdateHandlers(): void { ipcMain.handle('update:check', async () => { // Store builds are updated by the Store. Report "no update" so the UI never @@ -88,6 +95,23 @@ export function registerUpdateHandlers(): void { return cachedRelease?.displayVersion || cachedRelease?.version || null }) + // aicc_planning#514: the update dialog's counts. How many of the open local + // tabs the renderer names (by kind) an update now would keep running, by + // the rule the install below lets go of held sessions by + // (releasesHeldSessions, then the session helper's own rule). Read-only: + // nothing is let go of, written or started. Counts only: no id or path goes + // back. The question is read through updateKeepTabsFrom, so a malformed + // one is a question about no tab. + ipcMain.handle(IPC.UPDATE_SESSIONS_KEPT, async (_event, tabs?: unknown): Promise => { + if (!releasesHeldSessions()) return { ...NOTHING_KEPT } + try { + return sessionsKeptThroughUpdate(updateKeepTabsFrom(tabs)) + } catch (err) { + logError('[update] The sessions an update keeps could not be counted:', err) + return { ...NOTHING_KEPT } + } + }) + ipcMain.handle('update:hasSourcePath', async () => { return hasSourcePath() }) @@ -371,7 +395,7 @@ export function registerUpdateHandlers(): void { // takes it over (2.1.3-beta.17, S16 step 5); one no restored tab takes // over is ended there. macOS and Linux end them. // A release that fails stops nothing: what it did not let go of ends. - const releasing = process.platform === 'win32' + const releasing = releasesHeldSessions() try { if (releasing) { try { await releaseHeldTerminalsForUpdate({ discarded }) } catch (e) { logError('[update] The held terminals could not be let go of:', e) } diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts index 4f693103d..33b56a5a3 100644 --- a/src/main/pty-manager.ts +++ b/src/main/pty-manager.ts @@ -6427,11 +6427,11 @@ function spawnPtyResolved( // The directory the CLI will actually run in, after the resume decision. assertGatedDirectory(options, claudeCwd, 'resume directory', recordUnverifiedDirectory) - logInfo(`[pty-manager] Launching Claude via shell in PTY: ${spawnCmd} -> ${cmd} cwd=${describePathForLog(claudeCwd)} (resumePicker=${!!options?.useResumePicker}, resume=${resumeUuid ?? 'none'})`) - // Asked once: the launch line below starts the picker exactly when this // spawn's agent templates were written for it. const pickerScript = getResumePickerPath(!!options?.useResumePicker) + // #513: a resume-list launch says if its script was ready (if not, the direct line runs); never its path. + logInfo(`[pty-manager] Launching Claude via shell in PTY: ${spawnCmd} -> ${cmd} cwd=${describePathForLog(claudeCwd)} (resumePicker=${!!options?.useResumePicker}${options?.useResumePicker ? `, pickerScript=${pickerScript ? 'ready' : 'not ready'}` : ''}, resume=${resumeUuid ?? 'none'})`) // This session's agent templates, as the one object keyed by name that // Claude Code's --agents takes; a set it would not take is refused here, // before anything starts (claudeAgentsObject). Windows: they ride the @@ -6669,9 +6669,8 @@ function spawnPtyResolved( launchWriteScheduled = true launchPendingSessions.add(sessionId) setTimeout(() => { - // Liveness guard (see shell-only branch): the 300ms launch-write can race - // a kill / Restart / app-quit; writing to a dead/replaced PTY from this - // timer would crash main. Only write when our PTY is still registered. + // Liveness guard (see shell-only branch): the 300ms launch-write can race a kill / Restart / app-quit; + // writing to a dead/replaced PTY from this timer would crash main. Only write when our PTY is still registered. if (ptySessions.get(sessionId)?.ptyProcess !== ptyProcess) { abandonLaunchHold(); return } try { ptyProcess.write(escapedCmd + '\r') diff --git a/src/main/remote-helper/index.ts b/src/main/remote-helper/index.ts index 0f73bc489..74e57bff9 100644 --- a/src/main/remote-helper/index.ts +++ b/src/main/remote-helper/index.ts @@ -69,7 +69,8 @@ import { tryGetProvider } from '../providers' import { colorFgBgValue, resolveHostColorScheme } from '../providers/host-color-scheme' import type { HeldScreenRows, PasteKey, ProviderRemoteLaunch, RemoteAccounts, RemoteHelperCommands, RemoteHostFile, RemoteLaunchOptions, SessionProvider } from '../providers/types' import type { SSHOptions } from '../ssh-options' -import { HELPER_ONLY_STEP, ROUTE_WHY, helperPostConnect, persistentTab, routeSshTab, type PersistentStanding, type Route } from './route' +import { HELPER_ONLY_STEP, ROUTE_WHY, helperPostConnect, routeSshTab, type PersistentStanding, type Route } from './route' +import { persistentTab } from '../../shared/ssh-persistent' import { NoticePty, RemoteDriver, RemoteHelperPty, newSudoToken, remoteCwd, remoteHelperCommands, remoteLaunchSpec, remotePlainLaunchSpec, remoteSessionId, type PlainTerminal, type RemoteLaunchPlan, type RemoteTabAccount, type SudoLaunch } from './session' import { sudoSecretFits, type LaunchSpec } from '../session-helper/protocol' import { isContainerRuntime, parseDockerPostCommand } from '../../shared/container-command' @@ -624,7 +625,7 @@ export function remoteHelperPty(win: OutputWindow, sessionId: string, options: R } catch { settings = null } - // 2.1.3-beta.26 (planning #485): a plain terminal is never kept (route.ts persistentTab). + // 2.1.3-beta.26 (planning #485): a plain terminal is never kept (shared/ssh-persistent.ts persistentTab). const persistent = persistentTab(ssh, options.shellOnly === true) // A tab's mark (2.1.3-beta.19): its saved record's, or its last start's this run. const marked = persistent && (options.remoteVia === 'helper' || lastPath.get(sessionId) === 'kept') diff --git a/src/main/remote-helper/route.ts b/src/main/remote-helper/route.ts index 334d672cb..9f9eb72aa 100644 --- a/src/main/remote-helper/route.ts +++ b/src/main/remote-helper/route.ts @@ -133,6 +133,7 @@ import { composeRuntimeCommand, isContainerRuntime, parseDockerPostCommand } fro import type { SSHOptions } from '../ssh-options' import { logoutCleanUp, type RemoteMachineRecord } from './machines' import { callsSudoByName, postCommandOpensShell } from '../../shared/post-connect-shape' +import { persistentTab } from '../../shared/ssh-persistent' import type { HolderKind } from './scripts' import { PASSWORD_SIGN_IN_ABSENT } from './askpass' @@ -324,7 +325,7 @@ export const MARKED_STEP = { export function routeSshTab(i: RouteInput): Route { const ssh = i.ssh // 2.1.3-beta.26 (planning #485): a plain terminal is never kept, whatever - // its config's Connection says (persistentTab). + // its config's Connection says (shared/ssh-persistent.ts persistentTab). const persistent = persistentTab(ssh, i.shellOnly) const marked = persistent && i.standing?.marked === true const helperOnly = i.helperOnly === true @@ -422,14 +423,6 @@ export function routeSshTab(i: RouteInput): Route { return { via: 'helper', machine: i.machine, kind: persistent ? 'until-ended' : 'away' } } -/** Whether a tab is SSH Persistent as the route counts it: its config's - * Connection (no `detachable` value, or true), and not a plain terminal - * (2.1.3-beta.26, planning #485: a Terminal only tab or a partner terminal - * ends with its tab, as its plain connection does on the usual path). */ -export function persistentTab(ssh: Pick, shellOnly: boolean): boolean { - return ssh.detachable !== false && !shellOnly -} - /** * planning #488's review (NIT): the one line a Terminal only tab shows when * its container entry returns, before its login shell on the machine takes diff --git a/src/main/script-folders.ts b/src/main/script-folders.ts index 328e7053c..d143cb174 100644 --- a/src/main/script-folders.ts +++ b/src/main/script-folders.ts @@ -77,7 +77,21 @@ function noRead(a: Asked | undefined): boolean { return !a?.answer || a.answer.unread === true } -/** How long a local launch waits for this run's check and deploys. */ +/** How long a local launch waits for this run's check and deploys, counted + * from that launch's own ask (awaitScriptFolders). Not a deadline counted + * from the check's start: aicc_planning#513 tried one and dropped it, since + * a tab asked late into a slow check would then start without the app's + * status line for the session's whole life, a bigger cost than the wait it + * saved. Past this bound the launch no longer waits for the check: one that + * ends later reaches it only if something else still holds the launch then + * (pty-manager reads the scripts at the spawn). Before #513 the other holds + * came after this wait, one after another, so such a check had their sum to + * end in; side by side it has only what the longest of them runs past this + * bound, a trade #513 decided (CONTEXT.d/2026-12-03-b28-snap-d1-holds.md). + * As main saw the check, it took 1.0 to 1.6 s in every later app on a + * runner, 2.6 to 3.5 s with the disk cache purged, and 8.8 to 13.6 s in a + * runner's first app, whose first Windows PowerShell starts cold + * (CONTEXT.d/2026-11-27-b20-snap-d1.md). */ export const SCRIPT_FOLDERS_LAUNCH_WAIT_MS = 5000 /** How much of the rule's reason a warning carries. */ const DETAIL_MAX = 300 diff --git a/src/main/session-helper/app-wiring.ts b/src/main/session-helper/app-wiring.ts index 03ebe778e..8445eda51 100644 --- a/src/main/session-helper/app-wiring.ts +++ b/src/main/session-helper/app-wiring.ts @@ -3,7 +3,7 @@ * plugged into the Machines page (setMachinesSource), switched by Settings, * told which tabs are saved, and ended at a normal quit. index.ts calls these * and nothing else of the helper; update-handlers.ts calls the two for an app - * update on Windows. + * update on Windows, and the update dialog's count (sessionsKeptThroughUpdate). */ import { app } from 'electron' import { readConfig, readConfigChecked } from '../config-manager' @@ -16,6 +16,7 @@ import { endHelperHooks, helperHookEvent, helperHooksTaken } from '../session-si import { getConductorMcpPort, serveToolStream } from '../conductor-mcp-server' import { tryGetProvider } from '../providers' import type { ProviderId } from '../../shared/providers/ids' +import { NOTHING_KEPT, type UpdateKeepCounts, type UpdateKeepTabs } from '../../shared/update-keep' import { bundledHelperPath, helperRootDir } from './install' import { SessionHelperManager, agentRecordsIn, crashMarkIn, getSessionHelper, keptHookFoldersIn, keptSessionIdsIn, removeOldCopiesWithHelperOff, setSessionHelper, type HelperHookDeps, type HelperRouting, type HelperToolDeps, type SessionHelperServiceState } from './manager' @@ -247,6 +248,22 @@ export async function releaseHeldTerminalsForUpdate(choice: UpdateChoice = {}): return n } +/** + * aicc_planning#514: the update dialog's count. How many of the tabs the + * renderer names (its open local tabs, by kind) an app update now would keep + * running and show again in the new version, by the update's own rule: what + * it lets go of, and what it leaves running for the next start to keep again + * (the manager's tabsKeptThroughUpdate). Counts only. + * None when the helper was never switched on this run. Lets go of nothing. + */ +export function sessionsKeptThroughUpdate(tabs: UpdateKeepTabs): UpdateKeepCounts { + const m = getSessionHelper() + if (!m) return { ...NOTHING_KEPT } + const kept = m.tabsKeptThroughUpdate(new Set([...tabs.agents, ...tabs.terminals])) + const count = (ids: readonly string[]) => new Set(ids.filter((id) => kept.has(id))).size + return { agents: count(tabs.agents), terminals: count(tabs.terminals) } +} + /** What the user chose at an app update: `discarded` only for "Close sessions" * on the update dialog. Nothing passed is Save. */ export interface UpdateChoice { diff --git a/src/main/session-helper/helper-pty.ts b/src/main/session-helper/helper-pty.ts index 335056f97..9acfa1227 100644 --- a/src/main/session-helper/helper-pty.ts +++ b/src/main/session-helper/helper-pty.ts @@ -517,6 +517,11 @@ export class HelperPty implements IPty { get heldRecord(): HolderRecord | undefined { return this.inner ? undefined : this.record } /** True once release() let go of the holder for an app update. */ get isReleased(): boolean { return this.released } + /** aicc_planning#514: whether release() would let go of the holder now (a + * holder that has been attached, not starting, ending, over or released); + * release() asks this, and so does the update dialog's count (manager.ts + * keptThroughUpdate), which lets go of nothing. */ + get releasable(): boolean { return !(this.inner || this.exited || this.ending || this.released || !this.record || !this.everAttached) } /** The folder its program was launched in, and whether it runs on node-pty's * bundled ConPTY (2.1.3-beta.17, S16 step 5): what an update's record of an * agent session keeps for the take-over in its restored tab. */ @@ -635,7 +640,7 @@ export class HelperPty implements IPty { * (remote-helper/session.ts RemoteHelperPty.kill); its holder has no away clock. */ release(): boolean { - if (this.inner || this.exited || this.ending || this.released || !this.record || !this.everAttached) return false + if (!this.releasable) return false this.released = true const conn = this.conn // A flush waiting before a lone Enter sends the rest now, as it all went diff --git a/src/main/session-helper/manager.ts b/src/main/session-helper/manager.ts index d2dca6bfb..ef99eda57 100644 --- a/src/main/session-helper/manager.ts +++ b/src/main/session-helper/manager.ts @@ -516,13 +516,15 @@ const STORE_LOCK = '.lock' /** How long a start keeps a session an update kept running for its restored * tab to take over (S16 step 5) while no restored tab waits for it unseen: * from the start until Resume restores its tab (the resume prompt left open, - * or answered Don't open), and from the moment its tab is first shown (its - * launch may wait at its account picker: Settings, Accounts, 'Ask each - * time'). Then it is ended. A restored tab not on screen mounts its terminal - * only when it is shown (App.tsx renders it with display: none, and - * TerminalView starts it once its pane has a size), so between the two its - * session is kept with no limit (restoredTabs, aicc_planning#423): until the - * tab is shown and takes it over, or is closed. */ + * or answered Don't open; after an update the user chose Save sessions for, + * until the renderer names the tabs coming back at its startup load, before + * the release notes, aicc_planning#515: tabsComingBack), and from the moment its tab is first + * shown (its launch may wait at its account picker: Settings, Accounts, + * 'Ask each time'). Then it is ended. A restored tab not on screen mounts + * its terminal only when it is shown (App.tsx renders it with display: + * none, and TerminalView starts it once its pane has a size), so between the + * two its session is kept with no limit (restoredTabs, aicc_planning#423): + * until the tab is shown and takes it over, or is closed. */ const KEPT_TAKE_OVER_WAIT_MS = 5 * 60_000 /** aicc_planning#423 (B1d): how long after Resume restored its tab a session * kept for a tab not shown yet waits before its Conductor tool calls are @@ -686,12 +688,24 @@ const lastLine = (s: string): string => s.split(/\r?\n/).map((l) => l.trim()).fi const firstLine = (s: string): string => s.split(/\r?\n/).map((l) => l.trim()).find(Boolean) ?? '' const message = (err: unknown): string => (err instanceof Error ? err.message : String(err)) +/** A session an app update with Save sessions leaves running, and the tab + * (`label`) it is shown under (SessionHelperManager keptThroughUpdate says + * each kind). `forTab`: the next start shows it in that tab. */ +type UpdateKeep = + | { how: 'release'; sid: string; label: string; forTab: boolean; w: HelperPty; keeps: { kind: ProviderId; hooks: boolean } | null; record: HolderRecord } + | { how: 'keptForTab' | 'runsOn'; sid: string; label: string; forTab: true } + /** A session kept for its restored tab (SessionHelperManager keptForTabs). */ interface KeptForTab { kept: KeptRecord record: HolderRecord timer: ReturnType | null shown?: true + /** aicc_planning#515: the startup load after an update named its tab as + * coming back (tabsComingBack), which took its time limit off. Its tab is + * not in the renderer's store yet, so nothing is served for it until the + * restore's own word (restoredTabs), which arms `serve` and clears this. */ + comingBack?: true serve?: ReturnType /** B1e: its keeper's hook route, from its serving while its tab is not shown. */ hooks?: HookRoute @@ -2089,14 +2103,10 @@ export class SessionHelperManager implements MachinesSource { // B1f: each connection that takes hook events lets go by a detach, which // the update waits for (endsForUpdate): its later events wait in its holder. const lets: Promise[] = [] - for (const [sid, w] of this.live) { - if (!w.throughHelper || w.isReleased) continue - const kind = heldIdKind(sid) - const keeps = kind === 'agent' ? this.keepable(w) : null - if (kind !== 'plain' && !keeps) continue - const record = w.heldRecord - const tab = parentOfPartnerPtyId(w.label) ?? w.label - if (!record || !saved(tab)) continue + const leaves = this.keptThroughUpdate(saved) + for (const k of leaves) { + if (k.how !== 'release') continue + const { sid, w, keeps, record } = k // An agent session's record is written before it is let go of: one // that cannot be recorded is left to the kill, which ends it. const kept = keeps ? this.recordKept(sid, w.label, keeps.kind, w.launchShape, keeps.hooks) : undefined @@ -2118,8 +2128,7 @@ export class SessionHelperManager implements MachinesSource { // That is what the user chose with Save; only "Close sessions" ends it here. const ends: Promise[] = [] let leftRunning = 0 - for (const [sid, r] of new Map([...this.reclaimed, ...this.adoptable])) { - if (this.live.has(sid) || heldIdKind(sid) !== 'plain') continue + for (const [sid, r] of this.keptWithNoTerminal()) { if (restorable !== null) { leftRunning++ this.deps.log(`[session-helper] ${sid}: kept with no tab showing it; left running through the update, for the next start to keep again`) @@ -2143,11 +2152,95 @@ export class SessionHelperManager implements MachinesSource { const tail = restorable === null ? `the sessions were discarded, so ${ends.length} kept terminal(s) are ended` : `${leftRunning} kept terminal(s) are left running` - this.deps.log(`[session-helper] an app update: ${n - agents} held terminal(s) are let go of, for the new version to show again${agents > 0 ? `, and ${agents} agent session(s) are let go of with their CLIs running, recorded for the next start` : ''}; ${tail}`) + // An agent session kept for its restored tab not shown stays kept: the + // next start keeps it for its tab again (keptAtStart). + const forTabs = leaves.filter((k) => k.how === 'keptForTab').length + this.deps.log(`[session-helper] an app update: ${n - agents} held terminal(s) are let go of, for the new version to show again${agents > 0 ? `, and ${agents} agent session(s) are let go of with their CLIs running, recorded for the next start` : ''}; ${tail}${forTabs > 0 ? `; ${forTabs} agent session(s) kept for their tabs stay kept for the next start` : ''}`) this.changed() return n } + /** + * Every session an app update with Save sessions leaves running, each with + * the tab it is shown under: releaseForUpdate goes by it, and so does the + * update dialog's count (tabsKeptThroughUpdate, aicc_planning#514), so the + * two cannot part. On Windows and not quitting; a tab (a partner's is its + * session's) counts as saved when `saved` says so. Three kinds: + * + * - `release`: a terminal of this run through a holder that release() would + * let go of now (HelperPty.releasable): a plain or partner terminal, or an + * agent session whose routes an update keeps (keepable), its holder with a + * record. `forTab`: the next start shows it in its tab, which for an agent + * session needs its provider's take-over wired (deps.takeOver), because + * the next start ends any other (keptAtStart). + * - `keptForTab`: an agent session the last update kept for its restored + * tab, not taken over yet (keptForTabs; its tab is not shown). The update + * does not reach it: its keeper lets go (B1f) or drops at the exit, and + * the next start keeps it for its tab again, with the agent sessions' + * setting on and its provider's take-over wired (keptAtStart). + * - `runsOn`: a plain or partner terminal kept with no terminal of this run + * showing it (keptWithNoTerminal). The update does not reach it either: + * it runs on past the exit, and the next start keeps it again for the tab + * it is bound to (section B3). + * + * Reads only. + */ + private keptThroughUpdate(saved: (tab: string) => boolean): UpdateKeep[] { + const out: UpdateKeep[] = [] + if (this.os !== 'windows' || this.quitting) return out + const savedTab = (label: string) => saved(parentOfPartnerPtyId(label) ?? label) + for (const [sid, w] of this.live) { + if (!w.throughHelper || !w.releasable) continue + const kind = heldIdKind(sid) + const keeps = kind === 'agent' ? this.keepable(w) : null + if (kind !== 'plain' && !keeps) continue + const record = w.heldRecord + if (!record || !savedTab(w.label)) continue + out.push({ how: 'release', sid, label: w.label, forTab: !keeps || this.deps.takeOver?.[keeps.kind] === true, w, keeps, record }) + } + for (const [sid, e] of this.keptForTabs) { + if (!this.agentsOn || this.deps.takeOver?.[e.kept.provider] !== true || !savedTab(e.kept.label)) continue + out.push({ how: 'keptForTab', sid, label: e.kept.label, forTab: true }) + } + for (const [sid, r] of this.keptWithNoTerminal()) { + const label = this.appIdOf(r) + if (savedTab(label)) out.push({ how: 'runsOn', sid, label, forTab: true }) + } + return out + } + + /** The plain and partner terminals kept with no terminal of this run + * showing them (one a crash left, one Re-attach opened a tab for, one an + * earlier reclaim() kept), by session id: an update's kill does not reach + * them (releaseForUpdate, keptThroughUpdate). */ + private keptWithNoTerminal(): Map { + const out = new Map() + for (const [sid, r] of new Map([...this.reclaimed, ...this.adoptable])) { + if (this.live.has(sid) || heldIdKind(sid) !== 'plain') continue + out.set(sid, r) + } + return out + } + + /** + * aicc_planning#514: the tabs, of `tabs`, whose own session (not a partner + * terminal beside it) an app update now would keep running for the next + * version to show in that tab: the update dialog's count. Each of `tabs` is + * taken as saved, as Save sessions saves it before the install, and the + * rule is the update's own (keptThroughUpdate): a terminal it lets go of, + * an agent session kept for a restored tab not shown yet, and a terminal + * kept with no tab of this run showing it, each only where the next start + * shows it in its tab (`forTab`). Lets go of nothing, writes nothing, and + * leaves the update path as it is. + */ + tabsKeptThroughUpdate(tabs: ReadonlySet): Set { + const out = new Set() + for (const k of this.keptThroughUpdate((tab) => tabs.has(tab))) { + if (k.forTab && tabs.has(k.label)) out.add(k.label) + } + return out + } + /** Settles once every end the last releaseForUpdate sent was answered (or * failed): the kept terminals ended because the user discarded the saved * sessions; and, B1f, once each holder it let go of by a detach answered @@ -2305,24 +2398,55 @@ export class SessionHelperManager implements MachinesSource { * mounts its terminal, and asks for the take-over, only once it is shown. * The limit runs again from when the tab is shown (tabShown); a closed tab * ends it at once (tabClosed). One kept for a tab not among them keeps its - * limit. + * limit. aicc_planning#515: after an update the user chose Save sessions + * for, the renderer named its tabs at its startup load (tabsComingBack), + * which took the limit off and served nothing; the restore's call is the + * one that arms the serving for those, as for any other. * * B1d: each such session is served its Conductor tool calls if its tab is * still not shown UNSEEN_SERVE_AFTER_MS from now (serveUnseen), under the * tab's id, with the tab's configured folder (`cwd`) for its canvas roots. + * From now on, not before: the tabs are in the renderer's store, so the + * hook events and status lines its serving delivers (B1e) reach a tab. */ restoredTabs(tabs: ReadonlyArray): void { const open = new Map(tabs.map((t) => [t.id, t.cwd])) for (const [sid, e] of this.keptForTabs) { - if (e.shown || !e.timer || !open.has(e.kept.label)) continue - clearTimeout(e.timer) - e.timer = null + if (e.shown || !open.has(e.kept.label)) continue + if (e.timer) { + clearTimeout(e.timer) + e.timer = null + } else if (!e.comingBack) continue + e.comingBack = undefined this.deps.log(`[session-helper] ${sid}: tab ${e.kept.label} was restored, so the session is kept for it until the tab is shown and takes it over, or is closed`) const cwd = open.get(e.kept.label) e.serve = setTimeout(() => this.serveUnseen(sid, e, cwd), this.deps.unseenServeAfterMs ?? UNSEEN_SERVE_AFTER_MS) } } + /** + * aicc_planning#515: the start after an update the user chose Save sessions + * for restores its tabs only once the pages it opens with (the release + * notes) are closed, and the renderer names them at its startup load, before + * those pages. A session kept for one of them waits for it with no time + * limit from now, however long the pages stay open. That is all: its tab is + * not in the renderer's store yet, so nothing is served for it here (a hook + * event or a status line delivered now would reach no tab, and be lost). Its + * events stay queued in its holder until the restore's own word + * (restoredTabs) arms the serving. A tab named here that the restore does + * not bring back is closed (tabClosed), which ends its session. + */ + tabsComingBack(ids: ReadonlyArray): void { + const back = new Set(ids) + for (const [sid, e] of this.keptForTabs) { + if (e.shown || !e.timer || !back.has(e.kept.label)) continue + clearTimeout(e.timer) + e.timer = null + e.comingBack = true + this.deps.log(`[session-helper] ${sid}: tab ${e.kept.label} comes back once the pages the app opens with are closed, so the session is kept for it with no time limit until then`) + } + } + /** * aicc_planning#423 (B1d): a session kept for its restored tab, whose tab is * still not shown: its CLI's Conductor tool calls are served now, as its @@ -2771,9 +2895,12 @@ setKeptLaunchCheck((appPtyId) => current?.keepsLaunchOf(appPtyId) === true) // to take over (S16 step 5), the same way. setKeptTakeOver((appPtyId, provider, size, account) => current?.takeOverKept({ sessionId: appPtyId, kind: provider }, size, account) ?? null) // And what the renderer says of its restored tabs (aicc_planning#423: the -// tabs Resume restored, one shown, one closed) reaches it the same way. +// tabs Resume restored, one shown, one closed; aicc_planning#515: the tabs an +// after-update restore brings back, named at the startup load) reaches it the +// same way. setKeptTabSignals({ restored: (tabs) => current?.restoredTabs(tabs), + comingBack: (ids) => current?.tabsComingBack(ids), shown: (appPtyId) => current?.tabShown(appPtyId), closed: (appPtyId) => current?.tabClosed(appPtyId), // B1e: and whether one waits for its tab's take-over (no transcript is bound from it until then). diff --git a/src/main/session-signals/status.ts b/src/main/session-signals/status.ts index e384dc709..38a2fba3a 100644 --- a/src/main/session-signals/status.ts +++ b/src/main/session-signals/status.ts @@ -85,6 +85,17 @@ export function setStatuslineUsageSink(sink: StatuslineUsageSink): void { statuslineUsageSink = sink } +/** How the fan-out reads a payload's usage (nubbymong/aicc_planning#516). */ +export interface DeliverStatusOptions { + /** The bars are this computer's own reading of the account, not the + * session's: a frame of a tab through the session helper, whose bars + * statusline-watcher.ts joins from what main already holds. They go to the + * strip, never to the usage sink, which would file main's own reading back + * as the tab's live one. The tab's own windows reach its account through + * noteHelperReading and recordHelperTabUsage instead. */ + usageIsThisComputers?: boolean +} + /** * Common fan-out for any parsed StatuslineData payload — used by both the * file watcher and the SSH OSC sentinel dispatch path. Sends to the renderer @@ -95,7 +106,7 @@ export function setStatuslineUsageSink(sink: StatuslineUsageSink): void { * rebuild on EVERY tick — the ~30s UI freeze). The tokenomics worker now * indexes from raw transcripts on its own fs-watch/timer. */ -export function deliverStatus(data: StatuslineData, getWindow: (() => BrowserWindow | null) | null): void { +export function deliverStatus(data: StatuslineData, getWindow: (() => BrowserWindow | null) | null, opts: DeliverStatusOptions = {}): void { // Copilot review on PR #31 (p9.17): decorate with accountColour HERE, // at the renderer-send site, so the ContextBar sees accountColour. Decorate // once and forward the enriched object to every consumer. @@ -137,16 +148,20 @@ export function deliverStatus(data: StatuslineData, getWindow: (() => BrowserWin // Plan P2: harvest the account-level usage this session just delivered so the // account-usage page can reuse an OPEN account's figure. Read from raw `data` // (account-level, so unaffected by the subagent model/effort strip on - // forDisplay). Best-effort and guarded: the sink resolves the session's profile - // and stores nothing for an SSH or default-home session, and must never break - // the fan-out. + // forDisplay). Best-effort and guarded: the sink resolves the session's + // profile, and must never break the fan-out. // nubbymong/aicc_planning#509: with Claude Code's own 5-hour and weekly // windows (statuslineUsageOf), so a reading reaches the account even when // the status line script read no usage of its own. - const usage = data.sessionId && statuslineUsageSink ? statuslineUsageOf(data) : [] + // nubbymong/aicc_planning#516: a payload whose bars are this computer's own + // reading (a helper tab's frame) is never offered to the sink. + const usage = data.sessionId && statuslineUsageSink && !opts.usageIsThisComputers ? statuslineUsageOf(data) : [] if (data.sessionId && usage.length > 0 && statuslineUsageSink) { - // The transcript path goes with it: the sink files the figure under a - // profile only when the transcript lies in that profile's folder. + // The transcript path and the account email go with it: a session on + // this computer is filed under its profile only when the transcript lies + // in that profile's folder; a session with no local profile (an SSH tab, + // whose shim sends no transcript path) under the profile that holds the + // email its status line names. try { statuslineUsageSink(data.sessionId, usage, data.rateLimitExtra != null, data.transcriptPath, data.accountEmail) } catch { /* sink must not break fan-out */ } } // Sentinel Trigger A: observe the raw model id (modelId preferred; fall back to diff --git a/src/main/sessions/kept-launches.ts b/src/main/sessions/kept-launches.ts index 32ebeb464..276fb6b0e 100644 --- a/src/main/sessions/kept-launches.ts +++ b/src/main/sessions/kept-launches.ts @@ -207,9 +207,13 @@ export interface RestoredTab { /** What the renderer says of its tabs that a session kept for a restored tab * waits on (aicc_planning#423): the tabs Resume restored, a tab shown and - * starting now, and a tab closed. */ + * starting now, and a tab closed; and (aicc_planning#515) the tabs an + * after-update restore will bring back. */ export interface KeptTabSignals { restored(tabs: ReadonlyArray): void + /** aicc_planning#515: the tabs an after-update restore brings back, named + * at the renderer's startup load, before any is in its store. */ + comingBack?(sessionIds: ReadonlyArray): void shown(sessionId: string): void closed(sessionId: string): void /** B1e: whether a session is kept for this tab now, not yet taken over. */ @@ -226,6 +230,9 @@ export function setKeptTabSignals(s: KeptTabSignals | null): void { export function keptTabsRestored(tabs: ReadonlyArray): void { try { tabSignals?.restored(tabs) } catch { /* each kept session keeps its time limit */ } } +export function keptTabsComingBack(sessionIds: ReadonlyArray): void { + try { tabSignals?.comingBack?.(sessionIds) } catch { /* each kept session keeps its time limit until the restore says so */ } +} export function keptTabShown(sessionId: string): void { try { tabSignals?.shown(sessionId) } catch { /* its kept session keeps no limit then; a close or a quit ends it */ } } diff --git a/src/main/spawn-folders-ahead.ts b/src/main/spawn-folders-ahead.ts index a5c131a49..d35acc83a 100644 --- a/src/main/spawn-folders-ahead.ts +++ b/src/main/spawn-folders-ahead.ts @@ -11,9 +11,10 @@ // ~/.claude and the plugin's six folders: 1.15-1.36 s under load on CI. // // pty:spawn now awaits hardenSpawnFoldersAhead first, holding the launch as a -// prepared spawn (ipc/pty-handlers.ts), at most SPAWN_FOLDERS_WAIT_MS, and a -// session start held for any other wait asks it again once that wait is -// over: the same hardening, the same sequence, +// prepared spawn (ipc/pty-handlers.ts), at most SPAWN_FOLDERS_WAIT_MS in all, +// and a session start held for any other wait asks it again once that wait +// is over, within what is left of that bound: the same hardening, the same +// sequence, // with every icacls run started by execFile and awaited // (hardenCredentialDirOffThread), and the plugin's rebuild with it // (ensureCanvasPluginOffThread). What it proves is remembered by the rules @@ -101,12 +102,15 @@ export function spawnFoldersWantHardeningAhead(): boolean { } /** - * The most a held start waits for its folders: the time limit of one icacls - * run, and as long again. The work takes a second or so even under load; a - * start still waiting past this is waiting on a run that does not answer. - * It then goes on, and the spawn's writers make their folders owner-only - * themselves, on the main thread, as before. The work runs on to its own - * end, each run bounded by its own limit. + * The most a held start waits for its folders, in all: the time limit of one + * icacls run, and as long again. The work takes a second or so even under + * load; a start still waiting past this is waiting on a run that does not + * answer. It then goes on, and the spawn's writers make their folders + * owner-only themselves, on the main thread, as before. The work runs on to + * its own end, each run bounded by its own limit. A start that asks again + * (pty-handlers.ts) does not get this bound afresh: the ask again joins the + * same work, so the start waits only what its earlier wait left of it + * (aicc_planning#513 review). */ export const SPAWN_FOLDERS_WAIT_MS = 2 * ICACLS_TIMEOUT_MS @@ -115,22 +119,25 @@ export const SPAWN_FOLDERS_WAIT_MS = 2 * ICACLS_TIMEOUT_MS * (made as its writers make it, then hardened; a link there is accepted, as * before, and never remembered as proven), then, * with the built-in tools on, the canvas plugin's tree. Each only when it - * still wants it. Settles once that is done, or once SPAWN_FOLDERS_WAIT_MS - * has passed, whichever comes first. Never rejects: whatever does not get - * done here is done by the spawn's own writers, as before. + * still wants it. Settles once that is done, or once `waitMs` has passed, + * whichever comes first: true when the work ended in time (done, or left to + * the spawn's writers after a failure), false when the wait ran out first + * (the work runs on to its own end). `waitMs` is what the start has left of + * SPAWN_FOLDERS_WAIT_MS, all of it on its first wait. Never rejects: whatever + * does not get done here is done by the spawn's own writers, as before. */ -export function hardenSpawnFoldersAhead(): Promise { - if (!armed) return Promise.resolve() +export function hardenSpawnFoldersAhead(waitMs: number = SPAWN_FOLDERS_WAIT_MS): Promise { + if (!armed) return Promise.resolve(true) const work = foldersAhead() - return new Promise((resolve) => { + return new Promise((resolve) => { // Cleared once the work is done, so it runs only when the bound passed. const timer = setTimeout(() => { try { - logWarn(`[spawn] the session folders were not made owner-only ahead of the start within ${SPAWN_FOLDERS_WAIT_MS / 1000} s; the start goes on and does it itself`) - } catch { /* the wait ends all the same */ } finally { resolve() } - }, SPAWN_FOLDERS_WAIT_MS) + logWarn(`[spawn] the session folders were not made owner-only ahead of the start within ${Math.round(waitMs / 100) / 10} s; the start goes on and does it itself`) + } catch { /* the wait ends all the same */ } finally { resolve(false) } + }, waitMs) ;(timer as { unref?: () => void }).unref?.() - const done = (): void => { clearTimeout(timer); resolve() } + const done = (): void => { clearTimeout(timer); resolve(true) } void work.then(done, done) }) } diff --git a/src/main/statusline-watcher.ts b/src/main/statusline-watcher.ts index df4ab7c72..bd3a2696e 100644 --- a/src/main/statusline-watcher.ts +++ b/src/main/statusline-watcher.ts @@ -128,9 +128,10 @@ export function dispatchSSHStatuslineUpdate(json: string, fromSessionId?: string * this computer holds of that account (setHelperAccount), joined to each * frame here, each through its own gate. A frame of a tab whose account this * computer holds also asks for that reading again once it is due. The bars - * joined here are that reading: the fan-out offers them to the usage sink as - * any frame's, and the sink files nothing for them, since the frame carries - * no transcript path (usage/account-usage.ts recordLiveUsageForSession). + * joined here are that reading, so the fan-out is told they are this + * computer's own (usageIsThisComputers) and offers them to no usage sink + * (nubbymong/aicc_planning#516: the sink no longer tells a helper frame by its + * missing transcript path, which a plain SSH tab's report lacks too). * * nubbymong/aicc_planning#509: the tab is a session open on that account, so * its 5-hour and weekly windows (the frame's rateLimitCurrent and @@ -146,7 +147,7 @@ export function dispatchHelperStatus(appPtyId: string, line: Readonly { return out } -/** The tab's account fields alone, at once (before its first status frame). */ +/** The tab's account fields alone, at once (before its first status frame). + * Its bars are this computer's own reading, as a frame's are. */ function deliverHelperAccount(appPtyId: string): void { if (!sshDispatchWindow || !helperAccounts.has(appPtyId)) return - deliverStatus({ sessionId: appPtyId, ...helperAccountFields(appPtyId) }, sshDispatchWindow) + deliverStatus({ sessionId: appPtyId, ...helperAccountFields(appPtyId) }, sshDispatchWindow, { usageIsThisComputers: true }) } /** One usage reading of a held account's tab; delivered when it lands, if that start still stands. */ diff --git a/src/main/usage/account-usage.ts b/src/main/usage/account-usage.ts index ad195fada..35c6d4c8b 100644 --- a/src/main/usage/account-usage.ts +++ b/src/main/usage/account-usage.ts @@ -43,7 +43,7 @@ import { heldProfileFor } from './remote-tab-usage' import { USAGE_HOST, parseRetryAfter, usageHostPauses } from './usage-rate-limit' import { UsageChecker, IDLE_CHECK_INTERVAL_MS, type CheckOutcome, type CheckSchedule } from './usage-checker' import { USAGE_DETAIL_RENEWING, USAGE_DETAIL_NOT_SIGNED_IN, USAGE_DETAIL_DUPLICATE, USAGE_DETAIL_WRONG_ACCOUNT, USAGE_DETAIL_NO_READING, usageSignInProblem, type UsageSignInProblem, type AccountUsage, type UsageBucket, type CreditsInfo } from '../../shared/usage-types' -import { logWarn } from '../debug-logger' +import { logInfo, logWarn } from '../debug-logger' export type { AccountUsage } from '../../shared/usage-types' @@ -472,6 +472,21 @@ function profileForReportedEmail(sessionId: string, email: string): string | und return profileId } +/** Sessions a report that was not filed has been logged for: one line per + * session, so a session reporting every few seconds cannot fill the log. + * Bounded like the maps above; cleared when full. */ +const remoteNotFiledLogged = new Set() + +/** nubbymong/aicc_planning#516: say once per session why a report from a + * session with no local profile was not filed, so the drop leaves a line in + * the log. Neither the email nor any path is written. */ +function noteRemoteNotFiled(sessionId: string, why: string): void { + if (remoteNotFiledLogged.has(sessionId)) return + if (remoteNotFiledLogged.size >= LIVE_SESSIONS_MAX) remoteNotFiledLogged.clear() + remoteNotFiledLogged.add(sessionId) + try { logInfo(`[account-usage] session ${sessionId} (no local profile): its usage is not filed under an account, because ${why}. Later reports of this session are not logged.`) } catch { /* the log must not break the fan-out */ } +} + /** File a reading a session delivered, under the profile it runs on: the * session's own, and the profile's newest reading, kept in the snapshots * (nubbymong/aicc_planning#509: every reading the app sees is kept, so an @@ -498,7 +513,14 @@ function fileLiveReading(sessionId: string, profileId: string, buckets: UsageBuc * - a session with no local profile (an SSH tab, on its machine's own * sign-in), under the profile whose email is the one its status line * reports (`accountEmail`), when this computer holds one; that session - * then counts as open on the profile (noteRemoteSessionProfile). + * then counts as open on the profile (noteRemoteSessionProfile). Its + * report carries no transcript path (the SSH shim sends none), so none is + * asked for (nubbymong/aicc_planning#516). A tab through the session + * helper never reaches here: its frames' bars are this computer's own + * reading, which the fan-out keeps from the sink (session-signals/status.ts + * usageIsThisComputers); its own windows come in by recordHelperTabUsage. + * A report that is not filed says why once per session in the log + * (noteRemoteNotFiled), with neither the email nor any path. * An empty or all-malformed set is ignored (nothing to show). `hasCredits` is * not kept: the status line has no credits figure to show, so the credits row * comes from the last fetch (see newestFigure). @@ -516,17 +538,12 @@ export function recordLiveUsageForSession(sessionId: string, buckets: unknown, h if (owner !== localProfile) return profileId = localProfile } else { - // A session's own report carries its transcript path. A frame of a tab - // through the session helper carries none (the bars it shows are the - // reading main holds, statusline-watcher.ts dispatchHelperStatus), so it - // is never filed here: its own windows come in by recordHelperTabUsage. - if (typeof transcriptPath !== 'string' || !transcriptPath) return - if (typeof accountEmail !== 'string' || !accountEmail) return + if (typeof accountEmail !== 'string' || !accountEmail) { noteRemoteNotFiled(sessionId, 'its status line names no account email'); return } profileId = profileForReportedEmail(sessionId, accountEmail) // An account this computer does not hold (a switch on that machine) is // forgotten: the session no longer counts as open on the earlier one. noteRemoteSessionProfile(sessionId, profileId ?? '') - if (!profileId) return + if (!profileId) { noteRemoteNotFiled(sessionId, 'no account profile on this computer has the email its status line names'); return } } fileLiveReading(sessionId, profileId, clean, now) } @@ -683,7 +700,7 @@ async function inSessionUsage(base: AccountUsage, profileId: string, isPrimary: } /** Test seam: the live cache is module state and outlives a test file otherwise. */ -export function _resetLiveUsageForTest(): void { liveUsageBySession.clear(); remoteProfileCache.clear() } +export function _resetLiveUsageForTest(): void { liveUsageBySession.clear(); remoteProfileCache.clear(); remoteNotFiledLogged.clear() } /** Test seam: reset the hydrate latch + last-good map so a test can seed fresh * snapshots. Without it the once-per-process hydrate keeps the first test's view. */ diff --git a/src/preload/index.ts b/src/preload/index.ts index 13bb36a82..d8aa194e1 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -7,6 +7,7 @@ import { REMOTE_PLAN_MODE_WHYS, type RemotePlanModeWhy } from '../shared/types' import type { StatuslineData, SubmitTextResult, PromptButtonResult, CliBarCommand, AskConductorNotice, CanvasMarkerUndelivered, ClaudeMarkerAsk, ClaudeMarkerAnswer, CanvasSessionGuidance, AccountLogFolders, AccountLogFolderKind, AccountLogFolderOpenResult } from '../shared/types' import type { WebviewNavState } from '../shared/browser-url' import type { PasteKeyPress, PasteKeyResult, SnapPasteAnswer } from '../shared/clipboard-paste' +import type { UpdateKeepCounts, UpdateKeepTabs } from '../shared/update-keep' import type { AccountPaneStateView, CodexWebSessionView, CodexWebSignInState } from '../shared/account-web-session' import type { ModelRegistry } from '../shared/model-registry' import type { SentinelStateSnapshot } from '../shared/sentinel-types' @@ -287,6 +288,10 @@ export interface ElectronAPI { * Persistent tab with no mark with its config id, which main then reads * as under tmux before the tab spawns). */ tabsRestored: (tabs: Array<{ id: string; cwd?: string; tmuxConfigId?: string }>) => void + /** aicc_planning#515: the ids of the tabs an after-update restore brings + * back, named at the startup load, before any is restored: a session the + * update kept for one waits for it with no time limit from then. */ + tabsComingBack: (sessionIds: string[]) => void tabShown: (sessionId: string) => void onData: (sessionId: string, callback: (data: string) => void) => () => void onExit: (sessionId: string, callback: (exitCode: number) => void) => () => void @@ -648,6 +653,9 @@ export interface ElectronAPI { getVersion: () => Promise /** `discarded`: the user chose "Close sessions" on the update dialog. */ installAndRestart: (choice?: { discarded?: boolean }) => Promise + /** aicc_planning#514: how many of these open local tabs, by kind, an + * update now would keep running (the update dialog's counts). Counts only. */ + sessionsKept: (tabs: UpdateKeepTabs) => Promise hasSourcePath: () => Promise getSourcePath: () => Promise setSourcePath: (path: string) => Promise @@ -1153,6 +1161,7 @@ const electronAPI: ElectronAPI = { ipcRenderer.send(IPC.PTY_RESIZE, sessionId, cols, rows), kill: (sessionId, reason) => (reason === 'restart' ? ipcRenderer.send(IPC.PTY_KILL, sessionId, 'restart') : ipcRenderer.send(IPC.PTY_KILL, sessionId)), tabsRestored: (tabs) => ipcRenderer.send(IPC.PTY_TABS_RESTORED, tabs), + tabsComingBack: (sessionIds) => ipcRenderer.send(IPC.PTY_TABS_COMING_BACK, sessionIds), tabShown: (sessionId) => ipcRenderer.send(IPC.PTY_TAB_SHOWN, sessionId), onData: (sessionId, callback) => onChannel(ptyDataChannel(sessionId), callback), onExit: (sessionId, callback) => onChannel(ptyExitChannel(sessionId), callback), @@ -1379,6 +1388,8 @@ const electronAPI: ElectronAPI = { check: () => ipcRenderer.invoke(IPC.UPDATE_CHECK), getVersion: () => ipcRenderer.invoke(IPC.UPDATE_GET_VERSION), installAndRestart: (choice) => ipcRenderer.invoke(IPC.UPDATE_INSTALL_RESTART, { discarded: choice?.discarded === true }), + // Only the two id lists go; main reads them through updateKeepTabsFrom. + sessionsKept: (tabs) => ipcRenderer.invoke(IPC.UPDATE_SESSIONS_KEPT, { agents: tabs?.agents, terminals: tabs?.terminals }), hasSourcePath: () => ipcRenderer.invoke(IPC.UPDATE_HAS_SOURCE_PATH), getSourcePath: () => ipcRenderer.invoke(IPC.UPDATE_GET_SOURCE_PATH), setSourcePath: (path: string) => ipcRenderer.invoke(IPC.UPDATE_SET_SOURCE_PATH, path), diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 424c5d28b..60a3a6f02 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -106,12 +106,13 @@ import LoggingConsentPrompt from './components/LoggingConsentPrompt' import LogsWipeModal from './components/LogsWipeModal' import { bootChain, launchDialogsSuppressed } from './utils/bootGates' import ResumeSessionsPrompt from './components/ResumeSessionsPrompt' +import RestoreAfterUpdate from './components/RestoreAfterUpdate' import GitHubPanel from './components/github/GitHubPanel' import OnboardingModal from './components/github/onboarding/OnboardingModal' import AutoDetectBanner from './components/github/AutoDetectBanner' import { handleAutoDetectAccept } from './utils/githubAutoDetectAccept' import type { SessionState } from './types/electron' -import { buildSessionState, buildSessionStateWithResumeTargets, persistDetachedOnlyOrClear, hydrateDetachedFromSavedState, loadSavedStateAtStartup, closeWithNoSessions, discardAndClose, restoreSavedSessions, refreshRestoreOffer, setUnansweredRestore } from './session-persistence' +import { buildSessionState, buildSessionStateWithResumeTargets, persistDetachedOnlyOrClear, persistSessionState, hydrateDetachedFromSavedState, loadSavedStateAtStartup, closeWithNoSessions, discardAndClose, restoreSavedSessions, refreshRestoreOffer, setUnansweredRestore, markSavedForUpdate, restoreOfferAtStart, dropUpdateMarkOnDisk, tellMainTabsComingBack } from './session-persistence' import { useSessionAutosave, cancelSessionAutosave } from './hooks/useSessionAutosave' import { listenGoToSession } from './lib/goToSession' import { loggingConsentDue } from './utils/logging-consent' @@ -330,6 +331,12 @@ export default function App() { // this run. It is the whole saved set: a session whose provider cannot // launch is restored too and reopens as Not started (the prompt tags it). const [pendingRestore, setPendingRestore] = useState(null) + // aicc_planning#515: the saved set came from an app update the user chose + // Save sessions for, and this is a newer version (restoreOfferAtStart). Set + // with pendingRestore at the startup load: at the prompt's turn it is + // restored with nothing asked (RestoreAfterUpdate), each tab on its own + // account. + const [restoreAtOnce, setRestoreAtOnce] = useState(false) // P3.5 (a C item): while the prompt is unanswered, every write of the // session file keeps the set it offers (session-persistence), so a tab // launched meanwhile never overwrites it on disk. @@ -755,7 +762,20 @@ export default function App() { pingHosts: () => { void pingAllDetachedHosts() }, reconcile: () => useCommandBarStore.getState().reconcile(useSessionStore.getState().sessions.map((s) => s.id)), }) - if (savedState) setPendingRestore(savedState) + if (savedState) { + // aicc_planning#515: saved for an update by an older version, it is + // restored at the prompt's turn with nothing asked. The offer never + // carries the mark, and it is written back at once, so a quit or a + // crash before that turn leaves a set the next start asks about. + const { offer, atOnce } = restoreOfferAtStart(savedState, __APP_VERSION__) + setRestoreAtOnce(atOnce) + setPendingRestore(offer) + void dropUpdateMarkOnDisk(savedState, offer) + // Main hears now which tabs come back, so a session the update kept + // for one waits for it with no time limit while the release notes + // are up. A normal start says so only at Resume, as before. + if (atOnce) tellMainTabsComingBack(offer) + } // Nothing to ask about: nothing is restored, and what this start // brought back is the left-running registry just hydrated. else setRestoreTally({ sessions: [], detached: useDetachedRemotesStore.getState().entries }) @@ -918,6 +938,17 @@ export default function App() { } catch { stateToSave = buildSessionState() } + if (isUpdate) { + // aicc_planning#515: saved for this update, by this version, so the + // newer version's start reopens the set with nothing asked. A pending + // autosave would write the set again without the mark. + cancelSessionAutosave() + // Only with no resume offer pending: while the prompt is unanswered + // the set written keeps the tabs it offers (buildSessionState, P3.5), + // which nobody answered and the update dialog did not count. Unmarked, + // the newer version asks about the set as before. + if (pendingRestore === null) stateToSave = markSavedForUpdate(stateToSave, __APP_VERSION__) + } await window.electronAPI.session.save(stateToSave) console.log('[App] Session state saved') if (isUpdate) { @@ -930,6 +961,10 @@ export default function App() { } catch (err) { console.error('[App] Error during graceful shutdown:', err) if (!isUpdate) window.electronAPI.window.allowClose() + // aicc_planning#515: the update failed and the app stays, so the saved + // set is written again without the update's mark: a later start of this + // or another version asks as before. + else void persistSessionState() setIsClosing(false) // The update failed and the app stays: a later plain close must read // Closing..., not Updating... @@ -1347,6 +1382,28 @@ export default function App() { // here. } + // The restore of the saved set: the resume prompt's Resume, and + // (aicc_planning#515, `afterUpdate`) the restore after an app update the + // user chose Save sessions for, which asks nothing and carries each tab on + // on its own account. + const resumeSaved = (saved: SessionState, afterUpdate: boolean) => { + // Every saved session, as before: one whose provider cannot + // launch reopens as Not started and keeps its conversation, so a + // Restart once the provider is on carries on. + // What this start brings back, from the saved set itself (every + // session in it reopens, Not started or not), before the restore + // lands and before anything else can launch. + setRestoreTally({ sessions: saved.sessions, detached: saved.detachedRemotes ?? [] }) + // ADR-009 (Lens C, R7): mark the restore in flight BEFORE clearing + // the prompt, so a close before it lands keeps the saved file. + restoreUnsettledRef.current = true + setPendingRestore(null) + // P3.5: answered -- the file no longer keeps the offer (at once, + // before the restore's own write). + setUnansweredRestore(null) + void restoreSavedSessions(saved, restoreUnsettledRef, { probeGoneSessions, pingAllDetachedHosts, afterUpdate }) + } + // First-launch gates each have an independent trigger (wipe detection IPC, // version compare, settings flags, staggered boot timers); without a shared // priority they mount simultaneously and stack, with DOM order deciding who @@ -1494,28 +1551,16 @@ export default function App() { {/* Now a proper gate (bootGates: 'resume', lowest priority) rather than a surface that merely stepped around onboarding. It used to be gated on `bootGate !== 'onboarding'` alone, so a launch that showed - release notes painted this prompt over them. */} - {bootGate === 'resume' && pendingRestore && ( + release notes painted this prompt over them. aicc_planning#515: + after an app update the user chose Save sessions for, the same + turn restores with nothing asked (RestoreAfterUpdate), each tab on + its own account. */} + {bootGate === 'resume' && pendingRestore && (restoreAtOnce ? ( + resumeSaved(pendingRestore, true)} /> + ) : ( { - // Every saved session, as before: one whose provider cannot - // launch reopens as Not started and keeps its conversation, so a - // Restart once the provider is on carries on. - const saved = pendingRestore - // What this start brings back, from the saved set itself (every - // session in it reopens, Not started or not), before the restore - // lands and before anything else can launch. - setRestoreTally({ sessions: saved.sessions, detached: saved.detachedRemotes ?? [] }) - // ADR-009 (Lens C, R7): mark the restore in flight BEFORE clearing - // the prompt, so a close before it lands keeps the saved file. - restoreUnsettledRef.current = true - setPendingRestore(null) - // P3.5: answered -- the file no longer keeps the offer (at once, - // before the restore's own write). - setUnansweredRestore(null) - void restoreSavedSessions(saved, restoreUnsettledRef, { probeGoneSessions, pingAllDetachedHosts }) - }} + onResume={() => resumeSaved(pendingRestore, false)} onDontOpen={() => { const saved = pendingRestore setPendingRestore(null) @@ -1551,7 +1596,7 @@ export default function App() { } }} /> - )} + ))} {/* Last in the boot chain (bootGates): the second page of one upgrade story — release notes, then this — and its per-row copy counts read @@ -1589,7 +1634,10 @@ export default function App() { {closeDialog && ( { setCloseDialog(null); window.electronAPI.window.cancelClose() }} diff --git a/src/renderer/changelog.ts b/src/renderer/changelog.ts index 2acda84b1..10a79eaf2 100644 --- a/src/renderer/changelog.ts +++ b/src/renderer/changelog.ts @@ -40,6 +40,37 @@ export interface ChangelogEntry { // bracket-matching and tracks string quotes but NOT comments, so an apostrophe or // a backtick in a comment opens a phantom string and the parse fails. export const changelog: ChangelogEntry[] = [ + { + version: '2.1.3-beta.28', + date: '2026-12-04', + highlights: 'The close and update dialogs now say what Save sessions and Close sessions do to each kind of tab you have open, with a count for each. After an app update where you chose Save sessions, the new version reopens your tabs by itself, with nothing asked, starting with the update you make from this version. On the Accounts page, several lines can be open at once, every closed line has one shape, and a Claude Code tab over SSH now counts toward its account.', + warnings: [ + 'The update onto this version still asks you to resume your sessions, once, because 2.1.3-beta.27 and earlier do not mark the tabs they save for an update. You see the resume prompt and, with Settings, Accounts, Resuming sessions set to Ask each time, the account question for each tab. On Windows, if the update kept Claude Code or Codex sessions running, answer the resume prompt within five minutes of this version opening, and each tab\'s account question within five minutes of that tab first showing, or those sessions are ended. From the update you make from this version on, Save sessions reopens your tabs by itself, with nothing asked.', + 'A Claude Code tab over SSH is matched to one of your accounts by the email in the .claude.json file in your home folder on that machine. If you run Claude Code there with a CLAUDE_CONFIG_DIR of your own, signed in as another account, the tab\'s status line still names the account in that .claude.json file, so the Accounts page shows the tab\'s figures on that account\'s line and counts it In use. Leave CLAUDE_CONFIG_DIR unset on that machine for the tabs the app opens.', + 'This beta series begins moving the app\'s background services, and over the next betas your sessions, onto one helper per machine. If you want a quiet build, stay on the stable release.', + 'The app no longer renews a Claude Code account\'s sign-in. Claude Code renews it when you next open a session on that account. Until then an idle account whose sign-in has lapsed shows its last reading, marked as an estimate, and use made elsewhere on it does not show.', + 'On Windows, choosing Save sessions at an update keeps the terminals and the Claude Code and Codex sessions the session helper holds running only if the new version opens within two minutes of the old one closing. The installer\'s pages count toward those two minutes, so finish the installer promptly. The update dialog says how many of your tabs it keeps running.', + 'On Windows, Snap takes its picture with the app\'s own capture and overlay by default. If a press cannot take a picture, the earlier Snap opens for that press; to use the earlier Snap every time, choose Settings, Custom Commands, Snap, Snap on Windows: Previous.', + 'A picture you paste or Snap now goes through your clipboard. Snap leaves its picture there, and an image file you copied and paste into Claude Code is replaced on the clipboard by its picture. It is an ordinary clipboard item, so Windows clipboard history and sync follow your own Windows settings.', + 'Signing a Claude Code or Codex account in on a Linux machine (a preview on Windows, off by default) keeps that sign-in on that machine, in a folder only your user there can read. Nothing is copied from this computer. Sign out on the Machines page ends it, and Remove signs the accounts out first.', + 'If you later install a stable release and want stable releases only, open Settings, General, Update Channel and choose Stable. A beta build can leave Beta saved, and a stable release would then keep offering betas.', + 'To go back to 2.1.3-beta.27, download its installer from the GitHub releases page and run it over this version.', + ], + changes: [ + { type: 'improvement', description: 'After an app update where you chose Save sessions, the new version reopens your tabs by itself, with nothing asked, once you close the pages it opens with (such as the release notes). There is no resume prompt, and no account question for each tab, even with Settings, Accounts, Resuming sessions set to Ask each time: each tab carries on on the account it was on. On Windows, a session the update kept running waits for its tab however long those pages stay open. This starts with the update you make from this version on. A quit, a crash, the same version starting again, and an update made while the resume prompt was still unanswered still ask with the resume prompt.' }, + { type: 'improvement', description: 'The close and update dialogs now say what each button does to the tabs you have open, with a count for each kind. Under With Save sessions, the update dialog says how many keep running through the update and come back in the same tabs, how many SSH sessions keep running on their hosts and reconnect, how many restart and pick up their conversations, how many SSH sessions restart, and how many terminals restart as new terminals. The quit dialog does the same for the next launch. A tab that has not started (it reads Not started) comes back as it is, and a tab the app opened to sign in on a machine you added, or to install or update a program, closes and does not come back. The last line says what Close sessions does. A line with a count of none is left out.' }, + { type: 'fix', description: 'The close and update dialogs said that sessions you close are gone. An SSH Persistent session keeps running on its host when you choose Close sessions, and the dialog now says so.' }, + { type: 'improvement', description: 'The help text under Resuming sessions in Settings, Accounts now says the choice applies when you open the app again and resume your sessions, and that after an app update where you chose Save sessions each session keeps the account it was on, with no question.' }, + { type: 'improvement', description: 'On a slow PC, a session that starts while the app is still starting can start a little sooner: the start-up checks it waits for now run side by side instead of one after another. It still waits up to 5 seconds for the check that brings its status line and resume list. If that check takes longer, the session starts without them: restart the tab once the app has started.' }, + { type: 'fix', description: 'A Claude Code tab over SSH, on the usual SSH path rather than through the session helper, now counts toward its account on the Accounts page: the account shows In use with the tab\'s live figures. Before, an account you used only that way kept its last background reading and read Not in use while the tab showed live figures.' }, + { type: 'improvement', description: 'On the Accounts page, lines open and close on their own: any number can be open at once, and Escape closes the open line you are in.' }, + { type: 'improvement', description: 'Every closed line on the Accounts page has one shape: the name and plan, then the email and the account\'s roles, with the email shortened first when there is not room. How many tabs run on an account is on its open line, in a Running row. A per-model limit at 90% or more is named in place of a reset time, for example Opus 92% used. A stronger rule now parts one account from the next.' }, + { type: 'improvement', description: 'A figure on the Accounts page that is an estimate is marked ~, for example ~36% used, on its line and in the Most room now summary. The open line\'s Readings row is now called Usage read. It holds where the figures come from, the sentence that says an estimate is in use, and the age of any figure kept from an older reading. How readings work says what ~ means.' }, + { type: 'improvement', description: 'When Anthropic\'s rate limit makes the app\'s background check wait, the Usage heading now says so once for the page: Background check rate limited, with a countdown to when it retries. An open line says Rate limited and the countdown on its Usage read row. A closed line no longer says it.' }, + { type: 'improvement', description: 'What account isolation changed for your sessions is now said once, at the foot of the Accounts page behind What account isolation changed, with each change under the names of the accounts it was made for. An account\'s own line now shows only a launch that was refused or that started with something unchecked.' }, + { type: 'improvement', description: 'A name, email, role, reset time or note on an account\'s line that does not fit shows its whole words as a tooltip, and only while it is cut.' }, + ], + }, { version: '2.1.3-beta.27', date: '2026-12-03', diff --git a/src/renderer/components/CloseDialog.tsx b/src/renderer/components/CloseDialog.tsx index 299ee31ef..c49a8a67f 100644 --- a/src/renderer/components/CloseDialog.tsx +++ b/src/renderer/components/CloseDialog.tsx @@ -1,24 +1,57 @@ -import React, { useRef } from 'react' +import React, { useEffect, useRef, useState } from 'react' import { DialogOverlay, DialogPanel, DialogHeader, DialogBody, DialogFooter, DialogButton, useDialogEscape, WINDOW_CLOSE_Z } from './ui/Dialog' import { useContainFocus } from '../onboarding/contain-focus' import { useOccludesNativePanes } from '../stores/paneOcclusionStore' +import { closeDialogText, updateKeepQuestion, type CloseDialogTab } from '../utils/closeDialogText' +import { NOTHING_KEPT, updateKeepCountsFrom, type UpdateKeepCounts } from '../../shared/update-keep' interface CloseDialogProps { mode: 'close' | 'update' - sessionCount: number + /** The tabs open when the dialog opens; it reads them once. */ + tabs: ReadonlyArray onSaveAndClose: () => void onCloseWithoutSaving: () => void onCancel: () => void } +/** + * aicc_planning#514: how many of `tabs` an update now would keep running, by + * kind, as main answers (update:sessionsKept, by the rule the update itself + * goes by). Null while the answer is out. A quit keeps none, and so does an + * update with no local tab, a question that fails or an answer that does not + * read: the dialog then says less is kept, never more. + */ +function useKeptThroughUpdate(mode: 'close' | 'update', tabs: ReadonlyArray): UpdateKeepCounts | null { + const [kept, setKept] = useState(mode === 'update' ? null : NOTHING_KEPT) + useEffect(() => { + const question = updateKeepQuestion(tabs) + const ask = window.electronAPI?.update?.sessionsKept + if (mode !== 'update' || !ask || question.agents.length + question.terminals.length === 0) { + setKept(NOTHING_KEPT) + return + } + let live = true + setKept(null) + Promise.resolve() + .then(() => ask(question)) + .then((answer) => { if (live) setKept(updateKeepCountsFrom(answer) ?? NOTHING_KEPT) }, () => { if (live) setKept(NOTHING_KEPT) }) + return () => { live = false } + }, [mode, tabs]) + return kept +} + /** * Closing (or updating) with sessions open: save them, close them, or cancel. + * It says what each choice does to the tabs open now, with counts + * (closeDialogText, aicc_planning#514): a lead-in naming Save sessions, a + * line for each kind of tab open (what that button does), then one that + * starts with Close sessions, so each half names its button. * It paints on the top layer (WINDOW_CLOSE_Z), above the onboarding pages and * the introduction's takeover and replay, and keeps Tab inside itself while * it is open: it was once painted under those surfaces, invisible, with focus * on "Save sessions", and Tab walked out of it into the page behind. */ -export default function CloseDialog({ mode, sessionCount, onSaveAndClose, onCloseWithoutSaving, onCancel }: CloseDialogProps) { +export default function CloseDialog({ mode, tabs, onSaveAndClose, onCloseWithoutSaving, onCancel }: CloseDialogProps) { useDialogEscape(onCancel) const panelRef = useRef(null) // "Save sessions" keeps the focus it opens with (autoFocus below); the trap @@ -28,6 +61,12 @@ export default function CloseDialog({ mode, sessionCount, onSaveAndClose, onClos // above all HTML, so they hide while this shows. The overlay is `absolute`, // and DialogOverlay holds that flag only for a `fixed` one. useOccludesNativePanes() + // The tabs as they were when it opened: the count, the lines and main's + // answer are all about the same set, and main is asked once. + const [open] = useState(tabs) + const kept = useKeptThroughUpdate(mode, open) + const text = kept ? closeDialogText(mode, open, kept) : null + const sessionCount = open.length return ( @@ -37,9 +76,13 @@ export default function CloseDialog({ mode, sessionCount, onSaveAndClose, onClos subtitle={<>You have {sessionCount} active session{sessionCount !== 1 ? 's' : ''}.} /> -

- Save them and they come back at the next launch, in the same tabs; close them and they are gone. -

+ {text && ( +
+

{text.lead}

+ {text.lines.map((line) =>

{line}

)} +

{text.close}

+
+ )}
Cancel diff --git a/src/renderer/components/RestoreAfterUpdate.tsx b/src/renderer/components/RestoreAfterUpdate.tsx new file mode 100644 index 000000000..86cc31624 --- /dev/null +++ b/src/renderer/components/RestoreAfterUpdate.tsx @@ -0,0 +1,24 @@ +import { useEffect, useRef } from 'react' + +/** + * aicc_planning#515: the resume prompt's turn in the boot chain (bootGates, + * 'resume') when the saved set came from an app update the user chose Save + * sessions for, read by a newer version (restoreOfferAtStart's `atOnce`). + * Nothing is asked: it shows nothing and, once, restores (`onRestore`, the + * same restore the prompt's Resume starts). It takes the prompt's turn rather + * than restoring at load, so every page the chain shows before it (the + * release notes, the indexing notice) still comes first, and nothing starts + * behind one. Main heard at the startup load which tabs come back + * (tellMainTabsComingBack), so a session the update kept for one waits for it + * meanwhile with no time limit. Once only, also when React runs its effects + * twice in development. + */ +export default function RestoreAfterUpdate({ onRestore }: { onRestore: () => void }): null { + const done = useRef(false) + useEffect(() => { + if (done.current) return + done.current = true + onRestore() + }, [onRestore]) + return null +} diff --git a/src/renderer/components/SettingsPage.tsx b/src/renderer/components/SettingsPage.tsx index 563c11c62..2746c146e 100644 --- a/src/renderer/components/SettingsPage.tsx +++ b/src/renderer/components/SettingsPage.tsx @@ -614,7 +614,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat /> Plain terminals through the session helper - Preview, off by default. A Terminal only tab and the partner terminal of a session on this computer start inside the session helper. On Windows they keep running if the app crashes, and come back with their tabs if you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, for up to two minutes until the new version opens. Claude Code and Codex sessions have their own switch below, and SSH sessions are not affected. Quitting normally ends them. Applies to terminals opened after the change. The Machines page shows the helper and what it holds. + Preview, off by default. A Terminal only tab and the partner terminal of a session on this computer start inside the session helper. On Windows they keep running if the app crashes, and come back with their tabs if you open it again within two minutes and resume your sessions. On Windows they also keep running through an app update when you choose Save sessions, if the new version opens within two minutes. Claude Code and Codex sessions have their own switch below, and SSH sessions are not affected. Quitting normally ends them. Applies to terminals opened after the change. The Machines page shows the helper and what it holds. {/* 2.1.3-beta.7 (plan section A3): agent sessions through the session helper, a preview. */} @@ -627,7 +627,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat /> Claude Code and Codex sessions through the session helper - Preview, off by default. A Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before. It does not survive a crash yet: when you open the app again, the session is ended and its tab resumes the conversation as before. Quitting normally ends it. On Windows it keeps running through an app update when you choose Save sessions, for up to two minutes until the new version opens: resume your sessions within five minutes of that and its tab takes the same session over. On Windows, ending a session also ends every program it started, even one it opened in a window of its own. SSH sessions are not affected. Applies to sessions started after the change. The Machines page lists them. Insights' Claude Code report runs this way too. + Preview, off by default. A Claude Code or Codex session on this computer starts inside the session helper, launched exactly as before. It does not survive a crash yet: when you open the app again, the session is ended and its tab resumes the conversation as before. Quitting normally ends it. On Windows it keeps running through an app update when you choose Save sessions, if the new version opens within two minutes. The new version reopens your tabs by itself once you close the pages it opens with (such as the release notes), and each tab shows the same session again, however long those pages stay open. On Windows, ending a session also ends every program it started, even one it opened in a window of its own. SSH sessions are not affected. Applies to sessions started after the change. The Machines page lists them. Insights' Claude Code report runs this way too. {/* 2.1.3-beta.17 (plan section A2): remote sessions through the session helper, a preview (Windows). */} @@ -708,7 +708,7 @@ export default function SettingsPage({ initialTab, onNavigateToSessions, onUpdat

- Only matters with two or more Claude accounts. Applies when the app restarts and reopens your sessions. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in. + Only matters with two or more Claude accounts. Applies when you open the app again and resume your sessions. After an app update where you chose Save sessions, you are not asked: each session keeps the account it was on. Codex sessions keep their own Codex account, and SSH sessions use the remote machine's sign-in.

diff --git a/src/renderer/components/accounts/AccountsPage.tsx b/src/renderer/components/accounts/AccountsPage.tsx index 3fdb2b594..6bcebcd14 100644 --- a/src/renderer/components/accounts/AccountsPage.tsx +++ b/src/renderer/components/accounts/AccountsPage.tsx @@ -13,6 +13,12 @@ // (28 px), the column headings (24 px) and the first group's heading (32 px). // Above them, only when there is one: an account whose name or colour was // changed both here and in its provider, to settle (ConflictBanner). +// +// nubbymong/aicc_planning#517: every closed line has one shape (64 px), a +// strong rule (ROW_RULE) parts one account from the next, lines open and +// close on their own, and what is the same for the whole page is said once: +// the background check's rate limit in the Usage heading, what account +// isolation changed at the foot. import React, { useEffect, useLayoutEffect, useRef, useState } from 'react' import PageFrame from '../PageFrame' import { useRenderEvery } from '../../hooks/useRenderEvery' @@ -26,12 +32,15 @@ import { managedListProviders, providerView } from '../../stores/providerAccount import { PROVIDER_NAMES } from '../../provider-names' import { RowMenu } from '../ui/RowMenu' import { useMenuOccludesNativePanes, useSurfaceOnScreen } from '../../stores/paneOcclusionStore' -import { CLAUDE_OFF_USAGE_LINE, COUNTDOWN_TICK_MS, LineButton, MetersPending, MUTED, RENEWAL_BODY, Segmented } from './usage-parts' +import { + CLAUDE_OFF_USAGE_LINE, COUNTDOWN_TICK_MS, LineButton, MetersPending, MUTED, RATE_LIMITED_PAGE_LEAD, RateLimitedLine, RENEWAL_BODY, Segmented, figuresAreEstimate, +} from './usage-parts' import { PROFILES_PROVIDER, leftoversLine, ledgerItems, nameOfProfile, type LedgerItem } from './ledger' import { LedgerRow, type LedgerRowSlots } from './LedgerRow' import { ConflictBanner } from './ConflictBanner' import { noBreakHyphens } from '../settings/accounts/accounts-ui' -import { ACCOUNT_GUTTER, LEDGER_INSET, LEDGER_TRACKS, WIDE_FROM_PX, type LedgerLayout } from './layout' +import { AccountIsolationChanges } from '../settings/AccountIsolationNotice' +import { ACCOUNT_GUTTER, LEDGER_INSET, LEDGER_TRACKS, ROW_RULE, WIDE_FROM_PX, type LedgerLayout } from './layout' import type { AccountsPageActions, AccountsPageData } from './model' /** Lines' ages move on while the page stays open. */ @@ -51,9 +60,10 @@ export const MAC_ONE_ACCOUNT_LINE = 'Multiple Claude Code accounts are not avail export const CLAUDE_ACCOUNTS_NOTE = 'For Claude Code accounts, the email is the account and the name is only a label, and memory, settings and history are shared between them. You pick the account when a session starts.' /** "How readings work" opens upward, unless the scrolling area above its - * link has less room than this for the note (340 x 206 px and its gap); - * then it opens downward. */ -export const READINGS_NOTE_ROOM_PX = 220 + * link has less room than this for the note (340 x 226 px: ten 20 px lines, + * one more than before #517's sentence on "~", and its padding; then its + * gap); then it opens downward. */ +export const READINGS_NOTE_ROOM_PX = 240 /** The top of the nearest scrolling ancestor (the viewport's top when none). */ function scrollAreaTop(el: HTMLElement): number { @@ -75,9 +85,9 @@ export const peopleIcon = ( ) -/** The open line and where each line stood, kept while the app runs (never - * saved), so coming back finds the page as it was left. */ -const memory: { open: string | null | undefined; basis: UsageGridEntry[] | null } = { open: undefined, basis: null } +/** The open lines and where each line stood, kept while the app runs + * (never saved), so coming back finds the page as it was left. */ +const memory: { open: readonly string[] | undefined; basis: UsageGridEntry[] | null } = { open: undefined, basis: null } /** Start the next drawing afresh (tests, the harness's seed switch). */ export function resetAccountsPageMemory(): void { @@ -176,7 +186,7 @@ function BandHeading({ band, alone }: { band: UsageBand; alone: boolean }) { /** A line before the profiles' list first resolves. */ function PendingRow({ layout }: { layout: LedgerLayout }) { return ( -