mirror of
https://github.com/Twigpine/zero.git
synced 2026-11-11 23:40:28 -10:00
* feat(tui): actionable hints on provider/model errors Classify a failed turn's provider error into auth / rate-limit / connectivity / model-not-found / context-overflow and render a one-line next step below the red error row, instead of dumping an identical raw blob for every failure mode. The classifier lives in a new internal/errhint package so both the TUI error row and the CLI exec path can share it (TUIHint references slash commands, CLIHint references zero subcommands). Classification is a conservative string heuristic keyed off providerio.ClassifiedError's prefixes plus lower-level DNS/TLS/timeout/context-length signatures, since the numeric HTTP status is gone by the time the error reaches a UI surface. * feat(tools): budget bash output with head+tail truncation bash was the one tool that returned command output with no byte cap — 'cat large.log' or a verbose test run could dump megabytes into context and force compaction, while every other read/search tool already applies a budget. Cap stdout and stderr at 96KB each, keeping the head and tail of an oversized stream (build/test failures usually land at the tail) and dropping the middle behind a marker that points at redirect-to-file + read_file. Record raw_bytes/emitted_bytes/estimated_tokens/truncated in Meta like the other tools. Sandbox-denial and shell-issue detection still run on the full raw output before budgeting. * fix(gemini): retry 401 with refreshed OAuth token The Gemini provider used providerio.SendWithRetry (429/503/529 only), so an expired OAuth token surfaced as a terminal 'API key not valid' auth error while OpenAI and Anthropic silently recovered via SendWithAuthRetry's force-refresh-and-replay on 401. Plumb OAuthResolver through gemini.Options/Provider and the factory (exactly as the other two providers already do) and switch the stream send to SendWithAuthRetry. With a nil resolver (API-key users) behavior is unchanged. * fix(errhint): gate classification on provider-origin marker Address CodeRabbit review on #1: agentResponseMsg.err can also carry local failures (a tool's 'permission denied', a 'file does not exist', a config error), and broad substrings would have attached a bogus /provider or /model hint to those. Classify now returns Unknown unless the message carries a provider marker the provider layer always attaches (auth error: / rate limit error: / provider error: / provider request error: / provider stream error:). Local errors never draw a provider hint; provider errors sub-classify as before. Added local-failure test cases proving they stay Unknown. * feat(cli): actionable hint on text-mode exec provider errors zero exec printed provider failures as a bare '[zero] <raw error>' with no next step. Append a one-line hint (reusing the shared errhint classifier) for recognized provider failures — 'run `zero auth`', 'run `zero doctor`', etc. The provider-origin gate means non-provider codes (sandbox_error, mcp_error) and JSON/stream-json output are untouched. * fix(tools): set Result.Truncated for budgeted bash output Address CodeRabbit review on #3: budgetBashOutput recorded truncation in meta["truncated"] but never set the Result.Truncated struct field, so consumers reading the struct (like glob/web_fetch/read_minified do) would miss truncated bash results. Return the bool from budgetBashOutput and set Result.Truncated on every return path. * perf(tui): reuse one LSP manager across prompts runAgentWithOptions built a fresh lsp.NewManager per run and shut it down when the run returned, so gopls (and every other language server) cold-started on the first edit of every turn — 200ms-2s of latency the manager's own design (long-lived, reused servers) exists to avoid. Build one manager per session in newModel (cheap: servers start lazily on first Check) and reuse it across runs; the SelfCorrector still gets a fresh checker wrapping the shared manager each run. Torn down with a short deadline in quit(). Runs fall back to a per-run manager when the session manager is absent (cwd unknown, or a directly-built test model). * perf(tui): accumulate streamingText as []byte (O(1) append) m.streamingText += msg.delta was O(len) per delta -> O(n²) across a long generation (a 10k-token code gen allocates hundreds of MB of intermediate strings and the UI gets progressively laggier). Accumulate into a []byte with append (O(1) amortized) and read via streamingTextString(). A []byte rather than strings.Builder because the TUI model is copied by value on every Update, which would trip strings.Builder's copy check; []byte is nil-safe and copies cleanly like the other slice fields. * perf(tui): coalesce streamed text deltas to one frame Every OnText delta was its own tea.Msg, so a fast provider (100+ tok/s) drove 100+ full Update->View cycles per second, each re-parsing the growing markdown — visible stutter over SSH and wasted CPU. Batch agentTextMsg deltas at the runtime sink over a ~16ms frame and forward them as a single message, decoupling render rate from token rate. Any non-text message flushes pending text first so ordering with tool-call / reasoning / row messages is preserved; the final agentResponseMsg (a tea.Cmd return, not a sink message) is safe because the model already drops deltas for an inactive runID. * fix(agent): raise tool-failure stop threshold 4->6 guardrails.go halted a run after 4 consecutive same-error tool failures. A corrective hint fires at 2, and a model iterating on a genuinely tricky edit can legitimately fail a couple more times after the hint while converging — stopping at 4 cut those runs short. Raise to 6; the streak still resets the instant the tool succeeds or hits a different error, so only true same-error loops are affected. * fix(agent): more reconnect retries with jitter; narrow to transport errors #19: bump maxStreamReconnects 2->4 and add up-to-50% jitter on the exponential backoff (capped at 8s), so a multi-second network blip is ridden out instead of killing the run on a 2s hiccup, and concurrent runs (swarms, cron fleets) don't reconnect in lockstep. #34: drop the '502'/'503' substring matches from shouldReconnect. 503 already exhausted providerio.SendWithRetry (retrying here is a redundant double-retry) and 502 is non-idempotent by providerio's rule (the POST may have been processed). Only genuine transport failures — where no response was received — reconnect now. * fix(agent): reduce stall retries 2->1 to bound stuck-session time A no-output stream stall is detected only after the full stream idle timeout (~5min) elapses, and each retry can idle again — so 2 retries left an interactive session frozen for ~15min. Drop to 1 retry: keeps the common single-hiccup recovery while bounding the worst case to ~2x the idle timeout. * fix(tui): serialize coalescer forwarding to preserve message order Address CodeRabbit review on #7: flush() and the run-switch path drained the text buffer under c.mu but called forward() after releasing it, so a timer-fired text flush could race a concurrent non-text send() and land after the tool-call/reasoning message it should precede. Hold c.mu across drain AND forward (drainAndForwardLocked), so whoever holds the lock delivers atomically and the other caller blocks until it is done — text can never overtake a following non-text message. Added a concurrency stress test (timer racing an inline send) that passes under -race. * feat(tui): accept /compact now Bare /compact already triggers compaction, but /compact now — what users reach for when the context gauge climbs — hit the usage-error branch. Accept the 'now' keyword and advertise it in the command usage. * feat(tui): add /retry, /edit, /copy, /export commands /retry resends the last prompt; /edit recalls it into the composer to tweak and resend — both read a new lastPrompt field captured verbatim (pre-expansion) in launchPrompt. /copy puts the last answer on the clipboard via the existing copy machinery; /export writes a plain role-prefixed transcript to a file (timestamped default, or a given path). Real gaps for SSH users with no mouse select. * feat(tools): separator-insensitive tool_search matching tool_search ranked deferred tools by exact substring, so a model that typed 'webfetch' (dropping the underscore) matched nothing and looped. Add a separator-squashing fallback ('web_fetch' -> 'webfetch') scored below an exact substring match, so precise queries still rank first. * feat(tools): signal ask_user dismissal distinctly from a blank field Empty answers all rendered as '(no answer provided)', so the model couldn't tell a wholesale dismissal (user closed the prompt without answering anything) from one field left blank amid real answers — and might invent a default. FormatAskUserAnswers now flags a full dismissal up front as a skip and marks individual empties '(left blank)' vs '(skipped)'. * feat(tui): fuzzy ranking in model/session pickers The pickers filtered by flat strings.Contains with no ranking, so finding 'sonnet 4.5' among 50+ models meant an exact prefix or scrolling. Rank matches (exact < prefix < contains < subsequence, reusing fuzzySubsequenceGap) so the closest match lands on top, and 'snt45' now matches 'Sonnet 4.5'. Groups stay contiguous — ordered by their best match, never split — so the grouped model picker still renders one header per provider. Covers both /model and /resume (shared commandPicker). * perf(agent): cache per-tool schema render across turns partitionTools re-ran the recursive schema->map conversion (schemaToRuntimeMap) for every tool on every turn — redundant, since a tool's advertised name/description/schema is stable for the run. Add a per-run definition cache keyed by tool name (nil-safe; the plain partitionTools entrypoint and tests pass nil for fresh renders). The partitioning itself (visibility, deferral, ordering) still recomputes every turn — it must, because a tool's deferred state can flip mid-run (swarm tools un-defer once a swarm is active). Only the expensive schema render is memoized. tool_search is excluded by its callers (dynamic description) so it never poisons the cache. * perf(agent): calibrate compaction estimate against real prompt tokens The byte/4 heuristic (ApproxTextTokens) over-counts code-heavy content ~15-20%, so with triggerRatio=0.7 compaction fired at ~60% of true capacity — premature summarizer calls that degrade quality. Each turn now folds (rawEstimate, provider InputTokens) into an EMA calibration ratio, clamped per-sample to a sane band; maybeCompact and the reactive path scale their estimates by it. Turn 1 uses the raw estimate (no data yet); later turns compact near real capacity. * style: gofmt the new agent test files The CI gofmt check flagged the #22/#25 test files (struct-field and switch alignment). No behavior change. * feat(agent): turn-based plan staleness reminder The stale-plan nudge only fired after 10 tool calls since the last update_plan, so a plan that drifts stale across many low-tool-call turns (one call per turn) took many turns to catch — the 'plan set turn 1 stays pending forever' case. Add a turn-count complement: after stalePlanTurnThreshold (8) turns without an update AND with items still pending, fire the same one-shot reminder. Gated on pending items so a fully-completed plan is never nagged; the existing tool-call trigger is unchanged. (The roadmap's fuzzy 'tool calls unrelated to plan items' relevance match is deliberately omitted — too false-positive-prone.) * feat(agent): preserve recent-edits summary across compaction Compaction preserved the plan, loaded skills, tool schemas, and project instructions, but not file edits — so after the editing turns were elided the model knew it had changed a file only vaguely, and would re-read to rediscover its own footprint. Extract write_file/edit_file targets from the elided middle with a one-line note from each tool result, merge them across repeated compactions (newer note per path wins), and carry them in the preserved-state JSON (capped at 20 paths / 160 bytes per note). * feat(tui): workspace-scoped /resume + fewer event reads /resume listed sessions from every project globally, and read the full event file for each of them to test for resumable content. Filter the picker (and /resume latest) by the current workspace Cwd, checked BEFORE the per-session read so a large global history no longer pays N full file reads to build one workspace's list; also skip zero-event sessions via metadata without any read. Sessions with no recorded Cwd (older runs) and an unknown current workspace stay visible so nothing is hidden that can't be confidently placed. Explicit /resume <id> still resolves any session. * feat(tui): warn on model switch that drops staged images Staged images were silently dropped at submit when the active model had no vision support — the user only learned after sending. Chips already render above the composer (renderAttachmentChips); add an immediate amber warning line to the /model switch status (both same-provider and cross-provider paths) when images are staged and the newly selected model can't accept them, so the drop is surfaced at switch time. * feat(tui): inline recovery affordance on setup errors A first-run setup error rendered as a bare red 'error: <text>' with no pointer to the fix. Append a faint, stage-tailored recovery line (edit the endpoint/name/key above then Enter, or pick another model) that names only keys the stage's footer confirms, so the guidance is always accurate. Empty for stages whose footer already makes recovery obvious. * fix: address CodeRabbit review (5 findings) - loop.go: recompute the compaction calibration estimate at calibration time, not request-build time, so a reactive-compaction reissue that shrinks the request feeds the EMA the sample that actually completed. - errhint: match bare HTTP status codes (401/403/429/529) only at digit boundaries, so an incidental number ('4290ms', 'id 14015') isn't mis-bucketed as auth/rate-limit. - bash: drop the stray unmatched ']' in the output-truncation marker. - tui /retry: apply the same exiting/compactInFlight guards commandPrompt has, so a retry can't race compactResultMsg's rewrite of session state. - tui /export: write the transcript 0o600 (it may contain echoed secrets), not world/group-readable 0o644. * test(tui): skip export file-mode assertion on Windows os.WriteFile ignores Unix permission bits on Windows and Stat reports 0666, so the 0o600 assertion failed there. The production 0o600 is honored on Linux/macOS (where it matters); guard the check with runtime.GOOS so Windows smoke passes. * fix(tui): align /resume latest filters + case-insensitive workspace match on Windows Address CodeRabbit review on #21: - latestResumableInWorkspace now applies the SAME filters as the picker (skip zero-event metadata and empty/failed runs), so /resume latest can't land on a session the picker intentionally hides. - sessionMatchesWorkspace compares paths case-insensitively on Windows (its filesystem is), so the same workspace spelled with different casing no longer hides resumable sessions; other platforms stay case-sensitive. * fix(tui): /retry resends the last prompt's image/PDF attachments /retry relaunched only lastPrompt's text, but launchPrompt clears the pending image/document queues once a turn is sent. A vision- or PDF-backed prompt that failed would silently retry as text-only and answer a different task. Snapshot the consumed attachments at launch and re-stage them on /retry so launchPrompt rebuilds an identical request (document preamble, images, and the submit-time vision re-check). startNewSession drops the snapshot so a post-/new /retry cannot leak the previous session's attachments. Also correct the OAuthResolver factory comment, which omitted the Gemini provider it is now passed to. * fix: address jatmn review (reconnect 5xx, /edit attachments, edit-cap, coalescer test) - reconnect: exclude HTTP 5xx (500/502/503/504) before the transport substring match so "504 Gateway Timeout" no longer slips through on the generic "timeout" needle. A gateway timeout is non-idempotent — the completion POST may already have reached the model — so replaying the connect risked duplicate billable work. Reuses a digit-boundary status matcher exported from errhint (HasStatusCode). Test asserts 504/500 stay non-reconnectable. - tui /edit: re-stage the remembered image/PDF snapshot alongside the recalled prompt text, mirroring the /retry fix — editing a vision- or document-backed prompt no longer silently resends a text-only version. - compaction recent-edits: order edits by LAST edit, not first, and move a re-touched path to the newest position on merge, so the maxRecentEdits tail cap keeps the file the model most recently edited instead of dropping it. Adds mergeRecentEdits (edit-specific) and a capped-list regression. - coalescer test: inject the frame timer via afterFunc so TestCoalescerBatchesDeltas proves buffering deterministically instead of racing the real 16ms wall-clock timer. * fix(tools): bound bash output capture in memory, not just model-visible text Previously stdout/stderr streamed into unbounded bytes.Buffers and were only truncated to the 96 KiB budget AFTER the command finished, so a runaway command (cat huge.log, yes) could grow Zero's memory until it stalled or OOMed before budgetBashOutput ever ran. Replace the capture with boundedBuffer, an io.Writer that keeps only the head+tail each stream will surface and discards the middle as it arrives, while counting the true total for the truncation marker. Memory is now bounded to ~head+2×tail per stream regardless of output size. truncateHeadTail is refactored onto a total-aware core so the string path (and its tests) are unchanged, and budgetBashCapture reports the true raw_bytes even though only a bounded slice was held. Adds boundedBuffer/capture unit tests and an end-to-end test that streams ~5× the budget and asserts bounded emission with an accurate raw_bytes.
834 lines
27 KiB
Go
834 lines
27 KiB
Go
package tui
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
|
|
tea "charm.land/bubbletea/v2"
|
|
|
|
"github.com/Gitlawb/zero/internal/agent"
|
|
"github.com/Gitlawb/zero/internal/config"
|
|
"github.com/Gitlawb/zero/internal/modelregistry"
|
|
"github.com/Gitlawb/zero/internal/sessions"
|
|
"github.com/Gitlawb/zero/internal/usage"
|
|
"github.com/Gitlawb/zero/internal/zeroruntime"
|
|
)
|
|
|
|
var responseStyles = []string{"balanced", "concise", "explanatory", "review"}
|
|
|
|
const tuiCompactionPreserveLast = 8
|
|
const tuiCompactionMaxPromptChars = 8000
|
|
const compactStatusRowID = "compact/status"
|
|
|
|
var compactFrames = []string{"⠂", "⠒", "⠲", "⠴"}
|
|
|
|
type SessionCompactor interface {
|
|
CompactSession(context.Context, CompactRequest) (CompactResult, error)
|
|
}
|
|
|
|
type CompactRequest struct {
|
|
SessionID string
|
|
ModelName string
|
|
ContextWindow int
|
|
SessionEventCount int
|
|
EstimatedTokens int
|
|
VisibleTranscriptRows int
|
|
CompactRequests int
|
|
}
|
|
|
|
type CompactResult struct {
|
|
Compacted bool
|
|
BeforeTokens int
|
|
AfterTokens int
|
|
Summary string
|
|
}
|
|
|
|
type compactResultMsg struct {
|
|
result CompactResult
|
|
err error
|
|
activeSession sessions.Metadata
|
|
sessionEvents []sessions.Event
|
|
transcript []transcriptRow
|
|
hasSessionSnapshot bool
|
|
}
|
|
|
|
func (m model) handleEffortCommand(args string) (model, string) {
|
|
args = strings.TrimSpace(strings.ToLower(args))
|
|
if args == "" || args == "list" {
|
|
return m, m.effortText()
|
|
}
|
|
if args == "auto" {
|
|
m.reasoningEffort = ""
|
|
return m, m.effortStatusCard("auto", "Reasoning effort selection will follow the active model/provider defaults.")
|
|
}
|
|
|
|
requested := modelregistry.ReasoningEffort(args)
|
|
if !modelregistry.ValidReasoningEffort(requested) {
|
|
return m, m.effortStatusCard(args, "Unknown reasoning effort: "+args)
|
|
}
|
|
efforts := m.availableReasoningEfforts()
|
|
if len(efforts) == 0 {
|
|
return m, m.effortStatusCard("", "Active model does not expose reasoning effort controls.")
|
|
}
|
|
if !reasoningEffortAllowed(efforts, requested) {
|
|
return m, m.effortStatusCard(string(requested),
|
|
fmt.Sprintf("Reasoning effort %q is not supported by %s.", requested, displayValue(m.modelName, "the active model")))
|
|
}
|
|
|
|
m.reasoningEffort = requested
|
|
return m, m.effortStatusCard(string(requested), "Reasoning effort preference is stored for this TUI session.")
|
|
}
|
|
|
|
// effortStatusCard renders the small inline confirmation card shown after a
|
|
// /effort <value> mutation (set, auto, unknown, unsupported). The body is a
|
|
// lime-bordered card so the transition from "picker open" -> "card collapsed"
|
|
// reads as the same surface the picker came from, instead of a separate grey
|
|
// status block.
|
|
func (m model) effortStatusCard(value string, detail string) string {
|
|
active := strings.TrimSpace(value)
|
|
if active == "" {
|
|
active = "auto"
|
|
}
|
|
fields := []commandField{
|
|
{Key: "active effort", Value: active},
|
|
{Key: "model", Value: displayValue(m.modelName, "none")},
|
|
}
|
|
return renderCommandCardTranscript(commandCard{
|
|
Title: "Effort",
|
|
Summary: []string{"active effort: " + active},
|
|
Sections: []commandCardSection{{
|
|
Title: "State",
|
|
Fields: fields,
|
|
Lines: []string{detail},
|
|
}},
|
|
})
|
|
}
|
|
|
|
func (m model) effortText() string {
|
|
efforts := m.availableReasoningEfforts()
|
|
fields := []commandField{
|
|
{Key: "active effort", Value: m.effortDisplay()},
|
|
{Key: "model", Value: displayValue(m.modelName, "none")},
|
|
}
|
|
actions := []string{"use /effort <value> to switch", "/effort auto to clear"}
|
|
if len(efforts) == 0 {
|
|
fields = append(fields, commandField{Key: "available", Value: "none for active model"})
|
|
return renderCommandCardTranscript(commandCard{
|
|
Title: "Effort",
|
|
Summary: []string{"active effort: " + m.effortDisplay(), "no reasoning controls on this model"},
|
|
Sections: []commandCardSection{{Title: "State", Fields: fields}},
|
|
Actions: actions,
|
|
})
|
|
}
|
|
fields = append(fields, commandField{Key: "available", Value: joinReasoningEfforts(efforts)})
|
|
return renderCommandCardTranscript(commandCard{
|
|
Title: "Effort",
|
|
Summary: []string{"active effort: " + m.effortDisplay(), fmt.Sprintf("%d supported level(s)", len(efforts))},
|
|
Sections: []commandCardSection{{Title: "State", Fields: fields}},
|
|
Actions: actions,
|
|
})
|
|
}
|
|
|
|
func (m model) availableReasoningEfforts() []modelregistry.ReasoningEffort {
|
|
if strings.TrimSpace(m.modelName) == "" {
|
|
return nil
|
|
}
|
|
registry, err := modelregistry.DefaultRegistry()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return registry.ReasoningEfforts(m.modelName)
|
|
}
|
|
|
|
func (m model) effortDisplay() string {
|
|
if m.reasoningEffort == "" {
|
|
return "auto"
|
|
}
|
|
return string(m.reasoningEffort)
|
|
}
|
|
|
|
// cycleReasoningEffort advances the reasoning-effort ring:
|
|
// auto ("") -> first supported -> ... -> last supported -> auto. No-op (model
|
|
// unchanged) when the active model exposes no effort controls, so Ctrl+T stays
|
|
// quiet on non-reasoning models. Called from the Ctrl+T key case — a rare
|
|
// keypress — so the DefaultRegistry() lookup inside availableReasoningEfforts
|
|
// is fine here, but MUST NOT be called from the render path (the registry is
|
|
// rebuilt on every call).
|
|
func (m model) cycleReasoningEffort() (model, tea.Cmd) {
|
|
efforts := m.availableReasoningEfforts()
|
|
if len(efforts) == 0 {
|
|
return m, nil
|
|
}
|
|
if m.reasoningEffort == "" {
|
|
m.reasoningEffort = efforts[0]
|
|
return m, nil
|
|
}
|
|
idx := reasoningEffortIndex(efforts, m.reasoningEffort)
|
|
if idx == -1 || idx == len(efforts)-1 {
|
|
m.reasoningEffort = "" // wrap to auto
|
|
return m, nil
|
|
}
|
|
m.reasoningEffort = efforts[idx+1]
|
|
return m, nil
|
|
}
|
|
|
|
func reasoningEffortAllowed(efforts []modelregistry.ReasoningEffort, want modelregistry.ReasoningEffort) bool {
|
|
for _, effort := range efforts {
|
|
if effort == want {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// reasoningEffortIndex returns the position of want in efforts, or -1. Sibling
|
|
// to reasoningEffortAllowed; used by cycleReasoningEffort to find the current
|
|
// slot in the model's supported ring.
|
|
func reasoningEffortIndex(efforts []modelregistry.ReasoningEffort, want modelregistry.ReasoningEffort) int {
|
|
for index, effort := range efforts {
|
|
if effort == want {
|
|
return index
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
func joinReasoningEfforts(efforts []modelregistry.ReasoningEffort) string {
|
|
values := make([]string, 0, len(efforts))
|
|
for _, effort := range efforts {
|
|
values = append(values, string(effort))
|
|
}
|
|
return strings.Join(values, ", ")
|
|
}
|
|
|
|
func (m model) handleStyleCommand(args string) (model, string) {
|
|
args = strings.TrimSpace(strings.ToLower(args))
|
|
if args == "" || args == "list" {
|
|
return m, m.styleText()
|
|
}
|
|
if !responseStyleAllowed(args) {
|
|
return m, "Style\nUnknown response style: " + args
|
|
}
|
|
m.responseStyle = args
|
|
return m, strings.Join([]string{
|
|
"Style",
|
|
"active style: " + m.responseStyle,
|
|
"Style preference is stored for this TUI session.",
|
|
}, "\n")
|
|
}
|
|
|
|
func (m model) styleText() string {
|
|
return renderCommandOutput(commandOutput{
|
|
Title: "Style",
|
|
Status: commandStatusOK,
|
|
Sections: []commandSection{{
|
|
Title: "State",
|
|
Lines: []string{
|
|
"active style: " + m.responseStyle,
|
|
"available: " + strings.Join(responseStyles, ", "),
|
|
},
|
|
}},
|
|
Hints: []string{"use /style <value> to update this TUI session"},
|
|
})
|
|
}
|
|
|
|
func defaultedResponseStyle(value string) string {
|
|
value = strings.TrimSpace(strings.ToLower(value))
|
|
if responseStyleAllowed(value) {
|
|
return value
|
|
}
|
|
return defaultResponseStyle
|
|
}
|
|
|
|
func (m model) handleSelfCorrectCommand(args string) (model, string) {
|
|
args = strings.TrimSpace(strings.ToLower(args))
|
|
switch args {
|
|
case "", "status":
|
|
return m, m.selfCorrectText()
|
|
case "on", "tests", "full":
|
|
m.selfCorrectTests = true
|
|
case "off", "lsp":
|
|
m.selfCorrectTests = false
|
|
default:
|
|
return m, "Self-correct\nUsage: /selfcorrect [status|on|off|tests|full|lsp]"
|
|
}
|
|
return m, m.selfCorrectText()
|
|
}
|
|
|
|
// maxTurnsCeiling caps the per-session /turns budget so a typo (e.g. /turns 99999)
|
|
// can't set an absurd ceiling; real multi-step tasks fit comfortably under it. Shared
|
|
// with config so applyEnv enforces the same bound on an inherited ZERO_MAX_TURNS.
|
|
const maxTurnsCeiling = config.MaxTurnsCeiling
|
|
|
|
func (m model) handleTurnsCommand(args string) (model, string) {
|
|
args = strings.TrimSpace(args)
|
|
if args == "" || strings.EqualFold(args, "status") {
|
|
return m, m.turnsText()
|
|
}
|
|
n, err := strconv.Atoi(args)
|
|
if err != nil || n < 1 {
|
|
return m, "Turns\nUsage: /turns <n> — set the per-run tool-turn budget for this session (a positive number, e.g. /turns 150)."
|
|
}
|
|
if n > maxTurnsCeiling {
|
|
n = maxTurnsCeiling
|
|
}
|
|
m.agentOptions.MaxTurns = n
|
|
// Propagate the budget to spawned sub-agents / swarm members (which inherit the
|
|
// environment) so a delegated task gets the same budget, not config.json's default.
|
|
config.SetMaxTurnsEnv(n)
|
|
return m, m.turnsText()
|
|
}
|
|
|
|
func (m model) turnsText() string {
|
|
return renderCommandOutput(commandOutput{
|
|
Title: "Turns",
|
|
Status: commandStatusOK,
|
|
Sections: []commandSection{{
|
|
Title: "State",
|
|
Lines: []string{fmt.Sprintf("max tool-turns per run: %d", m.agentOptions.MaxTurns)},
|
|
}},
|
|
Hints: []string{fmt.Sprintf("/turns <n> sets this session's tool-turn budget (max %d); raise it for long multi-step tasks like delegation/swarm runs", maxTurnsCeiling)},
|
|
})
|
|
}
|
|
|
|
func (m model) selfCorrectText() string {
|
|
depth := "LSP diagnostics only — fast, scoped to changed files"
|
|
if m.selfCorrectTests {
|
|
depth = "LSP diagnostics + project test plan (e.g. go test ./...) — slower, whole-repo"
|
|
}
|
|
return renderCommandOutput(commandOutput{
|
|
Title: "Self-correct",
|
|
Status: commandStatusOK,
|
|
Sections: []commandSection{{
|
|
Title: "State",
|
|
Lines: []string{
|
|
"post-edit verification: " + depth,
|
|
"auto-fix vs report-only: follows the active permission mode",
|
|
},
|
|
}},
|
|
Hints: []string{"/selfcorrect on adds the full test suite; /selfcorrect off returns to LSP-only (default)"},
|
|
})
|
|
}
|
|
|
|
func responseStyleAllowed(value string) bool {
|
|
for _, style := range responseStyles {
|
|
if value == style {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (m model) handleCompactCommand(args string) (model, string, tea.Cmd) {
|
|
args = strings.TrimSpace(strings.ToLower(args))
|
|
if args == "status" {
|
|
return m, m.compactText(false), nil
|
|
}
|
|
// Bare "/compact" already triggers compaction; accept "now" too since that is
|
|
// what users reach for when they see the context gauge climbing.
|
|
if args != "" && args != "now" {
|
|
return m, "Compact\nusage: /compact [status|now]", nil
|
|
}
|
|
if m.compactInFlight {
|
|
return m, m.compactText(true), nil
|
|
}
|
|
m.compactRequests++
|
|
m.lastCompactError = ""
|
|
m.lastCompactResult = nil
|
|
if m.sessionCompactor == nil && !m.hasSessionBackedCompactor() {
|
|
return m, m.compactText(true), nil
|
|
}
|
|
m.compactInFlight = true
|
|
m.compactFrame = 0
|
|
return m, m.compactText(true), tea.Batch(m.runCompact(), m.spinner.Tick)
|
|
}
|
|
|
|
func (m model) runCompact() tea.Cmd {
|
|
request := m.compactRequest()
|
|
if m.sessionCompactor != nil {
|
|
compactor := m.sessionCompactor
|
|
ctx := m.ctx
|
|
return func() tea.Msg {
|
|
result, err := compactor.CompactSession(ctx, request)
|
|
return compactResultMsg{result: result, err: err}
|
|
}
|
|
}
|
|
return func() tea.Msg {
|
|
next, result, err := m.compactActiveSession()
|
|
if err != nil {
|
|
return compactResultMsg{err: err}
|
|
}
|
|
return compactResultMsg{
|
|
result: result,
|
|
activeSession: next.activeSession,
|
|
sessionEvents: append([]sessions.Event{}, next.sessionEvents...),
|
|
transcript: append([]transcriptRow{}, next.transcript...),
|
|
hasSessionSnapshot: true,
|
|
}
|
|
}
|
|
}
|
|
|
|
// handleRewindCommand restores workspace files to a checkpoint and truncates the
|
|
// session log. "/rewind" or "/rewind latest" undoes the most recent checkpoint;
|
|
// "/rewind <n>" rewinds to a specific event sequence.
|
|
func (m model) handleRewindCommand(args string) (model, string) {
|
|
if m.sessionStore == nil || m.activeSession.SessionID == "" {
|
|
return m, "Rewind\nno active session to rewind."
|
|
}
|
|
if m.pending {
|
|
return m, "Rewind\ncannot rewind while a run is in progress."
|
|
}
|
|
// A cancelled run's late flush hasn't appended its checkpoint events yet:
|
|
// ApplyRewind would prune those checkpoint blobs as unreferenced, then the
|
|
// flush would re-append pre-rewind events after the rewind marker.
|
|
if len(m.flushRunIDs) > 0 {
|
|
return m, "Rewind\ncannot rewind while a cancelled run is still flushing — retry in a moment."
|
|
}
|
|
arg := strings.TrimSpace(strings.ToLower(args))
|
|
target, err := m.resolveRewindTarget(arg)
|
|
if err != nil {
|
|
return m, "Rewind\n" + err.Error()
|
|
}
|
|
report, err := m.sessionStore.ApplyRewind(m.activeSession.SessionID, m.cwd, target)
|
|
if err != nil {
|
|
return m, "Rewind\n" + err.Error()
|
|
}
|
|
|
|
// ApplyRewind truncated the persisted event log, restored files, and appended a
|
|
// rewind marker — so reload the in-memory session state. Otherwise the dropped
|
|
// events would still (a) be re-sent to the agent as ContextEvents on the next
|
|
// prompt (sessionPrompt sends m.sessionEvents) and (b) linger in the transcript.
|
|
// A reload FAILURE must be surfaced (and the stale in-memory context dropped),
|
|
// not ignored — silently keeping m.sessionEvents would re-send rewound-away
|
|
// events on the next prompt, defeating the rewind.
|
|
if meta, getErr := m.sessionStore.Get(m.activeSession.SessionID); getErr == nil {
|
|
m.activeSession = *meta
|
|
}
|
|
events, readErr := m.sessionStore.ReadEvents(m.activeSession.SessionID)
|
|
if readErr != nil {
|
|
m.sessionEvents = nil // drop stale context so it can't reach the next prompt
|
|
return m, fmt.Sprintf("Rewind\nrewound to sequence %d, but reloading the session failed (in-memory context cleared): %s", target, readErr.Error())
|
|
}
|
|
m.sessionEvents = append([]sessions.Event{}, events...)
|
|
rows := initialTranscript()
|
|
rows = appendTranscriptRowsDedup(rows, transcriptRowsFromSessionEvents(events))
|
|
m.transcript = rows
|
|
// The rebuilt (post-rewind) transcript flushes fresh below a divider; the
|
|
// pre-rewind scrollback above it stays, as scrollback cannot be un-printed.
|
|
m.resetFlushFrontier("· rewound ·")
|
|
|
|
summary := fmt.Sprintf("Rewound to sequence %d\n%d file(s) restored, %d deleted, %d skipped.",
|
|
target, report.FilesRestored, report.FilesDeleted, len(report.Skipped))
|
|
if len(report.Skipped) > 0 {
|
|
summary += "\nskipped (not recoverable): " + strings.Join(report.Skipped, ", ")
|
|
}
|
|
return m, summary
|
|
}
|
|
|
|
// resolveRewindTarget maps a /rewind argument to a keep-through event sequence.
|
|
func (m model) resolveRewindTarget(arg string) (int, error) {
|
|
events, err := m.sessionStore.ReadEvents(m.activeSession.SessionID)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if arg == "" || arg == "latest" {
|
|
lastCheckpoint := 0
|
|
for _, ev := range events {
|
|
if ev.Type == sessions.EventSessionCheckpoint && ev.Sequence > lastCheckpoint {
|
|
lastCheckpoint = ev.Sequence
|
|
}
|
|
}
|
|
if lastCheckpoint == 0 {
|
|
return 0, fmt.Errorf("no checkpoints to rewind")
|
|
}
|
|
return lastCheckpoint - 1, nil // undo the most recent checkpoint
|
|
}
|
|
seq, err := strconv.Atoi(arg)
|
|
if err != nil || seq < 0 {
|
|
return 0, fmt.Errorf("usage: /rewind [latest|<sequence>]")
|
|
}
|
|
return seq, nil
|
|
}
|
|
|
|
func (m model) compactText(requested bool) string {
|
|
if m.compactInFlight {
|
|
return m.compactRunningText()
|
|
}
|
|
if requested && m.lastCompactResult != nil {
|
|
return compactCompleteText(*m.lastCompactResult)
|
|
}
|
|
status := commandStatusInfo
|
|
if requested {
|
|
status = commandStatusWarning
|
|
if m.lastCompactResult != nil {
|
|
status = commandStatusOK
|
|
}
|
|
if m.lastCompactError != "" {
|
|
status = commandStatusBlocked
|
|
}
|
|
}
|
|
request := m.compactRequest()
|
|
sections := []commandSection{
|
|
{
|
|
Title: "State",
|
|
Lines: []string{
|
|
"summary: " + m.compactionStatus(),
|
|
"requested: " + boolText(m.compactRequests > 0),
|
|
"model: " + displayValue(request.ModelName, "none"),
|
|
"context window: " + compactContextWindowText(request.ContextWindow),
|
|
"auto compaction: model adaptive at ~80% of context window",
|
|
fmt.Sprintf("estimated transcript: %d tokens", request.EstimatedTokens),
|
|
fmt.Sprintf("visible transcript rows: %d", request.VisibleTranscriptRows),
|
|
m.compactabilityText(request),
|
|
},
|
|
},
|
|
}
|
|
if m.lastCompactResult != nil {
|
|
sections = append(sections, commandSection{
|
|
Title: "Result",
|
|
Lines: compactResultLines(*m.lastCompactResult),
|
|
})
|
|
} else if m.lastCompactError != "" {
|
|
sections = append(sections, commandSection{
|
|
Title: "Result",
|
|
Lines: []string{
|
|
"compacted: no",
|
|
"error: " + m.lastCompactError,
|
|
},
|
|
})
|
|
} else if requested && m.sessionCompactor == nil {
|
|
sections = append(sections, commandSection{
|
|
Title: "Result",
|
|
Lines: []string{
|
|
"compacted: no",
|
|
"reason: manual compactor unavailable",
|
|
},
|
|
})
|
|
}
|
|
return renderCommandOutput(commandOutput{
|
|
Title: "Compact",
|
|
Status: status,
|
|
Sections: sections,
|
|
Hints: []string{"manual compaction affects this TUI session when a compactor is available"},
|
|
})
|
|
}
|
|
|
|
func (m model) compactRunningText() string {
|
|
return strings.Join([]string{
|
|
"Compressing session",
|
|
"Keep editing your draft; press Enter after compression finishes to send.",
|
|
m.compactAnimationLine(),
|
|
}, "\n")
|
|
}
|
|
|
|
func compactCompleteText(result CompactResult) string {
|
|
lines := []string{
|
|
"Compression complete",
|
|
"Session summary saved.",
|
|
"Ready for the next prompt.",
|
|
}
|
|
if result.Compacted && result.BeforeTokens > 0 && result.AfterTokens > 0 && result.AfterTokens < result.BeforeTokens {
|
|
lines = append(lines, fmt.Sprintf("Estimated context reduced by %s tokens.", formatContextWindow(result.BeforeTokens-result.AfterTokens)))
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func (m model) compactionStatus() string {
|
|
if m.compactInFlight {
|
|
return "compacting context"
|
|
}
|
|
if m.lastCompactResult != nil {
|
|
if m.lastCompactResult.Compacted {
|
|
return "compacted manually"
|
|
}
|
|
return "manual compactor completed without changes"
|
|
}
|
|
if m.lastCompactError != "" {
|
|
return "manual compaction failed"
|
|
}
|
|
if m.compactRequests > 0 {
|
|
return "requested, awaiting manual compactor"
|
|
}
|
|
return "not compacted"
|
|
}
|
|
|
|
func (m model) compactRequest() CompactRequest {
|
|
return CompactRequest{
|
|
SessionID: strings.TrimSpace(m.activeSession.SessionID),
|
|
ModelName: strings.TrimSpace(m.modelName),
|
|
ContextWindow: m.modelContextWindow(m.modelName),
|
|
SessionEventCount: len(m.sessionEvents),
|
|
EstimatedTokens: estimateTranscriptTokens(m.transcript),
|
|
VisibleTranscriptRows: len(m.transcript),
|
|
CompactRequests: m.compactRequests,
|
|
}
|
|
}
|
|
|
|
func (m model) compactabilityText(request CompactRequest) string {
|
|
if m.sessionCompactor == nil && !m.hasSessionBackedCompactor() {
|
|
return "compactable: no (manual compactor unavailable)"
|
|
}
|
|
if m.sessionCompactor == nil && request.SessionEventCount <= tuiCompactionPreserveLast {
|
|
return "compactable: no (not enough session history yet)"
|
|
}
|
|
if request.ContextWindow <= 0 {
|
|
return "compactable: no (unknown model context window)"
|
|
}
|
|
if request.EstimatedTokens <= 0 {
|
|
return "compactable: no (empty transcript)"
|
|
}
|
|
return "compactable: yes"
|
|
}
|
|
|
|
func (m model) hasSessionBackedCompactor() bool {
|
|
return m.sessionStore != nil && strings.TrimSpace(m.activeSession.SessionID) != ""
|
|
}
|
|
|
|
func (m model) compactActiveSession() (model, CompactResult, error) {
|
|
if m.sessionStore == nil || strings.TrimSpace(m.activeSession.SessionID) == "" {
|
|
return m, CompactResult{}, fmt.Errorf("no active session to compact")
|
|
}
|
|
beforeEvents := append([]sessions.Event{}, m.sessionEvents...)
|
|
beforeTokens := estimateTranscriptTokens(m.transcript)
|
|
plan, err := m.sessionStore.PlanCompaction(m.activeSession.SessionID, sessions.CompactionOptions{
|
|
PreserveLast: tuiCompactionPreserveLast,
|
|
MaxPromptChars: tuiCompactionMaxPromptChars,
|
|
})
|
|
if err != nil {
|
|
return m, CompactResult{}, err
|
|
}
|
|
if plan.CompactableCount == 0 {
|
|
return m, CompactResult{
|
|
Compacted: false,
|
|
BeforeTokens: beforeTokens,
|
|
AfterTokens: beforeTokens,
|
|
Summary: "not enough session history to compact yet",
|
|
}, nil
|
|
}
|
|
|
|
summary, err := m.summarizeCompactionPlan(plan)
|
|
if err != nil {
|
|
return m, CompactResult{}, err
|
|
}
|
|
if _, err := m.sessionStore.RecordCompaction(m.activeSession.SessionID, sessions.RecordCompactionInput{
|
|
Plan: plan,
|
|
Summary: summary,
|
|
}); err != nil {
|
|
return m, CompactResult{}, err
|
|
}
|
|
if meta, err := m.sessionStore.Get(m.activeSession.SessionID); err == nil && meta != nil {
|
|
m.activeSession = *meta
|
|
}
|
|
events, err := m.sessionStore.ReadRehydratedEvents(m.activeSession.SessionID)
|
|
if err != nil {
|
|
m.sessionEvents = nil
|
|
return m, CompactResult{}, fmt.Errorf("reload compacted session: %w", err)
|
|
}
|
|
m.sessionEvents = append([]sessions.Event{}, events...)
|
|
rows := initialTranscript()
|
|
rows = appendTranscriptRowsDedup(rows, transcriptRowsFromSessionEvents(events))
|
|
m.transcript = rows
|
|
m.resetFlushFrontier("· compacted ·")
|
|
|
|
return m, CompactResult{
|
|
Compacted: len(events) < len(beforeEvents)+1,
|
|
BeforeTokens: beforeTokens,
|
|
AfterTokens: estimateTranscriptTokens(m.transcript),
|
|
Summary: summary,
|
|
}, nil
|
|
}
|
|
|
|
func (m model) summarizeCompactionPlan(plan sessions.CompactionPlan) (string, error) {
|
|
if m.provider == nil {
|
|
return deterministicCompactionSummary(plan), nil
|
|
}
|
|
stream, err := m.provider.StreamCompletion(m.ctx, zeroruntime.CompletionRequest{
|
|
Messages: []zeroruntime.Message{
|
|
{Role: zeroruntime.MessageRoleSystem, Content: "Summarize compacted Zero session events for future coding context. Preserve user goals, decisions, files, tool outcomes, blockers, and exact next steps. Omit secrets and do not invent details."},
|
|
{Role: zeroruntime.MessageRoleUser, Content: plan.SummaryPrompt},
|
|
},
|
|
})
|
|
if err != nil {
|
|
return "", fmt.Errorf("summarize compacted session: %w", err)
|
|
}
|
|
collected := zeroruntime.CollectStream(m.ctx, stream)
|
|
if collected.Error != "" {
|
|
return "", fmt.Errorf("summarize compacted session: %s", collected.Error)
|
|
}
|
|
summary := strings.TrimSpace(collected.Text)
|
|
if summary == "" {
|
|
return "", fmt.Errorf("summarize compacted session: empty summary")
|
|
}
|
|
return summary, nil
|
|
}
|
|
|
|
func deterministicCompactionSummary(plan sessions.CompactionPlan) string {
|
|
lines := []string{
|
|
fmt.Sprintf("Compacted earlier session context: %d event(s) summarized, %d recent event(s) preserved.", plan.CompactableCount, plan.PreservedCount),
|
|
}
|
|
if len(plan.CompactableEvents) > 0 {
|
|
first := plan.CompactableEvents[0]
|
|
last := plan.CompactableEvents[len(plan.CompactableEvents)-1]
|
|
lines = append(lines, fmt.Sprintf("Compacted range: #%d %s through #%d %s.", first.Sequence, first.Type, last.Sequence, last.Type))
|
|
}
|
|
if len(plan.PreservedEvents) > 0 {
|
|
first := plan.PreservedEvents[0]
|
|
last := plan.PreservedEvents[len(plan.PreservedEvents)-1]
|
|
lines = append(lines, fmt.Sprintf("Preserved recent range: #%d %s through #%d %s.", first.Sequence, first.Type, last.Sequence, last.Type))
|
|
}
|
|
return strings.TrimSpace(strings.Join(lines, "\n"))
|
|
}
|
|
|
|
func compactContextWindowText(window int) string {
|
|
if window <= 0 {
|
|
return "unknown"
|
|
}
|
|
return formatContextWindow(window) + " tokens"
|
|
}
|
|
|
|
func estimateTranscriptTokens(rows []transcriptRow) int {
|
|
total := 0
|
|
for _, row := range rows {
|
|
text := row.text + "\n" + row.detail + "\n" + row.tool + "\n" + row.arg
|
|
text = strings.TrimSpace(text)
|
|
if text == "" {
|
|
continue
|
|
}
|
|
total += agent.ApproxTextTokens(text) + 4
|
|
}
|
|
return total
|
|
}
|
|
|
|
func compactResultLines(result CompactResult) []string {
|
|
lines := []string{
|
|
"compacted: " + boolText(result.Compacted),
|
|
}
|
|
if result.BeforeTokens > 0 {
|
|
lines = append(lines, fmt.Sprintf("before: %d tokens", result.BeforeTokens))
|
|
}
|
|
if result.AfterTokens > 0 {
|
|
lines = append(lines, fmt.Sprintf("after: %d tokens", result.AfterTokens))
|
|
}
|
|
if summary := strings.TrimSpace(result.Summary); summary != "" {
|
|
lines = append(lines, "summary: "+summary)
|
|
}
|
|
return lines
|
|
}
|
|
|
|
func (m model) compactAnimationLine() string {
|
|
frame := compactFrames[m.compactFrame%len(compactFrames)]
|
|
return frame + " Compressing history..."
|
|
}
|
|
|
|
func (m model) setCompactStatusRow(text string) model {
|
|
row := transcriptRow{kind: rowSystem, id: compactStatusRowID, text: text}
|
|
for i := len(m.transcript) - 1; i >= 0; i-- {
|
|
if m.transcript[i].id == compactStatusRowID {
|
|
m.transcript[i] = row
|
|
return m
|
|
}
|
|
}
|
|
m.transcript = appendTranscriptRow(m.transcript, row)
|
|
return m
|
|
}
|
|
|
|
func (m model) recordUsageEvent(modelID string, event zeroruntime.Usage) (model, []transcriptRow) {
|
|
if m.usageTracker == nil || strings.TrimSpace(modelID) == "" {
|
|
return m, nil
|
|
}
|
|
normalized, runtimeUsage, err := usage.Normalize(event)
|
|
if err != nil {
|
|
return m, []transcriptRow{{kind: rowError, text: "usage: " + err.Error()}}
|
|
}
|
|
m.lastUsage = normalized
|
|
m.lastUsageSeen = true
|
|
if _, err := m.usageTracker.Record(usage.RecordInput{
|
|
ModelID: modelID,
|
|
Usage: runtimeUsage,
|
|
Source: "tui",
|
|
}); err != nil {
|
|
if isUnpricedUsageError(err) {
|
|
m.unpricedRequests++
|
|
m.unpricedTokens += normalized.TotalTokens
|
|
return m, nil
|
|
}
|
|
return m, []transcriptRow{{kind: rowError, text: "usage: " + err.Error()}}
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
func (m model) latestUsageTokens(summary usage.Summary) int {
|
|
if m.lastUsageSeen && m.lastUsage.TotalTokens > 0 {
|
|
return m.lastUsage.TotalTokens
|
|
}
|
|
if summary.LastRecord != nil && summary.LastRecord.Usage.TotalTokens > 0 {
|
|
return summary.LastRecord.Usage.TotalTokens
|
|
}
|
|
return m.unpricedTokens
|
|
}
|
|
|
|
func isUnpricedUsageError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
message := strings.ToLower(err.Error())
|
|
for _, marker := range []string{
|
|
"unknown zero model",
|
|
"missing model input pricing rate",
|
|
"missing model output pricing rate",
|
|
"invalid model cached input pricing rate",
|
|
"no model cost tier covers",
|
|
} {
|
|
if strings.Contains(message, marker) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (m model) usageSummaryText() string {
|
|
if m.usageTracker == nil {
|
|
return "usage unavailable"
|
|
}
|
|
summary := m.usageTracker.Summary()
|
|
if summary.RecordCount == 0 && m.unpricedRequests == 0 {
|
|
return "no usage yet"
|
|
}
|
|
if summary.RecordCount == 0 {
|
|
return formatUnpricedUsage(m.unpricedRequests, m.unpricedTokens)
|
|
}
|
|
if m.unpricedRequests == 0 {
|
|
return usage.FormatSummary(summary)
|
|
}
|
|
return usage.FormatSummary(summary) + "; " + formatUnpricedUsage(m.unpricedRequests, m.unpricedTokens)
|
|
}
|
|
|
|
// cacheEfficiencyText reports the session's prompt-cache hit rate for /context so a
|
|
// user can see whether cache reads are actually saving work. A low rate across
|
|
// several turns usually means the cacheable prefix is churning (e.g. a tool list
|
|
// that shifts mid-session), so it flags that case to make slowness diagnosable.
|
|
func (m model) cacheEfficiencyText() string {
|
|
if m.usageTracker == nil {
|
|
return "usage unavailable"
|
|
}
|
|
summary := m.usageTracker.Summary()
|
|
if summary.InputTokens <= 0 {
|
|
return "n/a"
|
|
}
|
|
text := usage.FormatCacheEfficiency(summary)
|
|
if summary.RecordCount > 5 && summary.CacheHitRate() < 0.5 {
|
|
text += " — low; prefix may be unstable"
|
|
}
|
|
return text
|
|
}
|
|
|
|
func formatUnpricedUsage(requests int, tokens int) string {
|
|
requestLabel := "requests"
|
|
if requests == 1 {
|
|
requestLabel = "request"
|
|
}
|
|
return fmt.Sprintf("%d %s, %d tokens, cost unavailable", requests, requestLabel, tokens)
|
|
}
|