From b6930210bd38b9fc926732f0abae67f83f96628e Mon Sep 17 00:00:00 2001 From: Daniel Demmel Date: Sat, 5 Dec 2026 01:23:26 +0000 Subject: [PATCH 1/5] Show session peak context, and keep a Thinking pair's tokens out of the next row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #414. Session and page totals in the minimal theme now read `183k peak · 283k new · 155k out` instead of `X in · Y out`. The old "in" summed every turn's cache read, which counts the same context again on each turn, so it grew with how long a session ran rather than how full it got. Peak is the largest context one main-thread turn sent (sub-agents have their own windows); new is uncached input plus cache creation. The transcript header and the index's session rows show all three; project and archive lines show new · out. - Peak is computed beside the totals in compute_session_data and _collect_session_info, and persisted in a new sessions column (migration 019). The migration also zeroes every project's message total, so the next run refreshes each project in full from the cached entries (no re-parse) and fills the column; on a real 16-session archive that run took 0.6s. NULL means unknown (Codex, which reports only cumulative totals, or an archived session) and isn't shown. - The index's session rows never showed tokens: none of the builders passed them. All four (cached, archived, fallback, date window) and the Codex walker now pass numeric fields; minimal helpers read numbers instead of parsing token strings. - page_stats labelled cache creation `Cache Create:`, which the minimal header's parser didn't recognise. It now says `Cache Creation:` like every other summary. This changes the classic theme's paginated page header text; no classic snapshot covers it and no message markup moves. Gutter fixes: - A pair's first-half gutter hangs into its last half. With #414's two token lines a Thinking + Assistant pair's gutter is four lines, and on a short pair the output figure printed over the next row's time (237 overlaps on a real archive, against 20 near-misses on main before #414). The renderer now hands the first half's token usage to the last half (TemplateMessage.pair_token_usage), and the wide layout shows the figures in the last half's gutter, one line down, growing that row if needed, as P7c does for the lane tag. A redacted (empty) thought keeps one line of gutter height so the figures clear its role. The same archive now sweeps clean at both widths in all three branch modes. - At phone width the two figures sit on one line; the output gets its `·` back. - Tidy-ups: the unused mn_compact_tokens global and one-line compact_token_usage are gone, the tooltip is computed once per message (a minimal-only macro, so classic markup is untouched), the tokens.css comment keeps its role-icon note, and a turn that only read the cache shows `98k+0` rather than a bare total that looked uncached. Docs: css-classes.md, the migration list in application_model.md, and a token-figures section in docs/themes.md. Co-Authored-By: Claude Opus 5.5 --- claude_code_log/cache.py | 23 +- claude_code_log/converter.py | 64 +++++- claude_code_log/html/minimal_theme.py | 96 ++++----- .../html/templates/components/minimal/dag.css | 2 +- .../templates/components/minimal/layout.css | 52 +++++ .../templates/components/minimal/tokens.css | 3 +- .../templates/components/minimal/tokens.html | 13 ++ .../html/templates/transcript.html | 6 +- claude_code_log/html/utils.py | 1 - .../migrations/019_session_peak_context.sql | 20 ++ claude_code_log/renderer.py | 18 ++ claude_code_log/utils.py | 16 +- dev-docs/application_model.md | 10 + dev-docs/css-classes.md | 5 +- docs/themes.md | 15 ++ test/__snapshots__/test_snapshot_html.ambr | 197 ++++++++++++++++-- test/test_cache_atomic_refresh.py | 46 ++++ test/test_minimal_pages.py | 40 +++- test/test_minimal_theme.py | 93 +++++---- test/test_minimal_theme_browser.py | 98 +++++++++ test/test_session_peak_context.py | 182 ++++++++++++++++ 21 files changed, 872 insertions(+), 128 deletions(-) create mode 100644 claude_code_log/html/templates/components/minimal/tokens.html create mode 100644 claude_code_log/migrations/019_session_peak_context.sql create mode 100644 test/test_session_peak_context.py diff --git a/claude_code_log/cache.py b/claude_code_log/cache.py index fb9019ca..61032a5b 100644 --- a/claude_code_log/cache.py +++ b/claude_code_log/cache.py @@ -118,6 +118,11 @@ class CachedFileState(BaseModel): row_fingerprints: List[bytes] = [] +def _row_peak(row: sqlite3.Row) -> Optional[int]: + """A session row's ``peak_context_tokens`` (``None`` when unknown).""" + return row["peak_context_tokens"] if "peak_context_tokens" in row.keys() else None + + class SessionCacheData(BaseModel): """Cached session-level information.""" @@ -136,6 +141,12 @@ class SessionCacheData(BaseModel): total_output_tokens: int = 0 total_cache_creation_tokens: int = 0 total_cache_read_tokens: int = 0 + # Migration 019: the largest context one main-thread turn sent (input + + # cache creation + cache read). ``None`` is unknown — a row written + # before the migration, an archived session whose source is gone, or a + # provider (Codex) that reports only cumulative totals — and is not + # shown, never read as a zero. + peak_context_tokens: Optional[int] = None # Teammates feature — set when the session was active in a team. # First non-None ``teamName`` of any entry in the session. team_name: Optional[str] = None @@ -2918,8 +2929,9 @@ def write(conn: sqlite3.Connection) -> None: message_count, first_user_message, cwd, total_input_tokens, total_output_tokens, total_cache_creation_tokens, total_cache_read_tokens, - team_name, ai_title, hidden, residual_count - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + team_name, ai_title, hidden, residual_count, + peak_context_tokens + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, session_id) DO UPDATE SET summary = excluded.summary, first_timestamp = excluded.first_timestamp, @@ -2934,7 +2946,8 @@ def write(conn: sqlite3.Connection) -> None: team_name = excluded.team_name, ai_title = excluded.ai_title, hidden = excluded.hidden, - residual_count = excluded.residual_count + residual_count = excluded.residual_count, + peak_context_tokens = excluded.peak_context_tokens """, ( self._project_id, @@ -2957,6 +2970,7 @@ def write(conn: sqlite3.Connection) -> None: scrub_surrogates(data.ai_title), 1 if data.hidden else 0, data.residual_count or 0, + data.peak_context_tokens, ), ) @@ -3444,6 +3458,7 @@ def get_all_session_rows(self) -> Dict[str, SessionCacheData]: total_output_tokens=row["total_output_tokens"], total_cache_creation_tokens=row["total_cache_creation_tokens"], total_cache_read_tokens=row["total_cache_read_tokens"], + peak_context_tokens=_row_peak(row), team_name=row["team_name"] if "team_name" in row.keys() else None, hidden=bool(row["hidden"]), residual_count=row["residual_count"], @@ -3711,6 +3726,7 @@ def get_cached_project_data(self) -> Optional[ProjectCache]: total_output_tokens=row["total_output_tokens"], total_cache_creation_tokens=row["total_cache_creation_tokens"], total_cache_read_tokens=row["total_cache_read_tokens"], + peak_context_tokens=_row_peak(row), team_name=row["team_name"] if "team_name" in row.keys() else None, ) @@ -4182,6 +4198,7 @@ def get_archived_sessions( total_output_tokens=row["total_output_tokens"], total_cache_creation_tokens=row["total_cache_creation_tokens"], total_cache_read_tokens=row["total_cache_read_tokens"], + peak_context_tokens=_row_peak(row), team_name=row["team_name"] if "team_name" in row.keys() else None, diff --git a/claude_code_log/converter.py b/claude_code_log/converter.py index ee5ae46b..4f153ca4 100644 --- a/claude_code_log/converter.py +++ b/claude_code_log/converter.py @@ -45,6 +45,7 @@ get_project_display_name, is_agent_session, parse_date_bounds, + turn_context_tokens, relative_href, resident_bytes, resident_transcript_bytes, @@ -2594,10 +2595,43 @@ def compute_session_data( cache.total_cache_read_tokens += ( getattr(usage, "cache_read_input_tokens", 0) or 0 ) + if not getattr(message, "isSidechain", False): + context = turn_context_tokens(usage) + if context > (cache.peak_context_tokens or 0): + cache.peak_context_tokens = context return result +def session_token_fields(data: Optional[SessionCacheData]) -> Dict[str, Any]: + """A session's token figures for an index or nav row. + + The minimal theme's meta lines read these (peak · new · out); the + classic theme reads none of them. + """ + if data is None: + return {} + return { + "total_input_tokens": data.total_input_tokens, + "total_output_tokens": data.total_output_tokens, + "total_cache_creation_tokens": data.total_cache_creation_tokens, + "peak_context_tokens": data.peak_context_tokens, + } + + +def _provider_session_token_fields( + totals: "Optional[ProviderTokenTotals]", +) -> Dict[str, Any]: + """``session_token_fields`` for a provider that reports only cumulative + session totals (Codex): the same keys, the peak unknown.""" + return { + "total_input_tokens": totals.input_tokens if totals else 0, + "total_output_tokens": totals.output_tokens if totals else 0, + "total_cache_creation_tokens": 0, + "peak_context_tokens": None, + } + + def compute_session_residuals(messages: List[TranscriptEntry]) -> Dict[str, int]: """Per-session count of traversed entries ``compute_session_data`` skips. @@ -2741,6 +2775,7 @@ def _plan_page( total_output_tokens = 0 total_cache_creation_tokens = 0 total_cache_read_tokens = 0 + peak_context_tokens: Optional[int] = None # The cached count must be the sessions-table sum, because # is_page_stale() compares it against SUM(sessions.message_count) # on the next run. len(page_messages) counts what's rendered @@ -2766,6 +2801,10 @@ def _plan_page( total_output_tokens += s.total_output_tokens total_cache_creation_tokens += s.total_cache_creation_tokens total_cache_read_tokens += s.total_cache_read_tokens + if s.peak_context_tokens is not None: + peak_context_tokens = max( + peak_context_tokens or 0, s.peak_context_tokens + ) # Build page_info for navigation has_prev = page_num > 1 @@ -2796,7 +2835,7 @@ def _plan_page( if total_output_tokens: token_parts.append(f"Output: {total_output_tokens:,}") if total_cache_creation_tokens: - token_parts.append(f"Cache Create: {total_cache_creation_tokens:,}") + token_parts.append(f"Cache Creation: {total_cache_creation_tokens:,}") if total_cache_read_tokens: token_parts.append(f"Cache Read: {total_cache_read_tokens:,}") token_summary = " | ".join(token_parts) if token_parts else None @@ -2805,6 +2844,12 @@ def _plan_page( "message_count": page_message_count, "date_range": date_range, "token_summary": token_summary, + # The figures behind ``token_summary``, for the minimal theme's + # header (peak · new · out); the peak is the page's largest. + "total_input_tokens": total_input_tokens, + "total_output_tokens": total_output_tokens, + "total_cache_creation_tokens": total_cache_creation_tokens, + "peak_context_tokens": peak_context_tokens, } page_title = f"{title} - Page {page_num}" if page_num > 1 else title @@ -5240,6 +5285,7 @@ def _collect_project_sessions(messages: list[TranscriptEntry]) -> list[dict[str, "first_user_message": data.first_user_message if data.first_user_message else "[No user message found in session.]", + **session_token_fields(data), } ) @@ -5392,6 +5438,8 @@ def _project_window_view( "message_count": part.message_count if part else 0, "first_user_message": row.first_user_message, "team_name": row.team_name, + # The window's own figures, like its message count. + **session_token_fields(part), } ) sessions.sort(key=lambda s: (s["first_timestamp"] or "", s["id"])) @@ -6406,12 +6454,12 @@ def render_provider_wholesale( "first_user_message": first_user or "[No user message found in session.]", "file": f"{rel_dest}/session-{session_key}{suffix}.{ext}", - # NOTE: no per-session token_summary key here — the Claude - # index project-card session list carries none either, and - # the drift pin (test_index_summary_dict_shape_matches_claude_path) - # locks the two session-dict shapes together. Per-session - # cumulative totals are stored on the session cache instead - # (durability); the project card shows the rolled-up total. + # The same token keys as the Claude path's session rows + # (``session_token_fields``) — the drift pin + # (test_index_summary_dict_shape_matches_claude_path) + # locks the two shapes together. From the cumulative + # session totals; no peak, which needs per-turn usage. + **_provider_session_token_fields(session_totals.get(session_key)), } ) @@ -7893,6 +7941,7 @@ def _convert_plan_inline( "message_count": session_data.message_count, "first_user_message": session_data.first_user_message or "[No user message found in session.]", + **session_token_fields(session_data), # Per-session link relative to the index # root. Used by the index renderer when # `combined_suppressed` is True so the @@ -8124,6 +8173,7 @@ def _convert_plan_inline( "message_count": session_data.message_count, "first_user_message": session_data.first_user_message or "[No user message found in session.]", + **session_token_fields(session_data), # `{variant}` keeps the link in step with # `_generate_individual_session_files`'s # filename (`session-{id}{variant}.{ext}`). diff --git a/claude_code_log/html/minimal_theme.py b/claude_code_log/html/minimal_theme.py index 95d34ea1..3f4530a2 100644 --- a/claude_code_log/html/minimal_theme.py +++ b/claude_code_log/html/minimal_theme.py @@ -244,16 +244,6 @@ def _token_parts(summary: str) -> dict[str, int]: } -def _in_out(parts: dict[str, int]) -> tuple[int, int]: - """Context size in (input + cache creation + cache read), and output.""" - total_in = ( - parts.get("input", 0) - + parts.get("cache creation", 0) - + parts.get("cache read", 0) - ) - return total_in, parts.get("output", 0) - - def _gutter_count(value: int) -> str: """Compact gutter number: one decimal below 10k, rounded above it.""" return compact_count(value, decimal_threshold=10) @@ -266,7 +256,8 @@ def compact_token_usage_parts(token_usage: Optional[str]) -> tuple[str, str]: Creation`` after it, so a context line of ``98k+20k`` with ``364`` below it means about 98k reused tokens and 20k new input tokens, with 364 output tokens. A leading ``+`` marks a turn that created cache without - reading any. + reading any, a ``+0`` one that read it and added nothing, and a bare + number a turn with no cache at all. """ if not token_usage: return "", "" @@ -277,21 +268,15 @@ def compact_token_usage_parts(token_usage: Optional[str]) -> tuple[str, str]: cache_creation = parts.get("cache creation", 0) new_input = parts.get("input", 0) + cache_creation total_out = parts.get("output", 0) - if cache_read and new_input: + if cache_read: context = f"{_gutter_count(cache_read)}+{_gutter_count(new_input)}" - elif new_input and cache_creation: + elif cache_creation: context = f"+{_gutter_count(new_input)}" else: - context = _gutter_count(cache_read + new_input) + context = _gutter_count(new_input) return context, _gutter_count(total_out) -def compact_token_usage(token_usage: Optional[str]) -> str: - """The two gutter figures joined for one-line contexts (tests, fallback).""" - context, out = compact_token_usage_parts(token_usage) - return f"{context} · {out}" if context else "" - - def token_usage_tooltip(token_usage: Optional[str]) -> str: """Explain the compact minimal gutter figures without changing classic.""" if not token_usage: @@ -369,23 +354,12 @@ def page_meta( parts.append(str(page_stats["date_range"])) if page_stats.get("message_count"): parts.append(f"{page_stats['message_count']} msgs") - token_source = str(page_stats.get("token_summary") or "") + parts.extend(_token_figures([page_stats])) else: count = sum(int(s.get("message_count") or 0) for s in real) if count: parts.append(f"{count} msgs") - token_source = " | ".join(str(s.get("token_summary") or "") for s in real) - - totals: dict[str, int] = {} - # A multi-session summary repeats the same labels once per session. - for name, number in _TOKEN_PART.findall(token_source): - key = name.strip().lower() - totals[key] = totals.get(key, 0) + int(number.replace(",", "")) - total_in, total_out = _in_out(totals) - if total_in: - parts.append(f"{compact_count(total_in)} in") - if total_out: - parts.append(f"{compact_count(total_out)} out") + parts.extend(_token_figures(real)) return parts @@ -555,20 +529,40 @@ def project_when(project: Any) -> Optional[dict[str, str]]: return found -def token_totals( - input_tokens: int, output_tokens: int, cache_creation: int, cache_read: int -) -> list[str]: - """``["1.2M in", "48k out"]``: context consumed (input + cache) and output, - as the transcript header's meta line counts them (``page_meta``).""" - total_in = int(input_tokens or 0) + int(cache_creation or 0) + int(cache_read or 0) +def token_totals(peak: Optional[int], new_input: int, output: int) -> list[str]: + """``["183k peak", "283k new", "155k out"]``, leaving out what is zero. + + *Peak* is the largest context one turn sent — how full the context got. + *New* is the input that did not come from the cache (uncached input + plus cache creation): what the conversation added. Summed cache reads + are not shown: every turn reads the same context again, so their total + says how long a session ran, not how big it got. The classic figures, + cache reads included, stay in the tooltips. + """ parts: list[str] = [] - if total_in: - parts.append(f"{compact_count(total_in)} in") - if output_tokens: - parts.append(f"{compact_count(int(output_tokens))} out") + if peak: + parts.append(f"{compact_count(int(peak))} peak") + if new_input: + parts.append(f"{compact_count(int(new_input))} new") + if output: + parts.append(f"{compact_count(int(output))} out") return parts +def _token_figures(entries: Iterable[dict[str, Any]]) -> list[str]: + """``token_totals`` over session-nav, index or page-stats dicts: the + largest known peak, the summed new input and output.""" + peaks: list[int] = [] + new_input = output = 0 + for entry in entries: + if entry.get("peak_context_tokens"): + peaks.append(int(entry["peak_context_tokens"])) + new_input += int(entry.get("total_input_tokens") or 0) + new_input += int(entry.get("total_cache_creation_tokens") or 0) + output += int(entry.get("total_output_tokens") or 0) + return token_totals(max(peaks) if peaks else None, new_input, output) + + def _plural(count: int, word: str) -> str: return f"{count:,} {word}{'' if count == 1 else 's'}" @@ -582,10 +576,10 @@ def index_summary_meta(summary: Any) -> list[str]: ] parts.extend( token_totals( - summary.total_input_tokens, + None, + int(summary.total_input_tokens or 0) + + int(summary.total_cache_creation_tokens or 0), summary.total_output_tokens, - summary.total_cache_creation_tokens, - summary.total_cache_read_tokens, ) ) return parts @@ -606,10 +600,10 @@ def project_meta(project: Any) -> list[str]: ] parts.extend( token_totals( - project.total_input_tokens, + None, + int(project.total_input_tokens or 0) + + int(project.total_cache_creation_tokens or 0), project.total_output_tokens, - project.total_cache_creation_tokens, - project.total_cache_read_tokens, ) ) return parts @@ -646,9 +640,7 @@ def index_sessions(project: Any) -> list[dict[str, Any]]: count = entry.get("message_count") if count: meta.append(_plural(int(count), "msg")) - tokens = compact_token_usage(entry.get("token_summary")) - if tokens: - meta.append(tokens) + meta.extend(_token_figures([entry])) rows.append( { "href": entry.get("file") diff --git a/claude_code_log/html/templates/components/minimal/dag.css b/claude_code_log/html/templates/components/minimal/dag.css index a7beec0e..04c0622c 100644 --- a/claude_code_log/html/templates/components/minimal/dag.css +++ b/claude_code_log/html/templates/components/minimal/dag.css @@ -316,7 +316,7 @@ .message.dag-in:is(.pair_middle, .pair_last):not(.dag-split):not(.error) > .header > .header-info - > *, + > :not(.mn-tok-pair), .theme-minimal .mn-stage.dag-on #transcript diff --git a/claude_code_log/html/templates/components/minimal/layout.css b/claude_code_log/html/templates/components/minimal/layout.css index 9ae5bb6b..b5d430bf 100644 --- a/claude_code_log/html/templates/components/minimal/layout.css +++ b/claude_code_log/html/templates/components/minimal/layout.css @@ -405,6 +405,13 @@ color: var(--muted); } +/* A pair's token figures, repeated in its last half's gutter for the wide + layout (below). Hidden everywhere else — on a phone, and on a card whose + pairing was undone — where the first half's own copy shows. */ +.theme-minimal #transcript .mn-tok-pair { + display: none; +} + .theme-minimal #transcript .message > .debug-info { grid-column: 3; grid-row: 2; @@ -464,6 +471,45 @@ .theme-minimal #transcript .message.pair_first::before { margin-bottom: calc(-0.7em - 3.5px); } + + /* A Thinking + Assistant pair's token figures make that hanging gutter + four lines, and a short pair is shorter than that: the figures ran + into the next row's time. They move to the last half's gutter + instead, one line down — under the time and role hanging into it — + and that row grows to fit them if it must (as the lane tag does in + dag.css). */ + .theme-minimal #transcript .message.pair_first > .header > .header-info > .mn-tok { + display: none; + } + + /* …which assumes the first half is at least a line tall. A redacted + thought has no text and is not, so its pair's figures landed on its + own role; with figures to place, the hanging gutter keeps one line. */ + .theme-minimal #transcript .message.pair_first:has(> .header > .header-info > .mn-tok) > .header > .header-info { + height: 1.85em; + } + + .theme-minimal + #transcript + .message.pair_last:has(> .header > .header-info > .mn-tok-pair) + > .header + > .header-info { + display: flex; + padding-top: 1.85em; + } + + .theme-minimal + #transcript + .message.pair_last:has(> .header > .header-info > .mn-tok-pair) + > .header + > .header-info + > :not(.mn-tok-pair) { + display: none; + } + + .theme-minimal #transcript .message.pair_last > .header > .header-info > .mn-tok-pair { + display: inline; + } } /* …and the first block under a call line (the call's own body — a Write's @@ -1119,6 +1165,12 @@ padding-left: 4px; } + /* On one line the two token figures need their separator back: + `98k+20k · 364`, not two loose numbers. */ + .theme-minimal #transcript .mn-tok-out::before { + content: "· "; + } + .theme-minimal #transcript .mn-role { padding-right: 0; padding-left: calc(var(--ic) + var(--ic-gap)); diff --git a/claude_code_log/html/templates/components/minimal/tokens.css b/claude_code_log/html/templates/components/minimal/tokens.css index 9f6239be..18365275 100644 --- a/claude_code_log/html/templates/components/minimal/tokens.css +++ b/claude_code_log/html/templates/components/minimal/tokens.css @@ -46,7 +46,8 @@ /* Row geometry: gutter, rail, and the narrower pair used inside a nested sub-agent group (mockup .row / .nest .row). The gutters carry - the token figures on two lines (for example, 98k+20k over 364). */ + the role icon (--ic plus its gap) beside a label of ~10 characters, + and a turn's token figures on two lines (98k+20k over 364). */ --ic: 12px; --ic-gap: 3px; --gut: 72px; diff --git a/claude_code_log/html/templates/components/minimal/tokens.html b/claude_code_log/html/templates/components/minimal/tokens.html new file mode 100644 index 00000000..7965799d --- /dev/null +++ b/claude_code_log/html/templates/components/minimal/tokens.html @@ -0,0 +1,13 @@ +{#- Minimal theme: a turn's token figures in the gutter (transcript.html), + never rendered for the classic theme. + + Two lines, the context (cache read + new input, `98k+20k`) over the + output (`364`), both carrying the tooltip that spells them out + (minimal_theme.compact_token_usage_parts / token_usage_tooltip). + `extra` adds a class to both spans: `mn-tok-pair` marks a pair's figures + shown in its last half's gutter (TemplateMessage.pair_token_usage). -#} +{% macro mn_tokens(usage, extra='') -%} +{%- set parts = mn_compact_token_parts(usage) -%} +{%- set tip = mn_token_tooltip(usage) -%} +{{ parts[0] }}{{ parts[1] }} +{%- endmacro %} diff --git a/claude_code_log/html/templates/transcript.html b/claude_code_log/html/templates/transcript.html index 58f4c4d8..e07de813 100644 --- a/claude_code_log/html/templates/transcript.html +++ b/claude_code_log/html/templates/transcript.html @@ -11,7 +11,7 @@ {{ title }} {% from 'components/session_nav.html' import render_session_nav %} - {% from 'components/archive_search_link.html' import archive_search_link as render_archive_search_link %} + {% from 'components/archive_search_link.html' import archive_search_link as render_archive_search_link %}{% if minimal %}{% from 'components/minimal/tokens.html' import mn_tokens %}{% endif %}