Repository navigation
Inbox redesign: monthly savings basis, tabbed layout, auto-computed cost advisories - #525
Conversation
… resend adapter The Review inbox needs numbers on an explicit "/ mo" projected basis, kept separate from the window-scoped figures Overview/Optimize already compare tiles against. Relearn clusters and cost proposals now carry their own estimated_monthly_usd/estimated_monthly_tokens fields (relearn extrapolates occurrences over the corpus's own observed timespan; cost proposals reuse downsize's existing 30-day projection or a generic window-days extrapolation for every other analyzer). Relearn also derives a blended $/token rate from the cluster's own sessions when one is inspectable, so a priceable figure can lead instead of falling back to tokens-only. Cost-proposal recomputation previously ran only on the manual refresh endpoint, so a fresh install's cost-advisories tab stayed on "never_run" indefinitely. tj serve now schedules the same startup-kick + 6h-interval job the relearn detector already has, and a failed recompute records and surfaces its error instead of silently degrading to an empty list. The resend (context re-send) analyzer had real recoverable savings but no cost-proposal adapter and was excluded from COST_ANALYZERS; it now has one, alongside a comment on why summarize deliberately stays out (it owns a separate curate/diff review surface this single-card shape can't represent). Co-Authored-By: Claude <[email protected]>
Rebuilds the Review inbox around three tabs (Recurring mistakes / Cost advisories / Applied) instead of one long stacked page, matching the approved mockups: - Two headline stat tiles: estimated recoverable per month (dollars when at least half the open items are priceable, tokens otherwise) and verified saved. - Human-readable fix-type badges instead of internal rung/analyzer jargon (PROMPT TWEAK / CACHE BREAKPOINT / GUARDRAIL for relearn; DOWNSIZE / CACHE / TRIM / etc for cost advisories), with the internal detail kept in a tooltip. - Items sort by est./mo descending within each tab; past 8 open items the remainder collapses into one expandable row with bulk dismiss/mark-applied actions, so a long tail of small fixes reads as one bundled decision instead of dozens of peers. - The cost-advisories tab shows an inline warning when the last scheduled refresh failed, instead of reading a stale/empty list as "nothing to report." - Applied items always show their estimate labeled "est.", never a "verified" chip — the post-hoc verification pass that would produce a real measured figure was already removed from this codebase for making unsupportable realized-savings claims, and the dead verdict/ledger scaffolding that used to render an inert placeholder here is removed too. Plan-tier dollar suppression, the per-item Approve/Apply modal, bulk dismiss, and localStorage dismissal keys all carry over unchanged. Co-Authored-By: Claude <[email protected]>
Follows the Review inbox restructure: component/string fixtures now match the tabbed layout, monthly-basis figures, and renamed row/card components. Co-Authored-By: Claude <[email protected]>
…ied tile Adds unit coverage the prior commits landed without: relearn's corpus-window extrapolation and blended dollar rate (including the degrade-on-query- failure and no-conn paths), the generic vs. downsize-native monthly extrapolation split in cost_proposals.py, the resend adapter's advisory shape, and recompute_cost_proposals' locking + error-surfacing (a failed recompute records its error without wiping the last good result, and clears on the next success). Also updates the UI regression fixtures for the "Fixes applied" tile's final wording (the founder revised behavioral requirement #7 mid-implementation to explicitly ban any "verified" claim and specify the exact sub-line copy) and drops a genuinely-unused pre-existing import ruff flagged in the same file. Co-Authored-By: Claude <[email protected]>
|
| Filename | Overview |
|---|---|
| tokenjam/core/optimize/relearn_store.py | Adds write_cost_proposals_error/clear_cost_proposals_error and extends read_cost_proposals to surface error state. write_cache still only preserves cost_proposals/cost_computed_at, silently clearing any recorded cost-proposals error on each relearn detector run (flagged in prior review). |
| tokenjam/core/optimize/cost_proposals.py | Adds locking, _resend_to_proposals, trigger_background_cost_recompute, and generic monthly-extrapolation post-pass. Backend factory failures in the background job's outer try/except are swallowed without recording, leaving the tab at never_run instead of error. |
| tokenjam/core/optimize/analyzers/relearn.py | Adds corpus-window extrapolation, blended $/token rate lookup, and monthly fields on RelearnCluster/RelearnFinding. Correct design; estimated_monthly_tokens uses int=0 default vs estimated_monthly_usd=None asymmetry (flagged in prior review). |
| tokenjam/ui/index.html | Major inbox redesign: tabbed layout, sort-by-monthly-tokens, collapsible tail, human-readable badges, honest Applied tab. appliedEstimate() for cost items reads estimated_recoverable_* (window-scoped) rather than estimated_monthly_* (flagged in prior review thread). |
| tokenjam/api/routes/relearn.py | Extends cost-proposals endpoint with computing/error/degraded fields and adds framing to relearn endpoint. Status FSM logic is correct; proposals list guard now correctly requires cost_computed_at. |
| tokenjam/cli/cmd_serve.py | Adds cost-proposals 6h-interval scheduled job and startup kick, mirroring the relearn detector's existing pattern correctly. |
| tokenjam/core/optimize/relearn_apply.py | Snapshots estimated_monthly_usd/tokens onto the apply record at approval time — clean point-in-time copy, no live re-measurement. |
| tokenjam/core/optimize/relearn_proposals.py | Adds estimated_monthly_usd/tokens to APPLY_CLUSTER_FIELDS and applies backfill_legacy_monthly_fields to cached proposals at read time. |
Sequence Diagram
sequenceDiagram
participant Serve as tj serve
participant Scheduler
participant BgJob as cost-proposals-recompute (thread)
participant RecomputeFn as recompute_cost_proposals
participant Store as relearn_store (relearn_cache.json)
participant API as GET /relearn/cost-proposals
participant UI as Review Inbox (browser)
Serve->>Scheduler: "add_job(_cost_proposals_job, interval=6h)"
Serve->>BgJob: _cost_proposals_job() [startup kick]
BgJob->>BgJob: backend_factory() → DuckDBBackend
BgJob->>RecomputeFn: recompute_cost_proposals(db, config)
RecomputeFn->>RecomputeFn: acquire _COST_LOCK + set _COST_COMPUTING
RecomputeFn->>RecomputeFn: build_report → cost_proposals_from_report → _with_monthly_extrapolation
alt success
RecomputeFn->>Store: write_cost_proposals(proposals) + clear_cost_proposals_error()
else failure
RecomputeFn->>Store: write_cost_proposals_error(exc)
end
RecomputeFn->>RecomputeFn: clear _COST_COMPUTING + release _COST_LOCK
UI->>API: GET /relearn/cost-proposals
API->>Store: read_cost_proposals()
Store-->>API: cost_proposals, cost_computed_at, cost_proposals_error?
API-->>UI: status, proposals, rollup, framing, degraded, last_error
Reviews (4): Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." | Re-trigger Greptile
| if (Number.isNaN(then)) return ''; | ||
| const days = Math.floor((Date.now() - then) / 86400000); | ||
| if (days <= 0) return 'today'; | ||
| return days === 1 ? '1 day ago' : days + ' days ago'; | ||
| } |
There was a problem hiding this comment.
Applied tab: cost items show window-scoped estimate, not monthly
appliedEstimate returns rec.estimated_recoverable_usd / rec.estimated_recoverable_tokens for kind === 'cost', while relearn items return the monthly snapshot from rec.verify. This is because cost_apply.mark_applied only persists estimated_recoverable_* — the new monthly fields are never written to the ledger record. At DEFAULT_COST_WINDOW_DAYS = 30, the two figures are numerically identical (scale = 1.0), so the Applied tab is correct today. But if anyone changes the daemon window, cost items on the Applied tab will silently show the old window-scoped figure while the open Advisories tab shows the monthly one.
The fix is to also persist estimated_monthly_usd / estimated_monthly_tokens in CostAppliedRecord / mark_applied, then read rec.estimated_monthly_usd in appliedEstimate.
Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/ui/index.html
Line: 7990-7994
Comment:
**Applied tab: cost items show window-scoped estimate, not monthly**
`appliedEstimate` returns `rec.estimated_recoverable_usd` / `rec.estimated_recoverable_tokens` for `kind === 'cost'`, while relearn items return the monthly snapshot from `rec.verify`. This is because `cost_apply.mark_applied` only persists `estimated_recoverable_*` — the new monthly fields are never written to the ledger record. At `DEFAULT_COST_WINDOW_DAYS = 30`, the two figures are numerically identical (scale = 1.0), so the Applied tab is correct today. But if anyone changes the daemon window, cost items on the Applied tab will silently show the old window-scoped figure while the open Advisories tab shows the monthly one.
The fix is to also persist `estimated_monthly_usd` / `estimated_monthly_tokens` in `CostAppliedRecord` / `mark_applied`, then read `rec.estimated_monthly_usd` in `appliedEstimate`.
How can I resolve this? If you propose a fix, please make it concise.| """The occurrences-per-day -> per-30-days multiplier. 1.0 (no | ||
| extrapolation) when the window is unknown or degenerate — never invent a | ||
| multiplier from missing data (behavioral requirement #1).""" |
There was a problem hiding this comment.
Asymmetric sentinels between
estimated_monthly_tokens and estimated_monthly_usd
estimated_monthly_tokens defaults to 0 (int), while estimated_monthly_usd defaults to None. Code that checks if cluster.estimated_monthly_usd is None correctly detects "no rate available", but estimated_monthly_tokens = 0 looks like a computed zero rather than "no data". build_proposals always overwrites both, so nothing breaks today. The asymmetry could mislead a future serialisation round-trip or display path that checks for None to mean "not set". Changing the default to None (and updating the type annotation accordingly) would be consistent with the USD field and with RelearnFinding.estimated_monthly_tokens.
Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/optimize/analyzers/relearn.py
Line: 888-890
Comment:
**Asymmetric sentinels between `estimated_monthly_tokens` and `estimated_monthly_usd`**
`estimated_monthly_tokens` defaults to `0` (int), while `estimated_monthly_usd` defaults to `None`. Code that checks `if cluster.estimated_monthly_usd is None` correctly detects "no rate available", but `estimated_monthly_tokens = 0` looks like a computed zero rather than "no data". `build_proposals` always overwrites both, so nothing breaks today. The asymmetry could mislead a future serialisation round-trip or display path that checks for `None` to mean "not set". Changing the default to `None` (and updating the type annotation accordingly) would be consistent with the USD field and with `RelearnFinding.estimated_monthly_tokens`.
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
…l dollar rule
Real-data validation against a live 40-day store surfaced three gaps:
Sort order wasn't savings-descending on either tab. sortByEstMonthly ranked
by dollars the instant ANY item in the list carried one, leaving every other
(tokens-only) item tied at rank 0 and rendered in adapter-insertion order.
Tokens are the one figure every item on this page carries, priced or not, so
ranking now uses estimated_monthly_tokens uniformly; dollars stay a per-item
display preference (estMonthlyLine), decoupled from ranking, since comparing
a priced item against a tokens-only one for ordering purposes would mean
inventing a conversion rate.
Large token counts rendered ugly at billion scale ("11268.0M tok" instead of
"11.3B tok") — fmtTokens gets a billion-scale branch above the existing
million/thousand ones.
The collapsed long-tail row's combined figure used the same "dollars if ANY
item has one" rule as the old sort, understating a mostly-tokens-only tail
as a tiny dollar sum; it now uses the same priceable-majority rule the
headline stat tile already applies.
Co-Authored-By: Claude <[email protected]>
…ache The founder's headline "Model over-sizing" card had a genuinely computable dollar figure (its own evidence text showed "$1.15 per 30 days") but the card's headline still rendered tokens. The adapter code that sets estimated_monthly_usd is correct and was verified to match its own evidence text exactly for a fresh recompute; the discrepancy traces to a cost-proposal cache written before the monthly-basis fields existed on CostProposal, whose JSON simply lacks those keys. Reading a stale entry back would otherwise show a tokens-only headline for a priceable item indefinitely, until the next successful scheduled recompute (up to 6h away). list_cost_proposals now backfills estimated_monthly_usd/estimated_monthly_tokens from the window-basis fields (which every cache entry, old or new, always carries) on read, mirroring the existing defensive proposal-ID stamping this same function already does for the identical reason: a stale cache resolves correctly without forcing a recompute. A fresh proposal (which always has these fields set via _with_monthly_extrapolation) is never touched. Co-Authored-By: Claude <[email protected]>
…e only Deliberate product decision: the Review inbox's dollar figures are a savings/waste comparison, not a billed-amount claim, so this page now shows them unconditionally rather than falling back to tokens for a subscription-dominant account the way every other dollar figure in the app does. Verified against a real account (87% subscription-billed, Max 20x plan): the API payload already carried correct estimated_monthly_usd values for every priced item, but the page was needlessly gating them behind the same plan-tier suppression rule that governs Overview/Optimize/etc. ReviewInboxView now always passes suppressed=false to every dollar-first decision point on the page (the two stat tiles, each row/card, the collapsed-tail combined figure, and the Applied tab). dollarsSuppressed() itself is untouched and still governs every other surface in the app. One documented exception survives the carve-out: the resend/TRIM card is a structural token-share measurement, not a savings claim (its own evidence text says so), so it stays tokens-only even though its own estimated_monthly_usd is a real, non-null number — routed through a small shared helper so the exclusion can't be bypassed at any of the several call sites that read a dollar figure. Verified end-to-end against a live 40-day store via headless browser: the two "Model over-sizing" cards that previously showed tokens-only now show their dollar figures ($0.76 and $0.36 per month), the posthog MCP removal shows $396.00, the resend card stays token-only, and the headline tile shows $525.40. Co-Authored-By: Claude <[email protected]>
ruff 0.16.0 (released after main's last verified-green CI run) expanded ruff's own default lint rule set. This project has no [tool.ruff.lint] select/ignore block, so it always runs whatever the installed ruff version's defaults are. An unpinned `ruff` in the dev extras meant CI's `pip install -e ".[dev,mcp]"` picked up 0.16.0 the moment it hit PyPI and started flagging roughly 470 pre-existing patterns across the whole codebase that 0.15.x never checked, breaking every PR's Lint step (the first step in the test job, before Type check or Run tests) for a reason with zero relation to that PR's own diff. Pinned to the 0.15.x line, verified clean against the exact version (0.15.22) CI last ran green with on main. Bulk-fixing or re-triaging the ~470 newly-flagged patterns is out of scope here; that's a deliberate future ruff bump, not a side effect of an unrelated PR. Co-Authored-By: Claude <[email protected]>
# Conflicts: # pyproject.toml
Summary
Restructures the Review inbox around three tabs (Recurring mistakes / Cost advisories / Applied) instead of one long stacked page, and puts every savings figure on an explicit "estimated per month" basis instead of a raw scanned-window total.
estimated_monthly_usd/estimated_monthly_tokensalongside the existing window-scoped fields (Overview/Optimize tiles keep reading the window fields unchanged, so nothing there is affected). Relearn extrapolates occurrences over the corpus's own observed timespan since it scans unbounded history; cost proposals reuse the downsize analyzer's own 30-day projection where it exists, or a generic30/window_daysextrapolation otherwise.recompute_cost_proposals()previously only ran on the manual refresh endpoint, so a fresh install's Cost-advisories tab stayed onnever_runindefinitely.tj servenow schedules the same startup-kick + 6h-interval job the relearn detector already has, and a failed recompute records and surfaces its error (a small inline warning) instead of silently degrading to an empty list.resendcost-proposal adapter. The context re-send analyzer had real recoverable savings but no adapter and was excluded fromCOST_ANALYZERS; it now has one.summarizestays out deliberately (it owns its own curate/diff review surface), with a comment explaining why.VERIFIEDchip.Test plan
pytest tests/unit/ tests/synthetic/ tests/agents/ tests/integration/— 3496 passed, 1 skippedruff check tokenjam/— all checks passedmypy tokenjam/— no issues found in 217 source filestj serveagainst a throwaway config, confirmedGET /api/v1/relearn/proposalsandGET /api/v1/relearn/cost-proposalsboth return 200 with the newframing/degraded/last_errorfields andstatus: "computing"immediately on startup (the scheduled job's startup kick firing as expected)🤖 Generated with Claude Code