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(agents): suggest a repo's branches in the new-convo picker (#6646)

Wolf Mermelsteindfa5f4636238
diff --git a/apps/web/src/features/agents-view/core/repository.test.ts b/apps/web/src/features/agents-view/core/repository.test.ts
index db3cdb235d..1a180e9088 100644
--- a/apps/web/src/features/agents-view/core/repository.test.ts
+++ b/apps/web/src/features/agents-view/core/repository.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest';
import {
defaultBranchFor,
+ filterBranches,
filterRepositories,
+ orderBranches,
orderRepositories,
parseRepositoryInput,
type ReachableRepository,
@@ -117,3 +119,34 @@ describe('defaultBranchFor', () => {
expect(defaultBranchFor(all, undefined)).toBe('main');
});
});
+
+describe('orderBranches', () => {
+ it("puts the repository's default first when it is listed", () => {
+ expect(orderBranches(['feature/a', 'main', 'develop'], 'main')).toEqual([
+ 'main',
+ 'feature/a',
+ 'develop',
+ ]);
+ });
+
+ it('leaves GitHub order alone when the default is unknown or absent', () => {
+ expect(orderBranches(['feature/a', 'develop'], 'main')).toEqual([
+ 'feature/a',
+ 'develop',
+ ]);
+ expect(orderBranches(['feature/a', 'develop'])).toEqual([
+ 'feature/a',
+ 'develop',
+ ]);
+ });
+});
+
+describe('filterBranches', () => {
+ it('matches a branch name, ignoring case', () => {
+ const all = ['main', 'develop', 'feature/Home'];
+ expect(filterBranches(all, '')).toEqual(all);
+ expect(filterBranches(all, 'DEV')).toEqual(['develop']);
+ expect(filterBranches(all, 'home')).toEqual(['feature/Home']);
+ expect(filterBranches(all, 'nothing')).toEqual([]);
+ });
+});
diff --git a/apps/web/src/features/agents-view/core/repository.ts b/apps/web/src/features/agents-view/core/repository.ts
index 8dcb6ff55c..4df4eb4b56 100644
--- a/apps/web/src/features/agents-view/core/repository.ts
+++ b/apps/web/src/features/agents-view/core/repository.ts
@@ -147,3 +147,28 @@ export function defaultBranchFor(
?.defaultBranch ?? FALLBACK_BRANCH
);
}
+
+/**
+ * Branches to offer: the repository's default first when it is in the list,
+ * then the rest as GitHub returned them.
+ */
+export function orderBranches(
+ branches: readonly string[],
+ defaultBranch?: string
+): string[] {
+ if (!defaultBranch) return [...branches];
+ const rest = branches.filter((branch) => branch !== defaultBranch);
+ return branches.includes(defaultBranch)
+ ? [defaultBranch, ...rest]
+ : [...branches];
+}
+
+/** Branches whose names contain `search`, ignoring case; every branch for blank text. */
+export function filterBranches(
+ branches: readonly string[],
+ search: string
+): string[] {
+ const needle = search.trim().toLowerCase();
+ if (!needle) return [...branches];
+ return branches.filter((branch) => branch.toLowerCase().includes(needle));
+}
diff --git a/apps/web/src/features/agents-view/queries/repository-branches.ts b/apps/web/src/features/agents-view/queries/repository-branches.ts
new file mode 100644
index 0000000000..fd2556645b
--- /dev/null
+++ b/apps/web/src/features/agents-view/queries/repository-branches.ts
@@ -0,0 +1,31 @@
+import { useAgentRepositoryBranchesQuery } from '@queries/agent-repositories/branches';
+import { type Accessor, createMemo } from 'solid-js';
+
+export type RepositoryBranchesSource = {
+ /** Branch names on the selected repository, as GitHub listed them. */
+ branches: Accessor<string[]>;
+ /** The listing is on its first load. */
+ loading: Accessor<boolean>;
+ /** The listing failed; `retry` asks again. */
+ error: Accessor<boolean>;
+ retry: () => void;
+};
+
+/**
+ * The composer's view of one repository's branches. Reads are status-gated
+ * so a pending listing never suspends the composer around it.
+ */
+export function createRepositoryBranches(
+ repoUrl: Accessor<string | undefined>
+): RepositoryBranchesSource {
+ const query = useAgentRepositoryBranchesQuery(repoUrl);
+ const branches = createMemo<string[]>(() =>
+ query.isSuccess ? query.data.branches : []
+ );
+ return {
+ branches,
+ loading: () => query.isLoading,
+ error: () => query.isError,
+ retry: () => void query.refetch(),
+ };
+}
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
index 5765d7c3f3..819ac546c7 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
@@ -50,6 +50,14 @@ vi.mock('../queries/reachable-repositories', () => ({
retry: vi.fn(),
}),
}));
+vi.mock('../queries/repository-branches', () => ({
+ createRepositoryBranches: () => ({
+ branches: () => ['main', 'develop', 'feature/home'],
+ loading: () => false,
+ error: () => false,
+ retry: vi.fn(),
+ }),
+}));
vi.mock('../components/AgentGlyph', () => ({ AgentIcon: () => <span /> }));
vi.mock('@queries/agents/models', () => ({
@@ -223,10 +231,7 @@ describe('agent-led new conversation', () => {
screen.getByRole('button', { name: 'Branch' }).textContent
).toContain('develop');
fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
- fireEvent.input(screen.getByRole('textbox', { name: 'Starting branch' }), {
- target: { value: 'feature/home' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Use branch' }));
+ fireEvent.click(screen.getByRole('option', { name: 'feature/home' }));
await selectAgent(/^Chat default$/);
expect(screen.getByTestId('drawer').hasAttribute('hidden')).toBe(true);
expect(
@@ -289,16 +294,16 @@ describe('agent-led new conversation', () => {
screen.getByRole('button', { name: 'Branch' }).textContent
).toContain('develop');
fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
- fireEvent.input(screen.getByRole('textbox', { name: 'Starting branch' }), {
- target: { value: 'feature/home' },
+ fireEvent.input(screen.getByRole('combobox', { name: 'Search branches' }), {
+ target: { value: 'feature/other' },
});
- fireEvent.click(screen.getByRole('button', { name: 'Use branch' }));
+ fireEvent.click(screen.getByRole('option', { name: 'Use feature/other' }));
fireEvent.click(screen.getByRole('button', { name: 'Send' }));
expect(send).toHaveBeenLastCalledWith({
botId: CURSOR_BOT_ID,
prompt: 'Prompt',
repoUrl: 'https://github.com/macro-inc/macro',
- repoBranch: 'feature/home',
+ repoBranch: 'feature/other',
});
});
it('uses a saved agent without sending a per-session model override', async () => {
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.tsx b/apps/web/src/features/agents-view/views/NewChatPage.tsx
index 5614aeb60e..46aecd604c 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.tsx
@@ -16,6 +16,7 @@ import { defaultBranchFor } from '../core/repository';
import { MACRO_PERSONA_ID, type RosterAgent } from '../core/roster';
import { createRecentRepositories } from '../primitives/recent-repositories';
import { createReachableRepositories } from '../queries/reachable-repositories';
+import { createRepositoryBranches } from '../queries/repository-branches';
import { AgentPicker } from './AgentPicker';
import { RepositoryPicker } from './RepositoryPicker';
@@ -76,6 +77,10 @@ export function NewChatPage(props: {
};
// Listed only while the drawer can show them: chat agents never ask.
const reachable = createReachableRepositories(coding);
+ // Listed only while a repository is chosen: listing costs a GitHub call.
+ const reachableBranches = createRepositoryBranches(() =>
+ coding() ? repoUrl() : undefined
+ );
// A chosen branch, or where the selected repository's own clones start.
const repoBranch = () =>
branchOverride() ?? defaultBranchFor(reachable.repositories(), repoUrl());
@@ -164,6 +169,10 @@ export function NewChatPage(props: {
repositoriesError={reachable.error()}
recentRepositories={repositories.urls()}
onRetryRepositories={reachable.retry}
+ branches={reachableBranches.branches()}
+ branchesLoading={reachableBranches.loading()}
+ branchesError={reachableBranches.error()}
+ onRetryBranches={reachableBranches.retry}
onConnectGitHub={() => openSettings('Connected')}
onSelectRepository={selectRepository}
onSelectBranch={setBranchOverride}
diff --git a/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx b/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
index 26385a6a7d..7083b4f466 100644
--- a/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
+++ b/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
@@ -19,6 +19,7 @@ function picker(
onSelectRepository: vi.fn(),
onSelectBranch: vi.fn(),
onRetryRepositories: vi.fn(),
+ onRetryBranches: vi.fn(),
onConnectGitHub: vi.fn(),
};
render(() => (
@@ -28,6 +29,9 @@ function picker(
repositoriesLoading={false}
repositoriesError={false}
recentRepositories={[]}
+ branches={['main', 'develop', 'feature/home']}
+ branchesLoading={false}
+ branchesError={false}
{...handlers}
{...overrides}
/>
@@ -39,7 +43,9 @@ const openRepositories = () =>
const search = () =>
screen.getByRole('combobox', { name: 'Search repositories' });
const optionNames = () =>
- screen.getAllByRole('option').map((option) => option.textContent?.trim());
+ screen
+ .getAllByRole('option')
+ .map((option) => option.textContent?.replace(/\s+/g, ' ').trim());
describe('RepositoryPicker', () => {
beforeEach(() => vi.stubGlobal('scrollTo', vi.fn()));
@@ -172,23 +178,78 @@ describe('RepositoryPicker', () => {
expect(handlers.onSelectRepository).not.toHaveBeenCalled();
});
- it('shows the branch only with a repository and validates the one typed', () => {
+ it('shows the branch only with a repository and picks a listed one', () => {
expect(picker().onSelectBranch).not.toHaveBeenCalled();
expect(screen.queryByRole('button', { name: 'Branch' })).toBeNull();
cleanup();
- const handlers = picker({ repoUrl: infra.url, branch: 'develop' });
+ const handlers = picker({
+ repoUrl: infra.url,
+ branch: 'develop',
+ branches: ['main', 'develop', 'feature/home'],
+ });
const branch = screen.getByRole('button', { name: 'Branch' });
expect(branch.textContent).toContain('develop');
fireEvent.click(branch);
- const field = screen.getByRole('textbox', { name: 'Starting branch' });
- expect((field as HTMLInputElement).value).toBe('develop');
+ expect(optionNames()).toEqual([
+ 'develop (default)',
+ 'main',
+ 'feature/home',
+ ]);
+ const selected = screen.getByRole('option', { name: /develop/ });
+ expect(selected.querySelector('svg.ml-auto')).toBeTruthy();
+ fireEvent.click(screen.getByRole('option', { name: 'feature/home' }));
+ expect(handlers.onSelectBranch).toHaveBeenCalledWith('feature/home');
+ });
+
+ it('filters branches as you type and offers an unlisted name', () => {
+ const handlers = picker({
+ repoUrl: infra.url,
+ branch: 'develop',
+ branches: ['main', 'develop', 'feature/home'],
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
+ const field = screen.getByRole('combobox', { name: 'Search branches' });
+ fireEvent.input(field, { target: { value: 'HOME' } });
+ expect(optionNames()).toEqual(['feature/home', 'Use HOME']);
+ fireEvent.input(field, { target: { value: 'feature/other' } });
+ expect(optionNames()).toEqual(['Use feature/other']);
+ fireEvent.click(screen.getByRole('option', { name: 'Use feature/other' }));
+ expect(handlers.onSelectBranch).toHaveBeenCalledWith('feature/other');
+ });
+
+ it('refuses to submit text that is not a branch name', () => {
+ const handlers = picker({ repoUrl: infra.url, branch: 'develop' });
+ fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
+ const field = screen.getByRole('combobox', { name: 'Search branches' });
fireEvent.input(field, { target: { value: 'bad..name' } });
- fireEvent.click(screen.getByRole('button', { name: 'Use branch' }));
- expect(screen.getByRole('alert')).toBeTruthy();
+ fireEvent.submit(field.closest('form') as HTMLFormElement);
+ expect(screen.getByRole('alert').textContent).toContain('valid branch');
expect(handlers.onSelectBranch).not.toHaveBeenCalled();
- fireEvent.input(field, { target: { value: 'feature/home' } });
- fireEvent.click(screen.getByRole('button', { name: 'Use branch' }));
- expect(handlers.onSelectBranch).toHaveBeenCalledWith('feature/home');
+ });
+
+ it('shows the loading, failed, and empty branch listings', () => {
+ picker({
+ repoUrl: infra.url,
+ branches: [],
+ branchesLoading: true,
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
+ expect(screen.getByText('Loading branches…')).toBeTruthy();
+ cleanup();
+
+ const failed = picker({
+ repoUrl: infra.url,
+ branches: [],
+ branchesError: true,
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(failed.onRetryBranches).toHaveBeenCalledOnce();
+ cleanup();
+
+ picker({ repoUrl: infra.url, branches: [] });
+ fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
+ expect(screen.getByText(/No branches yet/)).toBeTruthy();
});
});
diff --git a/apps/web/src/features/agents-view/views/RepositoryPicker.tsx b/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
index a53b2eae92..d2fc752c62 100644
--- a/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
+++ b/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
@@ -15,7 +15,9 @@ import {
} from 'solid-js';
import { match } from 'ts-pattern';
import {
+ filterBranches,
filterRepositories,
+ orderBranches,
orderRepositories,
type ReachableRepository,
repositoryLabel,
@@ -26,6 +28,12 @@ import {
/** One row of the repository list. */
type RepositoryChoice = { kind: 'automatic' } | { kind: 'listed'; url: string };
+/** One row of the branch list. */
+type BranchChoice =
+ | { kind: 'listed'; name: string }
+ /** Named by hand rather than listed; the session starts from this ref. */
+ | { kind: 'typed'; name: string };
+
/** Explicit, portaled repository/branch controls shared by Home and Agents. */
export function RepositoryPicker(props: {
repoUrl?: string;
@@ -37,6 +45,11 @@ export function RepositoryPicker(props: {
/** Repositories handed to coders before, newest first; offered ahead of the rest. */
recentRepositories: string[];
onRetryRepositories: () => void;
+ /** Branch names on the selected repository, as GitHub listed them. */
+ branches: string[];
+ branchesLoading: boolean;
+ branchesError: boolean;
+ onRetryBranches: () => void;
/** Where to send someone who reaches no repository yet. */
onConnectGitHub?: () => void;
/** `undefined` leaves the choice to the coder. */
@@ -47,8 +60,9 @@ export function RepositoryPicker(props: {
const [repoOpen, setRepoOpen] = createSignal(false);
const [branchOpen, setBranchOpen] = createSignal(false);
const [search, setSearch] = createSignal('');
- const [branchInput, setBranchInput] = createSignal('');
+ const [branchSearch, setBranchSearch] = createSignal('');
const [error, setError] = createSignal('');
+ const branchListId = createUniqueId();
const offered = createMemo(() =>
orderRepositories(props.repositories, props.recentRepositories)
@@ -96,17 +110,63 @@ export function RepositoryPicker(props: {
offered().length === 0 &&
!search().trim();
- const applyBranch = () => {
- const branch = branchInput().trim();
- if (!validRepositoryBranch(branch)) {
- setError(
- 'Enter a valid branch name, for example main or feature/my-change.'
- );
- return;
+ const defaultBranch = () => {
+ const url = props.repoUrl;
+ return url
+ ? props.repositories.find((repository) =>
+ sameRepository(repository.url, url)
+ )?.defaultBranch
+ : undefined;
+ };
+ const offeredBranches = createMemo(() => {
+ const listed = orderBranches(props.branches, defaultBranch());
+ // Keep a chosen or default name visible while listing, or when GitHub
+ // has other branches but not this one. An empty successful listing is
+ // an empty repository: offer a typed name instead of inventing one.
+ const keepCurrent =
+ !!props.branch &&
+ validRepositoryBranch(props.branch) &&
+ !listed.includes(props.branch) &&
+ (listed.length > 0 || props.branchesLoading || props.branchesError);
+ return keepCurrent ? [props.branch, ...listed] : listed;
+ });
+ const branchChoices = createMemo<BranchChoice[]>(() => {
+ const text = branchSearch().trim();
+ const listed = filterBranches(offeredBranches(), text);
+ const choices: BranchChoice[] = listed.map((name) => ({
+ kind: 'listed' as const,
+ name,
+ }));
+ if (validRepositoryBranch(text) && !listed.includes(text)) {
+ choices.push({ kind: 'typed', name: text });
}
- props.onSelectBranch(branch);
+ return choices;
+ });
+ const chooseBranch = (choice: BranchChoice) => {
+ props.onSelectBranch(choice.name);
setBranchOpen(false);
};
+ const branchList = createCommandListController<BranchChoice>({
+ items: branchChoices,
+ onSelect: chooseBranch,
+ });
+ const highlightedBranchId = () =>
+ `${branchListId}-${branchList.selectedIndex()}`;
+ const scrollHighlightedBranchIntoView = () =>
+ document.getElementById(highlightedBranchId())?.scrollIntoView?.({
+ block: 'nearest',
+ });
+ const submitBranch = () => {
+ if (branchList.selectSelected()) return;
+ setError(
+ 'Enter a valid branch name, for example main or feature/my-change.'
+ );
+ };
+ const nothingListed = () =>
+ !props.branchesLoading &&
+ !props.branchesError &&
+ offeredBranches().length === 0 &&
+ !branchSearch().trim();
return (
<div class="flex min-w-0 flex-wrap items-center gap-2">
<Popover
@@ -258,7 +318,11 @@ export function RepositoryPicker(props: {
onOpenChange={(open) => {
setBranchOpen(open);
setError('');
- if (open) setBranchInput(props.branch);
+ if (open) {
+ setBranchSearch('');
+ const selected = offeredBranches().indexOf(props.branch);
+ branchList.setSelectedIndex(selected >= 0 ? selected : 0);
+ }
}}
placement="top-start"
gutter={8}
@@ -276,17 +340,35 @@ export function RepositoryPicker(props: {
<form
onSubmit={(event) => {
event.preventDefault();
- applyBranch();
+ submitBranch();
}}
class="flex flex-col gap-2"
>
<input
- aria-label="Starting branch"
- placeholder="main or feature/my-change"
- value={branchInput()}
+ role="combobox"
+ aria-label="Search branches"
+ aria-expanded="true"
+ aria-controls={branchListId}
+ aria-activedescendant={highlightedBranchId()}
+ aria-autocomplete="list"
+ autocomplete="off"
+ placeholder="Search, or type a branch name"
+ value={branchSearch()}
onInput={(event) => {
- setBranchInput(event.currentTarget.value);
+ setBranchSearch(event.currentTarget.value);
setError('');
+ branchList.setSelectedIndex(0);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ branchList.selectNext();
+ scrollHighlightedBranchIntoView();
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ branchList.selectPrevious();
+ scrollHighlightedBranchIntoView();
+ }
}}
class="w-full rounded-lg border border-edge-muted bg-input px-3 py-2 outline-none focus:border-accent"
/>
@@ -295,10 +377,76 @@ export function RepositoryPicker(props: {
{error()}
</p>
</Show>
- <Button type="submit" variant="strong">
- Use branch
- </Button>
</form>
+ <div
+ id={branchListId}
+ role="listbox"
+ aria-label="Branches"
+ class="mt-2 max-h-56 overflow-y-auto"
+ >
+ <For each={branchChoices()}>
+ {(choice, index) => (
+ <button
+ type="button"
+ role="option"
+ id={`${branchListId}-${index()}`}
+ aria-selected={branchList.isSelected(index())}
+ class="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left hover:bg-hover aria-selected:bg-active"
+ onClick={() => chooseBranch(choice)}
+ onMouseMove={() =>
+ branchList.setSelectedIndexFromPointer(index())
+ }
+ >
+ <GitBranchIcon class="size-4 shrink-0" />
+ <span class="min-w-0 truncate">
+ {choice.kind === 'typed'
+ ? `Use ${choice.name}`
+ : choice.name}
+ </span>
+ <Show when={choice.name === defaultBranch()}>
+ <span class="shrink-0 text-xs text-ink-muted">
+ {` (default)`}
+ </span>
+ </Show>
+ <Show when={choice.name === props.branch}>
+ <CheckIcon class="ml-auto size-4 shrink-0" />
+ </Show>
+ </button>
+ )}
+ </For>
+ <Switch>
+ <Match when={props.branchesError}>
+ <div class="flex items-center justify-between gap-2 px-2 py-2 text-xs text-ink-muted">
+ Couldn't load this repository's branches.
+ <Button
+ variant="outline"
+ size="sm"
+ depth={3}
+ onClick={() => props.onRetryBranches()}
+ >
+ Retry
+ </Button>
+ </div>
+ </Match>
+ <Match
+ when={props.branchesLoading && props.branches.length === 0}
+ >
+ <div class="px-2 py-2 text-xs text-ink-muted">
+ Loading branches…
+ </div>
+ </Match>
+ <Match when={nothingListed()}>
+ <div class="px-2 py-2 text-xs text-ink-muted">
+ No branches yet. Type a starting branch to use.
+ </div>
+ </Match>
+ <Match when={branchChoices().length === 0}>
+ <div class="px-2 py-2 text-xs text-ink-muted">
+ No branches match “{branchSearch().trim()}”.
+ </div>
+ </Match>
+ </Switch>
+ </div>
</Popover.Content>
</Popover.Portal>
</Popover>
diff --git a/apps/web/src/lib/queries/agent-repositories/branches.ts b/apps/web/src/lib/queries/agent-repositories/branches.ts
new file mode 100644
index 0000000000..2cb8eb4b77
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-repositories/branches.ts
@@ -0,0 +1,29 @@
+import { throwOnErr } from '@core/util/result';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import { useQuery } from '@tanstack/solid-query';
+import { agentRepositoryKeys } from './keys';
+
+/**
+ * The branches on one GitHub repository the signed-in user can start a
+ * coding session from. The same listing the picker offers, authorized the
+ * same way as an explicit `repoUrl` on create-session.
+ *
+ * Enabled only while a repository is selected: listing costs a GitHub call
+ * per repository, and chat agents never ask.
+ */
+export function useAgentRepositoryBranchesQuery(
+ repoUrl: () => string | undefined
+) {
+ return useQuery(() => {
+ const url = repoUrl();
+ return {
+ queryKey: agentRepositoryKeys.branches(url ?? '').queryKey,
+ queryFn: async () =>
+ throwOnErr(() =>
+ agentHarnessServiceClient.listRepositoryBranches(url ?? '')
+ ),
+ enabled: !!url,
+ staleTime: 2 * 60 * 1000,
+ };
+ });
+}
diff --git a/apps/web/src/lib/queries/agent-repositories/keys.ts b/apps/web/src/lib/queries/agent-repositories/keys.ts
index ace1b4c941..3710e0176a 100644
--- a/apps/web/src/lib/queries/agent-repositories/keys.ts
+++ b/apps/web/src/lib/queries/agent-repositories/keys.ts
@@ -2,4 +2,5 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
export const agentRepositoryKeys = createQueryKeys('agentRepositories', {
list: null,
+ branches: (repoUrl: string) => ({ queryKey: [repoUrl] }),
});
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts
index 433ca18234..8f95831001 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts
@@ -57,4 +57,14 @@ describe('repository listing', () => {
{ method: 'GET' }
);
});
+
+ it("asks the harness for one repository's branches", () => {
+ agentHarnessServiceClient.listRepositoryBranches(
+ 'https://github.com/macro-inc/macro'
+ );
+ expect(fetchWithToken).toHaveBeenCalledWith(
+ 'https://harness.example.com/agent-repositories/branches?repoUrl=https%3A%2F%2Fgithub.com%2Fmacro-inc%2Fmacro',
+ { method: 'GET' }
+ );
+ });
});
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
index 8e8fe4bd31..da63e9576c 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
@@ -3,6 +3,7 @@ import { fetchWithToken } from '@core/util/fetchWithToken';
import type { ErrorResponseHandler } from '@core/util/safeFetch';
import type {
AgentRepositoriesResponse,
+ AgentRepositoryBranchesResponse,
AgentSessionChangesPatchResponse,
AgentSessionChangesResponse,
AgentSessionLogResponse,
@@ -85,6 +86,19 @@ export const agentHarnessServiceClient = {
);
},
+ /**
+ * The branches on one GitHub repository the caller can start a coding
+ * session from. `repoUrl` is the canonical `https://github.com/owner/name`
+ * form `listRepositories` and create-session share.
+ */
+ listRepositoryBranches(repoUrl: string) {
+ const params = new URLSearchParams({ repoUrl });
+ return fetchWithToken<AgentRepositoryBranchesResponse>(
+ `${agentHarnessHost}/agent-repositories/branches?${params}`,
+ { method: 'GET' }
+ );
+ },
+
get(sessionId: string) {
return fetchWithToken<AgentSessionResponse>(
`${agentHarnessHost}/agent-sessions/${sessionId}`,
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index 20a8d7e7c6..80204a6e49 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -6,6 +6,7 @@
*/
import type {
AgentRepositoriesResponse,
+ AgentRepositoryBranchesResponse,
AgentSessionChangesPatchResponse,
AgentSessionChangesResponse,
AgentSessionLogResponse,
@@ -18,6 +19,7 @@ import type {
CreateAgentSessionResponse,
EditQueuedActionRequest,
EmptyRequest,
+ ListAgentRepositoryBranchesParams,
LoadAgentModelsRequest,
LoadAgentModelsResponse,
PreviewAgentSessionsRequest,
@@ -169,6 +171,90 @@ export const listAgentRepositories = async (
} as listAgentRepositoriesResponse;
};
+/**
+ * @summary List the branches on one repository the caller can start a session from.
+ */
+export type listAgentRepositoryBranchesResponse200 = {
+ data: AgentRepositoryBranchesResponse;
+ status: 200;
+};
+
+export type listAgentRepositoryBranchesResponse400 = {
+ data: void;
+ status: 400;
+};
+
+export type listAgentRepositoryBranchesResponse401 = {
+ data: void;
+ status: 401;
+};
+
+export type listAgentRepositoryBranchesResponse403 = {
+ data: void;
+ status: 403;
+};
+
+export type listAgentRepositoryBranchesResponse502 = {
+ data: void;
+ status: 502;
+};
+
+export type listAgentRepositoryBranchesResponseSuccess =
+ listAgentRepositoryBranchesResponse200 & {
+ headers: Headers;
+ };
+export type listAgentRepositoryBranchesResponseError = (
+ | listAgentRepositoryBranchesResponse400
+ | listAgentRepositoryBranchesResponse401
+ | listAgentRepositoryBranchesResponse403
+ | listAgentRepositoryBranchesResponse502
+) & {
+ headers: Headers;
+};
+
+export type listAgentRepositoryBranchesResponse =
+ | listAgentRepositoryBranchesResponseSuccess
+ | listAgentRepositoryBranchesResponseError;
+
+export const getListAgentRepositoryBranchesUrl = (
+ params: ListAgentRepositoryBranchesParams
+) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/agent-repositories/branches?${stringifiedParams}`
+ : `/agent-repositories/branches`;
+};
+
+export const listAgentRepositoryBranches = async (
+ params: ListAgentRepositoryBranchesParams,
+ options?: RequestInit
+): Promise<listAgentRepositoryBranchesResponse> => {
+ const res = await fetch(getListAgentRepositoryBranchesUrl(params), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listAgentRepositoryBranchesResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listAgentRepositoryBranchesResponse;
+};
+
/**
* @summary Read the caller's default sandbox size for new `@coder` sessions.
*/
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryBranchesResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryBranchesResponse.ts
new file mode 100644
index 0000000000..ee291a37da
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryBranchesResponse.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response body for `GET /agent-repositories/branches`.
+ */
+export interface AgentRepositoryBranchesResponse {
+ /** Branch names on the repository, in the order GitHub returned them.
+Empty when the repository has no commits yet. */
+ branches: string[];
+}
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 3ab37bc318..fe28a402b6 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
@@ -30,6 +30,7 @@ export * from './agentModelsStatusDto';
export * from './agentPermissionAction';
export * from './agentPromptAction';
export * from './agentRepositoriesResponse';
+export * from './agentRepositoryBranchesResponse';
export * from './agentRepositoryDto';
export * from './agentRepositoryDtoDefaultBranch';
export * from './agentRespondElicitationAction';
@@ -118,6 +119,7 @@ export * from './fileChangeKindDto';
export * from './gitRefDto';
export * from './gitRefDtoName';
export * from './gitRefDtoSha';
+export * from './listAgentRepositoryBranchesParams';
export * from './loadAgentModelsRequest';
export * from './loadAgentModelsRequestHarnessId';
export * from './loadAgentModelsResponse';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/listAgentRepositoryBranchesParams.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/listAgentRepositoryBranchesParams.ts
new file mode 100644
index 0000000000..1672972ef7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/listAgentRepositoryBranchesParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ListAgentRepositoryBranchesParams = {
+ /**
+ * Canonical https://github.com/owner/name URL
+ */
+ repoUrl: string;
+};
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 42d0ef5f75..47414b47d2 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
@@ -92,6 +92,53 @@
]
}
},
+ "/agent-repositories/branches": {
+ "get": {
+ "tags": ["agent-repositories"],
+ "summary": "List the branches on one repository the caller can start a session from.",
+ "operationId": "list_agent_repository_branches",
+ "parameters": [
+ {
+ "name": "repoUrl",
+ "in": "query",
+ "description": "Canonical https://github.com/owner/name URL",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The repository's branches",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentRepositoryBranchesResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "The query did not name a GitHub repository"
+ },
+ "401": {
+ "description": "Unauthenticated"
+ },
+ "403": {
+ "description": "The caller cannot reach this repository"
+ },
+ "502": {
+ "description": "GitHub could not be asked which branches the repository has"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
"/agent-sandbox-size": {
"get": {
"tags": ["agent-sessions"],
@@ -1456,6 +1503,20 @@
}
}
},
+ "AgentRepositoryBranchesResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-repositories/branches`.",
+ "required": ["branches"],
+ "properties": {
+ "branches": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Branch names on the repository, in the order GitHub returned them.\nEmpty when the repository has no commits yet."
+ }
+ }
+ },
"AgentRepositoryDto": {
"type": "object",
"description": "One repository the caller can select for a coding session.",
diff --git a/crates/agent_harness/src/domain/error.rs b/crates/agent_harness/src/domain/error.rs
index a3bc2a1108..ae92da7ca0 100644
--- a/crates/agent_harness/src/domain/error.rs
+++ b/crates/agent_harness/src/domain/error.rs
@@ -71,6 +71,13 @@ pub enum HarnessError {
/// App's credentials, an installation record, or a call to github.com.
#[error("failed to list reachable repositories: {0}")]
Repositories(rootcause::Report),
+ /// The named repository is not one the user reaches through the GitHub App.
+ ///
+ /// The same sentence the create-session path uses, so a picker that listed
+ /// a repository the user can no longer reach and a typed URL they never
+ /// could both explain themselves the same way.
+ #[error("repository is not available to this user")]
+ RepositoryUnavailable,
/// A bot's persisted agent runtime configuration could not be loaded.
#[error("failed to resolve agent runtime configuration: {0}")]
RuntimeDirectory(rootcause::Report),
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index ac3ae17d34..78f00f056e 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -43,6 +43,25 @@ pub trait ReachableRepositories: Send + Sync + 'static {
async fn for_user(&self, user: &MacroUserIdStr<'_>) -> Result<Vec<ReachableRepository>>;
}
+/// The branches on one repository a user can start a coding session from.
+///
+/// Separate from [`ReachableRepositories`] because listing every repository
+/// is a cached installation sweep, and listing one repository's branches is
+/// a scoped call after proving the user reaches that repository.
+#[async_trait::async_trait]
+pub trait RepositoryBranches: Send + Sync + 'static {
+ /// Branch names on `owner`/`name`, in the order GitHub returned them.
+ ///
+ /// [`HarnessError::RepositoryUnavailable`] when the user cannot reach the
+ /// repository. An empty repository is an empty list.
+ async fn for_repository(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ owner: &str,
+ name: &str,
+ ) -> Result<Vec<String>>;
+}
+
/// Forwards commands to the replica currently responsible for execution.
pub trait CommandForwarder: Send + Sync + 'static {
/// Run `command` at `target`.
diff --git a/crates/agent_harness/src/inbound/mod.rs b/crates/agent_harness/src/inbound/mod.rs
index 1ba54df893..9e8e749650 100644
--- a/crates/agent_harness/src/inbound/mod.rs
+++ b/crates/agent_harness/src/inbound/mod.rs
@@ -6,6 +6,6 @@
pub mod kafka;
/// Authenticated model discovery.
pub mod model_load;
-/// Authenticated repository listing.
+/// Authenticated repository and branch listing.
pub mod repositories;
pub mod runtime_gateway;
diff --git a/crates/agent_harness/src/inbound/repositories.rs b/crates/agent_harness/src/inbound/repositories.rs
index 9ce07038de..344138f0df 100644
--- a/crates/agent_harness/src/inbound/repositories.rs
+++ b/crates/agent_harness/src/inbound/repositories.rs
@@ -1,5 +1,5 @@
//! Authenticated HTTP adapter listing the repositories a caller can hand a
-//! coding session.
+//! coding session, and the branches on one of those repositories.
//!
//! The same listing the open path authorizes an explicit `repoUrl` against
//! and the Cursor chooser picks from, offered to the app so a repository is
@@ -9,19 +9,21 @@
use std::sync::Arc;
+use agent_egress::domain::model::RepoSlug;
use axum::Router;
-use axum::extract::{FromRef, Json, State};
+use axum::extract::{FromRef, Json, Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOnly,
};
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
+use crate::domain::error::HarnessError;
use crate::domain::model::ReachableRepository;
-use crate::domain::ports::ReachableRepositories;
+use crate::domain::ports::{ReachableRepositories, RepositoryBranches};
#[cfg(test)]
mod test;
@@ -63,9 +65,28 @@ impl From<Vec<ReachableRepository>> for AgentRepositoriesResponse {
}
}
+/// Query for `GET /agent-repositories/branches`.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentRepositoryBranchesQuery {
+ /// Canonical `https://github.com/owner/name` url, as `POST /agent-sessions`
+ /// accepts as `repoUrl`.
+ pub repo_url: String,
+}
+
+/// Response body for `GET /agent-repositories/branches`.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentRepositoryBranchesResponse {
+ /// Branch names on the repository, in the order GitHub returned them.
+ /// Empty when the repository has no commits yet.
+ pub branches: Vec<String>,
+}
+
/// Router state for repository listing.
pub struct AgentRepositoriesRouterState<Auth> {
repositories: Arc<dyn ReachableRepositories>,
+ branches: Arc<dyn RepositoryBranches>,
authorization: MacroAuthorizationState<Auth>,
}
@@ -73,10 +94,12 @@ impl<Auth> AgentRepositoriesRouterState<Auth> {
/// Build repository-listing route state.
pub fn new(
repositories: Arc<dyn ReachableRepositories>,
+ branches: Arc<dyn RepositoryBranches>,
authorization: MacroAuthorizationState<Auth>,
) -> Self {
Self {
repositories,
+ branches,
authorization,
}
}
@@ -86,6 +109,7 @@ impl<Auth> Clone for AgentRepositoriesRouterState<Auth> {
fn clone(&self) -> Self {
Self {
repositories: Arc::clone(&self.repositories),
+ branches: Arc::clone(&self.branches),
authorization: self.authorization.clone(),
}
}
@@ -108,6 +132,10 @@ where
"/agent-repositories",
get(list_agent_repositories_handler::<Auth>),
)
+ .route(
+ "/agent-repositories/branches",
+ get(list_agent_repository_branches_handler::<Auth>),
+ )
.with_state(state)
}
@@ -153,3 +181,67 @@ where
}
}
}
+
+/// List the branches on one repository the caller can start a session from.
+#[utoipa::path(
+ get,
+ path = "/agent-repositories/branches",
+ tag = "agent-repositories",
+ operation_id = "list_agent_repository_branches",
+ security(("bearerAuth" = [])),
+ params(
+ ("repoUrl" = String, Query, description = "Canonical https://github.com/owner/name URL")
+ ),
+ responses(
+ (status = 200, description = "The repository's branches", body = AgentRepositoryBranchesResponse),
+ (status = 400, description = "The query did not name a GitHub repository"),
+ (status = 401, description = "Unauthenticated"),
+ (status = 403, description = "The caller cannot reach this repository"),
+ (status = 502, description = "GitHub could not be asked which branches the repository has"),
+ )
+)]
+pub async fn list_agent_repository_branches_handler<Auth>(
+ State(state): State<AgentRepositoriesRouterState<Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOnly>,
+ Query(query): Query<AgentRepositoryBranchesQuery>,
+) -> Response
+where
+ Auth: MacroAuthorizationService,
+{
+ let Some(repository) = RepoSlug::parse_github_url(&query.repo_url) else {
+ return (
+ StatusCode::BAD_REQUEST,
+ "Enter a GitHub repository as https://github.com/owner/repo.".to_owned(),
+ )
+ .into_response();
+ };
+
+ match state
+ .branches
+ .for_repository(
+ &authorization.authorization.macro_user_id,
+ repository.owner(),
+ repository.name(),
+ )
+ .await
+ {
+ Ok(branches) => (
+ StatusCode::OK,
+ Json(AgentRepositoryBranchesResponse { branches }),
+ )
+ .into_response(),
+ Err(HarnessError::RepositoryUnavailable) => (
+ StatusCode::FORBIDDEN,
+ "repository is not available to this user".to_owned(),
+ )
+ .into_response(),
+ Err(error) => {
+ tracing::warn!(error = ?error, "could not list the repository's branches");
+ (
+ StatusCode::BAD_GATEWAY,
+ "could not list this repository's branches".to_owned(),
+ )
+ .into_response()
+ }
+ }
+}
diff --git a/crates/agent_harness/src/inbound/repositories/test.rs b/crates/agent_harness/src/inbound/repositories/test.rs
index 42172880f3..87cfe05769 100644
--- a/crates/agent_harness/src/inbound/repositories/test.rs
+++ b/crates/agent_harness/src/inbound/repositories/test.rs
@@ -10,6 +10,7 @@ use tower::ServiceExt as _;
use super::*;
use crate::domain::error::HarnessError;
+use crate::domain::ports::RepositoryBranches;
const USER_ID: &str = "macro|[email protected]";
@@ -61,20 +62,83 @@ impl ReachableRepositories for StubRepositories {
}
}
+/// A canned branch listing that records who asked, and for which repository.
+struct StubBranches {
+ listing: Result<Vec<String>, StubBranchError>,
+ asked_for: std::sync::Mutex<Vec<(String, String, String)>>,
+}
+
+#[derive(Clone, Copy)]
+enum StubBranchError {
+ Unavailable,
+ Failed,
+}
+
+#[async_trait::async_trait]
+impl RepositoryBranches for StubBranches {
+ async fn for_repository(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ owner: &str,
+ name: &str,
+ ) -> crate::domain::error::Result<Vec<String>> {
+ self.asked_for.lock().expect("stub poisoned").push((
+ user.to_string(),
+ owner.to_owned(),
+ name.to_owned(),
+ ));
+ match self.listing.clone() {
+ Ok(branches) => Ok(branches),
+ Err(StubBranchError::Unavailable) => Err(HarnessError::RepositoryUnavailable),
+ Err(StubBranchError::Failed) => Err(HarnessError::Repositories(rootcause::report!(
+ "github is down"
+ ))),
+ }
+ }
+}
+
fn router(listing: Result<Vec<ReachableRepository>, ()>) -> (Router, Arc<StubRepositories>) {
+ router_with_branches(listing, Ok(Vec::new()))
+}
+
+fn router_with_branches(
+ listing: Result<Vec<ReachableRepository>, ()>,
+ branches: Result<Vec<String>, StubBranchError>,
+) -> (Router, Arc<StubRepositories>) {
+ let (router, repositories, _) = router_parts(listing, branches);
+ (router, repositories)
+}
+
+fn router_parts(
+ listing: Result<Vec<ReachableRepository>, ()>,
+ branches: Result<Vec<String>, StubBranchError>,
+) -> (Router, Arc<StubRepositories>, Arc<StubBranches>) {
let repositories = Arc::new(StubRepositories {
listing,
asked_for: std::sync::Mutex::new(Vec::new()),
});
+ let branch_listing = Arc::new(StubBranches {
+ listing: branches,
+ asked_for: std::sync::Mutex::new(Vec::new()),
+ });
let state = AgentRepositoriesRouterState::new(
Arc::clone(&repositories) as Arc<dyn ReachableRepositories>,
+ Arc::clone(&branch_listing) as Arc<dyn RepositoryBranches>,
MacroAuthorizationState::new(Arc::new(TestAuthorizationService)),
);
- (agent_repositories_router(state), repositories)
+ (
+ agent_repositories_router(state),
+ repositories,
+ branch_listing,
+ )
}
fn request(token: Option<&str>) -> Request<Body> {
- let builder = Request::builder().uri("/agent-repositories").method("GET");
+ request_path("/agent-repositories", token)
+}
+
+fn request_path(uri: &str, token: Option<&str>) -> Request<Body> {
+ let builder = Request::builder().uri(uri).method("GET");
let builder = match token {
Some(token) => builder.header("authorization", format!("Bearer {token}")),
None => builder,
@@ -155,3 +219,80 @@ async fn a_failed_listing_is_a_bad_gateway() {
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
}
+
+#[tokio::test]
+async fn lists_the_named_repositorys_branches_for_the_caller() {
+ let (router, _, branches) = router_parts(
+ Ok(Vec::new()),
+ Ok(vec!["main".to_owned(), "develop".to_owned()]),
+ );
+
+ let response = router
+ .oneshot(request_path(
+ "/agent-repositories/branches?repoUrl=https://github.com/macro-inc/macro",
+ Some("valid"),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
+ serde_json::json!({ "branches": ["main", "develop"] })
+ );
+ assert_eq!(
+ *branches.asked_for.lock().unwrap(),
+ vec![(
+ USER_ID.to_owned(),
+ "macro-inc".to_owned(),
+ "macro".to_owned()
+ )]
+ );
+}
+
+#[tokio::test]
+async fn a_url_that_names_no_repository_is_refused_before_github_is_asked() {
+ let (router, _, branches) = router_parts(Ok(Vec::new()), Ok(Vec::new()));
+
+ let response = router
+ .oneshot(request_path(
+ "/agent-repositories/branches?repoUrl=https://example.com/not-github",
+ Some("valid"),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert!(branches.asked_for.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn an_unreachable_repository_is_forbidden() {
+ let (router, _, _) = router_parts(Ok(Vec::new()), Err(StubBranchError::Unavailable));
+
+ let response = router
+ .oneshot(request_path(
+ "/agent-repositories/branches?repoUrl=https://github.com/other/private",
+ Some("valid"),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+}
+
+#[tokio::test]
+async fn a_failed_branch_listing_is_a_bad_gateway() {
+ let (router, _, _) = router_parts(Ok(Vec::new()), Err(StubBranchError::Failed));
+
+ let response = router
+ .oneshot(request_path(
+ "/agent-repositories/branches?repoUrl=https://github.com/macro-inc/macro",
+ Some("valid"),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
+}
diff --git a/crates/agent_harness/src/outbound/github_branches.rs b/crates/agent_harness/src/outbound/github_branches.rs
new file mode 100644
index 0000000000..d889cff6ac
--- /dev/null
+++ b/crates/agent_harness/src/outbound/github_branches.rs
@@ -0,0 +1,50 @@
+//! The branches on a repository a user reaches through Macro's GitHub App.
+//!
+//! Reachability is the `github` crate's question: this adapter only maps its
+//! answer into the harness's vocabulary so a picker can list the same branches
+//! a session may start on.
+
+use github::domain::models::GithubError;
+use github::domain::ports::{GithubSyncClient, GithubSyncRepo};
+use github::domain::service::InstallationTokenService;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::domain::error::{HarnessError, Result};
+use crate::domain::ports::RepositoryBranches;
+
+/// [`RepositoryBranches`] backed by a scoped installation token.
+pub struct GithubRepositoryBranches<Installations, Client> {
+ tokens: InstallationTokenService<Installations, Client>,
+}
+
+impl<Installations, Client> GithubRepositoryBranches<Installations, Client>
+where
+ Installations: GithubSyncRepo,
+ Client: GithubSyncClient,
+{
+ /// Wrap the token service that already proves the user reaches the
+ /// repository before talking to GitHub.
+ pub fn new(tokens: InstallationTokenService<Installations, Client>) -> Self {
+ Self { tokens }
+ }
+}
+
+#[async_trait::async_trait]
+impl<Installations, Client> RepositoryBranches for GithubRepositoryBranches<Installations, Client>
+where
+ Installations: GithubSyncRepo,
+ Client: GithubSyncClient,
+{
+ async fn for_repository(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ owner: &str,
+ name: &str,
+ ) -> Result<Vec<String>> {
+ match self.tokens.branches_for_repository(user, owner, name).await {
+ Ok(branches) => Ok(branches),
+ Err(GithubError::RepositoryUnavailable) => Err(HarnessError::RepositoryUnavailable),
+ Err(error) => Err(HarnessError::Repositories(rootcause::report!("{error}"))),
+ }
+ }
+}
diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rs
index 02c4d5c8e6..f0fa284d4d 100644
--- a/crates/agent_harness/src/outbound/mod.rs
+++ b/crates/agent_harness/src/outbound/mod.rs
@@ -9,6 +9,7 @@ pub mod cursor;
pub mod daytona;
pub mod egress;
pub mod forward;
+pub mod github_branches;
pub mod github_repositories;
pub mod local;
pub(crate) mod managed_containers;
diff --git a/crates/github/src/domain/ports/sync.rs b/crates/github/src/domain/ports/sync.rs
index c2cbe955dd..6fa456a3c3 100644
--- a/crates/github/src/domain/ports/sync.rs
+++ b/crates/github/src/domain/ports/sync.rs
@@ -228,6 +228,16 @@ pub trait GithubSyncClient: Send + Sync + 'static {
&self,
access_token: &str,
) -> impl Future<Output = Result<Vec<EnrichedGithubPullRequest>, GithubError>> + Send;
+
+ /// Branch names on one repository, as GitHub lists them.
+ ///
+ /// An empty repository has no branches and is an empty list, not an error.
+ fn list_repository_branches(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repository: &str,
+ ) -> impl Future<Output = Result<Vec<String>, GithubError>> + Send;
}
/// Service interface for github sync operations (webhooks and sync app).
diff --git a/crates/github/src/domain/service/installation_tokens.rs b/crates/github/src/domain/service/installation_tokens.rs
index b65a202a1d..90ce646afa 100644
--- a/crates/github/src/domain/service/installation_tokens.rs
+++ b/crates/github/src/domain/service/installation_tokens.rs
@@ -31,6 +31,7 @@ use crate::domain::ports::{GithubSyncClient, GithubSyncRepo};
mod test;
/// The GitHub App tokens are minted for.
+#[derive(Clone)]
pub struct InstallationTokenConfig {
/// The App's client id, which GitHub wants as the JWT's `iss`.
pub client_id: String,
@@ -97,6 +98,28 @@ where
.await
}
+ /// The branch names `owner`/`repository` currently has, valid because
+ /// `macro_user_id` may reach it.
+ ///
+ /// Same refusal as [`Self::for_repository`]: a repository the App does
+ /// not cover, or one the user has no claim to, is
+ /// [`GithubError::RepositoryUnavailable`]. An empty repository has no
+ /// branches and is an empty list, not an error.
+ #[tracing::instrument(skip(self), err, fields(%macro_user_id, owner, repository))]
+ pub async fn branches_for_repository(
+ &self,
+ macro_user_id: &MacroUserIdStr<'_>,
+ owner: &str,
+ repository: &str,
+ ) -> Result<Vec<String>, GithubError> {
+ let token = self
+ .for_repository(macro_user_id, owner, repository, &[("contents", "read")])
+ .await?;
+ self.client
+ .list_repository_branches(&token.token, owner, repository)
+ .await
+ }
+
/// Confirm `installation` was installed by this user or by a team they
/// belong to.
async fn ensure_reachable(
diff --git a/crates/github/src/domain/service/installation_tokens/test.rs b/crates/github/src/domain/service/installation_tokens/test.rs
index d24678a35f..299d718223 100644
--- a/crates/github/src/domain/service/installation_tokens/test.rs
+++ b/crates/github/src/domain/service/installation_tokens/test.rs
@@ -144,6 +144,7 @@ impl GithubSyncRepo for FakeRepo {
struct FakeClient {
installation: Option<u64>,
minted: Mutex<Vec<(u64, String, Vec<(String, String)>)>>,
+ branches: Vec<String>,
}
impl FakeClient {
@@ -151,6 +152,7 @@ impl FakeClient {
Self {
installation: Some(INSTALLATION),
minted: Mutex::default(),
+ branches: vec!["main".to_owned(), "develop".to_owned()],
}
}
@@ -158,6 +160,7 @@ impl FakeClient {
Self {
installation: None,
minted: Mutex::default(),
+ branches: Vec::new(),
}
}
@@ -256,6 +259,15 @@ impl GithubSyncClient for FakeClient {
) -> Result<Vec<EnrichedGithubPullRequest>, GithubError> {
unimplemented!("minting a token does not list pull requests")
}
+
+ async fn list_repository_branches(
+ &self,
+ _access_token: &str,
+ _owner: &str,
+ _repository: &str,
+ ) -> Result<Vec<String>, GithubError> {
+ Ok(self.branches.clone())
+ }
}
fn service(
@@ -377,6 +389,48 @@ async fn scopes_the_token_to_the_one_repository_and_the_asked_for_permissions()
);
}
+#[tokio::test]
+async fn lists_branches_after_proving_the_user_reaches_the_repository() {
+ let service = service(
+ vec![GithubAppInstallationSource::User(user().to_string())],
+ vec![],
+ FakeClient::installed(),
+ );
+
+ let branches = service
+ .branches_for_repository(&user(), "macro-inc", "macro")
+ .await
+ .expect("listed");
+
+ assert_eq!(branches, vec!["main".to_owned(), "develop".to_owned()]);
+ let minted = service.client.minted.lock().expect("lock").clone();
+ assert_eq!(
+ minted,
+ vec![(
+ INSTALLATION,
+ "macro".to_owned(),
+ vec![("contents".to_owned(), "read".to_owned())]
+ )]
+ );
+}
+
+#[tokio::test]
+async fn listing_branches_refuses_a_repository_the_user_cannot_reach() {
+ let service = service(
+ vec![GithubAppInstallationSource::Team(uuid::Uuid::from_u128(1))],
+ vec![uuid::Uuid::from_u128(2)],
+ FakeClient::installed(),
+ );
+
+ let error = service
+ .branches_for_repository(&user(), "someone-else", "private")
+ .await
+ .expect_err("refused");
+
+ assert!(matches!(error, GithubError::RepositoryUnavailable));
+ assert_eq!(service.client.mint_count(), 0);
+}
+
#[test]
fn reads_the_expiry_github_sent() {
let token = GithubInstallationAccessToken {
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index 769828b16a..1e6228f36b 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -945,6 +945,15 @@ impl GithubSyncClient for StubSyncClient {
Ok(self.open_pull_requests.lock().unwrap().clone())
}
+
+ async fn list_repository_branches(
+ &self,
+ _access_token: &str,
+ _owner: &str,
+ _repository: &str,
+ ) -> Result<Vec<String>, GithubError> {
+ unimplemented!("the sync service does not list repository branches")
+ }
}
fn foreign_entity_id_from_receipt(
diff --git a/crates/github/src/outbound/github_sync_client.rs b/crates/github/src/outbound/github_sync_client.rs
index d374b7f5be..5df94bd503 100644
--- a/crates/github/src/outbound/github_sync_client.rs
+++ b/crates/github/src/outbound/github_sync_client.rs
@@ -19,6 +19,11 @@ use crate::domain::{
const GITHUB_API_BASE_URL: &str = "https://api.github.com";
const GITHUB_OAUTH_BASE_URL: &str = "https://github.com";
const USER_INSTALLATIONS_PAGE_SIZE: u64 = 100;
+const BRANCH_PAGE_SIZE: u64 = 100;
+/// GitHub's listing maxes at 100 names per page. Five pages is enough for a
+/// picker and bounds how long we hold an installation token against a
+/// repository with thousands of stale branches.
+const BRANCH_PAGE_LIMIT: u64 = 5;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
#[cfg(test)]
@@ -441,6 +446,70 @@ impl GithubSyncClient for GithubSyncClientImpl {
.await
.map_err(GithubError::Internal)
}
+
+ #[tracing::instrument(skip(self, access_token), err)]
+ async fn list_repository_branches(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repository: &str,
+ ) -> Result<Vec<String>, GithubError> {
+ #[derive(serde::Deserialize)]
+ struct BranchResponse {
+ name: String,
+ }
+
+ let mut page = 1_u64;
+ let mut branches = Vec::new();
+
+ loop {
+ let response = self
+ .client
+ .get(format!(
+ "{}/repos/{owner}/{repository}/branches?per_page={BRANCH_PAGE_SIZE}&page={page}",
+ self.api_base_url()
+ ))
+ .header("Authorization", format!("Bearer {access_token}"))
+ .header("Accept", "application/vnd.github+json")
+ .header("User-Agent", "Macro-Auth-Service")
+ .header("X-GitHub-Api-Version", "2022-11-28")
+ .send()
+ .await
+ .map_err(|_| {
+ GithubError::Internal(anyhow::anyhow!("GitHub branch list request failed"))
+ })?;
+
+ let status = response.status();
+ // An empty repository has no branches yet. GitHub answers 404
+ // (and occasionally 409) rather than an empty page.
+ if status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::CONFLICT {
+ return Ok(branches);
+ }
+ if !status.is_success() {
+ return Err(GithubError::Internal(anyhow::anyhow!(
+ "GitHub branch list failed with status {status}"
+ )));
+ }
+
+ let page_items: Vec<BranchResponse> = response.json().await.map_err(|_| {
+ GithubError::Internal(anyhow::anyhow!(
+ "GitHub branch list returned a malformed response"
+ ))
+ })?;
+ let last_page = (page_items.len() as u64) < BRANCH_PAGE_SIZE;
+ branches.extend(page_items.into_iter().map(|branch| branch.name));
+
+ if last_page || page >= BRANCH_PAGE_LIMIT {
+ return Ok(branches);
+ }
+
+ page = page.checked_add(1).ok_or_else(|| {
+ GithubError::Internal(anyhow::anyhow!(
+ "GitHub branch list pagination exceeded page limit"
+ ))
+ })?;
+ }
+ }
}
impl crate::domain::ports::GithubRepositoryClient for GithubSyncClientImpl {
diff --git a/crates/github/src/outbound/github_sync_client/test.rs b/crates/github/src/outbound/github_sync_client/test.rs
index 3cad9e5570..fb72b1ef31 100644
--- a/crates/github/src/outbound/github_sync_client/test.rs
+++ b/crates/github/src/outbound/github_sync_client/test.rs
@@ -225,3 +225,72 @@ async fn rejects_malformed_later_pagination_response_without_leaking_token() {
assert!(!error.contains("sensitive-user-token"));
assert_eq!(server.finish().len(), 2);
}
+
+#[tokio::test]
+async fn lists_repository_branches_across_pages_and_stops_on_a_short_page() {
+ let first_page: Vec<_> = (1..=100)
+ .map(|n| serde_json::json!({ "name": format!("branch-{n}") }))
+ .collect();
+ let server = MockServer::start(vec![
+ MockResponse::json(serde_json::json!(first_page)),
+ MockResponse::json(serde_json::json!([{ "name": "develop" }])),
+ ]);
+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());
+
+ let branches = client
+ .list_repository_branches("ghs-scoped", "macro-inc", "macro")
+ .await
+ .unwrap();
+
+ assert_eq!(branches.len(), 101);
+ assert_eq!(branches[0], "branch-1");
+ assert_eq!(branches[100], "develop");
+ let requests = server.finish();
+ assert!(
+ requests[0].starts_with("GET /repos/macro-inc/macro/branches?per_page=100&page=1 HTTP/1.1")
+ );
+ assert!(
+ requests[1].starts_with("GET /repos/macro-inc/macro/branches?per_page=100&page=2 HTTP/1.1")
+ );
+ for request in requests {
+ let lowercase_request = request.to_ascii_lowercase();
+ assert!(lowercase_request.contains("authorization: bearer ghs-scoped"));
+ assert!(lowercase_request.contains("accept: application/vnd.github+json"));
+ }
+}
+
+#[tokio::test]
+async fn an_empty_repository_is_an_empty_branch_list() {
+ let server = MockServer::start(vec![MockResponse {
+ status: "404 Not Found",
+ body: "{\"message\":\"Git Repository is empty.\"}".to_string(),
+ }]);
+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());
+
+ let branches = client
+ .list_repository_branches("ghs-scoped", "macro-inc", "empty")
+ .await
+ .unwrap();
+
+ assert!(branches.is_empty());
+ server.finish();
+}
+
+#[tokio::test]
+async fn rejects_an_unsuccessful_branch_list_without_leaking_the_token() {
+ let server = MockServer::start(vec![MockResponse {
+ status: "403 Forbidden",
+ body: "{\"message\":\"forbidden\"}".to_string(),
+ }]);
+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());
+
+ let error = client
+ .list_repository_branches("sensitive-install-token", "macro-inc", "macro")
+ .await
+ .unwrap_err()
+ .to_string();
+
+ assert!(error.contains("403 Forbidden"));
+ assert!(!error.contains("sensitive-install-token"));
+ server.finish();
+}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index d0f86eb4da..815dbfd582 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -87,10 +87,14 @@
GitHub**, which opens Settings → Connected. Listed recents are remembered
per user in local storage and offered first, without changing the Automatic
default. Once selected, **Branch** shows the repository's default branch (`main` when it
- has none) and opens a starting-branch field confirmed with **Use branch**;
- picking a different repository resets the branch to that repository's
- default. Omitting the branch on the create-session API likewise starts on
- the repository's default branch.
+ has none) and opens a searchable list of that repository's branches
+ (`GET /agent-repositories/branches?repoUrl=…` on the agent harness),
+ default first. Typing filters the list; an unlisted valid name adds a
+ **Use name** row. Arrow keys move the highlight and Enter or a click picks
+ it; there is no separate confirm button. Someone whose listing fails sees
+ **Retry**. Picking a different repository resets the branch to that
+ repository's default. Omitting the branch on the create-session API
+ likewise starts on the repository's default branch.
Both controls open above the drawer without clipping. The selections survive
agent changes and are sent only to coding agents. Cursor honors the explicit
repository and branch instead of choosing a repository from the prompt;
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index b5c7934b69..28ab76373c 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/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 { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';
+export type { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index 521b73a358..8964b807d4 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/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 { CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses } from './types.gen';
+import type { CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -83,6 +83,17 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * List the branches on one repository the caller can start a session from.
+ */
+ public listAgentRepositoryBranches<ThrowOnError extends boolean = false>(options: Options<ListAgentRepositoryBranchesData, ThrowOnError>): RequestResult<ListAgentRepositoryBranchesResponses, ListAgentRepositoryBranchesErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<ListAgentRepositoryBranchesResponses, ListAgentRepositoryBranchesErrors, ThrowOnError>({
+ security: [{ scheme: 'bearer', type: 'http' }],
+ url: '/agent-repositories/branches',
+ ...options
+ });
+ }
+
/**
* Read the caller's default sandbox size for new `@coder` sessions.
*/
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index a376e602f5..de299b81fe 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -110,6 +110,17 @@ export type AgentRepositoriesResponse = {
repositories: Array<AgentRepositoryDto>;
};
+/**
+ * Response body for `GET /agent-repositories/branches`.
+ */
+export type AgentRepositoryBranchesResponse = {
+ /**
+ * Branch names on the repository, in the order GitHub returned them.
+ * Empty when the repository has no commits yet.
+ */
+ branches: Array<string>;
+};
+
/**
* One repository the caller can select for a coding session.
*/
@@ -1148,6 +1159,46 @@ export type ListAgentRepositoriesResponses = {
export type ListAgentRepositoriesResponse = ListAgentRepositoriesResponses[keyof ListAgentRepositoriesResponses];
+export type ListAgentRepositoryBranchesData = {
+ body?: never;
+ path?: never;
+ query: {
+ /**
+ * Canonical https://github.com/owner/name URL
+ */
+ repoUrl: string;
+ };
+ url: '/agent-repositories/branches';
+};
+
+export type ListAgentRepositoryBranchesErrors = {
+ /**
+ * The query did not name a GitHub repository
+ */
+ 400: unknown;
+ /**
+ * Unauthenticated
+ */
+ 401: unknown;
+ /**
+ * The caller cannot reach this repository
+ */
+ 403: unknown;
+ /**
+ * GitHub could not be asked which branches the repository has
+ */
+ 502: unknown;
+};
+
+export type ListAgentRepositoryBranchesResponses = {
+ /**
+ * The repository's branches
+ */
+ 200: AgentRepositoryBranchesResponse;
+};
+
+export type ListAgentRepositoryBranchesResponse = ListAgentRepositoryBranchesResponses[keyof ListAgentRepositoryBranchesResponses];
+
export type GetAgentSandboxSizeData = {
body?: never;
path?: never;
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 42d0ef5f75..47414b47d2 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -92,6 +92,53 @@
]
}
},
+ "/agent-repositories/branches": {
+ "get": {
+ "tags": ["agent-repositories"],
+ "summary": "List the branches on one repository the caller can start a session from.",
+ "operationId": "list_agent_repository_branches",
+ "parameters": [
+ {
+ "name": "repoUrl",
+ "in": "query",
+ "description": "Canonical https://github.com/owner/name URL",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The repository's branches",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentRepositoryBranchesResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "The query did not name a GitHub repository"
+ },
+ "401": {
+ "description": "Unauthenticated"
+ },
+ "403": {
+ "description": "The caller cannot reach this repository"
+ },
+ "502": {
+ "description": "GitHub could not be asked which branches the repository has"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
"/agent-sandbox-size": {
"get": {
"tags": ["agent-sessions"],
@@ -1456,6 +1503,20 @@
}
}
},
+ "AgentRepositoryBranchesResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-repositories/branches`.",
+ "required": ["branches"],
+ "properties": {
+ "branches": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Branch names on the repository, in the order GitHub returned them.\nEmpty when the repository has no commits yet."
+ }
+ }
+ },
"AgentRepositoryDto": {
"type": "object",
"description": "One repository the caller can select for a coding session.",
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index f2235780f4..48b50e68ba 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -52,7 +52,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
/** Create a managed session, optionally delivering its first prompt. */
static async createManaged(
client: MacroClient,
- opts?: CreateManagedSessionOptions,
+ opts?: CreateManagedSessionOptions
): Promise<AgentSession> {
const { session } = unwrap(
await client.agentHarness.createAgentSession({
@@ -62,7 +62,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
repoUrl: opts?.repoUrl,
repoBranch: opts?.repoBranch,
},
- }),
+ })
);
return new AgentSession(client, session.id, session);
}
@@ -74,10 +74,10 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
* nowhere they reach.
*/
static async repositories(
- client: MacroClient,
+ client: MacroClient
): Promise<SelectableRepository[]> {
const { repositories } = unwrap(
- await client.agentHarness.listAgentRepositories(),
+ await client.agentHarness.listAgentRepositories()
);
return repositories.map((repository) => ({
url: repository.url,
@@ -85,11 +85,29 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
}));
}
+ /**
+ * Branch names on one repository the caller can start a managed session
+ * from, in the order GitHub listed them. Empty when the repository has
+ * no commits yet. `repoUrl` is one of the URLs {@link AgentSession.repositories}
+ * lists.
+ */
+ static async repositoryBranches(
+ client: MacroClient,
+ repoUrl: string
+ ): Promise<string[]> {
+ const { branches } = unwrap(
+ await client.agentHarness.listAgentRepositoryBranches({
+ query: { repoUrl },
+ })
+ );
+ return branches;
+ }
+
protected async fetch(): Promise<AgentSessionResponse> {
return unwrap(
await this.client.agentHarness.getAgentSession({
path: { session_id: this.id },
- }),
+ })
);
}
@@ -132,7 +150,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
client.agentHarness.renameAgentSession({
path: { session_id: this.id },
body: { name },
- }),
+ })
);
}
@@ -142,7 +160,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
client.agentHarness.putAgentSessionSandboxSize({
path: { session_id: this.id },
body: { size },
- }),
+ })
);
return next;
}
@@ -155,12 +173,12 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
/** Set the caller's default sandbox size for the next `@coder` mention. */
static async setDefaultSandboxSize(
client: MacroClient,
- size: SandboxSize,
+ size: SandboxSize
): Promise<SandboxSize> {
return unwrap(
await client.agentHarness.putAgentSandboxSize({
body: { size },
- }),
+ })
).size;
}
@@ -177,7 +195,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
client.agentHarness.controlAgentSession({
path: { session_id: this.id },
body: action,
- }),
+ })
);
}
@@ -190,7 +208,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
*/
prompt(
text: string,
- attachments?: PromptAttachment[],
+ attachments?: PromptAttachment[]
): Promise<ControlResponse> {
return this.control({
type: 'prompt',
@@ -207,10 +225,10 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
const { entries } = unwrap(
await this.client.agentHarness.getAgentSessionQueue({
path: { session_id: this.id },
- }),
+ })
);
return entries.map((entry) =>
- QueuedAction.from(this.client, this.id, entry),
+ QueuedAction.from(this.client, this.id, entry)
);
}
@@ -219,7 +237,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
return unwrap(
await this.client.agentHarness.getAgentSessionChanges({
path: { session_id: this.id },
- }),
+ })
);
}
@@ -228,7 +246,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
return unwrap(
await this.client.agentHarness.getAgentSessionChangesPatch({
path: { session_id: this.id },
- }),
+ })
).patch;
}
@@ -237,7 +255,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
return this.mutate((client) =>
client.agentHarness.refreshAgentSessionChanges({
path: { session_id: this.id },
- }),
+ })
);
}
@@ -246,7 +264,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
return unwrap(
await this.client.agentHarness.getAgentSessionLog({
path: { session_id: this.id },
- }),
+ })
);
}
@@ -255,7 +273,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
await this.mutate((client) =>
client.agentHarness.deleteAgentSession({
path: { session_id: this.id },
- }),
+ })
);
}
}
diff --git a/packages/sdk/src/entities/agent-sessions/namespace.ts b/packages/sdk/src/entities/agent-sessions/namespace.ts
index fd961ed605..5855c2be2d 100644
--- a/packages/sdk/src/entities/agent-sessions/namespace.ts
+++ b/packages/sdk/src/entities/agent-sessions/namespace.ts
@@ -28,6 +28,15 @@ export class AgentSessionNamespace {
return AgentSession.repositories(this.client);
}
+ /**
+ * Branch names on one repository the caller can start a managed session
+ * from. `repoUrl` is one of the URLs {@link AgentSessionNamespace.repositories}
+ * lists.
+ */
+ repositoryBranches(repoUrl: string): Promise<string[]> {
+ return AgentSession.repositoryBranches(this.client, repoUrl);
+ }
+
/** The caller's default sandbox size for new `@coder` sessions. */
defaultSandboxSize(): Promise<SandboxSize> {
return AgentSession.defaultSandboxSize(this.client);
diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.ts
index 99f9064632..2291820062 100644
--- a/packages/sdk/tests/agent-sessions.test.ts
+++ b/packages/sdk/tests/agent-sessions.test.ts
@@ -70,8 +70,8 @@ describe('AgentSession', () => {
expect(
requests.every(
(request) =>
- request.headers.get('authorization') === 'Bearer user-token',
- ),
+ request.headers.get('authorization') === 'Bearer user-token'
+ )
).toBe(true);
});
@@ -112,7 +112,7 @@ describe('AgentSession', () => {
expect(request?.method).toBe('PUT');
expect(request?.url).toBe(
- `https://agent.example.test/agent-sessions/${sessionId}/name`,
+ `https://agent.example.test/agent-sessions/${sessionId}/name`
);
expect(request?.headers.get('authorization')).toBe('Bearer user-token');
await expect(request?.json()).resolves.toEqual({ name: 'Fix Flaky Tests' });
@@ -130,12 +130,12 @@ describe('AgentSession', () => {
});
await expect(
- macro.agentSessions.byId(sessionId).setSandboxSize('large'),
+ macro.agentSessions.byId(sessionId).setSandboxSize('large')
).resolves.toBe('large');
expect(request?.method).toBe('PUT');
expect(request?.url).toBe(
- `https://agent.example.test/agent-sessions/${sessionId}/sandbox-size`,
+ `https://agent.example.test/agent-sessions/${sessionId}/sandbox-size`
);
await expect(request?.json()).resolves.toEqual({ size: 'large' });
});
@@ -153,10 +153,10 @@ describe('AgentSession', () => {
});
await expect(macro.agentSessions.defaultSandboxSize()).resolves.toBe(
- 'small',
+ 'small'
);
await expect(
- macro.agentSessions.setDefaultSandboxSize('small'),
+ macro.agentSessions.setDefaultSandboxSize('small')
).resolves.toBe('small');
expect(requests.map((request) => request.method)).toEqual(['GET', 'PUT']);
@@ -166,6 +166,30 @@ describe('AgentSession', () => {
]);
});
+ test('lists one repository branches through the agent-harness service', async () => {
+ let request: Request | undefined;
+ globalThis.fetch = (async (input) => {
+ request = input instanceof Request ? input : new Request(input);
+ return Response.json({ branches: ['main', 'develop'] }, { status: 200 });
+ }) as typeof fetch;
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { 'agent-harness': 'https://agent.example.test' },
+ });
+
+ await expect(
+ macro.agentSessions.repositoryBranches(
+ 'https://github.com/macro-inc/macro'
+ )
+ ).resolves.toEqual(['main', 'develop']);
+
+ expect(request?.method).toBe('GET');
+ expect(request?.url).toBe(
+ 'https://agent.example.test/agent-repositories/branches?repoUrl=https%3A%2F%2Fgithub.com%2Fmacro-inc%2Fmacro'
+ );
+ expect(request?.headers.get('authorization')).toBe('Bearer user-token');
+ });
+
test('wraps managed creation, control, logs, and deletion', async () => {
const requests: Request[] = [];
globalThis.fetch = (async (input) => {
@@ -180,7 +204,7 @@ describe('AgentSession', () => {
if (request.url.endsWith('/control')) {
return Response.json(
{ actionId: '0198a4cc-e138-7670-a308-a6b766602702', status: 'sent' },
- { status: 200 },
+ { status: 200 }
);
}
if (request.url.endsWith('/log')) {
@@ -189,7 +213,7 @@ describe('AgentSession', () => {
bot: { id: session.botId, name: 'Agent', handle: 'agent' },
entries: [],
},
- { status: 200 },
+ { status: 200 }
);
}
return new Response(null, { status: 200 });
@@ -227,7 +251,7 @@ describe('AgentSession', () => {
actionId: '0198a4cc-e138-7670-a308-a6b766602703',
status: 'queued',
},
- { status: 200 },
+ { status: 200 }
);
}) as typeof fetch;
const macro = new Macro({
@@ -236,7 +260,7 @@ describe('AgentSession', () => {
});
await expect(
- macro.agentSessions.byId(sessionId).prompt('Fix the flaky test'),
+ macro.agentSessions.byId(sessionId).prompt('Fix the flaky test')
).resolves.toEqual({
actionId: '0198a4cc-e138-7670-a308-a6b766602703',
status: 'queued',
@@ -244,7 +268,7 @@ describe('AgentSession', () => {
expect(request?.method).toBe('POST');
expect(request?.url).toBe(
- `https://agent.example.test/agent-sessions/${sessionId}/control`,
+ `https://agent.example.test/agent-sessions/${sessionId}/control`
);
await expect(request?.json()).resolves.toEqual({
type: 'prompt',
@@ -271,7 +295,7 @@ describe('AgentSession', () => {
},
],
},
- { status: 200 },
+ { status: 200 }
);
}
return new Response(null, { status: 204 });
@@ -297,13 +321,13 @@ describe('AgentSession', () => {
'DELETE',
]);
expect(requests[1]?.url).toBe(
- `https://agent.example.test/agent-sessions/${sessionId}/queue/${actionId}`,
+ `https://agent.example.test/agent-sessions/${sessionId}/queue/${actionId}`
);
await expect(requests[1]?.json()).resolves.toEqual({
prompt: 'Also update the README',
});
expect(requests[2]?.url).toBe(
- `https://agent.example.test/agent-sessions/${sessionId}/queue/${actionId}`,
+ `https://agent.example.test/agent-sessions/${sessionId}/queue/${actionId}`
);
});
});
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 682e333b72..41a8a59590 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -9,7 +9,9 @@ use agent_harness::inbound::model_load::{
self, AgentModelDto, AgentModelsStatusDto, LoadAgentModelsRequest, LoadAgentModelsResponse,
ModelHarnessDto,
};
-use agent_harness::inbound::repositories::{self, AgentRepositoriesResponse, AgentRepositoryDto};
+use agent_harness::inbound::repositories::{
+ self, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto,
+};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, PromptAttachment};
use agent_session::domain::model::{SandboxSize, SessionBot};
use agent_session::inbound::axum_router::{
@@ -63,6 +65,7 @@ impl Modify for SecurityAddon {
axum_router::put_agent_sandbox_size_handler,
model_load::load_agent_models_handler,
repositories::list_agent_repositories_handler,
+ repositories::list_agent_repository_branches_handler,
changes_router::get_agent_session_changes_handler,
changes_router::get_agent_session_changes_patch_handler,
changes_router::refresh_agent_session_changes_handler,
@@ -105,6 +108,7 @@ impl Modify for SecurityAddon {
AgentModelsStatusDto,
ModelHarnessDto,
AgentRepositoriesResponse,
+ AgentRepositoryBranchesResponse,
AgentRepositoryDto,
AgentSessionChangesResponse,
AgentSessionChangesPatchResponse,
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index a87e0eda31..4401f6ff4b 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -61,6 +61,7 @@ use agent_harness::outbound::daytona::{
};
use agent_harness::outbound::egress::EgressProvisioner;
use agent_harness::outbound::forward::RedisCommandForwarder;
+use agent_harness::outbound::github_branches::GithubRepositoryBranches;
use agent_harness::outbound::github_repositories::GithubReachableRepositories;
use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};
use agent_harness::outbound::notifications::IngressAgentSessionNotifier;
@@ -473,12 +474,20 @@ async fn run() -> anyhow::Result<()> {
// Which repositories a session may work on is the owner's question, not
// the deployment's: the same App credentials the egress proxy mints tokens
// with, read in the other direction - from the user to their installations.
+ let github_token_config = InstallationTokenConfig {
+ client_id: config.github_sync_app_client_id.clone(),
+ private_key_pem: config.github_sync_app_pem_secret_key.as_ref().to_owned(),
+ };
let reachable_repositories = Arc::new(GithubReachableRepositories::new(
ReachableRepositoriesService::new(
- InstallationTokenConfig {
- client_id: config.github_sync_app_client_id.clone(),
- private_key_pem: config.github_sync_app_pem_secret_key.as_ref().to_owned(),
- },
+ github_token_config.clone(),
+ PgGithubSyncRepo::new(pool.clone()),
+ GithubSyncClientImpl::default(),
+ ),
+ ));
+ let repository_branches = Arc::new(GithubRepositoryBranches::new(
+ InstallationTokenService::new(
+ github_token_config,
PgGithubSyncRepo::new(pool.clone()),
GithubSyncClientImpl::default(),
),
@@ -989,6 +998,7 @@ async fn run() -> anyhow::Result<()> {
// Served to the app by `GET /agent-repositories`; see `open_repositories`.
let repositories_state = AgentRepositoriesRouterState::new(
reachable_repositories,
+ repository_branches,
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
);
let http_runtime_commands_readiness = runtime_commands_readiness.clone();