Repository navigation
feat(native-chat): show context window usage in the composer - #22301
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds Claude context-usage capture through the control API and records context facts on structured journal turns. Shared types and schemas support provider reports, estimates, unknown states, model-specific windows, and validation. Journal revisions preserve context data across updates and replay. Structured sessions derive usage for the renderer. The native chat composer now displays a context ring with token counts, percentages, category rows, and estimated-state text. Composer interruption handling moves to a dedicated hook. Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🟡 Moderate · up to Context usage can be inaccurate, remain estimated after a turn, or lose persisted metadata during revision. These issues should be corrected before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Linked Issues checkExplanation [ ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 1e92e114-231a-46bc-873e-d44aeabd428c
📒 Files selected for processing (50)
src/main/claude/claude-agent-sdk-control-requests.tssrc/main/claude/claude-context-usage-observation.tssrc/main/claude/claude-context-usage.test.tssrc/main/claude/claude-context-usage.tssrc/main/claude/claude-structured-dispatch-test-support.tssrc/main/claude/claude-structured-options.test.tssrc/main/claude/claude-structured-session-acquisition-processless.test.tssrc/main/claude/claude-structured-session-adapter.tssrc/main/claude/claude-structured-session-publication.tssrc/main/claude/claude-structured-session-state.tssrc/main/claude/claude-structured-session-test-support.tssrc/main/native-chat/agent-session-wire/structured-agent-session-adapter-router.tssrc/main/native-chat/agent-session-wire/structured-agent-session-adapter.tssrc/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.tssrc/main/native-chat/agent-session-wire/structured-agent-session-side-channels.tssrc/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-subscribers.tssrc/main/native-chat/transcript-line-decoders-claude-usage.test.tssrc/main/native-chat/transcript-line-decoders-claude.tssrc/main/runtime/claude-structured-session-integration.test.tssrc/renderer/src/components/native-chat/NativeChatComposer.tsxsrc/renderer/src/components/native-chat/NativeChatComposerActions.tsxsrc/renderer/src/components/native-chat/NativeChatComposerField.tsxsrc/renderer/src/components/native-chat/NativeChatContextUsageRing.tsxsrc/renderer/src/components/native-chat/NativeChatResolvedView.tsxsrc/renderer/src/components/native-chat/NativeChatStructuredSession.tsxsrc/renderer/src/components/native-chat/native-chat-command-marker.tssrc/renderer/src/components/native-chat/native-chat-composer-types.tssrc/renderer/src/components/native-chat/native-chat-context-usage-answer.tssrc/renderer/src/components/native-chat/native-chat-context-usage-summary.test.tssrc/renderer/src/components/native-chat/native-chat-context-usage-summary.tssrc/renderer/src/components/native-chat/native-chat-pending.test.tssrc/renderer/src/components/native-chat/use-native-chat-composer-send-actions.tssrc/renderer/src/components/native-chat/use-native-chat-context-usage-summary.tssrc/renderer/src/components/native-chat/use-native-chat-derivations.tssrc/renderer/src/components/native-chat/use-native-chat-picker-command-dispatch.tssrc/renderer/src/components/native-chat/use-native-chat-pty-composer-send.tssrc/renderer/src/components/native-chat/use-structured-agent-session.tssrc/renderer/src/i18n/locales/en.jsonsrc/shared/agent-session-wire.tssrc/shared/claude-context-window.tssrc/shared/native-chat-context-usage.test.tssrc/shared/native-chat-context-usage.tssrc/shared/native-chat-local-commands.test.tssrc/shared/native-chat-local-commands.tssrc/shared/native-chat-slash-commands.test.tssrc/shared/native-chat-slash-commands.tssrc/shared/native-chat-types.tssrc/shared/structured-agent-session-reducer.test.tssrc/shared/structured-agent-session-reducer.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| onSlashCommand?.(text, localAnswer) | ||
| setHistory((previous) => pushHistory(previous, text)) | ||
| setDraft('') | ||
| setCaret(0) | ||
| setActiveSuggestion(0) | ||
| clearSkillOrigin() | ||
| setNotice(null) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '1,140p' src/renderer/src/components/native-chat/use-native-chat-picker-command-dispatch.ts
rg -n "useNativeChatPickerCommandDispatch|clearImageAttachments|imageAttachments" src/renderer/src/components/native-chatRepository: stablyai/orca
Length of output: 15332
🏁 Script executed:
#!/bin/bash
printf '%s\n' '--- NativeChatComposer dispatch and local-answer wiring ---'
sed -n '140,340p' src/renderer/src/components/native-chat/NativeChatComposer.tsx
printf '%s\n' '--- picker command dispatch tests ---'
sed -n '1,260p' src/renderer/src/components/native-chat/use-native-chat-picker-command-dispatch.test.tsx
printf '%s\n' '--- picker-related symbols and local answer definitions ---'
rg -n -C 5 "answerCommandLocally|/context|context|Picker|dispatchPtyPickerCommand|imageAttachments|clearImageAttachments" src/renderer/src/components/native-chat --glob '!*.snap'
printf '%s\n' '--- attachment send lifecycle ---'
sed -n '1,170p' src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts
sed -n '1,160p' src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.tsRepository: stablyai/orca
Length of output: 45542
🏁 Script executed:
#!/bin/bash
sed -n '175,335p' src/renderer/src/components/native-chat/NativeChatComposer.tsx
printf '%s\n' '--- local answer and picker references ---'
rg -n -C 8 "answerCommandLocally|dispatchPtyPickerCommand|/context|context" src/renderer/src/components/native-chat src/renderer/src --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- focused dispatch tests ---'
cat -n src/renderer/src/components/native-chat/use-native-chat-picker-command-dispatch.test.tsxRepository: stablyai/orca
Length of output: 45536
🏁 Script executed:
#!/bin/bash
printf '%s\n' '--- NativeChatComposer exact picker wiring ---'
sed -n '175,205p' src/renderer/src/components/native-chat/NativeChatComposer.tsx
sed -n '245,335p' src/renderer/src/components/native-chat/NativeChatComposer.tsx
printf '%s\n' '--- local answer implementation ---'
rg -n -C 12 "function useNativeChatDerivations|const answerCommandLocally|answerCommandLocally" src/renderer/src/components/native-chat/use-native-chat-derivations.ts src/renderer/src/components/native-chat/NativeChatResolvedView.tsx
printf '%s\n' '--- picker dispatchability definitions ---'
rg -n -C 12 "dispatchable|dispatchPickerCommand|completePickerItem" src/renderer/src/components/native-chat/use-native-chat-picker-state.ts src/renderer/src/components/native-chat/native-chat-composer-state.ts src/renderer/src/components/native-chat/use-native-chat-composer-keydown.tsRepository: stablyai/orca
Length of output: 28457
🏁 Script executed:
#!/bin/bash
printf '%s\n' '--- local command mapping ---'
cat -n shared/native-chat-local-commands.ts
printf '%s\n' '--- picker command catalog references ---'
rg -n -C 8 "name: ['\"]context['\"]|id: ['\"]command:context['\"]|context.*command|command.*context" shared src/renderer/src/components/native-chat --glob '*.ts' --glob '*.tsx'Repository: stablyai/orca
Length of output: 3662
🏁 Script executed:
#!/bin/bash
printf '%s\n' '--- locate local command implementation ---'
fd -i 'native-chat-local-commands' . --type f
printf '%s\n' '--- locate command catalog definitions ---'
fd -i 'native-chat-picker-items' . --type fRepository: stablyai/orca
Length of output: 399
🏁 Script executed:
#!/bin/bash
printf '%s\n' '--- local command implementation ---'
cat -n src/shared/native-chat-local-commands.ts
printf '%s\n' '--- picker catalog implementation ---'
cat -n src/renderer/src/components/native-chat/native-chat-picker-items.ts
printf '%s\n' '--- local command tests for context ---'
rg -n -C 8 "context|nativeChatLocalCommand" src/shared/native-chat-local-commands.test.tsRepository: stablyai/orca
Length of output: 14552
🏁 Script executed:
#!/bin/bash
printf '%s\n' '--- command catalog files and context references ---'
rg -l "SlashCommandSuggestion|agentCommands|/context|name: ['\"]context['\"]" src/shared src/renderer/src/components/native-chat --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- likely command catalog definitions ---'
rg -n -C 6 "name: ['\"]context['\"]|context.*SlashCommand|SlashCommandSuggestion|agentCommands" src/shared --glob '*.ts'Repository: stablyai/orca
Length of output: 30537
🏁 Script executed:
#!/bin/bash
cat -n src/renderer/src/components/native-chat/use-native-chat-composer-catalog.ts
printf '%s\n' '--- focused catalog tests ---'
rg -n -C 12 "context|commands|session|catalog" src/renderer/src/components/native-chat/use-native-chat-composer-catalog.test.tsxRepository: stablyai/orca
Length of output: 8783
Clear attachments after a locally handled PTY picker command.
The PTY picker offers /context and does not check image attachments before dispatch. The local-answer branch returns before clearImageAttachments(), so the image remains available for the next prompt.
Proposed fix
setActiveSuggestion(0)
clearSkillOrigin()
+ clearImageAttachments()
setNotice(null)
return📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| onSlashCommand?.(text, localAnswer) | |
| setHistory((previous) => pushHistory(previous, text)) | |
| setDraft('') | |
| setCaret(0) | |
| setActiveSuggestion(0) | |
| clearSkillOrigin() | |
| setNotice(null) | |
| onSlashCommand?.(text, localAnswer) | |
| setHistory((previous) => pushHistory(previous, text)) | |
| setDraft('') | |
| setCaret(0) | |
| setActiveSuggestion(0) | |
| clearSkillOrigin() | |
| clearImageAttachments() | |
| setNotice(null) |
| // marker, and the composer resets exactly as it would after a send. | ||
| const localAnswer = | ||
| classification === 'command' && imagePaths.length === 0 | ||
| ? (args.answerCommandLocally?.(text.trim()) ?? null) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Preserve leading whitespace during local-command recognition.
nativeChatLocalCommand intentionally treats " /context" as prose. Passing text.trim() converts that prose into /context, so the host consumes the message instead of sending it to Claude.
Proposed fix
- ? (args.answerCommandLocally?.(text.trim()) ?? null)
+ ? (args.answerCommandLocally?.(text) ?? null)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ? (args.answerCommandLocally?.(text.trim()) ?? null) | |
| ? (args.answerCommandLocally?.(text) ?? null) |
There was a problem hiding this comment.
ℹ️ No critical issues — two rough edges worth a look.
Reviewed changes
- Composer usage ring — a 16px SVG ring beside the send button that turns destructive past 90%, with a hover card listing per-category rows and an "estimated" note.
- Structured-session wire field — optional
contextUsageadded tosnapshot/batch/reset, threaded through the adapter router, client delivery, subscribers and the reducer. - Side-channel refactor —
commandsandcontextUsagenow sharestructured-agent-session-side-channels.ts, restating only changed fields on a batch; verified behavior-equivalent to the previous commands-only logic. - Claude host producer —
get_context_usageon turn settle plus the/contextstructured twin, stored by the new per-sessionClaudeContextUsageTracker. - Terminal estimate — the transcript decoder records
model/usageon assistant rows andderiveNativeChatContextUsagesums input + both cache counts against the model window. - Local
/contextanswer — Claude/contextdrafts are answered by the host in the terminal lane and recorded on the command marker.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — the structured-session scoping is clean and complete; one stale comment left behind by the removal.
Reviewed changes
- Ring scoped to structured sessions — the terminal-lane transcript estimate no longer feeds the composer ring;
useNativeChatContextUsageSummaryreturns null unless the structured transport carries a provider report. - Terminal hook split —
use-native-chat-derivations.tsbecameuse-native-chat-local-command-answer.ts, deriving the/contextestimate lazily in the callback instead of memoizing it for the ring. - Dead estimate path removed —
summarizeEstimatedContextUsageand thecontextUsageprop threaded throughNativeChatResolvedView→NativeChatComposerProps→NativeChatComposer→NativeChatComposerFieldare gone; no dangling references remain.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — the journal-row rewrite is clean and well-tested; two small cleanups in the new files.
Reviewed changes
- Context usage moved onto journal rows — the per-session
ClaudeContextUsageTracker, thecontextUsagewire field, andstructured-agent-session-side-channels.tsare gone; a settled turn's journal row now carries the provider's report, so the fact survives a restart with no session-side cache. - Turn-settle capture binding —
bindClaudeContextUsageCaptureasksget_context_usageon each provider-reported settle and annotates that turn's row;ClaudeOpenTurnretains the last four settled turns for a late answer and drops one too old. - Renderer projection —
selectStructuredAgentContextUsagereturns the newest turn report, or an estimate from an assistant response that landed after it, with the configured model supplying the[1m]window; the composer consumes it through the structured transport. - Assistant usage persisted — assistant journal rows and projected messages carry the API's token accounting and model id via the shared
claudeTokenUsagenormalizer, extending the renderer estimate the earlier commits introduced.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
8877e81 to
04498d5
Compare
There was a problem hiding this comment.
ℹ️ No critical issues — the incremental changes are clean; one observation on how the structured lane establishes its pre-report window.
Reviewed changes
- Window is host-establishable only —
claudeContextWindowTokensnow takes the host CLI's resolved session id plus the transcript model and returns 1M only when the two name the same model, so the standard 200k window is no longer guessed. resolvedModelplumbing — the Claude model probe,CatalogModel, PTY session-option discovery, and the commit-message model spec now carry the id the CLI resolves an alias to; the PTY options surface exposesresolvedSessionModel().- Host-answered
/contexthardening — the local answer takes the resolved session model, treats a/compactor/clearsent from the pane as invalidating older usage, and separates "not known yet" from "not available for this session";/contextmoved out of the shared per-agent catalog into a PTY-lane-only list. - Composer and picker wiring — typed and picked
/contextpass the resolved model into the answer, leave attachments armed, and render the answer in place of theRan …line.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
04498d5 to
d9f756a
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Context facts moved onto turn rows, with the window proven by the result. The per-session
ClaudeContextUsageTracker, thecontextUsagewire side-channel, and theresolvedModel/modelHint/claude-context-windowmachinery are gone.claude-context-facts.tswrites the window from the result's per-modelcontextWindowand the/contextbreakdown into the turn row'scontextUsage, so the ring is a projection of durable journal facts. - Recency decided by host clocks, not journal position.
selectStructuredAgentContextUsagetakes the newest report, else an estimate from a newer main-thread response, else null; a compaction or conversation reset hides the pre-reset size until a newer response or report restates it. - Capture hardened against overlap.
bindClaudeContextUsageCapturenumbers each request and drops any answer a newer request — or moved conversation activity — superseded, closing the earlier same-revision race. - Terminal-lane
/contextanswering removed. The local command catalog, the command-marker answer, andnative-chat-local-commands.tsare gone; the ring is structured-session only. - Composer stop/send tidied.
use-native-chat-composer-interrupt.tsnow holds the stop logic (behavior identical to the prior hook), the send predicate is inlined, and the deadmessage.model/NativeChatTokenUsagefields are removed.
ℹ️ PR description describes a superseded mechanism
The code is mergeable, but the body still describes the prior revision and would mislead a merger: it says "Stacked on #22294; merge that first (this branch includes its commit)" though #22294 is still open and this branch no longer contains it; it says the pre-report window comes from "the session's configured model" (it now comes from the result's per-model contextWindow); and its wire-impact list names message.model, which was removed. Worth re-writing the ELI5/Mechanism/Wire lines to the current design.
Technical details
# PR description is stale after the rewrite
## Affected sites
- PR body "Stacked on #22294" — `#22294` is OPEN and no longer a dependency; this branch's merge-base is `main` (`e16d9ca597`).
- PR body Mechanism → "Before any report exists, the window comes from the session's configured model" — `resolvedModel`/`modelHint` are gone; `claudeContextWindowFromResult` reads `message.modelUsage[*].contextWindow`, so the `[1m]` window is known without the configured model.
- PR body "Wire impact ... `message.model`" — `AgentJournalMessageItem` no longer carries `model`; only `message.usage` and `turn.contextUsage` were added.
## Required outcome
- The description matches the shipped mechanism, dependency state, and wire additions.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Request a context report for session-state turn… · claude-structured-journal-translation.ts:293
src/main/claude/claude-structured-journal-translation.ts:293
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRequest a context report for session-state turn endings.
When an idle session-state frame closes a turn after assistant usage, this branch skips the context report. The selector can then use a stale window and mark the usage as estimated, or return no context usage when no window exists.
Route the branch through
context.settle(event.message, end). The session-state message has no result window, butClaudeContextFacts.settlestill requests the report.Suggested fix
- turn.settle({ state: 'completed', completedAt: event.observedAt ?? Date.now() }) + context.settle(event.message, { + state: 'completed', + completedAt: event.observedAt ?? Date.now() + })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 7a0cb68d-2002-409f-ab15-acf6e91c12d9
📒 Files selected for processing (29)
src/main/claude/claude-context-facts.tssrc/main/claude/claude-context-usage.test.tssrc/main/claude/claude-context-usage.tssrc/main/claude/claude-open-turn.tssrc/main/claude/claude-structured-control-actions.test.tssrc/main/claude/claude-structured-dispatch.tssrc/main/claude/claude-structured-item-translation.tssrc/main/claude/claude-structured-journal-translation-context-usage.test.tssrc/main/claude/claude-structured-journal-translation.tssrc/main/claude/claude-structured-session-acquisition.tssrc/main/claude/claude-structured-session-journal-control.tssrc/main/claude/claude-turn-lifecycle-item.tssrc/main/claude/claude-turn-ownership.test.tssrc/renderer/src/components/native-chat/NativeChatComposer.tsxsrc/renderer/src/components/native-chat/NativeChatContextUsageRing.tsxsrc/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsxsrc/renderer/src/components/native-chat/NativeChatStructuredSession.tsxsrc/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsxsrc/renderer/src/components/native-chat/native-chat-composer-types.tssrc/renderer/src/components/native-chat/native-chat-context-usage-summary.test.tssrc/renderer/src/components/native-chat/native-chat-context-usage-summary.tssrc/renderer/src/components/native-chat/use-native-chat-composer-interrupt.tssrc/renderer/src/components/native-chat/use-native-chat-context-usage-summary.tssrc/renderer/src/i18n/locales/en.jsonsrc/shared/agent-session-context-usage.tssrc/shared/agent-session-journal-schemas.tssrc/shared/agent-session-journal-types.tssrc/shared/structured-agent-session-context-usage.test.tssrc/shared/structured-agent-session-context-usage.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/i18n/locales/en.json
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — the four new commits are clean, well-tested fixes; one stale doc line left behind by the new window selection.
Reviewed changes
- Window follows the main thread's model —
claudeContextWindowFromResultnow takes the turn'ssystem/initmodel (keyed exactly asmodelUsageis) and the newest main-thread response model. It matches the exact entry first, then by base id with the[1m]suffix stripped, so a session that switched between a 1M and a 200k variant, or whose subagent ran on a larger-window model, no longer reads the wrong window after every turn; the largest window is only the fallback when nothing names the model. - Tool-only responses move the ring — assistant usage moved off the (text-only) message rows onto the turn row's
contextUsage.response, deduped once per response, so a tool loop or any text-less response updates the live estimate;message.usage/message.modelwere removed from the journal body and schema. - Init model drives the window —
ClaudeContextFactskeeps{ initModel, responseModel }, resetting the response model on eachsystem/initso a model switch mid-session is picked up. - Composer control-order note corrected — the comment now says only the context ring separates the model picker from dictation.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues — the follow-up commit is a clean, tested fix. (Not approving because the earlier review's open inline thread is still unaddressed.)
Reviewed changes
- Context facts survive host-side turn settlement —
settledLifecyclenow copiescontextUsagefrom the running row into the settled row, so a stale running turn settled by the host (interruptedorunverifiable) no longer drops the response/reset facts the ring was already projecting. Since the settled body is rebuilt field by field, this is the correct place to carry the observed facts forward. - Regression test added —
runningTurnLifecycleRevisionsis asserted to keepcontextUsagefor both theinterruptedandunverifiableverdicts, which fails without the new branch.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Turn rows are revised against the journal, not in memory —
writeClaudeTurnRowperforms a queue-serialized read-modify-write (tryReviseResolvedItem) so each writer overrides only the fields it owns and keeps the rest;ClaudeOpenTurndrops its retained ended-turns map and late-annotation path, so the same rows are revised after a restart or reattach. - Context facts reshaped and schema-bounded —
contextUsageis now{ window, used }, withusedareport/estimate/unknownunion; a new shared zod schema admits it, andjournal-row-schema.tsdrops an unreadablecontextUsagefrom the row (item and lifecycle-batch bodies) instead of rejecting the whole row. - Selector orders by journal position — the newest row carrying
usedand the newest carryingwindoware picked independently bysequence, and an estimate is hidden until a window for the response's model exists (contextWindowServesModel). - Stale-turn settlement keeps fields it does not own —
settledLifecyclenow strips onlystate/completedAt/outcome/durationMs, so a hostinterrupted/unverifiableverdict no longer discardscontextUsageor unknown future fields. - Restart and revision coverage — new suites exercise the revision primitive (serialized reads, size reservation, skip-on-null), journal replay of every fact shape plus the drop-on-unreadable path, and two restart scenarios (compaction as first event, late context write after host settlement).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 68356e61-8c6f-4a37-9b6c-4b6b70acb304
📒 Files selected for processing (22)
src/main/claude/claude-context-facts.tssrc/main/claude/claude-context-usage-restart.test.tssrc/main/claude/claude-context-usage.test.tssrc/main/claude/claude-context-usage.tssrc/main/claude/claude-open-turn.tssrc/main/claude/claude-structured-control-actions.test.tssrc/main/claude/claude-structured-journal-translation-context-usage.test.tssrc/main/claude/claude-structured-journal-translation.tssrc/main/claude/claude-turn-ownership.test.tssrc/main/claude/claude-turn-row-revision.tssrc/main/native-chat/agent-session-journal/journal-row-context-usage.test.tssrc/main/native-chat/agent-session-journal/journal-row-schema.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink.tssrc/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.tssrc/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.tssrc/shared/agent-session-context-usage-schema.tssrc/shared/agent-session-context-usage.tssrc/shared/agent-session-journal-schemas.tssrc/shared/structured-agent-session-context-usage.test.tssrc/shared/structured-agent-session-context-usage.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/claude/claude-turn-ownership.test.ts
- src/shared/agent-session-journal-schemas.ts
- src/main/claude/claude-context-usage.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| const named = claudeText(response?.model) | ||
| const model = named && named.length <= MAX_CONTEXT_MODEL_ID_CHARS ? named : null | ||
| if (model) { | ||
| this.mainModel = { ...this.mainModel, responseModel: model } | ||
| } | ||
| const key = JSON.stringify([this.turn.id, usage, model]) | ||
| if (key === this.lastResponse) { | ||
| return | ||
| } | ||
| this.lastResponse = key | ||
| this.write({ | ||
| used: { kind: 'estimate', usage, ...(model ? { model } : {}), capturedAt: observedAt } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect assistant-frame contracts and fixtures for usage-bearing frames without a model.
rg -n -C5 --type=ts \
'type.*assistant|message\.model|model:\s*z\.|usage:|input_tokens' \
src/main/claude src/sharedRepository: stablyai/orca
Length of output: 42126
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- claude-context-facts.ts ---'
cat -n src/main/claude/claude-context-facts.ts | sed -n '1,150p'
printf '%s\n' '--- context usage implementation and selector references ---'
rg -n -C5 --type=ts \
'canonicalModel|responseModel|modelWindow|contextWindow|kind === .estimate.|kind: .estimate.|modelUsage|select.*usage|usedTokens' \
src/main/claude src/shared
printf '%s\n' '--- focused context usage tests ---'
cat -n src/shared/structured-agent-session-context-usage.test.ts | sed -n '1,260p'
cat -n src/main/claude/claude-context-facts.test.ts 2>/dev/null | sed -n '1,320p' || trueRepository: stablyai/orca
Length of output: 41996
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- claude-context-facts.ts ---'
cat -n src/main/claude/claude-context-facts.ts | sed -n '1,150p'
printf '%s\n' '--- selector and model-window references ---'
rg -n -C5 --type=ts 'canonicalModel|responseModel|modelWindow|contextWindow|kind === .estimate.|kind: .estimate.|modelUsage|select.*usage|usedTokens' src/main/claude src/shared
printf '%s\n' '--- focused context usage tests ---'
cat -n src/shared/structured-agent-session-context-usage.test.ts | sed -n '1,260p'
cat -n src/main/claude/claude-context-facts.test.ts 2>/dev/null | sed -n '1,320p' || trueRepository: stablyai/orca
Length of output: 41867
🏁 Script executed:
set -euo pipefail
cat -n src/main/claude/claude-context-facts.ts | sed -n '1,150p'
rg -n -C5 --type=ts 'canonicalModel|responseModel|modelWindow|contextWindow|kind === .estimate.|kind: .estimate.|modelUsage|usedTokens' src/main/claude src/shared
cat -n src/shared/structured-agent-session-context-usage.test.ts | sed -n '1,260p'
fd -i 'claude-context-facts' src/main/claudeRepository: stablyai/orca
Length of output: 42080
🏁 Script executed:
#!/bin/bash
set -euo pipefail
cat -n src/shared/structured-agent-session-context-usage.ts | sed -n '1,220p'
cat -n src/shared/structured-agent-session-context-usage.test.ts | sed -n '98,142p'Repository: stablyai/orca
Length of output: 5578
Record unknown usage when the response model is invalid.
observeResponse writes a model-less estimate when positive usage exists but response.model is absent or too long. selectStructuredAgentContextUsage skips model compatibility when fact.model is undefined, then uses the retained window. After a model switch, this can produce an incorrect percentage until a new window arrives.
Record kind: 'unknown' when no valid response model exists. Do not fall back to initModel, which may be stale.
| // Only a row grown by fields this build does not know gets here; the lifecycle still lands. | ||
| return write.lifecycle ? { identity, body: write.lifecycle } : null |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Do not replace an oversized revision with a lifecycle-only body.
If the existing row exceeds the fixed reservation, this fallback writes write.lifecycle alone. It deletes existing contextUsage and every unknown field that the merge logic is designed to preserve.
A future field larger than 8 KiB is sufficient to cause durable data loss during settlement. Reserve the supported row size, or reject the revision without replacing the existing body and surface the failure for retry.
| for (const body of bodies) { | ||
| if ( | ||
| isPlainObject(body) && | ||
| body.kind === 'turn' && | ||
| body.contextUsage !== undefined && | ||
| !isAdmissibleAgentSessionContextUsage(body.contextUsage) | ||
| ) { | ||
| delete body.contextUsage |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the status lifecycle type and its admission schema.
rg -n -C8 --type=ts \
'AgentJournalStatusItem|turnLifecycle|contextUsage' \
src/shared src/main/native-chat/agent-session-journalRepository: stablyai/orca
Length of output: 42342
🏁 Script executed:
sed -n '1,35p;175,212p' src/main/native-chat/agent-session-journal/journal-row-schema.ts
printf '\\n--- schema ---\\n'
sed -n '200,242p' src/shared/agent-session-journal-schemas.ts
printf '\\n--- reader ---\\n'
sed -n '15,27p' src/shared/agent-session-turn-record.tsRepository: stablyai/orca
Length of output: 5228
🏁 Script executed:
rg -n -C8 --type=ts 'export type AgentJournalTurnLifecycle|AgentJournalTurnLifecycle|isAdmissibleAgentJournalItemBody|safeParse|parseJournalRow' src/shared/agent-session-journal-types.ts src/shared/agent-session-journal-schemas.ts src/main/native-chat/agent-session-journal/journal-row-schema.tsRepository: stablyai/orca
Length of output: 15900
🏁 Script executed:
sed -n '195,220p;142,190p;220,305p' src/shared/agent-session-journal-types.ts src/main/native-chat/agent-session-journal/journal-row-schema.tsRepository: stablyai/orca
Length of output: 6735
🏁 Script executed:
sed -n '142,190p;220,305p' src/main/native-chat/agent-session-journal/journal-row-schema.tsRepository: stablyai/orca
Length of output: 5557
Sanitize contextUsage in legacy status lifecycles.
The status schema omits contextUsage, so this value does not cause row validation to fail. However, parseJournalRow returns the original upcast object after checking only the boolean result of safeParse. An invalid value can remain in status.turnLifecycle and reach context-usage readers.
Suggested fix
for (const body of bodies) {
+ const lifecycle =
+ isPlainObject(body) && body.kind === 'turn'
+ ? body
+ : isPlainObject(body) && body.kind === 'status' && isPlainObject(body.turnLifecycle)
+ ? body.turnLifecycle
+ : undefined
if (
- isPlainObject(body) &&
- body.kind === 'turn' &&
- body.contextUsage !== undefined &&
- !isAdmissibleAgentSessionContextUsage(body.contextUsage)
+ lifecycle &&
+ lifecycle.contextUsage !== undefined &&
+ !isAdmissibleAgentSessionContextUsage(lifecycle.contextUsage)
) {
- delete body.contextUsage
+ delete lifecycle.contextUsage
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for (const body of bodies) { | |
| if ( | |
| isPlainObject(body) && | |
| body.kind === 'turn' && | |
| body.contextUsage !== undefined && | |
| !isAdmissibleAgentSessionContextUsage(body.contextUsage) | |
| ) { | |
| delete body.contextUsage | |
| for (const body of bodies) { | |
| const lifecycle = | |
| isPlainObject(body) && body.kind === 'turn' | |
| ? body | |
| : isPlainObject(body) && body.kind === 'status' && isPlainObject(body.turnLifecycle) | |
| ? body.turnLifecycle | |
| : undefined | |
| if ( | |
| lifecycle && | |
| lifecycle.contextUsage !== undefined && | |
| !isAdmissibleAgentSessionContextUsage(lifecycle.contextUsage) | |
| ) { | |
| delete lifecycle.contextUsage |
| const TokenUsage = z.object({ | ||
| inputTokens: TokenCount, | ||
| cacheCreationInputTokens: TokenCount, | ||
| cacheReadInputTokens: TokenCount, | ||
| outputTokens: TokenCount | ||
| }) | ||
|
|
||
| const Used = z.discriminatedUnion('kind', [ | ||
| z.object({ | ||
| kind: z.literal('report'), | ||
| model: ModelId, | ||
| usedTokens: TokenCount, | ||
| windowTokens: WindowTokens, | ||
| percentage: z.number().finite(), | ||
| autoCompactAtTokens: TokenCount.optional(), | ||
| categories: z | ||
| .array( | ||
| z.object({ | ||
| name: z.string().min(1).max(MAX_CONTEXT_CATEGORY_NAME_CHARS), | ||
| tokens: TokenCount, | ||
| deferred: z.literal(true).optional() | ||
| }) | ||
| ) | ||
| .max(MAX_CONTEXT_CATEGORIES), | ||
| capturedAt: CapturedAt | ||
| }), | ||
| z.object({ | ||
| kind: z.literal('estimate'), | ||
| usage: TokenUsage, | ||
| model: ModelId.optional(), | ||
| capturedAt: CapturedAt | ||
| }), | ||
| z.object({ kind: z.literal('unknown'), capturedAt: CapturedAt }) | ||
| ]) | ||
|
|
||
| export const AgentSessionContextUsageSchema = z.object({ | ||
| window: z | ||
| .object({ | ||
| tokens: WindowTokens, | ||
| model: ModelId, | ||
| canonicalModel: ModelId.optional(), | ||
| capturedAt: CapturedAt | ||
| }) | ||
| .optional(), | ||
| used: Used.optional() | ||
| }) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Reject unknown fields instead of validating a stripped copy.
safeParse() can succeed after z.object() removes unknown properties from its parsed output. The predicate then retains the original value, including those properties.
A valid context fact with an arbitrarily large extra property therefore passes admission. This breaks the bounded-size invariant used by MAX_CONTEXT_PART_BYTES.
Use z.strictObject() at every object layer, or replace the input with the parsed result before persistence.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Named turn rows are revised by key instead of scanning —
writeClaudeTurnRowreads a{identity}target through the journal's newitemBodykeyed read, and only a{newest:true}context write still scans; the{turnId}target form is gone.StructuredAgentSessionRevisionJournalnow types exactly what a revision reads, and the resolved-append tests exercise the queue-serialized revision path. - A 1M window is told from a 200k one of the same model —
claudeMainThreadModelKeyreturns the turn init's exact model key ([1m]included) when the newest response still names that model, estimates record that key, andcontextWindowServesModelnow requires the full normalized id to agree rather than only the base id. New tests cover the switch between both windows. - A
usedkind this build cannot read yields no ring — the selector returnsnullfor an unrecognizedused.kind(a newer host's) instead of falling back to a stale report or estimate, with a test pinning it.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Plan-mode turns keep the ring — an
estimatenow records the response's own model id (responseModel, which drops[1m]) beside the init's exact key (model), and the reader — renamedcontextWindowServesEstimate— matches the exact key when one was recorded, falls back to base-id matching when only the response id is present. The old exact-only compare hid the ring for every--model opusplanturn, where the init names the resting model but the turn runs on Opus's 1M window. - Regression test drives the plan-mode shape —
turn-b/turn-c/turn-dassert the ring is hidden before the 1M result lands, shows 10% after it, keeps the reported 1M window through the next unnamed-model response, and hides again once the resting model's 200k window no longer serves the newest response. - Schema and dedupe updated —
responseModelis admitted as an optional bounded model id, and the per-response dedupe key now carries both the init key and the response id.
Verified locally: pnpm tc:node exits 0; structured selector (10), claude-context-usage (12), translation-context (16), and journal-row-context (3) suites all pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
The move to writer-owned window/model pairing drops the hold on a session re-acquisition, so a response after restart/reattach can be divided by a window from a different model and paint a wrong percentage. Details inline.
Reviewed changes
- Model identity removed from the ring's facts —
window.model/canonicalModelandestimate.model/responseModelare gone from the shared types and zod schema; the reader no longer verifies the window against the estimate's model, andcontextWindowServesEstimate/contextBaseModelIdleft the shared module. - Writer-owned model-change tracking —
ClaudeContextFactsnow keeps aservedModel(with aSTALEsentinel), writesused: unknownand requests a fresh report when amodel/permissionModeoption write changes the value, a restore cannot put the stored model back, or a mid-turn response names a different model; any window write (settle result or report) resets it to adopt the next response. - Option-write wiring and tests —
setClaudeStructuredOption/restoreClaudeStructuredSessionOptionscallmodelMayHaveChanged, and new suites cover the idle 1M/200k switch, theopusplantoggle, the mid-turn handoff, and the option/restore wiring.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| if (this.servedModel === STALE) { | ||
| return | ||
| } | ||
| // An approved plan hands the turn to another model mid-turn; only a response says so. | ||
| if (model && this.servedModel !== null && model !== this.servedModel) { | ||
| this.modelMayHaveChanged(observedAt) | ||
| return | ||
| } | ||
| this.servedModel = model ?? this.servedModel |
There was a problem hiding this comment.
A fresh translator starts with servedModel = null, so the first response after a session re-acquisition is adopted without any check against the window already persisted on the journal. If the model changed between two windows of one model (e.g. sonnet -> sonnet[1m]) and that switch's report never landed, this estimate is divided by the old window — I reproduced {usedTokens:160000, windowTokens:200000, percentage:80} where the true share over a 1M window is 16%. The reader-side exact-key check this commit removed used to hide exactly this case.
Technical details
# Restart/reattach loses the model-change hold
## Affected sites
- `src/main/claude/claude-context-facts.ts:40,103-111` — a new `ClaudeContextFacts` starts `servedModel = null`; the `this.servedModel !== null` guard is false, so any named model is adopted and an estimate is written against whatever window the journal holds.
- `src/shared/structured-agent-session-context-usage.ts:54-62` — the reader pairs the newest `used` with the newest `window` with no model check (the removed `contextWindowServesEstimate`).
- `src/main/claude/claude-structured-options.ts:235,244-246` — restore replays the stored model with `heldBeforeRestore = value`, so `input.value !== held` is false and `modelMayHaveChanged` is NOT re-issued on acquire; the explicit call only fires when the provider refuses the stored value.
- `src/main/claude/claude-context-usage.ts:206` — the report for the switch is dropped when conversation activity moved, and `getContextUsage` rejection (older CLI) is swallowed, either of which leaves the journal's old window in place.
## Trigger
1. Session on `sonnet`; a turn settles and writes `window: { tokens: 200_000 }`.
2. User picks `sonnet[1m]`; `modelMayHaveChanged` writes `used: unknown` and requests a report, but the report never lands (older CLI rejects `get_context_usage`, or the session is re-acquired before it answers).
3. Session is re-acquired: new translator `servedModel = null`, journal window still 200k; restore replays `model` with no `modelMayHaveChanged`.
4. First turn runs on the 1M model; the response names `claude-sonnet-5` (responses drop `[1m]`), is adopted, and the estimate is divided by the 200k window.
## Required outcome
- A percentage is never derived from a window measured on a different model than the response producing the estimate, including after re-acquisition.
## Suggested approach (optional)
- Keep a model fingerprint on the window (the response id plus the turn init's exact key) and let the reader verify it again — this restores the removed check, at the cost of re-adding a field the commit deliberately dropped.
- Or start a fresh writer with `servedModel = STALE` whenever the journal already holds a `window`, clearing it when a fresh window lands. Reports still render immediately; only an estimate from before the first new window is held.There was a problem hiding this comment.
✅ No new issues found in this commit. (Not approving while the earlier review's restart/reattach finding is still open.)
Reviewed changes
- A late context report now keeps its window —
recordReporttakes apart(report|window); the capture records only the window when conversation activity moved past the request, on the premise that activity changes what is used but not the window the CLI runs. An answer superseded by a newer request is still dropped entirely. - A report window now outranks the result's inference — a
windowReportedlatch is set whenever a report lands and reset by a turn init or amodelMayHaveChangedwrite;settleskips the result-derived window while it is set, so a turn result cannot undo a mid-turn switch between the 1M and 200k windows that a report already measured. - Coverage — the affected switch/result tests were rewritten for the new behavior, and the capture suite now pins the window-only path and confirms a superseded answer's window does not land.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- A turn's
system/initreleases the report latch — added a regression test (claude-context-model-switch.test.ts) pinning that a turn init clearswindowReported, so that turn's own result can restate the context window after an earlier turn's report set the latch; the case fails if the init does not clear it, and passes on head.
Not approving while the earlier review's restart/reattach finding on claude-context-facts.ts remains open — this commit does not touch it.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Context card switched from a hover card to a controlled
Popover—NativeChatContextUsageRingnow opens on hover, click, tap, or Enter; the trigger'sonMouseDown/onClickprevent default so the read-only ring never pulls focus out of the composer, andonOpenAutoFocus/onCloseAutoFocuskeep focus there on open and dismiss. - Mouse hover now waits 150 ms and is cancellable —
openAfterHoverschedules the open withHOVER_OPEN_DELAY_MS; any explicit open/close, an Escape, or unmount cancels the pending timer and removes the capturekeydownlistener, so a pointer crossing the ring toward dictation does not flash the card. - Duplicate provider category names get unique keys —
keyRowsdisambiguates repeats by index. - Coverage — a new happy-dom suite pins click-without-focus-loss, delayed hover open/close, immediate open on click during a pending hover, tap, Escape during/after a pending hover, unmount cleanup, and duplicate rows.
Not approving while the earlier review's restart/reattach finding on claude-context-facts.ts remains open — these commits do not touch it.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Context writes publish themselves —
writeClaudeTurnRownow takes a requiredClaudeTurnRowDelivery; a context fact queues its revision and its publication as one sink operation (tryReviseResolvedItemAndPublish, which appends then callsbound.publish()), so aget_context_usageanswer that arrives after the turn's last frame reaches live clients instead of waiting for the next frame. - Lifecycle writes keep their separate queued publish —
ClaudeOpenTurn.publishpassespublish: falseand retains the coalescedsink.publish({ coalescingKey: item.publishCoalescingKey }), preserving first-work evidence. - End-to-end coverage — a new integration case drives a settled turn whose report is the last event and asserts the client receives the breakdown; I confirmed it fails when
recordReport'spublishis reverted tofalse. - Million-token counts print capital
M—formatContextTokenCountcompares after rounding so 999,960 reads1Mrather than1000k; the aria-label and card tests are updated to match.
Verified locally: structured-agent-session-resolved-append (4), native-chat-context-usage-summary (2), NativeChatContextUsageRing (12), and claude-structured-session-integration (9) all pass on head.
Not approving while the earlier review's restart/reattach finding on claude-context-facts.ts:110-118 remains open — neither new commit touches it.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Context card stays open across the hover gap —
setOpenAfterHover(next)now schedules both the open (HOVER_OPEN_DELAY_MS = 150) and the close (HOVER_CLOSE_DELAY_MS = 100). A pointer that leaves the ring and crosses into the portaled card cancels the pending close through the wrapper'sonPointerEnter, while a pointer that leaves outright still closes after the delay. - Escape on an open card no longer stops the agent —
useNativeChatComposerKeyDownreturns early whenevent.key === 'Escape' && event.defaultPrevented. Radix'sDismissableLayerinstalls a document-capture Escape handler thatpreventDefault()s and dismisses the card, and that runs before React's container-bubble handler, so the first Escape closes the card and the second interrupts the turn. - Coverage — new cases pin the gap-crossing hover (would fail with an immediate close) and a real
Popover+ composer keydown sequence asserting the first Escape closes the card without callinginterrupt, the second calls it.
Not approving while the earlier review's restart/reattach finding on claude-context-facts.ts:110-118 remains open — neither new commit touches it.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Status: ready for review (head
|
0fa1c0a to
64d99cf
Compare
There was a problem hiding this comment.
✅ No new issues found in this commit. (Not approving while the earlier review's restart/reattach finding on
claude-context-facts.ts:110-118is still open — this commit does not touch it.)
Reviewed changes
Reviewed changes since commit 64d99cfa9b.
- Host answers with its whole-journal context facts —
AgentSessionOptionsResultgains an optionalcontextUsage: { current };readStructuredAgentSessionOptionsreturnssession.journal.contextUsage()when the adapter's newrecordsContextUsagereports the session writes facts (Claude: any live session; the router forwards to the live owner). - The selector is split so the host reuses it —
latestStructuredAgentContextFactsis now exported and runs over any{ sequence, body }iterable (max sequence per part, order-independent);selectStructuredAgentContextUsage(items, wholeJournal?)merges with the loaded rows winning each part they carry and the host answer filling a part they lack. - Client wiring — a new
useStructuredAgentSessionContextUsagememo feedsselectStructuredAgentContextUsage(journalItems, support?.current); the value is threaded fromuseStructuredAgentSessionOptionsthroughuseStructuredAgentSessioninto the composer. - A dropped live turn-row revision re-reads options — the reducer counts
unloadedTurnRevisionsper live batch whose turn-row revision the loaded window could not take, and the options hook re-readsagentSession.optionswhen that counter moves — gated on the host having answered withcontextUsage, so an older host or a session that writes no facts asks nothing. - Coverage — a host-side suite drives a real translator, a tail page that starts after the turn row, the no-fact session, and a late revision the window drops; a shared-suite pins the whole-journal merge and the order-independence of
latestStructuredAgentContextFacts; the reducer retention test pins the counter; and a happy-dom hook suite pins fill/prefer/no-refresh/refetch. Focused run on head:structured-agent-session-context-usage+structured-agent-session-item-retention+use-structured-agent-session-context-usage= 27 tests across 3 files pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found in this commit either. (Still not approving while the earlier review's restart/reattach finding on
claude-context-facts.ts:110-118remains open — this commit does not touch it.)
Reviewed changes
Reviewed changes since commit 71be88a003.
- Context-refresh reads are coalesced — the options read now runs through the shared
createCoalescedPollRunner(../right-sidebar/coalesced-poll-runner) with the defaultminIntervalMs0: the main effect owns the runner and fires it once, and a new[contextRefresh]effect fires it again when the missed-revision counter moves, so a burst of revisions keeps one read in flight and at most one queued rather than one read per revision (they share the session's host queue with sends and interrupts). - A trimmed turn row now counts as an unloaded revision —
outsideWindowcombines the live itemsliveItemsWithinWindowdropped with the head itemstrimRetainedItemsremoved, andlostTurnRowbumpsunloadedTurnRevisionsfor either, so the whole-journal answer is re-read when retention pushes the active turn row out of a long window.run()on a disposed runner is a safe no-op, and the counter is still preserved across ordinary batches. - Coverage — an integration case walks a turn past a 200-item window and asserts, at each step across the trim, that the ring's reading equals the whole-journal reading; a hook case pins one-in-flight/one-behind over five revisions; the retention suite pins the trim count and that a later non-turn trim does not re-count. Focused run on head:
use-structured-agent-session-context-usage(5) +claude-context-usage-unloaded-turn(4) +structured-agent-session-item-retention(12) = 21 tests pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed changes since commit 4b60542f7f.
- The ring is sized from the configured model before any window is measured — the new
claudeContextWindowHintmaps a[1m]name to 1M and every other name to 200k (default/empty to null);ClaudeContextFacts.modelWrittenstores it andmodelMayHaveChangedclears it. - The first response now paints a percentage instead of showing no ring — when a model or permission-mode write left the window stale,
observeResponseuses the written model's window rather than bailing out; with no hint it still holds the estimate. - A measured window still wins — the fallback is resolved inside
writeClaudeTurnRow(withFallbackWindow), which drops the hint when any journal row already carries awindow; the scan runs once per writer becausejournalMayLackWindowflips false on the first window write, and the byte reservation already covers the added window. - Option wiring and coverage — a live or restore-replayed model write calls
modelWrittenonly after the child applied it; refused or skipped writes never do.claude-context-window-hint.test.tsis new, plus option/restore sizing cases and two restart cases; the three focused suites pass locally (38 tests).
Not approving while the earlier review's restart/reattach finding on claude-context-facts.ts remains open — the fallback deliberately keeps the persisted window over the name hint, so this commit does not change that behavior.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The composer is at its line budget; lifting the stop action out makes room for the context usage ring without changing what Stop does.
…kes it A context report answers after the turn's last frame, so a revision that waited for the next frame's publish reached live clients only on the next turn. Context writes now queue their revision and its publication as one operation.
A lowercase m read as minutes on the context card.
…s into it The card closed the moment a mouse left the ring, so the pointer could not cross the gap into the card. Leaving now waits a beat, and entering the card cancels the close.
…the agent The card keeps focus in the composer, so the Escape that closed it also reached the composer and interrupted the running turn. The composer now skips an Escape an open layer already handled.
…the turn it belongs to The ring read context facts only from the rows the chat had loaded, so a reopened chat whose recent page started after the last turn row, or a live turn longer than the retained window, showed no ring until the next turn. The host now derives the newest context facts from its whole journal with the same selector the chat uses, and returns them on agentSession.options for sessions that write them. The chat prefers each fact its loaded rows carry and takes the host answer for a fact they lack. When a live batch revises a turn row older than the loaded window, the chat asks for options again so that answer stays current.
…rn row is trimmed Each turn-row revision the loaded window missed started its own options read. Those reads share the session's host queue with sends and interrupts, and each asks the CLI for its settings, so a burst could pile reads in front of a user action and discard every answer before it landed. The chat now keeps one options read in flight and at most one behind it. A live turn longer than the retained window also lost its turn row to the trim without asking for a fresh host answer, so the ring fell back to the answer read at turn start until the next response. Trimming a turn row now asks again, like a dropped revision does.
…d from the session's model A new session has no measured window until its first result, so the ring stayed hidden for the whole first turn. The host now keeps the window the applied model's name implies (1M for a [1m] name, unknown for default, 200k otherwise) and writes it beside an estimate when the journal holds no window, or after a model write, until the result or the CLI's report replaces it.
A bare model name does not fix the window: first-party runs today's opus, sonnet and fable models natively at 1M while a gateway or cloud provider runs them at 200k, and opusplan and haiku run another model in plan mode. Sizing their first response at 200k read the ring about five times too full, so only a [1m] name implies a window now; any other name waits for the result.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed changes since commit d2e7a31ea2.
- The implied window now comes only from a
[1m]model name —claudeContextWindowHintreturns 1M only when the configured name ends in[1m]andnullfor every other name, rather than guessing 200k for a bare name. A bare name runs at 1M first-party but at 200k through a gateway or some cloud providers, so the old guess could read several times too full; those sessions now show no ring until a result or report measures the window. This aligns the code with the PR body's stated behavior. - Tests tightened — the option-write sizing case now expects
nullfor a baresonnet(previously200_000), and the restart case was strengthened to prove a persisted 400k window beats a 1Mfable[1m]name hint instead of comparing two 1M windows.
Verified locally: claude-context-window-hint (27), claude-context-usage (14), claude-context-usage-restart (6), claude-context-model-switch (9), and claude-structured-options-context-window (8) all pass.
Not approving while the earlier review's restart/reattach finding on claude-context-facts.ts remains open — this commit does not touch it, and withFallbackWindow still deliberately keeps the persisted window over the name hint.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
e1bc62f to
9df679b
Compare
…any turn A model picked in a chat with no turn yet asks the CLI for its context report, but with no turn row the report's write lands nowhere. Recording it still marked the journal as holding a window, so the first response wrote none and the ring stayed hidden until the turn's result. The report's window now serves as the fallback a response writes while the journal holds no window, and recording a report no longer assumes its write landed.
…red integration suite The context-report delivery case pushed the suite past the 800-line limit, failing repo-wide lint. The fake child now lives in its own fixture.
There was a problem hiding this comment.
✅ No new issues found in these two commits. (Not approving while the earlier review's restart/reattach finding remains open — neither commit touches it.)
Reviewed changes
Reviewed changes since the prior pullfrog review (e1bc62faee, review 5298474789).
- First response is sized from a pre-turn report —
recordReportno longer marks the journal as holding a window (journalMayLackWindow = falsewas wrong when the report's{newest:true}write lands nowhere because the chat has no turn row yet). It instead stores the report's window aswindowHint, so the first response after a model pick carries it as the fallback window;withFallbackWindowstill drops that fallback when any journal row already holds a window. - Ablation-verified coverage — the new
it.eachcase inclaude-context-window-hint.test.tsdrives a pick ofsonnet[1m](1M) and baresonnet(the report's 200k) before any turn and asserts the ring's window and share. I confirmed both rows fail withring() === nullwhen the line is reverted tojournalMayLackWindow = false, and pass on head. Focused run:claude-context-window-hint(29) +claude-structured-session-integration(12) pass. - Fake Claude child extracted to a fixture — test-only: the inline
fakeClaude/FakeClaudeConnectionmove out ofclaude-structured-session-integration.test.tsintoclaude-structured-fake-connection-test-fixture.ts, parameterized byproviderSession, because the context-report delivery case pushed the suite past the 800-line lint limit. The one call site becomesfakeClaude(PROVIDER_SESSION); behavior is unchanged and no inline symbol is left dangling.oxlinton the four touched files: 0 warnings, 0 errors.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Status update: ready for review (head
|
Keeps both hooks where main added the conversation rail outline beside the context usage hook, and stubs the outline read in the context usage hook's test mock now that the session hook calls it.
#22301 added two src/shared modules this route reaches; its own CI never ran this suite, so the merged branch read 4224 against the 4222 pin. Measured on the merge.
…#22392 (#22702) * test(mobile): repin the RPC recording corpus to main after #22392 #22392 pinned baseline to a branch commit (2c2b84c) that the squash left unreachable, so the recording-pin ancestry job failed on main and every PR. Repin to main's tip 80e0bee and re-record the whole corpus: all 787 goldens change only their baseline header, so no recorded behaviour moved. * test(mobile): re-measure the session route closure on main after #22392 Main reads 4219, not 4217: #22301 added two src/shared modules to the route without touching mobile/, so main was already two over when #22392 measured its -2 against a branch base that lacked them.
…ocumented The census comment records #22301's two shared modules and the resulting 4219 -> 4221, but the constant was left at 4219. Measured on a clean origin/main worktree: this branch adds no module to that closure.
* feat(mobile): confirm host identity after pairing * refactor(mobile): unify host descriptor state * chore(i18n): translate the last-known host descriptor label The remote-host row's "Last known" label shipped in English only. Every other locale now carries it, worded as each catalog already words "last known". * fix(mobile): make the pairing naming step safe to abandon and show the machine live Pairing: - An unreadable status.get reply no longer strands the pairing race: the descriptor read ran inside the race's success handler and threw, so the candidate was never counted and a direct-only pairing sat on "Connecting..." until the timeout. The race now reads the status through a reader that returns null instead of throwing. - A pending pairing is now a small state machine: a save in flight owns the outcome (Cancel, back, or unmount no longer clear the journal under it), a failed save stays pending and the naming screen shows the error with Save still available, and Cancel never rejects. - When the desktop refuses relay provisioning, the journal is cleared before the naming step instead of at save, so an app kill on that screen no longer blocks every later scan with "recovery pending". - A pairing that resolves after the screen went away is cancelled rather than left with its journal. - The screens keep their root ref callbacks stable (the latest pending pairing is read from a ref) instead of re-creating them per pairing. - The label field's placeholder shows the name that an empty label saves. - "Is this an existing host" is derived from the id identity resolution hands back, so host-store and its tests go back to main's shape. Machine descriptor: - Mobile keeps the host-reported machine name and OS in memory only, filled by the status reads that already happen, and labels it "Last known" from the row's own connection state. This drops the per-host AsyncStorage copy, its web sibling and web-overrides entry, and the removal cleanup. It also fixes a latch: freshness used to stay true for the whole process once a host had answered. - Desktop reads the descriptor through lastVerifiedRuntimeStatus and marks it "Last known" using the same reachability verdict as the row's dot. - Drops the unused hostname/previousPlatform resolver inputs and moves the "OS · machine" formatting into the shared resolver. Also restores main's page-only Reconnect gate in the host header (#22326), undoes the no-op toStoredHostProfile reformat, and re-measures the web session route at 4222 modules (one fewer: the dropped web persistence file). * test(mobile): re-record RPC goldens for the deferred pairing save Repins baseline to the pairing fix commit and re-records every golden. Against main, 781 goldens move only in the header (baseline everywhere, adapterSha256 for the pairing adapter family). Six pairing goldens move in the body, and only in effect order: the pairing now resolves (closing its candidate sockets) before the naming step saves the host, and a refused relay provision clears its journal before the save rather than after. The set of effects and every outcome match main. This also removes the unhandled-rejection effects and the failed result-absent/result-null cells that the previous recording captured from the pairing race's throwing status read. * fix(mobile): keep the machine name out of the host header title while the label loads The host screen starts with an empty saved label and loads it asynchronously. With a descriptor already in memory, the resolver fell back to the machine name as the title for that window, so opening "Windows-Low Spec" briefly titled the header with the Mac's name. Read the descriptor only once the label is known. * test(mobile): build the pending-pairing status through its schema so the test typechecks The mobile tests typecheck ratchet rejected a partial status literal: the reply type keeps every optional field as a required key. Parsing the literal through the status schema yields that shape without a type assertion. * test(mobile-web): re-pin the session route closure after merging main #22301 added two src/shared modules this route reaches; its own CI never ran this suite, so the merged branch read 4224 against the 4222 pin. Measured on the merge. * feat(mobile): name each host by what its desktop reports Pairing saves the host immediately again and names it after the machine name the desktop publishes; every connection refreshes that name and OS, so a rename on the desktop reaches the phone. A name typed on the phone's Edit screen is kept as a phone-local override that wins; clearing it returns to the desktop's name. - Stored host profiles gain optional personalName, lastKnownMachineName and lastKnownHostPlatform; `name` stays the resolved value older builds read. Legacy records classify a generated "Host N" as desktop-named and any other name as a phone override. - The connection layer runs one retrying status probe per connected host and records the descriptor; the capability probe becomes a projection of it. - Rows and the header always show the OS, add the machine name under a phone override that hides it, and mark it "Last known" while the host is offline. - Removes the deferred-save naming screen and the one-shot home status fetch. - Name rules move to host-name-identity.ts and the host-list mutation queue to host-list-mutation-queue.ts; an unchanged mutation no longer rewrites storage. * test(mobile): restore the RPC recordings to main's Pairing saves the host back to back again and the recording adapter is main's, so every recording matches main byte for byte; the earlier deferred-save re-record and its baseline repin no longer apply. * fix(mobile): keep stored host name identity across snapshot saves and on the web page A connection re-saves its host profile snapshot on relay credential rotation or relay re-resolution. The re-pair merge let that snapshot's name identity win, so a phone rename cleared or changed since connect came back, and a newer desktop machine name rolled back. The stored record now keeps the name identity on every save; the save supplies the rest. The web page receives only the app's resolved host name, with no identity fields, so the docked host header treated a phone rename as "no override" and titled the host with the live machine name. The display hook now reads such a source the way storage reads a legacy record: a non-generated name is the user's label. * fix(mobile): hand the web page the host's stored name identity The page received only the app's resolved host name, so it had to guess whether that name was the phone's override or the desktop's name. It guessed "override" for any non-generated name, which froze a desktop-adopted name as the title after the desktop was renamed, and left an offline page header without the last-known OS and machine name. The shell now puts the stored personalName and last-known descriptor on the init host as optional fields. The page reads them exactly as the app does; a page handed its host by an older shell still falls back to classifying the name, and an older page ignores the fields. * fix(mobile): drop an unreadable host name field, not the whole host The stored host record and the page's init host checked the platform against a closed list and required non-empty names. A value this build does not know, such as a platform added in a later build, failed the whole record: the host list dropped the paired host and the next write persisted the list without it, and the page refused its init message. Those three optional fields are now salvaged, so an unreadable value drops only that field. Also states the one exception to the stored name rule (an OS reported without a machine name keeps the adopted name), and brings four mobile test files in line with the branch: the edit screen now saves `personalName`, and host opens now start a descriptor status probe. * refactor(mobile): name the shared host name fields for their role * fix(mobile): drop the "Last known" prefix from the host machine line The OS and machine name line under a host's name reads the same whether or not the host is connected; the connection status already says when it is offline, and a prefix that users could read as applying to the name added nothing. Removes the resolver's liveness input and the desktop row's translation key.
stablyai#22301 added src/shared/agent-session-context-usage.ts and src/shared/agent-session-context-usage-schema.ts to the route. It touched nothing under mobile/, so mains pin stayed at 4219 while the closure measures 4221.

ELI5
In a Claude chat (the structured chat view), a small ring now sits in the composer's action bar and fills up as the conversation uses the model's context window. Hover it, click it, tap it, or tab to it, and a card shows how many tokens are used, how big the window is, and what is taking the space: messages, system prompt, tools, memory files, skills, and so on. The numbers are saved with the conversation, so they are still there after Orca restarts.
What Changed
Before. The structured Claude chat gave no sign of how full the context window was. In the terminal view, Claude's statusline can show
ctx 27%; in the chat there was nothing.After. In a structured Claude chat:
Context, used and window tokens (e.g.26.7k/1M), a bar, and one row per category from Claude's own context report, sorted by size./compactthe ring clears, then shows the new, smaller size. After a model or plan-mode change it clears briefly, then shows the new model's window.The terminal-backed chat and mobile are unchanged, and Codex sessions show no ring yet.
One composer behavior changes beyond the ring. When Escape closes an open popup (the context card, a hover popover, a tooltip), that press no longer also stops the running turn; the next Escape does. Before, closing the card with Escape would also have stopped the agent. This matches how the settings, artifacts, and mobile pages already treat Escape.
Mechanism. Everything the ring shows is written to the session's journal, on the turn's own row, and the ring is a pure projection of those rows. Nothing is kept beside the journal or in the renderer.
get_context_usage, 5s timeout). A newer request drops the whole earlier answer. If the conversation has moved on, only the answer's used count is dropped, and its window is kept.[1m]name, the host records a 1M window beside the first estimate, so the ring shows from the first response. Any other name waits for the result: the same bare name runs at 1M on first-party Claude but at 200k through a gateway or some cloud providers, so a guess could read five times too full.contextUsagefield on theagentSession.optionsresult, the same way the Codex goal is delivered. The renderer uses facts from its loaded rows when it has them, which are newer, and the host's answer otherwise. When a turn's row falls outside the loaded rows during a live turn, the renderer re-reads options: at most one read runs at a time, with one more queued.Why
/compactright after a restart didn't clear the ring.Deviations from the usual design for this feature, noted for reviewers:
CLAUDE_CODE_USE_GATEWAY) whose gateway returns 501 for token counting. There, each count becomes a one-token model request, 7–35 per Claude start or model switch and never per turn.Scope note: 66 files. About 60% of the added lines are tests. The rest is the feature plus the supporting journal, sink, and options changes above, which were needed to keep the ring correct across restart, reopen, crash, and compaction.
Linked Issue
Relates to #11225 (the visibility half; configurable soft limits are a follow-up).
Visual Proof
Structured Claude chat in an isolated dev build of this branch, driven over CDP with a real Claude CLI (2.1.280). Before, the composer had no context indicator; the first shot is this build before any turn, which looks the same.
/compact(smaller size)Testing
Unit and integration tests cover:
Ablation. Each behavior test was confirmed to fail with its fix removed.
Local run.
pnpm tc, pluspnpm testoversrc/main/claude,src/shared,src/renderer/src/components/native-chat,src/main/native-chat,src/main/runtime, andsrc/main/codex(23,783 passing). The only failures are 5 real-binary timeout tests inclaude-structured-real-cli/claude-tui-resume-real-binary, which fail the same way onmain.Claude CLI 2.1.280, measured directly. Which model name each of these carries:
Checked in normal mode, with
[1m]models, in plan mode withopusplan, and after a model change.Manual (macOS). An isolated dev instance was driven over CDP with real Claude turns across three passes. I measured:
/compact.The first pass found that reports reached the journal but not the open chat; that is fixed, and passes 2 and 3 were clean.
Not exercised. Linux and Windows (the change has no platform-specific code), and a real touch device (touch is covered by synthetic-event tests).
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)