BATONPASS · 8 MIN
Every step that can fail goes first
A long Claude Code chat eventually runs out of room, and the fix is manual: ask it for a summary, copy that somewhere, open a new terminal, start a session, paste, and close the old one. BatonPass is a tray widget that shows how full each chat’s context window is and does that whole routine in one click. The summary is the baton; passing it is the point.
Both halves, the measuring and the handing off, turned out to be the same kind of problem. The obvious approach works on the case you’re imagining and fails quietly on the real files.
Measuring a chat from the outside
There’s no API for this, and BatonPass doesn’t want one. Everything comes from
the transcripts Claude Code already writes under ~/.claude. There’s no sign-in,
no key, and no networking code anywhere in the app.
A chat’s current context is the usage on its last assistant record:
function contextTokensOf(usage) {
return (
(usage.input_tokens || 0) +
(usage.cache_read_input_tokens || 0) +
(usage.cache_creation_input_tokens || 0)
);
}
Output tokens are left out on purpose. They come back as input on the next turn, so counting both would double them.
“The last assistant record” hides two traps. Interrupts and errors are written
as assistant records too, with the model set to <synthetic> and every usage
field zeroed. Read one of those as the current state and a full session reports
an empty context, which is exactly what made two transcripts appear to drop to
zero the first time I surveyed the data. They’re skipped. And apiBlockIndex,
which looks like a compaction marker, isn’t one: it cycles 0, 1, 2 within a
single turn, one entry per API call in a multi-tool turn.
Transcripts here run past 10 MB, and only the final record matters, so the scanner reads the last 512 KB and walks backwards. A tail that holds nothing usable falls back to the whole file. Checked against a naive full scan on every transcript on disk, it agreed 36 times out of 36 and ran 9.4x faster. Unchanged files come out of an mtime-keyed cache, so a poll costs about a millisecond.
The denominator is printed on purpose
A percentage needs a window size, and that’s a lookup:
const WINDOWS = [
{ match: /haiku/i, tokens: 200000 },
{ match: /opus-5|opus-4-[678]|sonnet-5|sonnet-4-6|fable|mythos/i, tokens: 1000000 },
];
First match wins, so order is load-bearing. Anything unrecognised falls back to 200k, the likelier size for an older model.
The widget always prints 419k / 1M rather than a bare 42%. If this table is
ever wrong, the mistake shows up on screen as an implausible figure instead of
silently skewing a bar. That’s also why the app measures context and not plan
quota: a context window is a published property of the model, and a plan limit
is a number I could only ever guess at.
The order is the safety property
The handoff is six steps, and the comment at the top of handoff.js says what
matters about them:
// The handoff: summarise -> validate -> save -> launch -> mark -> kill. Every
// step that can fail runs before any step the user can't undo.
Walk the failures through. An empty summary writes no file and kills nothing. A summary that saves but can’t get a terminal open leaves the file on disk and the old session running:
if (!opened.ok) {
// The summary survives and the old session keeps running; a second click
// retries only this step.
return setState(session.sessionId, {
status: 'failed',
filePath,
message: tidy(`Saved, but couldn't open a terminal. ${opened.error || ''}`),
}, onChange);
}
That filePath on the failed state is what makes the retry cheap. The next
click sees a failed job with a file that still exists, skips straight to the
launch, and doesn’t pay for the summary twice.
The kill comes last, and even then it isn’t destructive. The old chat is
stopped, never deleted. Its transcript stays on disk, so claude --resume
brings it back if the handoff turns out to be thin.
The chat writes its own summary
The tempting version parses the transcript and paraphrases it. That produces a much poorer summary from much less understanding. Instead, BatonPass asks the conversation itself:
const args = ['--print', '--resume', sessionId, '--fork-session'];
// ...
if (model && MODEL_NAME.test(model)) args.push('--model', model);
--resume supplies the context, all of it. --fork-session keeps the run out
of the live session’s transcript, and --print is the windowless part. It’s the
same conversation asked the same question, just not on screen.
What’s missing from that list matters as much as what’s in it. Prompt caching is
a prefix match over tools, then system, then messages, and anything that
disturbs the prefix re-bills the whole transcript at write price. So there is no
--tools "" (tool definitions sit at position zero), and --model is always the
chat’s own model, because caches are model-scoped. A measured run came back 81%
cache read. On a chat sitting at 500k tokens, that flag list is the cost story.
The summary reaches the new session as an @ mention of the saved file, which
Claude Code expands before the first turn. The alternative is passing the
document itself as an argument, where it has to survive three command-line
parsers and an 8191-character ceiling. A single space-free path survives all of
them.
Failures that don’t fail
Opening a visible terminal from a windowless GUI process is something neither OS makes easy, and the Windows side is a list of approaches that fail with no error at all:
wt.exeis an App Execution Alias, sofs.existsSyncreturns EACCES on it and reports Windows Terminal as missing on a machine where it’s installed. OnlyaccessSync(X_OK)tells the truth.startgiven a forward-slash path exits 0 and launches nothing.git-bash.exe --command=runs the command but opens no window for it. A probe that only wrote a file passed. Claude, which needs a terminal, launched invisibly and exited at once. Git Bash goes throughmintty.exeinstead.- A pid isn’t an identity, because Windows reuses them. Every kill is gated on the image name and the creation time Claude Code records, with a millisecond of tolerance because the two clocks round differently.
That third one is the lesson in miniature. A test that checks a side effect other than the one you care about will pass while the real thing is broken.
Even ancestry lies. MSYS emulates fork(), the intermediate process exits, and
Windows reports a Git Bash shell’s parent as a dead pid. MSYS keeps its own
process table, so detection tries Win32 ancestry first and falls through to
ps -W when the trail goes cold.
Coming back from the dead
A handed-over chat that gets written to again should return to the Active tab. Transcript mtime is the cheap trigger, since every row already carries it, but mtime lies at exactly the worst moment: stopping a session makes it flush one last record, about five seconds after the kill returns, with no process behind it.
So it takes two signals. The mtime has to move past a baseline taken after the kill, and the session has to be live again, checked against the registry with a signal-0. A corpse’s last write passes the first test and fails the second.
What’s still open
Claude Code auto-compacts before the hard window, so the percentage is an honest upper bound, not a countdown to compaction. I’m fine with that: no session on this machine has compacted yet, and the largest reached 541k of 1M.
Two limits I can’t fix from here. A chat that lived in VS Code hands off to
Windows Terminal, because the code CLI can’t open an integrated terminal
running a given command. And on macOS, a node-based dev install of Claude runs as
node …/cli.js, which detection doesn’t recognise, so that setup gets no host
detection and no kill. It costs a fallback launch rather than correctness, and
the check can never match the wrong process. When a guard has to be wrong in some
direction, that’s the direction to choose.