Repository navigation
fix: preserve Claude CLI chat context across account switches - #168781
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
@clawsweeper review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR gives fresh Claude CLI sessions a metadata-only history notice after account changes and recognizes that notice during native-history imports. Example: A chat remembers ALPHA1739, then an account change starts a fresh native Claude session.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: current main still lacks fresh-account history notices, the prior documentation finding is resolved, and no new actionable defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherCLI preparation reads the canonical conversation and admitted session identity, adds bounded metadata to the native prompt, and lets the existing history tool retrieve content; native-history imports correlate decorated prompts with original local rows. flowchart TD
A[Existing OpenClaw chat] --> B[CLI session preparation]
C[Account invalidation] --> B
B --> D[Metadata notice]
D --> E[Fresh Claude CLI session]
E --> F[Authorized history tool]
F --> A
E --> G[Native history correlation]
Technical reviewBest possible solution: Retain the shared metadata-notice and import-correlation implementation while preserving the existing automatic-replay boundary. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the missing fresh-account notice, and the contributor reports baseline failures for both memory and durable cases; this read-only review ran no target code. Is this the best way to solve the issue? The focused extension reuses the existing renderer, prompt delivery, tool-policy hint, and import-normalization owner while leaving raw replay and saved notes blocked. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 626eeac26d62. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +7, Tests +42, Docs +2. Total +51 across 6 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 10, 2026, 9:28 PM ET / October 11, 2026, 01:28 UTC (Revision 2). |
|
Corrected the existing history-boundary paragraph to distinguish fresh-session metadata notices from blocked automatic replay. Added inspected native stdin, tool-call and final-history excerpts from the successful 2/2 real-Claude account-switch campaign to the PR body. Documentation link and formatting checks pass. @clawsweeper re-review |
|
Landed in c8a4e51. Switching Claude CLI accounts now keeps the conversation through on-demand history reading. |
…aw#168781) When a Claude CLI chat moved to a different account (for example after one account's quota ran out), the new account started a fresh native Claude session with no idea the chat had history. The openclaw#140294 boundary blocked all context, and keychain logins (the common setup) never got same-account recovery either. The fresh native session now gets a one-turn note with metadata only: how many earlier messages the chat has, when, and on which models, plus the exact mcp__openclaw__sessions_history call to read them under normal tool policy. Raw transcript content is still never replayed across accounts. The note reuses the switch-back renderer, inline delivery and importer stripping from openclaw#168726, and it is omitted when tool policy hides sessions_history. Real Claude CLI proof: 2/2 account-switch loops read history with the exact session key and answered the original token; the no-switch control got no note; following turns did not repeat it. Co-authored-by: Ayaan Zaidi <[email protected]>
…164175) * fix(agents): carry isolated CLI completion turns into the next resume - A preserved inter-session turn that runs outside the bound native CLI session reports its prompt and reply; the binding owner stores them on that binding, bounded like other context blocks, only when the auth identity matches. - The next turn that resumes the bound session prepends them once as a marked context block; any completed turn in that session consumes them, and a fresh session recovers them from saved history instead. - The completion turn's tool projection, MCP configuration, and loopback grant are unchanged. - A real-seam regression covers continuity and denial; store guard, resume-context order, and chat-history dedupe tests cover the new binding field. - The Claude CLI Gateway live announce probe now sends one more requester turn and checks Claude's transcript for the session it resumed. - CLI backend and sub-agent tool policy docs describe the contract. * fix(agents): replay carried CLI exchanges only under the history account boundary - The resume renderer prepends pending completion exchanges only when the turn holds the CLI history writer, the authority that already gates saved-history recovery - Settlement keeps no exchange for a binding without an auth epoch (opaque native login) - Regression covers a named account (carried once), an opaque native login (nothing kept) and an identity-less login whose token is replaced (withheld and dropped) - The live continuity probe expects the exchange only when the requester's history boundary is known - Docs state the account requirement * fix(agents): carry completion replies from the canonical transcript - Drop the persisted unseenTurns binding field, its settlement (settlePreservedCliSessionTurn) and the cliUnseenTurn run meta; the native binding contract is back to main's - Derive the carried context at resume time from the requester transcript: completion replies saved after the bound session's last ordinary Claude reply, recognized by their announce run id (announce:) or by a saved user row with completion provenance, newest 8, each bounded like context JSON - Replay still requires the turn's CLI history writer; without it the session-gap note now counts those completion turns instead of treating the completion reply as the last turn the session saw - Add isAnnounceIdempotencyKey next to buildAnnounceIdempotencyKey - Regression harness mirrors the Gateway: completions run under the announce key and save no user row; credential replacement covers a named account as well as an identity-less login - Move the transcript-derivation unit test to session-history.preserved-turns.test.ts (line cap) * fix(agents): name carried completion turns as delivered events - Label the carried block as completion events delivered in a separate session, each with the reply sent then, and give each record its source tool; with only a bare reply, installed Claude answered the next message as if no completion had arrived - Read the transcript run id with asOptionalRecord - Keep the preserved-turn check inside session-history; input-provenance is unchanged - Publish the runtime config snapshot in the regression harness, as the sibling attempt tests do since #169714 - Pin the newest-8 bound in the preserved-turns test * test(gateway): match the carried completion record in the live announce probe The live CLI-backend announce probe searched the resumed Claude session's user turns for the inter-session prompt envelope. A completion saved without a user row renders a reply-only record, so the authorized branch failed even when the resumed session received the result; when the handoff resumed the bound session instead, the probe matched the handoff prompt itself. Parse the marked context blocks of the follow-up turn and match the record's source and reply. Whether the handoff resumed the bound session (prompt drift only) or ran in its own session (an MCP hash change) is recorded, not asserted: the follow-up turn owes the record either way. * fix(agents): describe carried completions without naming where they ran A completion handoff resumes the requester's bound Claude session when only prompt content drifted, and runs in its own session when its MCP projection hashes differently. The transcript does not record which one happened, yet the carried-completion label told Claude the events arrived in a separate session, and the session-gap note for a withheld login said they occurred outside this session. Both were wrong in the resumed case. Say what is known: the completion events were recorded in the conversation since the session's last reply here, and the session may already hold some of them. The gap note counts preserved turns with the same wording, and the prompt-text stripper recognizes it like the existing notes. The account gate and the bounded carry are unchanged. * fix(agents): simplify resumed Claude completion context Keep completion recovery in the canonical transcript owner, reuse bounded context rendering, and preserve account-authorized replay. Retain focused history, renderer, and import regressions; remove duplicate live proof scaffolding. Mark historical facts and preserve original user transcript text. Co-authored-by: Mitchell Etzel <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Mitchell Etzel <[email protected]> (cherry picked from commit d472fc5) Backport note: semantic port onto 2026.10.5. The release line lacks the Claude session-gap note (#168726/#168781), createCliCurrentPromptRenderer and cli-session-history.prompt-text.ts, so this keeps only the completion carry: session-history classifies Claude replies from the canonical transcript and renders the newest 8 preserved/announce exchanges since the last ordinary reply for a resumed claude-cli native session; prepare.ts prepends them (after any drift note) only when the turn holds the CLI history writer, via the renamed prependCliSessionResumeUserContext. Auth-boundary reasons already return before the transcript read, so withheld turns carry nothing. Gap-note wording, its stripper regex and their routed-prompt/dedupe test cases are dropped; docs say withheld content is not replayed. Renderer tests target the release helper; the preserved-turns test drops gap-note and admission assertions.
What Problem This Solves
Fixes loss of conversation continuity when an existing Claude CLI chat starts a fresh native session after an account change.
Related: #140294 and #168726.
User Impact
Account switches now keep continuity through on-demand history reading, including opaque native logins. The new session gets a metadata-only note; raw transcript replay and durable context remain blocked across accounts. No configuration or schema change is required.
Why This Change Was Made
Reuse the switch-back note renderer, inline prompt delivery, tool-policy-aware history hint, and importer stripping for fresh Claude sessions after auth-profile, auth-epoch, or auth-unknown invalidation. The note describes earlier recorded messages without including their contents. Subsequent native turns do not repeat it. Brand-new chats receive no note, and unavailable
sessions_historytools are never advertised.Evidence
origin/main(f28e5ba25b1) fails both memory/durable fresh-account regression cases: expected earlier-message note, receivedundefined(44 other tests passed).pnpm exec vitest run … --maxWorkers=1andOPENCLAW_RUN_NODE_SKIP_DTS_BUILD=1; formatting andgit diff --checkpassed. Full CI on the implementation head passed in 7m51s. The subsequent docs-only review repair passed link checks (14,991 links, zero broken), docs formatting andgit diff --check.mcp__openclaw__sessions_historywith the exact chat key and returned the original token. Account changes were simulated by changing only the saved native binding's prior auth-profile identity while the isolated Gateway was stopped, forcing the ordinary auth-invalidation path on restart.~/.claude/CLAUDE.mdandsettings*.jsonSHA-256 and mtimes unchanged. The one created native project directory was removed; no unexpected project directories were created.pnpm buildcompleted successfully. Its existing Control UI startup-size advisory was printed; this change does not touch UI assets.Two-way door: reverting removes the metadata note behavior without a migration. Blast radius is Claude CLI conversation preparation and decoration matching; other runtimes and raw-history account boundaries are unchanged.
Inspected native proof excerpts (synthetic tokens only)
Native stdin for loop 1 (exact user-prompt text):
Native stream-json tool call:
{"type":"tool_use","id":"toolu_01F5b3ZCq9mnqUYpXbTjQbzq","name":"mcp__openclaw__sessions_history","input":{"sessionKey":"agent:main:account-switch-1","limit":100},"caller":{"type":"direct"}}The matching
tool_resultcontains the earlier user messageRemember token ALPHA1739. Reply ACK only.and assistantACKunderagent:main:account-switch-1. The final answer wasALPHA1739. Projecting the finalchat.historyresponse to user text gives exactly:Loop 2 independently called the same tool with
{"sessionKey":"agent:main:account-switch-2","limit":100}, received the earlierALPHA2739message and answeredALPHA2739. The no-switch control answeredALPHA3739without calling history. All three next-turn prompts wereReply AFTER only.without an earlier-message note, and all three answeredAFTER.