Merge pull request #1350 from getagentseal/fix/pr-row-drill-through-1338

fix(app): open the sessions behind a pull request row
This commit is contained in:
Resham Joshi 2026-09-13 16:57:42 +03:00 • committed by GitHub
commit 68ce480ec1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 241 additions and 6 deletions

View file

@ -14,6 +14,7 @@
### Fixed
- **Shared and MCP-redacted payloads no longer carry git branch names or the working directory of a session.** Two identities were riding along in `current`: the `topSessions` rows added in #1316 carry `projectKey`, a dash-encoded absolute path such as `-Users-<user>-Projects-<repo>`, which `redactProjectNames` left verbatim even when an MCP client asked not to see project names, and the per-branch rows added in #788 carry the raw branch, which both `sanitizeForSharing` and the MCP pass let through, so a branch such as `exp/extraction-arms` reached a shared payload as typed. The MCP pass now hashes `projectKey` with the same salted pseudonym it already applies to `topProjects[].id`, hashes the drill-through `sessionId` on both `topSessions` and `topProjects[].sessionDetails` (a Codex id embeds the rollout timestamp the pass blanks out of `date`), and gives each distinct branch a stable `branch-xxxxxx` pseudonym, keeping the cost, calls and session counts untouched; a `null` branch stays null, because unbranched spend is not a name. Sharing drops the per-branch block outright, the way it already drops the project and session rows, since a pseudonymized branch tells a peer device nothing anyway. Nothing changes for the local menubar, the desktop app or the web dashboard, which read the unsanitized payload, and nothing changes for an MCP caller that passes `include_project_names: true` — it still gets every name as recorded. (#1325, #1321)
- **A pull request row now opens the sessions that produced it.** Every other aggregate in the app drills through — a day bar, a model name, a task category, a project — but the Pull requests section only ever expanded and collapsed: the PR selection builder and the drill-through callback were threaded through the section four component levels deep and nothing ever called either, so the one report that names actual shipped work had no way into the sessions behind it. An expanded PR row now carries a `View sessions for this pull request →` control above its work breakdown, the same affordance a project row in Spend already offers; it selects the PR by its URL — the aggregation key the by-PR report is built on — and lands in Sessions with the chip applied and each session's per-turn contribution reconciled against its full cost. The control is its own click target rather than the row, so clicking it or pressing Enter on it never costs the expansion, and a legacy row with no per-turn detail offers it too. Two smaller items from the same review: the sessions list's return-to-the-first-page reset wrote internal state the app does not read while it owns the pagination depth, so revealing another 120 rows and then changing the sort or removing a chip left you deep inside a list that had just been reordered — the reset now rides the same commit as the change that caused it, and the depth a Back/Forward restore brings back is left alone. And the investigation chips were keyed by the label they display, which truncates a session id to 12 characters and a project to its last path segment: two chips that read alike collided into one React key, warned about it, and risked reconciling or removing the wrong one — they are now keyed by the full provider+id and project+branch identity the selection is deduplicated by. (#1317)
- **The menubar second row's quota line now names the provider the flame is warning about.** "Quota remaining" picked each provider's *headline* window — weekly, else monthly, and only then the busiest one — which is the Capacity Dock's billing horizon, not a warning: on a machine with Cursor's API window at 100% and Claude's 5-hour window at 18%, the row reported Monthly 9.5% and Weekly 5% and read as if nothing were near a limit. Each provider now contributes its worst window, per-model rows included, which is exactly what the menu-bar flame already tints by, so the two surfaces agree. A provider backing off after a failed fetch keeps its last-known window instead of dropping out, so the row no longer vanishes — resizing the status item — for the length of a retry, matching what the dock shows dimmed. The row is also capped at 24 characters, shortening a long provider name ("GitHub Copilot 12% left · 6d 3h") rather than letting the second line more than double the item's width, and the two-line title now carries a VoiceOver label that reads as one phrase instead of a string with a newline in it. With the setting off nothing changed: the snapshot that feeds the row is no longer even built on a refresh, and the title is the single-row composition it has always been. (#1310)
- **Every Copilot credential rung now follows its own GitHub host, not just the two read from files.** #1286 taught `hosts.json` and `apps.json` to carry the host their token came from, but the rungs that carried none — `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, and a token pasted into Settings — were still sent to `api.github.com`, so a user whose only Copilot credential is a GitHub Enterprise Cloud login got a 401 and a terminal failure with no way out. The environment rung now reads `GH_HOST` from the same environment as the token; the `gh` rung resolves the host from gh's own `hosts.yml` (`GH_CONFIG_DIR`, then `XDG_CONFIG_HOME/gh`, then `~/.config/gh`), picking it the way gh picks the host for `gh auth token` and without a second subprocess; and macOS Settings gains a GitHub host field next to the pasted token, defaulting to `github.com` and saved in the same Keychain record as the token so the two can never drift apart. Settings refuses a host no endpoint can be derived from at the field rather than storing it, the connection row no longer promises `api.github.com` before anything has been fetched, and every one of these new host sources is character-validated before a URL is built, so a crafted value such as `evil.com?.ghe.com` fails closed with no request instead of pointing the Authorization header at a host of its own choosing. `codeburn quota` is unchanged: it still reads only the editor-plugin files, which already carry their host. (#1306)
- **Copilot live quota works for GitHub Enterprise Cloud enterprises on a `*.ghe.com` host.** Both readers hardcoded `https://api.github.com/copilot_internal/user` and threw away the host their credential came from, so a data-residency enterprise signed in on `<tenant>.ghe.com` could only ever report `available: false` with "Temporarily unavailable". A discovered credential now carries its host — `hosts.json` is keyed by host and newer `apps.json` files key by `<host>:<app id>` — and the request follows it: `api.github.com` for `github.com` and for any rung that carries no host of its own (an app-name `apps.json` key, `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, a pasted token), and `https://api.<tenant>.ghe.com/copilot_internal/user` for an enterprise host. The token and the host always come from the same entry, with `github.com` preferred when several hosts are signed in and otherwise the first `.ghe.com` tenant in sorted order; a host neither rule can address, such as a self-hosted GitHub Enterprise Server install, fails with a message naming that host instead of sending the credential to dotcom, and unreachable-host and HTTP failures name the host that was tried. The macOS Settings connection row now says which host answered. (#1286)

View file

@ -7,7 +7,8 @@ import { sanitizeProps } from '../electron/telemetry'
import { __resetPolledMemo, hasPolledMemo, primePolledMemo } from './hooks/usePolled'
import { setActiveCurrency } from './lib/format'
import { readOverviewHeadline, writeOverviewHeadline } from './lib/overviewSnapshot'
import type { BranchSpendReport, DateRange, MenubarPayload, ModelReportRow, OptimizeJsonReport, SpendFlow } from './lib/types'
import type { BranchSpendReport, DateRange, MenubarPayload, ModelReportRow, OptimizeJsonReport, SessionRow, SpendFlow } from './lib/types'
import { INITIAL_VISIBLE } from './sections/Sessions'
const stored = new Map<string, string>()
vi.stubGlobal('localStorage', {
@ -1350,3 +1351,57 @@ describe('usage_snapshot telemetry props', () => {
])
})
})
describe('sessions pagination', () => {
beforeEach(() => {
installDefaultMocks()
localStorage.clear()
localStorage.setItem('codeburn.defaultPeriod', '30days')
setPlatform('darwin')
})
afterEach(() => {
clearPlatform()
vi.useRealTimers()
})
function sessionRows(count: number): SessionRow[] {
return Array.from({ length: count }, (_, index) => ({
sessionId: `session-${index}`,
project: `project-${index}`,
provider: 'claude',
models: ['Opus 4.8'],
cost: count - index,
savingsUSD: 0,
calls: 1,
turns: 1,
inputTokens: 1_000,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
startedAt: '2026-09-10T10:00:00.000Z',
endedAt: '2026-09-10T10:01:00.000Z',
durationMs: 60_000,
}))
}
// 30s timeout: the list renders 120+ rows three times inside a full App
// render, and the suite runs its files in parallel.
it('returns a revealed sessions list to the first page when the sort changes', { timeout: 30_000 }, async () => {
mocks.getSessions.mockResolvedValue(sessionRows(INITIAL_VISIBLE + 5))
render(<App />)
expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument()
fireEvent.keyDown(document, { key: '2', metaKey: true })
expect(await screen.findByText(`Showing ${INITIAL_VISIBLE} of ${INITIAL_VISIBLE + 5}`)).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Show 5 more · 5 remaining' }))
expect(await screen.findByText(`Showing ${INITIAL_VISIBLE + 5} of ${INITIAL_VISIBLE + 5}`)).toBeInTheDocument()
// A new sort is a new ordering of the whole list: it starts at the first
// page again instead of holding the depth reached under the old one.
const toolbar = document.querySelector('.sessions-toolbar') as HTMLElement
fireEvent.click(within(toolbar).getByRole('tab', { name: 'Recent' }))
expect(await screen.findByText(`Showing ${INITIAL_VISIBLE} of ${INITIAL_VISIBLE + 5}`)).toBeInTheDocument()
})
})

View file

@ -933,7 +933,11 @@ function AppMain() {
{section === 'overview' ? (
<OverviewContent period={period} provider={provider} range={customRange} overview={overview} onNavigate={navigate} onInvestigate={investigate} ready={ready} scope={scope} headlineSnapshot={headlineSnapshot} />
) : section === 'sessions' ? (
<Sessions period={period} provider={provider} range={customRange} refreshToken={refreshToken} detectedProviders={visibleProviderEntries} onProviderChange={onProviderSelect} ready={ready} filters={filters} onFiltersChange={next => commitNav({ filters: next })} openSessionId={openSessionId} onSessionOpen={key => commitNav({ sessionId: key })} onSessionClose={() => commitNav({ sessionId: null })} sort={nav.sort as SessionSort} onSortChange={value => commitNav({ sort: value })} visibleCount={nav.visibleCount} onVisibleCountChange={value => commitNav({ visibleCount: value })} />
// A new sort or a changed selection reorders the whole list, so
// the pagination depth resets IN THE SAME commit — one history
// entry, and the depth a Back/Forward restores stays whatever it
// was when that position was committed.
<Sessions period={period} provider={provider} range={customRange} refreshToken={refreshToken} detectedProviders={visibleProviderEntries} onProviderChange={onProviderSelect} ready={ready} filters={filters} onFiltersChange={next => commitNav({ filters: next, visibleCount: INITIAL_VISIBLE })} openSessionId={openSessionId} onSessionOpen={key => commitNav({ sessionId: key })} onSessionClose={() => commitNav({ sessionId: null })} sort={nav.sort as SessionSort} onSortChange={value => commitNav({ sort: value, visibleCount: INITIAL_VISIBLE })} visibleCount={nav.visibleCount} onVisibleCountChange={value => commitNav({ visibleCount: value })} />
) : section === 'pullRequests' ? (
<PullRequestsContent overview={overview} period={period} provider={provider} range={customRange} onInvestigate={investigate} />
) : section === 'spend' ? (

View file

@ -0,0 +1,51 @@
// @vitest-environment jsdom
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { EMPTY_FILTERS, type InvestigationFilters } from '../lib/investigation'
import { FilterChips } from './FilterChips'
// Two sessions of the same provider whose ids agree on the first 12 characters
// (a real shape: one CLI's ids share a long prefix), so the chip LABEL — which
// truncates at 12 — is identical for both.
const COLLIDING: InvestigationFilters = {
...EMPTY_FILTERS,
sessions: [
{ provider: 'claude', sessionId: 'session-abcd-1111' },
{ provider: 'claude', sessionId: 'session-abcd-2222' },
],
branches: [
{ project: '/work/app', branch: 'main' },
{ project: '/personal/app', branch: 'main' },
],
}
afterEach(() => { vi.restoreAllMocks() })
describe('FilterChips', () => {
it('renders one chip per selected value even when two values share a display label', async () => {
const warn = vi.spyOn(console, 'error').mockImplementation(() => {})
const onChange = vi.fn()
render(<FilterChips filters={COLLIDING} onChange={onChange} />)
const bar = screen.getByRole('group', { name: /active investigation filters/i })
expect(within(bar).getAllByRole('button', { name: /remove session filter/i })).toHaveLength(2)
expect(within(bar).getAllByRole('button', { name: /remove branch filter/i })).toHaveLength(2)
// Chips keyed by the truncated label collide, which React reports as two
// children with the same key — and then reconciles the wrong one.
const keyWarnings = warn.mock.calls.filter(([first]) => String(first).includes('same key'))
expect(keyWarnings).toEqual([])
// Removing the second of two identically-labeled chips removes exactly it.
await userEvent.click(within(bar).getAllByRole('button', { name: /remove session filter/i })[1]!)
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({
sessions: [{ provider: 'claude', sessionId: 'session-abcd-1111' }],
}))
})
it('renders nothing without a selection', () => {
const { container } = render(<FilterChips filters={EMPTY_FILTERS} onChange={() => {}} />)
expect(container).toBeEmptyDOMElement()
})
})

View file

@ -1,4 +1,4 @@
import { filterChipLabel, type FilterDimension, type InvestigationFilters, withoutFilterValue } from '../lib/investigation'
import { filterChipKey, filterChipLabel, type FilterDimension, type InvestigationFilters, withoutFilterValue } from '../lib/investigation'
/** Chip descriptor: one active filter value. */
export type FilterChip = {
@ -45,8 +45,11 @@ export function FilterChips({ filters, onChange }: {
return (
<div className="drill-chips" role="group" aria-label="Active investigation filters">
<span className="drill-chips-label">Investigating</span>
{/* Keyed by the chip's identity, never by its label: the label truncates
a session id and shortens a project path, so two chips in the same
dimension can read identically while selecting different things. */}
{chips.map(chip => (
<span className={`drill-chip d-${chip.dimension}`} key={`${chip.dimension}:${filterChipLabel(chip.dimension, chip.value)}`}>
<span className={`drill-chip d-${chip.dimension}`} key={`${chip.dimension}:${filterChipKey(chip.dimension, chip.value)}`}>
<span className="drill-chip-dim">{DIMENSION_LABELS[chip.dimension]}</span>
<span className="drill-chip-value" title={chip.dimension === 'prs' ? String(chip.value) : undefined}>
{filterChipLabel(chip.dimension, chip.value)}

View file

@ -6,6 +6,8 @@ import {
categoryFilters,
dayFilters,
EMPTY_FILTERS,
filterChipKey,
filterChipLabel,
filtersActive,
filtersToKey,
modelFilters,
@ -280,4 +282,23 @@ describe('contribution math', () => {
expect(result.cost).toBeCloseTo(0.4, 10)
expect(result.included[0]!.row.parentSessionId).toBe('root-1')
})
it('keys a chip by its full identity, not by the label it truncates for display', () => {
// Two sessions whose ids share the first 12 characters, and two projects
// with the same last path segment, render the SAME chip label. The key
// that identifies the chip to React must still tell them apart.
const sessionA = { provider: 'claude', sessionId: 'session-abcdefgh-1111' }
const sessionB = { provider: 'claude', sessionId: 'session-abcdefgh-2222' }
expect(filterChipLabel('sessions', sessionA)).toBe(filterChipLabel('sessions', sessionB))
expect(filterChipKey('sessions', sessionA)).not.toBe(filterChipKey('sessions', sessionB))
const branchA = { project: '/work/app', branch: 'main' }
const branchB = { project: '/personal/app', branch: 'main' }
expect(filterChipLabel('branches', branchA)).toBe(filterChipLabel('branches', branchB))
expect(filterChipKey('branches', branchA)).not.toBe(filterChipKey('branches', branchB))
// A plain dimension keys by its own value, which is already its identity.
expect(filterChipKey('days', '2026-09-10')).toBe('2026-09-10')
expect(filterChipKey('prs', 'https://github.com/o/r/pull/7')).toBe('https://github.com/o/r/pull/7')
})
})

View file

@ -333,6 +333,23 @@ export function clearPersistedInvestigation(): void {
try { globalThis.localStorage?.removeItem(INVESTIGATION_SNAPSHOT_KEY) } catch { /* storage can be unavailable */ }
}
/** Stable identity of one chip — the same composite identity normalizeFilters
* dedupes by and withoutFilterValue removes by. The DISPLAY label truncates (a
* session id to 12 characters, a project to its last path segment), so two
* distinct values can read identically; this never collapses them, which is
* why the chip list keys on it. */
export function filterChipKey(dimension: FilterDimension, value: string | BranchFilter | SessionFilter): string {
if (dimension === 'branches') {
const b = value as BranchFilter
return `${b.project}\u0000${b.branch}`
}
if (dimension === 'sessions') {
const s = value as SessionFilter
return `${s.provider}\u0000${s.sessionId}`
}
return value as string
}
/** Display label for a filter chip. Values the destination can resolve from
* loaded data pass through; the rest show raw (still honest). */
export function filterChipLabel(dimension: FilterDimension, value: string | BranchFilter | SessionFilter): string {

View file

@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { formatDayShort } from '../lib/format'
import { prFilters } from '../lib/investigation'
import type { MenubarPayload } from '../lib/types'
import { PullRequests } from './PullRequests'
@ -173,6 +174,60 @@ describe('PullRequests', () => {
expect(row).toHaveAttribute('aria-expanded', 'false')
})
it('drills a PR through to the sessions that composed it, leaving the row expanded', async () => {
getOverview.mockResolvedValue(makePayload(SAMPLE))
const onInvestigate = vi.fn()
render(<PullRequests period="lifetime" provider="all" onInvestigate={onInvestigate} />)
const link = await screen.findByRole('link', { name: 'getagentseal/codeburn#780' })
const row = rowForLink(link)
await userEvent.click(row)
expect(row).toHaveAttribute('aria-expanded', 'true')
await userEvent.click(screen.getByRole('button', { name: /View sessions for this pull request/ }))
expect(onInvestigate).toHaveBeenCalledTimes(1)
expect(onInvestigate).toHaveBeenCalledWith({ filters: prFilters('https://github.com/getagentseal/codeburn/pull/780') })
// The affordance drills; the row it sits in keeps the state it was in.
expect(row).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByText('Feature work')).toBeInTheDocument()
})
it('drills from the keyboard and still leaves a legacy row expanded', async () => {
const approxPayload: PrPayload = {
rows: [
{ url: 'https://github.com/getagentseal/codeburn/pull/900', label: 'getagentseal/codeburn#900', cost: 12.5, savingsUSD: 0, sessions: 1, calls: 30, firstStarted: '2026-07-10T10:00:00Z', lastEnded: '2026-07-10T11:00:00Z', approx: true },
],
distinctCost: 12.5,
distinctSessions: 1,
attributedCost: 12.5,
unattributedCost: 0,
}
getOverview.mockResolvedValue(makePayload(approxPayload))
const onInvestigate = vi.fn()
render(<PullRequests period="lifetime" provider="all" onInvestigate={onInvestigate} />)
const link = await screen.findByRole('link', { name: 'getagentseal/codeburn#900' })
const row = rowForLink(link)
await userEvent.click(row)
// A row with no per-turn detail still offers the drill-through.
const drill = screen.getByRole('button', { name: /View sessions for this pull request/ })
drill.focus()
await userEvent.keyboard('{Enter}')
expect(onInvestigate).toHaveBeenCalledWith({ filters: prFilters('https://github.com/getagentseal/codeburn/pull/900') })
expect(row).toHaveAttribute('aria-expanded', 'true')
})
it('offers no drill-through affordance when the section has no destination to drill to', async () => {
getOverview.mockResolvedValue(makePayload(SAMPLE))
render(<PullRequests period="lifetime" provider="all" />)
const link = await screen.findByRole('link', { name: 'getagentseal/codeburn#780' })
await userEvent.click(rowForLink(link))
expect(screen.getByText('Feature work')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /View sessions/ })).toBeNull()
})
it('states the attributed-total footer and the summable framing', async () => {
getOverview.mockResolvedValue(makePayload(SAMPLE))
render(<PullRequests period="lifetime" provider="all" />)

View file

@ -57,14 +57,19 @@ function rowKeyDown(event: KeyboardEvent<HTMLDivElement>, toggle: () => void): v
/** Standalone entry: self-fetches the overview payload (used in tests). The App
* passes its shared overview poll straight into PullRequestsContent instead. */
export function PullRequests({ period, provider, range = null }: { period: Period; provider: string; range?: DateRange | null }) {
export function PullRequests({ period, provider, range = null, onInvestigate }: {
period: Period
provider: string
range?: DateRange | null
onInvestigate?: (request: InvestigateRequest) => void
}) {
const overview = usePolled<MenubarPayload>(
() => range ? codeburn.getOverview(period, provider, range) : codeburn.getOverview(period, provider),
[period, provider, range?.from, range?.to],
)
// The key remounts the content on a period/provider/range switch so row state
// (an open expansion) never survives onto the same PR rendered from new data.
return <PullRequestsContent key={`${period}|${provider}|${range?.from ?? ''}|${range?.to ?? ''}`} overview={overview} period={period} provider={provider} range={range} />
return <PullRequestsContent key={`${period}|${provider}|${range?.from ?? ''}|${range?.to ?? ''}`} overview={overview} period={period} provider={provider} range={range} onInvestigate={onInvestigate} />
}
export function PullRequestsContent({ overview, period, provider, range = null, onInvestigate }: {
@ -251,6 +256,22 @@ function PrRowView({ pr, expanded, onToggle, onInvestigate }: { pr: PrRow; expan
</div>
{expanded && (
<div className="pr-detail-cell">
{/* Drill-through entry: a control of its own, never the row. The row
is a toggle, so hanging the investigation off it would cost the
expansion; this opens the sessions that composed the PR while the
row stays exactly as the reader left it. The PR URL is the
aggregation key of the by-PR report, so it selects at the
destination without a lookup. */}
{onInvestigate && (
<button
className="ov-link pr-drill"
type="button"
title={`View sessions for ${pr.label}`}
onClick={() => onInvestigate({ filters: prFilters(pr.url) })}
>
View sessions for this pull request →
</button>
)}
{categories.length > 0 ? (
<div className="pr-detail" role="region" aria-label={`${pr.label} cost breakdown`}>
<div className="pr-detail-head">

View file

@ -251,7 +251,14 @@ export function Sessions({
}, [investigating, searched, selection.unattributable])
const included = summary.included
// Back to the first page when the list is reordered or re-populated under the
// reader. This writes the INTERNAL depth, so it applies to the uncontrolled
// wiring only: a parent that owns visibleCount (the app, which keeps it in the
// nav history) resets it in the same commit as the sort/selection change it
// owns. Pushing a reset from here would fire on a Back/Forward restore too,
// discarding the depth that was just restored.
useEffect(() => {
if (controlledVisibleCount !== undefined) return
setInternalVisibleCount(INITIAL_VISIBLE)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filterKey, sort, report.data, q])