Repository navigation
Add a universal CLI loading state (fixes silent tj optimize / tj status) - #693
Merged
Merged
Conversation
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]>
Contributor
|
| 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]
Reviews (2): Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." | Re-trigger Greptile
# Conflicts: # tokenjam/cli/cmd_optimize.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
tj optimizeandtj statusran 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
tokenjam/cli/tj_status.py:TjCommand/TjGroup, drop-inclick.Command/click.Groupsubclasses. Every registered command inmain.pyis built from one of these — a status line renders only when a command explicitly setsstatus_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.TjCommand/TjGroup. 18 commands render a status automatically; a handful with aclick.confirm/click.promptsomewhere in their body call the primitive manually, scoped to just their silent stretch; 4 are marked structural opt-outs with a comment on why.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()wrapssuper().invoke(ctx)inwith tj_status(self.status_message, ctx)whenstatus_messageis set, no-ops otherwise.TjGroup.command_class = TjCommand(+group_class = type) makes every subcommand attached with a plain@group.command(...)— nocls=needed at that call site — aTjCommandautomatically. Four commands are attached viagroup.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 explicitcls=TjCommandeach.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.promptanywhere in its body running under an active spinner corrupts both (verified). Those commands (optimize— its--validatecost-confirmation branch;uninstall/reset— delete confirmation;onboard— usage-path/plan-tier prompts) leavestatus_messageunset and calltj_status()directly around just the genuinely silent stretch, after any prompt has resolved.optimize's wrap covers only the report fetch/build (the--validatebranch returns before reaching it).summarize prep --via .../calibrate --gohad a weaker ad hoc treatment — a staticconsole.printper phase via anon_progresscallback, leaving a permanent line per phase instead of updating in place — both now converge ontotj_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=Truewith a comment at its own@click.commandexplaining 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/Livedefaults toredirect_stdout=True, redirect_stderr=True— installing a proxy oversys.stdout/sys.stderrfor 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 bareio.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 underCliRunner— it resolves the stream's underlying binary buffer and writes straight to it, sidestepping the proxy entirely (verified with a realisticTextIOWrapper-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 bareprint(), or any future direct write, would not get it._spinner()now passesredirect_stdout=False, redirect_stderr=Falseon everyProgressconstruction, 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,onboardneeded manual placement instead of the automatic class-level wrap (interactive prompts in their bodies — see above).backfill claude-codewas not wired — it already has its ownbackfill_progressper-item counter; a secondProgressinstance active at once raises Rich'sLiveError.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 offtokenjam.cli.main.cli) is aTjCommand/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: mergingmainin landed 6 newsummarizesubcommands (prune,expire,quarantine[+ itslist/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 forcetj_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.ruff check tokenjam/andmypy tokenjam/cli/— clean.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 -cfor\x1b[→ 0).tj status: ~82s real run under a forced pty (viascript) — "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 contextunder 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
core/optimize/runner.pydispatch is untouched.backfill claude-code's andonboard's existing per-item counters are unchanged in shape, only reused via the same_spinner()construction.