Skip to content

feat(native-chat): show context window usage in the composer - #22301

Merged
brennanb2025 merged 31 commits into
mainfrom
brennanb2025/chat-context-usage-ring
Sep 24, 2026
Merged

brennanb2025 merged 31 commits into
mainfrom
brennanb2025/chat-context-usage-ring

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3033 $\color{#cf222e}{\Huge{\mathbf{−}}}$​117 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2916
Prod 44 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1901 $\color{#cf222e}{\Huge{\mathbf{−}}}$​117 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1784

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:

  • A ring beside the model and effort pickers shows the used percentage. It turns destructive above 90%.
  • The card opens on hover (after a short delay, so passing over the ring doesn't flash it), on click or tap, and from the keyboard. It never takes focus away from the message box. It shows 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.
  • During a turn the ring moves with every main-thread response, including tool-only ones, and the card says it is an estimate. About a second after the turn settles, it shows Claude's report again.
  • After /compact the 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.
  • It comes back straight away after an Orca restart, a reattach, or a crash mid-turn.

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.

  • Window. When a result settles a turn, its per-model usage gives the window of the model the main thread ran on. This is chosen by a single rule in the host. It is not the largest entry, because that total is cumulative for the session and includes subagents.
  • Report. After each result, after a compaction, and after a successful model or permission-mode change, the host asks Claude for its context report over the control channel (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.
  • Estimate. Each main-thread response records its own usage (input + cache read + cache write) on the turn row. Subagent responses are ignored.
  • First turn. A new session has no measured window until its first result. If the session's model is a [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.
  • Model switches. They are detected where they happen, in the host. The ring reader never compares model names.
  • Turn-row writes. Every write to a turn row reads that row's current contents from the journal at the moment it runs, then overrides only the fields that writer owns. That covers the translator and also the host's own settlement of a turn it found still running after a crash. Each context write is published to open chats in the same step, so the card updates live. Supporting changes:
    • The sink gains a revise-from-journal operation (with a publishing variant).
    • The journal store gains a keyed item read, so a known row is found without scanning.
    • On replay, a context fact this build cannot read is dropped and its row is kept, rather than ending the replay at that row.
  • Reopened chats and very long turns. A chat loads only a recent page of rows and keeps at most 1,024, and a turn's row stays where the turn began. So the ring can't rely on the loaded rows alone. The host works out the latest context facts from the whole journal and returns them as an optional contextUsage field on the agentSession.options result, 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.
  • Wire. Optional fields only: on the existing turn item body, and on the options result. Older desktop and mobile clients ignore them, and an older host simply doesn't send the options field.

Why

  • Durable facts, not a side cache. The numbers live on journal rows, so they survive restart and reattach and reach reconnecting clients with nothing to reconcile. An earlier side-channel version lost them on restart.
  • The CLI's own numbers. The window comes from what Claude reports, not from guessing by model name. The window for a given name depends on account, provider, and environment, which the host cannot know.
  • Read at write time. Deriving each write's target and body from the journal removed a class of bugs found in review. When a writer held its own copy of a turn row, it could drop fields it didn't own: rings reset after a crash, and /compact right after a restart didn't clear the ring.

Deviations from the usual design for this feature, noted for reviewers:

  • Storage. Context facts are revisions of the turn row rather than separately appended events. A new journal item kind would need a schema version bump, which would put every Claude session into read-only mode on a downgraded host. An optional field on the turn row is simply ignored by older builds.
  • Window per model. The window is taken for the model the main thread ran on, not the largest one seen, which misstates it after a model switch or when a subagent runs on a larger model.
  • Refresh triggers. Beyond the usual refresh on a model change, the window is also refreshed after a plan-mode change and when the responding model changes mid-turn (an approved plan moving from one model to another). Without this, the ring would read several times too high or too low for the rest of that turn.
  • Cost. The per-turn report is what gives the per-category breakdown. Claude counts its fixed categories with Anthropic's token-counting endpoint, which is free and rate-limited separately from messages. Measured through a logging proxy (CLI 2.1.280, real user settings):
    • The first report in a Claude process makes 7–35 count requests (about 1 second).
    • Every later report makes 0–1, including after new turns, because the counts are cached and the used total comes from response usage.
    • A model switch recounts once.
    • The one billed case is an enterprise gateway login (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.
    • Other count failures fall back to a local estimate.

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.

Before any turn (no ring) After a turn: the CLI report, opened by hover
01-before-first-turn.png 03-hover-card.png
Mid-turn: live estimate Turn settled: report returns (~1s)
04-estimate-mid-turn.png 05-after-second-turn.png
After an Orca restart, before any new turn After /compact (smaller size)
07-after-restart-card.png 08-after-compact.png
Escape closes the card; the turn keeps running Pointer moved into the card; it stays open
10-escape-turn-continues.png 11-pointer-in-card.png

Testing

  • Unit and integration tests cover:

    • the window rule (plan mode, both 1M and 200k entries present, subagents on a larger model);
    • estimates through tool-only responses;
    • model and plan-mode switches, idle and mid-turn, including a send straight after a switch;
    • late, superseded, failed, and rejected reports;
    • live delivery of a report that arrives with no later frame, through the real host and subscriber path;
    • compaction mid-turn, and as the first action after a restart;
    • a crash mid-turn;
    • replay dropping an unreadable context fact;
    • the validator admitting exactly what the writer writes;
    • the selector;
    • the card's hover, click, touch, keyboard, and Escape behavior, including Escape not interrupting.
  • Ablation. Each behavior test was confirmed to fail with its fix removed.

  • Local run. pnpm tc, plus pnpm test over src/main/claude, src/shared, src/renderer/src/components/native-chat, src/main/native-chat, src/main/runtime, and src/main/codex (23,783 passing). The only failures are 5 real-binary timeout tests in claude-structured-real-cli / claude-tui-resume-real-binary, which fail the same way on main.

  • Claude CLI 2.1.280, measured directly. Which model name each of these carries:

    • the start-of-turn message;
    • responses;
    • per-model usage;
    • the context report.

    Checked in normal mode, with [1m] models, in plan mode with opusplan, and after a model change.

  • Manual (macOS). An isolated dev instance was driven over CDP with real Claude turns across three passes. I measured:

    • how long the report took to arrive after each settle (about 1.5s);
    • the estimate during tool calls;
    • hover and click open with composer focus kept;
    • Escape with the card open (the card closes and the turn completes normally);
    • Escape with the card closed (still stops the turn, in about 100ms);
    • the pointer crossing into the card;
    • keyboard Enter and Escape;
    • an Orca restart, and /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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and 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

  • Security. Only category names and token counts are stored. Memory-file paths and MCP tool lists from the report are dropped.
  • SSH / remote. The report and the facts are produced on the execution host, and travel as optional fields on existing journal rows.
  • Mobile / paired clients. Older clients ignore the new fields. A context kind that a newer host might write shows no ring rather than breaking the composer.
  • Performance. There is one turn-row revision per main-thread response, and no journal scan for a known row. The ring selector is memoized and runs once per journal change.

Checklist

  • This PR is small and focused (focused on one feature; not small, see the scope note under Why)
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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 61531

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)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning [ #22292 ] requires /context in the Chat slash menu and a visible Chat response for both terminal-backed and structured Claude sessions. The PR adds context usage reporting, persistence, and a struc… Add /context to the Chat slash-command menu. Render its result in both terminal-backed and structured Claude chat sessions. Add automated tests for menu availability and visible results in both lanes.
Docstring Coverage ⚠️ Warning Docstring coverage is 47.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 100 functions across 79 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The changes remain connected to [#22292]. Control-channel requests, context tracking, journal persistence, restart handling, structured-session projection, composer rendering, localization, and relate…
Title check ✅ Passed The title clearly and concisely describes the main change: showing context-window usage in the native chat composer.
Description check ✅ Passed The description is detailed and covers the user impact, implementation, rationale, linked issue, visual proof, testing, compatibility, and checklist. The AI Disclosure and Review sections contain no a…
Full details: Linked Issues check

Explanation

[ #22292 ] requires /context in the Chat slash menu and a visible Chat response for both terminal-backed and structured Claude sessions. The PR adds context usage reporting, persistence, and a structured-session composer ring. It does not add a /context command or transcript response path. The PR scope states that terminal-backed chat remains unchanged, so the terminal-backed requirement remains unmet.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1e92e114-231a-46bc-873e-d44aeabd428c

📥 Commits

Reviewing files that changed from the base of the PR and between a8786c0 and f9e10f2.

📒 Files selected for processing (50)
  • src/main/claude/claude-agent-sdk-control-requests.ts
  • src/main/claude/claude-context-usage-observation.ts
  • src/main/claude/claude-context-usage.test.ts
  • src/main/claude/claude-context-usage.ts
  • src/main/claude/claude-structured-dispatch-test-support.ts
  • src/main/claude/claude-structured-options.test.ts
  • src/main/claude/claude-structured-session-acquisition-processless.test.ts
  • src/main/claude/claude-structured-session-adapter.ts
  • src/main/claude/claude-structured-session-publication.ts
  • src/main/claude/claude-structured-session-state.ts
  • src/main/claude/claude-structured-session-test-support.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-adapter-router.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-client-delivery.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-side-channels.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.ts
  • src/main/native-chat/transcript-line-decoders-claude-usage.test.ts
  • src/main/native-chat/transcript-line-decoders-claude.ts
  • src/main/runtime/claude-structured-session-integration.test.ts
  • src/renderer/src/components/native-chat/NativeChatComposer.tsx
  • src/renderer/src/components/native-chat/NativeChatComposerActions.tsx
  • src/renderer/src/components/native-chat/NativeChatComposerField.tsx
  • src/renderer/src/components/native-chat/NativeChatContextUsageRing.tsx
  • src/renderer/src/components/native-chat/NativeChatResolvedView.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
  • src/renderer/src/components/native-chat/native-chat-command-marker.ts
  • src/renderer/src/components/native-chat/native-chat-composer-types.ts
  • src/renderer/src/components/native-chat/native-chat-context-usage-answer.ts
  • src/renderer/src/components/native-chat/native-chat-context-usage-summary.test.ts
  • src/renderer/src/components/native-chat/native-chat-context-usage-summary.ts
  • src/renderer/src/components/native-chat/native-chat-pending.test.ts
  • src/renderer/src/components/native-chat/use-native-chat-composer-send-actions.ts
  • src/renderer/src/components/native-chat/use-native-chat-context-usage-summary.ts
  • src/renderer/src/components/native-chat/use-native-chat-derivations.ts
  • src/renderer/src/components/native-chat/use-native-chat-picker-command-dispatch.ts
  • src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts
  • src/renderer/src/components/native-chat/use-structured-agent-session.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/agent-session-wire.ts
  • src/shared/claude-context-window.ts
  • src/shared/native-chat-context-usage.test.ts
  • src/shared/native-chat-context-usage.ts
  • src/shared/native-chat-local-commands.test.ts
  • src/shared/native-chat-local-commands.ts
  • src/shared/native-chat-slash-commands.test.ts
  • src/shared/native-chat-slash-commands.ts
  • src/shared/native-chat-types.ts
  • src/shared/structured-agent-session-reducer.test.ts
  • src/shared/structured-agent-session-reducer.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment on lines +69 to +75
onSlashCommand?.(text, localAnswer)
setHistory((previous) => pushHistory(previous, text))
setDraft('')
setCaret(0)
setActiveSuggestion(0)
clearSkillOrigin()
setNotice(null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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-chat

Repository: 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.ts

Repository: 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.tsx

Repository: 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.ts

Repository: 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 f

Repository: 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.ts

Repository: 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.tsx

Repository: 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.

Suggested change
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
? (args.answerCommandLocally?.(text.trim()) ?? null)
? (args.answerCommandLocally?.(text) ?? null)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 contextUsage added to snapshot/batch/reset, threaded through the adapter router, client delivery, subscribers and the reducer.
  • Side-channel refactor — commands and contextUsage now share structured-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_usage on turn settle plus the /context structured twin, stored by the new per-session ClaudeContextUsageTracker.
  • Terminal estimate — the transcript decoder records model/usage on assistant rows and deriveNativeChatContextUsage sums input + both cache counts against the model window.
  • Local /context answer — Claude /context drafts are answered by the host in the terminal lane and recorded on the command marker.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/claude/claude-context-usage.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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; useNativeChatContextUsageSummary returns null unless the structured transport carries a provider report.
  • Terminal hook split — use-native-chat-derivations.ts became use-native-chat-local-command-answer.ts, deriving the /context estimate lazily in the callback instead of memoizing it for the ring.
  • Dead estimate path removed — summarizeEstimatedContextUsage and the contextUsage prop threaded through NativeChatResolvedView → NativeChatComposerProps → NativeChatComposer → NativeChatComposerField are gone; no dangling references remain.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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, the contextUsage wire field, and structured-agent-session-side-channels.ts are 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 — bindClaudeContextUsageCapture asks get_context_usage on each provider-reported settle and annotates that turn's row; ClaudeOpenTurn retains the last four settled turns for a late answer and drops one too old.
  • Renderer projection — selectStructuredAgentContextUsage returns 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 claudeTokenUsage normalizer, extending the renderer estimate the earlier commits introduced.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/shared/claude-token-usage.ts Resolved
Comment thread src/main/claude/claude-context-usage.ts Resolved
@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-context-usage-ring branch 2 times, most recently from 8877e81 to 04498d5 Compare September 22, 2026 22:55

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — claudeContextWindowTokens now 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.
  • resolvedModel plumbing — 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 exposes resolvedSessionModel().
  • Host-answered /context hardening — the local answer takes the resolved session model, treats a /compact or /clear sent from the pane as invalidating older usage, and separates "not known yet" from "not available for this session"; /context moved out of the shared per-agent catalog into a PTY-lane-only list.
  • Composer and picker wiring — typed and picked /context pass the resolved model into the answer, leave attachments armed, and render the answer in place of the Ran … line.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-context-usage-ring branch from 04498d5 to d9f756a Compare September 22, 2026 23:41

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Context facts moved onto turn rows, with the window proven by the result. The per-session ClaudeContextUsageTracker, the contextUsage wire side-channel, and the resolvedModel/modelHint/claude-context-window machinery are gone. claude-context-facts.ts writes the window from the result's per-model contextWindow and the /context breakdown into the turn row's contextUsage, so the ring is a projection of durable journal facts.
  • Recency decided by host clocks, not journal position. selectStructuredAgentContextUsage takes 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. bindClaudeContextUsageCapture numbers each request and drops any answer a newer request — or moved conversation activity — superseded, closing the earlier same-revision race.
  • Terminal-lane /context answering removed. The local command catalog, the command-marker answer, and native-chat-local-commands.ts are gone; the ring is structured-session only.
  • Composer stop/send tidied. use-native-chat-composer-interrupt.ts now holds the stop logic (behavior identical to the prior hook), the send predicate is inlined, and the dead message.model / NativeChatTokenUsage fields 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 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 win

Request 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, but ClaudeContextFacts.settle still 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9ecbc4b and d9f756a.

📒 Files selected for processing (29)
  • src/main/claude/claude-context-facts.ts
  • src/main/claude/claude-context-usage.test.ts
  • src/main/claude/claude-context-usage.ts
  • src/main/claude/claude-open-turn.ts
  • src/main/claude/claude-structured-control-actions.test.ts
  • src/main/claude/claude-structured-dispatch.ts
  • src/main/claude/claude-structured-item-translation.ts
  • src/main/claude/claude-structured-journal-translation-context-usage.test.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-structured-session-acquisition.ts
  • src/main/claude/claude-structured-session-journal-control.ts
  • src/main/claude/claude-turn-lifecycle-item.ts
  • src/main/claude/claude-turn-ownership.test.ts
  • src/renderer/src/components/native-chat/NativeChatComposer.tsx
  • src/renderer/src/components/native-chat/NativeChatContextUsageRing.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
  • src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx
  • src/renderer/src/components/native-chat/native-chat-composer-types.ts
  • src/renderer/src/components/native-chat/native-chat-context-usage-summary.test.ts
  • src/renderer/src/components/native-chat/native-chat-context-usage-summary.ts
  • src/renderer/src/components/native-chat/use-native-chat-composer-interrupt.ts
  • src/renderer/src/components/native-chat/use-native-chat-context-usage-summary.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/agent-session-context-usage.ts
  • src/shared/agent-session-journal-schemas.ts
  • src/shared/agent-session-journal-types.ts
  • src/shared/structured-agent-session-context-usage.test.ts
  • src/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.

Comment thread src/main/claude/claude-context-facts.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — claudeContextWindowFromResult now takes the turn's system/init model (keyed exactly as modelUsage is) 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.model were removed from the journal body and schema.
  • Init model drives the window — ClaudeContextFacts keeps { initModel, responseModel }, resetting the response model on each system/init so 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 — settledLifecycle now copies contextUsage from the running row into the settled row, so a stale running turn settled by the host (interrupted or unverifiable) 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 — runningTurnLifecycleRevisions is asserted to keep contextUsage for both the interrupted and unverifiable verdicts, which fails without the new branch.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Turn rows are revised against the journal, not in memory — writeClaudeTurnRow performs a queue-serialized read-modify-write (tryReviseResolvedItem) so each writer overrides only the fields it owns and keeps the rest; ClaudeOpenTurn drops 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 — contextUsage is now { window, used }, with used a report / estimate / unknown union; a new shared zod schema admits it, and journal-row-schema.ts drops an unreadable contextUsage from the row (item and lifecycle-batch bodies) instead of rejecting the whole row.
  • Selector orders by journal position — the newest row carrying used and the newest carrying window are picked independently by sequence, and an estimate is hidden until a window for the response's model exists (contextWindowServesModel).
  • Stale-turn settlement keeps fields it does not own — settledLifecycle now strips only state / completedAt / outcome / durationMs, so a host interrupted / unverifiable verdict no longer discards contextUsage or 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).

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 68356e61-8c6f-4a37-9b6c-4b6b70acb304

📥 Commits

Reviewing files that changed from the base of the PR and between 1287531 and 6153106.

📒 Files selected for processing (22)
  • src/main/claude/claude-context-facts.ts
  • src/main/claude/claude-context-usage-restart.test.ts
  • src/main/claude/claude-context-usage.test.ts
  • src/main/claude/claude-context-usage.ts
  • src/main/claude/claude-open-turn.ts
  • src/main/claude/claude-structured-control-actions.test.ts
  • src/main/claude/claude-structured-journal-translation-context-usage.test.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-turn-ownership.test.ts
  • src/main/claude/claude-turn-row-revision.ts
  • src/main/native-chat/agent-session-journal/journal-row-context-usage.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-schema.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-resolved-append.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.ts
  • src/shared/agent-session-context-usage-schema.ts
  • src/shared/agent-session-context-usage.ts
  • src/shared/agent-session-journal-schemas.ts
  • src/shared/structured-agent-session-context-usage.test.ts
  • src/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.

Comment thread src/main/claude/claude-context-facts.ts Outdated
Comment on lines +92 to +103
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 }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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/shared

Repository: 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' || true

Repository: 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' || true

Repository: 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/claude

Repository: 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.

Comment on lines +173 to +174
// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +197 to +204
for (const body of bodies) {
if (
isPlainObject(body) &&
body.kind === 'turn' &&
body.contextUsage !== undefined &&
!isAdmissibleAgentSessionContextUsage(body.contextUsage)
) {
delete body.contextUsage

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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-journal

Repository: 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.ts

Repository: 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.ts

Repository: 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.ts

Repository: stablyai/orca

Length of output: 6735


🏁 Script executed:

sed -n '142,190p;220,305p' src/main/native-chat/agent-session-journal/journal-row-schema.ts

Repository: 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.

Suggested change
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

Comment on lines +17 to +62
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()
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Named turn rows are revised by key instead of scanning — writeClaudeTurnRow reads a {identity} target through the journal's new itemBody keyed read, and only a {newest:true} context write still scans; the {turnId} target form is gone. StructuredAgentSessionRevisionJournal now 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 — claudeMainThreadModelKey returns the turn init's exact model key ([1m] included) when the newest response still names that model, estimates record that key, and contextWindowServesModel now requires the full normalized id to agree rather than only the base id. New tests cover the switch between both windows.
  • A used kind this build cannot read yields no ring — the selector returns null for an unrecognized used.kind (a newer host's) instead of falling back to a stale report or estimate, with a test pinning it.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Plan-mode turns keep the ring — an estimate now records the response's own model id (responseModel, which drops [1m]) beside the init's exact key (model), and the reader — renamed contextWindowServesEstimate — 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 opusplan turn, 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-d assert 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 — responseModel is 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/canonicalModel and estimate.model/responseModel are gone from the shared types and zod schema; the reader no longer verifies the window against the estimate's model, and contextWindowServesEstimate/contextBaseModelId left the shared module.
  • Writer-owned model-change tracking — ClaudeContextFacts now keeps a servedModel (with a STALE sentinel), writes used: unknown and requests a fresh report when a model/permissionMode option 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/restoreClaudeStructuredSessionOptions call modelMayHaveChanged, and new suites cover the idle 1M/200k switch, the opusplan toggle, the mid-turn handoff, and the option/restore wiring.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +103 to +111
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — recordReport takes a part (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 windowReported latch is set whenever a report lands and reset by a turn init or a modelMayHaveChanged write; settle skips 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • A turn's system/init releases the report latch — added a regression test (claude-context-model-switch.test.ts) pinning that a turn init clears windowReported, 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Context card switched from a hover card to a controlled Popover — NativeChatContextUsageRing now opens on hover, click, tap, or Enter; the trigger's onMouseDown/onClick prevent default so the read-only ring never pulls focus out of the composer, and onOpenAutoFocus/onCloseAutoFocus keep focus there on open and dismiss.
  • Mouse hover now waits 150 ms and is cancellable — openAfterHover schedules the open with HOVER_OPEN_DELAY_MS; any explicit open/close, an Escape, or unmount cancels the pending timer and removes the capture keydown listener, so a pointer crossing the ring toward dictation does not flash the card.
  • Duplicate provider category names get unique keys — keyRows disambiguates 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Context writes publish themselves — writeClaudeTurnRow now takes a required ClaudeTurnRowDelivery; a context fact queues its revision and its publication as one sink operation (tryReviseResolvedItemAndPublish, which appends then calls bound.publish()), so a get_context_usage answer 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.publish passes publish: false and retains the coalesced sink.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's publish is reverted to false.
  • Million-token counts print capital M — formatContextTokenCount compares after rounding so 999,960 reads 1M rather than 1000k; 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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's onPointerEnter, while a pointer that leaves outright still closes after the delay.
  • Escape on an open card no longer stops the agent — useNativeChatComposerKeyDown returns early when event.key === 'Escape' && event.defaultPrevented. Radix's DismissableLayer installs a document-capture Escape handler that preventDefault()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 calling interrupt, 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: ready for review (head 0fa1c0a2c6)

CI: green. All 8 test shards, typecheck, static analysis, verify, cross-version wire compatibility, and the macOS and Windows package builds pass. The branch merges cleanly with current main.

Base: no longer stacked on #22294. This branch sits on main and doesn't touch the terminal-backed chat files that #22294 is reworking.

What happened in review

The PR went through repeated review passes until two came back clean, plus two architecture reviews and three passes of real-app QA. The main changes from the first version:

  • The window comes from Claude, not the model name. It is taken from each result's per-model usage, for the model the main thread ran on, or from Claude's context report. The largest entry was wrong after a model switch or when a subagent ran on a larger model.
  • Model and plan-mode switches are detected in the host. The ring never compares model names. The ring clears briefly and the new window arrives with a fresh report.
  • Every turn-row write reads the row from the journal when it runs. It then changes only its own fields. This fixed a class of bugs: rings reset after a crash, /compact right after a restart didn't clear the ring, and host settlement dropped context facts.
  • Reports now reach the open chat when they're written. Real-app QA found they were saved but only appeared on the next event or after a restart.
  • The card opens on click, tap, and keyboard, not just hover. It keeps focus in the message box, and Escape closes it without stopping the running turn.

Verified in the running app (macOS, Claude CLI 2.1.280)

  • The report arrives about 1.5s after each turn settles.
  • The estimate moves during tool calls.
  • The ring survives an Orca restart and is right after /compact.
  • Escape with the card open lets the turn finish.
  • Escape with the card closed still stops the turn.

Screenshots are in the description.

Decisions for a reviewer

  1. A tooltip takes the first Escape. When Escape closes any open popup in the composer area, that press no longer also stops the turn, and the next Escape does. This is what makes closing the context card safe, and it matches the settings, artifacts, and mobile pages. It also applies when a tooltip happens to be showing, for example when the mouse rests on the dictation button. Hovering the Stop button itself is unaffected. The alternative is to exempt only the card, but then Escape on the message-list hover popover and the dashboard drawers would go back to closing and stopping in one press.
  2. Cost. Each settled turn asks Claude for its context report, which counts some categories with Claude's token-counting endpoint. The first report on a model takes about a second; later ones return in milliseconds. That is what produces the per-category breakdown.
  3. Size. 54 files, about two thirds of the added lines are tests. The shared journal and sink changes (revise-from-journal, a keyed item read, dropping an unreadable context fact on replay) were needed to keep the ring correct across restart, crash, and compaction.

Not covered

  • The terminal-backed chat, mobile UI, and Codex show no ring (out of scope).
  • Linux and Windows were not exercised by hand (there is no platform-specific code).
  • A real touch device was not tested; touch is covered by synthetic-event tests.
  • A new session shows no ring until its first turn settles, because no window is known yet.
  • Unrelated to this PR, and the same on main: the model picker can read "Fable" during a turn when the session is set to opus[1m], because the CLI resolves that alias to a Fable model on some accounts.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-context-usage-ring branch from 0fa1c0a to 64d99cf Compare September 23, 2026 18:56

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found in this commit. (Not approving while the earlier review's restart/reattach finding on claude-context-facts.ts:110-118 is still open — this commit does not touch it.)

Reviewed changes

Reviewed changes since commit 64d99cfa9b.

  • Host answers with its whole-journal context facts — AgentSessionOptionsResult gains an optional contextUsage: { current }; readStructuredAgentSessionOptions returns session.journal.contextUsage() when the adapter's new recordsContextUsage reports the session writes facts (Claude: any live session; the router forwards to the live owner).
  • The selector is split so the host reuses it — latestStructuredAgentContextFacts is 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 useStructuredAgentSessionContextUsage memo feeds selectStructuredAgentContextUsage(journalItems, support?.current); the value is threaded from useStructuredAgentSessionOptions through useStructuredAgentSession into the composer.
  • A dropped live turn-row revision re-reads options — the reducer counts unloadedTurnRevisions per live batch whose turn-row revision the loaded window could not take, and the options hook re-reads agentSession.options when that counter moves — gated on the host having answered with contextUsage, 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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-118 remains 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 default minIntervalMs 0: 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 — outsideWindow combines the live items liveItemsWithinWindow dropped with the head items trimRetainedItems removed, and lostTurnRow bumps unloadedTurnRevisions for 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 claudeContextWindowHint maps a [1m] name to 1M and every other name to 200k (default/empty to null); ClaudeContextFacts.modelWritten stores it and modelMayHaveChanged clears it.
  • The first response now paints a percentage instead of showing no ring — when a model or permission-mode write left the window stale, observeResponse uses 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 a window; the scan runs once per writer because journalMayLackWindow flips 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 modelWritten only after the child applied it; refused or skipped writes never do. claude-context-window-hint.test.ts is 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Reviewed changes since commit d2e7a31ea2.

  • The implied window now comes only from a [1m] model name — claudeContextWindowHint returns 1M only when the configured name ends in [1m] and null for 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 null for a bare sonnet (previously 200_000), and the restart case was strengthened to prove a persisted 400k window beats a 1M fable[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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-context-usage-ring branch from e1bc62f to 9df679b Compare September 24, 2026 01:15
…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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — recordReport no longer marks the journal as holding a window (journalMayLackWindow = false was 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 as windowHint, so the first response after a model pick carries it as the fallback window; withFallbackWindow still drops that fallback when any journal row already holds a window.
  • Ablation-verified coverage — the new it.each case in claude-context-window-hint.test.ts drives a pick of sonnet[1m] (1M) and bare sonnet (the report's 200k) before any turn and asserts the ring's window and share. I confirmed both rows fail with ring() === null when the line is reverted to journalMayLackWindow = 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 / FakeClaudeConnection move out of claude-structured-session-integration.test.ts into claude-structured-fake-connection-test-fixture.ts, parameterized by providerSession, because the context-report delivery case pushed the suite past the 800-line lint limit. The one call site becomes fakeClaude(PROVIDER_SESSION); behavior is unchanged and no inline symbol is left dangling. oxlint on the four touched files: 0 warnings, 0 errors.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status update: ready for review (head b4e945c168)

This replaces the earlier status comment for 0fa1c0a2c6.

CI: green. All 8 test shards, typecheck, static analysis, verify, cross-version wire compatibility, the RPC recording pin, and the macOS and Windows package builds pass. The branch merges cleanly.
Base: rebased onto current main. The only conflict was en.json, where main added fileLinks and this PR adds contextUsage; both are kept. The PR's own changes are line-for-line identical to before the rebase.

What changed since the last status

  • Reopened chats and very long turns. A chat keeps only a recent page of rows, and a turn's row stays where the turn began. The host now also returns the newest context facts on agentSession.options, so a reopened chat shows the ring before any new turn.
    • The chat prefers the facts it has loaded and uses the host's answer for anything missing.
    • Refresh reads are capped: at most one in flight and one queued.
    • Both sides are optional, so an older host omits the field and an older client ignores it.
  • First turn. If the session's model name ends in [1m], the ring shows from the first response. If you pick a model before your first message, the first response uses the window Claude measures for it.
    • A bare model name is never guessed. The same 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.
  • Fixes found in review:
    • A model picked before the first message kept the ring hidden for the whole first turn. Fixed.
    • One integration test file had grown past the line limit. The fake Claude connection moved into its own fixture unchanged, with no lint rule disabled.

Cost of the per-turn breakdown (measured)

The category breakdown comes from Claude's context report. I measured the report through a logging proxy, using Claude CLI 2.1.280 with real user settings:

  • First report: the first report in a Claude process makes 7–35 requests to Anthropic's token-counting endpoint, taking about a second.
  • Later reports: every later report makes 0–1, including after new turns, because the counts are cached and the used total comes from the usage that responses already carry.
  • Model switch: a switch recounts once.
  • Price: token counting is free, and its rate limits are separate from message limits.
  • One billed case: an enterprise gateway login whose gateway returns 501 for token counting. There, each count becomes a one-token model request: 7–35 per Claude start or model switch, never per turn.
  • Other failures: any other failed count falls back to a local estimate.
  • Rejected option: Claude's cheaper summary report makes no requests, but its category numbers were far off (tools about 2x, messages near zero), so it was not used.

Decisions for a reviewer

  1. Escape and tooltips. When Escape closes an open popup in the composer area (the context card, a hover popover, a tooltip), that press no longer also stops the running turn; the next Escape does. This matches the settings, artifacts, and mobile pages. It also applies when a tooltip happens to be showing.
  2. Size. About 60% of the added lines are tests. The shared journal, sink, and options changes keep the ring correct across restart, reopen, crash, and compaction.

Known edge cases

  • Model switch inside the first message. If the model is switched inside the first message with a typed /model, the first reply can use the old model's window until that turn's result corrects it.
  • Restored model. If a new session's model comes from a restored setting, a [1m] name on an account with 1M blocked shows a 1M window until the first result.

Not covered

  • Other surfaces. The terminal-backed chat, mobile UI, and Codex show no ring (out of scope).
  • Platforms. Linux and Windows weren't exercised by hand; there's no platform-specific code.
  • Touch. Touch is covered by synthetic-event tests only.
  • Unrelated to this PR. Same as on main: the model picker can read "Fable" mid-turn for opus[1m].

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.
@brennanb2025
brennanb2025 merged commit 25d7c21 into main Sep 24, 2026
32 checks passed
brennanb2025 added a commit that referenced this pull request Sep 24, 2026
#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.
brennanb2025 added a commit that referenced this pull request Sep 24, 2026
Jinwoo-H added a commit that referenced this pull request Sep 24, 2026
…#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.
nwparker added a commit that referenced this pull request Sep 24, 2026
…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.
brennanb2025 added a commit that referenced this pull request Sep 25, 2026
* 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.
JasonJarvan added a commit to JasonJarvan/orca that referenced this pull request Sep 25, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant