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.

feat(reviews): add GitHub pull request reviews (#7115)

dev-rb689d4b1394fc
diff --git a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts b/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
index 89dde187c2..c137c0b064 100644
--- a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
+++ b/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
@@ -52,6 +52,8 @@ describe('application route search ownership', () => {
['/agents/session-1', 'the agents workspace'],
['/coders/session-1', 'a coding session'],
['/agent/session-1', 'the agent block'],
+ ['/reviews/pr/pr-1', 'a pull request in Reviews'],
+ ['/pr/pr-1', 'a standalone pull request'],
])('keeps the changes pane state on %s (%s)', (pathname) => {
expect(roundTrip(pathname, viewerState, false)).toContain(viewerState);
expect(roundTrip(pathname, viewerState, true)).toContain(viewerState);
diff --git a/apps/web/src/components/view-shell/ListDropdowns.tsx b/apps/web/src/components/view-shell/ListDropdowns.tsx
index b512ee9a3f..dc18e104b2 100644
--- a/apps/web/src/components/view-shell/ListDropdowns.tsx
+++ b/apps/web/src/components/view-shell/ListDropdowns.tsx
@@ -14,6 +14,8 @@ export type ListControlOption<TId extends string> = {
id: TId;
label: string;
icon?: () => JSX.Element;
+ /** Drawn in place of `label`, which still drives search. */
+ content?: () => JSX.Element;
disabled?: boolean;
};
@@ -73,7 +75,9 @@ function SingleSelectDropdown<TId extends string>(
{option.icon?.()}
</span>
</Show>
- <span class="flex-1">{option.label}</span>
+ <span class="flex-1">
+ {option.content?.() ?? option.label}
+ </span>
<Dropdown.ItemIndicator>
<CheckIcon class="size-3.5 text-accent" />
</Dropdown.ItemIndicator>
diff --git a/apps/web/src/features/agent-changes/README.md b/apps/web/src/features/agent-changes/README.md
index f198760e48..17e2e0aa91 100644
--- a/apps/web/src/features/agent-changes/README.md
+++ b/apps/web/src/features/agent-changes/README.md
@@ -22,9 +22,10 @@ path**, and review notes hang under their lines through `DiffView.Stack`'s
annotation slot. Another host composes the same components its own way.
The source owns fetching, cache identity, and conversion into the feature's core
-changeset types. A PR entity adapter should resolve its GitHub owner/repository/PR
-number and implement this same contract using shared queries. It does not need to
-construct an agent session. That adapter and its backend endpoint are not yet wired.
+changeset types. The PR page's adapter is `block-pr/data/pr-changes.ts`, over
+`GET /github_pull_requests/{id}/changes` and `/changes/patch` in the storage
+service; `block-pr/component/PrChanges.tsx` mounts it read-only under
+`pr:<foreign-entity-id>` without an agent session.
Layout and diff style come from `createPaneViewState()` (`pane-view-state.ts`).
Where the host's route lists `changesSearch.namespace` in its `search`, they live
diff --git a/apps/web/src/features/agent-changes/agent-changes.tsx b/apps/web/src/features/agent-changes/agent-changes.tsx
index 9ed2f7707d..9054f8a080 100644
--- a/apps/web/src/features/agent-changes/agent-changes.tsx
+++ b/apps/web/src/features/agent-changes/agent-changes.tsx
@@ -27,7 +27,7 @@ export {
ReviewNotesDock,
} from './views/SessionChangesControls';
-async function copyText(text: string): Promise<boolean> {
+export async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
diff --git a/apps/web/src/features/agent-changes/queries/session-changes.ts b/apps/web/src/features/agent-changes/queries/session-changes.ts
index d711ce1fc9..19e08474ba 100644
--- a/apps/web/src/features/agent-changes/queries/session-changes.ts
+++ b/apps/web/src/features/agent-changes/queries/session-changes.ts
@@ -83,7 +83,7 @@ export function decodeSessionChanges(
};
}
-function queryStatus(query: {
+export function queryStatus(query: {
isPending: boolean;
isError: boolean;
isSuccess: boolean;
diff --git a/apps/web/src/features/block-pr/component/Block.tsx b/apps/web/src/features/block-pr/component/Block.tsx
index a94d6b7b09..1d495148c1 100644
--- a/apps/web/src/features/block-pr/component/Block.tsx
+++ b/apps/web/src/features/block-pr/component/Block.tsx
@@ -12,7 +12,10 @@ export default function PrBlock() {
return (
<div class="size-full overflow-hidden flex flex-col relative">
<SidePanel.Layout floating>
- <PrSidePanelSections enrichment={detail.data()?.pullRequest} />
+ <PrSidePanelSections
+ enrichment={detail.data()?.pullRequest}
+ status={detail.query.status}
+ />
<div class="flex flex-col size-full min-w-0">
<Show when={detail.data()}>
{(data) => (
diff --git a/apps/web/src/features/block-pr/component/PrChanges.tsx b/apps/web/src/features/block-pr/component/PrChanges.tsx
new file mode 100644
index 0000000000..cdcb2371d0
--- /dev/null
+++ b/apps/web/src/features/block-pr/component/PrChanges.tsx
@@ -0,0 +1,45 @@
+/**
+ * The Changes pane on a pull request page: a read-only viewer over the pull
+ * request's changes at its current base and head. Review state is kept under
+ * `pr:<foreign-entity-id>`, apart from any agent session on the same pull
+ * request. Hosts place `AgentChangesSplit` and `ChangesToggle` inside.
+ */
+
+import { copyText } from '@app/features/agent-changes/agent-changes';
+import type { ChangesHost } from '@app/features/agent-changes/context/agent-changes-context';
+import { AgentChangesControllerProvider } from '@app/features/agent-changes/context/agent-changes-controller';
+import { createPaneViewState } from '@app/features/agent-changes/pane-view-state';
+import { createAgentChanges } from '@app/features/agent-changes/primitives/create-agent-changes';
+import { toast } from '@core/component/Toast/Toast';
+import { openExternalUrl } from '@core/util/url';
+import { createSignal, type ParentProps } from 'solid-js';
+import { createPrChangesSource } from '../data/pr-changes';
+
+export function PrChangesProvider(
+ props: ParentProps<{ foreignEntityId: string; pullRequestUrl?: string }>
+) {
+ const scopeKey = () => `pr:${props.foreignEntityId}`;
+ const source = createPrChangesSource(() => props.foreignEntityId);
+ const host: ChangesHost = {
+ scopeKey,
+ pullRequestUrl: () => props.pullRequestUrl,
+ openExternal: openExternalUrl,
+ copyText,
+ notify: (message, tone) => {
+ if (tone === 'success') toast.success(message);
+ else toast.failure(message);
+ },
+ };
+ const view = createPaneViewState();
+ const [dismissed, setDismissed] = createSignal<string>();
+ const controller = createAgentChanges({
+ context: { source, host },
+ view,
+ dismissed: [dismissed, (id) => setDismissed(id)],
+ });
+ return (
+ <AgentChangesControllerProvider value={controller}>
+ {props.children}
+ </AgentChangesControllerProvider>
+ );
+}
diff --git a/apps/web/src/features/block-pr/component/sidepanel/PrAgentSessionsSection.test.tsx b/apps/web/src/features/block-pr/component/sidepanel/PrAgentSessionsSection.test.tsx
new file mode 100644
index 0000000000..6871902824
--- /dev/null
+++ b/apps/web/src/features/block-pr/component/sidepanel/PrAgentSessionsSection.test.tsx
@@ -0,0 +1,97 @@
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import type { JSX } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const query = {
+ isPending: true,
+ isSuccess: false,
+ isError: false,
+ data: [] as string[],
+ refetch: vi.fn(),
+};
+let sessions = query;
+
+vi.mock('@components/app/side-panel', () => ({
+ SidePanel: { Section: (props: { children: JSX.Element }) => props.children },
+}));
+vi.mock('@components/app/split-layout/layout', () => ({
+ useSplitLayout: () => undefined,
+}));
+vi.mock('@app/components/view-shell', () => ({
+ ListFilterDropdown: () => null,
+}));
+vi.mock(
+ '@core/component/LexicalMarkdown/component/decorator/AgentSessionMentionLabel',
+ () => ({
+ AgentSessionMentionLabel: (props: { label: string }) => (
+ <span>{props.label}</span>
+ ),
+ })
+);
+vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));
+vi.mock('@queries/agent-session/mentions', () => ({
+ useAgentSessionMentionPreview: () => ({ isSuccess: false }),
+}));
+vi.mock('@queries/agent-session/pull-requests', () => ({
+ usePullRequestAgentSessionsQuery: () => sessions,
+ useAgentSessionPullRequestsQuery: () => ({ isSuccess: false }),
+ useLinkAgentSessionPullRequestMutation: () => ({}),
+ useUnlinkAgentSessionPullRequestMutation: () => ({}),
+}));
+vi.mock('@queries/soup/quick-access-agent-sessions', () => ({
+ useQuickAccessAgentSessionsQuery: () => ({ sessions: () => [] }),
+}));
+
+import { PrAgentSessionsSection } from './PrAgentSessionsSection';
+
+afterEach(cleanup);
+beforeEach(() => {
+ sessions = { ...query };
+});
+
+const url = 'https://github.com/org/repo/pull/7';
+
+describe('PR session loading states', () => {
+ it('does not call a pending PR an empty sessions list', () => {
+ render(() => <PrAgentSessionsSection prStatus="pending" />);
+ expect(screen.getByRole('status').textContent).toContain(
+ 'Loading pull request'
+ );
+ expect(screen.queryByText('No agent sessions')).toBeNull();
+ });
+
+ it('distinguishes missing PR details from missing sessions', () => {
+ render(() => <PrAgentSessionsSection prStatus="error" />);
+ expect(
+ screen.getByText('Pull request details couldn’t be loaded')
+ ).toBeTruthy();
+ expect(screen.queryByText('No agent sessions')).toBeNull();
+ });
+
+ it('does not call a successful PR without a URL an empty sessions list', () => {
+ render(() => <PrAgentSessionsSection prStatus="success" />);
+ expect(screen.getByText('Pull request URL isn’t available')).toBeTruthy();
+ expect(screen.queryByText('No agent sessions')).toBeNull();
+ });
+
+ it('shows loading until the sessions request succeeds', () => {
+ const [state, setState] = createStore({ ...query });
+ sessions = state;
+ render(() => <PrAgentSessionsSection url={url} prStatus="success" />);
+ expect(screen.getByRole('status').textContent).toContain(
+ 'Loading agent sessions'
+ );
+ expect(screen.queryByText('No agent sessions')).toBeNull();
+ setState({ isPending: false, isSuccess: true });
+ expect(screen.getByText('No agent sessions')).toBeTruthy();
+ });
+
+ it('distinguishes a failed sessions request from an empty list', () => {
+ sessions = { ...query, isPending: false, isError: true };
+ render(() => <PrAgentSessionsSection url={url} prStatus="success" />);
+ expect(screen.getByText('Agent sessions couldn’t be loaded')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();
+ expect(screen.queryByText('No agent sessions')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-pr/component/sidepanel/PrAgentSessionsSection.tsx b/apps/web/src/features/block-pr/component/sidepanel/PrAgentSessionsSection.tsx
new file mode 100644
index 0000000000..1ff49aeb20
--- /dev/null
+++ b/apps/web/src/features/block-pr/component/sidepanel/PrAgentSessionsSection.tsx
@@ -0,0 +1,203 @@
+import { ListFilterDropdown } from '@app/components/view-shell';
+import { SidePanel } from '@components/app/side-panel';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { AgentSessionMentionLabel } from '@core/component/LexicalMarkdown/component/decorator/AgentSessionMentionLabel';
+import { toast } from '@core/component/Toast/Toast';
+import PlusIcon from '@phosphor/plus.svg';
+import XIcon from '@phosphor/x.svg';
+import { useAgentSessionMentionPreview } from '@queries/agent-session/mentions';
+import {
+ useAgentSessionPullRequestsQuery,
+ useLinkAgentSessionPullRequestMutation,
+ usePullRequestAgentSessionsQuery,
+ useUnlinkAgentSessionPullRequestMutation,
+} from '@queries/agent-session/pull-requests';
+import { useQuickAccessAgentSessionsQuery } from '@queries/soup/quick-access-agent-sessions';
+import { Button, Dropdown, Tooltip } from '@ui';
+import { For, Match, Show, Switch } from 'solid-js';
+
+const pullRequestKey = (url: string) =>
+ url.replace(/^https:\/\/github\.com\//i, '').toLowerCase();
+
+function LinkedSessionRow(props: { sessionId: string; url: string }) {
+ const layout = useSplitLayout();
+ const preview = useAgentSessionMentionPreview(
+ () => props.sessionId,
+ () => true
+ );
+ const links = useAgentSessionPullRequestsQuery(() => props.sessionId);
+ const unlink = useUnlinkAgentSessionPullRequestMutation();
+ const session = () => {
+ const current = preview.isSuccess ? preview.data : undefined;
+ return current?.access === 'access' ? current.data : undefined;
+ };
+ const label = () => {
+ const current = preview.isSuccess ? preview.data : undefined;
+ if (current?.access === 'no_access') return 'Private agent session';
+ if (current?.access === 'does_not_exist') return 'Deleted agent session';
+ return session()?.name || 'Agent session';
+ };
+ // The pull request the session's agent opened cannot be unlinked.
+ const linkedByPerson = () =>
+ links.isSuccess &&
+ links.data.some(
+ (link) =>
+ link.source === 'user' &&
+ link.githubKey.toLowerCase() === pullRequestKey(props.url)
+ );
+
+ return (
+ <div class="flex h-6 min-w-0 items-center gap-2">
+ <Tooltip label={label()} class="min-w-0 flex-1">
+ <button
+ type="button"
+ class="w-full min-w-0 truncate text-left disabled:text-ink-placeholder"
+ disabled={!session()}
+ onClick={(event) =>
+ layout?.openWithSplit(
+ { type: 'agent', id: props.sessionId },
+ { preferNewSplit: event.shiftKey }
+ )
+ }
+ >
+ <AgentSessionMentionLabel label={label()} />
+ </button>
+ </Tooltip>
+ <Show when={linkedByPerson()}>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ class="ml-auto"
+ label={`Unlink ${label()}`}
+ disabled={unlink.isPending}
+ onClick={() =>
+ unlink.mutate(
+ { sessionId: props.sessionId, url: props.url },
+ {
+ onError: () =>
+ toast.failure('Couldn’t unlink the agent session.'),
+ }
+ )
+ }
+ >
+ <XIcon />
+ </Button>
+ </Show>
+ </div>
+ );
+}
+
+function LinkSessionPicker(props: {
+ url: string;
+ linkedSessionIds: readonly string[];
+}) {
+ const sessions = useQuickAccessAgentSessionsQuery();
+ const link = useLinkAgentSessionPullRequestMutation();
+ const options = () =>
+ sessions
+ .sessions()
+ .filter((session) => !props.linkedSessionIds.includes(session.id))
+ .map((session) => ({
+ id: session.id,
+ label: session.name || 'Agent session',
+ }));
+
+ return (
+ <ListFilterDropdown
+ label="Link agent session"
+ customTrigger={
+ <Dropdown.Trigger variant="ghost" size="xs" label="Link agent session">
+ <PlusIcon />
+ Link session
+ </Dropdown.Trigger>
+ }
+ groups={[
+ {
+ id: 'session',
+ label: 'Agent sessions',
+ options: options(),
+ searchPlaceholder: 'Search agent sessions',
+ },
+ ]}
+ isSelected={(_group, id) => props.linkedSessionIds.includes(id)}
+ onSelectionChange={(_group, sessionId, selected) => {
+ if (!selected) return;
+ link.mutate(
+ { sessionId, url: props.url },
+ {
+ onError: () => toast.failure('Couldn’t link the agent session.'),
+ }
+ );
+ }}
+ />
+ );
+}
+
+/** Agent sessions linked to a pull request, from either side of the link. */
+export function PrAgentSessionsSection(props: {
+ url?: string;
+ prStatus: 'pending' | 'error' | 'success';
+}) {
+ const sessions = usePullRequestAgentSessionsQuery(() => props.url);
+ const sessionIds = () => (sessions.isSuccess ? sessions.data : []);
+
+ return (
+ <SidePanel.Section id="pr-agent-sessions" title="Agent sessions" order={30}>
+ <Switch>
+ <Match when={props.prStatus === 'error'}>
+ <div class="text-ink-placeholder">
+ Pull request details couldn’t be loaded
+ </div>
+ </Match>
+ <Match when={!props.url}>
+ <div class="text-ink-placeholder" role="status">
+ {props.prStatus === 'pending'
+ ? 'Loading pull request details…'
+ : 'Pull request URL isn’t available'}
+ </div>
+ </Match>
+ <Match when={sessions.isPending}>
+ <div class="text-ink-placeholder" role="status">
+ Loading agent sessions…
+ </div>
+ </Match>
+ <Match when={sessions.isError}>
+ <div class="text-ink-placeholder">
+ Agent sessions couldn’t be loaded
+ </div>
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => void sessions.refetch()}
+ >
+ Retry
+ </Button>
+ </Match>
+ <Match when={sessions.isSuccess && props.url}>
+ {(url) => (
+ <div class="flex flex-col gap-1 text-xs">
+ <Show
+ when={sessionIds().length > 0}
+ fallback={
+ <div class="text-ink-placeholder">No agent sessions</div>
+ }
+ >
+ <For each={sessionIds()}>
+ {(sessionId) => (
+ <LinkedSessionRow sessionId={sessionId} url={url()} />
+ )}
+ </For>
+ </Show>
+ <div>
+ <LinkSessionPicker
+ url={url()}
+ linkedSessionIds={sessionIds()}
+ />
+ </div>
+ </div>
+ )}
+ </Match>
+ </Switch>
+ </SidePanel.Section>
+ );
+}
diff --git a/apps/web/src/features/block-pr/component/sidepanel/PrSidePanelSections.tsx b/apps/web/src/features/block-pr/component/sidepanel/PrSidePanelSections.tsx
index a98d5f0440..5ff76f4514 100644
--- a/apps/web/src/features/block-pr/component/sidepanel/PrSidePanelSections.tsx
+++ b/apps/web/src/features/block-pr/component/sidepanel/PrSidePanelSections.tsx
@@ -4,9 +4,11 @@ import {
} from '@components/app/side-panel';
import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
import { Show } from 'solid-js';
+import { PrAgentSessionsSection } from './PrAgentSessionsSection';
export function PrSidePanelSections(props: {
enrichment?: GithubPullRequestWithDetails;
+ status: 'pending' | 'error' | 'success';
}) {
return (
<>
@@ -44,6 +46,11 @@ export function PrSidePanelSections(props: {
<SidePanel.Section id="pr-checks" title="Checks" order={20}>
<GithubPullRequestChecksContent enrichment={props.enrichment} />
</SidePanel.Section>
+
+ <PrAgentSessionsSection
+ url={props.enrichment?.url}
+ prStatus={props.status}
+ />
</>
);
}
diff --git a/apps/web/src/features/block-pr/data/pr-changes.test.ts b/apps/web/src/features/block-pr/data/pr-changes.test.ts
new file mode 100644
index 0000000000..0605237259
--- /dev/null
+++ b/apps/web/src/features/block-pr/data/pr-changes.test.ts
@@ -0,0 +1,46 @@
+import { changesState } from '@app/features/agent-changes/core/changeset';
+import { describe, expect, it } from 'vitest';
+import { decodePrChanges } from './pr-changes';
+
+describe('decodePrChanges', () => {
+ it('shows the changeset GitHub provided', () => {
+ const decoded = decodePrChanges({
+ changeset: {
+ id: 'cs',
+ source: 'github_pull_request',
+ repository: 'https://github.com/o/r',
+ base: { name: 'main', sha: 'aaa' },
+ head: { name: 'work', sha: 'bbb' },
+ files: [
+ {
+ path: 'a.ts',
+ previousPath: null,
+ kind: 'modified',
+ additions: 1,
+ deletions: 2,
+ binary: false,
+ patchOmitted: false,
+ },
+ ],
+ additions: 1,
+ deletions: 2,
+ patchBytes: 10,
+ truncated: false,
+ capturedAt: 't1',
+ },
+ });
+ expect(changesState(decoded).kind).toBe('ready');
+ expect(decoded.changeset?.head).toEqual({ name: 'work', sha: 'bbb' });
+ });
+
+ it('shows why there are no changes', () => {
+ const decoded = decodePrChanges(
+ { error: 'This pull request is too large to load here.' },
+ 't0'
+ );
+ expect(changesState(decoded)).toEqual({
+ kind: 'not_ready',
+ message: 'This pull request is too large to load here.',
+ });
+ });
+});
diff --git a/apps/web/src/features/block-pr/data/pr-changes.ts b/apps/web/src/features/block-pr/data/pr-changes.ts
new file mode 100644
index 0000000000..3b29529d30
--- /dev/null
+++ b/apps/web/src/features/block-pr/data/pr-changes.ts
@@ -0,0 +1,74 @@
+/**
+ * Adapts the pull request changes queries to the Changes pane's
+ * `ChangesSource`: wire DTOs become core types here, and a reason GitHub
+ * gave no changes becomes a not-ready attempt the pane explains.
+ */
+
+import type {
+ ChangesSource,
+ PatchRead,
+} from '@app/features/agent-changes/context/agent-changes-context';
+import type { SessionChanges } from '@app/features/agent-changes/core/changeset';
+import {
+ decodeChangeset,
+ queryStatus,
+} from '@app/features/agent-changes/queries/session-changes';
+import {
+ useGithubPullRequestChangesPatchQuery,
+ useGithubPullRequestChangesQuery,
+} from '@queries/storage/github-pull-request-changes';
+import type { GithubPullRequestChangesResponse } from '@service-storage/generated/schemas/githubPullRequestChangesResponse';
+import type { Accessor } from 'solid-js';
+
+export function decodePrChanges(
+ dto: GithubPullRequestChangesResponse,
+ now = new Date().toISOString()
+): SessionChanges {
+ if (dto.changeset) {
+ return { changeset: decodeChangeset(dto.changeset), capturing: false };
+ }
+ return {
+ attempt: {
+ startedAt: now,
+ finishedAt: now,
+ outcome: 'not_ready',
+ error: dto.error ?? undefined,
+ },
+ capturing: false,
+ };
+}
+
+/** The changes of the pull request behind the foreign entity record `id`. */
+export function createPrChangesSource(
+ foreignEntityId: Accessor<string | undefined>
+): ChangesSource {
+ const summaryQuery = useGithubPullRequestChangesQuery(foreignEntityId);
+
+ // Gate every `data` read on status: an unguarded read suspends the
+ // nearest boundary (apps/web/AGENTS.md).
+ const summary = () =>
+ summaryQuery.isSuccess ? decodePrChanges(summaryQuery.data) : undefined;
+
+ const patch = (
+ changesetId: Accessor<string | undefined>,
+ enabled: Accessor<boolean>
+ ): PatchRead => {
+ const query = useGithubPullRequestChangesPatchQuery(foreignEntityId, () =>
+ enabled() ? changesetId() : undefined
+ );
+ return {
+ text: () => (query.isSuccess ? query.data.patch : undefined),
+ status: () => queryStatus(query),
+ retry: () => void query.refetch(),
+ };
+ };
+
+ return {
+ summary,
+ summaryStatus: () => queryStatus(summaryQuery),
+ patch,
+ refresh: async () => {
+ await summaryQuery.refetch();
+ },
+ };
+}
diff --git a/apps/web/src/features/block-pr/data/queries.ts b/apps/web/src/features/block-pr/data/queries.ts
index 7278ed0b77..3fb16bd1d2 100644
--- a/apps/web/src/features/block-pr/data/queries.ts
+++ b/apps/web/src/features/block-pr/data/queries.ts
@@ -1,20 +1,14 @@
import { throwOnErr } from '@core/util/result';
import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
import { storageServiceClient } from '@service-storage/client';
-import type { ForeignEntity } from '@service-storage/generated/schemas';
+import type { StoredGithubPullRequest } from '@service-storage/generated/schemas/storedGithubPullRequest';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import type { PrRef } from '../util/prKey';
-import {
- parseGithubKey,
- prDisplayName,
- prHtmlUrl,
- toGithubKey,
-} from '../util/prKey';
+import { prDisplayName } from '../util/prKey';
const PR_STALE_TIME = 60 * 1000;
-const GITHUB_PULL_REQUEST_SOURCE = 'github_pull_request';
export type PrForeignEntityData = {
id: string;
@@ -26,91 +20,48 @@ export function prForeignEntityQueryKey(id: string): string[] {
return ['github-pr', 'foreign-entity', id];
}
-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 | null | undefined {
- return typeof value === 'string' ? value : undefined;
-}
-
-function optionalNumber(value: unknown): number | null | undefined {
- return typeof value === 'number' ? value : undefined;
-}
-
-function optionalArray<T>(value: unknown): T[] | null | undefined {
- return Array.isArray(value) ? (value as T[]) : undefined;
-}
-
-function prForeignEntityDataFromParts(args: {
- id: string;
- foreignId: string;
- metadata: unknown;
-}): PrForeignEntityData {
- const metadata = metadataRecord(args.metadata);
- const owner = optionalString(metadata.owner);
- const repo = optionalString(metadata.repo);
- const number = optionalNumber(metadata.number);
- const refFromMetadata =
- owner && repo && number != null ? { owner, repo, number } : null;
- const prRef = refFromMetadata ?? parseGithubKey(args.foreignId);
-
- if (!prRef) {
- throw new Error(`Invalid GitHub pull request metadata for ${args.id}`);
- }
-
- const githubKey =
- optionalString(metadata.githubKey) ?? args.foreignId ?? toGithubKey(prRef);
+function prForeignEntityDataFromStored(
+ pullRequest: StoredGithubPullRequest
+): PrForeignEntityData {
+ const prRef: PrRef = {
+ owner: pullRequest.owner,
+ repo: pullRequest.repo,
+ number: pullRequest.number,
+ };
return {
- id: args.id,
+ id: pullRequest.id,
prRef,
pullRequest: {
- additions: optionalNumber(metadata.additions),
- authorLogin: optionalString(metadata.authorLogin),
- description: optionalString(metadata.description),
- checks: optionalArray(metadata.checks),
- comments: optionalArray(metadata.comments),
- deletions: optionalNumber(metadata.deletions),
- displayName: optionalString(metadata.displayName) ?? prDisplayName(prRef),
- foreignEntityId: args.id,
- githubKey,
- name: optionalString(metadata.name),
- number: prRef.number,
- owner: prRef.owner,
- repo: prRef.repo,
- status: optionalString(metadata.status),
- url: optionalString(metadata.url) ?? prHtmlUrl(prRef),
+ additions: pullRequest.additions,
+ authorLogin: pullRequest.authorLogin,
+ description: pullRequest.description,
+ checks: pullRequest.checks,
+ comments: pullRequest.comments,
+ deletions: pullRequest.deletions,
+ displayName: prDisplayName(prRef),
+ foreignEntityId: pullRequest.id,
+ githubKey: pullRequest.githubKey,
+ labels: pullRequest.labels,
+ name: pullRequest.title,
+ number: pullRequest.number,
+ owner: pullRequest.owner,
+ repo: pullRequest.repo,
+ status: pullRequest.status,
+ url: pullRequest.url,
},
};
}
-function prForeignEntityDataFromForeignEntity(
- entity: ForeignEntity
-): PrForeignEntityData {
- if (entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {
- throw new Error(`Foreign entity ${entity.id} is not a GitHub pull request`);
- }
-
- return prForeignEntityDataFromParts({
- id: entity.id,
- foreignId: entity.foreignEntityId,
- metadata: entity.metadata,
- });
-}
-
export function prForeignEntityQueryOptions(id: string) {
return {
queryKey: prForeignEntityQueryKey(id),
- queryFn: async (): Promise<PrForeignEntityData> => {
- const entity = await throwOnErr(() =>
- storageServiceClient.getForeignEntity({ id })
- );
- return prForeignEntityDataFromForeignEntity(entity);
- },
+ queryFn: async (): Promise<PrForeignEntityData> =>
+ prForeignEntityDataFromStored(
+ await throwOnErr(() =>
+ storageServiceClient.getGithubPullRequest({ id })
+ )
+ ),
staleTime: PR_STALE_TIME,
retry: 1,
};
diff --git a/apps/web/src/features/block-pr/route.tsx b/apps/web/src/features/block-pr/route.tsx
index 6d272e7c55..f18466fffe 100644
--- a/apps/web/src/features/block-pr/route.tsx
+++ b/apps/web/src/features/block-pr/route.tsx
@@ -1,3 +1,4 @@
+import { changesSearch } from '@app/features/agent-changes/changes-search';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { defineRoute, useParams } from '@app/lib/split-router';
import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';
@@ -31,4 +32,5 @@ export const prDetailRoute = defineRoute({
namespace: 'block',
id: `pr:${foreignEntityId}`,
}),
+ search: [changesSearch.namespace],
});
diff --git a/apps/web/src/features/block-pr/views/PrDetail.test.ts b/apps/web/src/features/block-pr/views/PrDetail.test.ts
new file mode 100644
index 0000000000..dcd4e8bae0
--- /dev/null
+++ b/apps/web/src/features/block-pr/views/PrDetail.test.ts
@@ -0,0 +1,76 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ invalidateQueries: vi.fn().mockResolvedValue(undefined),
+ onRefreshed: undefined as (() => void) | undefined,
+}));
+
+vi.mock('../data/prDiscussionSource', () => ({
+ createPrDiscussionSource: () => ({}),
+}));
+vi.mock('@app/components/view-shell', () => ({ ViewShell: {} }));
+vi.mock('@components/app/GlobalAppState', () => ({
+ useGlobalNotificationSource: vi.fn(),
+}));
+vi.mock('@components/app/side-panel', () => ({ SidePanel: {} }));
+vi.mock('@components/app/split-panel', () => ({ SplitPanel: {} }));
+vi.mock(
+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
+ () => ({
+ StaticMarkdown: () => null,
+ StaticMarkdownContext: {},
+ })
+);
+vi.mock('@entity/components/GithubLabelPill', () => ({
+ GithubLabelPills: () => null,
+}));
+vi.mock('@notifications', () => ({
+ DebouncedNotificationReadMarker: () => null,
+}));
+vi.mock('@tanstack/solid-query', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@tanstack/solid-query')>()),
+ useQueryClient: () => ({ invalidateQueries: mocks.invalidateQueries }),
+}));
+vi.mock('@queries/storage/github-pull-requests', () => ({
+ useRefreshGithubPullRequest: (
+ _reference: unknown,
+ onRefreshed: () => void
+ ) => {
+ mocks.onRefreshed = onRefreshed;
+ },
+}));
+vi.mock('../data/queries', () => ({
+ usePrForeignEntityQuery: () => ({ isPending: true }),
+ prForeignEntityQueryKey: (id: string) => ['pr-foreign-entity', id],
+}));
+vi.mock('@app/features/agent-changes/agent-changes', () => ({
+ AgentChangesSplit: () => null,
+ ChangesToggle: () => null,
+}));
+vi.mock('../component/PrChanges', () => ({ PrChangesProvider: () => null }));
+vi.mock('../component/PrTimeline', () => ({ PrTimeline: () => null }));
+vi.mock('../component/sidepanel/PrSidePanelSections', () => ({
+ PrSidePanelSections: () => null,
+}));
+
+import { githubPullRequestChangesKeys } from '@queries/storage/keys';
+import { usePrDetail } from './PrDetail';
+
+describe('PR refresh cache invalidation', () => {
+ it('invalidates the PR details and changes summary after a successful refresh', () => {
+ const id = '019a5faa-d2cd-7c55-8e8a-23aac4f0bc88';
+ createRoot((dispose) => {
+ usePrDetail(() => id);
+ mocks.onRefreshed?.();
+ expect(mocks.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ['pr-foreign-entity', id],
+ });
+ expect(mocks.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: githubPullRequestChangesKeys.summary(id).queryKey,
+ });
+ expect(mocks.invalidateQueries).toHaveBeenCalledTimes(2);
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/features/block-pr/views/PrDetail.tsx b/apps/web/src/features/block-pr/views/PrDetail.tsx
index fb1b8fa6e9..228c1e188c 100644
--- a/apps/web/src/features/block-pr/views/PrDetail.tsx
+++ b/apps/web/src/features/block-pr/views/PrDetail.tsx
@@ -1,4 +1,8 @@
import { ViewShell } from '@app/components/view-shell';
+import {
+ AgentChangesSplit,
+ ChangesToggle,
+} from '@app/features/agent-changes/agent-changes';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { SidePanel } from '@components/app/side-panel';
import { SplitPanel } from '@components/app/split-panel';
@@ -7,10 +11,17 @@ import {
StaticMarkdownContext,
} from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { openExternalUrl } from '@core/util/url';
+import { GithubLabelPills } from '@entity/components/GithubLabelPill';
import { DebouncedNotificationReadMarker } from '@notifications';
-import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
+import {
+ type GithubPullRequestWithDetails,
+ useRefreshGithubPullRequest,
+} from '@queries/storage/github-pull-requests';
+import { githubPullRequestChangesKeys } from '@queries/storage/keys';
+import { useQueryClient } from '@tanstack/solid-query';
import { Button, cn, Layer, Scroll } from '@ui';
import { type Accessor, createMemo, Show, Suspense } from 'solid-js';
+import { PrChangesProvider } from '../component/PrChanges';
import {
PrDescriptionSkeleton,
PrMetadataSkeleton,
@@ -27,6 +38,7 @@ import { PrSidePanelSections } from '../component/sidepanel/PrSidePanelSections'
import { createPrDiscussionSource } from '../data/prDiscussionSource';
import {
type PrForeignEntityData,
+ prForeignEntityQueryKey,
usePrForeignEntityQuery,
} from '../data/queries';
import {
@@ -39,11 +51,36 @@ import { prDisplayName, prHtmlUrl } from '../util/prKey';
/** Share PR query state without coupling the host's header to the detail body. */
export function usePrDetail(foreignEntityId: Accessor<string>) {
+ const queryClient = useQueryClient();
const query = usePrForeignEntityQuery(foreignEntityId);
// Detail-lifetime local Macro discussion (prototype-only, lost on reload).
const discussionSource = createPrDiscussionSource();
const data = (): PrForeignEntityData | undefined =>
query.isPending ? undefined : query.data;
+ const invalidateRefreshedPullRequest = async () => {
+ const id = foreignEntityId();
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: prForeignEntityQueryKey(id) }),
+ queryClient.invalidateQueries({
+ queryKey: githubPullRequestChangesKeys.summary(id).queryKey,
+ }),
+ ]);
+ };
+ useRefreshGithubPullRequest(
+ () => {
+ const pullRequest = data()?.pullRequest;
+ if (!pullRequest) return undefined;
+ return {
+ displayName: pullRequest.displayName,
+ githubKey: pullRequest.githubKey,
+ number: pullRequest.number,
+ owner: pullRequest.owner,
+ repo: pullRequest.repo,
+ url: pullRequest.url,
+ };
+ },
+ () => void invalidateRefreshedPullRequest()
+ );
return { query, data, discussionSource };
}
@@ -115,7 +152,10 @@ export function PrDetailBody(props: PrDetailBodyProps) {
);
}
-/** Native hosts own their header and place this content below it. */
+/**
+ * Native hosts own their header and place this content below it, both inside
+ * `PrChangesProvider`.
+ */
export function PrDetailContent(props: PrDetailBodyProps) {
return (
<div class="relative min-h-0 min-w-0 flex-1">
@@ -129,15 +169,20 @@ export function PrDetailContent(props: PrDetailBodyProps) {
}
>
<SidePanel.Layout headerToggle={false} floating>
- <PrSidePanelSections enrichment={props.data?.pullRequest} />
+ <PrSidePanelSections
+ enrichment={props.data?.pullRequest}
+ status={props.status}
+ />
<div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
- <PrDetailBody
- foreignEntityId={props.foreignEntityId}
- data={props.data}
- status={props.status}
- onRetry={props.onRetry}
- discussionSource={props.discussionSource}
- />
+ <AgentChangesSplit>
+ <PrDetailBody
+ foreignEntityId={props.foreignEntityId}
+ data={props.data}
+ status={props.status}
+ onRetry={props.onRetry}
+ discussionSource={props.discussionSource}
+ />
+ </AgentChangesSplit>
</div>
</SidePanel.Layout>
</Suspense>
@@ -148,6 +193,7 @@ export function PrDetailContent(props: PrDetailBodyProps) {
export function PrDetailActions(props: { url?: string }) {
return (
<div class="ml-auto flex shrink-0 items-center gap-2">
+ <ChangesToggle />
<Show when={props.url}>
{(url) => (
<Button
@@ -179,23 +225,28 @@ export function StandalonePrDetail(props: { foreignEntityId: string }) {
};
return (
<SidePanel.Root floating persistKey={`pr:${props.foreignEntityId}`}>
- <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
- <ViewShell.TopBar class="touch:flex">
- <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
- <Show when={detail.data()?.pullRequest.status}>
- {(status) => <PrStatusIcon status={status()} />}
- </Show>
- <span class="min-w-0 truncate text-sm font-semibold">{name()}</span>
- <PrDetailActions url={githubUrl()} />
- </ViewShell.TopBar>
- <PrDetailContent
- foreignEntityId={props.foreignEntityId}
- data={detail.data()}
- status={detail.query.status}
- discussionSource={detail.discussionSource}
- onRetry={() => void detail.query.refetch()}
- />
- </div>
+ <PrChangesProvider
+ foreignEntityId={props.foreignEntityId}
+ pullRequestUrl={githubUrl()}
+ >
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
+ <ViewShell.TopBar class="touch:flex">
+ <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
+ <Show when={detail.data()?.pullRequest.status}>
+ {(status) => <PrStatusIcon status={status()} />}
+ </Show>
+ <span class="min-w-0 truncate text-sm font-semibold">{name()}</span>
+ <PrDetailActions url={githubUrl()} />
+ </ViewShell.TopBar>
+ <PrDetailContent
+ foreignEntityId={props.foreignEntityId}
+ data={detail.data()}
+ status={detail.query.status}
+ discussionSource={detail.discussionSource}
+ onRetry={() => void detail.query.refetch()}
+ />
+ </div>
+ </PrChangesProvider>
</SidePanel.Root>
);
}
@@ -267,6 +318,11 @@ function PrMetadata(props: {
</span>
</Layer>
</Show>
+ <GithubLabelPills
+ labels={props.pullRequest?.labels ?? []}
+ class="contents"
+ pillClass="h-auto px-2 py-1 text-sm leading-tight"
+ />
</div>
);
}
diff --git a/apps/web/src/features/entity/components/GithubLabelPill.tsx b/apps/web/src/features/entity/components/GithubLabelPill.tsx
new file mode 100644
index 0000000000..9d5d0c3c47
--- /dev/null
+++ b/apps/web/src/features/entity/components/GithubLabelPill.tsx
@@ -0,0 +1,63 @@
+import { DEFAULT_TAG_COLOR } from '@property/tags/tagColors';
+import { cn } from '@ui';
+import { For, Show } from 'solid-js';
+import type { GithubPullRequestLabel } from '../types/entity';
+
+const GITHUB_HEX_COLOR = /^#?([0-9a-f]{6})$/i;
+
+/**
+ * A GitHub label drawn the way GitHub draws it. Dark themes tint the pill and
+ * lighten dark label colors until the text is readable; light themes fill with
+ * the label color and flip the text to black or white by its lightness.
+ */
+export function GithubLabelPill(props: {
+ name: string;
+ /** GitHub's six-digit hex color, with or without `#`. */
+ color?: string | null;
+ class?: string;
+}) {
+ const color = () => {
+ const hex = props.color && GITHUB_HEX_COLOR.exec(props.color)?.[1];
+ return hex ? `#${hex}` : DEFAULT_TAG_COLOR;
+ };
+
+ return (
+ <span
+ class={cn(
+ 'inline-flex h-5 max-w-full min-w-0 items-center rounded-full border px-[7px] text-xs leading-none font-medium',
+ 'dark-mode:border-[color:oklch(from_var(--label-color)_max(l,0.72)_c_h/0.3)] dark-mode:bg-[oklch(from_var(--label-color)_l_c_h/0.18)] dark-mode:text-[color:oklch(from_var(--label-color)_max(l,0.72)_c_h)]',
+ 'light-mode:border-[color:oklch(from_var(--label-color)_calc(l_-_0.25)_c_h/clamp(0,(l_-_0.95)_*_100,1))] light-mode:bg-(--label-color) light-mode:text-[color:oklch(from_var(--label-color)_clamp(0,(0.66_-_l)_*_1000,1)_0_0)]',
+ props.class
+ )}
+ style={{ '--label-color': color() }}
+ >
+ <span class="truncate">{props.name}</span>
+ </span>
+ );
+}
+
+/** A pull request's labels as pills, in GitHub's order. */
+export function GithubLabelPills(props: {
+ labels: readonly GithubPullRequestLabel[];
+ class?: string;
+ pillClass?: string;
+}) {
+ return (
+ <Show when={props.labels.length > 0}>
+ <span
+ class={cn('flex min-w-0 items-center gap-1', props.class)}
+ title={props.labels.map((label) => label.name).join(', ')}
+ >
+ <For each={props.labels}>
+ {(label) => (
+ <GithubLabelPill
+ name={label.name}
+ color={label.color}
+ class={props.pillClass}
+ />
+ )}
+ </For>
+ </span>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
index ae128fdc2e..3e93444a18 100644
--- a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
@@ -9,6 +9,7 @@ import {
CallStatusBadge,
SharedBadge,
} from '../../components/Badges';
+import { GithubLabelPills } from '../../components/GithubLabelPill';
import { MultiSelectCheckbox } from '../../components/MultiSelectCheckbox';
import { ProjectBreadCrumb } from '../../components/ProjectBreadCrumb';
import { UnreadIndicator } from '../../components/UnreadIndicator';
@@ -171,6 +172,12 @@ export function WideLayout(props: LayoutProps) {
<Entity.Title entity={entity()} />
</span>
<GithubPullRequestChecksIndicator entity={entity()} />
+ {/* One row tall, so labels that don't fit wrap out of view. */}
+ <GithubLabelPills
+ labels={entity().metadata.labels}
+ class="h-5 max-w-[40%] flex-wrap overflow-hidden"
+ pillClass="shrink-0"
+ />
</span>
)}
</Match>
diff --git a/apps/web/src/features/entity/tests/entity-icon.test.tsx b/apps/web/src/features/entity/tests/entity-icon.test.tsx
index a6f68f6c61..1cb96cf43c 100644
--- a/apps/web/src/features/entity/tests/entity-icon.test.tsx
+++ b/apps/web/src/features/entity/tests/entity-icon.test.tsx
@@ -75,6 +75,7 @@ function pullRequest(
deletions: 1,
comments: [],
checks: [],
+ labels: [],
},
};
}
diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.ts
index 5f72891235..d94eb96113 100644
--- a/apps/web/src/features/entity/types/entity.ts
+++ b/apps/web/src/features/entity/types/entity.ts
@@ -53,6 +53,12 @@ export type UnknownForeignEntity = ForeignEntityBase & {
};
};
+/** A GitHub label; `color` is GitHub's six-digit hex without `#`. */
+export type GithubPullRequestLabel = {
+ name: string;
+ color?: string | null;
+};
+
// Consider making this a generic pull request entity so we can display
// pull requests from other sources besides github
export type GithubPullRequestEntity = ForeignEntityBase & {
@@ -68,6 +74,7 @@ export type GithubPullRequestEntity = ForeignEntityBase & {
deletions: number;
comments: GithubPullRequestComment[];
checks: GithubPullRequestCheckRun[];
+ labels: GithubPullRequestLabel[];
authorLogin?: string;
authorId?: number;
};
diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/filter-menu.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/filter-menu.tsx
index 3bcc998107..fa4e1cda14 100644
--- a/apps/web/src/features/next-soup/soup-view/filters-bar/filter-menu.tsx
+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/filter-menu.tsx
@@ -34,6 +34,8 @@ export const TypeIndicator = (props: { active: boolean }) => (
export function FilterOptionItem(props: {
label: string;
icon?: () => JSX.Element;
+ /** Drawn in place of `label`. */
+ content?: () => JSX.Element;
active: boolean;
disabled?: boolean;
closeOnSelect?: boolean;
@@ -61,7 +63,7 @@ export function FilterOptionItem(props: {
props.active ? 'text-ink' : 'text-ink-muted'
)}
>
- {props.label}
+ {props.content?.() ?? props.label}
</span>
</Dropdown.Item>
);
@@ -89,6 +91,7 @@ export function FilterSubmenu<TId extends string>(props: {
id: TId;
label: string;
icon?: () => JSX.Element;
+ content?: () => JSX.Element;
disabled?: boolean;
}[];
isSelected: (id: TId) => boolean;
@@ -118,6 +121,7 @@ export function FilterSubmenu<TId extends string>(props: {
<FilterOptionItem
label={option.label}
icon={option.icon}
+ content={option.content}
disabled={option.disabled}
active={props.isSelected(option.id)}
onSelect={() => props.onSelect(option.id)}
@@ -148,7 +152,9 @@ export function FilterSubmenu<TId extends string>(props: {
{option.icon?.()}
</span>
</Show>
- <span class="flex-1">{option.label}</span>
+ <span class="flex-1">
+ {option.content?.() ?? option.label}
+ </span>
<Dropdown.ItemIndicator>
<CheckIcon class="size-3.5 text-accent" />
</Dropdown.ItemIndicator>
diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/searchable-multi-select.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/searchable-multi-select.tsx
index 209c0d6953..b0d9a2ce80 100644
--- a/apps/web/src/features/next-soup/soup-view/filters-bar/searchable-multi-select.tsx
+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/searchable-multi-select.tsx
@@ -17,6 +17,8 @@ export type SearchableOption = {
id: string;
label: string;
icon?: () => JSX.Element;
+ /** Drawn in place of `label`, which still drives search. */
+ content?: () => JSX.Element;
};
export type SearchableSelectAction = {
@@ -96,7 +98,7 @@ const SearchableMultiSelectItem = (itemProps: {
)}
</Show>
<Combobox.ItemLabel class="flex-1 truncate text-ink">
- {itemProps.item.rawValue.label}
+ {itemProps.item.rawValue.content?.() ?? itemProps.item.rawValue.label}
</Combobox.ItemLabel>
<Show
when={
diff --git a/apps/web/src/features/reviews-view/components/ReviewsControls.tsx b/apps/web/src/features/reviews-view/components/ReviewsControls.tsx
index 7df4ff8742..6175a04280 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsControls.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsControls.tsx
@@ -10,17 +10,23 @@ import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { Accordion } from '@kobalte/core/accordion';
import { createSignal, For, Show } from 'solid-js';
-import type { ReviewsSortId } from '../reviews-types';
-
-export type ReviewsFilterId = 'repository' | 'author';
+import type {
+ ReviewsFilterId,
+ ReviewsFilterSelection,
+ ReviewsReviewFilterId,
+ ReviewsSortId,
+} from '../reviews-types';
export type ReviewsControlProps = {
sort: ReviewsSortId;
onSortChange: (sort: ReviewsSortId) => void;
repositories: ListControlOption<string>[];
authors: ListControlOption<string>[];
- selectedRepositories: readonly string[];
- selectedAuthors: readonly string[];
+ assignees: ListControlOption<string>[];
+ labels: ListControlOption<string>[];
+ /** Offers the review filters that match the viewer's GitHub user id. */
+ hasGithubIdentity: boolean;
+ selected: ReviewsFilterSelection;
onFilterChange: (
group: ReviewsFilterId,
id: string,
@@ -30,8 +36,16 @@ export type ReviewsControlProps = {
};
const SORT_OPTIONS: ListControlOption<ReviewsSortId>[] = [
- { id: 'updated_at', label: 'Updated' },
- { id: 'created_at', label: 'Created' },
+ { id: 'recently_updated', label: 'Recently updated' },
+ { id: 'least_recently_updated', label: 'Least recently updated' },
+ { id: 'newest', label: 'Newest' },
+ { id: 'oldest', label: 'Oldest' },
+];
+
+const REVIEW_OPTIONS: ListControlOption<ReviewsReviewFilterId>[] = [
+ { id: 'reviewed_by_me', label: 'Reviewed by you' },
+ { id: 'not_reviewed_by_me', label: 'Not reviewed by you' },
+ { id: 'awaiting_my_review', label: 'Awaiting review from you' },
];
function filterGroups(
@@ -50,6 +64,21 @@ function filterGroups(
options: props.authors,
searchPlaceholder: 'Search authors',
},
+ {
+ id: 'assignee',
+ label: 'Assignee',
+ options: props.assignees,
+ searchPlaceholder: 'Search assignees',
+ },
+ {
+ id: 'label',
+ label: 'Label',
+ options: props.labels,
+ searchPlaceholder: 'Search labels',
+ },
+ ...(props.hasGithubIdentity
+ ? [{ id: 'review' as const, label: 'Reviews', options: REVIEW_OPTIONS }]
+ : []),
];
}
@@ -58,11 +87,12 @@ function isSelected(
group: ReviewsFilterId,
id: string
) {
- return (
- group === 'repository' ? props.selectedRepositories : props.selectedAuthors
- ).includes(id);
+ return props.selected[group].includes(id);
}
+export const activeReviewsFilterCount = (selected: ReviewsFilterSelection) =>
+ Object.values(selected).reduce((count, ids) => count + ids.length, 0);
+
export function ReviewsControls(props: ReviewsControlProps) {
const panel = useSplitPanelOrThrow();
const [openMenu, setOpenMenu] = createSignal<'filters' | 'sort'>();
@@ -97,8 +127,7 @@ export function ReviewsControls(props: ReviewsControlProps) {
},
});
- const activeCount = () =>
- props.selectedRepositories.length + props.selectedAuthors.length;
+ const activeCount = () => activeReviewsFilterCount(props.selected);
return (
<div class="flex min-w-0 shrink-0 items-center justify-end gap-2 @max-[720px]/view-shell:gap-1">
@@ -134,8 +163,7 @@ export function ReviewsControls(props: ReviewsControlProps) {
export function ReviewsFilterDrawer(props: ReviewsControlProps) {
const groups = () => filterGroups(props);
- const activeCount = () =>
- props.selectedRepositories.length + props.selectedAuthors.length;
+ const activeCount = () => activeReviewsFilterCount(props.selected);
return (
<MobileFilterDrawer
@@ -185,7 +213,7 @@ export function ReviewsFilterDrawer(props: ReviewsControlProps) {
props.onFilterChange(group.id, option.id, selected)
}
>
- {option.label}
+ {option.content?.() ?? option.label}
</MobileFilterDrawer.Option>
)}
</For>
diff --git a/apps/web/src/features/reviews-view/components/ReviewsEmptyState.tsx b/apps/web/src/features/reviews-view/components/ReviewsEmptyState.tsx
index f0c9a4c6ae..1ddc5a75d9 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsEmptyState.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsEmptyState.tsx
@@ -5,7 +5,18 @@ import type { GithubLinkStatus } from '@queries/auth/github-link';
import { EmptyStatePanel } from '@ui';
import { Match, Switch } from 'solid-js';
import { match } from 'ts-pattern';
-import type { ReviewsScope } from '../reviews-types';
+import {
+ type ReviewsScope,
+ scopeMatchesViewerGithubId,
+} from '../reviews-types';
+
+const IDENTITY_SUBJECTS: Record<ReviewsScope, string> = {
+ all: 'pull requests',
+ authored: 'pull requests you authored',
+ assigned: 'pull requests assigned to you',
+ involving: 'pull requests involving you',
+ review_requests: 'pull requests awaiting your review',
+};
export function ReviewsEmptyState(props: {
scope: ReviewsScope;
@@ -17,10 +28,7 @@ export function ReviewsEmptyState(props: {
onClearFilters: () => void;
}) {
const identityCopy = () => {
- const subject =
- props.scope === 'involving'
- ? 'pull requests involving you'
- : 'pull requests you authored';
+ const subject = IDENTITY_SUBJECTS[props.scope];
return match(props.githubAccountStatus)
.with('linked', () => ({
title: 'GitHub account details unavailable',
@@ -42,7 +50,11 @@ export function ReviewsEmptyState(props: {
return (
<Switch>
- <Match when={props.scope === 'authored' && !props.hasAuthorIdentity}>
+ <Match
+ when={
+ scopeMatchesViewerGithubId(props.scope) && !props.hasAuthorIdentity
+ }
+ >
<EmptyStatePanel
centered
graphic={GitPullRequestIcon}
@@ -81,7 +93,7 @@ export function ReviewsEmptyState(props: {
centered
graphic={EmptyStateNoFilterMatchGraphic}
title="No pull requests match these filters"
- description="Try another repository or author, or clear your filters."
+ description="Try other filters, or clear them."
primaryAction={{
label: 'Clear filters',
onClick: props.onClearFilters,
@@ -104,6 +116,22 @@ export function ReviewsEmptyState(props: {
description="Pull requests you authored and can access in Macro will appear here."
/>
</Match>
+ <Match when={props.scope === 'assigned'}>
+ <EmptyStatePanel
+ centered
+ graphic={GitPullRequestIcon}
+ title="No pull requests assigned to you"
+ description="Pull requests assigned to you and accessible in Macro will appear here."
+ />
+ </Match>
+ <Match when={props.scope === 'review_requests'}>
+ <EmptyStatePanel
+ centered
+ graphic={GitPullRequestIcon}
+ title="No review requests"
+ description="Pull requests waiting on your review will appear here."
+ />
+ </Match>
<Match when={true}>
<EmptyStatePanel
centered
diff --git a/apps/web/src/features/reviews-view/components/ReviewsList.tsx b/apps/web/src/features/reviews-view/components/ReviewsList.tsx
index f65963da5d..c222b4cbca 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsList.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsList.tsx
@@ -38,7 +38,10 @@ import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
import type { ReviewsListController } from '../primitives/create-reviews-list-controller';
import type { useReviewsQuery } from '../queries/use-reviews-query';
import { isAuthoredBy } from '../reviews-filter';
-import type { ReviewsScope } from '../reviews-types';
+import {
+ type ReviewsScope,
+ scopeMatchesViewerGithubId,
+} from '../reviews-types';
import { ReviewsEmptyState } from './ReviewsEmptyState';
export type ReviewsListProps = {
@@ -51,8 +54,7 @@ export type ReviewsListProps = {
githubIdentityLoading: boolean;
githubAccountStatus?: GithubLinkStatus | 'error';
search: string;
- selectedRepositories: readonly string[];
- selectedAuthors: readonly string[];
+ hasFilters: boolean;
onClearSearch: () => void;
onClearFilters: () => void;
onOpen: (foreignEntityId: string, newSplit: boolean) => void;
@@ -148,8 +150,8 @@ export function ReviewsList(props: ReviewsListProps) {
const list = props.list;
const reviews = list.items.all;
const selectedReviews = list.selection.items;
- const missingIdentity = () =>
- props.scope === 'authored' && !props.authorLogin && !props.authorId;
+ const matchesViewer = () => scopeMatchesViewerGithubId(props.scope);
+ const missingIdentity = () => matchesViewer() && !props.authorId;
const [listElement, setListElement] = createSignal<HTMLDivElement>();
const [sentinel, setSentinel] = createSignal<HTMLDivElement>();
const listSize = createElementSize(listElement);
@@ -207,7 +209,7 @@ export function ReviewsList(props: ReviewsListProps) {
source.isLoadingMore() ||
source.pageError() ||
!source.hasMore() ||
- (props.scope === 'authored' && props.githubIdentityLoading)
+ (matchesViewer() && props.githubIdentityLoading)
)
return;
if (element.scrollHeight - element.scrollTop - element.clientHeight < 320)
@@ -223,7 +225,7 @@ export function ReviewsList(props: ReviewsListProps) {
rootMargin: '320px',
});
- // The visible rows can be sparser than the fetched pages after local filters.
+ // The visible rows can be sparser than the fetched pages after a local search.
// Measure the scroll area after rendering each page and keep fetching until
// the viewport fills, a result is reachable, or pagination ends.
createEffect(() => {
@@ -255,7 +257,7 @@ export function ReviewsList(props: ReviewsListProps) {
<Match
when={
source.isLoading() ||
- (props.scope === 'authored' && props.githubIdentityLoading)
+ (matchesViewer() && props.githubIdentityLoading)
}
>
<div
@@ -307,13 +309,8 @@ export function ReviewsList(props: ReviewsListProps) {
<ReviewsEmptyState
scope={props.scope}
search={props.search}
- hasFilters={
- props.selectedRepositories.length > 0 ||
- props.selectedAuthors.length > 0
- }
- hasAuthorIdentity={Boolean(
- props.authorLogin || props.authorId
- )}
+ hasFilters={props.hasFilters}
+ hasAuthorIdentity={Boolean(props.authorId)}
githubAccountStatus={props.githubAccountStatus}
onClearSearch={props.onClearSearch}
onClearFilters={props.onClearFilters}
diff --git a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
index 90a9c8a5d2..18cd45b2c4 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
@@ -1,6 +1,7 @@
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useRouteParams } from '@app/lib/split-router';
+import { PrChangesProvider } from '@block-pr/component/PrChanges';
import { PrStatusIcon } from '@block-pr/component/PrStatus';
import { prDisplayName, prHtmlUrl } from '@block-pr/util/prKey';
import {
@@ -80,25 +81,30 @@ export function ReviewsPrDetail(props: { foreignEntityId: string }) {
return (
<SidePanel.Root persistKey={`pr:${props.foreignEntityId}`}>
- <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
- <ViewShell.TopBar class="touch:flex">
- <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
- <ViewBreadcrumbs.Outlet aria-label="Pull request location" />
- <PrDetailActions url={githubUrl()} />
- </ViewShell.TopBar>
- <ReviewsPrBreadcrumb
- foreignEntityId={props.foreignEntityId}
- name={name()}
- status={detail.data()?.pullRequest.status ?? undefined}
- />
- <PrDetailContent
- foreignEntityId={props.foreignEntityId}
- data={detail.data()}
- status={detail.query.status}
- discussionSource={detail.discussionSource}
- onRetry={() => void detail.query.refetch()}
- />
- </div>
+ <PrChangesProvider
+ foreignEntityId={props.foreignEntityId}
+ pullRequestUrl={githubUrl()}
+ >
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
+ <ViewShell.TopBar class="touch:flex">
+ <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
+ <ViewBreadcrumbs.Outlet aria-label="Pull request location" />
+ <PrDetailActions url={githubUrl()} />
+ </ViewShell.TopBar>
+ <ReviewsPrBreadcrumb
+ foreignEntityId={props.foreignEntityId}
+ name={name()}
+ status={detail.data()?.pullRequest.status ?? undefined}
+ />
+ <PrDetailContent
+ foreignEntityId={props.foreignEntityId}
+ data={detail.data()}
+ status={detail.query.status}
+ discussionSource={detail.discussionSource}
+ onRetry={() => void detail.query.refetch()}
+ />
+ </div>
+ </PrChangesProvider>
</SidePanel.Root>
);
}
diff --git a/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx b/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx
index fe6bd0ea5d..db3a5bd016 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx
@@ -12,12 +12,17 @@ import {
import { prDisplayName } from '@block-pr/util/prKey';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';
+import { GithubLabelPill } from '@entity/components/GithubLabelPill';
+import type { GithubPullRequestLabel } from '@entity/types/entity';
import { ContextMenu } from '@kobalte/core/context-menu';
import SplitIcon from '@phosphor/columns.svg';
+import EyeIcon from '@phosphor/eye.svg';
import GitPullRequestIcon from '@phosphor/git-pull-request.svg';
import StarIcon from '@phosphor/star.svg';
import UserIcon from '@phosphor/user.svg';
+import UserCircleCheckIcon from '@phosphor/user-circle-check.svg';
import UsersThreeIcon from '@phosphor/users-three.svg';
+import { selectSidebarTag } from '@property/tags/SidebarTagsSection';
import {
useFavoritesData,
useRemoveFavoriteMutation,
@@ -25,8 +30,19 @@ import {
import type { Favorite } from '@service-storage/generated/schemas/favorite';
import { makePersisted } from '@solid-primitives/storage';
import { useQueries } from '@tanstack/solid-query';
-import { createMemo, createSignal, For, Show } from 'solid-js';
-import type { ReviewsScope } from '../reviews-types';
+import { type Component, createMemo, createSignal, For, Show } from 'solid-js';
+import { REVIEWS_SCOPES, type ReviewsScope } from '../reviews-types';
+
+const SCOPE_ITEMS: Record<
+ ReviewsScope,
+ { label: string; icon: Component<{ class?: string }> }
+> = {
+ all: { label: 'Pull requests', icon: GitPullRequestIcon },
+ authored: { label: 'Authored by me', icon: UserIcon },
+ assigned: { label: 'Assigned to me', icon: UserCircleCheckIcon },
+ involving: { label: 'Involves me', icon: UsersThreeIcon },
+ review_requests: { label: 'Review requests', icon: EyeIcon },
+};
function ReviewFavoriteRow(props: {
favorite: Favorite;
@@ -135,9 +151,57 @@ function ReviewFavorites(props: {
);
}
+/**
+ * GitHub labels among the visible pull requests. Like the Tags section, a row
+ * is a destination: choosing a label shows it alone, and choosing the active
+ * label clears it.
+ */
+function ReviewLabels(props: {
+ labels: GithubPullRequestLabel[];
+ activeLabels: readonly string[];
+ onActiveLabelsChange: (labels: string[]) => void;
+}) {
+ const [open, setOpen] = makePersisted(createSignal(true), {
+ name: 'reviews-labels-open',
+ });
+
+ return (
+ <Show when={props.labels.length > 0}>
+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
+ <CollapsibleSection.Trigger>
+ <span class="min-w-0 truncate">Labels</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Content>
+ <ViewSidebar.Nav aria-label="Pull request labels">
+ <For each={props.labels}>
+ {(label) => (
+ <ViewSidebar.Item
+ title={label.name}
+ active={props.activeLabels.includes(label.name)}
+ onClick={() =>
+ props.onActiveLabelsChange(
+ selectSidebarTag(props.activeLabels, label.name)
+ )
+ }
+ >
+ <GithubLabelPill name={label.name} color={label.color} />
+ </ViewSidebar.Item>
+ )}
+ </For>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ </Show>
+ );
+}
+
export function ReviewsSidebar(props: {
scope: ReviewsScope;
onScopeChange: (scope: ReviewsScope) => void;
+ labels: GithubPullRequestLabel[];
+ activeLabels: readonly string[];
+ onActiveLabelsChange: (labels: string[]) => void;
onOpenReview: (id: string, newSplit: boolean) => void;
activeForeignEntityId?: string;
}) {
@@ -145,7 +209,7 @@ export function ReviewsSidebar(props: {
useViewTabHotkeys({
scopeId: panel.splitHotkeyScope,
enabled: panel.isPanelActive,
- ids: () => ['involving', 'all', 'authored'] as ReviewsScope[],
+ ids: () => [...REVIEWS_SCOPES],
activeId: () => props.scope,
setActiveId: props.onScopeChange,
});
@@ -160,38 +224,32 @@ export function ReviewsSidebar(props: {
</ViewSidebar.Header>
<ViewSidebar.Content>
<ViewSidebar.Nav aria-label="Pull request views">
- <ViewSidebar.Item
- active={props.scope === 'involving'}
- onClick={() => props.onScopeChange('involving')}
- >
- <ViewSidebar.Icon>
- <UsersThreeIcon class="size-4" />
- </ViewSidebar.Icon>
- <span class="truncate">Involving me</span>
- </ViewSidebar.Item>
- <ViewSidebar.Item
- active={props.scope === 'all'}
- onClick={() => props.onScopeChange('all')}
- >
- <ViewSidebar.Icon>
- <GitPullRequestIcon class="size-4" />
- </ViewSidebar.Icon>
- <span class="truncate">All PRs</span>
- </ViewSidebar.Item>
- <ViewSidebar.Item
- active={props.scope === 'authored'}
- onClick={() => props.onScopeChange('authored')}
- >
- <ViewSidebar.Icon>
- <UserIcon class="size-4" />
- </ViewSidebar.Icon>
- <span class="truncate">Authored by me</span>
- </ViewSidebar.Item>
+ <For each={REVIEWS_SCOPES}>
+ {(scope) => {
+ const Icon = SCOPE_ITEMS[scope].icon;
+ return (
+ <ViewSidebar.Item
+ active={props.scope === scope}
+ onClick={() => props.onScopeChange(scope)}
+ >
+ <ViewSidebar.Icon>
+ <Icon class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="truncate">{SCOPE_ITEMS[scope].label}</span>
+ </ViewSidebar.Item>
+ );
+ }}
+ </For>
</ViewSidebar.Nav>
<ReviewFavorites
onOpenReview={props.onOpenReview}
activeForeignEntityId={props.activeForeignEntityId}
/>
+ <ReviewLabels
+ labels={props.labels}
+ activeLabels={props.activeLabels}
+ onActiveLabelsChange={props.onActiveLabelsChange}
+ />
</ViewSidebar.Content>
</ViewSidebar.Root>
);
diff --git a/apps/web/src/features/reviews-view/queries/use-reviews-facets-query.ts b/apps/web/src/features/reviews-view/queries/use-reviews-facets-query.ts
new file mode 100644
index 0000000000..ec489535e4
--- /dev/null
+++ b/apps/web/src/features/reviews-view/queries/use-reviews-facets-query.ts
@@ -0,0 +1,42 @@
+import type { ListControlOption } from '@app/components/view-shell';
+import { throwOnErr } from '@core/util/result';
+import type { GithubPullRequestLabel } from '@entity/types/entity';
+import { storageServiceClient } from '@service-storage/client';
+import { useQuery } from '@tanstack/solid-query';
+
+const REVIEWS_FACETS_STALE_TIME = 60_000;
+
+type UserFacet = { githubUserId: string; login?: string | null };
+
+const userOption = (user: UserFacet): ListControlOption<string> => ({
+ id: user.githubUserId,
+ label: user.login ?? user.githubUserId,
+});
+
+/**
+ * Filter options across every pull request visible to the viewer and their
+ * team, not only the loaded pages. Repository, author, and assignee option ids
+ * are the numeric GitHub ids the backend filters match; label ids are names.
+ */
+export function useReviewsFacetsQuery() {
+ const query = useQuery(() => ({
+ queryKey: ['reviews', 'githubPullRequestFacets'] as const,
+ queryFn: () =>
+ throwOnErr(() => storageServiceClient.getGithubPullRequestFacets()),
+ staleTime: REVIEWS_FACETS_STALE_TIME,
+ }));
+ const facets = () => (query.isSuccess ? query.data : undefined);
+
+ const repositories = (): ListControlOption<string>[] =>
+ (facets()?.repositories ?? []).map((repository) => ({
+ id: repository.repositoryId,
+ label: repository.repository,
+ }));
+ const authors = (): ListControlOption<string>[] =>
+ (facets()?.authors ?? []).map(userOption);
+ const assignees = (): ListControlOption<string>[] =>
+ (facets()?.assignees ?? []).map(userOption);
+ const labels = (): GithubPullRequestLabel[] => facets()?.labels ?? [];
+
+ return { query, repositories, authors, assignees, labels };
+}
diff --git a/apps/web/src/features/reviews-view/queries/use-reviews-query.test.ts b/apps/web/src/features/reviews-view/queries/use-reviews-query.test.ts
deleted file mode 100644
index 128ed0f8e8..0000000000
--- a/apps/web/src/features/reviews-view/queries/use-reviews-query.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
-import type { GithubPullRequestEntity, Notification } from '@entity';
-import { unreadFilterFn } from '@entity/utils/filter';
-import type { NotificationSource } from '@notifications/notification-source';
-import {
- type SoupAstItemsQuery,
- useSoupAstItemsQuery,
-} from '@queries/soup/items';
-import { describe, expect, it, vi } from 'vitest';
-import { reviewsQueryBody, useReviewsQuery } from './use-reviews-query';
-
-vi.mock('@components/app/GlobalAppState', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@components/app/GlobalAppState')>()),
- useGlobalNotificationSource: vi.fn(),
-}));
-vi.mock('@queries/soup/items', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@queries/soup/items')>()),
- useSoupAstItemsQuery: vi.fn(),
-}));
-
-// Feature imports can reach websocket clients that cannot connect in jsdom.
-vi.mock('@service-storage/websocket', () => ({
- storageWS: { reconnectIfDisconnected: vi.fn() },
- createWebSocketJob: vi.fn(),
-}));
-vi.mock('@service-connection/websocket', () => ({
- ws: { addEventListener: vi.fn(), send: vi.fn() },
- state: () => 'closed',
- createConnectionBlockWebsocketEffect: vi.fn(),
- createConnectionWebsocketEffect: vi.fn(),
-}));
-
-describe('Reviews Soup filter', () => {
- it.each(['all', 'authored'] as const)(
- 'requests accessible GitHub pull requests for %s',
- (scope) => {
- expect(reviewsQueryBody(scope).fef).toEqual({
- l: { fes: 'github_pull_request' },
- });
- }
- );
-
- it('filters Involving me by the backend participant predicate', () => {
- expect(reviewsQueryBody('involving').fef).toEqual({
- '&': [{ l: { fes: 'github_pull_request' } }, { l: 'me' }],
- });
- });
-});
-
-describe('Reviews notifications', () => {
- it('adapts GraphQL item notifications and applies local overrides', () => {
- const notification: Notification = {
- id: 'notification-1',
- entity_id: 'pr-1',
- entity_type: 'foreign_entity',
- notification_event_type: 'github_pr_status_changed',
- notification_metadata: {
- tag: 'github_pr_status_changed',
- content: {
- displayName: 'Review',
- foreignEntityId: 'pr-1',
- githubKey: 'macro/repo/pull/1',
- number: 1,
- owner: 'macro',
- repo: 'repo',
- title: 'Review',
- url: 'https://github.com/macro/repo/pull/1',
- action: 'opened',
- status: 'open',
- },
- },
- sent: true,
- state: 'unseen',
- created_at: '2026-09-11T00:00:00Z',
- updated_at: '2026-09-11T00:00:00Z',
- };
- const review: GithubPullRequestEntity & { notifications: Notification[] } =
- {
- type: 'foreign',
- id: 'pr-1',
- name: 'Review',
- ownerId: 'macro|[email protected]',
- foreignSource: 'github_pull_request',
- foreignId: 'macro/repo/pull/1',
- storedForId: 'macro|[email protected]',
- storedForAuthEntity: 'macro',
- metadata: {
- number: 1,
- name: 'Review',
- owner: 'macro',
- repo: 'repo',
- url: 'https://github.com/macro/repo/pull/1',
- status: 'open',
- additions: 0,
- deletions: 0,
- comments: [],
- checks: [],
- },
- notifications: [notification],
- };
- vi.mocked(useGlobalNotificationSource).mockReturnValue({
- notificationsByEntity: () => ({}),
- withLocalOverrides: (item: Notification) => ({
- ...item,
- state: 'seen' as const,
- }),
- } as NotificationSource);
- vi.mocked(useSoupAstItemsQuery).mockReturnValue({
- data: { entities: [review], groups: undefined },
- error: null,
- isPending: false,
- isLoading: false,
- isFetching: false,
- isPlaceholderData: false,
- isFetchingNextPage: false,
- isEnabled: true,
- hasNextPage: false,
- transport: 'graphql',
- fetchNextPage: vi.fn(),
- refetch: vi.fn(),
- resetToInitialPage: vi.fn(),
- refresh: vi.fn(),
- } satisfies SoupAstItemsQuery);
-
- const entity = useReviewsQuery(
- () => 'updated_at',
- () => 'involving',
- () => true
- ).reviews()[0];
- if (!entity) throw new Error('Missing review');
- expect(entity.notifications?.()).toEqual([
- { ...notification, state: 'seen' },
- ]);
- expect(unreadFilterFn(entity)).toBe(false);
- });
-});
diff --git a/apps/web/src/features/reviews-view/queries/use-reviews-query.ts b/apps/web/src/features/reviews-view/queries/use-reviews-query.ts
index 583b56bbb9..8cffde946f 100644
--- a/apps/web/src/features/reviews-view/queries/use-reviews-query.ts
+++ b/apps/web/src/features/reviews-view/queries/use-reviews-query.ts
@@ -1,29 +1,111 @@
import { withEntityNotifications } from '@app/features/soup/entity-notifications';
-import { clause, compileClause, confine } from '@app/features/soup/filters';
+import {
+ clause,
+ compileClause,
+ confine,
+ type TargetExpr,
+} from '@app/features/soup/filters';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { isGithubPrEntity } from '@entity';
import { useSoupAstItemsQuery } from '@queries/soup/items';
import type { Accessor } from 'solid-js';
-import type { ReviewsScope, ReviewsSortId } from '../reviews-types';
+import type {
+ ReviewsFilterSelection,
+ ReviewsReviewFilterId,
+ ReviewsScope,
+ ReviewsSortId,
+} from '../reviews-types';
+
+/** What the Reviews list asks the backend for. */
+export type ReviewsServerFilter = {
+ scope: ReviewsScope;
+ /**
+ * Repository and author selections are numeric GitHub ids, assignees are
+ * numeric GitHub user ids, and labels are label names.
+ */
+ filters: ReviewsFilterSelection;
+ /** The viewer's GitHub user id, which the "me" scopes and filters match. */
+ viewerGithubUserId?: string;
+};
+
+const REVIEWS_SORTS: Record<
+ ReviewsSortId,
+ { sort_method: 'updated_at' | 'created_at'; sort_direction: 'asc' | 'desc' }
+> = {
+ recently_updated: { sort_method: 'updated_at', sort_direction: 'desc' },
+ least_recently_updated: { sort_method: 'updated_at', sort_direction: 'asc' },
+ newest: { sort_method: 'created_at', sort_direction: 'desc' },
+ oldest: { sort_method: 'created_at', sort_direction: 'asc' },
+};
+
+const anyOf = (field: string, ids: readonly string[]) =>
+ clause.or(...ids.map((id) => clause.eq(field, id)));
+
+function reviewClause(
+ id: ReviewsReviewFilterId,
+ viewer: string | undefined
+): TargetExpr | undefined {
+ switch (id) {
+ case 'reviewed_by_me':
+ return viewer
+ ? clause.eq('githubPullRequestReviewedBy', viewer)
+ : undefined;
+ case 'not_reviewed_by_me':
+ return viewer
+ ? clause.not(clause.eq('githubPullRequestReviewedBy', viewer))
+ : undefined;
+ case 'awaiting_my_review':
+ return viewer
+ ? clause.eq('githubPullRequestReviewRequested', viewer)
+ : undefined;
+ }
+}
+
+const SCOPE_FIELDS: Partial<Record<ReviewsScope, string>> = {
+ authored: 'githubPullRequestAuthorId',
+ assigned: 'githubPullRequestAssigneeId',
+ review_requests: 'githubPullRequestReviewRequested',
+};
/** Backend participant matching requires the viewer's linked GitHub user ID. */
-export const reviewsQueryBody = (scope: ReviewsScope) =>
- compileClause(
+export const reviewsQueryBody = (filter: ReviewsServerFilter) => {
+ const { filters, viewerGithubUserId: viewer } = filter;
+ const pullRequest: TargetExpr[] = [];
+ if (filters.repository.length > 0)
+ pullRequest.push(
+ anyOf('githubPullRequestRepositoryId', filters.repository)
+ );
+ if (filters.author.length > 0)
+ pullRequest.push(anyOf('githubPullRequestAuthorId', filters.author));
+ if (filters.assignee.length > 0)
+ pullRequest.push(anyOf('githubPullRequestAssigneeId', filters.assignee));
+ if (filters.label.length > 0)
+ pullRequest.push(anyOf('githubPullRequestLabel', filters.label));
+ const reviews = filters.review.flatMap(
+ (id) => reviewClause(id as ReviewsReviewFilterId, viewer) ?? []
+ );
+ if (reviews.length > 0) pullRequest.push(clause.or(...reviews));
+ const scopeField = SCOPE_FIELDS[filter.scope];
+ if (scopeField && viewer) pullRequest.push(clause.eq(scopeField, viewer));
+
+ return compileClause(
confine({
fef:
- scope === 'involving'
+ filter.scope === 'involving'
? clause.and(
clause.eq('foreignEntitySource', 'github_pull_request'),
clause.eq('foreignEntityIncludesMe', true)
)
: clause.eq('foreignEntitySource', 'github_pull_request'),
+ ...(pullRequest.length > 0 ? { ghprf: clause.and(...pullRequest) } : {}),
})
);
+};
/** GitHub pull requests accessible through Soup, with pagination. */
export function useReviewsQuery(
sort: Accessor<ReviewsSortId>,
- scope: Accessor<ReviewsScope>,
+ filter: Accessor<ReviewsServerFilter>,
enabled: Accessor<boolean>
) {
const notificationSource = useGlobalNotificationSource();
@@ -32,10 +114,9 @@ export function useReviewsQuery(
params: {
expand: true,
limit: 100,
- sort_method: sort(),
- sort_direction: 'desc',
+ ...REVIEWS_SORTS[sort()],
},
- body: reviewsQueryBody(scope()),
+ body: reviewsQueryBody(filter()),
}),
() => ({ enabled: enabled(), showSupportedForeignEntities: true })
);
diff --git a/apps/web/src/features/reviews-view/reviews-filter.test.ts b/apps/web/src/features/reviews-view/reviews-filter.test.ts
new file mode 100644
index 0000000000..040a8c4de1
--- /dev/null
+++ b/apps/web/src/features/reviews-view/reviews-filter.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+import { effectiveReviewsFilters } from './reviews-filter';
+import {
+ EMPTY_REVIEWS_FILTERS,
+ type ReviewsFilterSelection,
+} from './reviews-types';
+
+describe('effective review filters', () => {
+ const saved: ReviewsFilterSelection = {
+ ...EMPTY_REVIEWS_FILTERS,
+ repository: ['42'],
+ review: ['awaiting_my_review'],
+ };
+
+ it('excludes viewer-specific selections without changing saved filters', () => {
+ const active = effectiveReviewsFilters(saved, false);
+ expect(active.review).toEqual([]);
+ expect(active.repository).toEqual(['42']);
+ expect(saved.review).toEqual(['awaiting_my_review']);
+ });
+
+ it('restores saved selections when the GitHub identity returns', () => {
+ effectiveReviewsFilters(saved, false);
+ expect(effectiveReviewsFilters(saved, true)).toBe(saved);
+ });
+
+ it('has no active selections when only unavailable review filters are saved', () => {
+ const active = effectiveReviewsFilters(
+ { ...EMPTY_REVIEWS_FILTERS, review: ['reviewed_by_me'] },
+ false
+ );
+ expect(Object.values(active).flat()).toEqual([]);
+ });
+});
diff --git a/apps/web/src/features/reviews-view/reviews-filter.ts b/apps/web/src/features/reviews-view/reviews-filter.ts
index db50915611..a3abedc3ad 100644
--- a/apps/web/src/features/reviews-view/reviews-filter.ts
+++ b/apps/web/src/features/reviews-view/reviews-filter.ts
@@ -1,14 +1,13 @@
import type { GithubPullRequestEntity } from '@entity';
-import type { ReviewsScope } from './reviews-types';
-
-export type ReviewsFilter = {
- scope: ReviewsScope;
- authorLogin?: string;
- authorId?: string;
- search: string;
- repositories: readonly string[];
- authors: readonly string[];
-};
+import type { ReviewsFilterSelection } from './reviews-types';
+
+/** Keep saved viewer-specific filters inactive until a GitHub identity is available. */
+export function effectiveReviewsFilters(
+ filters: ReviewsFilterSelection,
+ hasGithubIdentity: boolean
+): ReviewsFilterSelection {
+ return hasGithubIdentity ? filters : { ...filters, review: [] };
+}
export function isAuthoredBy(
review: GithubPullRequestEntity,
@@ -26,43 +25,20 @@ export function isAuthoredBy(
return reviewAuthor.toLowerCase() === authorLogin.toLowerCase();
}
-export function filterReviews(
+/** Scope, repository, and author filters run on the backend; search runs here. */
+export function searchReviews(
reviews: readonly GithubPullRequestEntity[],
- filter: ReviewsFilter
+ search: string
): GithubPullRequestEntity[] {
- const search = filter.search.trim().toLocaleLowerCase();
-
- return reviews.filter((review) => {
- if (
- filter.scope === 'authored' &&
- !isAuthoredBy(review, filter.authorLogin, filter.authorId)
- ) {
- return false;
- }
-
- const repository = `${review.metadata.owner}/${review.metadata.repo}`;
- if (
- filter.repositories.length > 0 &&
- !filter.repositories.includes(repository)
- ) {
- return false;
- }
-
- const author = review.metadata.authorLogin;
- if (filter.authors.length > 0) {
- if (!author || !filter.authors.includes(author)) return false;
- }
-
- if (!search) return true;
+ const query = search.trim().toLocaleLowerCase();
+ if (!query) return [...reviews];
- const searchableFields = [
+ return reviews.filter((review) =>
+ [
review.metadata.name,
- repository,
+ `${review.metadata.owner}/${review.metadata.repo}`,
String(review.metadata.number),
- author ?? '',
- ];
- return searchableFields.some((value) =>
- value.toLocaleLowerCase().includes(search)
- );
- });
+ review.metadata.authorLogin ?? '',
+ ].some((value) => value.toLocaleLowerCase().includes(query))
+ );
}
diff --git a/apps/web/src/features/reviews-view/reviews-tab-search.test.ts b/apps/web/src/features/reviews-view/reviews-tab-search.test.ts
index 1d6daeba2f..e9acc21e96 100644
--- a/apps/web/src/features/reviews-view/reviews-tab-search.test.ts
+++ b/apps/web/src/features/reviews-view/reviews-tab-search.test.ts
@@ -2,16 +2,19 @@ import { describe, expect, it } from 'vitest';
import { reviewsTabSearchCodec } from './reviews-tab-search';
describe('Reviews tab URL', () => {
- it.each(['involving', 'all', 'authored'] as const)(
- 'round-trips the %s tab',
- (tab) => {
- const encoded = reviewsTabSearchCodec.serialize({ tab });
- expect(reviewsTabSearchCodec.parse(encoded)).toEqual({
- value: { tab },
- valid: true,
- });
- }
- );
+ it.each([
+ 'all',
+ 'authored',
+ 'assigned',
+ 'involving',
+ 'review_requests',
+ ] as const)('round-trips the %s tab', (tab) => {
+ const encoded = reviewsTabSearchCodec.serialize({ tab });
+ expect(reviewsTabSearchCodec.parse(encoded)).toEqual({
+ value: { tab },
+ valid: true,
+ });
+ });
it('defaults to involving for invalid or missing tabs', () => {
expect(reviewsTabSearchCodec.parse({})).toEqual({
diff --git a/apps/web/src/features/reviews-view/reviews-tab-search.ts b/apps/web/src/features/reviews-view/reviews-tab-search.ts
index 0b4324b9ed..9f8242985d 100644
--- a/apps/web/src/features/reviews-view/reviews-tab-search.ts
+++ b/apps/web/src/features/reviews-view/reviews-tab-search.ts
@@ -4,7 +4,15 @@ import type { ReviewsScope } from './reviews-types';
export const reviewsTabSearch = {
namespace: 'reviews',
- schema: z.object({ tab: z.enum(['involving', 'all', 'authored']) }),
+ schema: z.object({
+ tab: z.enum([
+ 'all',
+ 'authored',
+ 'assigned',
+ 'involving',
+ 'review_requests',
+ ]),
+ }),
defaults: { tab: 'involving' as ReviewsScope },
};
diff --git a/apps/web/src/features/reviews-view/reviews-types.ts b/apps/web/src/features/reviews-view/reviews-types.ts
index 10ca9f2817..f125331d6b 100644
--- a/apps/web/src/features/reviews-view/reviews-types.ts
+++ b/apps/web/src/features/reviews-view/reviews-types.ts
@@ -1,2 +1,48 @@
-export type ReviewsScope = 'all' | 'involving' | 'authored';
-export type ReviewsSortId = 'updated_at' | 'created_at';
+export type ReviewsScope =
+ | 'all'
+ | 'authored'
+ | 'assigned'
+ | 'involving'
+ | 'review_requests';
+export type ReviewsSortId =
+ | 'recently_updated'
+ | 'least_recently_updated'
+ | 'newest'
+ | 'oldest';
+/** Review filters, which match the viewer's GitHub user id. */
+export type ReviewsReviewFilterId =
+ | 'reviewed_by_me'
+ | 'not_reviewed_by_me'
+ | 'awaiting_my_review';
+export type ReviewsFilterId =
+ | 'repository'
+ | 'author'
+ | 'assignee'
+ | 'label'
+ | 'review';
+/** Selected option ids per filter group; any option in a group matches. */
+export type ReviewsFilterSelection = Record<ReviewsFilterId, readonly string[]>;
+
+export const EMPTY_REVIEWS_FILTERS: ReviewsFilterSelection = {
+ repository: [],
+ author: [],
+ assignee: [],
+ label: [],
+ review: [],
+};
+
+/** Sidebar order, which the tab hotkeys follow. */
+export const REVIEWS_SCOPES: readonly ReviewsScope[] = [
+ 'all',
+ 'authored',
+ 'assigned',
+ 'involving',
+ 'review_requests',
+];
+
+/**
+ * Scopes the backend matches against the viewer's GitHub user id, so they wait
+ * for it. "Involves me" resolves the linked identity on the backend instead.
+ */
+export const scopeMatchesViewerGithubId = (scope: ReviewsScope) =>
+ scope === 'authored' || scope === 'assigned' || scope === 'review_requests';
diff --git a/apps/web/src/features/reviews-view/reviews-view.tsx b/apps/web/src/features/reviews-view/reviews-view.tsx
index dde49199cd..861f46651a 100644
--- a/apps/web/src/features/reviews-view/reviews-view.tsx
+++ b/apps/web/src/features/reviews-view/reviews-view.tsx
@@ -16,6 +16,7 @@ import { SplitPanel } from '@components/app/split-panel';
import { useUserContext } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { ListEntityMetadataQueryProvider } from '@entity';
+import { GithubLabelPill } from '@entity/components/GithubLabelPill';
import { useGithubLinkStatusQuery } from '@queries/auth/github-link';
import {
createMemo,
@@ -26,30 +27,39 @@ import {
Suspense,
} from 'solid-js';
import {
+ activeReviewsFilterCount,
ReviewsControls,
ReviewsFilterDrawer,
- type ReviewsFilterId,
} from './components/ReviewsControls';
import { ReviewsList } from './components/ReviewsList';
import { ReviewsSidebar } from './components/ReviewsSidebar';
import { createReviewsListController } from './primitives/create-reviews-list-controller';
+import { useReviewsFacetsQuery } from './queries/use-reviews-facets-query';
import { useReviewsQuery } from './queries/use-reviews-query';
-import { filterReviews } from './reviews-filter';
+import { effectiveReviewsFilters, searchReviews } from './reviews-filter';
import { reviewsHostedContent } from './reviews-hosted-content';
import { reviewsTabSearch, reviewsTabSearchCodec } from './reviews-tab-search';
-import type { ReviewsScope, ReviewsSortId } from './reviews-types';
+import {
+ EMPTY_REVIEWS_FILTERS,
+ REVIEWS_SCOPES,
+ type ReviewsFilterId,
+ type ReviewsFilterSelection,
+ type ReviewsScope,
+ type ReviewsSortId,
+ scopeMatchesViewerGithubId,
+} from './reviews-types';
import { reviewsPrRoute, reviewsSplitRoute } from './route';
const REVIEW_SCOPE_TITLES: Record<ReviewsScope, string> = {
- all: 'All PRs',
- involving: 'Involving me',
+ all: 'Pull requests',
authored: 'Authored by me',
+ assigned: 'Assigned to me',
+ involving: 'Involves me',
+ review_requests: 'Review requests',
};
-const REVIEW_SCOPE_TABS: PillTabItem<ReviewsScope>[] = [
- { value: 'involving', label: REVIEW_SCOPE_TITLES.involving },
- { value: 'all', label: REVIEW_SCOPE_TITLES.all },
- { value: 'authored', label: REVIEW_SCOPE_TITLES.authored },
-];
+const REVIEW_SCOPE_TABS: PillTabItem<ReviewsScope>[] = REVIEWS_SCOPES.map(
+ (scope) => ({ value: scope, label: REVIEW_SCOPE_TITLES[scope] })
+);
function ReviewsRoot() {
const panel = useSplitPanelOrThrow();
const layout = useSplitLayout();
@@ -62,59 +72,46 @@ function ReviewsRoot() {
const scope = (): ReviewsScope => tabSearch.tab;
const scopeTitle = () => REVIEW_SCOPE_TITLES[scope()];
const [search, setSearch] = createSignal('');
- const [sort, setSort] = createSignal<ReviewsSortId>('updated_at');
- const [selectedRepositories, setSelectedRepositories] = createSignal<
- string[]
- >([]);
- const [selectedAuthors, setSelectedAuthors] = createSignal<string[]>([]);
- const listEnabled = () => !params.foreignEntityId;
- const source = useReviewsQuery(sort, scope, listEnabled);
- const githubLink = useGithubLinkStatusQuery({ enabled: listEnabled });
+ const [sort, setSort] = createSignal<ReviewsSortId>('recently_updated');
+ const [filters, setFilters] = createSignal<ReviewsFilterSelection>(
+ EMPTY_REVIEWS_FILTERS
+ );
+ const listVisible = () => !params.foreignEntityId;
+ const githubLink = useGithubLinkStatusQuery({ enabled: listVisible });
const viewer = useUserContext();
const authorLogin = () =>
githubLink.isPending ? undefined : githubLink.data?.username;
const authorId = () =>
githubLink.isPending ? undefined : githubLink.data?.userId;
- const repositories = createMemo(() =>
- [
- ...new Set(
- source
- .reviews()
- .map((review) => `${review.metadata.owner}/${review.metadata.repo}`)
- ),
- ]
- .sort()
- .map((id) => ({ id, label: id }))
- );
- const authors = createMemo(() =>
- [
- ...new Set(
- source
- .reviews()
- .flatMap((review) =>
- review.metadata.authorLogin ? [review.metadata.authorLogin] : []
- )
- ),
- ]
- .sort()
- .map((id) => ({ id, label: id }))
+ const activeFilters = () =>
+ effectiveReviewsFilters(filters(), Boolean(authorId()));
+ const listEnabled = () =>
+ listVisible() &&
+ (!scopeMatchesViewerGithubId(scope()) || Boolean(authorId()));
+ const source = useReviewsQuery(
+ sort,
+ () => ({
+ scope: scope(),
+ filters: activeFilters(),
+ viewerGithubUserId: authorId(),
+ }),
+ listEnabled
);
+ const facets = useReviewsFacetsQuery();
const changeFilter = (
group: ReviewsFilterId,
id: string,
selected: boolean
- ) => {
- const setter =
- group === 'repository' ? setSelectedRepositories : setSelectedAuthors;
- setter((current) => {
- if (!selected) return current.filter((value) => value !== id);
- return current.includes(id) ? current : [...current, id];
+ ) =>
+ setFilters((current) => {
+ const ids = current[group];
+ if (selected === ids.includes(id)) return current;
+ return {
+ ...current,
+ [group]: selected ? [...ids, id] : ids.filter((value) => value !== id),
+ };
});
- };
- const clearFilters = () => {
- setSelectedRepositories([]);
- setSelectedAuthors([]);
- };
+ const clearFilters = () => setFilters(EMPTY_REVIEWS_FILTERS);
const clearSearch = () => setSearch('');
const searchForTab = (tab: ReviewsScope) => ({
[reviewsTabSearch.namespace]: reviewsTabSearchCodec.serialize({ tab }),
@@ -151,24 +148,25 @@ function ReviewsRoot() {
{ search: searchForTab(scope()) }
);
};
- const reviews = createMemo(() =>
- filterReviews(source.reviews(), {
- scope: scope(),
- authorLogin: authorLogin(),
- authorId: authorId(),
- search: search(),
- repositories: selectedRepositories(),
- authors: selectedAuthors(),
- })
- );
+ const reviews = createMemo(() => searchReviews(source.reviews(), search()));
const listController = createReviewsListController(reviews, openReview);
+ const selectLabels = (labels: string[]) => {
+ setFilters((current) => ({ ...current, label: labels }));
+ if (!listVisible()) openList();
+ };
const controls = () => ({
sort: sort(),
onSortChange: setSort,
- repositories: repositories(),
- authors: authors(),
- selectedRepositories: selectedRepositories(),
- selectedAuthors: selectedAuthors(),
+ repositories: facets.repositories(),
+ authors: facets.authors(),
+ assignees: facets.assignees(),
+ labels: facets.labels().map((label) => ({
+ id: label.name,
+ label: label.name,
+ content: () => <GithubLabelPill name={label.name} color={label.color} />,
+ })),
+ hasGithubIdentity: Boolean(authorId()),
+ selected: activeFilters(),
onFilterChange: changeFilter,
onClearFilters: clearFilters,
});
@@ -242,8 +240,7 @@ function ReviewsRoot() {
: githubLink.data?.status
}
search={search()}
- selectedRepositories={selectedRepositories()}
- selectedAuthors={selectedAuthors()}
+ hasFilters={activeReviewsFilterCount(activeFilters()) > 0}
onClearFilters={clearFilters}
onClearSearch={clearSearch}
onOpen={openReview}
@@ -289,6 +286,9 @@ function ReviewsRoot() {
<ReviewsSidebar
scope={scope()}
onScopeChange={selectScope}
+ labels={facets.labels()}
+ activeLabels={filters().label}
+ onActiveLabelsChange={selectLabels}
onOpenReview={openReview}
activeForeignEntityId={params.foreignEntityId}
/>
diff --git a/apps/web/src/features/reviews-view/route.tsx b/apps/web/src/features/reviews-view/route.tsx
index 2a0b3cf89a..5a92e02906 100644
--- a/apps/web/src/features/reviews-view/route.tsx
+++ b/apps/web/src/features/reviews-view/route.tsx
@@ -1,3 +1,4 @@
+import { changesSearch } from '@app/features/agent-changes/changes-search';
import { tasksSplitRoute } from '@app/features/tasks-view/route';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { defineRoute, useNavigate, useParams } from '@app/lib/split-router';
@@ -59,6 +60,7 @@ export const reviewsPrRoute = defineRoute({
namespace: 'block',
id: `pr:${foreignEntityId}`,
}),
+ search: [changesSearch.namespace],
toReference: ({ foreignEntityId }) => ({ type: 'pr', id: foreignEntityId }),
});
diff --git a/apps/web/src/lib/queries/agent-session/keys.ts b/apps/web/src/lib/queries/agent-session/keys.ts
index f5cd0ad902..a7461b12cf 100644
--- a/apps/web/src/lib/queries/agent-session/keys.ts
+++ b/apps/web/src/lib/queries/agent-session/keys.ts
@@ -16,3 +16,12 @@ export const agentSessionChangesKeys = createQueryKeys('agentSessionChanges', {
queryKey: [sessionId, changesetId],
}),
});
+
+/** Pull request links, looked up from either side. */
+export const agentSessionPullRequestKeys = createQueryKeys(
+ 'agentSessionPullRequests',
+ {
+ forPullRequest: (url: string) => ({ queryKey: [url] }),
+ forSession: (sessionId: string) => ({ queryKey: [sessionId] }),
+ }
+);
diff --git a/apps/web/src/lib/queries/agent-session/pull-requests.ts b/apps/web/src/lib/queries/agent-session/pull-requests.ts
new file mode 100644
index 0000000000..3c226dd042
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-session/pull-requests.ts
@@ -0,0 +1,73 @@
+import { throwOnErr } from '@core/util/result';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { queryClient } from '../client';
+import { agentSessionPullRequestKeys } from './keys';
+
+const PULL_REQUEST_LINKS_STALE_TIME = 30_000;
+
+/** Ids of the viewable sessions linked to the pull request at `url`. */
+export function usePullRequestAgentSessionsQuery(
+ url: Accessor<string | undefined>
+) {
+ return useQuery(() => ({
+ queryKey: agentSessionPullRequestKeys.forPullRequest(url() ?? '').queryKey,
+ queryFn: async () =>
+ (
+ await throwOnErr(() =>
+ agentHarnessServiceClient.sessionsForPullRequest(url()!)
+ )
+ ).sessionIds,
+ enabled: Boolean(url()),
+ staleTime: PULL_REQUEST_LINKS_STALE_TIME,
+ }));
+}
+
+/** The pull requests linked to a session, with who linked each. */
+export function useAgentSessionPullRequestsQuery(sessionId: Accessor<string>) {
+ return useQuery(() => ({
+ queryKey: agentSessionPullRequestKeys.forSession(sessionId()).queryKey,
+ queryFn: async () =>
+ (
+ await throwOnErr(() =>
+ agentHarnessServiceClient.listPullRequests(sessionId())
+ )
+ ).pullRequests,
+ staleTime: PULL_REQUEST_LINKS_STALE_TIME,
+ }));
+}
+
+type PullRequestLinkChange = { sessionId: string; url: string };
+
+const invalidateLink = ({ sessionId, url }: PullRequestLinkChange) =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: agentSessionPullRequestKeys.forPullRequest(url).queryKey,
+ }),
+ queryClient.invalidateQueries({
+ queryKey: agentSessionPullRequestKeys.forSession(sessionId).queryKey,
+ }),
+ ]);
+
+/** Link a pull request to a session the caller can edit. */
+export function useLinkAgentSessionPullRequestMutation() {
+ return useMutation(() => ({
+ mutationFn: ({ sessionId, url }: PullRequestLinkChange) =>
+ throwOnErr(() =>
+ agentHarnessServiceClient.linkPullRequest(sessionId, url)
+ ),
+ onSettled: (_data, _error, change) => invalidateLink(change),
+ }));
+}
+
+/** Unlink a pull request a person linked to a session. */
+export function useUnlinkAgentSessionPullRequestMutation() {
+ return useMutation(() => ({
+ mutationFn: ({ sessionId, url }: PullRequestLinkChange) =>
+ throwOnErr(() =>
+ agentHarnessServiceClient.unlinkPullRequest(sessionId, url)
+ ),
+ onSettled: (_data, _error, change) => invalidateLink(change),
+ }));
+}
diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.ts
index 09b1a6edb3..59e0d51fdb 100644
--- a/apps/web/src/lib/queries/soup/transform-utils.ts
+++ b/apps/web/src/lib/queries/soup/transform-utils.ts
@@ -32,7 +32,7 @@ import type {
SearchData,
WithSearch,
} from '@entity';
-import { toSubType } from '@entity/types/entity';
+import { type GithubPullRequestLabel, toSubType } from '@entity/types/entity';
import { resolveNotifiedAt } from '@queries/soup/normalized-cache/notified-floor';
import { resolveOwnTouch } from '@queries/soup/normalized-cache/own-touch';
import type {
@@ -908,11 +908,12 @@ export const mapApiSoupItemToEntity = (
return out;
})
.with({ tag: 'foreignEntity' }, (item) => {
- // `authorLogin`/`authorId` are enrichment-only fields the backend now
- // returns but that aren't on the base generated schema yet.
+ // `authorLogin`/`authorId`/`labels` are enrichment-only fields the
+ // backend now returns but that aren't on the base generated schema yet.
const metadata = item.data.metadata as unknown as GithubPullRequest & {
authorLogin?: string | null;
authorId?: number | null;
+ labels?: GithubPullRequestLabel[] | null;
};
let status: GithubPullRequestEntity['metadata']['status'] = 'open';
@@ -945,6 +946,7 @@ export const mapApiSoupItemToEntity = (
deletions: metadata.deletions ?? 0,
comments: metadata.comments ?? [],
checks: metadata.checks?.filter(Boolean) ?? [],
+ labels: metadata.labels ?? [],
authorLogin: metadata.authorLogin ?? undefined,
authorId: metadata.authorId ?? undefined,
},
diff --git a/apps/web/src/lib/queries/storage/github-pull-request-changes.ts b/apps/web/src/lib/queries/storage/github-pull-request-changes.ts
new file mode 100644
index 0000000000..eb3dfd82fd
--- /dev/null
+++ b/apps/web/src/lib/queries/storage/github-pull-request-changes.ts
@@ -0,0 +1,62 @@
+/**
+ * Queries for a GitHub pull request's changes at its current base and head.
+ *
+ * The server reads GitHub once per base and head and stores the result, so
+ * the summary answers from storage after the first viewer. A changeset id
+ * names one base and head, so its patch is cached for the life of the page.
+ */
+
+import { throwOnErr } from '@core/util/result';
+import { storageServiceClient } from '@service-storage/client';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { githubPullRequestChangesKeys } from './keys';
+
+const GITHUB_PULL_REQUEST_CHANGES_STALE_TIME = 60 * 1000;
+
+/** The changes of the pull request behind a foreign entity record. */
+export function useGithubPullRequestChangesQuery(
+ foreignEntityId: Accessor<string | undefined>
+) {
+ return useQuery(() => {
+ const id = foreignEntityId();
+ return {
+ queryKey: githubPullRequestChangesKeys.summary(id ?? '').queryKey,
+ queryFn: () =>
+ throwOnErr(() =>
+ storageServiceClient.getGithubPullRequestChanges({ id: id! })
+ ),
+ enabled: Boolean(id),
+ retry: false,
+ staleTime: GITHUB_PULL_REQUEST_CHANGES_STALE_TIME,
+ };
+ });
+}
+
+/**
+ * The unified diff behind one changeset of that pull request. `undefined`
+ * disables the query.
+ */
+export function useGithubPullRequestChangesPatchQuery(
+ foreignEntityId: Accessor<string | undefined>,
+ changesetId: Accessor<string | undefined>
+) {
+ return useQuery(() => {
+ const id = foreignEntityId();
+ const changeset = changesetId();
+ return {
+ queryKey: githubPullRequestChangesKeys.patch(id ?? '', changeset ?? '')
+ .queryKey,
+ queryFn: () =>
+ throwOnErr(() =>
+ storageServiceClient.getGithubPullRequestChangesPatch({
+ id: id!,
+ changeset: changeset!,
+ })
+ ),
+ enabled: Boolean(id) && Boolean(changeset),
+ retry: 1,
+ staleTime: Number.POSITIVE_INFINITY,
+ };
+ });
+}
diff --git a/apps/web/src/lib/queries/storage/github-pull-requests.ts b/apps/web/src/lib/queries/storage/github-pull-requests.ts
index 49fc6a716c..f94979309d 100644
--- a/apps/web/src/lib/queries/storage/github-pull-requests.ts
+++ b/apps/web/src/lib/queries/storage/github-pull-requests.ts
@@ -1,4 +1,5 @@
import { throwOnErr } from '@core/util/result';
+import type { GithubPullRequestLabel } from '@entity/types/entity';
import { authServiceClient } from '@service-auth/client';
import type {
EnrichedGithubPullRequest,
@@ -11,9 +12,13 @@ import type {
} from '@service-storage/generated/schemas';
import { useQuery, useQueryClient } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
-import { documentGithubPullRequestsKeys } from './keys';
+import {
+ documentGithubPullRequestsKeys,
+ githubPullRequestRefreshKeys,
+} from './keys';
const DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME = 60 * 1000;
+const GITHUB_PULL_REQUEST_REFRESH_STALE_TIME = 5 * 60 * 1000;
type DocumentIdInput =
| string
@@ -39,12 +44,13 @@ function readEnabled(enabled: EnabledInput | undefined): boolean {
/**
* Storage pull request extended with enrichment-only fields. The documents
- * service doesn't expose body/author yet, so they only arrive via the live
- * enrich merge and must stay optional.
+ * service doesn't expose body/author/labels yet, so they only arrive via the
+ * live enrich merge or stored metadata and must stay optional.
*/
export type GithubPullRequestWithDetails = GithubPullRequest & {
description?: string | null;
authorLogin?: string | null;
+ labels?: GithubPullRequestLabel[] | null;
};
function toGithubPullRequestRef(
@@ -187,3 +193,34 @@ export function useDocumentGithubPullRequestsQuery(
};
});
}
+
+/**
+ * Refresh one pull request from GitHub with the viewer's linked account, which
+ * rewrites every stored copy, then run `onRefreshed` so readers of the stored
+ * copy load it again. Without a linked account, or when GitHub is unavailable,
+ * the stored copy stays as it is.
+ */
+export function useRefreshGithubPullRequest(
+ pullRequest: Accessor<GithubPullRequestRef | undefined>,
+ onRefreshed: () => void
+) {
+ return useQuery(() => {
+ const reference = pullRequest();
+ return {
+ queryKey: githubPullRequestRefreshKeys.refresh(reference?.githubKey ?? '')
+ .queryKey,
+ enabled: reference !== undefined,
+ queryFn: async () => {
+ const result = await authServiceClient.enrichGithubPullRequests({
+ pullRequests: [reference!],
+ });
+ if (result.isErr()) return false;
+ onRefreshed();
+ return true;
+ },
+ staleTime: GITHUB_PULL_REQUEST_REFRESH_STALE_TIME,
+ retry: false,
+ refetchOnWindowFocus: false,
+ };
+ });
+}
diff --git a/apps/web/src/lib/queries/storage/keys.ts b/apps/web/src/lib/queries/storage/keys.ts
index ac51893dae..40503f7700 100644
--- a/apps/web/src/lib/queries/storage/keys.ts
+++ b/apps/web/src/lib/queries/storage/keys.ts
@@ -37,6 +37,15 @@ export const snippetRawKeys = createQueryKeys('snippetRaw', {
}),
});
+export const githubPullRequestRefreshKeys = createQueryKeys(
+ 'githubPullRequestRefresh',
+ {
+ refresh: (githubKey: string) => ({
+ queryKey: [githubKey],
+ }),
+ }
+);
+
export const documentGithubPullRequestsKeys = createQueryKeys(
'documentGithubPullRequests',
{
@@ -46,6 +55,18 @@ export const documentGithubPullRequestsKeys = createQueryKeys(
}
);
+export const githubPullRequestChangesKeys = createQueryKeys(
+ 'githubPullRequestChanges',
+ {
+ summary: (foreignEntityId: string) => ({
+ queryKey: [foreignEntityId],
+ }),
+ patch: (foreignEntityId: string, changesetId: string) => ({
+ queryKey: [foreignEntityId, changesetId],
+ }),
+ }
+);
+
export const pullRequestMentionKeys = createQueryKeys('pullRequestMention', {
foreignEntity: (id: string) => ({
queryKey: [id],
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
index fdf1e4ccec..28d418aabd 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
@@ -18,8 +18,10 @@ import type {
LoadAgentModelsRequest,
LoadAgentModelsResponse,
PreviewAgentSessionsResponse,
+ PullRequestSessionsResponse,
SandboxSize,
SandboxSizeBody,
+ SessionPullRequestsResponse,
SharePermissionV2,
UpdateSharePermissionRequestV2,
} from './generated/schemas';
@@ -287,6 +289,47 @@ export const agentHarnessServiceClient = {
);
},
+ /** The pull requests linked to a session: its agent's and any a person linked. */
+ listPullRequests(sessionId: string) {
+ return fetchWithToken<SessionPullRequestsResponse>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/pull-requests`,
+ { method: 'GET' }
+ );
+ },
+
+ /** Link the pull request at `url` to a session the caller can edit. */
+ linkPullRequest(sessionId: string, url: string) {
+ return fetchWithToken<Record<string, never>>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/pull-requests`,
+ {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url }),
+ errorResponseHandler: sessionError,
+ }
+ ).then((result) => result.map(() => undefined));
+ },
+
+ /** Unlink a pull request a person linked; the agent's own stays linked. */
+ unlinkPullRequest(sessionId: string, url: string) {
+ return fetchWithToken<Record<string, never>>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/pull-requests?${new URLSearchParams({ url })}`,
+ { method: 'DELETE', errorResponseHandler: sessionError }
+ ).then((result) => result.map(() => undefined));
+ },
+
+ /** The sessions linked to the pull request at `url` that the caller can view. */
+ sessionsForPullRequest(url: string) {
+ return fetchWithToken<PullRequestSessionsResponse>(
+ `${agentHarnessHost}/agent-sessions/by-pull-request`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url }),
+ }
+ );
+ },
+
setSessionSandboxSize(sessionId: string, size: SandboxSize) {
return fetchWithToken<SandboxSizeBody>(
`${agentHarnessHost}/agent-sessions/${sessionId}/sandbox-size`,
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index c015bbb5b9..1111e07a3e 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -115,6 +115,9 @@ import type { GetPendingProjectsHandler200 } from './generated/schemas/getPendin
import type { GetProjectContentResponse } from './generated/schemas/getProjectContentResponse';
import type { GetProjectResponse } from './generated/schemas/getProjectResponse';
import type { GetSystemSkillsHandler200 } from './generated/schemas/getSystemSkillsHandler200';
+import type { GithubPullRequestChangesPatchResponse } from './generated/schemas/githubPullRequestChangesPatchResponse';
+import type { GithubPullRequestChangesResponse } from './generated/schemas/githubPullRequestChangesResponse';
+import type { GithubPullRequestFacets } from './generated/schemas/githubPullRequestFacets';
import type { GithubPullRequestsResponse } from './generated/schemas/githubPullRequestsResponse';
import type { GroupedSoupGroupPage } from './generated/schemas/groupedSoupGroupPage';
import type { GroupedSoupInitialPage } from './generated/schemas/groupedSoupInitialPage';
@@ -162,6 +165,7 @@ import type { SlackCreateRequest } from './generated/schemas/slackCreateRequest'
import type { SlackRegisterRequest } from './generated/schemas/slackRegisterRequest';
import type { SmartTagPreview } from './generated/schemas/smartTagPreview';
import type { SoupPage } from './generated/schemas/soupPage';
+import type { StoredGithubPullRequest } from './generated/schemas/storedGithubPullRequest';
import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';
import type { TeamOutOfOfficeResponse } from './generated/schemas/teamOutOfOfficeResponse';
import type { TypedSuccessResponse } from './generated/schemas/typedSuccessResponse';
@@ -1753,6 +1757,72 @@ export const storageServiceClient = {
);
},
+ /**
+ * Repositories and authors among the GitHub pull requests visible to the
+ * caller and their team, most pull requests first.
+ */
+ async getGithubPullRequestFacets(): Promise<
+ Result<GithubPullRequestFacets, ResultError<FetchWithTokenErrorCode>[]>
+ > {
+ return await dssFetch<GithubPullRequestFacets>(
+ '/github_pull_requests/facets',
+ { method: 'GET' }
+ );
+ },
+
+ /** The pull request behind a foreign entity record the caller can view. */
+ async getGithubPullRequest({
+ id,
+ }: {
+ id: string;
+ }): Promise<
+ Result<StoredGithubPullRequest, ResultError<FetchWithTokenErrorCode>[]>
+ > {
+ return await dssFetch<StoredGithubPullRequest>(
+ `/github_pull_requests/${id}`,
+ { method: 'GET' }
+ );
+ },
+
+ /**
+ * The changes of that pull request at its current base and head, or why
+ * GitHub could not provide them.
+ */
+ async getGithubPullRequestChanges({
+ id,
+ }: {
+ id: string;
+ }): Promise<
+ Result<
+ GithubPullRequestChangesResponse,
+ ResultError<FetchWithTokenErrorCode>[]
+ >
+ > {
+ return await dssFetch<GithubPullRequestChangesResponse>(
+ `/github_pull_requests/${id}/changes`,
+ { method: 'GET' }
+ );
+ },
+
+ /** The patch of one changeset of that pull request. */
+ async getGithubPullRequestChangesPatch({
+ id,
+ changeset,
+ }: {
+ id: string;
+ changeset: string;
+ }): Promise<
+ Result<
+ GithubPullRequestChangesPatchResponse,
+ ResultError<FetchWithTokenErrorCode>[]
+ >
+ > {
+ return await dssFetch<GithubPullRequestChangesPatchResponse>(
+ `/github_pull_requests/${id}/changes/patch?changeset=${encodeURIComponent(changeset)}`,
+ { method: 'GET' }
+ );
+ },
+
async exportDocument({ documentId }) {
return (
await dssFetch<ExportDocumentResponse>(
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 194bf5c06b..f0081f114d 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -901,7 +901,8 @@ Existing announcement chips remain locked to the turn they announced.
Sessions with a linked GitHub pull request capture that PR's diff when each
turn ends, regardless of the coding runtime. Unpushed workspace changes and
-branches without a PR are not included. The session header gains a **Changes**
+branches without a PR are not included. The capture is the same stored diff the
+PR's Changes pane in Reviews shows for that base and head. The session header gains a **Changes**
toggle (`aria-pressed`) with green additions and red deletions (`+N −M`); it opens a resizable
**Changes** pane beside the transcript (drag the 1px divider between them).
Chat sessions on Macro's in-memory harness have no repository, so they show
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index c96ecddf34..9bda119cb5 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -47,18 +47,27 @@ instead. Keyboard list navigation only moves focus; press Enter to open the focu
With `enable-tasks-reviews` enabled (on by default in development), a
`Reviews` shortcut appears above `My Tasks` in the Tasks sidebar and mobile tabs.
-It opens a separate `/app/reviews` shell with `Involving me` first and selected
-by default, followed by `All PRs` and `Authored by me`. The selected tab is
-stored in the URL and survives opening a PR and returning through the breadcrumb.
-The list contains accessible GitHub pull requests of any status. `Involving me`
+It opens a separate `/app/reviews` shell whose sidebar lists `Pull requests`,
+`Authored by me`, `Assigned to me`, `Involves me`, and `Review requests`;
+`Involves me` is selected by default. The selected tab is stored in the URL and
+survives opening a PR and returning through the breadcrumb.
+The list contains accessible GitHub pull requests of any status. `Involves me`
uses the server's participant filter for your linked GitHub account: author,
requested reviewer, assignee, commenter, or reviewer. Participant IDs are retained
across partial GitHub refreshes, so this is not strictly a list of current
review requests.
-`Authored by me` matches the linked GitHub login or user ID. If the link-status
-endpoint has no identity, the list explains why Authored by me is unavailable.
-Search, repository and author filters, and Updated/Created sort controls appear
-above the list. PR rows use the shared entity layout with selection checkboxes,
+`Authored by me`, `Assigned to me`, and `Review requests` match the linked
+GitHub user ID. If the link-status endpoint has no identity, the list explains
+why the tab is unavailable.
+Search, filter, and sort controls appear above the list. Filters cover
+repository, author, assignee, label, and, when a GitHub identity is linked,
+reviews (Reviewed by you, Not reviewed by you, and Awaiting review from you).
+Saved review selections stay inactive, including their filter badge and empty-state
+copy, while the GitHub identity is unavailable; they resume when it returns.
+Sort offers Recently updated, Least recently updated, Newest, and Oldest. When visible PRs
+have GitHub labels, a Labels section below Favorites lists them with their
+colors; choosing a label shows only PRs with it, and choosing it again clears
+it. PR rows use the shared entity layout with selection checkboxes,
author avatars and names, and a context menu. The current user's Macro display
name appears when their linked GitHub identity matches the PR author; other
authors fall back to GitHub names. The virtualized list fetches more pages as
@@ -72,17 +81,38 @@ context menu can remove the favorite. PR favorites also open in Reviews from the
global Favorites sidebar or command menu.
Select a PR to open `/app/reviews/pr/<foreignEntityId>` in the Reviews shell.
+Opening a PR refreshes it from GitHub in the background for viewers with a
+linked GitHub account, so labels, reviewers, and review state catch up without
+waiting for GitHub's next webhook. A successful refresh also reloads the Changes
+summary, so new commits replace the previous diff range.
Its breadcrumb returns to the Reviews list. Old `/app/pr/<id>` links redirect
to the Reviews detail. When the flag is off, the Reviews shortcut is hidden and
opening `/app/reviews` redirects to `/app/tasks` after flags load. Copied PR
detail links still work; check both URLs with the flag off.
-Check all three tab URLs, author avatars and display names, row selection and
+The PR header has a **Changes** toggle (`aria-pressed`) with the diff's `+N −M`
+at the PR's current base and head. It opens the same resizable Changes pane as
+an agent session (see "Reviewing a linked GitHub pull request" in
+[AI chat](ai-chat.md)) beside the PR, read-only: there is no review-note gutter,
+notes chip, or hand-off card. The PR's split stores the pane in
+`s<N>.changes.pane` and `s<N>.changes.style`, the same as a session, until you
+leave the PR or close its split. The first view of a base and head reads GitHub; later
+views, and agent sessions linked to the same PR, reuse the stored diff. An
+unavailable or oversized PR is explained in the pane.
+
+The Agent sessions side-panel section distinguishes loading PR details, loading
+sessions, failed requests, and an empty result. Failed session requests offer Retry.
+Hover a truncated session name to see its full name.
+
+Check all five tab URLs, the Labels section, author avatars and display names, row selection and
context menu, favorites add/remove and collapse/empty visibility, filters, sort,
illustrated empty states, loading, errors, and pagination after filtering. Use
Open in new split from a PR row's context menu; verify the Reviews list stays in
the original split and the PR appears beside it. Open a favorite from the global
sidebar, return through the breadcrumb, and open a copied link in a second split.
+Open a PR's Changes pane; check the file tree, a file's diff, **Unified / Split**,
+refresh after new commits, and that reloading with `s<N>.changes.pane` in the URL
+restores the pane. Check session loading/error/empty copy and full-name tooltips.
Use existing PRs and do not modify hosted data.
## Create a task