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: coding agent repo selection discovery (#6604)

Eric Hayesc7d88c711446
diff --git a/Cargo.lock b/Cargo.lock
index dc21efc13a..83cfc0234f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -295,6 +295,7 @@ dependencies = [
"tokio",
"tokio-tungstenite 0.28.0",
"tokio-util",
+ "tower 0.5.3",
"tracing",
"tracing-opentelemetry",
"url",
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 108ac621fe..431929264c 100644
--- a/apps/web/src/features/agents-view/core/repository.test.ts
+++ b/apps/web/src/features/agents-view/core/repository.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
import {
+ defaultBranchFor,
+ filterRepositories,
+ orderRepositories,
parseRepositoryInput,
+ type ReachableRepository,
repositoryLabel,
repositoryShortName,
} from './repository';
@@ -51,3 +55,65 @@ describe('repository names', () => {
);
});
});
+
+const macro: ReachableRepository = {
+ url: 'https://github.com/macro-inc/macro',
+ defaultBranch: 'main',
+};
+const infra: ReachableRepository = {
+ url: 'https://github.com/macro-inc/infra',
+ defaultBranch: 'develop',
+};
+const scratch: ReachableRepository = {
+ url: 'https://github.com/macro-inc/scratch',
+};
+
+describe('orderRepositories', () => {
+ it('puts recents first, in their order, then the rest as listed', () => {
+ expect(orderRepositories([infra, macro, scratch], [scratch.url])).toEqual([
+ scratch,
+ infra,
+ macro,
+ ]);
+ });
+
+ it('keeps a recent the listing no longer carries, and dedupes by spelling', () => {
+ expect(
+ orderRepositories(
+ [macro],
+ [
+ 'https://github.com/macro-inc/gone',
+ 'https://github.com/Macro-Inc/MACRO',
+ ]
+ )
+ ).toEqual([{ url: 'https://github.com/macro-inc/gone' }, macro]);
+ });
+});
+
+describe('filterRepositories', () => {
+ it('matches the owner/repo label and the url, ignoring case', () => {
+ const all = [macro, infra, scratch];
+ expect(filterRepositories(all, '')).toEqual(all);
+ expect(filterRepositories(all, 'INFRA')).toEqual([infra]);
+ expect(filterRepositories(all, 'macro-inc/s')).toEqual([scratch]);
+ expect(filterRepositories(all, 'github.com/macro-inc/macro')).toEqual([
+ macro,
+ ]);
+ expect(filterRepositories(all, 'nothing')).toEqual([]);
+ });
+});
+
+describe('defaultBranchFor', () => {
+ it("starts on the repository's default branch, or main without one", () => {
+ const all = [macro, infra, scratch];
+ expect(defaultBranchFor(all, infra.url)).toBe('develop');
+ expect(defaultBranchFor(all, 'https://github.com/Macro-Inc/Infra')).toBe(
+ 'develop'
+ );
+ expect(defaultBranchFor(all, scratch.url)).toBe('main');
+ expect(defaultBranchFor(all, 'https://github.com/macro-inc/unlisted')).toBe(
+ 'main'
+ );
+ expect(defaultBranchFor(all, undefined)).toBe('main');
+ });
+});
diff --git a/apps/web/src/features/agents-view/core/repository.ts b/apps/web/src/features/agents-view/core/repository.ts
index 0cbd851ace..5818c5236e 100644
--- a/apps/web/src/features/agents-view/core/repository.ts
+++ b/apps/web/src/features/agents-view/core/repository.ts
@@ -71,3 +71,80 @@ export function validRepositoryBranch(branch: string): boolean {
)
);
}
+
+/** A repository the signed-in user can hand a coder, as the harness lists it. */
+export type ReachableRepository = {
+ /** The canonical https URL, the form the create-session API accepts. */
+ url: string;
+ /** The branch its clones check out; absent for a repository with no commits. */
+ defaultBranch?: string;
+};
+
+/** The branch a coder starts on when the repository has none to offer. */
+const FALLBACK_BRANCH = 'main';
+
+/** GitHub treats owner and repository names case-insensitively, so two spellings are one repository. */
+export function sameRepository(left: string, right: string): boolean {
+ return left.toLowerCase() === right.toLowerCase();
+}
+
+/**
+ * The repositories to offer: recents first, in their own order, then every
+ * other reachable repository as the harness sorted it. A recent the listing
+ * no longer carries stays offered - the service, not this list, decides what
+ * a session may use, and it says so when it refuses.
+ */
+export function orderRepositories(
+ reachable: readonly ReachableRepository[],
+ recents: readonly string[]
+): ReachableRepository[] {
+ const ordered: ReachableRepository[] = [];
+ const seen = new Set<string>();
+ const add = (repository: ReachableRepository) => {
+ const key = repository.url.toLowerCase();
+ if (seen.has(key)) return;
+ seen.add(key);
+ ordered.push(repository);
+ };
+ for (const url of recents) {
+ add(
+ reachable.find((repository) => sameRepository(repository.url, url)) ?? {
+ url,
+ }
+ );
+ }
+ for (const repository of reachable) add(repository);
+ return ordered;
+}
+
+/**
+ * Repositories whose `owner/repo` label or URL contains `search`, ignoring
+ * case; every repository for blank text.
+ */
+export function filterRepositories(
+ repositories: readonly ReachableRepository[],
+ search: string
+): ReachableRepository[] {
+ const needle = search.trim().toLowerCase();
+ if (!needle) return [...repositories];
+ return repositories.filter(
+ (repository) =>
+ repositoryLabel(repository.url).toLowerCase().includes(needle) ||
+ repository.url.toLowerCase().includes(needle)
+ );
+}
+
+/**
+ * The branch a coder starts on for `url` when none was chosen: the
+ * repository's own default branch, or `main` when it is unknown or unlisted.
+ */
+export function defaultBranchFor(
+ repositories: readonly ReachableRepository[],
+ url: string | undefined
+): string {
+ if (!url) return FALLBACK_BRANCH;
+ return (
+ repositories.find((repository) => sameRepository(repository.url, url))
+ ?.defaultBranch ?? FALLBACK_BRANCH
+ );
+}
diff --git a/apps/web/src/features/agents-view/primitives/recent-repositories.ts b/apps/web/src/features/agents-view/primitives/recent-repositories.ts
index 5bf0d31476..41cb943499 100644
--- a/apps/web/src/features/agents-view/primitives/recent-repositories.ts
+++ b/apps/web/src/features/agents-view/primitives/recent-repositories.ts
@@ -6,8 +6,8 @@ const RECENT_REPOSITORY_LIMIT = 8;
/**
* Repositories handed to coders from this composer, newest first and scoped
- * to the signed-in user. There is no server-side list of a person's
- * repositories yet, so the ones they have typed are the recents.
+ * to the signed-in user. The picker offers them ahead of the GitHub App's
+ * full listing, and the newest is where the next session starts.
*/
export function createRecentRepositories(userId: string | undefined) {
const storage = createUserScopedStorage('agents-view-repositories-v1');
diff --git a/apps/web/src/features/agents-view/queries/reachable-repositories.ts b/apps/web/src/features/agents-view/queries/reachable-repositories.ts
new file mode 100644
index 0000000000..4bb0c1268f
--- /dev/null
+++ b/apps/web/src/features/agents-view/queries/reachable-repositories.ts
@@ -0,0 +1,37 @@
+import { useAgentRepositoriesQuery } from '@queries/agent-repositories/repositories';
+import { type Accessor, createMemo } from 'solid-js';
+import type { ReachableRepository } from '../core/repository';
+
+export type ReachableRepositoriesSource = {
+ /** Every repository the caller can hand a coder, as the harness sorted them. */
+ repositories: Accessor<ReachableRepository[]>;
+ /** 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 the caller's reachable repositories. Reads are
+ * status-gated so a pending listing never suspends the composer around it.
+ */
+export function createReachableRepositories(
+ enabled: Accessor<boolean>
+): ReachableRepositoriesSource {
+ const query = useAgentRepositoriesQuery(enabled);
+ const repositories = createMemo<ReachableRepository[]>(() =>
+ query.isSuccess
+ ? query.data.repositories.map((repository) => ({
+ url: repository.url,
+ defaultBranch: repository.defaultBranch ?? undefined,
+ }))
+ : []
+ );
+ return {
+ repositories,
+ 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 0a619d253d..a6af6d41fb 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
@@ -16,6 +16,7 @@ import { NewChatPage } from './NewChatPage';
const mocks = vi.hoisted(() => ({
openSettings: vi.fn(),
recentIds: [] as string[],
+ repositories: [] as { url: string; defaultBranch?: string }[],
}));
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user' }));
vi.mock('@core/constant/SettingsState', () => ({
@@ -30,6 +31,14 @@ vi.mock('@app/features/block-agent/context/recent-agent-selections', () => ({
vi.mock('../primitives/recent-repositories', () => ({
createRecentRepositories: () => ({ urls: () => [], remember: vi.fn() }),
}));
+vi.mock('../queries/reachable-repositories', () => ({
+ createReachableRepositories: () => ({
+ repositories: () => mocks.repositories,
+ loading: () => false,
+ error: () => false,
+ retry: vi.fn(),
+ }),
+}));
vi.mock('../components/AgentGlyph', () => ({ AgentIcon: () => <span /> }));
vi.mock('@queries/agents/models', () => ({
@@ -140,6 +149,9 @@ describe('agent-led new conversation', () => {
let motionStyles: HTMLStyleElement;
beforeEach(() => {
mocks.recentIds = [MACRO_CODER_BOT_ID];
+ mocks.repositories = [
+ { url: 'https://github.com/macro-inc/macro', defaultBranch: 'develop' },
+ ];
vi.clearAllMocks();
motionStyles = document.createElement('style');
motionStyles.textContent =
@@ -185,10 +197,11 @@ describe('agent-led new conversation', () => {
).toBeTruthy();
expect(screen.getByTestId('drawer').hasAttribute('hidden')).toBe(false);
fireEvent.click(screen.getByRole('button', { name: 'Repository' }));
- fireEvent.input(screen.getByRole('textbox', { name: 'Add repository' }), {
- target: { value: 'macro-inc/macro' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Use repository' }));
+ fireEvent.click(screen.getByRole('option', { name: 'macro-inc/macro' }));
+ // The listed repository's own default branch, until one is chosen.
+ expect(
+ 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' },
@@ -216,6 +229,51 @@ describe('agent-led new conversation', () => {
repoBranch: 'feature/home',
});
});
+ it('starts a typed repository on main and a listed one on its default branch', async () => {
+ const send = page();
+ await selectAgent(/Cursor/);
+ fireEvent.click(screen.getByRole('button', { name: 'Repository' }));
+ fireEvent.input(
+ screen.getByRole('combobox', { name: 'Search repositories' }),
+ {
+ target: { value: 'macro-inc/other' },
+ }
+ );
+ expect(
+ screen.queryByRole('option', { name: 'Choose automatically' })
+ ).toBeNull();
+ fireEvent.click(
+ screen.getByRole('option', { name: 'Use macro-inc/other' })
+ );
+ expect(
+ screen.getByRole('button', { name: 'Branch' }).textContent
+ ).toContain('main');
+ fireEvent.click(screen.getByRole('button', { name: 'Branch' }));
+ fireEvent.input(screen.getByRole('textbox', { name: 'Starting branch' }), {
+ target: { value: 'feature/other' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Use branch' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));
+ expect(send).toHaveBeenLastCalledWith({
+ botId: CURSOR_BOT_ID,
+ prompt: 'Prompt',
+ repoUrl: 'https://github.com/macro-inc/other',
+ repoBranch: 'feature/other',
+ });
+ // Another repository drops the chosen branch for its own default.
+ fireEvent.click(screen.getByRole('button', { name: 'Repository' }));
+ fireEvent.click(screen.getByRole('option', { name: 'macro-inc/macro' }));
+ expect(
+ screen.getByRole('button', { name: 'Branch' }).textContent
+ ).toContain('develop');
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));
+ expect(send).toHaveBeenLastCalledWith({
+ botId: CURSOR_BOT_ID,
+ prompt: 'Prompt',
+ repoUrl: 'https://github.com/macro-inc/macro',
+ repoBranch: 'develop',
+ });
+ });
it('uses a saved agent without sending a per-session model override', async () => {
const send = page(true, [
{
@@ -249,10 +307,7 @@ describe('agent-led new conversation', () => {
]);
await selectAgent(/Cursor/);
fireEvent.click(screen.getByRole('button', { name: 'Repository' }));
- fireEvent.input(screen.getByRole('textbox', { name: 'Add repository' }), {
- target: { value: 'macro-inc/macro' },
- });
- fireEvent.click(screen.getByRole('button', { name: 'Use repository' }));
+ fireEvent.click(screen.getByRole('option', { name: 'macro-inc/macro' }));
await selectAgent(/Cloud reviewer/);
expect(screen.getByTestId('drawer').hasAttribute('hidden')).toBe(false);
expect(screen.getByRole('button', { name: 'Repository' })).toBeTruthy();
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.tsx b/apps/web/src/features/agents-view/views/NewChatPage.tsx
index 223ab1d152..fcdccbff31 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.tsx
@@ -4,8 +4,10 @@ import { useUserId } from '@core/context/user';
import { createMemo, createSignal } from 'solid-js';
import { ChatComposer } from '../components/ChatComposer';
import type { AgentKind } from '../core/agent-kind';
+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 { AgentPicker } from './AgentPicker';
import { RepositoryPicker } from './RepositoryPicker';
@@ -38,6 +40,7 @@ export function NewChatPage(props: {
const options = () => props.roster;
const [agentId, setAgentId] = createSignal<string>();
const [modelOverride, setModelOverride] = createSignal<string>();
+ // The last repository handed to a coder is where the next one starts.
const [repoUrl, setRepoUrl] = createSignal<string | undefined>(
repositories.urls()[0]
);
@@ -45,7 +48,7 @@ export function NewChatPage(props: {
const draft = () => props.draft ?? localDraft();
const setDraft = (text: string) =>
props.onDraftChange ? props.onDraftChange(text) : setLocalDraft(text);
- const [repoBranch, setRepoBranch] = createSignal('main');
+ const [branchOverride, setBranchOverride] = createSignal<string>();
const selected = createMemo(() => {
const wanted =
agentId() ??
@@ -64,6 +67,17 @@ export function NewChatPage(props: {
const agent = selected();
return agent ? agent.unavailableReason : 'Choose an agent to start';
};
+ // Listed only while the drawer can show them: chat agents never ask.
+ const reachable = createReachableRepositories(coding);
+ // A chosen branch, or where the selected repository's own clones start.
+ const repoBranch = () =>
+ branchOverride() ?? defaultBranchFor(reachable.repositories(), repoUrl());
+ const selectRepository = (url: string | undefined) => {
+ // Another repository starts on its own default branch, not the last one's.
+ if (url !== repoUrl()) setBranchOverride(undefined);
+ setRepoUrl(url);
+ if (url) repositories.remember(url);
+ };
const connect = (agent: RosterAgent) => {
if (agent.harness === 'cursor') openSettings('Harness');
@@ -119,12 +133,14 @@ export function NewChatPage(props: {
<RepositoryPicker
repoUrl={repoUrl()}
branch={repoBranch()}
+ repositories={reachable.repositories()}
+ repositoriesLoading={reachable.loading()}
+ repositoriesError={reachable.error()}
recentRepositories={repositories.urls()}
- onSelect={(url, branch) => {
- setRepoUrl(url);
- setRepoBranch(branch);
- if (url) repositories.remember(url);
- }}
+ onRetryRepositories={reachable.retry}
+ onConnectGitHub={() => openSettings('Connected')}
+ onSelectRepository={selectRepository}
+ onSelectBranch={setBranchOverride}
/>
}
drawerOpen={coding()}
diff --git a/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx b/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
new file mode 100644
index 0000000000..743c400ba9
--- /dev/null
+++ b/apps/web/src/features/agents-view/views/RepositoryPicker.test.tsx
@@ -0,0 +1,183 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ReachableRepository } from '../core/repository';
+import { RepositoryPicker } from './RepositoryPicker';
+
+const macro: ReachableRepository = {
+ url: 'https://github.com/macro-inc/macro',
+ defaultBranch: 'main',
+};
+const infra: ReachableRepository = {
+ url: 'https://github.com/macro-inc/infra',
+ defaultBranch: 'develop',
+};
+
+function picker(
+ overrides: Partial<Parameters<typeof RepositoryPicker>[0]> = {}
+) {
+ const handlers = {
+ onSelectRepository: vi.fn(),
+ onSelectBranch: vi.fn(),
+ onRetryRepositories: vi.fn(),
+ onConnectGitHub: vi.fn(),
+ };
+ render(() => (
+ <RepositoryPicker
+ branch="main"
+ repositories={[macro, infra]}
+ repositoriesLoading={false}
+ repositoriesError={false}
+ recentRepositories={[]}
+ {...handlers}
+ {...overrides}
+ />
+ ));
+ return handlers;
+}
+const openRepositories = () =>
+ fireEvent.click(screen.getByRole('button', { name: 'Repository' }));
+const search = () =>
+ screen.getByRole('combobox', { name: 'Search repositories' });
+const optionNames = () =>
+ screen.getAllByRole('option').map((option) => option.textContent?.trim());
+
+describe('RepositoryPicker', () => {
+ beforeEach(() => vi.stubGlobal('scrollTo', vi.fn()));
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it('lists automatic first, then recents, then the rest, marking the selection', () => {
+ picker({ repoUrl: infra.url, recentRepositories: [infra.url] });
+ expect(
+ screen.getByRole('button', { name: 'Repository' }).textContent
+ ).toContain('macro-inc/infra');
+ openRepositories();
+ expect(optionNames()).toEqual([
+ 'Choose automatically',
+ 'macro-inc/infra',
+ 'macro-inc/macro',
+ ]);
+ const selected = screen.getByRole('option', { name: 'macro-inc/infra' });
+ expect(selected.querySelector('svg.ml-auto')).toBeTruthy();
+ expect(
+ screen
+ .getByRole('option', { name: 'macro-inc/macro' })
+ .querySelector('svg.ml-auto')
+ ).toBeNull();
+ });
+
+ it('filters as you type and picks the highlighted match on Enter', () => {
+ const handlers = picker();
+ openRepositories();
+ fireEvent.input(search(), { target: { value: 'INFRA' } });
+ expect(optionNames()).toEqual(['macro-inc/infra']);
+ fireEvent.submit(search().closest('form') as HTMLFormElement);
+ expect(handlers.onSelectRepository).toHaveBeenCalledWith(infra.url);
+ });
+
+ it('moves the highlight with the arrow keys', () => {
+ const handlers = picker();
+ openRepositories();
+ expect(
+ screen
+ .getByRole('option', { name: 'Choose automatically' })
+ .getAttribute('aria-selected')
+ ).toBe('true');
+ fireEvent.keyDown(search(), { key: 'ArrowDown' });
+ fireEvent.keyDown(search(), { key: 'ArrowDown' });
+ expect(
+ screen
+ .getByRole('option', { name: 'macro-inc/infra' })
+ .getAttribute('aria-selected')
+ ).toBe('true');
+ fireEvent.keyDown(search(), { key: 'ArrowUp' });
+ fireEvent.submit(search().closest('form') as HTMLFormElement);
+ expect(handlers.onSelectRepository).toHaveBeenCalledWith(macro.url);
+ });
+
+ it('offers an unlisted GitHub repository typed by hand, canonicalized', () => {
+ const handlers = picker();
+ openRepositories();
+ fireEvent.input(search(), {
+ target: { value: 'https://github.com/macro-inc/other.git' },
+ });
+ expect(optionNames()).toEqual(['Use macro-inc/other']);
+ fireEvent.click(
+ screen.getByRole('option', { name: 'Use macro-inc/other' })
+ );
+ expect(handlers.onSelectRepository).toHaveBeenCalledWith(
+ 'https://github.com/macro-inc/other'
+ );
+ });
+
+ it('does not duplicate a listed repository typed in full', () => {
+ picker();
+ openRepositories();
+ fireEvent.input(search(), { target: { value: 'macro-inc/macro' } });
+ expect(optionNames()).toEqual(['macro-inc/macro']);
+ });
+
+ it('explains when nothing matches and refuses to submit text that names no repository', () => {
+ const handlers = picker();
+ openRepositories();
+ fireEvent.input(search(), { target: { value: 'nothing here' } });
+ expect(screen.queryAllByRole('option')).toHaveLength(0);
+ expect(screen.getByText(/No repositories match/).textContent).toContain(
+ 'nothing here'
+ );
+ fireEvent.submit(search().closest('form') as HTMLFormElement);
+ expect(screen.getByRole('alert').textContent).toContain('owner/repo');
+ expect(handlers.onSelectRepository).not.toHaveBeenCalled();
+ });
+
+ it('leaves the choice to the coder with Choose automatically', () => {
+ const handlers = picker({ repoUrl: macro.url });
+ openRepositories();
+ fireEvent.click(
+ screen.getByRole('option', { name: 'Choose automatically' })
+ );
+ expect(handlers.onSelectRepository).toHaveBeenCalledWith(undefined);
+ });
+
+ it('shows the loading, failed, and empty listings', () => {
+ const handlers = picker({ repositories: [], repositoriesLoading: true });
+ openRepositories();
+ expect(screen.getByText('Loading your repositories…')).toBeTruthy();
+ cleanup();
+
+ const failed = picker({ repositories: [], repositoriesError: true });
+ openRepositories();
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(failed.onRetryRepositories).toHaveBeenCalledOnce();
+ cleanup();
+
+ const empty = picker({ repositories: [] });
+ openRepositories();
+ expect(screen.getByText(/No repositories yet/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Connect GitHub' }));
+ expect(empty.onConnectGitHub).toHaveBeenCalledOnce();
+ expect(handlers.onSelectRepository).not.toHaveBeenCalled();
+ });
+
+ it('shows the branch only with a repository and validates the one typed', () => {
+ expect(picker().onSelectBranch).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'Branch' })).toBeNull();
+ cleanup();
+
+ const handlers = picker({ repoUrl: infra.url, branch: 'develop' });
+ 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');
+ fireEvent.input(field, { target: { value: 'bad..name' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Use branch' }));
+ expect(screen.getByRole('alert')).toBeTruthy();
+ 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');
+ });
+});
diff --git a/apps/web/src/features/agents-view/views/RepositoryPicker.tsx b/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
index a6eeb8bdd9..a8c6cd6e32 100644
--- a/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
+++ b/apps/web/src/features/agents-view/views/RepositoryPicker.tsx
@@ -3,38 +3,112 @@ import CaretDownIcon from '@phosphor/caret-down.svg';
import CheckIcon from '@phosphor/check.svg';
import GitBranchIcon from '@phosphor/git-branch.svg';
import GithubIcon from '@phosphor/github-logo.svg';
-import { Button } from '@ui';
-import { createSignal, For, Show } from 'solid-js';
+import { Button, createCommandListController } from '@ui';
import {
+ createMemo,
+ createSignal,
+ createUniqueId,
+ For,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import { match } from 'ts-pattern';
+import {
+ filterRepositories,
+ orderRepositories,
parseRepositoryInput,
+ type ReachableRepository,
repositoryLabel,
+ sameRepository,
validRepositoryBranch,
} from '../core/repository';
+/** One row of the repository list. */
+type RepositoryChoice =
+ | { kind: 'automatic' }
+ | { kind: 'listed'; url: string }
+ /** Named by hand rather than listed; the service decides whether it may be used. */
+ | { kind: 'typed'; url: string };
+
/** Explicit, portaled repository/branch controls shared by Home and Agents. */
export function RepositoryPicker(props: {
repoUrl?: string;
branch: string;
+ /** Every repository the signed-in user reaches through Macro's GitHub App. */
+ repositories: ReachableRepository[];
+ repositoriesLoading: boolean;
+ repositoriesError: boolean;
+ /** Repositories handed to coders before, newest first; offered ahead of the rest. */
recentRepositories: string[];
- onSelect: (url: string | undefined, branch: string) => void;
+ onRetryRepositories: () => void;
+ /** Where to send someone who reaches no repository yet. */
+ onConnectGitHub?: () => void;
+ /** `undefined` leaves the choice to the coder. */
+ onSelectRepository: (url: string | undefined) => void;
+ onSelectBranch: (branch: string) => void;
}) {
+ const listId = createUniqueId();
const [repoOpen, setRepoOpen] = createSignal(false);
const [branchOpen, setBranchOpen] = createSignal(false);
- const [repoInput, setRepoInput] = createSignal('');
+ const [search, setSearch] = createSignal('');
const [branchInput, setBranchInput] = createSignal('');
const [error, setError] = createSignal('');
- const selectRepo = (url: string | undefined) => {
- props.onSelect(url, url === props.repoUrl ? props.branch : 'main');
+
+ const offered = createMemo(() =>
+ orderRepositories(props.repositories, props.recentRepositories)
+ );
+ const choices = createMemo<RepositoryChoice[]>(() => {
+ const text = search().trim();
+ const listed = filterRepositories(offered(), text);
+ const choices: RepositoryChoice[] = text ? [] : [{ kind: 'automatic' }];
+ for (const repository of listed) {
+ choices.push({ kind: 'listed', url: repository.url });
+ }
+ const typed = parseRepositoryInput(text);
+ if (
+ typed?.startsWith('https://github.com/') &&
+ !listed.some((repository) => sameRepository(repository.url, typed))
+ ) {
+ choices.push({ kind: 'typed', url: typed });
+ }
+ return choices;
+ });
+ const choose = (choice: RepositoryChoice) => {
+ props.onSelectRepository(
+ choice.kind === 'automatic' ? undefined : choice.url
+ );
setRepoOpen(false);
};
- const applyRepo = () => {
- const url = parseRepositoryInput(repoInput());
- if (!url || !url.startsWith('https://github.com/')) {
- setError('Enter a GitHub repository as owner/repo or a repository URL.');
- return;
- }
- selectRepo(url);
+ const list = createCommandListController<RepositoryChoice>({
+ items: choices,
+ onSelect: choose,
+ });
+ const highlightedId = () => `${listId}-${list.selectedIndex()}`;
+ const scrollHighlightedIntoView = () =>
+ document.getElementById(highlightedId())?.scrollIntoView?.({
+ block: 'nearest',
+ });
+ const submitRepository = () => {
+ if (list.selectSelected()) return;
+ setError('Enter a GitHub repository as owner/repo or a repository URL.');
};
+ const chosen = (choice: RepositoryChoice) =>
+ choice.kind === 'automatic'
+ ? !props.repoUrl
+ : !!props.repoUrl && sameRepository(props.repoUrl, choice.url);
+ const rowLabel = (choice: RepositoryChoice) =>
+ match(choice)
+ .with({ kind: 'automatic' }, () => 'Choose automatically')
+ .with({ kind: 'listed' }, ({ url }) => repositoryLabel(url))
+ .with({ kind: 'typed' }, ({ url }) => `Use ${repositoryLabel(url)}`)
+ .exhaustive();
+ const nothingReachable = () =>
+ !props.repositoriesLoading &&
+ !props.repositoriesError &&
+ offered().length === 0 &&
+ !search().trim();
+
const applyBranch = () => {
const branch = branchInput().trim();
if (!validRepositoryBranch(branch)) {
@@ -43,7 +117,7 @@ export function RepositoryPicker(props: {
);
return;
}
- props.onSelect(props.repoUrl, branch);
+ props.onSelectBranch(branch);
setBranchOpen(false);
};
return (
@@ -53,7 +127,10 @@ export function RepositoryPicker(props: {
onOpenChange={(open) => {
setRepoOpen(open);
setError('');
- if (open) setRepoInput(props.repoUrl ?? '');
+ if (open) {
+ setSearch('');
+ list.setSelectedIndex(0);
+ }
}}
placement="top-start"
gutter={8}
@@ -61,7 +138,9 @@ export function RepositoryPicker(props: {
<Popover.Trigger class="pill max-w-full" aria-label="Repository">
<GithubIcon class="size-4 shrink-0" />
<span class="truncate">
- {props.repoUrl ? repositoryLabel(props.repoUrl) : 'Add repository'}
+ {props.repoUrl
+ ? repositoryLabel(props.repoUrl)
+ : 'Choose repository'}
</span>
<CaretDownIcon class="size-3 shrink-0" />
</Popover.Trigger>
@@ -71,17 +150,35 @@ export function RepositoryPicker(props: {
<form
onSubmit={(event) => {
event.preventDefault();
- applyRepo();
+ submitRepository();
}}
class="flex flex-col gap-2"
>
<input
- aria-label="Add repository"
- placeholder="owner/repo or GitHub URL"
- value={repoInput()}
+ role="combobox"
+ aria-label="Search repositories"
+ aria-expanded="true"
+ aria-controls={listId}
+ aria-activedescendant={highlightedId()}
+ aria-autocomplete="list"
+ autocomplete="off"
+ placeholder="Search, or paste owner/repo"
+ value={search()}
onInput={(event) => {
- setRepoInput(event.currentTarget.value);
+ setSearch(event.currentTarget.value);
setError('');
+ list.setSelectedIndex(0);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ list.selectNext();
+ scrollHighlightedIntoView();
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ list.selectPrevious();
+ scrollHighlightedIntoView();
+ }
}}
class="w-full rounded-lg border border-edge-muted bg-input px-3 py-2 outline-none focus:border-accent"
/>
@@ -90,36 +187,80 @@ export function RepositoryPicker(props: {
{error()}
</p>
</Show>
- <Button type="submit" variant="strong">
- Use repository
- </Button>
</form>
- <div class="mt-2 max-h-48 overflow-y-auto">
- <button
- type="button"
- class="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left hover:bg-hover"
- onClick={() => selectRepo(undefined)}
- >
- Choose automatically
- <Show when={!props.repoUrl}>
- <CheckIcon class="ml-auto size-4" />
- </Show>
- </button>
- <For each={props.recentRepositories}>
- {(url) => (
+ <div
+ id={listId}
+ role="listbox"
+ aria-label="Repositories"
+ class="mt-2 max-h-56 overflow-y-auto"
+ >
+ <For each={choices()}>
+ {(choice, index) => (
<button
type="button"
- class="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left hover:bg-hover"
- onClick={() => selectRepo(url)}
+ role="option"
+ id={`${listId}-${index()}`}
+ aria-selected={list.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={() => choose(choice)}
+ onMouseMove={() =>
+ list.setSelectedIndexFromPointer(index())
+ }
>
- <GithubIcon class="size-4 shrink-0" />
- <span class="truncate">{repositoryLabel(url)}</span>
- <Show when={url === props.repoUrl}>
+ <Show when={choice.kind !== 'automatic'}>
+ <GithubIcon class="size-4 shrink-0" />
+ </Show>
+ <span class="truncate">{rowLabel(choice)}</span>
+ <Show when={chosen(choice)}>
<CheckIcon class="ml-auto size-4 shrink-0" />
</Show>
</button>
)}
</For>
+ <Switch>
+ <Match when={props.repositoriesError}>
+ <div class="flex items-center justify-between gap-2 px-2 py-2 text-xs text-ink-muted">
+ Couldn't load your repositories.
+ <Button
+ variant="outline"
+ size="sm"
+ depth={3}
+ onClick={() => props.onRetryRepositories()}
+ >
+ Retry
+ </Button>
+ </div>
+ </Match>
+ <Match
+ when={props.repositoriesLoading && offered().length === 0}
+ >
+ <div class="px-2 py-2 text-xs text-ink-muted">
+ Loading your repositories…
+ </div>
+ </Match>
+ <Match when={nothingReachable()}>
+ <div class="flex flex-col gap-2 px-2 py-2 text-xs text-ink-muted">
+ No repositories yet. Give Macro's GitHub App access to the
+ repositories your coders should work on.
+ <Show when={props.onConnectGitHub}>
+ <Button
+ variant="outline"
+ size="sm"
+ depth={3}
+ class="self-start"
+ onClick={() => props.onConnectGitHub?.()}
+ >
+ Connect GitHub
+ </Button>
+ </Show>
+ </div>
+ </Match>
+ <Match when={choices().length === 0}>
+ <div class="px-2 py-2 text-xs text-ink-muted">
+ No repositories match “{search().trim()}”.
+ </div>
+ </Match>
+ </Switch>
</div>
</Popover.Content>
</Popover.Portal>
diff --git a/apps/web/src/lib/queries/agent-repositories/keys.ts b/apps/web/src/lib/queries/agent-repositories/keys.ts
new file mode 100644
index 0000000000..ace1b4c941
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-repositories/keys.ts
@@ -0,0 +1,5 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const agentRepositoryKeys = createQueryKeys('agentRepositories', {
+ list: null,
+});
diff --git a/apps/web/src/lib/queries/agent-repositories/repositories.ts b/apps/web/src/lib/queries/agent-repositories/repositories.ts
new file mode 100644
index 0000000000..95affdbad1
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-repositories/repositories.ts
@@ -0,0 +1,24 @@
+import { throwOnErr } from '@core/util/result';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import { useQuery } from '@tanstack/solid-query';
+import { agentRepositoryKeys } from './keys';
+
+/**
+ * The GitHub repositories the signed-in user can hand a coding session: every
+ * repository under an installation of Macro's GitHub App they or their teams
+ * made. The same list the create-session API authorizes an explicit
+ * repository against, so what a picker offers is exactly what a session may
+ * select.
+ *
+ * Kept fresh for a while: the harness caches the listing for ten minutes
+ * itself, and installing the App somewhere new is rare and deliberate.
+ */
+export function useAgentRepositoriesQuery(enabled: () => boolean = () => true) {
+ return useQuery(() => ({
+ queryKey: agentRepositoryKeys.list.queryKey,
+ queryFn: async () =>
+ throwOnErr(() => agentHarnessServiceClient.listRepositories()),
+ enabled: enabled(),
+ staleTime: 5 * 60 * 1000,
+ }));
+}
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 af74b8be40..433ca18234 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
@@ -48,3 +48,13 @@ describe('session request errors', () => {
expect(error.message).toBe('Agent request failed (HTTP 502).');
});
});
+
+describe('repository listing', () => {
+ it("asks the harness for the caller's repositories", () => {
+ agentHarnessServiceClient.listRepositories();
+ expect(fetchWithToken).toHaveBeenCalledWith(
+ 'https://harness.example.com/agent-repositories',
+ { 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 2d0b1ff622..e2bd75329e 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
@@ -2,6 +2,7 @@ import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import type { ErrorResponseHandler } from '@core/util/safeFetch';
import type {
+ AgentRepositoriesResponse,
AgentSessionLogResponse,
AgentSessionQueueResponse,
AgentSessionResponse,
@@ -71,6 +72,17 @@ export const agentHarnessServiceClient = {
);
},
+ /**
+ * The GitHub repositories the caller can select for a coding session, with
+ * the branch each one's sessions start on by default.
+ */
+ listRepositories() {
+ return fetchWithToken<AgentRepositoriesResponse>(
+ `${agentHarnessHost}/agent-repositories`,
+ { 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 c16b9a49c4..81f4d98e96 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
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type {
+ AgentRepositoriesResponse,
AgentSessionLogResponse,
AgentSessionQueueResponse,
AgentSessionResponse,
@@ -109,6 +110,63 @@ export const loadAgentModelsHandler = async (
} as loadAgentModelsHandlerResponse;
};
+/**
+ * @summary List the GitHub repositories the caller can select for a coding session.
+ */
+export type listAgentRepositoriesResponse200 = {
+ data: AgentRepositoriesResponse;
+ status: 200;
+};
+
+export type listAgentRepositoriesResponse401 = {
+ data: void;
+ status: 401;
+};
+
+export type listAgentRepositoriesResponse502 = {
+ data: void;
+ status: 502;
+};
+
+export type listAgentRepositoriesResponseSuccess =
+ listAgentRepositoriesResponse200 & {
+ headers: Headers;
+ };
+export type listAgentRepositoriesResponseError = (
+ | listAgentRepositoriesResponse401
+ | listAgentRepositoriesResponse502
+) & {
+ headers: Headers;
+};
+
+export type listAgentRepositoriesResponse =
+ | listAgentRepositoriesResponseSuccess
+ | listAgentRepositoriesResponseError;
+
+export const getListAgentRepositoriesUrl = () => {
+ return `/agent-repositories`;
+};
+
+export const listAgentRepositories = async (
+ options?: RequestInit
+): Promise<listAgentRepositoriesResponse> => {
+ const res = await fetch(getListAgentRepositoriesUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listAgentRepositoriesResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listAgentRepositoriesResponse;
+};
+
/**
* @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/agentRepositoriesResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoriesResponse.ts
new file mode 100644
index 0000000000..7754c06adf
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoriesResponse.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentRepositoryDto } from './agentRepositoryDto';
+
+/**
+ * Response body for `GET /agent-repositories`.
+ */
+export interface AgentRepositoriesResponse {
+ /** Every repository the caller reaches through Macro's GitHub App, sorted
+by `owner/name`. Empty when the App is installed nowhere the caller
+has a claim to. */
+ repositories: AgentRepositoryDto[];
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryDto.ts
new file mode 100644
index 0000000000..30ab54e0fe
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryDto.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentRepositoryDtoDefaultBranch } from './agentRepositoryDtoDefaultBranch';
+
+/**
+ * One repository the caller can select for a coding session.
+ */
+export interface AgentRepositoryDto {
+ /** The branch a clone checks out, and where a session starts when its
+request selects this repository without a `repoBranch`. Absent for a
+repository with no commits. */
+ defaultBranch?: AgentRepositoryDtoDefaultBranch;
+ /** The canonical `https://github.com/owner/name` url, in the form
+`POST /agent-sessions` accepts as `repoUrl`. */
+ url: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryDtoDefaultBranch.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryDtoDefaultBranch.ts
new file mode 100644
index 0000000000..ed2b82c072
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRepositoryDtoDefaultBranch.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The branch a clone checks out, and where a session starts when its
+request selects this repository without a `repoBranch`. Absent for a
+repository with no commits.
+ */
+export type AgentRepositoryDtoDefaultBranch = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
index e9a8487b0b..0196a9cd34 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
@@ -54,11 +54,13 @@ bot's say-so. */
only - an external runtime sends its own first prompt through the
control endpoint. Omitted, the session opens idle. */
prompt?: CreateAgentSessionRequestPrompt;
- /** Starting branch for a managed coding session's selected repository. */
+ /** Starting branch for a managed coding session's selected repository.
+Omitted, the session starts on the repository's default branch. */
repoBranch?: CreateAgentSessionRequestRepoBranch;
- /** Explicit GitHub repository for a managed Cursor session. Access is
-checked for the session owner. For external sessions this is
-informational: cloning it is the runtime operator's job. */
+ /** Explicit GitHub repository for a managed Cursor session, as one of the
+urls `GET /agent-repositories` lists for the caller. Access is checked
+for the session owner. For external sessions this is informational:
+cloning it is the runtime operator's job. */
repoUrl?: CreateAgentSessionRequestRepoUrl;
thread?: CreateAgentSessionRequestThread;
/** Absolute directory the bot's harness runs in on its runtime. Present
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoBranch.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoBranch.ts
index ef0e9f0b6f..8b597cda01 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoBranch.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoBranch.ts
@@ -7,5 +7,6 @@
/**
* Starting branch for a managed coding session's selected repository.
+Omitted, the session starts on the repository's default branch.
*/
export type CreateAgentSessionRequestRepoBranch = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts
index 0e82985115..b0a4792686 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts
@@ -6,8 +6,9 @@
*/
/**
- * Explicit GitHub repository for a managed Cursor session. Access is
-checked for the session owner. For external sessions this is
-informational: cloning it is the runtime operator's job.
+ * Explicit GitHub repository for a managed Cursor session, as one of the
+urls `GET /agent-repositories` lists for the caller. Access is checked
+for the session owner. For external sessions this is informational:
+cloning it is the runtime operator's job.
*/
export type CreateAgentSessionRequestRepoUrl = string | null;
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 19ddf08200..729a5ab766 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
@@ -25,6 +25,9 @@ export * from './agentModelDtoDescription';
export * from './agentModelDtoGroup';
export * from './agentModelsStatusDto';
export * from './agentPromptAction';
+export * from './agentRepositoriesResponse';
+export * from './agentRepositoryDto';
+export * from './agentRepositoryDtoDefaultBranch';
export * from './agentRespondElicitationAction';
export * from './agentRespondElicitationActionAllOf';
export * from './agentSessionLogEntryDto';
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 7ca3f4554b..0e62286fae 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
@@ -62,6 +62,36 @@
]
}
},
+ "/agent-repositories": {
+ "get": {
+ "tags": ["agent-repositories"],
+ "summary": "List the GitHub repositories the caller can select for a coding session.",
+ "operationId": "list_agent_repositories",
+ "responses": {
+ "200": {
+ "description": "The caller's reachable repositories",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentRepositoriesResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthenticated"
+ },
+ "502": {
+ "description": "GitHub could not be asked which repositories the caller reaches"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
"/agent-sandbox-size": {
"get": {
"tags": ["agent-sessions"],
@@ -1179,6 +1209,35 @@
}
}
},
+ "AgentRepositoriesResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-repositories`.",
+ "required": ["repositories"],
+ "properties": {
+ "repositories": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentRepositoryDto"
+ },
+ "description": "Every repository the caller reaches through Macro's GitHub App, sorted\nby `owner/name`. Empty when the App is installed nowhere the caller\nhas a claim to."
+ }
+ }
+ },
+ "AgentRepositoryDto": {
+ "type": "object",
+ "description": "One repository the caller can select for a coding session.",
+ "required": ["url"],
+ "properties": {
+ "defaultBranch": {
+ "type": ["string", "null"],
+ "description": "The branch a clone checks out, and where a session starts when its\nrequest selects this repository without a `repoBranch`. Absent for a\nrepository with no commits."
+ },
+ "url": {
+ "type": "string",
+ "description": "The canonical `https://github.com/owner/name` url, in the form\n`POST /agent-sessions` accepts as `repoUrl`."
+ }
+ }
+ },
"AgentRespondElicitationAction": {
"allOf": [
{
@@ -1602,11 +1661,11 @@
},
"repoBranch": {
"type": ["string", "null"],
- "description": "Starting branch for a managed coding session's selected repository."
+ "description": "Starting branch for a managed coding session's selected repository.\nOmitted, the session starts on the repository's default branch."
},
"repoUrl": {
"type": ["string", "null"],
- "description": "Explicit GitHub repository for a managed Cursor session. Access is\nchecked for the session owner. For external sessions this is\ninformational: cloning it is the runtime operator's job."
+ "description": "Explicit GitHub repository for a managed Cursor session, as one of the\nurls `GET /agent-repositories` lists for the caller. Access is checked\nfor the session owner. For external sessions this is informational:\ncloning it is the runtime operator's job."
},
"thread": {
"oneOf": [
@@ -2121,6 +2180,10 @@
{
"name": "agent-models",
"description": "Fresh provider model discovery"
+ },
+ {
+ "name": "agent-repositories",
+ "description": "Repositories a coding session can work on"
}
]
}
diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.toml
index 482686461a..b4b77d2713 100644
--- a/crates/agent_harness/Cargo.toml
+++ b/crates/agent_harness/Cargo.toml
@@ -86,3 +86,4 @@ bot_id = { path = "../bot_id", features = ["test-utils"] }
harness_id = { path = "../harness_id", features = ["test-utils"] }
mockall = { workspace = true }
model_user = { path = "../model_user" }
+tower = { workspace = true }
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 896cce401d..093432696f 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -535,6 +535,19 @@ impl SessionRepository {
}
}
+/// One repository a user can reach through Macro's GitHub App.
+///
+/// What a chooser offers and what the open path authorizes against: the url
+/// is the value a session's row is pinned to, and the default branch is where
+/// a session starts when its caller selected the repository but no branch.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ReachableRepository {
+ /// The canonical `https://github.com/owner/name` url.
+ pub url: String,
+ /// The branch a clone checks out, absent for a repository with no commits.
+ pub default_branch: Option<String>,
+}
+
/// Session-row values that remain deployment configuration for now.
#[derive(Debug, Clone)]
pub struct SessionDefaults {
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 43ed3664ae..330681e57a 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -15,7 +15,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, HarnessCommand, PriorMessage,
- ProvisionedEgress, SandboxEgress, SessionAnnouncement, SpawnContainer,
+ ProvisionedEgress, ReachableRepository, SandboxEgress, SessionAnnouncement, SpawnContainer,
};
use super::notifications::PlannedNotification;
use super::sandbox::SandboxResizeEffect;
@@ -32,13 +32,13 @@ pub enum CommandTarget {
/// The repositories a user can reach through Macro's GitHub App.
///
/// A port rather than the `github` crate's service directly, so the harness
-/// states what it needs - a list of repository urls for one user - without the
-/// installation records, App credentials and HTTP client that answering it
-/// takes. Reaching nothing is an empty list, not an error.
+/// states what it needs - each repository's url and default branch, for one
+/// user - without the installation records, App credentials and HTTP client
+/// that answering it takes. Reaching nothing is an empty list, not an error.
#[async_trait::async_trait]
pub trait ReachableRepositories: Send + Sync + 'static {
- /// Every repository `user` reaches, as `https://github.com/owner/name`.
- async fn for_user(&self, user: &MacroUserIdStr<'_>) -> Result<Vec<String>>;
+ /// Every repository `user` reaches, sorted by `owner/name`.
+ async fn for_user(&self, user: &MacroUserIdStr<'_>) -> Result<Vec<ReachableRepository>>;
}
/// Forwards commands to the replica currently responsible for execution.
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index adad74ba44..34b7709aa5 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -3,6 +3,7 @@
//! where there is a sandbox to give it to, and attaches the runtime.
use agent_session::domain::ports::SelectedManagedPersona;
+use agent_session::domain::repository_branch::RepositoryBranch;
use super::*;
use crate::domain::model::SessionRepository;
@@ -203,13 +204,16 @@ where
.for_user(&request.owner)
.await
.map_err(into_session_error)?;
- if !reachable
+ let listed = reachable
.iter()
- .any(|allowed| allowed.eq_ignore_ascii_case(repo.as_str()))
- {
- return Err(agent_session::domain::error::AgentSessionError::Forbidden);
- }
- Some(repo)
+ .find(|allowed| allowed.url.eq_ignore_ascii_case(repo.as_str()))
+ .ok_or(agent_session::domain::error::AgentSessionError::Forbidden)?;
+ // The caller's branch, or the one the repository's own clones start on.
+ let branch = request
+ .repo_branch
+ .clone()
+ .unwrap_or_else(|| starting_branch(listed.default_branch.as_deref()));
+ Some((repo, branch))
} else {
if request.repo_branch.is_some() {
return Err(
@@ -240,14 +244,7 @@ where
.inner
.sessions
.create_session(CreateAgentSessionParams {
- repo_branch: selected_repo.as_ref().map(|_| {
- request.repo_branch.unwrap_or_else(|| {
- agent_session::domain::repository_branch::RepositoryBranch::parse(
- "main".to_owned(),
- )
- .expect("main is a valid branch")
- })
- }),
+ repo_branch: selected_repo.as_ref().map(|(_, branch)| branch.clone()),
id: session_id,
owner_id: request.owner.clone(),
bot_id,
@@ -260,6 +257,7 @@ where
// somewhere this deployment does not name.
repo_url: selected_repo
.as_ref()
+ .map(|(repo, _)| repo)
.or(defaults.repo_url.as_ref())
.map(|repo| repo.as_str().to_owned()),
// Managed sandboxes run in the path baked into their image.
@@ -520,3 +518,16 @@ where
Ok(())
}
}
+
+/// The branch a session starts on when its caller selected a repository but
+/// no branch: the repository's own default branch, or `main` for an empty
+/// repository. GitHub reports the default branch's name as git holds it, so
+/// one that fails to parse belongs to a repository nothing could check out
+/// anyway - `main` is as good a guess as any there.
+pub(super) fn starting_branch(default_branch: Option<&str>) -> RepositoryBranch {
+ default_branch
+ .and_then(|branch| RepositoryBranch::parse(branch.to_owned()).ok())
+ .unwrap_or_else(|| {
+ RepositoryBranch::parse("main".to_owned()).expect("main is a valid branch")
+ })
+}
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 53cb5dbf60..802a12a993 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -3303,10 +3303,29 @@ async fn codex_channel_mention_provisions_egress_without_advertising_mcp() {
mod reopen;
-struct SelectedRepositories(Vec<String>);
+/// The owner's reachable repositories, as the GitHub App would list them.
+struct SelectedRepositories(Vec<crate::domain::model::ReachableRepository>);
+
+impl SelectedRepositories {
+ /// Repositories whose clones start on `main`.
+ fn urls(urls: &[&str]) -> Self {
+ Self(
+ urls.iter()
+ .map(|url| crate::domain::model::ReachableRepository {
+ url: (*url).to_owned(),
+ default_branch: Some("main".to_owned()),
+ })
+ .collect(),
+ )
+ }
+}
+
#[async_trait::async_trait]
impl crate::domain::ports::ReachableRepositories for SelectedRepositories {
- async fn for_user(&self, _: &MacroUserIdStr<'_>) -> crate::domain::error::Result<Vec<String>> {
+ async fn for_user(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> crate::domain::error::Result<Vec<crate::domain::model::ReachableRepository>> {
Ok(self.0.clone())
}
}
@@ -3333,7 +3352,7 @@ fn explicit_cursor_request() -> OpenManagedSession {
#[tokio::test]
async fn selected_repository_requires_owner_access_before_provisioning() {
let (service, _, containers, _, _) = harness();
- let service = service.with_repositories(Arc::new(SelectedRepositories(vec![])));
+ let service = service.with_repositories(Arc::new(SelectedRepositories::urls(&[])));
let result = service
.open_managed_session(explicit_cursor_request())
.await;
@@ -3348,8 +3367,8 @@ async fn selected_repository_requires_owner_access_before_provisioning() {
#[tokio::test]
async fn selected_repository_and_branch_are_persisted_for_cursor() {
let (service, repo, containers, _, _) = harness();
- let service = service.with_repositories(Arc::new(SelectedRepositories(vec![
- "https://github.com/macro-inc/macro".into(),
+ let service = service.with_repositories(Arc::new(SelectedRepositories::urls(&[
+ "https://github.com/macro-inc/macro",
])));
let open = service.open_managed_session(explicit_cursor_request());
let drive = async {
@@ -3371,6 +3390,80 @@ async fn selected_repository_and_branch_are_persisted_for_cursor() {
);
}
+/// Opens `request` against a listing that reaches `macro-inc/macro` with the
+/// given default branch, and reads back the branch the row was given.
+async fn branch_persisted_for(
+ default_branch: Option<&str>,
+ request: OpenManagedSession,
+) -> Option<String> {
+ let (service, repo, containers, _, _) = harness();
+ let service = service.with_repositories(Arc::new(SelectedRepositories(vec![
+ crate::domain::model::ReachableRepository {
+ url: "https://github.com/macro-inc/macro".to_owned(),
+ default_branch: default_branch.map(str::to_owned),
+ },
+ ])));
+ let open = service.open_managed_session(request);
+ let drive = async {
+ while containers.spawned() == 0 {
+ tokio::task::yield_now().await;
+ }
+ let container = containers.container(session_of(&containers)).unwrap();
+ complete_session_handshake(&container).await;
+ };
+ let (opened, _) = tokio::join!(open, drive);
+ let session = repo.get(opened.unwrap().id).await.unwrap();
+ session
+ .repo_branch
+ .as_ref()
+ .map(|branch| branch.as_str().to_owned())
+}
+
+#[tokio::test]
+async fn selected_repository_without_branch_starts_on_its_default_branch() {
+ let mut request = explicit_cursor_request();
+ request.repo_branch = None;
+ assert_eq!(
+ branch_persisted_for(Some("develop"), request)
+ .await
+ .as_deref(),
+ Some("develop")
+ );
+}
+
+#[tokio::test]
+async fn selected_repository_without_a_default_branch_starts_on_main() {
+ let mut request = explicit_cursor_request();
+ request.repo_branch = None;
+ assert_eq!(
+ branch_persisted_for(None, request).await.as_deref(),
+ Some("main")
+ );
+}
+
+#[tokio::test]
+async fn explicit_branch_wins_over_the_repository_default() {
+ assert_eq!(
+ branch_persisted_for(Some("develop"), explicit_cursor_request())
+ .await
+ .as_deref(),
+ Some("feature/home")
+ );
+}
+
+#[test]
+fn starting_branch_falls_back_to_main_for_an_unusable_default() {
+ assert_eq!(
+ super::open::starting_branch(Some("release")).as_str(),
+ "release"
+ );
+ assert_eq!(
+ super::open::starting_branch(Some("bad..name")).as_str(),
+ "main"
+ );
+ assert_eq!(super::open::starting_branch(None).as_str(), "main");
+}
+
#[tokio::test]
async fn branch_without_repository_is_rejected_before_provisioning() {
let (service, _, containers, _, _) = harness();
diff --git a/crates/agent_harness/src/inbound/mod.rs b/crates/agent_harness/src/inbound/mod.rs
index 333a7b10bf..1ba54df893 100644
--- a/crates/agent_harness/src/inbound/mod.rs
+++ b/crates/agent_harness/src/inbound/mod.rs
@@ -6,4 +6,6 @@
pub mod kafka;
/// Authenticated model discovery.
pub mod model_load;
+/// Authenticated repository 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
new file mode 100644
index 0000000000..9ce07038de
--- /dev/null
+++ b/crates/agent_harness/src/inbound/repositories.rs
@@ -0,0 +1,155 @@
+//! Authenticated HTTP adapter listing the repositories a caller can hand a
+//! coding session.
+//!
+//! 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
+//! chosen from what the caller actually reaches instead of typed from memory.
+//! The caller is always the user the token names: which installations a
+//! person has a claim to is a fact about them, not about any session.
+
+use std::sync::Arc;
+
+use axum::Router;
+use axum::extract::{FromRef, Json, 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 utoipa::ToSchema;
+
+use crate::domain::model::ReachableRepository;
+use crate::domain::ports::ReachableRepositories;
+
+#[cfg(test)]
+mod test;
+
+/// One repository the caller can select for a coding session.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentRepositoryDto {
+ /// The canonical `https://github.com/owner/name` url, in the form
+ /// `POST /agent-sessions` accepts as `repoUrl`.
+ pub url: String,
+ /// The branch a clone checks out, and where a session starts when its
+ /// request selects this repository without a `repoBranch`. Absent for a
+ /// repository with no commits.
+ pub default_branch: Option<String>,
+}
+
+/// Response body for `GET /agent-repositories`.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentRepositoriesResponse {
+ /// Every repository the caller reaches through Macro's GitHub App, sorted
+ /// by `owner/name`. Empty when the App is installed nowhere the caller
+ /// has a claim to.
+ pub repositories: Vec<AgentRepositoryDto>,
+}
+
+impl From<Vec<ReachableRepository>> for AgentRepositoriesResponse {
+ fn from(repositories: Vec<ReachableRepository>) -> Self {
+ Self {
+ repositories: repositories
+ .into_iter()
+ .map(|repository| AgentRepositoryDto {
+ url: repository.url,
+ default_branch: repository.default_branch,
+ })
+ .collect(),
+ }
+ }
+}
+
+/// Router state for repository listing.
+pub struct AgentRepositoriesRouterState<Auth> {
+ repositories: Arc<dyn ReachableRepositories>,
+ authorization: MacroAuthorizationState<Auth>,
+}
+
+impl<Auth> AgentRepositoriesRouterState<Auth> {
+ /// Build repository-listing route state.
+ pub fn new(
+ repositories: Arc<dyn ReachableRepositories>,
+ authorization: MacroAuthorizationState<Auth>,
+ ) -> Self {
+ Self {
+ repositories,
+ authorization,
+ }
+ }
+}
+
+impl<Auth> Clone for AgentRepositoriesRouterState<Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ repositories: Arc::clone(&self.repositories),
+ authorization: self.authorization.clone(),
+ }
+ }
+}
+
+impl<Auth> FromRef<AgentRepositoriesRouterState<Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &AgentRepositoriesRouterState<Auth>) -> Self {
+ state.authorization.clone()
+ }
+}
+
+/// Build `GET /agent-repositories`.
+pub fn agent_repositories_router<Auth, S>(state: AgentRepositoriesRouterState<Auth>) -> Router<S>
+where
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/agent-repositories",
+ get(list_agent_repositories_handler::<Auth>),
+ )
+ .with_state(state)
+}
+
+/// List the GitHub repositories the caller can select for a coding session.
+#[utoipa::path(
+ get,
+ path = "/agent-repositories",
+ tag = "agent-repositories",
+ operation_id = "list_agent_repositories",
+ security(("bearerAuth" = [])),
+ responses(
+ (status = 200, description = "The caller's reachable repositories", body = AgentRepositoriesResponse),
+ (status = 401, description = "Unauthenticated"),
+ (status = 502, description = "GitHub could not be asked which repositories the caller reaches"),
+ )
+)]
+pub async fn list_agent_repositories_handler<Auth>(
+ State(state): State<AgentRepositoriesRouterState<Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOnly>,
+) -> Response
+where
+ Auth: MacroAuthorizationService,
+{
+ match state
+ .repositories
+ .for_user(&authorization.authorization.macro_user_id)
+ .await
+ {
+ Ok(repositories) => (
+ StatusCode::OK,
+ Json(AgentRepositoriesResponse::from(repositories)),
+ )
+ .into_response(),
+ // The listing is one GitHub call per installation; a failure here is
+ // GitHub's or our App credentials', never the caller's.
+ Err(error) => {
+ tracing::warn!(error = ?error, "could not list the caller's reachable repositories");
+ (
+ StatusCode::BAD_GATEWAY,
+ "could not list your GitHub repositories".to_owned(),
+ )
+ .into_response()
+ }
+ }
+}
diff --git a/crates/agent_harness/src/inbound/repositories/test.rs b/crates/agent_harness/src/inbound/repositories/test.rs
new file mode 100644
index 0000000000..42172880f3
--- /dev/null
+++ b/crates/agent_harness/src/inbound/repositories/test.rs
@@ -0,0 +1,157 @@
+use std::sync::Arc;
+
+use axum::body::{Body, to_bytes};
+use axum::http::{Request, StatusCode};
+use macro_authorization::{InternalIdentityClaims, MacroAuthorizationError};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::UserContext;
+use rootcause::Report;
+use tower::ServiceExt as _;
+
+use super::*;
+use crate::domain::error::HarnessError;
+
+const USER_ID: &str = "macro|[email protected]";
+
+/// Admits the one token `valid`, as the user above.
+#[derive(Clone)]
+struct TestAuthorizationService;
+
+impl MacroAuthorizationService for TestAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ if jwt != "valid" {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(UserContext {
+ user_id: USER_ID.to_owned(),
+ fusion_user_id: "fusion-repository-lister".to_owned(),
+ permissions: None,
+ organization_id: None,
+ })
+ }
+
+ async fn authorize_internal(
+ &self,
+ _provided_key: &str,
+ _claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
+/// A canned listing that records who it was asked about, or a refusal.
+struct StubRepositories {
+ listing: Result<Vec<ReachableRepository>, ()>,
+ asked_for: std::sync::Mutex<Vec<String>>,
+}
+
+#[async_trait::async_trait]
+impl ReachableRepositories for StubRepositories {
+ async fn for_user(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> crate::domain::error::Result<Vec<ReachableRepository>> {
+ self.asked_for
+ .lock()
+ .expect("stub poisoned")
+ .push(user.to_string());
+ self.listing
+ .clone()
+ .map_err(|()| HarnessError::Repositories(rootcause::report!("github is down")))
+ }
+}
+
+fn router(listing: Result<Vec<ReachableRepository>, ()>) -> (Router, Arc<StubRepositories>) {
+ let repositories = Arc::new(StubRepositories {
+ listing,
+ asked_for: std::sync::Mutex::new(Vec::new()),
+ });
+ let state = AgentRepositoriesRouterState::new(
+ Arc::clone(&repositories) as Arc<dyn ReachableRepositories>,
+ MacroAuthorizationState::new(Arc::new(TestAuthorizationService)),
+ );
+ (agent_repositories_router(state), repositories)
+}
+
+fn request(token: Option<&str>) -> Request<Body> {
+ let builder = Request::builder().uri("/agent-repositories").method("GET");
+ let builder = match token {
+ Some(token) => builder.header("authorization", format!("Bearer {token}")),
+ None => builder,
+ };
+ builder.body(Body::empty()).unwrap()
+}
+
+#[tokio::test]
+async fn lists_the_callers_repositories_with_their_default_branches() {
+ let (router, repositories) = router(Ok(vec![
+ ReachableRepository {
+ url: "https://github.com/macro-inc/infra".to_owned(),
+ default_branch: Some("main".to_owned()),
+ },
+ ReachableRepository {
+ url: "https://github.com/macro-inc/scratch".to_owned(),
+ default_branch: None,
+ },
+ ]));
+
+ let response = router.oneshot(request(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!({
+ "repositories": [
+ {
+ "url": "https://github.com/macro-inc/infra",
+ "defaultBranch": "main"
+ },
+ {
+ "url": "https://github.com/macro-inc/scratch",
+ "defaultBranch": null
+ }
+ ]
+ })
+ );
+ // The listing is the token's user's, never anything the request names.
+ assert_eq!(
+ *repositories.asked_for.lock().unwrap(),
+ vec![USER_ID.to_owned()]
+ );
+}
+
+#[tokio::test]
+async fn reaching_nothing_is_an_empty_list() {
+ let (router, _) = router(Ok(Vec::new()));
+
+ let response = router.oneshot(request(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!({ "repositories": [] })
+ );
+}
+
+#[tokio::test]
+async fn unauthenticated_callers_are_refused_before_github_is_asked() {
+ for token in [None, Some("forged")] {
+ let (router, repositories) = router(Ok(Vec::new()));
+
+ let response = router.oneshot(request(token)).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{token:?}");
+ assert!(repositories.asked_for.lock().unwrap().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn a_failed_listing_is_a_bad_gateway() {
+ let (router, _) = router(Err(()));
+
+ let response = router.oneshot(request(Some("valid"))).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
+}
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index 77917e7a85..24171d9009 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -412,7 +412,10 @@ struct NoRepositories;
#[async_trait::async_trait]
impl ReachableRepositories for NoRepositories {
- async fn for_user(&self, _user: &MacroUserIdStr<'_>) -> Result<Vec<String>> {
+ async fn for_user(
+ &self,
+ _user: &MacroUserIdStr<'_>,
+ ) -> Result<Vec<crate::domain::model::ReachableRepository>> {
Ok(Vec::new())
}
}
diff --git a/crates/agent_harness/src/outbound/cursor/repository_chooser.rs b/crates/agent_harness/src/outbound/cursor/repository_chooser.rs
index 945fe5b95c..304244262c 100644
--- a/crates/agent_harness/src/outbound/cursor/repository_chooser.rs
+++ b/crates/agent_harness/src/outbound/cursor/repository_chooser.rs
@@ -105,10 +105,17 @@ where
fields(agent.session.id = %self.session_id)
)]
async fn reachable_repositories(&self) -> Result<Vec<String>, rootcause::Report> {
- self.repositories
+ // The model chooses between urls: they are what the session row is
+ // pinned to, and a candidate's default branch is no help in deciding
+ // which repository a prompt belongs to.
+ Ok(self
+ .repositories
.for_user(&self.owner)
.await
- .map_err(|error| rootcause::report!("could not list reachable repositories: {error}"))
+ .map_err(|error| rootcause::report!("could not list reachable repositories: {error}"))?
+ .into_iter()
+ .map(|repository| repository.url)
+ .collect())
}
/// The five prior sessions, excluding the placeholder being initialized.
diff --git a/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs b/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs
index 479dc202d9..10f68d08ef 100644
--- a/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs
@@ -22,12 +22,19 @@ impl ReachableRepositories for StubRepositories {
async fn for_user(
&self,
user: &MacroUserIdStr<'_>,
- ) -> crate::domain::error::Result<Vec<String>> {
+ ) -> crate::domain::error::Result<Vec<crate::domain::model::ReachableRepository>> {
self.asked_for
.lock()
.expect("stub poisoned")
.push(user.to_string());
- Ok(self.repositories.clone())
+ Ok(self
+ .repositories
+ .iter()
+ .map(|url| crate::domain::model::ReachableRepository {
+ url: url.clone(),
+ default_branch: Some("main".to_owned()),
+ })
+ .collect())
}
}
diff --git a/crates/agent_harness/src/outbound/github_repositories.rs b/crates/agent_harness/src/outbound/github_repositories.rs
index 29850e7355..3ef74f5368 100644
--- a/crates/agent_harness/src/outbound/github_repositories.rs
+++ b/crates/agent_harness/src/outbound/github_repositories.rs
@@ -3,13 +3,14 @@
//! Everything this knows about GitHub - which installations belong to whom,
//! what each one covers, how to prove we are the App - belongs to the `github`
//! crate. This adapter only narrows its answer to what the harness asked for:
-//! a list of repository urls for one user.
+//! each repository's url and default branch, for one user.
use github::domain::ports::{GithubRepositoryClient, GithubSyncRepo};
use github::domain::service::ReachableRepositoriesService;
use macro_user_id::user_id::MacroUserIdStr;
use crate::domain::error::{HarnessError, Result};
+use crate::domain::model::ReachableRepository;
use crate::domain::ports::ReachableRepositories;
/// [`ReachableRepositories`] backed by the `github` crate's listing service.
@@ -35,7 +36,7 @@ where
Installations: GithubSyncRepo,
Client: GithubRepositoryClient,
{
- async fn for_user(&self, user: &MacroUserIdStr<'_>) -> Result<Vec<String>> {
+ async fn for_user(&self, user: &MacroUserIdStr<'_>) -> Result<Vec<ReachableRepository>> {
let repositories = self
.repositories
.for_user(user)
@@ -45,8 +46,11 @@ where
// what Cursor is given and what the session row is pinned to, and both
// must agree with what the model was offered.
Ok(repositories
- .iter()
- .map(github::domain::models::GithubRepository::https_url)
+ .into_iter()
+ .map(|repository| ReachableRepository {
+ url: repository.https_url(),
+ default_branch: repository.default_branch,
+ })
.collect())
}
}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 5c09bc4138..9680ff731a 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -1407,11 +1407,13 @@ pub struct CreateAgentSessionRequest {
/// only - an external runtime sends its own first prompt through the
/// control endpoint. Omitted, the session opens idle.
pub prompt: Option<String>,
- /// Explicit GitHub repository for a managed Cursor session. Access is
- /// checked for the session owner. For external sessions this is
- /// informational: cloning it is the runtime operator's job.
+ /// Explicit GitHub repository for a managed Cursor session, as one of the
+ /// urls `GET /agent-repositories` lists for the caller. Access is checked
+ /// for the session owner. For external sessions this is informational:
+ /// cloning it is the runtime operator's job.
pub repo_url: Option<String>,
/// Starting branch for a managed coding session's selected repository.
+ /// Omitted, the session starts on the repository's default branch.
pub repo_branch: Option<String>,
/// The user who owns the session. Ignored for user callers, who always
/// own their own sessions, and for harness callers, whose verified acting
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 7e5111199b..4922c43fb9 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -60,9 +60,20 @@
behind it throughout the transition, keeping its existing edge-muted border.
Selecting a chat agent retracts it. Reduced-motion
preferences disable the animation. The hidden drawer is inert. **Repository**
- offers **Choose automatically**, recent repositories, or GitHub `owner/repo` /
- URL entry confirmed with **Use repository**. Once selected, **Branch** opens
- a starting-branch field confirmed with **Use branch** (initially `main`).
+ (**Choose repository** until one is picked) opens a searchable list:
+ **Choose automatically**, then the repositories the signed-in user reaches
+ through Macro's GitHub App (`GET /agent-repositories` on the agent harness),
+ recently used ones first. Typing filters the list; an unlisted GitHub
+ `owner/repo` or URL adds a **Use owner/repo** row. Arrow keys move the
+ highlight and Enter or a click picks it; there is no separate confirm
+ button. Someone who reaches no repository sees a hint with **Connect
+ GitHub**, which opens Settings → Connected. The last repository picked is
+ remembered per user in local storage and preselected next time. 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.
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 d6a4b61923..06c4807a04 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, AgentPromptAction, AgentRespondElicitationAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, 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, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, 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, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, 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, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, 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 f52bfcfa83..d150f40ac2 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, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, 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, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, 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> & {
/**
@@ -72,6 +72,17 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * List the GitHub repositories the caller can select for a coding session.
+ */
+ public listAgentRepositories<ThrowOnError extends boolean = false>(options?: Options<ListAgentRepositoriesData, ThrowOnError>): RequestResult<ListAgentRepositoriesResponses, ListAgentRepositoriesErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<ListAgentRepositoriesResponses, ListAgentRepositoriesErrors, ThrowOnError>({
+ security: [{ scheme: 'bearer', type: 'http' }],
+ url: '/agent-repositories',
+ ...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 064a3c96f1..ffc44ee603 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -71,6 +71,35 @@ export type AgentPromptAction = {
prompt: string;
};
+/**
+ * Response body for `GET /agent-repositories`.
+ */
+export type AgentRepositoriesResponse = {
+ /**
+ * Every repository the caller reaches through Macro's GitHub App, sorted
+ * by `owner/name`. Empty when the App is installed nowhere the caller
+ * has a claim to.
+ */
+ repositories: Array<AgentRepositoryDto>;
+};
+
+/**
+ * One repository the caller can select for a coding session.
+ */
+export type AgentRepositoryDto = {
+ /**
+ * The branch a clone checks out, and where a session starts when its
+ * request selects this repository without a `repoBranch`. Absent for a
+ * repository with no commits.
+ */
+ defaultBranch?: string | null;
+ /**
+ * The canonical `https://github.com/owner/name` url, in the form
+ * `POST /agent-sessions` accepts as `repoUrl`.
+ */
+ url: string;
+};
+
/**
* Answer an elicitation the agent is waiting on.
*/
@@ -417,12 +446,14 @@ export type CreateAgentSessionRequest = {
prompt?: string | null;
/**
* Starting branch for a managed coding session's selected repository.
+ * Omitted, the session starts on the repository's default branch.
*/
repoBranch?: string | null;
/**
- * Explicit GitHub repository for a managed Cursor session. Access is
- * checked for the session owner. For external sessions this is
- * informational: cloning it is the runtime operator's job.
+ * Explicit GitHub repository for a managed Cursor session, as one of the
+ * urls `GET /agent-repositories` lists for the caller. Access is checked
+ * for the session owner. For external sessions this is informational:
+ * cloning it is the runtime operator's job.
*/
repoUrl?: string | null;
thread?: null | CreateSessionThread;
@@ -851,6 +882,33 @@ export type LoadAgentModelsHandlerResponses = {
export type LoadAgentModelsHandlerResponse = LoadAgentModelsHandlerResponses[keyof LoadAgentModelsHandlerResponses];
+export type ListAgentRepositoriesData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/agent-repositories';
+};
+
+export type ListAgentRepositoriesErrors = {
+ /**
+ * Unauthenticated
+ */
+ 401: unknown;
+ /**
+ * GitHub could not be asked which repositories the caller reaches
+ */
+ 502: unknown;
+};
+
+export type ListAgentRepositoriesResponses = {
+ /**
+ * The caller's reachable repositories
+ */
+ 200: AgentRepositoriesResponse;
+};
+
+export type ListAgentRepositoriesResponse = ListAgentRepositoriesResponses[keyof ListAgentRepositoriesResponses];
+
export type GetAgentSandboxSizeData = {
body?: never;
path?: never;
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 7ca3f4554b..0e62286fae 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -62,6 +62,36 @@
]
}
},
+ "/agent-repositories": {
+ "get": {
+ "tags": ["agent-repositories"],
+ "summary": "List the GitHub repositories the caller can select for a coding session.",
+ "operationId": "list_agent_repositories",
+ "responses": {
+ "200": {
+ "description": "The caller's reachable repositories",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentRepositoriesResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Unauthenticated"
+ },
+ "502": {
+ "description": "GitHub could not be asked which repositories the caller reaches"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
"/agent-sandbox-size": {
"get": {
"tags": ["agent-sessions"],
@@ -1179,6 +1209,35 @@
}
}
},
+ "AgentRepositoriesResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-repositories`.",
+ "required": ["repositories"],
+ "properties": {
+ "repositories": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentRepositoryDto"
+ },
+ "description": "Every repository the caller reaches through Macro's GitHub App, sorted\nby `owner/name`. Empty when the App is installed nowhere the caller\nhas a claim to."
+ }
+ }
+ },
+ "AgentRepositoryDto": {
+ "type": "object",
+ "description": "One repository the caller can select for a coding session.",
+ "required": ["url"],
+ "properties": {
+ "defaultBranch": {
+ "type": ["string", "null"],
+ "description": "The branch a clone checks out, and where a session starts when its\nrequest selects this repository without a `repoBranch`. Absent for a\nrepository with no commits."
+ },
+ "url": {
+ "type": "string",
+ "description": "The canonical `https://github.com/owner/name` url, in the form\n`POST /agent-sessions` accepts as `repoUrl`."
+ }
+ }
+ },
"AgentRespondElicitationAction": {
"allOf": [
{
@@ -1602,11 +1661,11 @@
},
"repoBranch": {
"type": ["string", "null"],
- "description": "Starting branch for a managed coding session's selected repository."
+ "description": "Starting branch for a managed coding session's selected repository.\nOmitted, the session starts on the repository's default branch."
},
"repoUrl": {
"type": ["string", "null"],
- "description": "Explicit GitHub repository for a managed Cursor session. Access is\nchecked for the session owner. For external sessions this is\ninformational: cloning it is the runtime operator's job."
+ "description": "Explicit GitHub repository for a managed Cursor session, as one of the\nurls `GET /agent-repositories` lists for the caller. Access is checked\nfor the session owner. For external sessions this is informational:\ncloning it is the runtime operator's job."
},
"thread": {
"oneOf": [
@@ -2121,6 +2180,10 @@
{
"name": "agent-models",
"description": "Fresh provider model discovery"
+ },
+ {
+ "name": "agent-repositories",
+ "description": "Repositories a coding session can work on"
}
]
}
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index d202407a01..ddf7ac348b 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -10,6 +10,36 @@ import type { MacroClient } from '../../utils/client';
import { MacroEntity } from '../entity';
import { QueuedAction } from './queued-action';
+/** A GitHub repository the caller can point a managed session at. */
+export type SelectableRepository = {
+ /** The canonical `https://github.com/owner/name` URL, as `createManaged` takes it. */
+ url: string;
+ /**
+ * The branch its clones check out, and where a session starts unless
+ * `createManaged` names another. Absent for a repository with no commits.
+ */
+ defaultBranch?: string;
+};
+
+/** What a managed session is created with. */
+export type CreateManagedSessionOptions = {
+ /** First prompt to deliver once the session is running. */
+ prompt?: string;
+ /** Instructions the session's runtime works under, fixed for its life. */
+ instructions?: string;
+ /**
+ * The repository the session works on, as one of the URLs
+ * {@link AgentSession.repositories} lists for the caller. Omitted, the
+ * runtime chooses from the prompt. Honored for Cursor sessions.
+ */
+ repoUrl?: string;
+ /**
+ * The branch the session starts on; needs `repoUrl`. Omitted, the
+ * repository's default branch.
+ */
+ repoBranch?: string;
+};
+
/** A managed or externally hosted coding-agent session. */
export class AgentSession extends MacroEntity<AgentSessionResponse> {
/** A handle to an agent session by id. Details load on first access. */
@@ -20,16 +50,39 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
/** Create a managed session, optionally delivering its first prompt. */
static async createManaged(
client: MacroClient,
- opts?: { prompt?: string; instructions?: string },
+ opts?: CreateManagedSessionOptions,
): Promise<AgentSession> {
const { session } = unwrap(
await client.agentHarness.createAgentSession({
- body: { prompt: opts?.prompt, instructions: opts?.instructions },
+ body: {
+ prompt: opts?.prompt,
+ instructions: opts?.instructions,
+ repoUrl: opts?.repoUrl,
+ repoBranch: opts?.repoBranch,
+ },
}),
);
return new AgentSession(client, session.id, session);
}
+ /**
+ * The GitHub repositories the caller can hand a managed session: every
+ * repository under an installation of Macro's GitHub App they or their
+ * teams made, sorted by `owner/name`. Empty when the App is installed
+ * nowhere they reach.
+ */
+ static async repositories(
+ client: MacroClient,
+ ): Promise<SelectableRepository[]> {
+ const { repositories } = unwrap(
+ await client.agentHarness.listAgentRepositories(),
+ );
+ return repositories.map((repository) => ({
+ url: repository.url,
+ defaultBranch: repository.defaultBranch ?? undefined,
+ }));
+ }
+
protected async fetch(): Promise<AgentSessionResponse> {
return unwrap(
await this.client.agentHarness.getAgentSession({
diff --git a/packages/sdk/src/entities/agent-sessions/namespace.ts b/packages/sdk/src/entities/agent-sessions/namespace.ts
index 8564e0479e..fd961ed605 100644
--- a/packages/sdk/src/entities/agent-sessions/namespace.ts
+++ b/packages/sdk/src/entities/agent-sessions/namespace.ts
@@ -1,6 +1,10 @@
import type { SandboxSize } from '../../../generated/agent-harness/types.gen';
import type { MacroClient } from '../../utils/client';
-import { AgentSession } from './agent-session';
+import {
+ AgentSession,
+ type CreateManagedSessionOptions,
+ type SelectableRepository,
+} from './agent-session';
/** Entry point for coding-agent sessions. */
export class AgentSessionNamespace {
@@ -12,13 +16,18 @@ export class AgentSessionNamespace {
}
/** Create a managed agent session. */
- createManaged(opts?: {
- prompt?: string;
- instructions?: string;
- }): Promise<AgentSession> {
+ createManaged(opts?: CreateManagedSessionOptions): Promise<AgentSession> {
return AgentSession.createManaged(this.client, opts);
}
+ /**
+ * The GitHub repositories the caller can hand a managed session, with the
+ * branch each one's sessions start on by default.
+ */
+ repositories(): Promise<SelectableRepository[]> {
+ return AgentSession.repositories(this.client);
+ }
+
/** The caller's default sandbox size for new `@coder` sessions. */
defaultSandboxSize(): Promise<SandboxSize> {
return AgentSession.defaultSandboxSize(this.client);
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index b0ab4790cb..45f7f3ecea 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -9,6 +9,9 @@ use agent_egress::domain::service::EgressService;
use agent_egress::inbound::axum_router::{EgressRouterState, egress_router};
use agent_harness::domain::model_load::AgentModelsService;
use agent_harness::inbound::model_load::{AgentModelsRouterState, agent_models_router};
+use agent_harness::inbound::repositories::{
+ AgentRepositoriesRouterState, agent_repositories_router,
+};
use agent_harness::inbound::runtime_gateway::{RuntimeGatewayState, runtime_gateway_router};
use agent_session::domain::ports::{
AgentSessionNotificationRecipient, BotDirectory, SessionOpener,
@@ -62,6 +65,7 @@ pub struct ApiStates<T, R, Opener, Bots, Access, Auth, Models> {
create: CreateSessionState<Opener, Bots, Auth>,
gateway: RuntimeGatewayState<Auth>,
models: AgentModelsRouterState<Models, Auth>,
+ repositories: AgentRepositoriesRouterState<Auth>,
claude_auth: Router,
}
@@ -73,6 +77,7 @@ impl<T, R, Opener, Bots, Access, Auth, Models> ApiStates<T, R, Opener, Bots, Acc
create: CreateSessionState<Opener, Bots, Auth>,
gateway: RuntimeGatewayState<Auth>,
models: AgentModelsRouterState<Models, Auth>,
+ repositories: AgentRepositoriesRouterState<Auth>,
) -> Self {
Self {
read,
@@ -80,6 +85,7 @@ impl<T, R, Opener, Bots, Access, Auth, Models> ApiStates<T, R, Opener, Bots, Acc
create,
gateway,
models,
+ repositories,
claude_auth: Router::new(),
}
}
@@ -179,6 +185,7 @@ where
.nest("/agent-sessions", agent_sessions)
.merge(agent_sandbox_size_router(states.read))
.merge(agent_models_router(states.models))
+ .merge(agent_repositories_router(states.repositories))
.merge(states.claude_auth)
.nest("/runtime", runtime_gateway_router(states.gateway))
}
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 26d603168b..df21d7609f 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -4,6 +4,7 @@ use agent_harness::inbound::model_load::{
self, AgentModelDto, AgentModelsStatusDto, LoadAgentModelsRequest, LoadAgentModelsResponse,
ModelHarnessDto,
};
+use agent_harness::inbound::repositories::{self, AgentRepositoriesResponse, AgentRepositoryDto};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::domain::model::{SandboxSize, SessionBot};
use agent_session::inbound::axum_router::{
@@ -56,6 +57,7 @@ impl Modify for SecurityAddon {
axum_router::get_agent_sandbox_size_handler,
axum_router::put_agent_sandbox_size_handler,
model_load::load_agent_models_handler,
+ repositories::list_agent_repositories_handler,
),
components(schemas(
claude_auth::StatusResponse,
@@ -93,10 +95,13 @@ impl Modify for SecurityAddon {
AgentModelDto,
AgentModelsStatusDto,
ModelHarnessDto,
+ AgentRepositoriesResponse,
+ AgentRepositoryDto,
)),
tags(
(name = "agent-sessions", description = "Agent sessions"),
- (name = "agent-models", description = "Fresh provider model discovery")
+ (name = "agent-models", description = "Fresh provider model discovery"),
+ (name = "agent-repositories", description = "Repositories a coding session can work on")
)
)]
pub struct ApiDoc;
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 86abae3a5d..2573afad83 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -41,6 +41,7 @@ use agent_harness::domain::trigger_router::{
RoutedTrigger, agent_trigger_bot_id, route_agent_trigger,
};
use agent_harness::inbound::model_load::AgentModelsRouterState;
+use agent_harness::inbound::repositories::AgentRepositoriesRouterState;
use agent_harness::inbound::runtime_gateway::RuntimeGatewayState;
use agent_harness::outbound::agent_prompt_composer::LexicalAgentPromptComposer;
use agent_harness::outbound::channel_announcer::MessageAnnouncer;
@@ -771,6 +772,10 @@ async fn run() -> anyhow::Result<()> {
// explicitly selected coding agents keep their configured runtimes.
.with_managed_bot(inmem_bot);
+ // The open path authorizes explicit repositories against the same listing
+ // the repository route below serves, so what the app offers is exactly
+ // what a session may select.
+ let open_repositories = Arc::clone(&reachable_repositories);
let harness = Arc::new(
AgentHarnessService::new(
sessions,
@@ -792,7 +797,7 @@ async fn run() -> anyhow::Result<()> {
// notification ingress channel messages use.
IngressAgentSessionNotifier::new(Arc::clone(&notifications)),
)
- .with_repositories(reachable_repositories),
+ .with_repositories(open_repositories),
);
// Close the loop: turn ends observed by the session actors drain the
// harness's prompt queue.
@@ -905,6 +910,11 @@ async fn run() -> anyhow::Result<()> {
runtimes,
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
);
+ // Served to the app by `GET /agent-repositories`; see `open_repositories`.
+ let repositories_state = AgentRepositoriesRouterState::new(
+ reachable_repositories,
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ );
let http_runtime_commands_readiness = runtime_commands_readiness.clone();
let claude_auth = claude_cloud_agents::inbound::auth::router(
claude_cloud_agents::inbound::auth::ClaudeAuthState::new(
@@ -925,6 +935,7 @@ async fn run() -> anyhow::Result<()> {
create_state,
gateway_state,
model_state,
+ repositories_state,
)
.with_claude_auth(claude_auth),
http_runtime_commands_readiness,