diff --git a/CHANGELOG.md b/CHANGELOG.md index 75103020..1c6deab3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ - **The Capacity Dock card and the popover quota rows no longer print a pace verdict under each window.** The "On pace" / "Lasts until reset" caption from #1314 added a third line to every window cell and made the card read as clutter; the cells are back to percent, label and countdown, up to three windows share one row again with a fourth wrapping to a second, and the pace math still feeds the tooltip and the agent-tab card. ### Fixed +- **The dashboard no longer crashes with `RangeError: Maximum call stack size exceeded` on a large session history.** Column widths were measured by spreading a per-session key list into `Math.max(...)`, and those lists grow with every session, so past roughly 124,000 entries the call blew V8's argument limit and took the process down before the first frame rendered. The width measurements now fold over the values instead of spreading them, in the dashboard, the plain-text tables, the overview and the sessions report alike. (#1453) - **The Overview no longer replaces itself with "This screen hit an error" when the act report has no totals.** The realized-savings figure read `actReport.data.totals.realizedCostUSD` behind a guard on the payload only, so an act report without a `totals` block threw during render and the section's error boundary latched — and because the desktop app repaints the durable report snapshot instantly on the next launch, a single such payload persisted in `localStorage` (one written by an older build that answered `{}`) crashed the Overview on every relaunch. The read now tolerates a missing block and reports $0 saved, which is what the card already shows before the first act report arrives. - **Codex sub-agent rollouts no longer double-count their parent's usage.** A thread spawned as a sub-agent replays its parent's history, including every `token_count` event with its original timestamp, and names the parent under `source.subagent.thread_spawn.parent_thread_id` rather than `forked_from_id`, so the fork guard never saw it and the replayed prefix was counted again per child. The parent id is now read from either field, and the replayed events drop like a fork's. On a corpus with 381 spawned children this removed 405 duplicate calls and 403,712 duplicate cache tokens; rollouts without sub-agents are unchanged. (#1380) - **Shared and MCP-redacted payloads no longer carry pull request urls or owner/repo labels.** `current.pullRequests` survived both passes verbatim: each row's full GitHub url and its `owner/repo#123` label named the repository to a paired peer device and to a name-redacted MCP client, the same class of leak #1337 closed for branch names. Sharing now drops the block outright, the way it already drops the project, session and per-branch rows. The MCP pass with `include_project_names: false` pseudonymizes `url` and `label` from the url — the aggregation key — with the same salted hash as the project and branch pseudonyms, domain-separated so rows referring to the same PR still line up while the cost, calls and totals stay untouched; `include_project_names: true` still sees the real urls and labels. (#1346) diff --git a/src/dashboard.tsx b/src/dashboard.tsx index ed8cd90d..ac92575b 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -5,6 +5,7 @@ import React, { Fragment, useState, useCallback, useEffect, useLayoutEffect, use import { render, Box, Text, measureElement, useInput, useApp, useWindowSize, type DOMElement, type Instance, type RenderOptions } from 'ink' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import { formatCost, formatTokens, markEstimated, carriedCostNote } from './format.js' +import { maxOf } from './math-utils.js' import { formatSessionCount } from './session-count-label.js' import { aggregateModelEfficiency } from './model-efficiency.js' import { parseAllSessions, filterProjectsByDateRange, filterProjectsByName, setInteractiveScanUI, withSinglePassParse, withColdFirstPaintFloor, filesParsedFromSourceCount, isCompleteSessionSnapshotAvailable } from './parser.js' @@ -480,7 +481,7 @@ function fit(s: string, n: number): string { type MetricCell = { text: string; color?: string; dimColor?: boolean } function getMetricWidths(headers: string[], rows: string[][]): number[] { - return headers.map((header, index) => Math.max(header.length, ...rows.map(row => row[index]?.length ?? 0))) + return headers.map((header, index) => maxOf(rows.map(row => row[index]?.length ?? 0), header.length)) } function getMetricGroupWidth(metricWidths: number[]): number { @@ -684,7 +685,7 @@ function DailyActivity({ projects, days = 14, pw, bw, scrollable = false, cursor const allRows = getDailyActivityRows(projects) const orderedRows = scrollable ? [...allRows].reverse() : allRows const rows = scrollable ? orderedRows.slice(cursor, cursor + days) : orderedRows.slice(-days) - const maxCost = Math.max(0, ...(scrollable ? orderedRows : rows).map(row => row.cost)) + const maxCost = maxOf((scrollable ? orderedRows : rows).map(row => row.cost), 0) const headers = ['cost', 'calls'] const values = rows.map(row => [formatCost(row.cost), String(row.calls)]) const metricWidths = getMetricWidths(headers, values) @@ -764,13 +765,13 @@ export function shortProject(absPath: string, width = Infinity): string { export function getDashboardMaxWidth(projects: ProjectSummary[], budgets?: Map, activeProvider?: string): number { const sessions = projects.flatMap(project => project.sessions) - const longest = (values: string[]) => Math.max(1, ...values.map(value => value.length)) + const longest = (values: string[]) => maxOf(values.map(value => value.length), 1) const rowWidth = (labels: string[], metricCount: number, metricWidth = 7) => PANEL_CHROME + 10 + 1 + longest(labels) + metricCount * metricWidth const modelTotals = aggregateModelTotals(projects) - const modelMetricWidth = Math.max(7, ...Object.values(modelTotals).map(model => + const modelMetricWidth = maxOf(Object.values(modelTotals).map(model => markEstimated(formatCost(model.costUSD), model.estimatedCostUSD > 0).length - )) + ), 7) const categoryLabels = sessions.flatMap(session => Object.keys(session.categoryBreakdown).map(category => CATEGORY_LABELS[category as TaskCategory] ?? category)) const skillLabels = sessions.flatMap(session => Object.keys(session.skillBreakdown)) const agentLabels = sessions.flatMap(session => Object.keys(session.subagentBreakdown)) @@ -792,7 +793,7 @@ function getProjectBreakdownRowLimit(period: Period, dayMode = false): number { } function ProjectBreakdown({ projects, pw, bw, budgets, rows = 14 }: { projects: ProjectSummary[]; pw: number; bw: number; budgets?: Map; rows?: number }) { - const maxCost = Math.max(...projects.map(p => p.totalCostUSD)) + const maxCost = maxOf(projects.map(p => p.totalCostUSD), -Infinity) const hasBudgets = budgets && budgets.size > 0 const headers = ['cost', 'avg/s', 'session', ...(hasBudgets ? ['overhead'] : [])] const visibleProjects = projects.slice(0, rows) diff --git a/src/math-utils.ts b/src/math-utils.ts new file mode 100644 index 00000000..4cd88e76 --- /dev/null +++ b/src/math-utils.ts @@ -0,0 +1,5 @@ +export function maxOf(values: readonly number[], initial: number): number { + let max = initial + for (const value of values) if (value > max) max = value + return max +} diff --git a/src/overview.ts b/src/overview.ts index a4ba7a99..7b27088c 100644 --- a/src/overview.ts +++ b/src/overview.ts @@ -7,6 +7,7 @@ import { formatCost as baseCost, getCurrency } from './currency.js' import { findUnpricedModels, getShortModelName, unpricedModelHint } from './models.js' import { callBillableOutputTokens, sessionBillableOutputTokens, sessionModelBillableOutputTokens } from './session-output.js' import { markEstimated } from './format.js' +import { maxOf } from './math-utils.js' import { formatSessionCount, SESSION_COUNT_HELP, type SessionCountBasis } from './session-count-label.js' import { normalizeAbsProjectPathKey } from './parser.js' import { dateKey } from './day-aggregator.js' @@ -79,7 +80,7 @@ function vlen(s: string): number { function renderTable(c: ChalkInstance, cols: Col[], rows: string[][]): string { const widths = cols.map((col, i) => - Math.max(vlen(col.header), ...rows.map((r) => vlen(r[i] ?? ''))), + maxOf(rows.map((r) => vlen(r[i] ?? '')), vlen(col.header)), ) const pad = (s: string, w: number, right?: boolean): string => { const fill = ' '.repeat(Math.max(0, w - vlen(s))) diff --git a/src/sessions-report.ts b/src/sessions-report.ts index 4a4444f7..d036eb72 100644 --- a/src/sessions-report.ts +++ b/src/sessions-report.ts @@ -1,5 +1,6 @@ import { behavioralCallCount, behavioralTurnCount } from './behavioral-weight.js' import { getShortModelName } from './models.js' +import { maxOf } from './math-utils.js' import { inferSessionProvider, sessionBillableOutputTokens } from './session-output.js' import { CATEGORY_LABELS } from './types.js' import type { ProjectSummary, SessionSummary, TaskCategory } from './types.js' @@ -191,7 +192,7 @@ function renderSessionGrid(columns: SessionColumn[], items: T[], cell: (item: // Content can use spare room, but never grow beyond the terminal frame. for (let i = 0; i < fitted.length; i++) { const col = fitted[i]! - const longest = Math.max(col.header.length, ...values.map(row => row[i]?.length ?? 0)) + const longest = maxOf(values.map(row => row[i]?.length ?? 0), col.header.length) const spare = available - frameWidth(fitted) const wanted = Math.max(0, Math.min(longest - col.width, spare)) col.width += wanted diff --git a/src/text-table.ts b/src/text-table.ts index 2a82d7c6..005dc772 100644 --- a/src/text-table.ts +++ b/src/text-table.ts @@ -1,4 +1,5 @@ import { Chalk } from 'chalk' +import { maxOf } from './math-utils.js' export type TableColumn = { header: string; right?: boolean } @@ -18,7 +19,7 @@ export function renderTable( ): string { const c = new Chalk(opts.color === false ? { level: 0 } : {}) const bold = opts.boldRows ?? new Set() - const widths = columns.map((col, i) => Math.max(vlen(col.header), ...rows.map((r) => vlen(r[i] ?? '')))) + const widths = columns.map((col, i) => maxOf(rows.map((r) => vlen(r[i] ?? '')), vlen(col.header))) const pad = (s: string, w: number, right?: boolean): string => { const fill = ' '.repeat(Math.max(0, w - vlen(s))) return right ? fill + s : s + fill diff --git a/tests/dashboard.test.ts b/tests/dashboard.test.ts index c6f64495..7935a7d7 100644 --- a/tests/dashboard.test.ts +++ b/tests/dashboard.test.ts @@ -340,6 +340,13 @@ describe('getLayout - dashboard width breakpoints', () => { expect(getDashboardMaxWidth([long])).toBe(256) expect(getDashboardMaxWidth([short])).toBeLessThan(256) }) + + it('measures a breakdown with 200,000 keys without overflowing the stack', () => { + const session = makeSession('huge', 1) + for (let i = 0; i < 200_000; i++) session.toolBreakdown[`tool-${i}`] = { calls: 1 } + + expect(getDashboardMaxWidth([makeProject('huge', [session])])).toBeGreaterThan(0) + }) }) describe('Daily Activity viewport', () => {