Skip to content

Inbox redesign: monthly savings basis, tabbed layout, auto-computed cost advisories - #525

Merged
anilmurty merged 9 commits into
mainfrom
inbox-redesign
Jul 23, 2026
Merged

anilmurty merged 9 commits into
mainfrom
inbox-redesign

Conversation

@anshss

@anshss anshss commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

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.

  • Monthly savings basis. Relearn clusters and cost proposals now carry estimated_monthly_usd/estimated_monthly_tokens alongside 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 generic 30/window_days extrapolation otherwise.
  • Blended dollar rate for relearn. When a cluster's own sessions carry priced spans, a blended $/token rate is derived from them (never invented) so the row can lead with dollars instead of falling back to tokens-only; the derivation is inspectable via a tooltip naming the models it came from.
  • Auto-computed cost advisories. recompute_cost_proposals() previously only ran 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 (a small inline warning) instead of silently degrading to an empty list.
  • resend cost-proposal adapter. The context re-send analyzer had real recoverable savings but no adapter and was excluded from COST_ANALYZERS; it now has one. summarize stays out deliberately (it owns its own curate/diff review surface), with a comment explaining why.
  • UI restructure. Two headline stat tiles (estimated recoverable / mo, and fixes applied), human-readable fix-type badges instead of internal rung/analyzer jargon, sort-by-savings with a collapsible long tail past 8 open items (bulk dismiss / mark-applied for the collapsed set), and an honest "Fixes applied" tile that never claims verification — the post-hoc measurement pass that would produce a real verified figure was already removed from this codebase earlier for making unsupportable realized-savings claims, so nothing here fakes a VERIFIED chip.
  • Plan-tier dollar suppression, the per-item Approve/Apply modal, bulk dismiss, and localStorage dismissal keys all carry over unchanged.

Test plan

  • pytest tests/unit/ tests/synthetic/ tests/agents/ tests/integration/ — 3496 passed, 1 skipped
  • ruff check tokenjam/ — all checks passed
  • mypy tokenjam/ — no issues found in 217 source files
  • Manual boot smoke test: tj serve against a throwaway config, confirmed GET /api/v1/relearn/proposals and GET /api/v1/relearn/cost-proposals both return 200 with the new framing/degraded/last_error fields and status: "computing" immediately on startup (the scheduled job's startup kick firing as expected)

🤖 Generated with Claude Code

anshss and others added 4 commits July 23, 2026 20:54
… 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]>
@anshss
anshss requested a review from anilmurty as a code owner July 23, 2026 15:34
@greptile-apps

greptile-apps Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR restructures the Review inbox around three tabs (Recurring mistakes / Cost advisories / Applied), puts every savings figure on an explicit per-month basis, auto-schedules the cost-proposals recompute job on tj serve startup and at 6-hour intervals (matching the existing relearn detector), adds a resend adapter to COST_ANALYZERS, and surfaces recompute failures via a degraded/last_error field instead of silently showing an empty tab.

  • Monthly-basis fields: RelearnCluster and CostProposal gain estimated_monthly_usd/estimated_monthly_tokens, extrapolated from the corpus's own observed timespan (_corpus_window_days) or from the analyzer's existing 30-day projection (downsize). The existing window-scoped estimated_recoverable_* fields are unchanged; Overview/Optimize tiles keep reading them.
  • UI redesign: Tabbed layout, sortByEstMonthly (tokens-first uniform sort key), collapsible long-tail past 8 items with bulk dismiss / mark-applied, human-readable fix-type badges, and an honest Applied tab that labels snapshots as est. with no verified chip.
  • Error surfacing: write_cost_proposals_error / clear_cost_proposals_error new store helpers; recompute_cost_proposals now records failures and clears them on success; the API exposes status: "error" for a fresh install where every recompute has failed.

Confidence Score: 3/5

Safe to merge with awareness of two open issues from prior reviews: the relearn detector job silently clears recorded cost-proposals error state each run, and the Applied tab reads window-scoped estimates for cost items rather than the new monthly ones.

Two issues carried over from previous review rounds remain unaddressed. write_cache in relearn_store only preserves cost_proposals and cost_computed_at when the relearn detector fires — cost_proposals_error is silently dropped, making the degraded banner disappear at the next detector tick rather than persisting until a successful recompute clears it. Additionally, appliedEstimate() reads estimated_recoverable_usd/tokens (window-scoped) for cost applied records rather than the new estimated_monthly_* fields; at DEFAULT_COST_WINDOW_DAYS=30 the numbers are identical today, but the mismatch will surface silently if the window ever changes.

tokenjam/core/optimize/relearn_store.py (write_cache does not forward cost_proposals_error on relearn detector writes) and tokenjam/ui/index.html (appliedEstimate reads estimated_recoverable_* instead of estimated_monthly_* for cost-kind applied records).

Important Files Changed

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
Loading

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

Comment thread tokenjam/ui/index.html
Comment on lines +7990 to +7994
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';
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Comment on lines +888 to +890
"""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)."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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!

anshss and others added 5 commits July 23, 2026 21:32
…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]>
@anilmurty
anilmurty merged commit 1b7045b into main Jul 23, 2026
5 checks passed
@anilmurty
anilmurty deleted the inbox-redesign branch July 23, 2026 22:53
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.

2 participants