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 PR board, date groups, and channel origin pills (#7844)

Jacob Beckermanfe739be188a6
diff --git a/.sqlx/query-79c6d4a87facfbb433b9bfde54f94c7349983acf44ed2cded7c067d60d2b59e6.json b/.sqlx/query-b2d1e6250064842220ae51006d63acd58ba2c3e596118b833e55ed81f1af5534.json
similarity index 59%
rename from .sqlx/query-79c6d4a87facfbb433b9bfde54f94c7349983acf44ed2cded7c067d60d2b59e6.json
rename to .sqlx/query-b2d1e6250064842220ae51006d63acd58ba2c3e596118b833e55ed81f1af5534.json
index b0f4e424c6..5bf9fc32ec 100644
--- a/.sqlx/query-79c6d4a87facfbb433b9bfde54f94c7349983acf44ed2cded7c067d60d2b59e6.json
+++ b/.sqlx/query-b2d1e6250064842220ae51006d63acd58ba2c3e596118b833e55ed81f1af5534.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n link.github_key,\n link.agent_session_id,\n link.source,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\"\n FROM agent_session_pull_request AS link\n JOIN agent_session AS session ON session.id = link.agent_session_id\n WHERE lower(link.github_key) = ANY($1)\n ORDER BY link.created_at, link.agent_session_id\n ",
+ "query": "\n SELECT\n link.github_key,\n link.agent_session_id,\n link.source,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n COALESCE(session.originating_message_id, session.thread_id)\n AS \"origin_message_id?: Uuid\"\n FROM agent_session_pull_request AS link\n JOIN agent_session AS session ON session.id = link.agent_session_id\n WHERE lower(link.github_key) = ANY($1)\n ORDER BY link.created_at, link.agent_session_id\n ",
"describe": {
"columns": [
{
@@ -22,6 +22,11 @@
"ordinal": 3,
"name": "thread_parent?: Json<MessageParent>",
"type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "origin_message_id?: Uuid",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -33,8 +38,9 @@
false,
false,
false,
+ null,
null
]
},
- "hash": "79c6d4a87facfbb433b9bfde54f94c7349983acf44ed2cded7c067d60d2b59e6"
+ "hash": "b2d1e6250064842220ae51006d63acd58ba2c3e596118b833e55ed81f1af5534"
}
diff --git a/apps/web/src/features/block-pr/component/MergePullRequestButton.tsx b/apps/web/src/features/block-pr/component/MergePullRequestButton.tsx
index 2aeba58c97..34a779cb82 100644
--- a/apps/web/src/features/block-pr/component/MergePullRequestButton.tsx
+++ b/apps/web/src/features/block-pr/component/MergePullRequestButton.tsx
@@ -1,6 +1,6 @@
import GitMerge from '@phosphor/git-merge.svg';
import { Button, type ButtonSize, cn, confirmDialog } from '@ui';
-import { getOwner, Show } from 'solid-js';
+import { getOwner, type Owner, Show } from 'solid-js';
import {
createMergePullRequestAction,
type MergePullRequestTarget,
@@ -11,6 +11,45 @@ import {
} from '../primitives/pull-request-ready-to-merge';
import { prDisplayName } from '../util/prKey';
+/** Ask before merging, naming the pull request. */
+export function confirmMergePullRequest(
+ target: MergePullRequestTarget,
+ owner: Owner | null
+) {
+ return confirmDialog(
+ {
+ title: 'Merge pull request?',
+ get body() {
+ return (
+ <div class="space-y-4 pt-2">
+ <div class="flex items-start gap-3 rounded-lg border border-edge-muted bg-input p-3">
+ <GitMerge
+ aria-hidden="true"
+ class="mt-0.5 size-4 shrink-0 text-ink-muted"
+ />
+ <div class="min-w-0 space-y-1">
+ <Show when={target.title}>
+ <p class="text-sm font-medium text-ink wrap-anywhere">
+ {target.title}
+ </p>
+ </Show>
+ <p class="text-xs text-ink-muted wrap-anywhere">
+ {prDisplayName(target)}
+ </p>
+ </div>
+ </div>
+ <p>
+ This will merge the pull request into its base branch on GitHub.
+ </p>
+ </div>
+ );
+ },
+ confirmLabel: 'Merge pull request',
+ },
+ { owner }
+ );
+}
+
/**
* Merge an open pull request as the signed-in user. Renders nothing unless
* the pull request is open, not a draft, and its checks have finished
@@ -31,40 +70,7 @@ export function MergePullRequestButton(props: {
const owner = getOwner();
const action = createMergePullRequestAction({
onMerged: props.onMerged,
- confirm: (target) =>
- confirmDialog(
- {
- title: 'Merge pull request?',
- get body() {
- return (
- <div class="space-y-4 pt-2">
- <div class="flex items-start gap-3 rounded-lg border border-edge-muted bg-input p-3">
- <GitMerge
- aria-hidden="true"
- class="mt-0.5 size-4 shrink-0 text-ink-muted"
- />
- <div class="min-w-0 space-y-1">
- <Show when={target.title}>
- <p class="text-sm font-medium text-ink wrap-anywhere">
- {target.title}
- </p>
- </Show>
- <p class="text-xs text-ink-muted wrap-anywhere">
- {prDisplayName(target)}
- </p>
- </div>
- </div>
- <p>
- This will merge the pull request into its base branch on
- GitHub.
- </p>
- </div>
- );
- },
- confirmLabel: 'Merge pull request',
- },
- { owner }
- ),
+ confirm: (target) => confirmMergePullRequest(target, owner),
});
const label = () => (action.pending() ? 'Merging…' : 'Merge');
return (
diff --git a/apps/web/src/features/block-pr/component/PrLinks.tsx b/apps/web/src/features/block-pr/component/PrLinks.tsx
index 21c015baf8..ba9cf885f6 100644
--- a/apps/web/src/features/block-pr/component/PrLinks.tsx
+++ b/apps/web/src/features/block-pr/component/PrLinks.tsx
@@ -1,6 +1,12 @@
+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import type { SplitContent } from '@components/app/split-layout/layoutManager';
-import { AgentSessionMentionLabel } from '@core/component/LexicalMarkdown/component/decorator/AgentSessionMentionLabel';
+import { PopupPreview } from '@core/component/DocumentPreview';
+import { HoverCard } from '@core/component/HoverCard';
import { useChannelName } from '@core/context/channels';
+import {
+ rowPillClasses,
+ rowPillTriggerClasses,
+} from '@entity/components/row-pill';
import MacroIcon from '@icon/macro-logo.svg';
import ClaudeIcon from '@icon/wide-claude.svg';
import CodexIcon from '@icon/wide-codex-ide.svg';
@@ -11,16 +17,15 @@ import GithubIcon from '@phosphor/github-logo.svg';
import HashIcon from '@phosphor/hash.svg';
import ListChecksIcon from '@phosphor/list-checks.svg';
import RobotIcon from '@phosphor/robot.svg';
-import AgentIcon from '@phosphor/sparkle.svg';
import { PropertyValueIcon } from '@property/component/propertyValue';
import { PROPERTY_OPTION_IDS } from '@property/constants';
-import { useAgentSessionMentionPreview } from '@queries/agent-session/mentions';
import { cn, Surface, Tooltip } from '@ui';
import { type Component, For, type JSX, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { match } from 'ts-pattern';
import {
PR_PRIORITY_LABELS,
+ type PrChannelOrigin,
type PrLinks,
type PrPriority,
type PrPriorityId,
@@ -124,9 +129,11 @@ function LinkPill(props: {
const body = () => (
<>
<props.icon class="size-3 shrink-0" />
- <span class="min-w-0 truncate">{first()?.label()}</span>
+ <span data-pill-text class="min-w-0 truncate">
+ {first()?.label()}
+ </span>
<Show when={props.items.length > 1}>
- <span class="shrink-0 tabular-nums text-ink-extra-muted">
+ <span data-pill-text class="shrink-0 tabular-nums text-ink-extra-muted">
+{props.items.length - 1}
</span>
</Show>
@@ -147,10 +154,7 @@ function LinkPill(props: {
>
<button
type="button"
- class={cn(
- 'inline-flex h-6 min-w-0 max-w-40 items-center gap-1 rounded-full border border-edge bg-surface/50 px-1.5 text-xs font-medium text-ink-muted hover:bg-hover hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',
- props.class
- )}
+ class={rowPillTriggerClasses(cn('max-w-40', props.class))}
aria-label={`Open linked ${props.kind.toLowerCase()}`}
{...isolate}
onClick={(event) => {
@@ -165,10 +169,7 @@ function LinkPill(props: {
>
<Popover placement="bottom-end" gutter={4} flip>
<Popover.Trigger
- class={cn(
- 'inline-flex h-6 min-w-0 max-w-40 items-center gap-1 rounded-full border border-edge bg-surface/50 px-1.5 text-xs font-medium text-ink-muted hover:bg-hover hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',
- props.class
- )}
+ class={rowPillTriggerClasses(cn('max-w-40', props.class))}
aria-label={`${props.items.length} linked ${props.kind.toLowerCase()}s`}
{...isolate}
onClick={(event: MouseEvent) => event.stopPropagation()}
@@ -213,42 +214,118 @@ function LinkPill(props: {
);
}
-function SessionName(props: { id: string }) {
- const preview = useAgentSessionMentionPreview(
- () => props.id,
- () => true
+/** The channel message an agent was started from, opened at that message. */
+const channelOriginContent = (origin: PrChannelOrigin): SplitContent => ({
+ type: 'channel',
+ id: origin.channelId,
+ params: origin.messageId
+ ? { [CHANNEL_URL_PARAMS.message]: origin.messageId }
+ : undefined,
+});
+
+function ChannelOriginPill(props: {
+ origin: PrChannelOrigin;
+ /** Show only the mark, for the pills stacked behind the first. */
+ stacked: boolean;
+ onOpen: OpenPrLink;
+}) {
+ const name = useChannelName(props.origin.channelId, 'Channel');
+ const pill = () => (
+ <button
+ type="button"
+ class={rowPillTriggerClasses('max-w-40')}
+ aria-label={`Open the message in #${name()} that started the agent`}
+ {...isolate}
+ onClick={(event) => {
+ event.stopPropagation();
+ props.onOpen(channelOriginContent(props.origin), event.shiftKey);
+ }}
+ >
+ <HashIcon class="size-3 shrink-0" />
+ <span
+ data-pill-text
+ class={cn(
+ 'min-w-0 truncate',
+ props.stacked &&
+ 'hidden group-hover/channels:inline group-focus-within/channels:inline'
+ )}
+ >
+ {name()}
+ </span>
+ </button>
+ );
+ return (
+ <Show
+ when={props.origin.messageId}
+ fallback={
+ <Tooltip as="span" label={`Started from #${name()}`}>
+ {pill()}
+ </Tooltip>
+ }
+ >
+ {(messageId) => (
+ <HoverCard
+ triggerClass="min-w-0"
+ trigger={pill()}
+ content={
+ <PopupPreview
+ mouseEnter={() => {}}
+ mouseLeave={() => {}}
+ documentInfo={{
+ id: props.origin.channelId,
+ type: 'channel',
+ params: { [CHANNEL_URL_PARAMS.message]: messageId() },
+ isOpenable: true,
+ }}
+ />
+ }
+ />
+ )}
+ </Show>
);
- const name = () => {
- const current = preview.isSuccess ? preview.data : undefined;
- return current?.access === 'access'
- ? current.data.name || 'Agent session'
- : 'Agent session';
- };
- return <AgentSessionMentionLabel label={name()} />;
}
-function ChannelName(props: { id: string }) {
- const name = useChannelName(props.id, 'Channel');
- return <>{name()}</>;
+/**
+ * The channel messages the linked agents were started from, such as an
+ * @mention. Several overlap as a stack that spreads out on hover; each
+ * previews its message on hover and opens the channel at it.
+ */
+function ChannelOriginPills(props: {
+ origins: readonly PrChannelOrigin[];
+ onOpen: OpenPrLink;
+}) {
+ return (
+ <Show when={props.origins.length > 0}>
+ <span
+ class="group/channels flex min-w-0 shrink items-center [&>*+*]:-ml-2 hover:[&>*+*]:ml-0.5 focus-within:[&>*+*]:ml-0.5 [&>*]:relative [&>*]:transition-[margin] [&>*:hover]:z-10"
+ aria-label={`Started from ${props.origins.length} channel ${
+ props.origins.length === 1 ? 'message' : 'messages'
+ }`}
+ >
+ <For each={props.origins}>
+ {(origin, index) => (
+ <ChannelOriginPill
+ origin={origin}
+ stacked={index() > 0}
+ onOpen={props.onOpen}
+ />
+ )}
+ </For>
+ </span>
+ </Show>
+ );
}
/**
- * Chips for the agents, tickets, customers, and channels a pull request links
- * to. Each opens the linked item in a split.
+ * Chips for where a pull request was started (the tool and the channel
+ * messages its agents came from) and the customers and tickets it links to.
+ * Each opens the linked item in a split. Agent sessions have their own chip.
*/
export function PrLinkChips(props: {
links: PrLinks;
companyName: (id: string) => string | undefined;
onOpen: OpenPrLink;
}) {
- const sessions = (): LinkItem[] =>
- props.links.sessions.map((session) => ({
- key: session.id,
- content: { type: 'agent', id: session.id },
- text: () =>
- session.source === 'agent' ? 'opened by its agent' : 'linked session',
- label: () => <SessionName id={session.id} />,
- }));
const tasks = (): LinkItem[] =>
props.links.tasks.map((task) => ({
key: task.id,
@@ -278,22 +355,15 @@ export function PrLinkChips(props: {
label: text,
};
});
- const channels = (): LinkItem[] =>
- props.links.channelIds.map((id) => ({
- key: id,
- content: { type: 'channel', id },
- label: () => <ChannelName id={id} />,
- }));
+ // Contents, so a compacting row can stack these pills with its own.
return (
- <span class="flex min-w-0 shrink items-center gap-1">
+ <span class="contents">
<Show when={props.links.origin}>
{(origin) => <PrOriginBadge origin={origin()} onOpen={props.onOpen} />}
</Show>
- <LinkPill
- kind="Agent session"
- icon={AgentIcon}
- items={sessions()}
+ <ChannelOriginPills
+ origins={props.links.channelOrigins}
onOpen={props.onOpen}
/>
<LinkPill
@@ -308,12 +378,6 @@ export function PrLinkChips(props: {
items={tasks()}
onOpen={props.onOpen}
/>
- <LinkPill
- kind="Channel"
- icon={HashIcon}
- items={channels()}
- onOpen={props.onOpen}
- />
</span>
);
}
@@ -357,7 +421,7 @@ export function PrOriginBadge(props: { origin: PrOrigin; onOpen: OpenPrLink }) {
const content = () => (
<>
<PrOriginIcon tool={props.origin.tool} />
- <span class="min-w-0 truncate">
+ <span data-pill-text class="min-w-0 truncate">
{PR_ORIGIN_LABELS[props.origin.tool]}
</span>
</>
@@ -368,7 +432,7 @@ export function PrOriginBadge(props: { origin: PrOrigin; onOpen: OpenPrLink }) {
when={target()}
fallback={
<span
- class="inline-flex h-6 min-w-0 max-w-32 items-center gap-1 rounded-full border border-edge bg-surface/50 px-1.5 text-xs font-medium text-ink-muted"
+ class={rowPillClasses('max-w-32')}
aria-label={prOriginDescription(props.origin)}
>
{content()}
@@ -377,7 +441,7 @@ export function PrOriginBadge(props: { origin: PrOrigin; onOpen: OpenPrLink }) {
>
<button
type="button"
- class="inline-flex h-6 min-w-0 max-w-32 items-center gap-1 rounded-full border border-edge bg-surface/50 px-1.5 text-xs font-medium text-ink-muted hover:bg-hover hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
+ class={rowPillTriggerClasses('max-w-32')}
aria-label={`${prOriginDescription(props.origin)}. Open the session`}
{...isolate}
onClick={(event) => {
@@ -401,7 +465,7 @@ export function PrLinksPending() {
return (
<span
aria-hidden="true"
- class="h-5 w-12 shrink-0 animate-pulse rounded-full bg-ink/5"
+ class="h-6 w-12 shrink-0 animate-pulse rounded-full bg-ink/5"
/>
);
}
diff --git a/apps/web/src/features/block-pr/data/pr-links.ts b/apps/web/src/features/block-pr/data/pr-links.ts
index 6c6f868b9e..f744ef9f0c 100644
--- a/apps/web/src/features/block-pr/data/pr-links.ts
+++ b/apps/web/src/features/block-pr/data/pr-links.ts
@@ -27,6 +27,16 @@ export type PrLinkSession = {
parent?: PrLinkSessionParent;
/** The session's harness slug, for sessions whose agent opened the PR. */
harness?: string;
+ /** The message that started the session, such as an @mention, when known. */
+ messageId?: string;
+};
+
+/** A channel message an agent was started from, such as an @mention. */
+export type PrChannelOrigin = {
+ channelId: string;
+ /** The message that started the agent; absent when it is not known. */
+ messageId?: string;
+ sessionId: string;
};
/** A task the pull request references: a customer ticket when it names a company. */
@@ -47,6 +57,8 @@ export type PrLinks = {
/** Linked tasks, open first, most urgent first. */
tasks: PrLinkTask[];
channelIds: string[];
+ /** The channel messages linked agents were started from, oldest link first. */
+ channelOrigins: PrChannelOrigin[];
companyIds: string[];
priority: PrPriority;
/** Where the pull request was started, when anything gives it away. */
@@ -161,6 +173,7 @@ export function buildPrLinks(input: {
session.parent?.type === 'channel' ? [session.parent.id] : []
)
),
+ channelOrigins: channelOrigins(input.sessions),
companyIds: unique([
...tasks.flatMap((task) => task.companyIds),
...input.sessions.flatMap((session) =>
@@ -172,6 +185,22 @@ export function buildPrLinks(input: {
};
}
+/** One origin per channel message; sessions from the same message share it. */
+function channelOrigins(sessions: readonly PrLinkSession[]): PrChannelOrigin[] {
+ const origins = new Map<string, PrChannelOrigin>();
+ for (const session of sessions) {
+ if (session.parent?.type !== 'channel') continue;
+ const key = `${session.parent.id}:${session.messageId ?? session.id}`;
+ if (!origins.has(key))
+ origins.set(key, {
+ channelId: session.parent.id,
+ messageId: session.messageId,
+ sessionId: session.id,
+ });
+ }
+ return [...origins.values()];
+}
+
/** Whether any link of `kind` exists, for the Reviews link filter. */
export const hasPrLink = (links: PrLinks, kind: PrLinkKind) =>
match(kind)
diff --git a/apps/web/src/features/block-pr/queries/pr-links-query.ts b/apps/web/src/features/block-pr/queries/pr-links-query.ts
index e0f3efe9a8..3ce5fd9549 100644
--- a/apps/web/src/features/block-pr/queries/pr-links-query.ts
+++ b/apps/web/src/features/block-pr/queries/pr-links-query.ts
@@ -165,6 +165,7 @@ export async function fetchPrLinks(
id: session.sessionId,
source: session.source,
parent: sessionParent(session.threadParent),
+ messageId: session.originMessageId ?? undefined,
})),
])
);
diff --git a/apps/web/src/features/email-view/components/EmailDateGroupHeader.tsx b/apps/web/src/features/email-view/components/EmailDateGroupHeader.tsx
index f51bf2a549..77af55d908 100644
--- a/apps/web/src/features/email-view/components/EmailDateGroupHeader.tsx
+++ b/apps/web/src/features/email-view/components/EmailDateGroupHeader.tsx
@@ -1,37 +1,14 @@
-import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';
+import { DateGroupHeading } from '@app/features/next-soup/soup-view/date-group-heading';
import type { SoupGroupHeaderRow } from '@app/features/soup';
-import { SOUP_ROW_CLASS } from '@entity/composed/list-entity/row-geometry';
-import { useListLayout } from '@entity/composed/list-entity/shared';
-import { cn } from '@ui';
export function EmailDateGroupHeader(props: {
row: SoupGroupHeaderRow;
isFirst: boolean;
}) {
- const listLayout = useListLayout();
-
- // Take the geometry of the single-line rows this header sits among (they
- // split by container width off the same `isWide`), so the label starts
- // exactly where their content does — just past the unread/checkbox gutter.
- const geometryClass = () =>
- (listLayout?.isWide() ?? true)
- ? SOUP_ROW_CLASS.wide
- : SOUP_ROW_CLASS.narrow;
-
return (
<div id={props.row.id} role="row">
<div role="gridcell">
- <SoupSectionHeader
- class={cn(
- geometryClass(),
- 'border-none my-0 bg-transparent text-ink-extra-muted/80',
- 'mx-(--soup-row-gutter) w-[calc(100%-2*var(--soup-row-gutter))]',
- 'pl-[calc(var(--soup-row-content-inset)-var(--soup-row-gutter))]',
- !props.isFirst && 'pt-5'
- )}
- >
- <span class="truncate">{props.row.label}</span>
- </SoupSectionHeader>
+ <DateGroupHeading label={props.row.label} isFirst={props.isFirst} />
</div>
</div>
);
diff --git a/apps/web/src/features/entity/components/GithubLabelPill.tsx b/apps/web/src/features/entity/components/GithubLabelPill.tsx
index 9d5d0c3c47..ec90d66d2f 100644
--- a/apps/web/src/features/entity/components/GithubLabelPill.tsx
+++ b/apps/web/src/features/entity/components/GithubLabelPill.tsx
@@ -1,14 +1,20 @@
import { DEFAULT_TAG_COLOR } from '@property/tags/tagColors';
-import { cn } from '@ui';
+import { cn, TagDot } from '@ui';
import { For, Show } from 'solid-js';
import type { GithubPullRequestLabel } from '../types/entity';
+import { rowPillClasses } from './row-pill';
const GITHUB_HEX_COLOR = /^#?([0-9a-f]{6})$/i;
+/** A GitHub label's color as CSS, or the default tag color when it has none. */
+export function githubLabelColor(color: string | null | undefined): string {
+ const hex = color && GITHUB_HEX_COLOR.exec(color)?.[1];
+ return hex ? `#${hex}` : DEFAULT_TAG_COLOR;
+}
+
/**
- * 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.
+ * A GitHub label drawn like Macro's tag pills: a neutral outline pill with
+ * the label's color as a dot, so labels read the same as email and task tags.
*/
export function GithubLabelPill(props: {
name: string;
@@ -16,22 +22,15 @@ export function GithubLabelPill(props: {
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() }}
+ title={props.name}
+ class={rowPillClasses(cn('max-w-full', props.class))}
>
- <span class="truncate">{props.name}</span>
+ <TagDot fill={githubLabelColor(props.color)} size="sm" />
+ <span data-pill-text class="min-w-0 truncate">
+ {props.name}
+ </span>
</span>
);
}
@@ -44,10 +43,7 @@ export function GithubLabelPills(props: {
}) {
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(', ')}
- >
+ <span class={cn('flex min-w-0 items-center gap-1', props.class)}>
<For each={props.labels}>
{(label) => (
<GithubLabelPill
diff --git a/apps/web/src/features/entity/components/PrAgentSessionsChip.tsx b/apps/web/src/features/entity/components/PrAgentSessionsChip.tsx
index 705bffa7b5..a4c0c88abb 100644
--- a/apps/web/src/features/entity/components/PrAgentSessionsChip.tsx
+++ b/apps/web/src/features/entity/components/PrAgentSessionsChip.tsx
@@ -1,12 +1,15 @@
import SparkleIcon from '@phosphor/sparkle.svg';
import { Button, cn, Dropdown } from '@ui';
import type { ParentProps } from 'solid-js';
+import { rowPillTriggerClasses } from './row-pill';
function ChipLabel(props: { label: string }) {
return (
<>
<SparkleIcon class="size-3 shrink-0 text-chat" aria-hidden="true" />
- <span class="min-w-0 truncate">{props.label}</span>
+ <span data-pill-text class="min-w-0 truncate">
+ {props.label}
+ </span>
</>
);
}
@@ -22,10 +25,7 @@ export function PrAgentSessionChip(props: {
variant="ghost"
size="xs"
noTouchResize
- class={cn(
- 'h-auto min-w-0 max-w-48 gap-1.5 rounded-full border-edge bg-surface/50 px-1.5 py-1 text-xs font-medium leading-tight text-ink-muted',
- props.class
- )}
+ class={cn(rowPillTriggerClasses('max-w-48'), props.class)}
title={props.label}
label={`Open agent session: ${props.label}`}
disabled={props.disabled}
@@ -57,10 +57,7 @@ export function PrAgentSessionsCountChip(
variant="ghost"
size="xs"
noTouchResize
- class={cn(
- 'h-auto min-w-0 max-w-48 gap-1.5 rounded-full border-edge bg-surface/50 px-1.5 py-1 text-xs font-medium leading-tight text-ink-muted',
- props.class
- )}
+ class={cn(rowPillTriggerClasses('max-w-48'), props.class)}
title={label()}
label={`Show ${label()}`}
onClick={(event: MouseEvent) => event.stopPropagation()}
diff --git a/apps/web/src/features/entity/components/row-pill.ts b/apps/web/src/features/entity/components/row-pill.ts
new file mode 100644
index 0000000000..53070b0c6e
--- /dev/null
+++ b/apps/web/src/features/entity/components/row-pill.ts
@@ -0,0 +1,28 @@
+import { badgeClasses, badgeTriggerClasses, cn } from '@ui';
+
+/**
+ * A non-interactive row pill drawn like a tag pill (`tagPillClasses`): a
+ * neutral outline with muted text, so pull request pills match email tags.
+ */
+export function rowPillClasses(className?: string): string {
+ return badgeClasses({
+ variant: 'outline',
+ size: 'sm',
+ class: cn(
+ 'min-w-0 border-edge-button bg-control text-ink-muted',
+ className
+ ),
+ });
+}
+
+/**
+ * An interactive row pill, the same classes as `tagPillClasses`. Kept here so
+ * row pills don't pull the tag picker into every pull request surface.
+ */
+export function rowPillTriggerClasses(className?: string): string {
+ return badgeTriggerClasses({
+ variant: 'outline',
+ size: 'sm',
+ class: cn('min-w-0 text-ink-muted transition-colors', className),
+ });
+}
diff --git a/apps/web/src/features/entity/composed/list-entity/compacting-pills.tsx b/apps/web/src/features/entity/composed/list-entity/compacting-pills.tsx
new file mode 100644
index 0000000000..777370b3e5
--- /dev/null
+++ b/apps/web/src/features/entity/composed/list-entity/compacting-pills.tsx
@@ -0,0 +1,36 @@
+import { cn } from '@ui';
+import { createSignal, type JSX } from 'solid-js';
+import { createPillCompaction } from './pill-compaction';
+
+/**
+ * A row of pills that gives way to the title: when the pills no longer fit,
+ * each drops its text (anything marked `data-pill-text`) and they overlap
+ * like a stack, keeping icons, dots, and their tooltips.
+ */
+export function CompactingPills(props: {
+ class?: string;
+ children: JSX.Element;
+}) {
+ const [element, setElement] = createSignal<HTMLElement>();
+ // The row is marked `data-pill-row`; it is what the pills measure room against.
+ const compaction = createPillCompaction(element, (pills) =>
+ pills.closest('[data-pill-row]')
+ );
+
+ return (
+ <span
+ ref={setElement}
+ data-compact={compaction.compact() ? '' : undefined}
+ class={cn(
+ 'group/pills flex min-w-0 items-center gap-1 overflow-hidden',
+ 'data-compact:gap-0 data-compact:[&_[data-pill-text]]:hidden',
+ // Pill groups render as `contents`, so their pills stack here too.
+ 'data-compact:[&>*+*]:-ml-1.5 data-compact:[&>.contents:not(:first-child)>*]:-ml-1.5 data-compact:[&>.contents>*+*]:-ml-1.5',
+ '[&>*]:relative [&>.contents>*]:relative [&_*:hover]:z-10',
+ props.class
+ )}
+ >
+ {props.children}
+ </span>
+ );
+}
diff --git a/apps/web/src/features/entity/composed/list-entity/foreign.tsx b/apps/web/src/features/entity/composed/list-entity/foreign.tsx
index 027fc93830..d2ccc2f5cb 100644
--- a/apps/web/src/features/entity/composed/list-entity/foreign.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/foreign.tsx
@@ -17,6 +17,7 @@ import {
Show,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
+import { rowPillClasses } from '../../components/row-pill';
import type { GithubPullRequestEntity } from '../../types/entity';
import { PrAgentSessionsChip } from '../../views/PrAgentSessionsChip';
@@ -28,13 +29,7 @@ type PillProps = {
function Pill(props: PillProps) {
return (
- <span
- title={props.title}
- class={cn(
- 'min-w-0 rounded-full inline-flex items-center gap-1 px-1.5 py-1 leading-tight text-xs font-medium border border-edge bg-surface/50',
- props.class
- )}
- >
+ <span title={props.title} class={rowPillClasses(props.class)}>
{props.children}
</span>
);
@@ -451,7 +446,9 @@ export function GithubAuthorBadge(props: {
/>
)}
</Show>
- <span class="min-w-0 truncate">{name()}</span>
+ <span data-pill-text class="min-w-0 truncate">
+ {name()}
+ </span>
</span>
);
}
diff --git a/apps/web/src/features/entity/composed/list-entity/pill-compaction.test.ts b/apps/web/src/features/entity/composed/list-entity/pill-compaction.test.ts
new file mode 100644
index 0000000000..473f7b1212
--- /dev/null
+++ b/apps/web/src/features/entity/composed/list-entity/pill-compaction.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+import { EXPANDED, nextPillCompaction } from './pill-compaction';
+
+describe('nextPillCompaction', () => {
+ it('stays expanded while the pills fit', () => {
+ expect(nextPillCompaction(EXPANDED, { overflow: 0, rowWidth: 800 })).toBe(
+ EXPANDED
+ );
+ });
+
+ it('compacts when the expanded pills overflow, remembering by how much', () => {
+ expect(
+ nextPillCompaction(EXPANDED, { overflow: 60, rowWidth: 700 })
+ ).toEqual({ compact: true, rowWidth: 700, deficit: 60 });
+ });
+
+ it('expands only once the row has grown by the deficit', () => {
+ const compact = nextPillCompaction(EXPANDED, {
+ overflow: 60,
+ rowWidth: 700,
+ });
+ expect(nextPillCompaction(compact, { overflow: 0, rowWidth: 740 })).toBe(
+ compact
+ );
+ expect(nextPillCompaction(compact, { overflow: 0, rowWidth: 760 })).toBe(
+ EXPANDED
+ );
+ });
+});
diff --git a/apps/web/src/features/entity/composed/list-entity/pill-compaction.ts b/apps/web/src/features/entity/composed/list-entity/pill-compaction.ts
new file mode 100644
index 0000000000..839ed70e3f
--- /dev/null
+++ b/apps/web/src/features/entity/composed/list-entity/pill-compaction.ts
@@ -0,0 +1,85 @@
+import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
+
+/** What compaction remembers about the moment it compacted. */
+export type PillCompactionState =
+ | { compact: false }
+ | {
+ compact: true;
+ /** The row's width when the pills stopped fitting. */
+ rowWidth: number;
+ /** How far the expanded pills overflowed then. */
+ deficit: number;
+ };
+
+export const EXPANDED: PillCompactionState = { compact: false };
+
+/**
+ * Compact once the expanded pills overflow, and expand again only when the
+ * row has grown by what they lacked. Compact pills always fit, so their own
+ * width cannot say whether the expanded ones would; the row width can.
+ */
+export function nextPillCompaction(
+ state: PillCompactionState,
+ measurement: { overflow: number; rowWidth: number }
+): PillCompactionState {
+ if (!state.compact)
+ return measurement.overflow > 1
+ ? {
+ compact: true,
+ rowWidth: measurement.rowWidth,
+ deficit: measurement.overflow,
+ }
+ : state;
+ return measurement.rowWidth >= state.rowWidth + state.deficit
+ ? EXPANDED
+ : state;
+}
+
+/**
+ * Whether a row's pills should collapse to their icons and overlap so the
+ * title keeps its room. Content changes start over from the expanded pills.
+ */
+export function createPillCompaction(
+ element: Accessor<HTMLElement | undefined>,
+ row: (element: HTMLElement) => HTMLElement | null
+) {
+ const [state, setState] = createSignal<PillCompactionState>(EXPANDED);
+
+ createEffect(() => {
+ const pills = element();
+ if (!pills) return;
+ const container = row(pills) ?? pills;
+ let frame: number | undefined;
+ const measure = () => {
+ frame = undefined;
+ setState((current) =>
+ nextPillCompaction(current, {
+ overflow: pills.scrollWidth - pills.clientWidth,
+ rowWidth: container.clientWidth,
+ })
+ );
+ };
+ const schedule = () => {
+ if (frame === undefined) frame = requestAnimationFrame(measure);
+ };
+ const resize = new ResizeObserver(schedule);
+ resize.observe(pills);
+ resize.observe(container);
+ const mutation = new MutationObserver(() => {
+ setState(EXPANDED);
+ schedule();
+ });
+ mutation.observe(pills, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ });
+ onCleanup(() => {
+ resize.disconnect();
+ mutation.disconnect();
+ if (frame !== undefined) cancelAnimationFrame(frame);
+ });
+ });
+
+ return { compact: () => state().compact };
+}
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 d74b6a07de..5a0845c352 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
@@ -36,6 +36,7 @@ import {
ChannelMessageWideContent,
ChannelWideContent,
} from './channel';
+import { CompactingPills } from './compacting-pills';
import { EmailWideContent, useOwningInboxForEntity } from './email';
import {
GithubPullRequestChecksIndicator,
@@ -89,8 +90,11 @@ export function WideLayout(props: LayoutProps) {
: props.hideCheckbox
? 'grid-cols-[1fr_auto_8ch]'
: 'grid-cols-[var(--soup-row-indicator-width)_1fr_auto_8ch]',
- '[--title-width:10rem]'
+ '[--title-width:10rem]',
+ // Pull request pills give way to the title rather than starve it.
+ isGithubPrEntity(props.entity) && '[container-type:inline-size]'
)}
+ data-pill-row={isGithubPrEntity(props.entity) ? '' : undefined}
style={{
'grid-template-areas': props.hideCheckbox
? '"content meta timestamp"'
@@ -119,7 +123,10 @@ export function WideLayout(props: LayoutProps) {
</Show>
<Entity.Slot
placement="content"
- class="ph-no-capture font-medium truncate items-center gap-2 flex"
+ class={cn(
+ 'ph-no-capture font-medium truncate items-center gap-2 flex',
+ isGithubPrEntity(props.entity) && 'min-w-[min(26rem,50cqw)]'
+ )}
>
<div class="size-4 shrink-0">
<Entity.Icon entity={props.entity} streamState={props.streamState} />
@@ -169,12 +176,6 @@ 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>
@@ -183,8 +184,32 @@ export function WideLayout(props: LayoutProps) {
</Match>
</Switch>
</Entity.Slot>
- <Entity.Slot placement="meta" class="flex items-center gap-2">
- {props.meta}
+ <Entity.Slot
+ placement="meta"
+ class={cn(
+ 'flex items-center gap-2',
+ isGithubPrEntity(props.entity) && 'min-w-0 overflow-hidden'
+ )}
+ >
+ <Show
+ when={isGithubPrEntity(props.entity) && props.entity}
+ fallback={props.meta}
+ >
+ {(entity) => (
+ <CompactingPills>
+ {props.meta}
+ <GithubLabelPills
+ labels={entity().metadata.labels}
+ class="contents"
+ pillClass="max-w-32 shrink-0"
+ />
+ <GithubPullRequestPills
+ entity={entity()}
+ authorDisplayName={props.authorDisplayName}
+ />
+ </CompactingPills>
+ )}
+ </Show>
<Show when={isProjectEntity(props.entity) && props.entity}>
{(entity) => (
<RowTags
@@ -250,14 +275,6 @@ export function WideLayout(props: LayoutProps) {
>
<SharedBadge ownerId={props.entity.ownerId} />
</Show>
- <Show when={isGithubPrEntity(props.entity) && props.entity}>
- {(entity) => (
- <GithubPullRequestPills
- entity={entity()}
- authorDisplayName={props.authorDisplayName}
- />
- )}
- </Show>
<Show when={isCallEntity(props.entity) && props.entity}>
{(entity) => (
<>
diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.ts
index 95c20f3bbb..cc4a05c641 100644
--- a/apps/web/src/features/entity/types/entity.ts
+++ b/apps/web/src/features/entity/types/entity.ts
@@ -81,6 +81,8 @@ export type GithubPullRequestEntity = ForeignEntityBase & {
description?: string;
/** The branch carrying the pull request's changes, when stored. */
headBranch?: string;
+ /** Whether the pull request is a draft, when known. */
+ draft?: boolean;
};
};
diff --git a/apps/web/src/features/next-soup/soup-view/date-group-heading.tsx b/apps/web/src/features/next-soup/soup-view/date-group-heading.tsx
new file mode 100644
index 0000000000..be2af1b8f3
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/date-group-heading.tsx
@@ -0,0 +1,34 @@
+import { SOUP_ROW_CLASS } from '@entity/composed/list-entity/row-geometry';
+import { useListLayout } from '@entity/composed/list-entity/shared';
+import { cn } from '@ui';
+import { SoupSectionHeader } from './section-header';
+
+/**
+ * A date bucket's heading ("Today", "Last 7 days") among list rows, as the
+ * email list draws it. Callers supply the row semantics around it.
+ */
+export function DateGroupHeading(props: { label: string; isFirst: boolean }) {
+ const listLayout = useListLayout();
+
+ // Take the geometry of the single-line rows this header sits among (they
+ // split by container width off the same `isWide`), so the label starts
+ // exactly where their content does — just past the unread/checkbox gutter.
+ const geometryClass = () =>
+ (listLayout?.isWide() ?? true)
+ ? SOUP_ROW_CLASS.wide
+ : SOUP_ROW_CLASS.narrow;
+
+ return (
+ <SoupSectionHeader
+ class={cn(
+ geometryClass(),
+ 'border-none my-0 bg-transparent text-ink-extra-muted/80',
+ 'mx-(--soup-row-gutter) w-[calc(100%-2*var(--soup-row-gutter))]',
+ 'pl-[calc(var(--soup-row-content-inset)-var(--soup-row-gutter))]',
+ !props.isFirst && 'pt-5'
+ )}
+ >
+ <span class="truncate">{props.label}</span>
+ </SoupSectionHeader>
+ );
+}
diff --git a/apps/web/src/features/reviews-view/components/ReviewsBoard.tsx b/apps/web/src/features/reviews-view/components/ReviewsBoard.tsx
new file mode 100644
index 0000000000..a85a51321b
--- /dev/null
+++ b/apps/web/src/features/reviews-view/components/ReviewsBoard.tsx
@@ -0,0 +1,345 @@
+import { TaskBoard } from '@app/features/tasks-view/components/task-board';
+import type {
+ TaskBoardColumn,
+ TaskBoardMove,
+ TaskBoardTask,
+} from '@app/features/tasks-view/core/task-board';
+import { confirmMergePullRequest } from '@block-pr/component/MergePullRequestButton';
+import {
+ PrLinkChips,
+ PrLinksPending,
+ PrPriorityBadge,
+} from '@block-pr/component/PrLinks';
+import { PrStatusIcon } from '@block-pr/component/PrStatus';
+import { priorityTaskName } from '@block-pr/data/pr-links';
+import { prDisplayName } from '@block-pr/util/prKey';
+import { toast } from '@core/component/Toast/Toast';
+import { ThrownResultError } from '@core/util/result';
+import type { GithubPullRequestEntity } from '@entity';
+import { GithubLabelPills } from '@entity/components/GithubLabelPill';
+import {
+ GithubAuthorBadge,
+ GithubPullRequestChecksIndicator,
+} from '@entity/composed/list-entity/foreign';
+import { PrAgentSessionsChip } from '@entity/views/PrAgentSessionsChip';
+import { queryClient } from '@queries/client';
+import { soupKeys } from '@queries/soup/keys';
+import { useSetGithubPullRequestDraftMutation } from '@queries/storage/pr-draft';
+import { useMergeGithubPullRequestMutation } from '@queries/storage/pr-merge';
+import { Button } from '@ui/components/Button';
+import { createMemo, createSignal, getOwner, Show } from 'solid-js';
+import { match } from 'ts-pattern';
+import {
+ isReviewsBoardStage,
+ type PullRequestMergeability,
+ REVIEWS_BOARD_STAGES,
+ type ReviewsBoardAction,
+ type ReviewsBoardStage,
+ reviewsBoardAction,
+ reviewsBoardStage,
+} from '../core/reviews-board';
+import type { ReviewsListLinks } from './ReviewsList';
+
+/** A stage set by a move, kept until the pull request itself changes. */
+type PendingStage = { stage: ReviewsBoardStage; updatedAt: unknown };
+
+function failureMessage(error: unknown, fallback: string) {
+ // GitHub's own reason when it declined; anything else is ours.
+ return error instanceof ThrownResultError && error.errors.length > 0
+ ? error.message
+ : fallback;
+}
+
+const ACTION_COPY: Record<
+ ReviewsBoardAction,
+ { done: string; failed: string }
+> = {
+ merge: { done: 'Merged', failed: 'Failed to merge pull request' },
+ 'convert-to-draft': {
+ done: 'Converted to draft:',
+ failed: 'Failed to convert pull request to a draft',
+ },
+ 'mark-ready': {
+ done: 'Ready for review:',
+ failed: 'Failed to mark pull request ready for review',
+ },
+};
+
+/**
+ * Pull requests as a board from Draft to Merged. Dropping a card asks GitHub
+ * for the matching change: Merged merges, Draft converts to a draft, and In
+ * review marks a draft ready. Checks failing, Conflicts, and Ready to merge
+ * are GitHub's verdicts, so they take no drops.
+ */
+export function ReviewsBoard(props: {
+ reviews: readonly GithubPullRequestEntity[];
+ mergeability: (
+ pullRequest: GithubPullRequestEntity['metadata']
+ ) => PullRequestMergeability | undefined;
+ links: ReviewsListLinks;
+ /** Changes when the board's contents are replaced, to drop stale motion. */
+ scope: string;
+ hasMore: boolean;
+ isLoadingMore: boolean;
+ onLoadMore: () => void;
+ onOpen: (foreignEntityId: string, newSplit: boolean) => void;
+}) {
+ const owner = getOwner();
+ const merge = useMergeGithubPullRequestMutation();
+ const setDraft = useSetGithubPullRequestDraftMutation();
+ const [pendingStages, setPendingStages] = createSignal<
+ ReadonlyMap<string, PendingStage>
+ >(new Map());
+ const [moving, setMoving] = createSignal<ReadonlySet<string>>(new Set());
+
+ const byId = createMemo(
+ () => new Map(props.reviews.map((review) => [review.id, review]))
+ );
+ const stageOf = (review: GithubPullRequestEntity) => {
+ const pending = pendingStages().get(review.id);
+ if (pending && pending.updatedAt === review.updatedAt) return pending.stage;
+ return reviewsBoardStage({
+ ...review.metadata,
+ mergeability: props.mergeability(review.metadata),
+ });
+ };
+ const columns = createMemo<TaskBoardColumn[]>(() => {
+ const cards = new Map<ReviewsBoardStage, TaskBoardTask[]>(
+ REVIEWS_BOARD_STAGES.map((stage) => [stage.id, []])
+ );
+ for (const review of props.reviews) {
+ const stage = stageOf(review);
+ if (!stage) continue;
+ cards.get(stage)?.push({
+ id: review.id,
+ name: review.metadata.name,
+ assigneeIds: [],
+ projectIds: [],
+ });
+ }
+ return REVIEWS_BOARD_STAGES.map((stage) => ({
+ id: stage.id,
+ label: stage.label,
+ tasks: cards.get(stage.id) ?? [],
+ hasMore: false,
+ loadingMore: false,
+ }));
+ });
+
+ const actionFor = (move: TaskBoardMove) => {
+ const review = byId().get(move.id);
+ if (!review || moving().has(move.id)) return undefined;
+ if (
+ !isReviewsBoardStage(move.fromLane) ||
+ !isReviewsBoardStage(move.toLane)
+ )
+ return undefined;
+ if (stageOf(review) !== move.fromLane) return undefined;
+ const action = reviewsBoardAction(move.fromLane, move.toLane);
+ return action && { review, action, toStage: move.toLane };
+ };
+
+ const updateSet = (id: string, add: boolean) =>
+ setMoving((current) => {
+ const next = new Set(current);
+ if (add) next.add(id);
+ else next.delete(id);
+ return next;
+ });
+ const updatePending = (id: string, value?: PendingStage) =>
+ setPendingStages((current) => {
+ const next = new Map(current);
+ if (value) next.set(id, value);
+ else next.delete(id);
+ return next;
+ });
+
+ const move = async (request: TaskBoardMove) => {
+ const found = actionFor(request);
+ if (!found) return false;
+ const { review, action, toStage } = found;
+ const target = {
+ owner: review.metadata.owner,
+ repo: review.metadata.repo,
+ number: review.metadata.number,
+ };
+ if (
+ action === 'merge' &&
+ !(await confirmMergePullRequest(
+ { ...target, title: review.metadata.name },
+ owner
+ ))
+ )
+ return false;
+
+ updateSet(review.id, true);
+ updatePending(review.id, { stage: toStage, updatedAt: review.updatedAt });
+ try {
+ await match(action)
+ .with('merge', () => merge.mutateAsync(target))
+ .with('convert-to-draft', () =>
+ setDraft.mutateAsync({ ...target, draft: true })
+ )
+ .with('mark-ready', () =>
+ setDraft.mutateAsync({ ...target, draft: false })
+ )
+ .exhaustive();
+ } catch (error) {
+ updatePending(review.id);
+ toast.failure(failureMessage(error, ACTION_COPY[action].failed));
+ return false;
+ } finally {
+ updateSet(review.id, false);
+ }
+ toast.success(`${ACTION_COPY[action].done} ${prDisplayName(target)}`);
+ // The routes patch the stored pull request first, so the list refetch
+ // already sees the change.
+ void queryClient.invalidateQueries({ queryKey: soupKeys.astItems._def });
+ return true;
+ };
+
+ const stageDescription = (id: string) =>
+ REVIEWS_BOARD_STAGES.find((stage) => stage.id === id)?.description;
+
+ return (
+ // Size from the content slot, which is not a flex container, like the
+ // task board: columns are absolutely placed and need a definite height.
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
+ <TaskBoard.Root
+ animationScope={props.scope}
+ columns={columns()}
+ canMove={(request) => actionFor(request) !== undefined}
+ onMove={move}
+ >
+ <TaskBoard.Columns aria-label="Pull request board">
+ {(column) => (
+ <TaskBoard.Column>
+ <TaskBoard.Header>
+ <h2
+ class="truncate text-sm font-medium"
+ title={stageDescription(column().id)}
+ >
+ {column().label}
+ </h2>
+ <span class="ml-auto shrink-0 text-xs text-ink-muted">
+ {column().tasks.length}
+ </span>
+ </TaskBoard.Header>
+ <TaskBoard.DropOverlay>
+ {stageDescription(column().id)}
+ </TaskBoard.DropOverlay>
+ <TaskBoard.Cards
+ itemsLabel="pull requests"
+ empty={
+ <p class="px-2 py-6 text-center text-xs text-ink-extra-muted">
+ No pull requests
+ </p>
+ }
+ >
+ {(card) => (
+ <Show when={byId().get(card().id)}>
+ {(review) => (
+ <TaskBoard.Card
+ task={card()}
+ canDrag={
+ column().id !== 'merged' && !moving().has(card().id)
+ }
+ pending={moving().has(card().id)}
+ onOpen={(_, event) =>
+ props.onOpen(card().id, event.shiftKey)
+ }
+ >
+ <ReviewsBoardCard
+ review={review()}
+ links={props.links}
+ onOpen={props.onOpen}
+ />
+ </TaskBoard.Card>
+ )}
+ </Show>
+ )}
+ </TaskBoard.Cards>
+ </TaskBoard.Column>
+ )}
+ </TaskBoard.Columns>
+ </TaskBoard.Root>
+ <Show when={props.hasMore}>
+ <div class="p-3">
+ <Button
+ size="sm"
+ disabled={props.isLoadingMore}
+ onClick={props.onLoadMore}
+ >
+ {props.isLoadingMore ? 'Loading…' : 'Load more pull requests'}
+ </Button>
+ </div>
+ </Show>
+ </div>
+ );
+}
+
+function ReviewsBoardCard(props: {
+ review: GithubPullRequestEntity;
+ links: ReviewsListLinks;
+ onOpen: (foreignEntityId: string, newSplit: boolean) => void;
+}) {
+ const links = () => props.links.linksFor(props.review);
+ return (
+ <div class="flex flex-col gap-2 p-3">
+ <div class="flex min-w-0 items-start gap-2">
+ <span class="flex h-6 shrink-0 items-center gap-1">
+ <PrStatusIcon status={props.review.metadata.status} />
+ <Show when={links()}>
+ {(current) => (
+ <PrPriorityBadge
+ priority={current().priority}
+ taskName={priorityTaskName(current())}
+ />
+ )}
+ </Show>
+ </span>
+ <button
+ type="button"
+ class="min-w-0 flex-1 break-words text-left text-sm font-medium leading-6 text-ink hover:underline"
+ onClick={(event) => {
+ if (event.detail > 1) return;
+ props.onOpen(props.review.id, event.shiftKey);
+ }}
+ >
+ {props.review.metadata.name}
+ </button>
+ <span data-kanban-no-drag class="flex shrink-0 items-center">
+ <GithubPullRequestChecksIndicator entity={props.review} />
+ </span>
+ </div>
+ <div class="flex min-w-0 items-center gap-2 text-xs text-ink-muted">
+ <span class="min-w-0 truncate">
+ {prDisplayName(props.review.metadata)}
+ </span>
+ <span class="ml-auto flex min-w-0 shrink-0 items-center">
+ <GithubAuthorBadge entity={props.review} />
+ </span>
+ </div>
+ <div
+ data-kanban-no-drag
+ class="flex min-w-0 flex-wrap items-center gap-1 empty:hidden"
+ >
+ <Show when={links()} fallback={<PrLinksPending />}>
+ {(current) => (
+ <PrLinkChips
+ links={current()}
+ companyName={props.links.companyName}
+ onOpen={props.links.onOpen}
+ />
+ )}
+ </Show>
+ <GithubLabelPills
+ labels={props.review.metadata.labels}
+ class="contents"
+ pillClass="max-w-40"
+ />
+ <PrAgentSessionsChip url={props.review.metadata.url} />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/reviews-view/components/ReviewsControls.tsx b/apps/web/src/features/reviews-view/components/ReviewsControls.tsx
index 6a00d206fa..709c0f830b 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsControls.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsControls.tsx
@@ -35,6 +35,8 @@ export type ReviewsControlProps = {
labels: ListControlOption<string>[];
/** Offers the review filters that match the viewer's GitHub user id. */
hasGithubIdentity: boolean;
+ /** Leaves out Status, for layouts that lay pull requests out by status. */
+ hideStatus?: boolean;
selected: ReviewsFilterSelection;
onFilterChange: (
group: ReviewsFilterId,
@@ -92,7 +94,9 @@ function filterGroups(
props: ReviewsControlProps
): ListFilterGroup<ReviewsFilterId, string>[] {
return [
- { id: 'status', label: 'Status', options: STATUS_OPTIONS },
+ ...(props.hideStatus
+ ? []
+ : [{ id: 'status' as const, label: 'Status', options: STATUS_OPTIONS }]),
{ id: 'priority', label: 'Priority', options: PRIORITY_OPTIONS },
{ id: 'linked', label: 'Linked to', options: LINKED_OPTIONS },
{ id: 'origin', label: 'Started from', options: ORIGIN_OPTIONS },
diff --git a/apps/web/src/features/reviews-view/components/ReviewsList.tsx b/apps/web/src/features/reviews-view/components/ReviewsList.tsx
index 25c836e356..2250899c1f 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsList.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsList.tsx
@@ -5,6 +5,7 @@ import {
toEntityActionListState,
useEntityActionHotkeys,
} from '@app/features/next-soup/actions';
+import { DateGroupHeading } from '@app/features/next-soup/soup-view/date-group-heading';
import { useInfiniteScrollSentinel } from '@app/lib/primitives/infinite-scroll-sentinel';
import { globalSplitManager } from '@app/signal/splitLayout';
import {
@@ -33,6 +34,7 @@ import { createElementSize } from '@solid-primitives/resize-observer';
import { Button } from '@ui';
import {
createEffect,
+ createMemo,
createSignal,
type JSX,
Match,
@@ -42,11 +44,13 @@ import {
Switch,
} from 'solid-js';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
+import { buildReviewsRows } from '../core/reviews-rows';
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,
+ type ReviewsSortId,
scopeMatchesViewerGithubId,
} from '../reviews-types';
import { ReviewsEmptyState } from './ReviewsEmptyState';
@@ -62,6 +66,7 @@ export type ReviewsListProps = {
list: ReviewsListController;
source: ReturnType<typeof useReviewsQuery>;
scope: ReviewsScope;
+ sort: ReviewsSortId;
authorLogin?: string;
authorId?: string;
viewerName?: string;
@@ -196,11 +201,39 @@ export function ReviewsList(props: ReviewsListProps) {
const [sentinel, setSentinel] = createSignal<HTMLDivElement>();
const listSize = createElementSize(listElement);
const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();
+ // Date headings sit among the rows like email's; focus and selection keep
+ // counting pull requests, so their indexes map to rows for scrolling.
+ const rows = createMemo(() =>
+ buildReviewsRows(reviews(), {
+ sort: props.sort,
+ grouped: !props.search.trim(),
+ })
+ );
+ const rowIndexes = createMemo(() => {
+ const indexes: number[] = [];
+ rows().forEach((row, index) => {
+ if (row.kind === 'review') indexes[row.index] = index;
+ });
+ return indexes;
+ });
+ const rowIndex = (reviewIndex: number) =>
+ rowIndexes()[reviewIndex] ?? reviewIndex;
+ const scrollHandle = () => {
+ const handle = virtualizer();
+ return (
+ handle && {
+ scrollToIndex: (
+ index: number,
+ options?: Parameters<VirtualizerHandle['scrollToIndex']>[1]
+ ) => handle.scrollToIndex(rowIndex(index), options),
+ }
+ );
+ };
const listInteractions = useListInteractions({
controller: list,
scopeId: panel.splitHotkeyScope,
enabled: panel.isPanelActive,
- scrollHandle: virtualizer,
+ scrollHandle,
activation: {
createMetadata: (intent) => ({ newSplit: intent === 'alternate' }),
alternateDescription: 'Open in new split',
@@ -211,7 +244,7 @@ export function ReviewsList(props: ReviewsListProps) {
getEntity: (review) => review,
onFocus: (target) => {
if (target)
- virtualizer()?.scrollToIndex(target.index, { align: 'nearest' });
+ scrollHandle()?.scrollToIndex(target.index, { align: 'nearest' });
listElement()?.focus();
},
});
@@ -383,57 +416,84 @@ export function ReviewsList(props: ReviewsListProps) {
<Virtualizer
as={ReviewListElement}
item="li"
- data={reviews()}
+ data={rows()}
scrollRef={listElement()}
ref={setVirtualizer}
keepMounted={
- list.focus.index() >= 0 ? [list.focus.index()] : undefined
+ list.focus.index() >= 0
+ ? [rowIndex(list.focus.index())]
+ : undefined
}
bufferSize={320}
itemSize={48}
onScroll={checkNearEnd}
>
- {(review) => (
- <ReviewRow
- review={review}
- checked={list.selection.isSelected(review.id)}
- authorDisplayName={
- isAuthoredBy(
- review,
- props.authorLogin,
- props.authorId
- )
- ? props.viewerName
- : undefined
- }
- favoriteAction={favoriteAction}
- onOpen={props.onOpen}
- links={props.links}
- onChecked={(checked, shiftKey) =>
- listInteractions.selection.set(review.id, checked, {
- range: shiftKey,
- })
- }
- onFocus={() =>
- list.focus.set(review.id, { reason: 'pointer' })
- }
- onClick={(event) => {
- if (event.metaKey || event.ctrlKey) {
- listInteractions.selection.toggle(review.id);
- return;
- }
- list.activate.key(review.id, {
- reason: 'pointer',
- metadata: { newSplit: event.shiftKey },
- });
- }}
- onActivate={(newSplit) =>
- list.activate.key(review.id, {
- reason: 'keyboard',
- metadata: { newSplit },
- })
- }
- />
+ {(row) => (
+ <Switch>
+ <Match when={row.kind === 'header' ? row : undefined}>
+ {(header) => (
+ <DateGroupHeading
+ label={header().label}
+ isFirst={rows()[0]?.id === header().id}
+ />
+ )}
+ </Match>
+ <Match when={row.kind === 'review' ? row : undefined}>
+ {(item) => {
+ const review = () => item().review;
+ return (
+ <ReviewRow
+ review={review()}
+ checked={list.selection.isSelected(review().id)}
+ authorDisplayName={
+ isAuthoredBy(
+ review(),
+ props.authorLogin,
+ props.authorId
+ )
+ ? props.viewerName
+ : undefined
+ }
+ favoriteAction={favoriteAction}
+ onOpen={props.onOpen}
+ links={props.links}
+ onChecked={(checked, shiftKey) =>
+ listInteractions.selection.set(
+ review().id,
+ checked,
+ {
+ range: shiftKey,
+ }
+ )
+ }
+ onFocus={() =>
+ list.focus.set(review().id, {
+ reason: 'pointer',
+ })
+ }
+ onClick={(event) => {
+ if (event.metaKey || event.ctrlKey) {
+ listInteractions.selection.toggle(
+ review().id
+ );
+ return;
+ }
+ list.activate.key(review().id, {
+ reason: 'pointer',
+ metadata: { newSplit: event.shiftKey },
+ });
+ }}
+ onActivate={(newSplit) =>
+ list.activate.key(review().id, {
+ reason: 'keyboard',
+ metadata: { newSplit },
+ })
+ }
+ />
+ );
+ }}
+ </Match>
+ </Switch>
)}
</Virtualizer>
</ListLayoutProvider>
diff --git a/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx b/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx
index db3a5bd016..cca3b4df63 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsSidebar.tsx
@@ -1,10 +1,13 @@
import {
CollapsibleSection,
+ SearchBar,
useViewTabHotkeys,
ViewSidebar,
} from '@app/components/view-shell';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { PrOriginIcon } from '@block-pr/component/PrLinks';
import { PrStatusIcon } from '@block-pr/component/PrStatus';
+import { PR_ORIGIN_LABELS, type PrOriginTool } from '@block-pr/data/pr-origin';
import {
type PrForeignEntityData,
prForeignEntityQueryOptions,
@@ -12,7 +15,9 @@ 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 { TabsInset } from '@core/component/TabsInset';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { githubLabelColor } from '@entity/components/GithubLabelPill';
import type { GithubPullRequestLabel } from '@entity/types/entity';
import { ContextMenu } from '@kobalte/core/context-menu';
import SplitIcon from '@phosphor/columns.svg';
@@ -30,8 +35,15 @@ import {
import type { Favorite } from '@service-storage/generated/schemas/favorite';
import { makePersisted } from '@solid-primitives/storage';
import { useQueries } from '@tanstack/solid-query';
+import { TagDot } from '@ui';
import { type Component, createMemo, createSignal, For, Show } from 'solid-js';
-import { REVIEWS_SCOPES, type ReviewsScope } from '../reviews-types';
+import {
+ REVIEWS_SCOPES,
+ type ReviewsLayout,
+ type ReviewsScope,
+ type ReviewsStatusTabId,
+} from '../reviews-types';
+import { ReviewsStatusTabs } from './ReviewsStatusTabs';
const SCOPE_ITEMS: Record<
ReviewsScope,
@@ -152,9 +164,9 @@ 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.
+ * GitHub labels among the visible pull requests, drawn like the email 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[];
@@ -185,7 +197,57 @@ function ReviewLabels(props: {
)
}
>
- <GithubLabelPill name={label.name} color={label.color} />
+ <ViewSidebar.Icon>
+ <TagDot fill={githubLabelColor(label.color)} />
+ </ViewSidebar.Icon>
+ <span class="truncate">{label.name}</span>
+ </ViewSidebar.Item>
+ )}
+ </For>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ </Show>
+ );
+}
+
+/**
+ * The tools the visible pull requests were started from, such as Claude or
+ * Codex. Like Labels, choosing one shows it alone and choosing it again clears it.
+ */
+function ReviewAgents(props: {
+ tools: readonly PrOriginTool[];
+ activeTools: readonly string[];
+ onActiveToolsChange: (tools: string[]) => void;
+}) {
+ const [open, setOpen] = makePersisted(createSignal(true), {
+ name: 'reviews-agents-open',
+ });
+
+ return (
+ <Show when={props.tools.length > 0}>
+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
+ <CollapsibleSection.Trigger>
+ <span class="min-w-0 truncate">Agents</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Content>
+ <ViewSidebar.Nav aria-label="Pull request agents">
+ <For each={props.tools}>
+ {(tool) => (
+ <ViewSidebar.Item
+ title={`Started from ${PR_ORIGIN_LABELS[tool]}`}
+ active={props.activeTools.includes(tool)}
+ onClick={() =>
+ props.onActiveToolsChange(
+ selectSidebarTag(props.activeTools, tool)
+ )
+ }
+ >
+ <ViewSidebar.Icon>
+ <PrOriginIcon tool={tool} class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="truncate">{PR_ORIGIN_LABELS[tool]}</span>
</ViewSidebar.Item>
)}
</For>
@@ -197,11 +259,24 @@ function ReviewLabels(props: {
}
export function ReviewsSidebar(props: {
+ search: string;
+ onSearchChange: (search: string) => void;
+ layout: ReviewsLayout;
+ onLayoutChange: (layout: ReviewsLayout) => void;
+ /** The status toggle; omitted when the status selection is custom or the board shows. */
+ status?: {
+ value: ReviewsStatusTabId | undefined;
+ onChange: (value: ReviewsStatusTabId) => void;
+ };
scope: ReviewsScope;
onScopeChange: (scope: ReviewsScope) => void;
labels: GithubPullRequestLabel[];
activeLabels: readonly string[];
onActiveLabelsChange: (labels: string[]) => void;
+ /** Tools the visible pull requests were started from, in display order. */
+ agents: readonly PrOriginTool[];
+ activeAgents: readonly string[];
+ onActiveAgentsChange: (tools: string[]) => void;
onOpenReview: (id: string, newSplit: boolean) => void;
activeForeignEntityId?: string;
}) {
@@ -222,6 +297,42 @@ export function ReviewsSidebar(props: {
<ViewSidebar.Title>Reviews</ViewSidebar.Title>
</div>
</ViewSidebar.Header>
+ <ViewSidebar.Primary class="flex flex-col gap-2">
+ <SearchBar
+ label="Search reviews"
+ placeholder="Search reviews"
+ autocomplete="off"
+ value={props.search}
+ onValueChange={props.onSearchChange}
+ class="border-0 bg-ink/5 shadow-none"
+ onEscape={() => props.onSearchChange('')}
+ />
+ {/* Touch layouts list pull requests; the board needs a pointer to drag. */}
+ <Show when={!isTouchDevice()}>
+ <TabsInset
+ aria-label="Pull request layout"
+ fullWidth
+ class="h-auto"
+ labelClass="py-1.5"
+ list={[
+ { value: 'board', label: 'Board' },
+ { value: 'list', label: 'List' },
+ ]}
+ value={props.layout}
+ onChange={(layout) =>
+ props.onLayoutChange(layout === 'board' ? 'board' : 'list')
+ }
+ />
+ </Show>
+ <Show when={props.status}>
+ {(status) => (
+ <ReviewsStatusTabs
+ value={status().value}
+ onChange={status().onChange}
+ />
+ )}
+ </Show>
+ </ViewSidebar.Primary>
<ViewSidebar.Content>
<ViewSidebar.Nav aria-label="Pull request views">
<For each={REVIEWS_SCOPES}>
@@ -245,6 +356,11 @@ export function ReviewsSidebar(props: {
onOpenReview={props.onOpenReview}
activeForeignEntityId={props.activeForeignEntityId}
/>
+ <ReviewAgents
+ tools={props.agents}
+ activeTools={props.activeAgents}
+ onActiveToolsChange={props.onActiveAgentsChange}
+ />
<ReviewLabels
labels={props.labels}
activeLabels={props.activeLabels}
diff --git a/apps/web/src/features/reviews-view/components/ReviewsStatusTabs.tsx b/apps/web/src/features/reviews-view/components/ReviewsStatusTabs.tsx
index d6c05758c9..cf28853451 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsStatusTabs.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsStatusTabs.tsx
@@ -1,27 +1,48 @@
-import { Tabs } from '@ui';
+import { TabsInset } from '@core/component/TabsInset';
+import GitMergeIcon from '@phosphor/git-merge.svg';
+import GitPullRequestIcon from '@phosphor/git-pull-request.svg';
+import StackIcon from '@phosphor/stack.svg';
+import type { Component } from 'solid-js';
+import { match } from 'ts-pattern';
import type { ReviewsStatusTabId } from '../reviews-types';
-const STATUS_TABS: { value: ReviewsStatusTabId; label: string }[] = [
- { value: 'open', label: 'Open' },
- { value: 'closed', label: 'Closed' },
+const STATUS_TABS: {
+ value: ReviewsStatusTabId;
+ label: string;
+ icon: Component<{ class?: string }>;
+}[] = [
+ { value: 'open', label: 'Open', icon: GitPullRequestIcon },
+ { value: 'closed', label: 'Closed', icon: GitMergeIcon },
+ { value: 'all', label: 'All', icon: StackIcon },
];
+/** Open, Closed (closed and merged), or All pull requests, as a toggle. */
export function ReviewsStatusTabs(props: {
value: ReviewsStatusTabId | undefined;
onChange: (value: ReviewsStatusTabId) => void;
+ class?: string;
}) {
- const onChange = (value: string) => {
- if (value === 'open' || value === 'closed') {
- props.onChange(value);
- }
- };
-
return (
- <Tabs
+ <TabsInset
aria-label="Pull request status"
- list={STATUS_TABS}
+ fullWidth
+ class={props.class ?? 'h-auto'}
+ labelClass="gap-1.5 py-1.5"
+ list={STATUS_TABS.map((tab) => ({
+ value: tab.value,
+ label: (
+ <>
+ <tab.icon class="size-3.5 shrink-0" aria-hidden="true" />
+ {tab.label}
+ </>
+ ),
+ }))}
value={props.value ?? ''}
- onChange={onChange}
+ onChange={(value) =>
+ match(value)
+ .with('open', 'closed', 'all', (status) => props.onChange(status))
+ .otherwise(() => undefined)
+ }
/>
);
}
diff --git a/apps/web/src/features/reviews-view/core/reviews-board.test.ts b/apps/web/src/features/reviews-view/core/reviews-board.test.ts
new file mode 100644
index 0000000000..db249f15e0
--- /dev/null
+++ b/apps/web/src/features/reviews-view/core/reviews-board.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import { reviewsBoardAction, reviewsBoardStage } from './reviews-board';
+
+const passed = { status: 'completed', conclusion: 'success' };
+const failed = { status: 'completed', conclusion: 'failure' };
+const running = { status: 'in_progress', conclusion: null };
+
+describe('reviewsBoardStage', () => {
+ it('places merged and closed pull requests', () => {
+ expect(reviewsBoardStage({ status: 'merged', checks: [failed] })).toBe(
+ 'merged'
+ );
+ expect(reviewsBoardStage({ status: 'closed' })).toBeUndefined();
+ });
+
+ it('keeps drafts in Draft whatever their checks or conflicts say', () => {
+ expect(
+ reviewsBoardStage({
+ status: 'open',
+ draft: true,
+ checks: [failed],
+ mergeability: 'conflicting',
+ })
+ ).toBe('draft');
+ });
+
+ it('ranks conflicts over failing checks over a clean run', () => {
+ expect(
+ reviewsBoardStage({
+ status: 'open',
+ checks: [failed],
+ mergeability: 'conflicting',
+ })
+ ).toBe('conflicts');
+ expect(
+ reviewsBoardStage({ status: 'open', checks: [passed, failed] })
+ ).toBe('failing');
+ expect(
+ reviewsBoardStage({
+ status: 'open',
+ checks: [passed],
+ mergeability: 'mergeable',
+ })
+ ).toBe('ready');
+ });
+
+ it('keeps pull requests with running or missing checks in review', () => {
+ expect(
+ reviewsBoardStage({ status: 'open', checks: [passed, running] })
+ ).toBe('review');
+ expect(reviewsBoardStage({ status: 'open', checks: [] })).toBe('review');
+ });
+});
+
+describe('reviewsBoardAction', () => {
+ it('merges from In review and Ready to merge only', () => {
+ expect(reviewsBoardAction('ready', 'merged')).toBe('merge');
+ expect(reviewsBoardAction('review', 'merged')).toBe('merge');
+ expect(reviewsBoardAction('failing', 'merged')).toBeUndefined();
+ expect(reviewsBoardAction('conflicts', 'merged')).toBeUndefined();
+ expect(reviewsBoardAction('draft', 'merged')).toBeUndefined();
+ });
+
+ it('converts any open pull request to a draft and marks drafts ready', () => {
+ for (const from of ['review', 'failing', 'conflicts', 'ready'] as const)
+ expect(reviewsBoardAction(from, 'draft')).toBe('convert-to-draft');
+ expect(reviewsBoardAction('draft', 'review')).toBe('mark-ready');
+ });
+
+ it('rejects drops on GitHub verdicts and moves out of Merged', () => {
+ expect(reviewsBoardAction('review', 'failing')).toBeUndefined();
+ expect(reviewsBoardAction('review', 'conflicts')).toBeUndefined();
+ expect(reviewsBoardAction('review', 'ready')).toBeUndefined();
+ expect(reviewsBoardAction('ready', 'review')).toBeUndefined();
+ expect(reviewsBoardAction('merged', 'draft')).toBeUndefined();
+ expect(reviewsBoardAction('draft', 'draft')).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/reviews-view/core/reviews-board.ts b/apps/web/src/features/reviews-view/core/reviews-board.ts
new file mode 100644
index 0000000000..3c1cec8b77
--- /dev/null
+++ b/apps/web/src/features/reviews-view/core/reviews-board.ts
@@ -0,0 +1,120 @@
+import {
+ type PullRequestCheck,
+ pullRequestReadyToMerge,
+} from '@block-pr/primitives/pull-request-ready-to-merge';
+import { match } from 'ts-pattern';
+
+/** Where a pull request stands on its way to merging. */
+export type ReviewsBoardStage =
+ | 'draft'
+ | 'review'
+ | 'failing'
+ | 'conflicts'
+ | 'ready'
+ | 'merged';
+
+/** Whether GitHub can merge a pull request's head into its base. */
+export type PullRequestMergeability = 'mergeable' | 'conflicting' | 'unknown';
+
+export const REVIEWS_BOARD_STAGES: readonly {
+ id: ReviewsBoardStage;
+ label: string;
+ description: string;
+}[] = [
+ {
+ id: 'draft',
+ label: 'Draft',
+ description: 'Drop a pull request here to convert it to a draft',
+ },
+ {
+ id: 'review',
+ label: 'In review',
+ description: 'Open, with checks running or none reported yet',
+ },
+ {
+ id: 'failing',
+ label: 'Checks failing',
+ description: 'A check failed on the latest commit',
+ },
+ {
+ id: 'conflicts',
+ label: 'Conflicts',
+ description: 'The branch conflicts with its base',
+ },
+ {
+ id: 'ready',
+ label: 'Ready to merge',
+ description: 'Every check passed',
+ },
+ {
+ id: 'merged',
+ label: 'Merged',
+ description: 'Drop a pull request here to merge it',
+ },
+];
+
+/** Finished conclusions that fail the head commit. */
+const FAILING_CONCLUSIONS = new Set([
+ 'failure',
+ 'timed_out',
+ 'cancelled',
+ 'action_required',
+ 'startup_failure',
+]);
+
+/**
+ * The column a pull request belongs in. A draft stays a draft whatever its
+ * checks say; otherwise conflicts outrank failing checks, which outrank a
+ * clean run. Closed pull requests have no column.
+ */
+export function reviewsBoardStage(input: {
+ status: string | null | undefined;
+ draft?: boolean | null;
+ checks?: readonly PullRequestCheck[] | null;
+ mergeability?: PullRequestMergeability;
+}): ReviewsBoardStage | undefined {
+ if (input.status === 'merged') return 'merged';
+ if (input.status !== 'open') return undefined;
+ if (input.draft) return 'draft';
+ if (input.mergeability === 'conflicting') return 'conflicts';
+ const failing = (input.checks ?? []).some(
+ (check) =>
+ check.status === 'completed' &&
+ check.conclusion != null &&
+ FAILING_CONCLUSIONS.has(check.conclusion)
+ );
+ if (failing) return 'failing';
+ if (pullRequestReadyToMerge(input)) return 'ready';
+ return 'review';
+}
+
+/** What dropping a card between two columns does on GitHub. */
+export type ReviewsBoardAction = 'merge' | 'convert-to-draft' | 'mark-ready';
+
+/**
+ * The GitHub action a move asks for, or `undefined` when the move is not
+ * allowed. Checks, conflicts, and readiness are GitHub's verdicts, so only
+ * Draft, In review, and Merged accept drops; a merge comes from In review
+ * or Ready to merge, and GitHub still decides whether it goes through.
+ */
+export function reviewsBoardAction(
+ from: ReviewsBoardStage,
+ to: ReviewsBoardStage
+): ReviewsBoardAction | undefined {
+ if (from === to || from === 'merged') return undefined;
+ return match(to)
+ .with('draft', () => 'convert-to-draft' as const)
+ .with('review', () =>
+ from === 'draft' ? ('mark-ready' as const) : undefined
+ )
+ .with('merged', () =>
+ from === 'ready' || from === 'review' ? ('merge' as const) : undefined
+ )
+ .with('failing', 'conflicts', 'ready', () => undefined)
+ .exhaustive();
+}
+
+export const isReviewsBoardStage = (
+ value: string
+): value is ReviewsBoardStage =>
+ REVIEWS_BOARD_STAGES.some((stage) => stage.id === value);
diff --git a/apps/web/src/features/reviews-view/core/reviews-rows.test.ts b/apps/web/src/features/reviews-view/core/reviews-rows.test.ts
new file mode 100644
index 0000000000..69455902c7
--- /dev/null
+++ b/apps/web/src/features/reviews-view/core/reviews-rows.test.ts
@@ -0,0 +1,71 @@
+import type { GithubPullRequestEntity } from '@entity';
+import { describe, expect, it } from 'vitest';
+import { buildReviewsRows } from './reviews-rows';
+
+const now = new Date('2026-10-09T12:00:00');
+const review = (id: string, updatedAt: string, createdAt = updatedAt) =>
+ ({ id, updatedAt, createdAt }) as unknown as GithubPullRequestEntity;
+
+const labels = (rows: ReturnType<typeof buildReviewsRows>) =>
+ rows.map((row) => (row.kind === 'header' ? `# ${row.label}` : row.id));
+
+describe('buildReviewsRows', () => {
+ const reviews = [
+ review('a', '2026-10-09T09:00:00', '2026-09-01T09:00:00'),
+ review('b', '2026-10-09T08:00:00', '2026-10-08T09:00:00'),
+ review('c', '2026-10-08T08:00:00'),
+ review('d', '2026-10-05T08:00:00'),
+ ];
+
+ it('heads each date bucket of the sort timestamp like email', () => {
+ expect(
+ labels(
+ buildReviewsRows(reviews, {
+ sort: 'recently_updated',
+ grouped: true,
+ now,
+ })
+ )
+ ).toEqual(['# Today', 'a', 'b', '# Yesterday', 'c', '# Last 7 days', 'd']);
+ });
+
+ it('groups creation sorts by when pull requests were opened', () => {
+ expect(
+ labels(
+ buildReviewsRows(reviews.slice(0, 2), {
+ sort: 'newest',
+ grouped: true,
+ now,
+ })
+ )
+ ).toEqual(['# Last month', 'a', '# Yesterday', 'b']);
+ });
+
+ it('lists flat while searching or sorted by priority', () => {
+ expect(
+ labels(
+ buildReviewsRows(reviews, {
+ sort: 'recently_updated',
+ grouped: false,
+ now,
+ })
+ )
+ ).toEqual(['a', 'b', 'c', 'd']);
+ expect(
+ labels(
+ buildReviewsRows(reviews, { sort: 'priority', grouped: true, now })
+ )
+ ).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('keeps each pull request at its index among pull requests', () => {
+ const rows = buildReviewsRows(reviews, {
+ sort: 'recently_updated',
+ grouped: true,
+ now,
+ });
+ expect(
+ rows.flatMap((row) => (row.kind === 'review' ? [row.index] : []))
+ ).toEqual([0, 1, 2, 3]);
+ });
+});
diff --git a/apps/web/src/features/reviews-view/core/reviews-rows.ts b/apps/web/src/features/reviews-view/core/reviews-rows.ts
new file mode 100644
index 0000000000..166bc5f790
--- /dev/null
+++ b/apps/web/src/features/reviews-view/core/reviews-rows.ts
@@ -0,0 +1,60 @@
+import { dateBucket } from '@app/features/soup/collection/date-buckets';
+import type { GithubPullRequestEntity } from '@entity';
+import { match } from 'ts-pattern';
+import type { ReviewsSortId } from '../reviews-types';
+
+/** A Reviews list row: a date heading, or a pull request with its list index. */
+export type ReviewsRow =
+ | { kind: 'header'; id: string; label: string }
+ | {
+ kind: 'review';
+ id: string;
+ review: GithubPullRequestEntity;
+ /** Position among the pull requests, which focus and selection use. */
+ index: number;
+ };
+
+/** The timestamp a sort orders by, or `undefined` when it is not by date. */
+const sortTimestamp = (sort: ReviewsSortId) =>
+ match(sort)
+ .with(
+ 'recently_updated',
+ 'least_recently_updated',
+ () => (review: GithubPullRequestEntity) => review.updatedAt
+ )
+ .with(
+ 'newest',
+ 'oldest',
+ () => (review: GithubPullRequestEntity) => review.createdAt
+ )
+ .with('priority', () => undefined)
+ .exhaustive();
+
+/**
+ * Pull requests under the same date headings as email (Today, Yesterday,
+ * Last 7 days, …) by the date the list is sorted on. A sort that is not by
+ * date, or a search, lists them flat.
+ */
+export function buildReviewsRows(
+ reviews: readonly GithubPullRequestEntity[],
+ options: { sort: ReviewsSortId; grouped: boolean; now?: Date }
+): ReviewsRow[] {
+ const timestamp = options.grouped ? sortTimestamp(options.sort) : undefined;
+ const rows: ReviewsRow[] = [];
+ let bucket: string | undefined;
+ reviews.forEach((review, index) => {
+ if (timestamp) {
+ const next = dateBucket(timestamp(review), options.now);
+ if (next.key !== bucket) {
+ bucket = next.key;
+ rows.push({
+ kind: 'header',
+ id: `header:${next.key}:${index}`,
+ label: next.label,
+ });
+ }
+ }
+ rows.push({ kind: 'review', id: review.id, review, index });
+ });
+ return rows;
+}
diff --git a/apps/web/src/features/reviews-view/core/reviews-status.test.ts b/apps/web/src/features/reviews-view/core/reviews-status.test.ts
new file mode 100644
index 0000000000..9b3a489ba4
--- /dev/null
+++ b/apps/web/src/features/reviews-view/core/reviews-status.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import {
+ reviewsStatusTab,
+ reviewsStatusTabSelection,
+ showReviewsStatusTabs,
+} from './reviews-status';
+
+describe('reviews status toggle', () => {
+ it('highlights the preset a selection matches', () => {
+ expect(reviewsStatusTab(['open'])).toBe('open');
+ expect(reviewsStatusTab(['merged', 'closed'])).toBe('closed');
+ expect(reviewsStatusTab([])).toBe('all');
+ expect(reviewsStatusTab(['merged'])).toBeUndefined();
+ });
+
+ it('selects every status for All', () => {
+ expect(reviewsStatusTabSelection('all')).toEqual([]);
+ expect(reviewsStatusTabSelection('closed')).toEqual(['closed', 'merged']);
+ });
+
+ it('hides the toggle only for custom multi-status selections', () => {
+ expect(showReviewsStatusTabs([])).toBe(true);
+ expect(showReviewsStatusTabs(['open', 'merged'])).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/reviews-view/core/reviews-status.ts b/apps/web/src/features/reviews-view/core/reviews-status.ts
index 665a5e6db9..7c1d4780fa 100644
--- a/apps/web/src/features/reviews-view/core/reviews-status.ts
+++ b/apps/web/src/features/reviews-view/core/reviews-status.ts
@@ -7,6 +7,7 @@ import type {
export function reviewsStatusTab(
statuses: readonly string[]
): ReviewsStatusTabId | undefined {
+ if (statuses.length === 0) return 'all';
if (statuses.length === 1 && statuses[0] === 'open') return 'open';
if (
statuses.length === 2 &&
@@ -28,9 +29,10 @@ const STATUS_TAB_SELECTIONS: Record<
> = {
open: ['open'],
closed: ['closed', 'merged'],
+ all: [],
};
-/** Closed includes merged PRs; menu choices remain independently selectable. */
+/** Closed includes merged PRs, and All filters on no status; menu choices remain independently selectable. */
export const reviewsStatusTabSelection = (
tab: ReviewsStatusTabId
): ReviewsStatusFilterId[] => [...STATUS_TAB_SELECTIONS[tab]];
diff --git a/apps/web/src/features/reviews-view/queries/use-reviews-mergeability-query.ts b/apps/web/src/features/reviews-view/queries/use-reviews-mergeability-query.ts
new file mode 100644
index 0000000000..4613bbdb21
--- /dev/null
+++ b/apps/web/src/features/reviews-view/queries/use-reviews-mergeability-query.ts
@@ -0,0 +1,81 @@
+import { throwOnErr } from '@core/util/result';
+import { authServiceClient } from '@service-auth/client';
+import type { GithubPullRequestNumber } from '@service-auth/generated/schemas';
+import { useQueries } from '@tanstack/solid-query';
+import { type Accessor, createMemo } from 'solid-js';
+import type { PullRequestMergeability } from '../core/reviews-board';
+
+/** The mergeability route answers at most this many pull requests at once. */
+const MERGEABILITY_CHUNK_SIZE = 100;
+/** GitHub recomputes mergeability when either branch moves. */
+const MERGEABILITY_STALE_TIME = 60_000;
+
+const mergeabilityKey = (pullRequest: GithubPullRequestNumber) =>
+ `${pullRequest.owner}/${pullRequest.repo}#${pullRequest.number}`.toLowerCase();
+
+const reviewsMergeabilityQueryOptions = (
+ pullRequests: readonly GithubPullRequestNumber[]
+) => ({
+ queryKey: [
+ 'reviews',
+ 'mergeability',
+ pullRequests.map(mergeabilityKey),
+ ] as const,
+ queryFn: async () => {
+ const response = await throwOnErr(() =>
+ authServiceClient.getGithubPullRequestMergeability({
+ pullRequests: [...pullRequests],
+ })
+ );
+ return response.pullRequests.map(
+ (entry) =>
+ [mergeabilityKey(entry), entry.mergeability] as [
+ string,
+ PullRequestMergeability,
+ ]
+ );
+ },
+ staleTime: MERGEABILITY_STALE_TIME,
+});
+
+/**
+ * Whether GitHub can merge each open pull request, read live because
+ * conflicts appear whenever the base moves, without an event on the pull
+ * request itself. Pull requests the viewer cannot see stay unknown.
+ */
+export function useReviewsMergeabilityQuery(
+ pullRequests: Accessor<readonly GithubPullRequestNumber[]>,
+ enabled: Accessor<boolean>
+) {
+ const chunks = createMemo(() => {
+ const all = pullRequests();
+ const result: GithubPullRequestNumber[][] = [];
+ for (let index = 0; index < all.length; index += MERGEABILITY_CHUNK_SIZE)
+ result.push(
+ all
+ .slice(index, index + MERGEABILITY_CHUNK_SIZE)
+ .map(({ owner, repo, number }) => ({ owner, repo, number }))
+ );
+ return result;
+ });
+ const queries = useQueries(() => ({
+ queries: chunks().map((chunk) => ({
+ ...reviewsMergeabilityQueryOptions(chunk),
+ enabled: enabled(),
+ })),
+ }));
+ const byKey = createMemo(() => {
+ const result = new Map<string, PullRequestMergeability>();
+ for (const query of queries) {
+ if (!query.isSuccess) continue;
+ for (const [key, value] of query.data) result.set(key, value);
+ }
+ return result;
+ });
+
+ return {
+ mergeability: (pullRequest: GithubPullRequestNumber) =>
+ byKey().get(mergeabilityKey(pullRequest)),
+ isError: () => queries.some((query) => query.isError),
+ };
+}
diff --git a/apps/web/src/features/reviews-view/reviews-filter.test.ts b/apps/web/src/features/reviews-view/reviews-filter.test.ts
index 54a5f9ba26..085ca09056 100644
--- a/apps/web/src/features/reviews-view/reviews-filter.test.ts
+++ b/apps/web/src/features/reviews-view/reviews-filter.test.ts
@@ -46,6 +46,7 @@ describe('review link filters and priority sort', () => {
sessions: [],
tasks: [],
channelIds: [],
+ channelOrigins: [],
companyIds: [],
priority: { id: 'none' },
...overrides,
diff --git a/apps/web/src/features/reviews-view/reviews-types.ts b/apps/web/src/features/reviews-view/reviews-types.ts
index 4e07f3e4c3..7e2f261291 100644
--- a/apps/web/src/features/reviews-view/reviews-types.ts
+++ b/apps/web/src/features/reviews-view/reviews-types.ts
@@ -4,6 +4,8 @@ export type ReviewsScope =
| 'assigned'
| 'involving'
| 'review_requests';
+/** How the Reviews list lays out pull requests. */
+export type ReviewsLayout = 'list' | 'board';
export type ReviewsSortId =
| 'priority'
| 'recently_updated'
@@ -16,7 +18,7 @@ export type ReviewsReviewFilterId =
| 'not_reviewed_by_me'
| 'awaiting_my_review';
export type ReviewsStatusFilterId = 'open' | 'closed' | 'merged';
-export type ReviewsStatusTabId = 'open' | 'closed';
+export type ReviewsStatusTabId = 'open' | 'closed' | 'all';
export type ReviewsFilterId =
| 'status'
| 'repository'
diff --git a/apps/web/src/features/reviews-view/reviews-view.tsx b/apps/web/src/features/reviews-view/reviews-view.tsx
index 501cd84698..b7a48ce032 100644
--- a/apps/web/src/features/reviews-view/reviews-view.tsx
+++ b/apps/web/src/features/reviews-view/reviews-view.tsx
@@ -11,6 +11,7 @@ import {
useParams,
} from '@app/lib/split-router';
import { reviewsPrRoute, reviewsSplitRoute } from '@app/routes/routes';
+import { PR_ORIGIN_TOOLS } from '@block-pr/data/pr-origin';
import {
prLinksTarget,
usePrLinksQuery,
@@ -28,14 +29,20 @@ import {
} from '@entity';
import { GithubLabelPill } from '@entity/components/GithubLabelPill';
import { useGithubLinkStatusQuery } from '@queries/auth/github-link';
+import { makePersisted } from '@solid-primitives/storage';
+import { Button } from '@ui';
import {
createMemo,
createRenderEffect,
createSignal,
+ type JSX,
+ Match,
onMount,
Show,
Suspense,
+ Switch,
} from 'solid-js';
+import { ReviewsBoard } from './components/ReviewsBoard';
import {
activeReviewsFilterCount,
ReviewsControls,
@@ -51,6 +58,7 @@ import {
} from './core/reviews-status';
import { createReviewsListController } from './primitives/create-reviews-list-controller';
import { useReviewsFacetsQuery } from './queries/use-reviews-facets-query';
+import { useReviewsMergeabilityQuery } from './queries/use-reviews-mergeability-query';
import { useReviewsQuery } from './queries/use-reviews-query';
import {
applyReviewLinks,
@@ -65,6 +73,7 @@ import {
REVIEWS_SCOPES,
type ReviewsFilterId,
type ReviewsFilterSelection,
+ type ReviewsLayout,
type ReviewsScope,
type ReviewsSortId,
type ReviewsStatusTabId,
@@ -82,13 +91,44 @@ const REVIEW_SCOPE_TITLES: Record<ReviewsScope, string> = {
const REVIEW_SCOPE_TABS: PillTabItem<ReviewsScope>[] = REVIEWS_SCOPES.map(
(scope) => ({ value: scope, label: REVIEW_SCOPE_TITLES[scope] })
);
-function ReviewsListScopeHeading(props: { title: string }) {
+/** The board's status filter: open pull requests on their way, and merged ones. */
+const BOARD_STATUSES = ['open', 'merged'];
+
+/** The status toggle above the list, for touch layouts and a hidden sidebar. */
+function ReviewsHeaderStatusTabs(props: { children: JSX.Element }) {
+ const shell = useViewShell();
+ return (
+ <Show
+ when={
+ isTouchDevice() ||
+ shell.breakpoints.narrow?.() ||
+ shell.aside.isCollapsed()
+ }
+ >
+ <div class="mt-3 min-w-0 overflow-x-auto">{props.children}</div>
+ </Show>
+ );
+}
+
+/** Shown in the list header when the sidebar, with its own search, is hidden. */
+function ReviewsListScopeHeading(props: {
+ title: string;
+ search: string;
+ onSearchChange: (search: string) => void;
+}) {
const shell = useViewShell();
return (
<Show when={shell.breakpoints.narrow?.() || shell.aside.isCollapsed()}>
<div class="flex h-8 min-w-0 items-center">
<h2 class="truncate text-xl font-semibold text-ink">{props.title}</h2>
</div>
+ <SearchBar
+ label="Search reviews"
+ value={props.search}
+ onValueChange={props.onSearchChange}
+ placeholder="Search reviews"
+ class="max-w-md"
+ />
</Show>
);
}
@@ -105,6 +145,11 @@ function ReviewsRoot() {
const scope = (): ReviewsScope => tabSearch.tab;
const scopeTitle = () => REVIEW_SCOPE_TITLES[scope()];
const [search, setSearch] = createSignal('');
+ const [reviewsLayout, setReviewsLayout] = makePersisted(
+ createSignal<ReviewsLayout>('list'),
+ { name: 'reviews-layout' }
+ );
+ const boardVisible = () => reviewsLayout() === 'board' && !isTouchDevice();
const [sort, setSort] = createSignal<ReviewsSortId>('recently_updated');
const [filters, setFilters] = createSignal<ReviewsFilterSelection>(
DEFAULT_REVIEWS_FILTERS
@@ -116,8 +161,13 @@ function ReviewsRoot() {
githubLink.isPending ? undefined : githubLink.data?.username;
const authorId = () =>
githubLink.isPending ? undefined : githubLink.data?.userId;
- const activeFilters = () =>
- effectiveReviewsFilters(filters(), Boolean(authorId()));
+ const activeFilters = () => {
+ const effective = effectiveReviewsFilters(filters(), Boolean(authorId()));
+ // The board lays pull requests out by status itself.
+ return boardVisible()
+ ? { ...effective, status: BOARD_STATUSES }
+ : effective;
+ };
const listEnabled = () =>
listVisible() &&
(!scopeMatchesViewerGithubId(scope()) || Boolean(authorId()));
@@ -151,6 +201,10 @@ function ReviewsRoot() {
...current,
status: reviewsStatusTabSelection(status),
}));
+ const statusToggle = () =>
+ !boardVisible() && showReviewsStatusTabs(filters().status)
+ ? { value: statusTab(), onChange: selectStatusTab }
+ : undefined;
const clearSearch = () => setSearch('');
const searchForTab = (tab: ReviewsScope) => ({
[reviewsTabSearch.namespace]: reviewsTabSearchCodec.serialize({ tab }),
@@ -228,6 +282,37 @@ function ReviewsRoot() {
const openLink = (content: SplitContent, newSplit: boolean) =>
layout.openWithSplit(content, { preferNewSplit: newSplit });
const listController = createReviewsListController(reviews, openReview);
+ // Conflicts are read live, and only for the open pull requests on the board.
+ // Like links, they load for every fetched row so search keeps the cache.
+ const mergeability = useReviewsMergeabilityQuery(
+ () =>
+ boardVisible()
+ ? source
+ .reviews()
+ .map((review) => review.metadata)
+ .filter((pullRequest) => pullRequest.status === 'open')
+ : [],
+ boardVisible
+ );
+ const loadMore = async () => {
+ if (source.isLoadingMore() || !source.hasMore()) return;
+ try {
+ await source.loadMore();
+ } catch {
+ // The query owns the page error; the board keeps its Load more button.
+ }
+ };
+ // Tools the loaded pull requests were started from, in the filter menu's order.
+ const agents = createMemo(() => {
+ const found = new Set(
+ source.reviews().flatMap((review) => linksFor(review)?.origin?.tool ?? [])
+ );
+ return PR_ORIGIN_TOOLS.filter((tool) => found.has(tool));
+ });
+ const selectAgents = (tools: string[]) => {
+ setFilters((current) => ({ ...current, origin: tools }));
+ if (!listVisible()) openList();
+ };
const selectLabels = (labels: string[]) => {
setFilters((current) => ({ ...current, label: labels }));
if (!listVisible()) openList();
@@ -244,7 +329,11 @@ function ReviewsRoot() {
content: () => <GithubLabelPill name={label.name} color={label.color} />,
})),
hasGithubIdentity: Boolean(authorId()),
- selected: activeFilters(),
+ // The board's columns are its status, so Status neither shows nor counts.
+ hideStatus: boardVisible(),
+ selected: boardVisible()
+ ? { ...activeFilters(), status: [] }
+ : activeFilters(),
onFilterChange: changeFilter,
onClearFilters: clearFilters,
});
@@ -256,15 +345,12 @@ function ReviewsRoot() {
when={isTouchDevice()}
fallback={
<div class="flex min-w-0 flex-col gap-3">
- <ReviewsListScopeHeading title={scopeTitle()} />
- <div class="flex min-w-0 items-center justify-between gap-3">
- <SearchBar
- label="Search reviews"
- value={search()}
- onValueChange={setSearch}
- placeholder="Search reviews"
- class="max-w-md flex-1"
- />
+ <ReviewsListScopeHeading
+ title={scopeTitle()}
+ search={search()}
+ onSearchChange={setSearch}
+ />
+ <div class="flex min-w-0 items-center justify-end gap-3">
<ReviewsControls {...controls()} />
</div>
</div>
@@ -288,42 +374,97 @@ function ReviewsRoot() {
/>
</div>
</Show>
- <Show when={showReviewsStatusTabs(filters().status)}>
- <div class="mt-3 min-w-0 overflow-x-auto">
- <ReviewsStatusTabs value={statusTab()} onChange={selectStatusTab} />
- </div>
+ {/* The sidebar holds the toggle; without one it sits above the list. */}
+ <Show when={statusToggle()}>
+ {(status) => (
+ <ReviewsHeaderStatusTabs>
+ <ReviewsStatusTabs
+ value={status().value}
+ onChange={status().onChange}
+ class="h-auto max-w-sm"
+ />
+ </ReviewsHeaderStatusTabs>
+ )}
</Show>
</ViewShell.Header>
<ViewShell.Content>
- <ReviewsList
- list={listController}
- source={listSource}
- links={{
- linksFor,
- companyName: links.companyName,
- onOpen: openLink,
- }}
- scope={scope()}
- authorLogin={authorLogin()}
- authorId={authorId()}
- viewerName={viewer.userInfo()?.name ?? undefined}
- githubIdentityLoading={githubLink.isPending}
- githubAccountStatus={
- githubLink.isError
- ? 'error'
- : githubLink.isPending
- ? undefined
- : githubLink.data?.status
- }
- search={search()}
- hasFilters={
- activeReviewsFilterCount(activeFilters()) >
- (statusTab() === 'open' ? 1 : 0)
+ <Show
+ when={boardVisible()}
+ fallback={
+ <ReviewsList
+ list={listController}
+ source={listSource}
+ links={{
+ linksFor,
+ companyName: links.companyName,
+ onOpen: openLink,
+ }}
+ scope={scope()}
+ sort={sort()}
+ authorLogin={authorLogin()}
+ authorId={authorId()}
+ viewerName={viewer.userInfo()?.name ?? undefined}
+ githubIdentityLoading={githubLink.isPending}
+ githubAccountStatus={
+ githubLink.isError
+ ? 'error'
+ : githubLink.isPending
+ ? undefined
+ : githubLink.data?.status
+ }
+ search={search()}
+ hasFilters={
+ activeReviewsFilterCount(activeFilters()) >
+ (statusTab() === 'open' ? 1 : 0)
+ }
+ onClearFilters={clearFilters}
+ onClearSearch={clearSearch}
+ onOpen={openReview}
+ />
}
- onClearFilters={clearFilters}
- onClearSearch={clearSearch}
- onOpen={openReview}
- />
+ >
+ <Switch>
+ <Match when={listSource.isLoading()}>
+ <div
+ role="status"
+ class="grid size-full place-items-center text-sm text-ink-muted"
+ >
+ Loading pull requests…
+ </div>
+ </Match>
+ <Match when={listSource.error()}>
+ <div
+ role="alert"
+ class="flex size-full flex-col items-center justify-center gap-3 text-sm text-ink-muted"
+ >
+ <span>Reviews couldn’t be loaded.</span>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void listSource.retry()}
+ >
+ Try again
+ </Button>
+ </div>
+ </Match>
+ <Match when={true}>
+ <ReviewsBoard
+ reviews={reviews()}
+ mergeability={mergeability.mergeability}
+ links={{
+ linksFor,
+ companyName: links.companyName,
+ onOpen: openLink,
+ }}
+ scope={JSON.stringify([scope(), activeFilters(), search()])}
+ hasMore={source.hasMore()}
+ isLoadingMore={source.isLoadingMore()}
+ onLoadMore={() => void loadMore()}
+ onOpen={openReview}
+ />
+ </Match>
+ </Switch>
+ </Show>
</ViewShell.Content>
</>
);
@@ -363,11 +504,19 @@ function ReviewsRoot() {
>
<ViewShell.Aside>
<ReviewsSidebar
+ status={statusToggle()}
+ search={search()}
+ onSearchChange={setSearch}
+ layout={reviewsLayout()}
+ onLayoutChange={setReviewsLayout}
scope={scope()}
onScopeChange={selectScope}
labels={facets.labels()}
activeLabels={filters().label}
onActiveLabelsChange={selectLabels}
+ agents={agents()}
+ activeAgents={filters().origin}
+ onActiveAgentsChange={selectAgents}
onOpenReview={openReview}
activeForeignEntityId={params.foreignEntityId}
/>
diff --git a/apps/web/src/features/tasks-view/components/task-board.tsx b/apps/web/src/features/tasks-view/components/task-board.tsx
index f1f3a3453d..7a87667161 100644
--- a/apps/web/src/features/tasks-view/components/task-board.tsx
+++ b/apps/web/src/features/tasks-view/components/task-board.tsx
@@ -241,6 +241,8 @@ function Root(props: {
function Columns(props: {
children(column: Accessor<TaskBoardColumn>): JSX.Element;
endColumn?: () => JSX.Element;
+ /** The board's accessible name; boards of other items name their own. */
+ 'aria-label'?: string;
}) {
const board = useBoardContext();
let viewport: HTMLDivElement | undefined;
@@ -318,7 +320,7 @@ function Columns(props: {
viewportProps={{
tabindex: -1,
role: 'region',
- 'aria-label': 'Task board',
+ 'aria-label': props['aria-label'] ?? 'Task board',
class: 'pt-1 pb-4 outline-none',
}}
contentProps={{ style: { height: '100%' } }}
@@ -424,6 +426,8 @@ function Cards(props: {
children(task: Accessor<TaskBoardTask>): JSX.Element;
empty?: JSX.Element;
footer?: JSX.Element;
+ /** What the cards are, for each column's accessible name. */
+ itemsLabel?: string;
}) {
const board = useBoardContext();
const lane = useColumnContext();
@@ -490,7 +494,7 @@ function Cards(props: {
class="min-h-0 flex-auto"
viewportProps={{
role: 'region',
- 'aria-label': `${lane.column().label} tasks`,
+ 'aria-label': `${lane.column().label} ${props.itemsLabel ?? 'tasks'}`,
'aria-labelledby': lane.headerId,
tabindex: 0,
'data-task-board-scroll': lane.column().id,
diff --git a/apps/web/src/lib/queries/storage/pr-draft.ts b/apps/web/src/lib/queries/storage/pr-draft.ts
new file mode 100644
index 0000000000..2e423c3acb
--- /dev/null
+++ b/apps/web/src/lib/queries/storage/pr-draft.ts
@@ -0,0 +1,23 @@
+import { throwOnErr } from '@core/util/result';
+import { authServiceClient } from '@service-auth/client';
+import type { SetGithubPullRequestDraftRequest } from '@service-auth/generated/schemas';
+import { useMutation } from '@tanstack/solid-query';
+import { invalidateMergedPullRequestCaches } from './pr-merge';
+
+export type SetGithubPullRequestDraftInput = SetGithubPullRequestDraftRequest;
+
+/**
+ * Convert a GitHub pull request to a draft, or mark it ready for review, as
+ * the signed-in user. A refusal rejects with GitHub's message as the error
+ * text. The route patches the stored entity before answering, so the same
+ * caches a merge refreshes are refreshed here.
+ */
+export function useSetGithubPullRequestDraftMutation() {
+ return useMutation(() => ({
+ mutationFn: async (input: SetGithubPullRequestDraftInput) =>
+ await throwOnErr(() =>
+ authServiceClient.setGithubPullRequestDraft(input)
+ ),
+ onSuccess: () => invalidateMergedPullRequestCaches(),
+ }));
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 1dd01ed668..c760df99bc 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -186,6 +186,7 @@ export * from './promptAttachment';
export * from './promptAttachmentMimeType';
export * from './promptAttachmentSize';
export * from './pullRequestLinkedSession';
+export * from './pullRequestLinkedSessionOriginMessageId';
export * from './pullRequestLinkedSessionThreadParent';
export * from './pullRequestLinkSource';
export * from './pullRequestSessions';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkedSession.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkedSession.ts
index 7ea81eb8a8..327b409249 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkedSession.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkedSession.ts
@@ -4,7 +4,7 @@
* agent_harness_service
* OpenAPI spec version: 0.1.0
*/
-
+import type { PullRequestLinkedSessionOriginMessageId } from './pullRequestLinkedSessionOriginMessageId';
import type { PullRequestLinkedSessionThreadParent } from './pullRequestLinkedSessionThreadParent';
import type { PullRequestLinkSource } from './pullRequestLinkSource';
@@ -12,6 +12,9 @@ import type { PullRequestLinkSource } from './pullRequestLinkSource';
* A session linked to a pull request, as a viewer of that session sees it.
*/
export interface PullRequestLinkedSession {
+ /** The message that started the session, such as an @mention, when it was
+started from a thread. A mention inside a thread is that reply, not the root. */
+ originMessageId?: PullRequestLinkedSessionOriginMessageId;
/** The session id. */
sessionId: string;
/** Who associated the pull request with the session. */
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkedSessionOriginMessageId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkedSessionOriginMessageId.ts
new file mode 100644
index 0000000000..89bf8750e9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/pullRequestLinkedSessionOriginMessageId.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The message that started the session, such as an @mention, when it was
+started from a thread. A mention inside a thread is that reply, not the root.
+ */
+export type PullRequestLinkedSessionOriginMessageId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 08de27bd58..5f2bad61a0 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -3849,6 +3849,11 @@
"description": "A session linked to a pull request, as a viewer of that session sees it.",
"required": ["sessionId", "source"],
"properties": {
+ "originMessageId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The message that started the session, such as an @mention, when it was\nstarted from a thread. A mention inside a thread is that reply, not the root."
+ },
"sessionId": {
"type": "string",
"format": "uuid",
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index ca391d8452..c53ce3897c 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -29,6 +29,8 @@ import type {
EnrichGithubPullRequestsProxyRequest,
EnrichGithubPullRequestsResponse,
GithubLinkStatusResponse,
+ GithubPullRequestMergeabilityRequest,
+ GithubPullRequestMergeabilityResponse,
GmailLinkStatusResponse,
InitGithubLinkResponse,
InitGmailLinkResponse,
@@ -36,6 +38,8 @@ import type {
MergeGithubPullRequestResponse,
PatchUserTutorialRequest,
SendMobileWelcomeEmailResponse,
+ SetGithubPullRequestDraftRequest,
+ SetGithubPullRequestDraftResponse,
UserQuota,
} from './generated/schemas';
import type { AppleLoginRequest } from './generated/schemas/appleLoginRequest';
@@ -242,12 +246,15 @@ async function readErrorMessage(
}
/**
- * Keeps GitHub's own words on a declined merge. GitHub names the failing
- * check, the missing review, or the disallowed method; the status alone
- * ("409") tells the user nothing they can act on.
+ * Keeps GitHub's own words when it declines a change. GitHub names the
+ * failing check, the missing review, or the missing permission; the status
+ * alone ("409") tells the user nothing they can act on.
*/
-const githubMergeErrorResponseHandler: ErrorResponseHandler<GithubMergeErrorCode> =
- async function handleGithubMergeErrorResponse(response) {
+function githubChangeErrorResponseHandler(copy: {
+ noLink: string;
+ rejected: string;
+}): ErrorResponseHandler<GithubMergeErrorCode> {
+ return async function handleGithubChangeErrorResponse(response) {
if (response.status === 428) {
return {
code: 'REAUTHENTICATION_REQUIRED',
@@ -259,16 +266,21 @@ const githubMergeErrorResponseHandler: ErrorResponseHandler<GithubMergeErrorCode
}
const message = await readErrorMessage(response);
if (response.status === 404 && message === NO_GITHUB_LINK_MESSAGE) {
- return {
- code: 'NO_GITHUB_LINK',
- message: 'Connect GitHub in Settings to merge pull requests',
- };
+ return { code: 'NO_GITHUB_LINK', message: copy.noLink };
}
- return {
- code: 'MERGE_REJECTED',
- message: message ?? 'GitHub declined to merge the pull request',
- };
+ return { code: 'MERGE_REJECTED', message: message ?? copy.rejected };
};
+}
+
+const githubMergeErrorResponseHandler = githubChangeErrorResponseHandler({
+ noLink: 'Connect GitHub in Settings to merge pull requests',
+ rejected: 'GitHub declined to merge the pull request',
+});
+
+const githubDraftErrorResponseHandler = githubChangeErrorResponseHandler({
+ noLink: 'Connect GitHub in Settings to change pull requests',
+ rejected: 'GitHub declined to change the pull request',
+});
const githubErrorResponseHandler: ErrorResponseHandler<GithubReauthenticationErrorCode> =
async function handleGithubErrorResponse(response) {
@@ -517,6 +529,32 @@ export const authServiceClient = {
)
).map((result) => result);
},
+ async setGithubPullRequestDraft(args: SetGithubPullRequestDraftRequest) {
+ return (
+ await fetchWithAuth<
+ SetGithubPullRequestDraftResponse,
+ GithubMergeErrorCode
+ >(`${authHost}/github_pull_requests/draft`, {
+ method: 'POST',
+ body: JSON.stringify(args),
+ errorResponseHandler: githubDraftErrorResponseHandler,
+ })
+ ).map((result) => result);
+ },
+ async getGithubPullRequestMergeability(
+ args: GithubPullRequestMergeabilityRequest
+ ) {
+ return (
+ await fetchWithAuth<
+ GithubPullRequestMergeabilityResponse,
+ GithubReauthenticationErrorCode
+ >(`${authHost}/github_pull_requests/mergeability`, {
+ method: 'POST',
+ body: JSON.stringify(args),
+ errorResponseHandler: githubErrorResponseHandler,
+ })
+ ).map((result) => result);
+ },
async patchUserTutorial(args: PatchUserTutorialRequest) {
return (
await fetchWithAuth<EmptyResponse>(`${authHost}/user/tutorial`, {
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index e78b7a9fa7..c4904d662a 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -37,6 +37,8 @@ import type {
GetUserInfo,
GetUserLinkExistsParams,
GithubLinkStatusResponse,
+ GithubPullRequestMergeabilityRequest,
+ GithubPullRequestMergeabilityResponse,
GmailLinkStatusResponse,
GtmInviteLink,
GtmInviteLinkList,
@@ -79,6 +81,8 @@ import type {
SendInviteBody,
SendMobileWelcomeEmailRequest,
SendMobileWelcomeEmailResponse,
+ SetGithubPullRequestDraftRequest,
+ SetGithubPullRequestDraftResponse,
SsoLoginParams,
SsoRequiredResponse,
StripeSessionResponse,
@@ -1207,6 +1211,91 @@ export const verifyEmailLink = async (
} as verifyEmailLinkResponse;
};
+/**
+ * @summary Converts a GitHub pull request to a draft, or marks it ready for review,
+as the authenticated user with their own GitHub grant.
+ */
+export type setGithubPullRequestDraftResponse200 = {
+ data: SetGithubPullRequestDraftResponse;
+ status: 200;
+};
+
+export type setGithubPullRequestDraftResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type setGithubPullRequestDraftResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type setGithubPullRequestDraftResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type setGithubPullRequestDraftResponse422 = {
+ data: ErrorResponse;
+ status: 422;
+};
+
+export type setGithubPullRequestDraftResponse428 = {
+ data: ErrorResponse;
+ status: 428;
+};
+
+export type setGithubPullRequestDraftResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type setGithubPullRequestDraftResponseSuccess =
+ setGithubPullRequestDraftResponse200 & {
+ headers: Headers;
+ };
+export type setGithubPullRequestDraftResponseError = (
+ | setGithubPullRequestDraftResponse401
+ | setGithubPullRequestDraftResponse403
+ | setGithubPullRequestDraftResponse404
+ | setGithubPullRequestDraftResponse422
+ | setGithubPullRequestDraftResponse428
+ | setGithubPullRequestDraftResponse500
+) & {
+ headers: Headers;
+};
+
+export type setGithubPullRequestDraftResponse =
+ | setGithubPullRequestDraftResponseSuccess
+ | setGithubPullRequestDraftResponseError;
+
+export const getSetGithubPullRequestDraftUrl = () => {
+ return `/github_pull_requests/draft`;
+};
+
+export const setGithubPullRequestDraft = async (
+ setGithubPullRequestDraftRequest: SetGithubPullRequestDraftRequest,
+ options?: RequestInit
+): Promise<setGithubPullRequestDraftResponse> => {
+ const res = await fetch(getSetGithubPullRequestDraftUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(setGithubPullRequestDraftRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: setGithubPullRequestDraftResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as setGithubPullRequestDraftResponse;
+};
+
/**
* @summary Enriches GitHub pull request references with live GitHub data for the authenticated user.
*/
@@ -1371,6 +1460,86 @@ export const mergeGithubPullRequest = async (
} as mergeGithubPullRequestResponse;
};
+/**
+ * @summary Reads whether each GitHub pull request merges cleanly into its base, as
+the authenticated user sees it. Pull requests the user cannot see are
+left out.
+ */
+export type getGithubPullRequestMergeabilityResponse200 = {
+ data: GithubPullRequestMergeabilityResponse;
+ status: 200;
+};
+
+export type getGithubPullRequestMergeabilityResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type getGithubPullRequestMergeabilityResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type getGithubPullRequestMergeabilityResponse422 = {
+ data: ErrorResponse;
+ status: 422;
+};
+
+export type getGithubPullRequestMergeabilityResponse428 = {
+ data: ErrorResponse;
+ status: 428;
+};
+
+export type getGithubPullRequestMergeabilityResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type getGithubPullRequestMergeabilityResponseSuccess =
+ getGithubPullRequestMergeabilityResponse200 & {
+ headers: Headers;
+ };
+export type getGithubPullRequestMergeabilityResponseError = (
+ | getGithubPullRequestMergeabilityResponse401
+ | getGithubPullRequestMergeabilityResponse404
+ | getGithubPullRequestMergeabilityResponse422
+ | getGithubPullRequestMergeabilityResponse428
+ | getGithubPullRequestMergeabilityResponse500
+) & {
+ headers: Headers;
+};
+
+export type getGithubPullRequestMergeabilityResponse =
+ | getGithubPullRequestMergeabilityResponseSuccess
+ | getGithubPullRequestMergeabilityResponseError;
+
+export const getGetGithubPullRequestMergeabilityUrl = () => {
+ return `/github_pull_requests/mergeability`;
+};
+
+export const getGithubPullRequestMergeability = async (
+ githubPullRequestMergeabilityRequest: GithubPullRequestMergeabilityRequest,
+ options?: RequestInit
+): Promise<getGithubPullRequestMergeabilityResponse> => {
+ const res = await fetch(getGetGithubPullRequestMergeabilityUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(githubPullRequestMergeabilityRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getGithubPullRequestMergeabilityResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getGithubPullRequestMergeabilityResponse;
+};
+
/**
* @summary Lists invite links, newest first. Macro staff only.
*/
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeability.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeability.ts
new file mode 100644
index 0000000000..3fc9f45445
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeability.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether GitHub can merge a pull request's head into its base without conflicts.
+ */
+export type GithubPullRequestMergeability =
+ (typeof GithubPullRequestMergeability)[keyof typeof GithubPullRequestMergeability];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const GithubPullRequestMergeability = {
+ mergeable: 'mergeable',
+ conflicting: 'conflicting',
+ unknown: 'unknown',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityEntry.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityEntry.ts
new file mode 100644
index 0000000000..cf0aee368b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityEntry.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestMergeability } from './githubPullRequestMergeability';
+
+/**
+ * One pull request's mergeability.
+ */
+export interface GithubPullRequestMergeabilityEntry {
+ /** Whether the head merges cleanly into the base. */
+ mergeability: GithubPullRequestMergeability;
+ /**
+ * The GitHub pull request number.
+ * @minimum 0
+ */
+ number: number;
+ /** The GitHub repository owner or organization. */
+ owner: string;
+ /** The GitHub repository name. */
+ repo: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityRequest.ts
new file mode 100644
index 0000000000..19fdd794b6
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityRequest.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestNumber } from './githubPullRequestNumber';
+
+/**
+ * Request body for the mergeability of several pull requests.
+ */
+export interface GithubPullRequestMergeabilityRequest {
+ /** The pull requests to check, at most [`GithubPullRequestMergeabilityRequest::MAX`]. */
+ pullRequests: GithubPullRequestNumber[];
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityResponse.ts
new file mode 100644
index 0000000000..917f36e1bc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestMergeabilityResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestMergeabilityEntry } from './githubPullRequestMergeabilityEntry';
+
+/**
+ * Response body for pull request mergeability. Pull requests the user
+cannot see are left out.
+ */
+export interface GithubPullRequestMergeabilityResponse {
+ /** The mergeability of each visible pull request. */
+ pullRequests: GithubPullRequestMergeabilityEntry[];
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestNumber.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestNumber.ts
new file mode 100644
index 0000000000..55fa821b72
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestNumber.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * One pull request, by repository and number.
+ */
+export interface GithubPullRequestNumber {
+ /**
+ * The GitHub pull request number.
+ * @minimum 0
+ */
+ number: number;
+ /** The GitHub repository owner or organization. */
+ owner: string;
+ /** The GitHub repository name. */
+ repo: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index e94a40a2a2..d8363937a7 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -100,6 +100,11 @@ export * from './githubPullRequestCommentUpdatedAt';
export * from './githubPullRequestCommentUrl';
export * from './githubPullRequestLabel';
export * from './githubPullRequestLabelColor';
+export * from './githubPullRequestMergeability';
+export * from './githubPullRequestMergeabilityEntry';
+export * from './githubPullRequestMergeabilityRequest';
+export * from './githubPullRequestMergeabilityResponse';
+export * from './githubPullRequestNumber';
export * from './githubPullRequestRef';
export * from './githubPullRequestReview';
export * from './githubPullRequestReviewReviewerLogin';
@@ -180,6 +185,9 @@ export * from './seatPlan';
export * from './sendInviteBody';
export * from './sendMobileWelcomeEmailRequest';
export * from './sendMobileWelcomeEmailResponse';
+export * from './setGithubPullRequestDraftRequest';
+export * from './setGithubPullRequestDraftResponse';
+export * from './setGithubPullRequestDraftResponsePullRequest';
export * from './ssoLoginParams';
export * from './ssoRequiredResponse';
export * from './stripeSessionResponse';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftRequest.ts
new file mode 100644
index 0000000000..fbca2db4b3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftRequest.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A request to mark one pull request as a draft, or as ready for review, on
+the user's behalf.
+ */
+export interface SetGithubPullRequestDraftRequest {
+ /** `true` converts the pull request to a draft; `false` marks it ready for review. */
+ draft: boolean;
+ /**
+ * The GitHub pull request number.
+ * @minimum 0
+ */
+ number: number;
+ /** The GitHub repository owner or organization. */
+ owner: string;
+ /** The GitHub repository name. */
+ repo: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftResponse.ts
new file mode 100644
index 0000000000..743484049c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SetGithubPullRequestDraftResponsePullRequest } from './setGithubPullRequestDraftResponsePullRequest';
+
+/**
+ * Response body for a pull request whose draft state changed.
+ */
+export interface SetGithubPullRequestDraftResponse {
+ /** Whether the pull request is now a draft. */
+ draft: boolean;
+ pullRequest?: SetGithubPullRequestDraftResponsePullRequest;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftResponsePullRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftResponsePullRequest.ts
new file mode 100644
index 0000000000..e288e567f0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestDraftResponsePullRequest.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EnrichedGithubPullRequest } from './enrichedGithubPullRequest';
+
+export type SetGithubPullRequestDraftResponsePullRequest =
+ null | EnrichedGithubPullRequest;
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 2ea9d10496..779b244b66 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -845,6 +845,95 @@
}
}
},
+ "/github_pull_requests/draft": {
+ "post": {
+ "tags": ["github_pull_requests"],
+ "summary": "Converts a GitHub pull request to a draft, or marks it ready for review,\nas the authenticated user with their own GitHub grant.",
+ "operationId": "set_github_pull_request_draft",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetGithubPullRequestDraftRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetGithubPullRequestDraftResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "The user cannot change the pull request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No GitHub link, or the pull request is not visible to the user",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "GitHub declined the change",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/github_pull_requests/enrich": {
"post": {
"tags": ["github_pull_requests"],
@@ -1013,6 +1102,85 @@
}
}
},
+ "/github_pull_requests/mergeability": {
+ "post": {
+ "tags": ["github_pull_requests"],
+ "summary": "Reads whether each GitHub pull request merges cleanly into its base, as\nthe authenticated user sees it. Pull requests the user cannot see are\nleft out.",
+ "operationId": "get_github_pull_request_mergeability",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeabilityRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeabilityResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No GitHub link",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Too many pull requests requested",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/gtm-invite/links": {
"get": {
"tags": ["gtm_invite"],
@@ -5831,6 +5999,85 @@
}
}
},
+ "GithubPullRequestMergeability": {
+ "type": "string",
+ "description": "Whether GitHub can merge a pull request's head into its base without conflicts.",
+ "enum": ["mergeable", "conflicting", "unknown"]
+ },
+ "GithubPullRequestMergeabilityEntry": {
+ "type": "object",
+ "description": "One pull request's mergeability.",
+ "required": ["owner", "repo", "number", "mergeability"],
+ "properties": {
+ "mergeability": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeability",
+ "description": "Whether the head merges cleanly into the base."
+ },
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
+ "GithubPullRequestMergeabilityRequest": {
+ "type": "object",
+ "description": "Request body for the mergeability of several pull requests.",
+ "required": ["pullRequests"],
+ "properties": {
+ "pullRequests": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestNumber"
+ },
+ "description": "The pull requests to check, at most [`GithubPullRequestMergeabilityRequest::MAX`]."
+ }
+ }
+ },
+ "GithubPullRequestMergeabilityResponse": {
+ "type": "object",
+ "description": "Response body for pull request mergeability. Pull requests the user\ncannot see are left out.",
+ "required": ["pullRequests"],
+ "properties": {
+ "pullRequests": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeabilityEntry"
+ },
+ "description": "The mergeability of each visible pull request."
+ }
+ }
+ },
+ "GithubPullRequestNumber": {
+ "type": "object",
+ "description": "One pull request, by repository and number.",
+ "required": ["owner", "repo", "number"],
+ "properties": {
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
"GithubPullRequestRef": {
"type": "object",
"description": "A pull request reference that can be enriched with live GitHub data.",
@@ -6691,6 +6938,53 @@
}
}
},
+ "SetGithubPullRequestDraftRequest": {
+ "type": "object",
+ "description": "A request to mark one pull request as a draft, or as ready for review, on\nthe user's behalf.",
+ "required": ["owner", "repo", "number", "draft"],
+ "properties": {
+ "draft": {
+ "type": "boolean",
+ "description": "`true` converts the pull request to a draft; `false` marks it ready for review."
+ },
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
+ "SetGithubPullRequestDraftResponse": {
+ "type": "object",
+ "description": "Response body for a pull request whose draft state changed.",
+ "required": ["draft"],
+ "properties": {
+ "draft": {
+ "type": "boolean",
+ "description": "Whether the pull request is now a draft."
+ },
+ "pullRequest": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EnrichedGithubPullRequest",
+ "description": "The pull request as GitHub reports it after the change, when the\nrefresh succeeded."
+ }
+ ]
+ }
+ }
+ },
"SsoRequiredResponse": {
"type": "object",
"required": ["idp_id"],
diff --git a/crates/agent_session/src/domain/pull_request_links.rs b/crates/agent_session/src/domain/pull_request_links.rs
index 42e0073f18..6089777400 100644
--- a/crates/agent_session/src/domain/pull_request_links.rs
+++ b/crates/agent_session/src/domain/pull_request_links.rs
@@ -63,6 +63,8 @@ pub struct PullRequestSessionLinkRow {
pub source: PullRequestLinkSource,
/// The entity whose thread the session was started from, if any.
pub thread_parent: Option<MessageParent>,
+ /// The message that started the session, if it was started from a thread.
+ pub origin_message_id: Option<Uuid>,
}
/// A session linked to a pull request, as a viewer of that session sees it.
@@ -77,6 +79,10 @@ pub struct PullRequestLinkedSession {
pub source: PullRequestLinkSource,
/// The channel, task, or CRM record whose thread the session was started from, if any.
pub thread_parent: Option<MessageParent>,
+ /// The message that started the session, such as an @mention, when it was
+ /// started from a thread. A mention inside a thread is that reply, not the root.
+ #[cfg_attr(feature = "schema", schema(value_type = Option<Uuid>))]
+ pub origin_message_id: Option<Uuid>,
}
/// The sessions linked to one pull request that the caller can view.
@@ -296,6 +302,7 @@ impl<R: SessionPullRequestLinkRepo> SessionPullRequestLinks for SessionPullReque
session_id: row.session.as_uuid(),
source: row.source,
thread_parent: row.thread_parent,
+ origin_message_id: row.origin_message_id,
});
}
for pull_request in &mut requested {
diff --git a/crates/agent_session/src/domain/pull_request_links/test.rs b/crates/agent_session/src/domain/pull_request_links/test.rs
index d5ee99498b..23c27ed334 100644
--- a/crates/agent_session/src/domain/pull_request_links/test.rs
+++ b/crates/agent_session/src/domain/pull_request_links/test.rs
@@ -112,6 +112,7 @@ impl SessionPullRequestLinkRepo for Arc<StubLinks> {
session: *session,
source: *source,
thread_parent: Some(MessageParent::Channel(session.as_uuid())),
+ origin_message_id: Some(session.as_uuid()),
})
.collect())
}
@@ -351,6 +352,10 @@ async fn sessions_for_pull_requests_answers_each_requested_pull_request_in_order
pull_requests[0].sessions[0].thread_parent,
Some(MessageParent::Channel(visible.as_uuid()))
);
+ assert_eq!(
+ pull_requests[0].sessions[0].origin_message_id,
+ Some(visible.as_uuid())
+ );
}
#[tokio::test]
diff --git a/crates/agent_session/src/outbound/postgres/pull_request.rs b/crates/agent_session/src/outbound/postgres/pull_request.rs
index d5c1148640..1251671372 100644
--- a/crates/agent_session/src/outbound/postgres/pull_request.rs
+++ b/crates/agent_session/src/outbound/postgres/pull_request.rs
@@ -173,7 +173,9 @@ impl<B: BotFacts + 'static> crate::domain::pull_request_links::SessionPullReques
link.source,
(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)
FROM comms_messages WHERE id = session.thread_id)
- AS "thread_parent?: Json<MessageParent>"
+ AS "thread_parent?: Json<MessageParent>",
+ COALESCE(session.originating_message_id, session.thread_id)
+ AS "origin_message_id?: Uuid"
FROM agent_session_pull_request AS link
JOIN agent_session AS session ON session.id = link.agent_session_id
WHERE lower(link.github_key) = ANY($1)
@@ -196,6 +198,7 @@ impl<B: BotFacts + 'static> crate::domain::pull_request_links::SessionPullReques
PullRequestLinkSource::User
},
thread_parent: row.thread_parent.map(|parent| parent.0),
+ origin_message_id: row.origin_message_id,
})
.collect())
}
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 5131670216..47769c68f0 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -2470,6 +2470,7 @@ async fn links_for_pull_requests_returns_every_link_to_the_requested_keys(pool:
]
);
assert!(rows.iter().all(|row| row.thread_parent.is_none()));
+ assert!(rows.iter().all(|row| row.origin_message_id.is_none()));
assert!(repo.links_for_pull_requests(&[]).await.unwrap().is_empty());
}
diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rs
index 8978228f96..74f627e5c5 100644
--- a/crates/github/src/domain/models.rs
+++ b/crates/github/src/domain/models.rs
@@ -16,13 +16,16 @@ pub use app_jwt::AppJwt;
pub(crate) use app_jwt::app_jwt;
pub use github_pull_requests::domain::models::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
- EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GitRef, GithubKey,
- GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection, GithubPullRequestCheckRun,
- GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestLabel,
- GithubPullRequestMerge, GithubPullRequestRef, GithubPullRequestReview,
- GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser,
- GithubRepositoryMergeSettings, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
- latest_reviews,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GitRef,
+ GithubDraftOutcome, GithubKey, GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,
+ GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestDetails,
+ GithubPullRequestLabel, GithubPullRequestMerge, GithubPullRequestMergeability,
+ GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest,
+ GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef,
+ GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus,
+ GithubPullRequestUpdateRejection, GithubPullRequestUser, GithubRepositoryMergeSettings,
+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, latest_reviews,
};
pub use installation_state::{
InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,
@@ -91,4 +94,16 @@ pub enum GithubError {
/// GitHub's message for the user.
message: String,
},
+ /// GitHub declined to change the pull request. The message is GitHub's
+ /// own and is written for the person who asked, so it is safe to show.
+ #[error("GitHub declined to change the pull request: {message}")]
+ PullRequestUpdateRejected {
+ /// Why GitHub declined.
+ rejection: GithubPullRequestUpdateRejection,
+ /// GitHub's message for the user.
+ message: String,
+ },
+ /// The request asked for more pull requests than one call may cover.
+ #[error("too many pull requests requested")]
+ TooManyPullRequests,
}
diff --git a/crates/github/src/domain/ports/link.rs b/crates/github/src/domain/ports/link.rs
index c33e118a22..5b06147947 100644
--- a/crates/github/src/domain/ports/link.rs
+++ b/crates/github/src/domain/ports/link.rs
@@ -3,10 +3,12 @@
use std::future::Future;
use crate::domain::models::{
- EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubExchangeTokenResponse,
- GithubLink, GithubMergeMethod, GithubMergeOutcome, GithubPullRequestDetails,
+ EnrichedGithubPullRequest, GithubAccessToken, GithubDraftOutcome, GithubError,
+ GithubExchangeTokenResponse, GithubLink, GithubMergeMethod, GithubMergeOutcome,
+ GithubPullRequestDetails, GithubPullRequestMergeabilityEntry, GithubPullRequestNumber,
GithubPullRequestRef, GithubRepositoryMergeSettings, GithubUserInfo,
MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
@@ -129,6 +131,26 @@ pub trait GithubOauth: Send + Sync + 'static {
number: u64,
merge_method: GithubMergeMethod,
) -> impl Future<Output = Result<GithubMergeOutcome, Self::Err>> + Send;
+
+ /// Converts a pull request to a draft, or marks it ready for review, as
+ /// the user. A change GitHub declines is a [`GithubDraftOutcome::Rejected`]
+ /// value, not an error.
+ fn set_pull_request_draft(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+ draft: bool,
+ ) -> impl Future<Output = Result<GithubDraftOutcome, Self::Err>> + Send;
+
+ /// Reads whether each pull request merges cleanly, as the user sees it.
+ /// Pull requests the user cannot see are left out.
+ fn get_pull_request_mergeability(
+ &self,
+ access_token: &str,
+ pull_requests: &[GithubPullRequestNumber],
+ ) -> impl Future<Output = Result<Vec<GithubPullRequestMergeabilityEntry>, Self::Err>> + Send;
}
/// Repository for handling auth related actions.
@@ -217,4 +239,25 @@ pub trait GithubLinkService: Send + Sync + 'static {
user_id: &MacroUserId<Lowercase<'static>>,
request: MergeGithubPullRequestRequest,
) -> impl Future<Output = Result<MergeGithubPullRequestResponse, GithubError>> + Send;
+
+ /// Converts a pull request to a draft, or marks it ready for review, as
+ /// the user with their own GitHub grant.
+ ///
+ /// A change GitHub declines is
+ /// [`GithubError::PullRequestUpdateRejected`] with GitHub's message.
+ fn set_pull_request_draft(
+ &self,
+ user_id: &MacroUserId<Lowercase<'static>>,
+ request: SetGithubPullRequestDraftRequest,
+ ) -> impl Future<Output = Result<SetGithubPullRequestDraftResponse, GithubError>> + Send;
+
+ /// Reads whether each pull request merges cleanly into its base, as the
+ /// user sees it. More than
+ /// [`GithubPullRequestMergeabilityRequest::MAX`](crate::domain::models::GithubPullRequestMergeabilityRequest::MAX)
+ /// pull requests is [`GithubError::TooManyPullRequests`].
+ fn get_pull_request_mergeability(
+ &self,
+ user_id: &MacroUserId<Lowercase<'static>>,
+ pull_requests: Vec<GithubPullRequestNumber>,
+ ) -> impl Future<Output = Result<Vec<GithubPullRequestMergeabilityEntry>, GithubError>> + Send;
}
diff --git a/crates/github/src/domain/service/link.rs b/crates/github/src/domain/service/link.rs
index 55b08ab07e..d2ea0626ac 100644
--- a/crates/github/src/domain/service/link.rs
+++ b/crates/github/src/domain/service/link.rs
@@ -9,9 +9,12 @@ use macro_user_id::{
use crate::domain::{
models::{
- EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubLink, GithubMergeMethod,
- GithubMergeOutcome, GithubMergeRejection, GithubPullRequestRef,
- MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ EnrichedGithubPullRequest, GithubAccessToken, GithubDraftOutcome, GithubError, GithubLink,
+ GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,
+ GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest,
+ GithubPullRequestNumber, GithubPullRequestRef, MergeGithubPullRequestRequest,
+ MergeGithubPullRequestResponse, SetGithubPullRequestDraftRequest,
+ SetGithubPullRequestDraftResponse,
},
ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
};
@@ -144,10 +147,10 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService>
}
}
- /// The pull request as GitHub reports it after a merge, written back to
- /// its foreign entities so the app shows it merged before the webhook
- /// arrives. Best-effort: the merge already happened.
- async fn refresh_merged_pull_request(
+ /// The pull request as GitHub reports it after a merge or draft change,
+ /// written back to its foreign entities so the app shows the change
+ /// before the webhook arrives. Best-effort: the change already happened.
+ async fn refresh_changed_pull_request(
&self,
access_token: &GithubAccessToken,
reference: GithubPullRequestRef,
@@ -167,7 +170,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService>
owner=%reference.owner,
repo=%reference.repo,
number=reference.number,
- "failed to refresh GitHub pull request after merge"
+ "failed to refresh GitHub pull request after a change"
);
})
.ok()?;
@@ -302,7 +305,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
};
let pull_request = self
- .refresh_merged_pull_request(&access_token, request.to_reference())
+ .refresh_changed_pull_request(&access_token, request.to_reference())
.await;
Ok(MergeGithubPullRequestResponse {
@@ -312,6 +315,64 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
})
}
+ #[tracing::instrument(skip(self), err)]
+ async fn set_pull_request_draft(
+ &self,
+ macro_user_id: &MacroUserId<Lowercase<'static>>,
+ request: SetGithubPullRequestDraftRequest,
+ ) -> Result<SetGithubPullRequestDraftResponse, GithubError> {
+ let access_token = self.validated_access_token(macro_user_id).await?;
+
+ let outcome = self
+ .oauth
+ .set_pull_request_draft(
+ access_token.as_str(),
+ &request.owner,
+ &request.repo,
+ request.number,
+ request.draft,
+ )
+ .await
+ .map_err(|error| GithubError::Internal(error.into()))?;
+
+ let draft = match outcome {
+ GithubDraftOutcome::Changed { draft } => draft,
+ GithubDraftOutcome::Rejected { rejection, message } => {
+ return Err(GithubError::PullRequestUpdateRejected { rejection, message });
+ }
+ };
+
+ let pull_request = self
+ .refresh_changed_pull_request(&access_token, request.to_reference())
+ .await;
+
+ Ok(SetGithubPullRequestDraftResponse {
+ draft,
+ pull_request,
+ })
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_pull_request_mergeability(
+ &self,
+ macro_user_id: &MacroUserId<Lowercase<'static>>,
+ pull_requests: Vec<GithubPullRequestNumber>,
+ ) -> Result<Vec<GithubPullRequestMergeabilityEntry>, GithubError> {
+ if pull_requests.len() > GithubPullRequestMergeabilityRequest::MAX {
+ return Err(GithubError::TooManyPullRequests);
+ }
+ if pull_requests.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let access_token = self.validated_access_token(macro_user_id).await?;
+
+ self.oauth
+ .get_pull_request_mergeability(access_token.as_str(), &pull_requests)
+ .await
+ .map_err(|error| GithubError::Internal(error.into()))
+ }
+
#[tracing::instrument(skip(self), err)]
async fn delete_user_link(
&self,
diff --git a/crates/github/src/domain/service/link_test.rs b/crates/github/src/domain/service/link_test.rs
index 833fc1d86e..f6f8d6a6c7 100644
--- a/crates/github/src/domain/service/link_test.rs
+++ b/crates/github/src/domain/service/link_test.rs
@@ -22,10 +22,12 @@ use macro_user_id::{
use crate::domain::{
models::{
EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubAccessToken,
- GithubError, GithubExchangeTokenResponse, GithubLink, GithubMergeMethod,
- GithubMergeOutcome, GithubMergeRejection, GithubPullRequestDetails, GithubPullRequestMerge,
- GithubPullRequestRef, GithubRepositoryMergeSettings, GithubUserInfo,
- MergeGithubPullRequestRequest,
+ GithubDraftOutcome, GithubError, GithubExchangeTokenResponse, GithubLink,
+ GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection, GithubPullRequestDetails,
+ GithubPullRequestMerge, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry,
+ GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestUpdateRejection,
+ GithubRepositoryMergeSettings, GithubUserInfo, MergeGithubPullRequestRequest,
+ SetGithubPullRequestDraftRequest,
},
ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
};
@@ -185,6 +187,9 @@ struct StubGithubOauthState {
merge_settings_calls: u32,
merge_outcome: Option<GithubMergeOutcome>,
merge_calls: Vec<MergeCall>,
+ draft_outcome: Option<GithubDraftOutcome>,
+ draft_calls: Vec<(String, u64, bool)>,
+ mergeability_calls: Vec<Vec<GithubPullRequestNumber>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -253,6 +258,19 @@ impl StubGithubOauth {
fn merge_calls(&self) -> Vec<MergeCall> {
self.state.lock().unwrap().merge_calls.clone()
}
+
+ fn with_draft_outcome(self, outcome: GithubDraftOutcome) -> Self {
+ self.state.lock().unwrap().draft_outcome = Some(outcome);
+ self
+ }
+
+ fn draft_calls(&self) -> Vec<(String, u64, bool)> {
+ self.state.lock().unwrap().draft_calls.clone()
+ }
+
+ fn mergeability_calls(&self) -> Vec<Vec<GithubPullRequestNumber>> {
+ self.state.lock().unwrap().mergeability_calls.clone()
+ }
}
fn merged_outcome() -> GithubMergeOutcome {
@@ -406,6 +424,42 @@ impl GithubOauth for StubGithubOauth {
.clone()
.ok_or_else(|| anyhow::anyhow!("GitHub unreachable"))
}
+
+ async fn set_pull_request_draft(
+ &self,
+ _access_token: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+ draft: bool,
+ ) -> Result<GithubDraftOutcome, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state
+ .draft_calls
+ .push((format!("{owner}/{repo}"), number, draft));
+ state
+ .draft_outcome
+ .clone()
+ .ok_or_else(|| anyhow::anyhow!("GitHub unreachable"))
+ }
+
+ async fn get_pull_request_mergeability(
+ &self,
+ _access_token: &str,
+ pull_requests: &[GithubPullRequestNumber],
+ ) -> Result<Vec<GithubPullRequestMergeabilityEntry>, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.mergeability_calls.push(pull_requests.to_vec());
+ Ok(pull_requests
+ .iter()
+ .map(|pull_request| GithubPullRequestMergeabilityEntry {
+ owner: pull_request.owner.clone(),
+ repo: pull_request.repo.clone(),
+ number: pull_request.number,
+ mergeability: GithubPullRequestMergeability::Conflicting,
+ })
+ .collect())
+ }
}
#[derive(Clone)]
@@ -1257,6 +1311,161 @@ async fn merge_pull_request_still_reports_the_merge_when_the_refresh_fails() {
assert!(foreign_entity_service.patch_calls().is_empty());
}
+fn draft_request(draft: bool) -> SetGithubPullRequestDraftRequest {
+ SetGithubPullRequestDraftRequest {
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 7,
+ draft,
+ }
+}
+
+#[tokio::test]
+async fn set_pull_request_draft_changes_state_and_refreshes() {
+ let user_id = test_user_id();
+ let oauth =
+ StubGithubOauth::new(false).with_draft_outcome(GithubDraftOutcome::Changed { draft: true });
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ let response = service
+ .set_pull_request_draft(&user_id, draft_request(true))
+ .await
+ .unwrap();
+
+ assert!(response.draft);
+ assert_eq!(
+ response
+ .pull_request
+ .map(|pull_request| pull_request.github_key),
+ Some("macro/app/pull/7".to_string())
+ );
+ assert_eq!(
+ oauth.draft_calls(),
+ vec![("macro/app".to_string(), 7, true)]
+ );
+ assert_eq!(oauth.pull_request_detail_calls().len(), 1);
+}
+
+#[tokio::test]
+async fn set_pull_request_draft_surfaces_githubs_refusal() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false).with_draft_outcome(GithubDraftOutcome::Rejected {
+ rejection: GithubPullRequestUpdateRejection::Forbidden,
+ message: "Resource not accessible by integration".to_string(),
+ });
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ let result = service
+ .set_pull_request_draft(&user_id, draft_request(false))
+ .await;
+
+ match result {
+ Err(GithubError::PullRequestUpdateRejected { rejection, message }) => {
+ assert_eq!(rejection, GithubPullRequestUpdateRejection::Forbidden);
+ assert_eq!(message, "Resource not accessible by integration");
+ }
+ other => panic!("expected an update rejection, got {other:?}"),
+ }
+ assert!(oauth.pull_request_detail_calls().is_empty());
+}
+
+#[tokio::test]
+async fn set_pull_request_draft_requires_a_valid_grant() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(true);
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("expired-token"),
+ );
+
+ let result = service
+ .set_pull_request_draft(&user_id, draft_request(true))
+ .await;
+
+ assert!(matches!(result, Err(GithubError::ReauthenticationRequired)));
+ assert!(oauth.draft_calls().is_empty());
+}
+
+fn pull_request_number(number: u64) -> GithubPullRequestNumber {
+ GithubPullRequestNumber {
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number,
+ }
+}
+
+#[tokio::test]
+async fn get_pull_request_mergeability_reads_each_pull_request() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false);
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ let entries = service
+ .get_pull_request_mergeability(
+ &user_id,
+ vec![pull_request_number(7), pull_request_number(8)],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(entries.len(), 2);
+ assert_eq!(
+ entries[1].mergeability,
+ GithubPullRequestMergeability::Conflicting
+ );
+ assert_eq!(oauth.mergeability_calls().len(), 1);
+}
+
+#[tokio::test]
+async fn get_pull_request_mergeability_skips_github_for_an_empty_request() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false);
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ let entries = service
+ .get_pull_request_mergeability(&user_id, Vec::new())
+ .await
+ .unwrap();
+
+ assert!(entries.is_empty());
+ assert!(oauth.mergeability_calls().is_empty());
+}
+
+#[tokio::test]
+async fn get_pull_request_mergeability_rejects_too_many_pull_requests() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false);
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token"),
+ );
+
+ let result = service
+ .get_pull_request_mergeability(&user_id, (0..101).map(pull_request_number).collect())
+ .await;
+
+ assert!(matches!(result, Err(GithubError::TooManyPullRequests)));
+ assert!(oauth.mergeability_calls().is_empty());
+}
+
#[tokio::test]
async fn link_user_as_sharer_reuses_owner_grant_without_calling_auth() {
let user_id = test_user_id();
diff --git a/crates/github/src/inbound.rs b/crates/github/src/inbound.rs
index a03bc8e11c..528d48b27e 100644
--- a/crates/github/src/inbound.rs
+++ b/crates/github/src/inbound.rs
@@ -50,6 +50,14 @@ impl axum::response::IntoResponse for crate::domain::models::GithubError {
rejection,
message,
} => (merge_rejection_status(rejection), message.into()),
+ crate::domain::models::GithubError::PullRequestUpdateRejected {
+ rejection,
+ message,
+ } => (update_rejection_status(rejection), message.into()),
+ crate::domain::models::GithubError::TooManyPullRequests => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "too many pull requests requested".into(),
+ ),
};
(
@@ -78,3 +86,17 @@ pub fn merge_rejection_status(
GithubMergeRejection::Invalid => StatusCode::UNPROCESSABLE_ENTITY,
}
}
+
+/// The status a declined pull request change is reported with.
+#[cfg(feature = "axum")]
+pub fn update_rejection_status(
+ rejection: crate::domain::models::GithubPullRequestUpdateRejection,
+) -> axum::http::StatusCode {
+ use crate::domain::models::GithubPullRequestUpdateRejection;
+ use axum::http::StatusCode;
+ match rejection {
+ GithubPullRequestUpdateRejection::NotFound => StatusCode::NOT_FOUND,
+ GithubPullRequestUpdateRejection::Forbidden => StatusCode::FORBIDDEN,
+ GithubPullRequestUpdateRejection::Invalid => StatusCode::UNPROCESSABLE_ENTITY,
+ }
+}
diff --git a/crates/github/src/outbound/github_oauth_client.rs b/crates/github/src/outbound/github_oauth_client.rs
index 5c872fd5c7..f46ed4a6d5 100644
--- a/crates/github/src/outbound/github_oauth_client.rs
+++ b/crates/github/src/outbound/github_oauth_client.rs
@@ -6,9 +6,10 @@ use super::pull_request_metadata::fetch_pull_request_metadata;
use crate::domain::{
models::{
- GithubExchangeTokenResponse, GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,
- GithubPullRequestDetails, GithubPullRequestMerge, GithubRepositoryMergeSettings,
- GithubUserInfo,
+ GithubDraftOutcome, GithubExchangeTokenResponse, GithubMergeMethod, GithubMergeOutcome,
+ GithubMergeRejection, GithubPullRequestDetails, GithubPullRequestMerge,
+ GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestNumber,
+ GithubPullRequestUpdateRejection, GithubRepositoryMergeSettings, GithubUserInfo,
},
ports::GithubOauth,
};
@@ -63,7 +64,135 @@ fn default_true() -> bool {
true
}
+/// A GraphQL answer: data, errors, or both when part of the query failed.
+#[derive(serde::Deserialize)]
+struct GraphqlResponse<T> {
+ data: Option<T>,
+ #[serde(default)]
+ errors: Vec<GraphqlError>,
+}
+
+#[derive(serde::Deserialize)]
+struct GraphqlError {
+ message: String,
+ #[serde(rename = "type")]
+ kind: Option<String>,
+}
+
+impl GraphqlError {
+ fn rejection(&self) -> GithubPullRequestUpdateRejection {
+ match self.kind.as_deref() {
+ Some("NOT_FOUND") => GithubPullRequestUpdateRejection::NotFound,
+ Some("FORBIDDEN") => GithubPullRequestUpdateRejection::Forbidden,
+ _ => GithubPullRequestUpdateRejection::Invalid,
+ }
+ }
+}
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DraftStateRepository {
+ pull_request: Option<DraftStatePullRequest>,
+}
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DraftStatePullRequest {
+ id: String,
+ is_draft: bool,
+}
+
+#[derive(serde::Deserialize)]
+struct DraftStateData {
+ repository: Option<DraftStateRepository>,
+}
+
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct MergeabilityRepository {
+ pull_request: Option<MergeabilityPullRequest>,
+}
+
+#[derive(serde::Deserialize)]
+struct MergeabilityPullRequest {
+ mergeable: Option<String>,
+}
+
+const DRAFT_STATE_QUERY: &str = "query($owner: String!, $repo: String!, $number: Int!) { \
+ repository(owner: $owner, name: $repo) { pullRequest(number: $number) { id isDraft } } }";
+const CONVERT_TO_DRAFT_MUTATION: &str = "mutation($id: ID!) { \
+ convertPullRequestToDraft(input: { pullRequestId: $id }) { pullRequest { isDraft } } }";
+const MARK_READY_MUTATION: &str = "mutation($id: ID!) { \
+ markPullRequestReadyForReview(input: { pullRequestId: $id }) { pullRequest { isDraft } } }";
+
+/// One aliased lookup per pull request, so a batch is a single request.
+fn mergeability_query(
+ pull_requests: &[GithubPullRequestNumber],
+) -> (String, serde_json::Map<String, serde_json::Value>) {
+ let mut parameters = Vec::with_capacity(pull_requests.len());
+ let mut fields = Vec::with_capacity(pull_requests.len());
+ let mut variables = serde_json::Map::new();
+ for (index, pull_request) in pull_requests.iter().enumerate() {
+ parameters.push(format!(
+ "$o{index}: String!, $r{index}: String!, $n{index}: Int!"
+ ));
+ fields.push(format!(
+ "p{index}: repository(owner: $o{index}, name: $r{index}) \
+ {{ pullRequest(number: $n{index}) {{ mergeable }} }}"
+ ));
+ variables.insert(format!("o{index}"), pull_request.owner.clone().into());
+ variables.insert(format!("r{index}"), pull_request.repo.clone().into());
+ variables.insert(format!("n{index}"), pull_request.number.into());
+ }
+ (
+ format!(
+ "query({}) {{ {} }}",
+ parameters.join(", "),
+ fields.join(" ")
+ ),
+ variables,
+ )
+}
+
+fn mergeability(value: Option<&str>) -> GithubPullRequestMergeability {
+ match value {
+ Some("MERGEABLE") => GithubPullRequestMergeability::Mergeable,
+ Some("CONFLICTING") => GithubPullRequestMergeability::Conflicting,
+ _ => GithubPullRequestMergeability::Unknown,
+ }
+}
+
impl GithubOauthImpl {
+ /// Runs a GraphQL request as the user. GraphQL reports refusals in the
+ /// body, so only a failed request is an error here.
+ async fn graphql<T: serde::de::DeserializeOwned>(
+ &self,
+ access_token: &str,
+ query: &str,
+ variables: serde_json::Value,
+ ) -> anyhow::Result<GraphqlResponse<T>> {
+ let response = self
+ .client
+ .post(format!("{}/graphql", self.api_base_url()))
+ .header("Authorization", format!("Bearer {access_token}"))
+ .header("User-Agent", USER_AGENT)
+ .json(&serde_json::json!({ "query": query, "variables": variables }))
+ .timeout(REQUEST_TIMEOUT)
+ .send()
+ .await?;
+
+ let status = response.status();
+ if !status.is_success() {
+ let error_body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "unknown error".to_string());
+ anyhow::bail!("GitHub GraphQL request failed (status {status}): {error_body}");
+ }
+
+ Ok(response.json().await?)
+ }
+
fn api_base_url(&self) -> &str {
#[cfg(test)]
if let Some(api_base_url) = &self.api_base_url {
@@ -379,4 +508,105 @@ impl GithubOauth for GithubOauthImpl {
Ok(GithubMergeOutcome::Rejected { rejection, message })
}
+
+ #[tracing::instrument(skip(self, access_token), err)]
+ async fn set_pull_request_draft(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+ draft: bool,
+ ) -> Result<GithubDraftOutcome, Self::Err> {
+ let state: GraphqlResponse<DraftStateData> = self
+ .graphql(
+ access_token,
+ DRAFT_STATE_QUERY,
+ serde_json::json!({ "owner": owner, "repo": repo, "number": number }),
+ )
+ .await?;
+ let pull_request = state
+ .data
+ .and_then(|data| data.repository)
+ .and_then(|repository| repository.pull_request);
+ let Some(pull_request) = pull_request else {
+ let error = state.errors.into_iter().next();
+ return Ok(GithubDraftOutcome::Rejected {
+ rejection: error
+ .as_ref()
+ .map(GraphqlError::rejection)
+ .unwrap_or(GithubPullRequestUpdateRejection::NotFound),
+ message: error
+ .map(|error| error.message)
+ .unwrap_or_else(|| "GitHub could not find the pull request.".to_string()),
+ });
+ };
+ if pull_request.is_draft == draft {
+ return Ok(GithubDraftOutcome::Changed { draft });
+ }
+
+ let mutation = if draft {
+ CONVERT_TO_DRAFT_MUTATION
+ } else {
+ MARK_READY_MUTATION
+ };
+ let changed: GraphqlResponse<serde_json::Value> = self
+ .graphql(
+ access_token,
+ mutation,
+ serde_json::json!({ "id": pull_request.id }),
+ )
+ .await?;
+ if let Some(error) = changed.errors.into_iter().next() {
+ return Ok(GithubDraftOutcome::Rejected {
+ rejection: error.rejection(),
+ message: error.message,
+ });
+ }
+
+ Ok(GithubDraftOutcome::Changed { draft })
+ }
+
+ #[tracing::instrument(skip(self, access_token, pull_requests), fields(count = pull_requests.len()), err)]
+ async fn get_pull_request_mergeability(
+ &self,
+ access_token: &str,
+ pull_requests: &[GithubPullRequestNumber],
+ ) -> Result<Vec<GithubPullRequestMergeabilityEntry>, Self::Err> {
+ if pull_requests.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let (query, variables) = mergeability_query(pull_requests);
+ // Pull requests the user cannot see come back as null with an error
+ // beside them; they are left out rather than failing the batch.
+ let response: GraphqlResponse<
+ std::collections::HashMap<String, Option<MergeabilityRepository>>,
+ > = self
+ .graphql(access_token, &query, serde_json::Value::Object(variables))
+ .await?;
+ let Some(mut data) = response.data else {
+ let message = response
+ .errors
+ .into_iter()
+ .next()
+ .map(|error| error.message)
+ .unwrap_or_else(|| "no data".to_string());
+ anyhow::bail!("failed to read pull request mergeability: {message}");
+ };
+
+ Ok(pull_requests
+ .iter()
+ .enumerate()
+ .filter_map(|(index, pull_request)| {
+ let found = data.remove(&format!("p{index}")).flatten()?.pull_request?;
+ Some(GithubPullRequestMergeabilityEntry {
+ owner: pull_request.owner.clone(),
+ repo: pull_request.repo.clone(),
+ number: pull_request.number,
+ mergeability: mergeability(found.mergeable.as_deref()),
+ })
+ })
+ .collect())
+ }
}
diff --git a/crates/github/src/outbound/github_oauth_client/test.rs b/crates/github/src/outbound/github_oauth_client/test.rs
index 37b4f9b6e0..5f52a2d060 100644
--- a/crates/github/src/outbound/github_oauth_client/test.rs
+++ b/crates/github/src/outbound/github_oauth_client/test.rs
@@ -19,21 +19,28 @@ struct MockServer {
impl MockServer {
fn start(response: MockResponse) -> Self {
+ Self::start_many(vec![response])
+ }
+
+ /// Answers one connection per response, in order.
+ fn start_many(responses: Vec<MockResponse>) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let (request_sender, requests) = mpsc::channel();
let handle = std::thread::spawn(move || {
- let (mut stream, _) = listener.accept().unwrap();
- let request = read_request(&mut stream);
- request_sender.send(request).unwrap();
- write!(
- stream,
- "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
- response.status,
- response.body.len(),
- response.body
- )
- .unwrap();
+ for response in responses {
+ let (mut stream, _) = listener.accept().unwrap();
+ let request = read_request(&mut stream);
+ request_sender.send(request).unwrap();
+ write!(
+ stream,
+ "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ response.status,
+ response.body.len(),
+ response.body
+ )
+ .unwrap();
+ }
});
Self {
@@ -44,8 +51,12 @@ impl MockServer {
}
fn finish(self) -> String {
+ self.finish_all().remove(0)
+ }
+
+ fn finish_all(self) -> Vec<String> {
self.handle.join().unwrap();
- self.requests.recv().unwrap()
+ self.requests.try_iter().collect()
}
}
@@ -242,3 +253,196 @@ async fn get_repository_merge_settings_defaults_missing_fields_to_allowed() {
assert_eq!(settings.default_method(), Some(GithubMergeMethod::Merge));
server.finish();
}
+
+fn graphql_body(request: &str) -> serde_json::Value {
+ let body = request.split("\r\n\r\n").nth(1).unwrap();
+ serde_json::from_str(body).unwrap()
+}
+
+#[tokio::test]
+async fn set_pull_request_draft_converts_an_open_pull_request() {
+ let server = MockServer::start_many(vec![
+ MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "data": { "repository": { "pullRequest": { "id": "PR_node", "isDraft": false } } }
+ })
+ .to_string(),
+ },
+ MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "data": { "convertPullRequestToDraft": { "pullRequest": { "isDraft": true } } }
+ })
+ .to_string(),
+ },
+ ]);
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let outcome = client
+ .set_pull_request_draft("token", "macro", "app", 7, true)
+ .await
+ .unwrap();
+
+ assert_eq!(outcome, GithubDraftOutcome::Changed { draft: true });
+ let requests = server.finish_all();
+ assert_eq!(requests.len(), 2);
+ assert!(requests[0].starts_with("POST /graphql HTTP/1.1"));
+ let lookup = graphql_body(&requests[0]);
+ assert_eq!(
+ lookup["variables"],
+ serde_json::json!({ "owner": "macro", "repo": "app", "number": 7 })
+ );
+ let mutation = graphql_body(&requests[1]);
+ assert!(
+ mutation["query"]
+ .as_str()
+ .unwrap()
+ .contains("convertPullRequestToDraft")
+ );
+ assert_eq!(
+ mutation["variables"],
+ serde_json::json!({ "id": "PR_node" })
+ );
+}
+
+#[tokio::test]
+async fn set_pull_request_draft_skips_the_mutation_when_already_in_state() {
+ let server = MockServer::start(MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "data": { "repository": { "pullRequest": { "id": "PR_node", "isDraft": false } } }
+ })
+ .to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let outcome = client
+ .set_pull_request_draft("token", "macro", "app", 7, false)
+ .await
+ .unwrap();
+
+ assert_eq!(outcome, GithubDraftOutcome::Changed { draft: false });
+ assert_eq!(server.finish_all().len(), 1);
+}
+
+#[tokio::test]
+async fn set_pull_request_draft_reports_graphql_refusals() {
+ let server = MockServer::start_many(vec![
+ MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "data": { "repository": { "pullRequest": { "id": "PR_node", "isDraft": true } } }
+ })
+ .to_string(),
+ },
+ MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "data": { "markPullRequestReadyForReview": null },
+ "errors": [{ "type": "FORBIDDEN", "message": "Resource not accessible" }]
+ })
+ .to_string(),
+ },
+ ]);
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let outcome = client
+ .set_pull_request_draft("token", "macro", "app", 7, false)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ outcome,
+ GithubDraftOutcome::Rejected {
+ rejection: GithubPullRequestUpdateRejection::Forbidden,
+ message: "Resource not accessible".to_string(),
+ }
+ );
+ let requests = server.finish_all();
+ assert!(
+ graphql_body(&requests[1])["query"]
+ .as_str()
+ .unwrap()
+ .contains("markPullRequestReadyForReview")
+ );
+}
+
+#[tokio::test]
+async fn set_pull_request_draft_reports_a_missing_pull_request() {
+ let server = MockServer::start(MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "data": { "repository": null },
+ "errors": [{ "type": "NOT_FOUND", "message": "Could not resolve to a Repository" }]
+ })
+ .to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+
+ let outcome = client
+ .set_pull_request_draft("token", "macro", "app", 7, true)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ outcome,
+ GithubDraftOutcome::Rejected {
+ rejection: GithubPullRequestUpdateRejection::NotFound,
+ message: "Could not resolve to a Repository".to_string(),
+ }
+ );
+ server.finish();
+}
+
+#[tokio::test]
+async fn get_pull_request_mergeability_batches_and_skips_hidden_pull_requests() {
+ let server = MockServer::start(MockResponse {
+ status: "200 OK",
+ body: serde_json::json!({
+ "data": {
+ "p0": { "pullRequest": { "mergeable": "CONFLICTING" } },
+ "p1": null,
+ "p2": { "pullRequest": { "mergeable": "UNKNOWN" } }
+ },
+ "errors": [{ "type": "NOT_FOUND", "message": "Could not resolve to a Repository" }]
+ })
+ .to_string(),
+ });
+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());
+ let number = |repo: &str, number| GithubPullRequestNumber {
+ owner: "macro".to_string(),
+ repo: repo.to_string(),
+ number,
+ };
+
+ let entries = client
+ .get_pull_request_mergeability(
+ "token",
+ &[number("app", 7), number("secret", 1), number("app", 9)],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ entries,
+ vec![
+ GithubPullRequestMergeabilityEntry {
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 7,
+ mergeability: GithubPullRequestMergeability::Conflicting,
+ },
+ GithubPullRequestMergeabilityEntry {
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 9,
+ mergeability: GithubPullRequestMergeability::Unknown,
+ },
+ ]
+ );
+ let body = graphql_body(&server.finish());
+ assert_eq!(body["variables"]["r1"], "secret");
+ assert_eq!(body["variables"]["n2"], 9);
+ assert!(body["query"].as_str().unwrap().contains("p2: repository"));
+}
diff --git a/crates/github_pull_requests/src/domain/models.rs b/crates/github_pull_requests/src/domain/models.rs
index 4655ffbe5a..0c61beb453 100644
--- a/crates/github_pull_requests/src/domain/models.rs
+++ b/crates/github_pull_requests/src/domain/models.rs
@@ -25,12 +25,16 @@ pub use index::{PullRequestIndexOutcome, PullRequestIndexRecord, PullRequestInde
pub use key::GithubKey;
pub use pull_request::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
- EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubMergeMethod,
- GithubMergeOutcome, GithubMergeRejection, GithubPullRequestCheckRun, GithubPullRequestComment,
- GithubPullRequestDetails, GithubPullRequestLabel, GithubPullRequestMerge, GithubPullRequestRef,
- GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState,
- GithubPullRequestStatus, GithubPullRequestUser, GithubRepositoryMergeSettings,
- MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, latest_reviews,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubDraftOutcome,
+ GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection, GithubPullRequestCheckRun,
+ GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestLabel,
+ GithubPullRequestMerge, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry,
+ GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse,
+ GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview,
+ GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestStatus,
+ GithubPullRequestUpdateRejection, GithubPullRequestUser, GithubRepositoryMergeSettings,
+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, latest_reviews,
};
/// A pull request's latest data, for the record stored for one source.
diff --git a/crates/github_pull_requests/src/domain/models/pull_request.rs b/crates/github_pull_requests/src/domain/models/pull_request.rs
index c172e87dba..b7346df0aa 100644
--- a/crates/github_pull_requests/src/domain/models/pull_request.rs
+++ b/crates/github_pull_requests/src/domain/models/pull_request.rs
@@ -788,17 +788,12 @@ pub struct MergeGithubPullRequestRequest {
impl MergeGithubPullRequestRequest {
/// The reference enrichment uses for this pull request.
pub fn to_reference(&self) -> GithubPullRequestRef {
- GithubPullRequestRef {
- github_key: format!("{}/{}/pull/{}", self.owner, self.repo, self.number),
+ GithubPullRequestNumber {
owner: self.owner.clone(),
repo: self.repo.clone(),
number: self.number,
- url: format!(
- "https://github.com/{}/{}/pull/{}",
- self.owner, self.repo, self.number
- ),
- display_name: format!("{}/{}#{}", self.owner, self.repo, self.number),
}
+ .to_reference()
}
}
@@ -817,6 +812,157 @@ pub struct MergeGithubPullRequestResponse {
pub pull_request: Option<EnrichedGithubPullRequest>,
}
+/// A request to mark one pull request as a draft, or as ready for review, on
+/// the user's behalf.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct SetGithubPullRequestDraftRequest {
+ /// The GitHub repository owner or organization.
+ pub owner: String,
+ /// The GitHub repository name.
+ pub repo: String,
+ /// The GitHub pull request number.
+ pub number: u64,
+ /// `true` converts the pull request to a draft; `false` marks it ready for review.
+ pub draft: bool,
+}
+
+impl SetGithubPullRequestDraftRequest {
+ /// The reference enrichment uses for this pull request.
+ pub fn to_reference(&self) -> GithubPullRequestRef {
+ GithubPullRequestNumber {
+ owner: self.owner.clone(),
+ repo: self.repo.clone(),
+ number: self.number,
+ }
+ .to_reference()
+ }
+}
+
+/// Response body for a pull request whose draft state changed.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct SetGithubPullRequestDraftResponse {
+ /// Whether the pull request is now a draft.
+ pub draft: bool,
+ /// The pull request as GitHub reports it after the change, when the
+ /// refresh succeeded.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pull_request: Option<EnrichedGithubPullRequest>,
+}
+
+/// Why GitHub declined to change a pull request.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GithubPullRequestUpdateRejection {
+ /// The user's token cannot see the pull request.
+ NotFound,
+ /// The user may not change the pull request.
+ Forbidden,
+ /// GitHub rejected the change, for example on a closed pull request.
+ Invalid,
+}
+
+/// GitHub's answer to a draft change: performed, or declined with its reason.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum GithubDraftOutcome {
+ /// The pull request's draft state is now the one asked for.
+ Changed {
+ /// Whether the pull request is now a draft.
+ draft: bool,
+ },
+ /// GitHub declined, with the message it gave for the user.
+ Rejected {
+ /// Why GitHub declined.
+ rejection: GithubPullRequestUpdateRejection,
+ /// GitHub's message, written for the person who asked.
+ message: String,
+ },
+}
+
+/// One pull request, by repository and number.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestNumber {
+ /// The GitHub repository owner or organization.
+ pub owner: String,
+ /// The GitHub repository name.
+ pub repo: String,
+ /// The GitHub pull request number.
+ pub number: u64,
+}
+
+impl GithubPullRequestNumber {
+ /// The reference enrichment uses for this pull request.
+ pub fn to_reference(&self) -> GithubPullRequestRef {
+ GithubPullRequestRef {
+ github_key: format!("{}/{}/pull/{}", self.owner, self.repo, self.number),
+ owner: self.owner.clone(),
+ repo: self.repo.clone(),
+ number: self.number,
+ url: format!(
+ "https://github.com/{}/{}/pull/{}",
+ self.owner, self.repo, self.number
+ ),
+ display_name: format!("{}/{}#{}", self.owner, self.repo, self.number),
+ }
+ }
+}
+
+/// Whether GitHub can merge a pull request's head into its base without conflicts.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum GithubPullRequestMergeability {
+ /// The head merges cleanly into the base.
+ Mergeable,
+ /// The head conflicts with the base.
+ Conflicting,
+ /// GitHub has not computed it yet, or the pull request is not open.
+ Unknown,
+}
+
+/// Request body for the mergeability of several pull requests.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestMergeabilityRequest {
+ /// The pull requests to check, at most [`GithubPullRequestMergeabilityRequest::MAX`].
+ pub pull_requests: Vec<GithubPullRequestNumber>,
+}
+
+impl GithubPullRequestMergeabilityRequest {
+ /// The most pull requests one request may check.
+ pub const MAX: usize = 100;
+}
+
+/// One pull request's mergeability.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestMergeabilityEntry {
+ /// The GitHub repository owner or organization.
+ pub owner: String,
+ /// The GitHub repository name.
+ pub repo: String,
+ /// The GitHub pull request number.
+ pub number: u64,
+ /// Whether the head merges cleanly into the base.
+ pub mergeability: GithubPullRequestMergeability,
+}
+
+/// Response body for pull request mergeability. Pull requests the user
+/// cannot see are left out.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestMergeabilityResponse {
+ /// The mergeability of each visible pull request.
+ pub pull_requests: Vec<GithubPullRequestMergeabilityEntry>,
+}
+
/// Request body for the authenticated pull request enrichment proxy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.md
index c143d96599..2ef84cdaa7 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/AGENT_GUIDE/tasks.md
@@ -208,12 +208,18 @@ review requests.
`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. Below them, the same
-sliding tabs used by Chat offer Open and Closed. Open is the default; Closed
-includes both closed and merged PRs. The filter dropdown and mobile drawer also
+The sidebar starts with a **Search reviews** field (styled like Settings' search)
+and, on pointer devices, a **Board**/**List** toggle (`aria-label="Pull request
+layout"`); List is the default and the choice is remembered. When the sidebar is
+collapsed or narrow, the search moves above the list under the scope heading.
+Filter and sort controls appear above the list. Below the layout toggle, an
+**Open** / **Closed** / **All** toggle with icons (`aria-label="Pull request
+status"`) picks the status; it moves above the list on touch devices or when the
+sidebar is hidden, and the board hides it. Open is the default; Closed includes
+both closed and merged PRs, and All shows every status. The filter dropdown and mobile drawer also
offer independent Open, Closed, and Merged selections. Custom multi-status
-selections hide the tabs, except the combined Closed preset keeps them visible.
-A partial Closed-only or Merged-only selection leaves both tabs unhighlighted.
+selections hide the toggle, except the combined Closed preset keeps it visible.
+A partial Closed-only or Merged-only selection leaves every option unhighlighted.
Status combines with other filters, counts toward filter badges, and applies
before pagination. Clearing filters resets to Open. Other filters cover
priority, linked work, started from, repository, author, assignee, label, and,
@@ -225,10 +231,15 @@ Saved review selections stay inactive, including their filter badge and empty-st
copy, while the GitHub identity is unavailable; they resume when it returns.
Sort offers Priority, Recently updated, Least recently updated, Newest, and Oldest;
Priority orders the loaded rows most urgent first and keeps recency within a
-priority. 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,
+priority. Date sorts group rows under the same headings as email (Today,
+Yesterday, Last 7 days, Earlier this month, Last month, Older) by the sorted
+date; Priority sorts and searches list rows flat. When visible PRs
+have GitHub labels, a Labels section below Favorites lists them like email's
+Tags section (a colored dot and the name); choosing a label shows only PRs with
+it, and choosing it again clears it. Above it, an **Agents** section lists the
+tools the loaded PRs were started from (Claude, Codex, Cursor, and so on, with
+their marks); choosing one shows only PRs started from it, using the same
+**Started from** filter as the filter menu. 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
@@ -245,15 +256,22 @@ The PR's status pill stays passive; status filtering lives in the Reviews list t
Each PR row shows what it links to. A priority icon before the title comes from
the most urgent open linked task (a closed task counts only when none is open),
otherwise from a GitHub priority label (`P0`–`P3`, `priority: high`, `urgent`,
-`critical`); the tooltip names its source. Pills before the author show the
-linked **Agent session**s (sessions an agent opened the PR from, or a person
-linked), **Customer**s (CRM companies in linked tasks' Companies property, or a
-company whose thread started a session), **Ticket**s (tasks the PR text, branch,
-or comments mention as `MACRO-<id>`, and tasks whose thread started a session),
-and **Channel**s (channels whose thread started a session). A pill with one item
-opens it (Shift-click for another split); with more it shows `+N` and opens a
-list. Items the viewer cannot access are omitted. Rows show a pulsing
-placeholder while links load. The first pill names where the PR was started
+`critical`); the tooltip names its source. Row pills use the email tag style
+(neutral outline; GitHub labels show a colored dot and name). After the title
+they show where the PR was started, the **channel messages** its agents were
+started from (for example an @mention), **Customer**s (CRM companies in linked
+tasks' Companies property, or a company whose thread started a session),
+**Ticket**s (tasks the PR text, branch, or comments mention as `MACRO-<id>`, and
+tasks whose thread started a session), the GitHub labels, the author, the diff
+size, comments, and the linked agent sessions chip. A channel pill names the
+channel; hovering it previews the starting message in the same card as message
+mentions, and clicking opens the channel at that message (Shift-click for
+another split). Several channel messages stack as overlapping pills that spread
+out on hover. Customer and ticket pills with one item open it; with more they
+show `+N` and open a list. Items the viewer cannot access are omitted. When the
+pills would squeeze the title, they drop their text (keeping icons, dots, and
+tooltips) and overlap; they expand again once the row is wide enough. Rows show
+a pulsing placeholder while links load. The first pill names where the PR was started
(Claude, Codex, Cursor, Devin, Copilot, Jules, or Macro), including PRs opened
outside Macro: a Macro agent session that opened the PR wins and shows the tool
its harness ran; otherwise a session link in the description (`claude.ai/code/…`,
@@ -270,6 +288,20 @@ which wait for their links before matching. The PR side panel's **Linked work**
section shows the same origin under **Started from**, plus the priority,
tickets, customers, and channels.
+**Board** lays the scope's open and merged PRs (status filter and tabs give
+way to the board) out in columns: **Draft**, **In review** (checks running or
+none), **Checks failing**, **Conflicts** (GitHub reports the branch conflicting
+with its base; read live for the open PRs on the board), **Ready to merge**
+(every check passed), and **Merged**. Cards show the status icon, priority,
+title, checks, `owner/repo#N`, author, link pills, labels, and agent sessions;
+clicking a card opens the PR. Dragging asks GitHub for the change as you: drop
+on **Merged** (from In review or Ready to merge) to merge after the same
+confirmation as the PR's Merge button; drop on **Draft** to convert any open PR
+to a draft; drop a draft on **In review** to mark it ready for review. Checks
+failing, Conflicts, and Ready to merge take no drops, and merged cards cannot be
+dragged. A refusal shows GitHub's message and the card returns. **Load more pull
+requests** fetches the next page.
+
PR rows can be added to or removed from Favorites through their context menu or
bulk entity actions. When at least one accessible PR is favorited, Reviews shows
a collapsible Favorites section below the views; the section is hidden otherwise.
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 49b2a9f832..95d49acb13 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -1202,6 +1202,11 @@ export type PullRequestLinkSource = 'agent' | 'user';
* A session linked to a pull request, as a viewer of that session sees it.
*/
export type PullRequestLinkedSession = {
+ /**
+ * The message that started the session, such as an @mention, when it was
+ * started from a thread. A mention inside a thread is that reply, not the root.
+ */
+ originMessageId?: string | null;
/**
* The session id.
*/
diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.ts
index 8199dc987b..2ebf327bd5 100644
--- a/packages/sdk/generated/auth/index.ts
+++ b/packages/sdk/generated/auth/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
+export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.ts
index cc654e985e..5a250313e5 100644
--- a/packages/sdk/generated/auth/sdk.gen.ts
+++ b/packages/sdk/generated/auth/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -272,6 +272,21 @@ export class Sdk extends HeyApiClient {
return (options.client ?? this.client).get<VerifyEmailLinkResponses, VerifyEmailLinkErrors, ThrowOnError>({ url: '/email/verify/{verification_id}', ...options });
}
+ /**
+ * Converts a GitHub pull request to a draft, or marks it ready for review,
+ * as the authenticated user with their own GitHub grant.
+ */
+ public setGithubPullRequestDraft<ThrowOnError extends boolean = false>(options: Options<SetGithubPullRequestDraftData, ThrowOnError>): RequestResult<SetGithubPullRequestDraftResponses, SetGithubPullRequestDraftErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<SetGithubPullRequestDraftResponses, SetGithubPullRequestDraftErrors, ThrowOnError>({
+ url: '/github_pull_requests/draft',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Enriches GitHub pull request references with live GitHub data for the authenticated user.
*/
@@ -302,6 +317,22 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Reads whether each GitHub pull request merges cleanly into its base, as
+ * the authenticated user sees it. Pull requests the user cannot see are
+ * left out.
+ */
+ public getGithubPullRequestMergeability<ThrowOnError extends boolean = false>(options: Options<GetGithubPullRequestMergeabilityData, ThrowOnError>): RequestResult<GetGithubPullRequestMergeabilityResponses, GetGithubPullRequestMergeabilityErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<GetGithubPullRequestMergeabilityResponses, GetGithubPullRequestMergeabilityErrors, ThrowOnError>({
+ url: '/github_pull_requests/mergeability',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Lists invite links, newest first. Macro staff only.
*/
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 5eba0e4d66..0604515cf7 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -759,6 +759,72 @@ export type GithubPullRequestLabel = {
name: string;
};
+/**
+ * Whether GitHub can merge a pull request's head into its base without conflicts.
+ */
+export type GithubPullRequestMergeability = 'mergeable' | 'conflicting' | 'unknown';
+
+/**
+ * One pull request's mergeability.
+ */
+export type GithubPullRequestMergeabilityEntry = {
+ /**
+ * Whether the head merges cleanly into the base.
+ */
+ mergeability: GithubPullRequestMergeability;
+ /**
+ * The GitHub pull request number.
+ */
+ number: number;
+ /**
+ * The GitHub repository owner or organization.
+ */
+ owner: string;
+ /**
+ * The GitHub repository name.
+ */
+ repo: string;
+};
+
+/**
+ * Request body for the mergeability of several pull requests.
+ */
+export type GithubPullRequestMergeabilityRequest = {
+ /**
+ * The pull requests to check, at most [`GithubPullRequestMergeabilityRequest::MAX`].
+ */
+ pullRequests: Array<GithubPullRequestNumber>;
+};
+
+/**
+ * Response body for pull request mergeability. Pull requests the user
+ * cannot see are left out.
+ */
+export type GithubPullRequestMergeabilityResponse = {
+ /**
+ * The mergeability of each visible pull request.
+ */
+ pullRequests: Array<GithubPullRequestMergeabilityEntry>;
+};
+
+/**
+ * One pull request, by repository and number.
+ */
+export type GithubPullRequestNumber = {
+ /**
+ * The GitHub pull request number.
+ */
+ number: number;
+ /**
+ * The GitHub repository owner or organization.
+ */
+ owner: string;
+ /**
+ * The GitHub repository name.
+ */
+ repo: string;
+};
+
/**
* A pull request reference that can be enriched with live GitHub data.
*/
@@ -1414,6 +1480,40 @@ export type SendMobileWelcomeEmailResponse = {
sent: boolean;
};
+/**
+ * A request to mark one pull request as a draft, or as ready for review, on
+ * the user's behalf.
+ */
+export type SetGithubPullRequestDraftRequest = {
+ /**
+ * `true` converts the pull request to a draft; `false` marks it ready for review.
+ */
+ draft: boolean;
+ /**
+ * The GitHub pull request number.
+ */
+ number: number;
+ /**
+ * The GitHub repository owner or organization.
+ */
+ owner: string;
+ /**
+ * The GitHub repository name.
+ */
+ repo: string;
+};
+
+/**
+ * Response body for a pull request whose draft state changed.
+ */
+export type SetGithubPullRequestDraftResponse = {
+ /**
+ * Whether the pull request is now a draft.
+ */
+ draft: boolean;
+ pullRequest?: null | EnrichedGithubPullRequest;
+};
+
export type SsoRequiredResponse = {
/**
* The idp_id you need to perform sso login with.
@@ -2242,6 +2342,39 @@ export type VerifyEmailLinkResponses = {
export type VerifyEmailLinkResponse = VerifyEmailLinkResponses[keyof VerifyEmailLinkResponses];
+export type SetGithubPullRequestDraftData = {
+ body: SetGithubPullRequestDraftRequest;
+ path?: never;
+ query?: never;
+ url: '/github_pull_requests/draft';
+};
+
+export type SetGithubPullRequestDraftErrors = {
+ 401: ErrorResponse;
+ /**
+ * The user cannot change the pull request
+ */
+ 403: ErrorResponse;
+ /**
+ * No GitHub link, or the pull request is not visible to the user
+ */
+ 404: ErrorResponse;
+ /**
+ * GitHub declined the change
+ */
+ 422: ErrorResponse;
+ 428: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type SetGithubPullRequestDraftError = SetGithubPullRequestDraftErrors[keyof SetGithubPullRequestDraftErrors];
+
+export type SetGithubPullRequestDraftResponses = {
+ 200: SetGithubPullRequestDraftResponse;
+};
+
+export type SetGithubPullRequestDraftResponse2 = SetGithubPullRequestDraftResponses[keyof SetGithubPullRequestDraftResponses];
+
export type EnrichGithubPullRequestsData = {
body: EnrichGithubPullRequestsProxyRequest;
path?: never;
@@ -2298,6 +2431,35 @@ export type MergeGithubPullRequestResponses = {
export type MergeGithubPullRequestResponse2 = MergeGithubPullRequestResponses[keyof MergeGithubPullRequestResponses];
+export type GetGithubPullRequestMergeabilityData = {
+ body: GithubPullRequestMergeabilityRequest;
+ path?: never;
+ query?: never;
+ url: '/github_pull_requests/mergeability';
+};
+
+export type GetGithubPullRequestMergeabilityErrors = {
+ 401: ErrorResponse;
+ /**
+ * No GitHub link
+ */
+ 404: ErrorResponse;
+ /**
+ * Too many pull requests requested
+ */
+ 422: ErrorResponse;
+ 428: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type GetGithubPullRequestMergeabilityError = GetGithubPullRequestMergeabilityErrors[keyof GetGithubPullRequestMergeabilityErrors];
+
+export type GetGithubPullRequestMergeabilityResponses = {
+ 200: GithubPullRequestMergeabilityResponse;
+};
+
+export type GetGithubPullRequestMergeabilityResponse = GetGithubPullRequestMergeabilityResponses[keyof GetGithubPullRequestMergeabilityResponses];
+
export type ListGtmInviteLinksData = {
body?: never;
path?: never;
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 08de27bd58..5f2bad61a0 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -3849,6 +3849,11 @@
"description": "A session linked to a pull request, as a viewer of that session sees it.",
"required": ["sessionId", "source"],
"properties": {
+ "originMessageId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The message that started the session, such as an @mention, when it was\nstarted from a thread. A mention inside a thread is that reply, not the root."
+ },
"sessionId": {
"type": "string",
"format": "uuid",
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 2ea9d10496..779b244b66 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -845,6 +845,95 @@
}
}
},
+ "/github_pull_requests/draft": {
+ "post": {
+ "tags": ["github_pull_requests"],
+ "summary": "Converts a GitHub pull request to a draft, or marks it ready for review,\nas the authenticated user with their own GitHub grant.",
+ "operationId": "set_github_pull_request_draft",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetGithubPullRequestDraftRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetGithubPullRequestDraftResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "The user cannot change the pull request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No GitHub link, or the pull request is not visible to the user",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "GitHub declined the change",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/github_pull_requests/enrich": {
"post": {
"tags": ["github_pull_requests"],
@@ -1013,6 +1102,85 @@
}
}
},
+ "/github_pull_requests/mergeability": {
+ "post": {
+ "tags": ["github_pull_requests"],
+ "summary": "Reads whether each GitHub pull request merges cleanly into its base, as\nthe authenticated user sees it. Pull requests the user cannot see are\nleft out.",
+ "operationId": "get_github_pull_request_mergeability",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeabilityRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeabilityResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No GitHub link",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Too many pull requests requested",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/gtm-invite/links": {
"get": {
"tags": ["gtm_invite"],
@@ -5831,6 +5999,85 @@
}
}
},
+ "GithubPullRequestMergeability": {
+ "type": "string",
+ "description": "Whether GitHub can merge a pull request's head into its base without conflicts.",
+ "enum": ["mergeable", "conflicting", "unknown"]
+ },
+ "GithubPullRequestMergeabilityEntry": {
+ "type": "object",
+ "description": "One pull request's mergeability.",
+ "required": ["owner", "repo", "number", "mergeability"],
+ "properties": {
+ "mergeability": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeability",
+ "description": "Whether the head merges cleanly into the base."
+ },
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
+ "GithubPullRequestMergeabilityRequest": {
+ "type": "object",
+ "description": "Request body for the mergeability of several pull requests.",
+ "required": ["pullRequests"],
+ "properties": {
+ "pullRequests": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestNumber"
+ },
+ "description": "The pull requests to check, at most [`GithubPullRequestMergeabilityRequest::MAX`]."
+ }
+ }
+ },
+ "GithubPullRequestMergeabilityResponse": {
+ "type": "object",
+ "description": "Response body for pull request mergeability. Pull requests the user\ncannot see are left out.",
+ "required": ["pullRequests"],
+ "properties": {
+ "pullRequests": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestMergeabilityEntry"
+ },
+ "description": "The mergeability of each visible pull request."
+ }
+ }
+ },
+ "GithubPullRequestNumber": {
+ "type": "object",
+ "description": "One pull request, by repository and number.",
+ "required": ["owner", "repo", "number"],
+ "properties": {
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
"GithubPullRequestRef": {
"type": "object",
"description": "A pull request reference that can be enriched with live GitHub data.",
@@ -6691,6 +6938,53 @@
}
}
},
+ "SetGithubPullRequestDraftRequest": {
+ "type": "object",
+ "description": "A request to mark one pull request as a draft, or as ready for review, on\nthe user's behalf.",
+ "required": ["owner", "repo", "number", "draft"],
+ "properties": {
+ "draft": {
+ "type": "boolean",
+ "description": "`true` converts the pull request to a draft; `false` marks it ready for review."
+ },
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ }
+ }
+ },
+ "SetGithubPullRequestDraftResponse": {
+ "type": "object",
+ "description": "Response body for a pull request whose draft state changed.",
+ "required": ["draft"],
+ "properties": {
+ "draft": {
+ "type": "boolean",
+ "description": "Whether the pull request is now a draft."
+ },
+ "pullRequest": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EnrichedGithubPullRequest",
+ "description": "The pull request as GitHub reports it after the change, when the\nrefresh succeeded."
+ }
+ ]
+ }
+ }
+ },
"SsoRequiredResponse": {
"type": "object",
"required": ["idp_id"],
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 2c717c73df..5770887f68 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -71,6 +71,7 @@ export const authExcluded = [
'getAiBillingSummary',
'getCodexConnection',
'getCursorApiKey',
+ 'getGithubPullRequestMergeability',
'getGtmInviteOffer',
'getLegacyUserPermissions',
'getPermissions',
@@ -124,6 +125,7 @@ export const authExcluded = [
'sendReferralCode',
'sessionCreation',
'sessionLogin',
+ 'setGithubPullRequestDraft',
'ssoLogin',
'startCodexLogin',
'toggleTeamAutoJoinDomain',
diff --git a/services/authentication_service/src/api/github_pull_requests.rs b/services/authentication_service/src/api/github_pull_requests.rs
index cb595b268e..1e9a717565 100644
--- a/services/authentication_service/src/api/github_pull_requests.rs
+++ b/services/authentication_service/src/api/github_pull_requests.rs
@@ -8,7 +8,9 @@ use axum::{
use github::domain::{
models::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, GithubError,
+ GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse,
MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,
},
ports::GithubLinkService,
};
@@ -89,10 +91,55 @@ impl IntoResponse for MergeGithubPullRequestError {
}
}
+#[derive(thiserror::Error, Debug)]
+pub enum UpdateGithubPullRequestError {
+ #[error(transparent)]
+ Github(#[from] GithubError),
+}
+
+impl IntoResponse for UpdateGithubPullRequestError {
+ fn into_response(self) -> Response {
+ let (status_code, message) = match self {
+ Self::Github(GithubError::NoLinkFound) => {
+ (StatusCode::NOT_FOUND, "no github link found".to_string())
+ }
+ Self::Github(GithubError::ReauthenticationRequired) => (
+ StatusCode::PRECONDITION_REQUIRED,
+ "reauthentication required".to_string(),
+ ),
+ // GitHub's own message says why the change was declined.
+ Self::Github(GithubError::PullRequestUpdateRejected { rejection, message }) => {
+ (github::inbound::update_rejection_status(rejection), message)
+ }
+ Self::Github(GithubError::TooManyPullRequests) => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "too many pull requests requested".to_string(),
+ ),
+ Self::Github(error) => {
+ tracing::error!(error=?error, "failed to update GitHub pull request");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "internal error".to_string(),
+ )
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
pub fn router() -> Router<ApiContext> {
Router::new()
.route("/enrich", post(handler))
.route("/merge", post(merge_handler))
+ .route("/draft", post(draft_handler))
+ .route("/mergeability", post(mergeability_handler))
}
/// Enriches GitHub pull request references with live GitHub data for the authenticated user.
@@ -162,3 +209,72 @@ pub async fn merge_handler(
Ok(Json(response))
}
+
+/// Converts a GitHub pull request to a draft, or marks it ready for review,
+/// as the authenticated user with their own GitHub grant.
+#[utoipa::path(
+ post,
+ path = "/github_pull_requests/draft",
+ operation_id = "set_github_pull_request_draft",
+ request_body = SetGithubPullRequestDraftRequest,
+ responses(
+ (status = 200, body = SetGithubPullRequestDraftResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, description = "The user cannot change the pull request", body = ErrorResponse),
+ (status = 404, description = "No GitHub link, or the pull request is not visible to the user", body = ErrorResponse),
+ (status = 422, description = "GitHub declined the change", body = ErrorResponse),
+ (status = 428, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, authorization, request), fields(user_id = %authorization.authorization.user.macro_user_id), err)]
+pub async fn draft_handler(
+ State(ctx): State<ApiContext>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
+ extract::Json(request): extract::Json<SetGithubPullRequestDraftRequest>,
+) -> Result<Json<SetGithubPullRequestDraftResponse>, UpdateGithubPullRequestError> {
+ tracing::info!("set_github_pull_request_draft");
+
+ let response = ctx
+ .github_link_service
+ .set_pull_request_draft(&authorization.authorization.user.macro_user_id, request)
+ .await?;
+
+ Ok(Json(response))
+}
+
+/// Reads whether each GitHub pull request merges cleanly into its base, as
+/// the authenticated user sees it. Pull requests the user cannot see are
+/// left out.
+#[utoipa::path(
+ post,
+ path = "/github_pull_requests/mergeability",
+ operation_id = "get_github_pull_request_mergeability",
+ request_body = GithubPullRequestMergeabilityRequest,
+ responses(
+ (status = 200, body = GithubPullRequestMergeabilityResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, description = "No GitHub link", body = ErrorResponse),
+ (status = 422, description = "Too many pull requests requested", body = ErrorResponse),
+ (status = 428, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, authorization, request), fields(user_id = %authorization.authorization.user.macro_user_id), err)]
+pub async fn mergeability_handler(
+ State(ctx): State<ApiContext>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
+ extract::Json(request): extract::Json<GithubPullRequestMergeabilityRequest>,
+) -> Result<Json<GithubPullRequestMergeabilityResponse>, UpdateGithubPullRequestError> {
+ let pull_requests = ctx
+ .github_link_service
+ .get_pull_request_mergeability(
+ &authorization.authorization.user.macro_user_id,
+ request.pull_requests,
+ )
+ .await?;
+
+ Ok(Json(GithubPullRequestMergeabilityResponse {
+ pull_requests,
+ }))
+}
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index 8706f14603..b594ab52da 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -1,8 +1,11 @@
use github::domain::models::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
EnrichedGithubPullRequest, GithubMergeMethod, GithubPullRequestCheckRun,
- GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus,
+ GithubPullRequestComment, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry,
+ GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse,
+ GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestStatus,
MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
+ SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,
};
use gtm_invite::inbound::axum_router::dto::{
CreateGtmInviteLinkRequest, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus,
@@ -111,6 +114,8 @@ use model::user::{
/// /github_pull_requests
github_pull_requests::handler,
github_pull_requests::merge_handler,
+ github_pull_requests::draft_handler,
+ github_pull_requests::mergeability_handler,
/// /oauth
oauth::oauth_redirect::handler,
@@ -267,6 +272,13 @@ use model::user::{
GithubMergeMethod,
MergeGithubPullRequestRequest,
MergeGithubPullRequestResponse,
+ SetGithubPullRequestDraftRequest,
+ SetGithubPullRequestDraftResponse,
+ GithubPullRequestNumber,
+ GithubPullRequestMergeability,
+ GithubPullRequestMergeabilityEntry,
+ GithubPullRequestMergeabilityRequest,
+ GithubPullRequestMergeabilityResponse,
UserQuota,
UserOrganizationResponse,
@@ -376,6 +388,31 @@ mod tests {
assert!(response_properties.get("pullRequest").is_some());
}
+ #[test]
+ fn github_pull_requests_openapi_includes_draft_and_mergeability_paths() {
+ let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();
+ let draft = &openapi["paths"]["/github_pull_requests/draft"]["post"];
+ assert_eq!(draft["operationId"], "set_github_pull_request_draft");
+ assert_eq!(
+ draft["requestBody"]["content"]["application/json"]["schema"]["$ref"].as_str(),
+ Some("#/components/schemas/SetGithubPullRequestDraftRequest")
+ );
+ let mergeability = &openapi["paths"]["/github_pull_requests/mergeability"]["post"];
+ assert_eq!(
+ mergeability["operationId"],
+ "get_github_pull_request_mergeability"
+ );
+ assert_eq!(
+ mergeability["responses"]["200"]["content"]["application/json"]["schema"]["$ref"]
+ .as_str(),
+ Some("#/components/schemas/GithubPullRequestMergeabilityResponse")
+ );
+ assert_eq!(
+ openapi["components"]["schemas"]["GithubPullRequestMergeability"]["enum"],
+ serde_json::json!(["mergeable", "conflicting", "unknown"])
+ );
+ }
+
#[test]
fn github_link_status_openapi_includes_path_and_schema() {
let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();