|
| 1 | +# Plan: Restore Live Token Usage Feature (PR #4709) |
| 2 | + |
| 3 | +**Date:** 2025-12-09 |
| 4 | +**Related PR:** https://github.com/sst/opencode/pull/4709 |
| 5 | +**Status:** IMPLEMENTED - Feature restored 2025-12-10 |
| 6 | + |
| 7 | +## Overview |
| 8 | + |
| 9 | +This plan documents the restoration of the "Live Token Usage During Streaming" feature that was originally added in PR #4709. The feature provides: |
| 10 | + |
| 11 | +- Real-time token tracking while streaming responses |
| 12 | +- `IN/OUT` format display for input/output tokens |
| 13 | +- Reasoning token display for "thinking" models |
| 14 | +- Toggle tokens command in TUI |
| 15 | + |
| 16 | +## Current State Analysis |
| 17 | + |
| 18 | +### What's Working |
| 19 | + |
| 20 | +| Component | File | Status | |
| 21 | +| ------------------------------ | --------------------------------------------- | -------------------------- | |
| 22 | +| Token utility functions | `packages/opencode/src/util/token.ts` | **EXISTS** | |
| 23 | +| Message schema fields | `packages/opencode/src/session/message-v2.ts` | **EXISTS** | |
| 24 | +| Token calculation in prompt.ts | `packages/opencode/src/session/prompt.ts` | **EXISTS** | |
| 25 | +| Subtask completion fix | `packages/opencode/src/session/prompt.ts` | **EXISTS** (bug was fixed) | |
| 26 | + |
| 27 | +### What's Missing |
| 28 | + |
| 29 | +| Component | File | Status | |
| 30 | +| ------------------------ | ------------------------------------------------------------ | ----------- | |
| 31 | +| Streaming token updates | `packages/opencode/src/session/processor.ts` | **MISSING** | |
| 32 | +| `showTokens` state | `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` | **MISSING** | |
| 33 | +| `contextLimit` memo | `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` | **MISSING** | |
| 34 | +| IN/OUT token display | `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` | **MISSING** | |
| 35 | +| Reasoning token display | `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` | **MISSING** | |
| 36 | +| "Toggle tokens" command | `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` | **MISSING** | |
| 37 | +| User message token count | `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` | **MISSING** | |
| 38 | + |
| 39 | +### Backend Token Utility (Exists) |
| 40 | + |
| 41 | +```typescript |
| 42 | +// packages/opencode/src/util/token.ts |
| 43 | +Token.estimate(input: string) // Character-based estimation |
| 44 | +Token.toCharCount(tokenEstimate: number) // Convert tokens to chars |
| 45 | +Token.toTokenEstimate(charCount: number) // Convert chars to tokens |
| 46 | +Token.calculateToolResultTokens(parts) // Estimate tool result size |
| 47 | +``` |
| 48 | + |
| 49 | +### Message Schema Fields (Exist) |
| 50 | + |
| 51 | +```typescript |
| 52 | +// UserMessage |
| 53 | +sentEstimate: z.number().optional() |
| 54 | +contextEstimate: z.number().optional() |
| 55 | + |
| 56 | +// AssistantMessage |
| 57 | +outputEstimate: z.number().optional() |
| 58 | +reasoningEstimate: z.number().optional() |
| 59 | +contextEstimate: z.number().optional() |
| 60 | +sentEstimate: z.number().optional() |
| 61 | +``` |
| 62 | + |
| 63 | +## Technical Approach |
| 64 | + |
| 65 | +### Token Estimation Logic |
| 66 | + |
| 67 | +- Simple estimation based on character count using `CHARS_PER_TOKEN` constant |
| 68 | +- `calculateToolResultTokens` estimates size of tool inputs, outputs, and errors |
| 69 | +- Estimates prefixed with `~` to indicate they are approximate |
| 70 | + |
| 71 | +### Display Format |
| 72 | + |
| 73 | +- `IN X↓` - Input/context tokens (sent to model) |
| 74 | +- `OUT Y↑` - Output tokens (generated by model) |
| 75 | +- `~X think` - Reasoning tokens for thinking models |
| 76 | +- Context percentage: `X% of limit` |
| 77 | + |
| 78 | +## Implementation Tasks |
| 79 | + |
| 80 | +### Phase 1: Add Streaming Token Updates to Processor |
| 81 | + |
| 82 | +- [x] Import `Token` module in `packages/opencode/src/session/processor.ts` |
| 83 | +- [x] Add `reasoningTotal` and `textTotal` character accumulators at processor creation |
| 84 | +- [x] Update `reasoning-delta` handler to calculate and store `reasoningEstimate`: |
| 85 | + ```typescript |
| 86 | + case "reasoning-delta": |
| 87 | + reasoningTotal += value.text.length |
| 88 | + input.assistantMessage.reasoningEstimate = Token.toTokenEstimate(reasoningTotal) |
| 89 | + await Session.updateMessage(input.assistantMessage) |
| 90 | + ``` |
| 91 | +- [x] Update `text-delta` handler to calculate and store `outputEstimate`: |
| 92 | + ```typescript |
| 93 | + case "text-delta": |
| 94 | + textTotal += value.text.length |
| 95 | + input.assistantMessage.outputEstimate = Token.toTokenEstimate(textTotal) |
| 96 | + await Session.updateMessage(input.assistantMessage) |
| 97 | + ``` |
| 98 | +- [ ] Update `finish-step` to emit final `contextEstimate` from usage data |
| 99 | + |
| 100 | +### Phase 2: Add Token Display State |
| 101 | + |
| 102 | +- [x] Add `showTokens` signal to session component: |
| 103 | + ```typescript |
| 104 | + const [showTokens, setShowTokens] = createSignal(kv.get("show_tokens", false)) |
| 105 | + ``` |
| 106 | +- [ ] Add `contextLimit` memo that gets limit from current model/provider |
| 107 | +- [x] Add to context provider: `showTokens: () => boolean` |
| 108 | + |
| 109 | +### Phase 3: Add Toggle Tokens Command |
| 110 | + |
| 111 | +- [x] Add "Toggle tokens" command to `command.register()` array: |
| 112 | + ```typescript |
| 113 | + { |
| 114 | + title: showTokens() ? "Hide tokens" : "Show tokens", |
| 115 | + value: "session.toggle.tokens", |
| 116 | + category: "Session", |
| 117 | + onSelect: (dialog) => { |
| 118 | + setShowTokens((prev) => { |
| 119 | + const next = !prev |
| 120 | + kv.set("show_tokens", next) |
| 121 | + return next |
| 122 | + }) |
| 123 | + dialog.clear() |
| 124 | + }, |
| 125 | + } |
| 126 | + ``` |
| 127 | + |
| 128 | +### Phase 4: Update AssistantMessage Component |
| 129 | + |
| 130 | +- [x] Add token calculation logic: |
| 131 | + ```typescript |
| 132 | + const inputTokens = createMemo(() => { |
| 133 | + const sent = props.message.sentEstimate ?? 0 |
| 134 | + const context = props.message.contextEstimate ?? 0 |
| 135 | + return sent + context |
| 136 | + }) |
| 137 | + const outputTokens = createMemo(() => props.message.tokens?.output ?? props.message.outputEstimate ?? 0) |
| 138 | + const reasoningTokens = createMemo(() => props.message.tokens?.reasoning ?? props.message.reasoningEstimate ?? 0) |
| 139 | + ``` |
| 140 | +- [x] Add conditional token display: |
| 141 | + ```tsx |
| 142 | + <Show when={showTokens()}> |
| 143 | + <text fg={theme.textMuted}> |
| 144 | + IN {inputTokens().toLocaleString()}↓ OUT {outputTokens().toLocaleString()}↑ |
| 145 | + <Show when={reasoningTokens()}> ~{reasoningTokens().toLocaleString()} think</Show> |
| 146 | + </text> |
| 147 | + </Show> |
| 148 | + ``` |
| 149 | + |
| 150 | +### Phase 5: Update UserMessage Component |
| 151 | + |
| 152 | +- [x] Add individual token count display when `showTokens()` is true: |
| 153 | + ```tsx |
| 154 | + <Show when={showTokens() && props.message.sentEstimate}> |
| 155 | + <text fg={theme.textMuted}>~{props.message.sentEstimate?.toLocaleString()} tokens</text> |
| 156 | + </Show> |
| 157 | + ``` |
| 158 | + |
| 159 | +## Code References |
| 160 | + |
| 161 | +### Internal Files |
| 162 | + |
| 163 | +- `packages/opencode/src/util/token.ts` - Token utility functions (exists) |
| 164 | +- `packages/opencode/src/session/message-v2.ts:308-309` - User message estimate fields (exists) |
| 165 | +- `packages/opencode/src/session/message-v2.ts:369-372` - Assistant message estimate fields (exists) |
| 166 | +- `packages/opencode/src/session/processor.ts:82-88` - reasoning-delta handler (needs update) |
| 167 | +- `packages/opencode/src/session/processor.ts:305-315` - text-delta handler (needs update) |
| 168 | +- `packages/opencode/src/session/processor.ts:251-270` - finish-step handler (needs update) |
| 169 | +- `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx:1097-1162` - AssistantMessage component |
| 170 | +- `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx:1001-1095` - UserMessage component |
| 171 | +- `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx:241-777` - Command registration |
| 172 | + |
| 173 | +### External References |
| 174 | + |
| 175 | +- Original PR: https://github.com/sst/opencode/pull/4709 |
| 176 | + |
| 177 | +## Estimated Changes |
| 178 | + |
| 179 | +| File | Lines Added | Lines Modified | |
| 180 | +| -------------- | ----------- | -------------- | |
| 181 | +| `processor.ts` | ~15 | ~10 | |
| 182 | +| `index.tsx` | ~50 | ~15 | |
| 183 | +| **Total** | ~65 | ~25 | |
| 184 | + |
| 185 | +## Validation Criteria |
| 186 | + |
| 187 | +- [x] Token estimates display during streaming (before final usage available) |
| 188 | +- [x] `IN X↓` shows input/context tokens accurately |
| 189 | +- [x] `OUT Y↑` shows output tokens, updating in real-time during generation |
| 190 | +- [x] Reasoning tokens display for models that support thinking (e.g., Claude) |
| 191 | +- [x] "Toggle tokens" command appears in command palette |
| 192 | +- [x] Toggle persists via KV store across sessions |
| 193 | +- [x] User messages show estimated token count when toggle enabled |
| 194 | +- [x] Estimates use `~` prefix to indicate approximation |
| 195 | +- [x] Final token counts from API replace estimates when available |
| 196 | + |
| 197 | +## Dependencies |
| 198 | + |
| 199 | +None - all required utilities and schema fields already exist. |
| 200 | + |
| 201 | +## Risks & Considerations |
| 202 | + |
| 203 | +1. **Estimation Accuracy**: Character-based estimation is approximate. Actual tokenization varies by model. Consider this acceptable for UX purposes. |
| 204 | + |
| 205 | +2. **Performance**: Updating message on every delta may cause performance issues. Consider throttling updates (e.g., every 100ms or 100 chars). |
| 206 | + |
| 207 | +3. **Context Limit**: Different models have different context limits. Need to properly fetch limit from provider/model configuration. |
| 208 | + |
| 209 | +4. **Subtask Bug Status**: The regression bug mentioned in PR discussions (missing `updatePart` call after `taskTool.execute`) was previously fixed and the fix is still present. No action needed. |
0 commit comments