Skip to content

fix(runtime): persist contextRemaining on the stored TokenUsageMessage so TUI ctx survives transcript rebuilds #4019

Closed

Description

@me2seeks

Problem

The TUI status line permanently degrades to ctx ?/<window> (#3371 fallback) even for providers that report per-step usage, because the stored TokenUsageMessage never carries contextRemaining.

In packages/runtime/src/ai-sdk-backend.ts the turn-end usage write has two asymmetric paths:

The TUI rebuilds usage from stored messages in replaceTranscriptWithStoredMessages (packages/cli/src/pi-transcript.ts), so after any transcript reload (abort refresh, session resume, reconnect) contextRemaining is washed back to undefined and the status line falls back to ctx ?/<window> — even though the runtime event ledger (runtime_events.actions.tokenUsage) proves the value was computed (e.g. contextRemaining: 230068 for a 262144-window model).

cacheHit/cacheMiss survive the same rebuild (they are persisted), which is why cache NN% stays correct while ctx reverts to ?.

Expected

The persisted TokenUsageMessage carries contextRemaining (same conditional-spread value as the live event), so the ctx segment survives transcript rebuilds.

Scope

  • Move contextRemainingForUsage computation above the stored tu literal and add the field to it (schema already allows it: packages/core/src/usage-record-schema.ts, packages/core/src/session.ts; replay/read-model paths already preserve it: runtime-event-backfill.ts, runtime-event-read-model.ts).
  • Extend the ai-sdk-backend usage tests to assert the stored message includes contextRemaining.

Refs: #1067 (origin), #3371 (degrade-to-? fallback), #1422 (preserve token usage fields across replay).

Activity

  1. me2seeks commented on Aug 27, 2026

    @me2seeks
    ContributorAuthor

    I'm working on this.

  2. me2seeks commented on Aug 27, 2026

    @me2seeks
    ContributorAuthor

    Field report consistent with this issue (posted via AI agent on behalf of the reporter):

    If this provider does report per-step usage, this session is a real-world repro of the wash-out described here: after a transcript rebuild the durable TokenUsageMessage lacks contextRemaining, the status line falls back to ?/<window>, and the user loses exactly the visibility that would have warned them before the budget verdict. (If the provider does not report per-step usage, the ? is the expected #3371 degrade and orthogonal to this fix — the reporter believes usage is reported.)

  3. added a commit that references this issue on Aug 28, 2026
    c848fcb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions