Skip to content

Add a universal CLI loading state (fixes silent tj optimize / tj status) - #693

Merged
anshss merged 7 commits into
mainfrom
cli-loading-state
Aug 4, 2026
Merged

anshss merged 7 commits into
mainfrom
cli-loading-state

Conversation

@anshss

@anshss anshss commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

tj optimize and tj status ran in total silence for 96s and 48s on a real corpus. This adds one central choke point so every command's loading state goes through the same class, and any future command gets the behavior for free.

Summary

  • New tokenjam/cli/tj_status.py: TjCommand/TjGroup, drop-in click.Command/click.Group subclasses. Every registered command in main.py is built from one of these — a status line renders only when a command explicitly sets status_message; there is no timing heuristic anywhere.
  • tokenjam/cli/backfill_progress.py (the existing progress primitive, previously wired into 4 call sites) gains a third shape, phase_status, for multi-phase stretches, and a shared _spinner() factory so the whole loading UI is a one-file edit.
  • 39 command files updated to route through TjCommand/TjGroup. 18 commands render a status automatically; a handful with a click.confirm/click.prompt somewhere in their body call the primitive manually, scoped to just their silent stretch; 4 are marked structural opt-outs with a comment on why.
  • A registry guard test (tests/unit/test_cli_status_registry.py) partitions the entire live command graph into four buckets and asserts every command lands in exactly one — a new command that isn't classified fails the test.

Architecture: one choke point, automatic at the Click layer

TjCommand.invoke() wraps super().invoke(ctx) in with tj_status(self.status_message, ctx) when status_message is set, no-ops otherwise. TjGroup.command_class = TjCommand (+ group_class = type) makes every subcommand attached with a plain @group.command(...) — no cls= needed at that call site — a TjCommand automatically. Four commands are attached via group.add_command(...) instead of the decorator shortcut (relearn's write verbs + cost-proposal verbs), which does not auto-inherit the command class, so those got an explicit cls=TjCommand each.

Why some commands can't use the automatic wrap: Rich's spinner is a live, auto-refreshing display. A command with a click.confirm/click.prompt anywhere in its body running under an active spinner corrupts both (verified). Those commands (optimize — its --validate cost-confirmation branch; uninstall/reset — delete confirmation; onboard — usage-path/plan-tier prompts) leave status_message unset and call tj_status() directly around just the genuinely silent stretch, after any prompt has resolved. optimize's wrap covers only the report fetch/build (the --validate branch returns before reaching it). summarize prep --via ... / calibrate --go had a weaker ad hoc treatment — a static console.print per phase via an on_progress callback, leaving a permanent line per phase instead of updating in place — both now converge onto tj_status_stream (phase_status), one live line replaced per phase.

Opt-outs and why each is exempt

  • mcp — stdio JSON-RPC; any stray stdout write corrupts the protocol. The file has no print statement at all, deliberately.
  • serve — prints its own banner then blocks forever inside uvicorn; there's no "done" for a transient status to erase on.
  • statusline — invoked by Claude Code after every turn, reads stdout directly into the terminal status line; must stay near-instant and byte-exact.
  • session-end — best-effort, called on shell exit, intentionally silent unless -v.

Each is no_status=True with a comment at its own @click.command explaining why, so it reads as a considered decision rather than something a later pass "fixes".

A real bug found and fixed along the way

Rich's Progress/Live defaults to redirect_stdout=True, redirect_stderr=True — installing a proxy over sys.stdout/sys.stderr for the display's lifetime that routes ANY raw write on either stream through whichever console the spinner renders to. Under --json, that console is stderr. Verified empirically with a synthetic repro (a bare io.StringIO-backed stream) that this reroutes a raw stdout write into stderr, ANSI-mangled.

Turns out click.echo() specifically isn't at risk of this in a real terminal or under CliRunner — it resolves the stream's underlying binary buffer and writes straight to it, sidestepping the proxy entirely (verified with a realistic TextIOWrapper-backed stream, both with and without the fix). But that protection is Click's own implementation detail, not a contract this module should lean on — a bare print(), or any future direct write, would not get it. _spinner() now passes redirect_stdout=False, redirect_stderr=False on every Progress construction, removing the whole class of risk at zero cost: nothing here needs Rich to intercept writes on a stream it isn't rendering to.

Corrections to the audited slow-command list

  • optimize, uninstall, reset, onboard needed manual placement instead of the automatic class-level wrap (interactive prompts in their bodies — see above).
  • backfill claude-code was not wired — it already has its own backfill_progress per-item counter; a second Progress instance active at once raises Rich's LiveError.
  • Everything else in the brief matched: status, doctor (+ --repair), upgrade, export, ping, context, tokenmaxx, quota-audit, route export, stop, cost (+ --compare), backfill status|codex|langfuse|helicone|otlp, report --trim|--reuse, summarize list --recursive, summarize prep --via claude-p|api, summarize calibrate --go.

Tests / Verification

  • tests/unit/test_cli_status_registry.py (new): every registered command (walked recursively off tokenjam.cli.main.cli) is a TjCommand/TjGroup, and the four buckets (auto status / manually-scoped / structural opt-out / deliberately none) partition the graph exactly — set equality, not a superset check. Confirmed this actually catches a regression: merging main in landed 6 new summarize subcommands (prune, expire, quarantine [+ its list/show], restore) from a concurrent branch, and the test failed until they were classified.
  • tests/integration/test_cli.py: two new tests (optimize --json, status --json) that force tj_status's consoles into terminal mode — CliRunner's captured streams are never a tty, so without this the spinner never activates and a byte-clean-stdout assertion would pass vacuously either way — then assert stdout is exactly the JSON payload and confirm (by inspecting the forced console's own buffer) that the spinner really did run.
  • Existing targeted suite (551 tests: backfill, onboard, uninstall, reset, optimize, summarize, relearn, CLI palette/entrypoint, status/quota/context, quickstart) — all pass.
  • ruff check tokenjam/ and mypy tokenjam/cli/ — clean.
  • Dogfooded against a real ~2GB / 5,201-transcript Claude Code corpus (throwaway HOME, backfilled read-only from the real ~/.claude/projects):
    • tj optimize: ~148s real run. Piped to a file: zero ANSI escape codes in the output (grep -c for \x1b[ → 0).
    • tj status: ~82s real run under a forced pty (via script) — "Scanning your sessions…" spinner visible from the start, cursor hidden then restored, final sequence is a clean erase (\x1b[?25h\x1b[1A\x1b[2K), no residue.
    • tj context under a forced pty: spinner correctly interleaves with real printed report content (Rich's Live "print above" behavior), erases cleanly on exit.
    • tj alerts (fast, no status) under a forced pty: instant, no spinner escape codes at all.

What's NOT in this PR

  • No analyzer/runner behavior changed — core/optimize/runner.py dispatch is untouched.
  • backfill claude-code's and onboard's existing per-item counters are unchanged in shape, only reused via the same _spinner() construction.

anshss and others added 6 commits August 4, 2026 20:07
tj optimize and tj status ran in total silence for 96s and 48s on a real
corpus -- the classic "is this hung?" complaint. A progress primitive
(backfill_progress.py) already existed but was wired into only four call
sites, since nothing forced a new command to consider it.

tokenjam/cli/tj_status.py adds TjCommand/TjGroup, drop-in click.Command/
click.Group subclasses that wrap invocation centrally: every command routes
through the same class, and a status line renders only when the command
explicitly sets status_message (no timing heuristic anywhere). backfill_
progress.py gains a third shape, phase_status, for multi-phase stretches,
and every Progress construction now disables Rich's default stdout/stderr
redirection -- Live redirects both by default, which can reroute a raw
stdout write through whichever console the spinner renders to (verified:
under --json, that console is stderr).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Every leaf command gets cls=TjCommand and every group gets cls=TjGroup --
including four commands attached via group.add_command() rather than the
@group.command() shortcut (relearn's write verbs + cost-proposal verbs),
which does not auto-inherit the command class the way the decorator does.

Commands that do real multi-second work with nothing interactive in their
body declare a status_message and render automatically: status, doctor,
upgrade, export, ping, context, tokenmaxx, quota-audit, stop, cost, route
export, report, summarize list, and backfill's status/codex/langfuse/
helicone/otlp subcommands (backfill claude-code keeps its own existing
per-item backfill_progress counter instead -- a second Progress instance
active at once raises Rich's LiveError).

Four commands are marked no_status=True with a comment explaining why a
status must never be wired in even later: mcp (stdio JSON-RPC -- any stray
stdout write corrupts the protocol), serve (prints its own banner then
blocks forever in uvicorn), statusline (every-turn, must stay near-instant),
session-end (best-effort, intentionally silent unless -v).

Everything else (traces, alerts, tools, budget, the read-only policy/
pricing/proxy/loop/rules/relearn subcommands, etc.) gets the class with no
status_message -- a deliberate "no", not an oversight, per the registry
guard test in the next commit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
optimize, uninstall, reset, and onboard each have a click.confirm/prompt
somewhere in their body (optimize's --validate cost gate; uninstall/reset's
delete confirmation; onboard's usage-path and plan-tier prompts). Rich's
spinner is a live, auto-refreshing display -- active at the same time as a
blocking stdin read, the two collide on the same terminal region. All four
leave status_message unset and call tj_status directly around just the
silent stretch, after any prompt has already resolved:

- optimize wraps only the report fetch/build (the --validate branch returns
  before reaching it, so its confirm() is never live under a spinner).
- uninstall/reset wrap only the teardown, after the delete confirmation.
- onboard wraps its Codex backfill (previously silent) and its --verify
  poll (previously a static "Polling for up to Ns..." line with no
  indication anything was happening for the whole wait).

summarize prep --via ... and calibrate --go had a weaker ad hoc treatment:
a bare console.print per phase via an on_progress callback, so each phase
left a permanent line instead of updating in place. Both now converge onto
tj_status_stream (phase_status) -- one live line, replaced per phase,
erased on exit -- reusing the same on_progress hook already threaded
through summarize_via / run_calibration.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
test_cli_status_registry.py partitions the ENTIRE registered command graph
into four buckets (auto status, manually-scoped status, structural opt-out,
deliberately none) and asserts every command is a TjCommand/TjGroup and
lands in exactly one bucket. A newly added command that isn't classified
fails the set-equality assertion -- the guard this whole mechanism exists
for: a new command cannot silently ship with no consideration.

test_cli.py gains two tests that force tj_status's consoles into terminal
mode (CliRunner's captured streams are never a tty, so without this the
spinner would never activate and a byte-clean-stdout assertion would pass
vacuously either way) and confirm --json stdout is exactly the JSON
payload -- both for optimize (manually-scoped tj_status) and status
(class-level status_message), covering both wiring shapes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Merging main in brought six new summarize subcommands (prune, expire,
quarantine [group] + its list/show, restore) landed by a concurrent branch.
The registry guard test correctly failed on them -- exactly the regression
it exists to catch -- so this adds each to its bucket: quarantine is a
group (nests under summarize's TjGroup automatically), the rest are fast
single-file operations with no declared status.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@anshss
anshss requested a review from anilmurty as a code owner August 4, 2026 14:43
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR centralizes CLI loading-state behavior through shared Click command classes and Rich progress primitives while preserving clean JSON output and explicitly excluding interactive or protocol-sensitive commands.

  • Adds TjCommand and TjGroup as the common command-construction path.
  • Extends the shared progress implementation with reusable transient and multi-phase status displays.
  • Classifies the complete registered command graph and tests status routing, opt-outs, and JSON stream cleanliness.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
tokenjam/cli/tj_status.py Introduces the centralized Click command/group classes, status routing, and JSON-aware console selection without an accepted correctness issue.
tokenjam/cli/backfill_progress.py Consolidates Rich progress construction, disables stream redirection, and adds a multi-phase status context manager.
tokenjam/cli/cmd_optimize.py Scopes the new status display to the non-interactive report-building stretch, leaving the validation prompt outside it.
tokenjam/cli/cmd_summarize.py Replaces accumulating phase messages with a shared updating status line while preserving JSON-mode silence.
tests/unit/test_cli_status_registry.py Enforces central command classes and an exhaustive, mutually exclusive status classification for the live command graph.
tests/integration/test_cli.py Adds forced-terminal coverage proving status activation while JSON stdout remains parseable and free of terminal escapes.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  CLI[TjGroup CLI] --> Command[TjCommand.invoke]
  Command --> HasStatus{status_message set?}
  HasStatus -->|No| Callback[Invoke command callback]
  HasStatus -->|Yes| JsonMode{JSON requested?}
  JsonMode -->|Yes| Stderr[Render transient status on stderr]
  JsonMode -->|No| Stdout[Render transient status on stdout]
  Stderr --> Callback
  Stdout --> Callback
  Manual[Interactive or multi-phase command] --> Scoped[tj_status / tj_status_stream]
  Scoped --> Progress[Shared backfill_progress primitive]
Loading

Reviews (2): Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." | Re-trigger Greptile

# Conflicts:
#	tokenjam/cli/cmd_optimize.py
@anshss
anshss merged commit 4692ea7 into main Aug 4, 2026
6 checks passed
@anilmurty
anilmurty deleted the cli-loading-state branch September 18, 2026 21:02
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