Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(agents): add a compact GitHub PR status chip to agent sessions (#6492)

Wolf Mermelsteine8ebebd94803
diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
index ed1c34c2d4..ce07e7bf11 100644
--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
@@ -1,4 +1,5 @@
import { AgentComposer } from '@app/features/block-agent/component/AgentComposer';
+import { AgentPullRequestChip } from '@app/features/block-agent/component/AgentPullRequestChip';
import { Transcript } from '@app/features/block-agent/component/Transcript';
import {
AgentSessionProvider,
@@ -17,10 +18,13 @@ function AgentSessionContent() {
return (
<>
- <header class="flex h-12 shrink-0 items-center border-b border-edge px-4">
- <h2 class="truncate text-sm font-semibold text-ink">
+ <header class="flex h-12 shrink-0 items-center justify-between gap-3 border-b border-edge px-4">
+ <h2 class="min-w-0 truncate text-sm font-semibold text-ink">
{metadata()?.title ?? session()?.name ?? 'New Chat'}
</h2>
+ <Show when={session()?.pullRequestUrl}>
+ {(url) => <AgentPullRequestChip url={url()} />}
+ </Show>
</header>
<Show
when={!loadFailed()}
diff --git a/apps/web/src/features/block-agent/component/AgentPullRequestChip.test.tsx b/apps/web/src/features/block-agent/component/AgentPullRequestChip.test.tsx
new file mode 100644
index 0000000000..c566fb644c
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/AgentPullRequestChip.test.tsx
@@ -0,0 +1,161 @@
+/** @vitest-environment jsdom */
+import { queryClient } from '@queries/client';
+import { handlePullRequestUpdated } from '@queries/storage/pr-mention-sync';
+import { storageServiceClient } from '@service-storage/client';
+import type { ForeignEntity } from '@service-storage/generated/schemas';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { err } from 'neverthrow';
+import { Suspense } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { AgentPullRequestChip } from './AgentPullRequestChip';
+
+const { openWithSplit } = vi.hoisted(() => {
+ class FakeWebSocket {
+ url: string;
+ readyState = 1;
+ constructor(url: string) {
+ this.url = url;
+ }
+ close() {}
+ addEventListener() {}
+ removeEventListener() {}
+ send() {}
+ }
+ vi.stubGlobal('WebSocket', FakeWebSocket);
+ return { openWithSplit: vi.fn() };
+});
+
+vi.mock('@queries/client', async () => {
+ const { QueryClient } = await import('@tanstack/solid-query');
+ return {
+ queryClient: new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+ };
+});
+
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: { getForeignEntityBySource: vi.fn() },
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
+ createConnectionWebsocketEffect: vi.fn(),
+ parseWebsocketPayload: vi.fn(),
+}));
+vi.mock('@components/app/split-layout/layout', () => ({
+ useSplitLayout: () => ({ openWithSplit }),
+}));
+vi.mock('@core/util/useSplitNavigationHandler', () => ({
+ useSplitNavigationHandler: (onClick: (event: MouseEvent) => void) => ({
+ onClick,
+ }),
+}));
+vi.mock('@core/component/HoverCard', () => ({
+ HoverCard: (props: { trigger: import('solid-js').JSX.Element }) =>
+ props.trigger,
+}));
+vi.mock(
+ '@core/component/LexicalMarkdown/component/decorator/PullRequestMention',
+ () => ({
+ PullRequestPreviewCard: () => null,
+ })
+);
+
+const url = 'https://github.com/macro-inc/macro/pull/6303';
+
+function entity(status: string): ForeignEntity {
+ return {
+ id: '019f0000-0000-7000-8000-000000000001',
+ foreignEntityId: 'macro-inc/macro/pull/6303',
+ foreignEntitySource: 'github_pull_request',
+ metadata: { status, name: 'Add the header chip', number: 6303 },
+ storedForId: 'macro|[email protected]',
+ storedForAuthEntity: 'user',
+ createdAt: '2026-09-11T00:00:00Z',
+ updatedAt: '2026-09-11T00:00:00Z',
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ queryClient.clear();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+it('shows a GitHub fallback without suspending while the webhook mapping is pending', async () => {
+ type Lookup = ReturnType<
+ typeof storageServiceClient.getForeignEntityBySource
+ >;
+ let resolve!: (value: Awaited<Lookup>) => void;
+ vi.mocked(storageServiceClient.getForeignEntityBySource).mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }) as Lookup
+ );
+ const client = new QueryClient();
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Suspense fallback={<span>Loading chip</span>}>
+ <AgentPullRequestChip url={url} />
+ </Suspense>
+ </QueryClientProvider>
+ ));
+ const link = screen.getByRole('link');
+ expect(link.getAttribute('href')).toBe(url);
+ expect(link.textContent).toContain('#6303');
+ expect(link.textContent).toContain('Open');
+ expect(screen.queryByText('Loading chip')).toBeNull();
+ resolve(
+ err([{ code: 'NOT_FOUND', message: 'Not synced' }]) as Awaited<Lookup>
+ );
+ await waitFor(() =>
+ expect(client.getQueryCache().getAll()[0].state.status).toBe('success')
+ );
+ expect(screen.getByRole('link').getAttribute('href')).toBe(url);
+ client.clear();
+});
+
+it('opens the PR entity once synced and follows later status changes', async () => {
+ vi.useFakeTimers();
+ const lookup = vi.mocked(storageServiceClient.getForeignEntityBySource);
+ type Lookup = ReturnType<
+ typeof storageServiceClient.getForeignEntityBySource
+ >;
+ lookup.mockResolvedValue(
+ err([{ code: 'NOT_FOUND', message: 'Not synced' }]) as Awaited<Lookup>
+ );
+ const client = queryClient;
+ const rendered = render(() => (
+ <QueryClientProvider client={client}>
+ <AgentPullRequestChip url={url} />
+ </QueryClientProvider>
+ ));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(screen.getByRole('link')).toBeTruthy();
+ await handlePullRequestUpdated(entity('open'));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(screen.getByRole('button').textContent).toContain('#6303');
+ expect(screen.getByRole('button').textContent).toContain('Open');
+ fireEvent.click(screen.getByRole('button'));
+ expect(openWithSplit).toHaveBeenCalledWith(
+ { type: 'pr', id: entity('open').id },
+ { preferNewSplit: true }
+ );
+ await handlePullRequestUpdated({
+ ...entity('merged'),
+ metadata: { status: 'merged', name: 'Add the header chip', number: 6303 },
+ updatedAt: '2026-09-11T00:01:00Z',
+ });
+ await vi.advanceTimersByTimeAsync(1);
+ expect(screen.getByRole('button').textContent).toContain('Merged');
+ rendered.unmount();
+ client.clear();
+});
diff --git a/apps/web/src/features/block-agent/component/AgentPullRequestChip.tsx b/apps/web/src/features/block-agent/component/AgentPullRequestChip.tsx
new file mode 100644
index 0000000000..d54a100dc0
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/AgentPullRequestChip.tsx
@@ -0,0 +1,184 @@
+/**
+ * Compact header chip for the session's linked pull request: `#N` plus
+ * status, opening the PR entity once GitHub has synced it. Cloud runtimes
+ * can report the URL before the webhook entity exists; until then this is
+ * a GitHub link with the same face.
+ */
+
+import { GithubPullRequestStatusIcon } from '@app/features/block-pr/side-panel/github-pull-request';
+import {
+ parseGithubPrUrl,
+ toGithubKey,
+} from '@app/features/block-pr/util/prKey';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { HoverCard } from '@core/component/HoverCard';
+import { PullRequestPreviewCard } from '@core/component/LexicalMarkdown/component/decorator/PullRequestMention';
+import { openInNewSplitForMention } from '@core/util/openInNewSplit';
+import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
+import { usePullRequestByGithubKeyQuery } from '@queries/storage/pr-mention';
+import type { ForeignEntity } from '@service-storage/generated/schemas';
+import { cn, Layer } from '@ui';
+import { createMemo, type JSX, type ParentProps, Show } from 'solid-js';
+import { match } from 'ts-pattern';
+
+function metadataRecord(metadata: unknown): Record<string, unknown> {
+ if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {
+ return metadata as Record<string, unknown>;
+ }
+ return {};
+}
+
+function optionalString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value : undefined;
+}
+
+function pullRequestStatus(entity: ForeignEntity | undefined): string {
+ if (!entity || entity.foreignEntitySource !== 'github_pull_request') {
+ return 'open';
+ }
+ return optionalString(metadataRecord(entity.metadata).status) ?? 'open';
+}
+
+function pullRequestTitle(
+ entity: ForeignEntity | undefined
+): string | undefined {
+ if (!entity || entity.foreignEntitySource !== 'github_pull_request') {
+ return undefined;
+ }
+ return optionalString(metadataRecord(entity.metadata).name);
+}
+
+function statusTextClass(status: string): string {
+ return match(status)
+ .with('merged', () => 'text-note')
+ .with('closed', () => 'text-failure')
+ .otherwise(() => 'text-success');
+}
+
+function capitalize(value: string): string {
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
+function ChipFace(props: {
+ status: string;
+ number?: number;
+ title?: string;
+}): JSX.Element {
+ const label = () =>
+ props.number != null ? `#${props.number}` : 'Pull request';
+
+ return (
+ <>
+ <GithubPullRequestStatusIcon
+ status={props.status}
+ class="size-3 shrink-0"
+ />
+ <span
+ class="min-w-0 truncate tabular-nums"
+ title={props.title ?? label()}
+ >
+ {label()}
+ </span>
+ <span class={cn('shrink-0', statusTextClass(props.status))}>
+ {capitalize(props.status)}
+ </span>
+ </>
+ );
+}
+
+/** Shared pill chrome for the GitHub fallback and the entity button. */
+function ChipShell(props: ParentProps): JSX.Element {
+ return (
+ <span class="inline-flex h-7 max-w-44 min-w-0 items-center gap-1 rounded-full border border-edge-muted bg-surface px-2 text-xs leading-none text-ink-muted hover:bg-hover hover:text-ink">
+ {props.children}
+ </span>
+ );
+}
+
+function GithubFallback(props: { url: string; number?: number }): JSX.Element {
+ return (
+ <a
+ href={props.url}
+ target="_blank"
+ rel="noreferrer"
+ data-agent-pull-request={props.url}
+ title={
+ props.number != null
+ ? `Open #${props.number} on GitHub`
+ : 'Open pull request on GitHub'
+ }
+ onClick={(event) => event.stopPropagation()}
+ >
+ <ChipShell>
+ <ChipFace status="open" number={props.number} />
+ </ChipShell>
+ </a>
+ );
+}
+
+function EntityChip(props: {
+ entity: ForeignEntity;
+ number?: number;
+}): JSX.Element {
+ const { openWithSplit } = useSplitLayout();
+ const status = () => pullRequestStatus(props.entity);
+ const title = () => pullRequestTitle(props.entity);
+ const open = (event: MouseEvent | KeyboardEvent) => {
+ event.stopPropagation();
+ openWithSplit(
+ { type: 'pr', id: props.entity.id },
+ { preferNewSplit: openInNewSplitForMention(event.shiftKey, true) }
+ );
+ };
+ const navHandlers = useSplitNavigationHandler<HTMLButtonElement>(open);
+
+ return (
+ <HoverCard
+ triggerClass="min-w-0 max-w-full"
+ trigger={
+ <button
+ type="button"
+ data-agent-pull-request={props.entity.id}
+ data-pr-entity-link={props.entity.id}
+ title={
+ title() ??
+ (props.number != null
+ ? `Open #${props.number}`
+ : 'Open pull request')
+ }
+ {...navHandlers}
+ >
+ <ChipShell>
+ <ChipFace status={status()} number={props.number} title={title()} />
+ </ChipShell>
+ </button>
+ }
+ content={<PullRequestPreviewCard id={props.entity.id} />}
+ />
+ );
+}
+
+export function AgentPullRequestChip(props: { url: string }): JSX.Element {
+ const reference = createMemo(() => parseGithubPrUrl(props.url));
+ const githubKey = createMemo(() => {
+ const parsed = reference();
+ return parsed ? toGithubKey(parsed) : undefined;
+ });
+ const query = usePullRequestByGithubKeyQuery(githubKey);
+ const entity = () => (query.isSuccess ? query.data : undefined);
+
+ return (
+ <Layer depth={2}>
+ <Show
+ when={entity()}
+ fallback={
+ <GithubFallback url={props.url} number={reference()?.number} />
+ }
+ >
+ {(synced) => (
+ <EntityChip entity={synced()} number={reference()?.number} />
+ )}
+ </Show>
+ </Layer>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx
index 6b1d91d708..c26a4b1610 100644
--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx
+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx
@@ -26,14 +26,15 @@ import ShareIcon from '@phosphor/share.svg';
import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';
import { createSignal, For, Show, Suspense } from 'solid-js';
import { useAgentSession } from '../context/AgentSessionContext';
+import { AgentPullRequestChip } from './AgentPullRequestChip';
import { harnessTitle } from './compose-agent-session-options';
export { harnessTitle };
/**
* Agent-session identity in the split header chrome plus the standard split
- * toolbar: static label, shared entity actions, and session-specific
- * repository and external-provider links.
+ * toolbar: static label, shared entity actions, the session's pull request
+ * once one exists, and external-provider links.
*
* Rename lives on the title menu (channel / automation), not on a tap of
* the name — `StaticSplitLabel` without `onRename` so a touch tap opens
@@ -136,9 +137,12 @@ export function AgentSplitHeader(props: {
would push non-Share tools onto a second toolbar row. Markup
mirrors its own header-tools branch; on mobile the tools collapse
into the title menu via `menuTools` below instead. */}
- <Show when={!isMobile()}>
- <SplitHeaderRight>
- <div class="order-[1000] flex items-center gap-1">
+ <SplitHeaderRight>
+ <div class="order-[1000] flex items-center gap-1.5">
+ <Show when={props.session?.pullRequestUrl}>
+ {(url) => <AgentPullRequestChip url={url()} />}
+ </Show>
+ <Show when={!isMobile()}>
<For each={tools}>
{(tool) => (
<Show when={!tool.condition || tool.condition()}>
@@ -146,9 +150,9 @@ export function AgentSplitHeader(props: {
</Show>
)}
</For>
- </div>
- </SplitHeaderRight>
- </Show>
+ </Show>
+ </div>
+ </SplitHeaderRight>
<Show when={entity()}>
{(session) => (
diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
index b15def33da..88edffee1d 100644
--- a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
@@ -27,6 +27,7 @@ import {
SessionStatusPill,
TodoList,
} from '../../ui';
+import { AgentPullRequestChip } from '../AgentPullRequestChip';
import { harnessTitle } from '../AgentSplitHeader';
export function AgentSidePanelSections() {
@@ -84,6 +85,13 @@ export function AgentSidePanelSections() {
</SidePanel.Row>
)}
</Show>
+ <Show when={session()?.pullRequestUrl}>
+ {(url) => (
+ <SidePanel.Row label="Pull request">
+ <AgentPullRequestChip url={url()} />
+ </SidePanel.Row>
+ )}
+ </Show>
<Show when={session()?.createdAt}>
{(created) => (
<SidePanel.Row label="Created">
diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
index c97934f20b..9f4a6854f6 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
@@ -401,6 +401,35 @@ describe('createAgentSessionFeed live updates', () => {
expect(feed.session()?.name).toBe('Fix Flaky Tests');
});
+ it('adopts a linked pull request when the session row updates', async () => {
+ const { createAgentSessionFeed } = await import(
+ './create-agent-session-feed'
+ );
+ const { handleAgentSessionUpdated } = await import(
+ '@queries/agent-session/session-metadata-sync'
+ );
+ const feed = createRoot(() => createAgentSessionFeed(() => 'session'));
+ await flush();
+
+ expect(feed.session()?.pullRequestUrl).toBeUndefined();
+ worker.getSession = async () => ({
+ isErr: () => false,
+ value: {
+ id: 'session',
+ name: 'Agent Session',
+ modifiedAt: '2026-08-24T12:00:02Z',
+ harness: 'claude-code',
+ pullRequestUrl: 'https://github.com/macro-inc/macro/pull/6303',
+ },
+ });
+ await handleAgentSessionUpdated({ agentSessionId: 'session' });
+ await flush();
+
+ expect(feed.session()?.pullRequestUrl).toBe(
+ 'https://github.com/macro-inc/macro/pull/6303'
+ );
+ });
+
it('uses persisted state instead of a stale event payload', async () => {
const { createAgentSessionFeed } = await import(
'./create-agent-session-feed'
diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
index e872af1ea7..33eff9a851 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
@@ -12,7 +12,10 @@
import type { AgentSessionRenamedEvent } from '@queries/agent-session/realtime-protocol';
import { acquireAgentSessionFold } from '@queries/agent-session/session-fold';
-import { subscribeAgentSessionRenamed } from '@queries/agent-session/session-metadata-sync';
+import {
+ subscribeAgentSessionRenamed,
+ subscribeAgentSessionUpdated,
+} from '@queries/agent-session/session-metadata-sync';
import type {
FoldedMessage,
SessionMetadata,
@@ -209,6 +212,27 @@ export function createAgentSessionFeed(
})
);
+ let updateRefresh = 0;
+ onCleanup(
+ subscribeAgentSessionUpdated((event) => {
+ if (event.agentSessionId !== sessionId()) return;
+ const run = ++updateRefresh;
+ void (async () => {
+ const session = await agentHarnessServiceClient.get(
+ event.agentSessionId
+ );
+ if (
+ session.isErr() ||
+ run !== updateRefresh ||
+ event.agentSessionId !== sessionId()
+ ) {
+ return;
+ }
+ mutate((current) => (current ? session.value : current));
+ })();
+ })
+ );
+
const messages = () => list;
// A user-authored tail means a prompt is awaiting its reply — except when
// it is a control, which is user-authored, never gets a stop reason, and
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
index 294c576a4d..c2370dc626 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
@@ -339,7 +339,10 @@ function PullRequestPreviewBody(props: { id: string; fallbackLabel?: string }) {
);
}
-function PullRequestPreviewCard(props: { id: string; fallbackLabel?: string }) {
+export function PullRequestPreviewCard(props: {
+ id: string;
+ fallbackLabel?: string;
+}) {
return (
<div class="select-none overflow-hidden w-80 text-ink">
<Surface depth={3} class="rounded-xl shadow-lg shadow-drop-shadow">
diff --git a/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts b/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts
index b6c6d3b81b..1a93f2fe16 100644
--- a/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts
+++ b/apps/web/src/lib/queries/agent-session/session-metadata-sync.ts
@@ -6,6 +6,7 @@ import type {
} from './realtime-protocol';
const renameListeners = new Set<(event: AgentSessionRenamedEvent) => void>();
+const updateListeners = new Set<(event: AgentSessionUpdatedEvent) => void>();
/** Apply a server-persisted rename to active agent-session consumers. */
export function handleAgentSessionRenamed(
@@ -22,10 +23,19 @@ export function subscribeAgentSessionRenamed(
return () => renameListeners.delete(listener);
}
+/** Follow committed session-row changes (e.g. a linked pull request). */
+export function subscribeAgentSessionUpdated(
+ listener: (event: AgentSessionUpdatedEvent) => void
+): () => void {
+ updateListeners.add(listener);
+ return () => updateListeners.delete(listener);
+}
+
/** Cancel stale snapshots before refetching the committed session metadata. */
export async function handleAgentSessionUpdated(
event: AgentSessionUpdatedEvent
): Promise<void> {
+ for (const listener of updateListeners) listener(event);
const filters = {
queryKey: agentSessionKeys.detail(event.agentSessionId).queryKey,
exact: true,
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index ee38c549f8..970f30e754 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -270,6 +270,12 @@ to open the title menu (caret), then **Rename** — that opens the generic entit
rename dialog. Do not expect a tap on the name itself to start
an inline edit.
+When the session has opened a pull request, a compact `#N` status chip
+appears in the header (top right) and in the side-panel Details. Click it
+to open the PR entity in a split; until GitHub has synced the entity the
+chip is a GitHub link instead. The icon and status word follow open /
+merged / closed.
+
Tool groups and individual tool cards start collapsed. Expand a group to see
its calls, then expand an edit card to view its file diffs. Diff bodies load
only when their card opens; syntax highlighting may appear after the diff text.