Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agents): use GitHub PR statistics for change counts (#6734)
Eric Hayes08266b8943ce
diff --git a/apps/web/src/features/agent-changes/agent-changes.tsx b/apps/web/src/features/agent-changes/agent-changes.tsxindex 9c4ab82dad..f669bda69d 100644--- a/apps/web/src/features/agent-changes/agent-changes.tsx+++ b/apps/web/src/features/agent-changes/agent-changes.tsx@@ -16,6 +16,7 @@ import { useAgentSession } from '../block-agent/context/AgentSessionContext';import type { ChangesHost } from './context/agent-changes-context';import { AgentChangesControllerProvider } from './context/agent-changes-controller';import { createAgentChanges } from './primitives/create-agent-changes';+import { createPullRequestStatsSource } from './queries/pull-request-stats';import { createSessionChangesSource } from './queries/session-changes';import { createUrlDiffState } from './url-diff-state';@@ -53,7 +54,13 @@ export function AgentChangesProvider(props: ParentProps) {toast.failure('The review notes could not be sent');}};+ const pullRequestChangeCounts = createPullRequestStatsSource(+ () =>+ coding() ? (session.session()?.pullRequestUrl ?? undefined) : undefined,+ () => source.summary()?.changeset?.id+ );const host: ChangesHost = {+ pullRequestChangeCounts,scopeKey: session.sessionId,agent: {send: (markdown) => void sendPrompt(markdown),diff --git a/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsxindex 0657df05b3..db6f82cdd2 100644--- a/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx+++ b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx@@ -1,5 +1,6 @@import SquareSplitHorizontalIcon from '@phosphor/square-split-horizontal.svg';import { Button, cn } from '@ui';+import { Show } from 'solid-js';import { DiffCounts } from './DiffCounts';/** Opens the changes pane and summarizes its added/deleted lines. */@@ -17,14 +18,16 @@ export function ChangesToggleButton(props: {size="sm"aria-pressed={props.open}tooltip={props.open ? 'Hide the changes pane' : 'Show the changes pane'}- class={cn('gap-1.5 pr-1.5', props.open && 'bg-active text-ink')}+ class={cn('gap-1.5', props.open && 'bg-active text-ink')}onClick={() => props.onToggle()}><SquareSplitHorizontalIcon class="size-3.5" /><span>Changes</span>- <span class={cn('text-xs', props.capturing && 'animate-pulse')}>- <DiffCounts additions={props.additions} deletions={props.deletions} />- </span>+ <Show when={props.additions > 0 || props.deletions > 0}>+ <span class={cn('text-xs', props.capturing && 'animate-pulse')}>+ <DiffCounts additions={props.additions} deletions={props.deletions} />+ </span>+ </Show></Button>);}diff --git a/apps/web/src/features/agent-changes/components/DiffCounts.tsx b/apps/web/src/features/agent-changes/components/DiffCounts.tsxindex d1dec335fb..7737e0f165 100644--- a/apps/web/src/features/agent-changes/components/DiffCounts.tsx+++ b/apps/web/src/features/agent-changes/components/DiffCounts.tsx@@ -1,9 +1,17 @@+import { Show } from 'solid-js';+/** Numeric line totals shared by the viewer and its entry controls. */export function DiffCounts(props: { additions: number; deletions: number }) {return (- <span class="inline-flex shrink-0 items-center gap-2 font-mono tabular-nums">- <span class="text-success">{`+${props.additions}`}</span>- <span class="text-failure">{`−${props.deletions}`}</span>- </span>+ <Show when={props.additions > 0 || props.deletions > 0}>+ <span class="inline-flex shrink-0 items-center gap-2 font-mono tabular-nums">+ <Show when={props.additions > 0}>+ <span class="text-success">{`+${props.additions}`}</span>+ </Show>+ <Show when={props.deletions > 0}>+ <span class="text-failure">{`−${props.deletions}`}</span>+ </Show>+ </span>+ </Show>);}diff --git a/apps/web/src/features/agent-changes/context/agent-changes-context.ts b/apps/web/src/features/agent-changes/context/agent-changes-context.tsindex a74dfe14e0..6ac782faf1 100644--- a/apps/web/src/features/agent-changes/context/agent-changes-context.ts+++ b/apps/web/src/features/agent-changes/context/agent-changes-context.ts@@ -56,6 +56,10 @@ export type ChangesHost = {* empty pane.*/canHaveChanges?: Accessor<boolean>;+ /** GitHub API totals; undefined while unavailable, with no estimated fallback. */+ pullRequestChangeCounts?: Accessor<+ { additions: number; deletions: number } | undefined+ >;/** The pull request represented by the source. */pullRequestUrl: Accessor<string | undefined>;openExternal: (url: string) => void;diff --git a/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts b/apps/web/src/features/agent-changes/primitives/create-agent-changes.tsindex 231b0ad869..96a878816d 100644--- a/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts+++ b/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts@@ -25,6 +25,8 @@ export type AgentChangesController = {available: Accessor<boolean>;layout: PaneLayoutController;model: ChangesModel;+ /** Authoritative PR totals shared by the session header and sidebar. */+ changeCounts: Accessor<{ additions: number; deletions: number } | undefined>;review: ReviewController;diffStyle: Accessor<DiffStyle>;setDiffStyle: (style: DiffStyle) => void;@@ -99,6 +101,10 @@ export function createAgentChanges(options: {available: () => host.canHaveChanges?.() ?? true,layout,model,+ changeCounts: () =>+ host.pullRequestChangeCounts+ ? host.pullRequestChangeCounts()+ : model.changeset(),review,diffStyle,setDiffStyle,diff --git a/apps/web/src/features/agent-changes/queries/keys.ts b/apps/web/src/features/agent-changes/queries/keys.tsnew file mode 100644index 0000000000..7bd4b5796a--- /dev/null+++ b/apps/web/src/features/agent-changes/queries/keys.ts@@ -0,0 +1,7 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';++export const agentChangesKeys = createQueryKeys('agent-changes', {+ pullRequestStats: (githubKey: string, captureId: string) => ({+ queryKey: [githubKey, captureId],+ }),+});diff --git a/apps/web/src/features/agent-changes/queries/pull-request-stats.test.ts b/apps/web/src/features/agent-changes/queries/pull-request-stats.test.tsnew file mode 100644index 0000000000..d757fc100a--- /dev/null+++ b/apps/web/src/features/agent-changes/queries/pull-request-stats.test.ts@@ -0,0 +1,104 @@+import { authServiceClient } from '@service-auth/client';+import { err, ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { pullRequestStatsQueryOptions } from './pull-request-stats';++vi.mock('@service-auth/client', () => ({+ authServiceClient: { enrichGithubPullRequests: vi.fn() },+}));++const reference = {+ owner: 'macro-inc',+ repo: 'macro',+ number: 42,+ githubKey: 'macro-inc/macro/pull/42',+ displayName: 'macro-inc/macro#42',+ url: 'https://github.com/macro-inc/macro/pull/42',+};+const enrich = vi.mocked(authServiceClient.enrichGithubPullRequests);++beforeEach(() => vi.clearAllMocks());++describe('GitHub PR statistics', () => {+ it('requests the linked PR and returns GitHub totals unchanged', async () => {+ enrich.mockResolvedValue(+ ok({ pullRequests: [{ ...reference, additions: 728, deletions: 193 }] })+ );+ expect(await pullRequestStatsQueryOptions(reference.url).queryFn()).toEqual(+ { additions: 728, deletions: 193 }+ );+ expect(enrich).toHaveBeenCalledWith({ pullRequests: [reference] });+ });++ it('preserves real zero totals', async () => {+ enrich.mockResolvedValue(+ ok({ pullRequests: [{ ...reference, additions: 0, deletions: 0 }] })+ );+ expect(await pullRequestStatsQueryOptions(reference.url).queryFn()).toEqual(+ { additions: 0, deletions: 0 }+ );+ });++ it('treats missing enrichment as unavailable rather than zero', async () => {+ enrich.mockResolvedValue(ok({ pullRequests: [reference] }));+ expect(+ await pullRequestStatsQueryOptions(reference.url).queryFn()+ ).toBeNull();+ });++ it('does not substitute another PR or partial counts', async () => {+ enrich.mockResolvedValue(+ ok({+ pullRequests: [+ {+ ...reference,+ githubKey: 'other/repo/pull/1',+ additions: 8,+ deletions: 9,+ },+ ],+ })+ );+ expect(+ await pullRequestStatsQueryOptions(reference.url).queryFn()+ ).toBeNull();+ enrich.mockResolvedValue(+ ok({ pullRequests: [{ ...reference, additions: 8, deletions: null }] })+ );+ expect(+ await pullRequestStatsQueryOptions(reference.url).queryFn()+ ).toBeNull();+ });++ it('does not request statistics without a PR', async () => {+ for (const url of [undefined, 'not a PR']) {+ const query = pullRequestStatsQueryOptions(url);+ expect(query.enabled).toBe(false);+ expect(await query.queryFn()).toBeNull();+ }+ expect(enrich).not.toHaveBeenCalled();+ });++ it('propagates GitHub authentication errors without inventing totals', async () => {+ enrich.mockResolvedValue(+ err([{ code: 'REAUTHENTICATION_REQUIRED', message: 'Reconnect GitHub' }])+ );+ await expect(+ pullRequestStatsQueryOptions(reference.url).queryFn()+ ).rejects.toThrow();+ });++ it('isolates PRs and captures and periodically refreshes GitHub', () => {+ const first = pullRequestStatsQueryOptions(reference.url, 'capture-1');+ expect(first.queryKey).not.toEqual(+ pullRequestStatsQueryOptions(reference.url, 'capture-2').queryKey+ );+ expect(first.queryKey).not.toEqual(+ pullRequestStatsQueryOptions(+ 'https://github.com/macro-inc/macro/pull/43',+ 'capture-1'+ ).queryKey+ );+ expect(first.refetchInterval).toBe(30_000);+ });+});diff --git a/apps/web/src/features/agent-changes/queries/pull-request-stats.ts b/apps/web/src/features/agent-changes/queries/pull-request-stats.tsnew file mode 100644index 0000000000..9c113e76c7--- /dev/null+++ b/apps/web/src/features/agent-changes/queries/pull-request-stats.ts@@ -0,0 +1,58 @@+import { throwOnErr } from '@core/util/result';+import { authServiceClient } from '@service-auth/client';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import {+ parseGithubPrUrl,+ prDisplayName,+ prHtmlUrl,+ toGithubKey,+} from '../../block-pr/util/prKey';+import { agentChangesKeys } from './keys';++export function pullRequestStatsQueryOptions(+ url: string | undefined,+ captureId?: string+) {+ const reference = url ? parseGithubPrUrl(url) : null;+ const githubKey = reference ? toGithubKey(reference) : '';+ return {+ queryKey: agentChangesKeys.pullRequestStats(githubKey, captureId ?? '')+ .queryKey,+ enabled: reference !== null,+ queryFn: async () => {+ if (!reference) return null;+ // The auth-service proxy calls GitHub with the viewer's linked account.+ const response = await throwOnErr(() =>+ authServiceClient.enrichGithubPullRequests({+ pullRequests: [+ {+ ...reference,+ githubKey,+ displayName: prDisplayName(reference),+ url: prHtmlUrl(reference),+ },+ ],+ })+ );+ const pr = response.pullRequests.find((pr) => pr.githubKey === githubKey);+ // Enrichment can return a bare reference when GitHub is unavailable.+ if (pr?.additions == null || pr.deletions == null) return null;+ return { additions: pr.additions, deletions: pr.deletions };+ },+ staleTime: 30_000,+ refetchInterval: 30_000,+ retry: false,+ };+}++/** One guarded source shared by the header and sidebar; never suspends them. */+export function createPullRequestStatsSource(+ url: Accessor<string | undefined>,+ captureId: Accessor<string | undefined>+) {+ const query = useQuery(() =>+ pullRequestStatsQueryOptions(url(), captureId())+ );+ return () => (query.isSuccess ? (query.data ?? undefined) : undefined);+}diff --git a/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx b/apps/web/src/features/agent-changes/views/SessionChangesControls.tsxindex c41a29d8f5..e5d2a41e84 100644--- a/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx+++ b/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx@@ -15,14 +15,18 @@ import { useOptionalAgentChanges } from '../context/agent-changes-controller';export function ChangesToggle() {const controller = useOptionalAgentChanges();if (!controller) return null;- const { available, layout, model } = controller;+ const { available, layout, model, context } = controller;+ const counts = controller.changeCounts;return (<Show when={available()}><ChangesToggleButtonopen={layout.changesVisible()}- additions={model.changeset()?.additions ?? 0}- deletions={model.changeset()?.deletions ?? 0}- capturing={model.state().kind === 'capturing'}+ additions={counts()?.additions ?? 0}+ deletions={counts()?.deletions ?? 0}+ capturing={+ !context.host.pullRequestChangeCounts &&+ model.state().kind === 'capturing'+ }onToggle={layout.toggle}/></Show>@@ -43,8 +47,8 @@ export function ChangesHandoff() {<Show when={visible()}><ChangesReadyCardfileCount={model.files().length}- additions={model.changeset()?.additions ?? 0}- deletions={model.changeset()?.deletions ?? 0}+ additions={controller.changeCounts()?.additions ?? 0}+ deletions={controller.changeCounts()?.deletions ?? 0}linkedUrl={context.host.pullRequestUrl()}onReview={() => {const first = model.files()[0];diff --git a/apps/web/src/features/agent-changes/views/changes-pane.test.tsx b/apps/web/src/features/agent-changes/views/changes-pane.test.tsxindex b2a3fef00f..cf5a1e67ba 100644--- a/apps/web/src/features/agent-changes/views/changes-pane.test.tsx+++ b/apps/web/src/features/agent-changes/views/changes-pane.test.tsx@@ -234,6 +234,52 @@ describe('session controls', () => {expect(toggle.getAttribute('aria-pressed')).toBe('true');});+ it('uses GitHub API totals without falling back to captured estimates', () => {+ const context = readyContext();+ const [counts, setCounts] = createSignal<+ { additions: number; deletions: number } | undefined+ >({ additions: 8, deletions: 2 });+ context.host.pullRequestChangeCounts = counts;+ const { controller } = mount(context, () => <ChangesToggle />);+ const toggle = screen.getByRole('button', { name: /Changes/ });+ expect(toggle.textContent).toBe('Changes+8−2');++ // A missing or stale PR capture must not replace GitHub totals.+ context.setSummary(undefined);+ expect(toggle.textContent).toBe('Changes+8−2');+ context.setSummary({ capturing: true, changeset: mockChangeset() });+ expect(toggle.textContent).toBe('Changes+8−2');+ expect(toggle.querySelector('.animate-pulse')).toBeNull();+ expect(controller().changeCounts()).toEqual({ additions: 8, deletions: 2 });+ // Missing GitHub data must not expose the snapshot's +3 / −1 estimates.+ setCounts(undefined);+ expect(toggle.textContent).toBe('Changes');+ expect(controller().changeCounts()).toBeUndefined();++ setCounts({ additions: 12, deletions: 0 });+ expect(toggle.textContent).toBe('Changes+12');+ setCounts({ additions: 0, deletions: 4 });+ expect(toggle.textContent).toBe('Changes−4');+ setCounts({ additions: 0, deletions: 0 });+ expect(toggle.textContent).toBe('Changes');+ fireEvent.click(toggle);+ expect(controller().layout.changesVisible()).toBe(true);+ });++ it('does not display fake zero counts before a snapshot loads or for empty snapshots', () => {+ const context = createMockAgentChangesContext();+ mount(context, () => <ChangesToggle />);+ const toggle = screen.getByRole('button', { name: /Changes/ });+ expect(toggle.textContent).toBe('Changes');+ context.setSummary({+ capturing: false,+ changeset: mockChangeset({ files: [], additions: 0, deletions: 0 }),+ });+ expect(toggle.textContent).toBe('Changes');+ context.setSummary({ capturing: false, changeset: mockChangeset() });+ expect(toggle.textContent).toBe('Changes+3−1');+ });+it('hands off to the pane while it is closed, and can be dismissed', () => {const context = readyContext();const { controller } = mount(context, () => <ChangesHandoff />);diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsxindex 1e9f738fc7..cfd7e0d53b 100644--- a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx@@ -5,11 +5,12 @@* `<SidePanel.Section>` elements that self-register into the enclosing* `<SidePanel.Layout>`.*- * Everything rendered here is derived from state the block already holds —- * the session record, the fold's metadata, and pure summaries over the- * folded transcript (`state/session-summary.ts`).+ * Session details and activity use the live fold; changed files and totals+ * use the shared PR changes controller.*/+import { DiffCounts } from '@app/features/agent-changes/components/DiffCounts';+import { useOptionalAgentChanges } from '@app/features/agent-changes/context/agent-changes-controller';import { SidePanel } from '@components/app/side-panel';import { formatDate } from '@core/util/date';import { openExternalUrl } from '@core/util/url';@@ -17,17 +18,8 @@ import GitBranch from '@phosphor/git-branch.svg';import { createMemo, For, Show } from 'solid-js';import { useAgentSession } from '../../context/AgentSessionContext';import { sessionStatus } from '../../state/session-status';-import {- activityCounts,- changedFiles,- latestPlan,-} from '../../state/session-summary';-import {- CountSummary,- DiffChanges,- SessionStatusPill,- TodoList,-} from '../../ui';+import { activityCounts, latestPlan } from '../../state/session-summary';+import { CountSummary, SessionStatusPill, TodoList } from '../../ui';import { AgentPullRequestChip } from '../AgentPullRequestChip';import {sessionHarnessTitle,@@ -38,12 +30,10 @@ export function AgentSidePanelSections() {const { session, bot, metadata, messages } = useAgentSession();const plan = createMemo(() => latestPlan(messages()));- const files = createMemo(() => changedFiles(messages()));+ const changes = useOptionalAgentChanges();+ const files = () => changes?.model.files() ?? [];const activity = createMemo(() => activityCounts(messages()));- const totals = createMemo(() => ({- additions: files().reduce((sum, file) => sum + file.additions, 0),- deletions: files().reduce((sum, file) => sum + file.deletions, 0),- }));+ const totals = () => changes?.changeCounts();return (<>@@ -147,7 +137,11 @@ export function AgentSidePanelSections() {}defaultOpenorder={20}- actions={<DiffChanges variant="bars" {...totals()} />}+ actions={+ <Show when={totals()}>+ {(counts) => <DiffCounts {...counts()} />}+ </Show>+ }><div class="flex flex-col gap-1"><For each={files()}>@@ -159,7 +153,7 @@ export function AgentSidePanelSections() {>{file.path}</span>- <DiffChanges+ <DiffCountsadditions={file.additions}deletions={file.deletions}/>diff --git a/apps/web/src/features/block-agent/state/session-summary.test.ts b/apps/web/src/features/block-agent/state/session-summary.test.tsindex 086e8d21ab..1e16da09f8 100644--- a/apps/web/src/features/block-agent/state/session-summary.test.ts+++ b/apps/web/src/features/block-agent/state/session-summary.test.ts@@ -5,7 +5,6 @@ import type {import { describe, expect, it } from 'vitest';import {activityCounts,- changedFiles,countDiffChanges,latestPlan,} from './session-summary';@@ -76,27 +75,6 @@ describe('latestPlan', () => {});});-describe('changedFiles', () => {- it('sums stats per path across edits, in first-touched order', () => {- const messages = [- message(0, [- edit([{ path: 'a.ts', oldText: 'x\n', newText: 'x\ny\n' }]),- edit([{ path: 'b.ts', oldText: null, newText: 'one\ntwo\n' }]),- ]),- message(1, [edit([{ path: 'a.ts', oldText: 'y\n', newText: 'z\n' }])]),- ];- expect(changedFiles(messages)).toEqual([- { path: 'a.ts', additions: 2, deletions: 1 },- { path: 'b.ts', additions: 2, deletions: 0 },- ]);- });-- it('ignores non-edit tools', () => {- const messages = [message(0, [tool({ kind: 'read', paths: ['a.ts'] })])];- expect(changedFiles(messages)).toEqual([]);- });-});-describe('subagent descent', () => {it("counts a subagent's edits and tool calls as the session's", () => {const nested = edit([{ path: 'b.rs', oldText: 'x\n', newText: 'y\n' }]);@@ -117,7 +95,6 @@ describe('subagent descent', () => {},};const messages = [message(0, [subagent])];- expect(changedFiles(messages).map((file) => file.path)).toEqual(['b.rs']);const counts = Object.fromEntries(activityCounts(messages).map((item) => [item.key, item.count]));diff --git a/apps/web/src/features/block-agent/state/session-summary.ts b/apps/web/src/features/block-agent/state/session-summary.tsindex d3f57ea8c5..f185f6f030 100644--- a/apps/web/src/features/block-agent/state/session-summary.ts+++ b/apps/web/src/features/block-agent/state/session-summary.ts@@ -42,12 +42,6 @@ export function latestPlan(messages: FoldedMessage[]): PlanEntry[] | undefined {return undefined;}-export type ChangedFile = {- path: string;- additions: number;- deletions: number;-};-/*** Every tool call in the transcript, in order, descending into the calls a* subagent made: a file the subagent edited is a file the session edited.@@ -64,30 +58,6 @@ function* toolCalls(}}-/**- * Every file the session's edit tools touched, in first-touched order, with- * line stats summed across all edits of that file.- */-export function changedFiles(messages: FoldedMessage[]): ChangedFile[] {- const byPath = new Map<string, ChangedFile>();- for (const message of messages) {- for (const part of toolCalls(message.parts)) {- if (part.detail.kind !== 'edit') continue;- for (const diff of part.detail.diffs) {- const changes = countDiffChanges([diff]);- const existing = byPath.get(diff.path);- if (existing) {- existing.additions += changes.additions;- existing.deletions += changes.deletions;- } else {- byPath.set(diff.path, { path: diff.path, ...changes });- }- }- }- }- return [...byPath.values()];-}-/*** Tool-call counts by kind, shaped for `ui/CountSummary` ("3 files read,* 2 searches"). Zero-count items are included — the summary component slidesdiff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex b5f138d351..f8a5d8b86f 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -463,6 +463,13 @@ that file in the Changes pane. Notes never go to GitHub. Collapsed files andunsent notes persist per session in localStorage; a new capture expands allfiles.+The session header's **Changes** pill and sidebar totals display the linked+PR's `additions` and `deletions` returned by the GitHub API, without summing+transcript edits. The sidebar lists files from the captured PR diff. Counts+refresh when a capture changes and every 30 seconds while the session is open.+Zero-valued counts and unavailable GitHub statistics are hidden; a missing PR+or failed GitHub request never falls back to estimated transcript totals.+While the pane is closed and a capture has files, a **Changes ready toreview** card sits above the composer with **Review changes**, **Pull request#N** (opens GitHub), and **Dismiss**. With no linked PR, the pane explains