Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9021: return GitHub connections to the original page with repositories preselected (#10363)

Bohan Jiang5894f11a95fa
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 96d1e98453..5820fbf1fb 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -5280,13 +5280,10 @@ export class ApiClient {
// GitHub integration
async getGitHubConnectURL(
workspaceId: string,
- returnTo?: "github" | "repositories",
+ options?: { desktop?: boolean },
): Promise<GitHubConnectResponse> {
- const search = new URLSearchParams();
- if (returnTo) search.set("return_to", returnTo);
- const suffix = search.size > 0 ? `?${search.toString()}` : "";
const raw = await this.fetch<unknown>(
- `/api/workspaces/${workspaceId}/github/connect${suffix}`,
+ `/api/workspaces/${workspaceId}/github/connect${options?.desktop ? "?desktop=1" : ""}`,
);
return parseWithFallback(
raw,
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 208cfcca5b..6835c0d0d8 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -61,18 +61,34 @@ describe("ApiClient schema fallback", () => {
});
});
- it("adds the allowlisted repository return target to the connect request", async () => {
+ it.each([undefined, "all", "selected", "future-selection", 42])("handles repository selection metadata safely (%s)", async (selection) => {
+ stubFetchJson({ repositories: [], total_count: 0, next_page: null, repository_selection: selection });
+ const client = new ApiClient("https://api.example.test");
+ const response = await client.listGitHubInstallationRepositories("ws-1", "install-1");
+ expect(response.repository_selection).toBe(selection === undefined ? undefined : selection === "all" || selection === "selected" ? selection : "unknown");
+ });
+
+ it.each([undefined, "desktop-nonce", 42])("accepts missing or malformed connect correlation metadata (%s)", async (connectionID) => {
+ stubFetchJson({ configured: true, url: "https://github.com/apps/test/installations/new", connection_id: connectionID });
+ const client = new ApiClient("https://api.example.test");
+ const response = await client.getGitHubConnectURL("ws-1", { desktop: true });
+ expect(response.configured).toBe(true);
+ expect(response.connection_id).toBe(typeof connectionID === "string" ? connectionID : undefined);
+ expect(vi.mocked(fetch).mock.calls[0]?.[0]).toBe("https://api.example.test/api/workspaces/ws-1/github/connect?desktop=1");
+ });
+
+ it("uses the unified GitHub connect endpoint", async () => {
stubFetchJson({
configured: true,
url: "https://github.com/apps/multica/installations/new",
});
const client = new ApiClient("https://api.example.test");
- await client.getGitHubConnectURL("ws-1", "repositories");
+ await client.getGitHubConnectURL("ws-1");
const fetchMock = vi.mocked(fetch);
expect(fetchMock).toHaveBeenCalledWith(
- "https://api.example.test/api/workspaces/ws-1/github/connect?return_to=repositories",
+ "https://api.example.test/api/workspaces/ws-1/github/connect",
expect.any(Object),
);
});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 2bd9b7f083..640e71a74a 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -378,6 +378,7 @@ export const EMPTY_LIST_GITHUB_INSTALLATIONS_RESPONSE: ListGitHubInstallationsRe
};
export const GitHubConnectResponseSchema = z.object({
+ connection_id: z.string().optional().catch(undefined),
url: z.string().optional(),
configured: z.boolean().optional().default(false),
}).loose();
@@ -398,6 +399,7 @@ export const GitHubRepositorySchema = z.object({
}).loose();
export const ListGitHubRepositoriesResponseSchema = z.object({
+ repository_selection: z.enum(["all", "selected", "unknown"]).catch("unknown").optional(),
repositories: z.array(GitHubRepositorySchema).default([]),
total_count: z.number().optional().default(0),
next_page: z.number().nullable().optional().default(null),
diff --git a/packages/core/github/connection-event.ts b/packages/core/github/connection-event.ts
new file mode 100644
index 0000000000..94db7f1aee
--- /dev/null
+++ b/packages/core/github/connection-event.ts
@@ -0,0 +1,6 @@
+import { z } from "zod";
+
+export const GitHubConnectionEventSchema = z.object({
+ installation: z.object({ id: z.string(), workspace_id: z.string() }),
+ connection_id: z.string().optional(),
+});
diff --git a/packages/core/github/connection-store.ts b/packages/core/github/connection-store.ts
new file mode 100644
index 0000000000..f66af8d11a
--- /dev/null
+++ b/packages/core/github/connection-store.ts
@@ -0,0 +1,43 @@
+import { create } from "zustand";
+import { GitHubConnectionEventSchema } from "./connection-event";
+
+interface GitHubConnection {
+ workspaceID: string;
+ connectionID?: string;
+ installationID: string;
+}
+
+interface GitHubConnectionState {
+ connection: GitHubConnection | null;
+ begin: (workspaceID: string, connectionID?: string) => void;
+ complete: (payload: unknown) => void;
+ reset: (workspaceID?: string) => void;
+}
+
+// This window's transient handoff survives settings navigation. Installation
+// data stays in Query; only the initiated flow and its completion pointer live here.
+export const useGitHubConnectionStore = create<GitHubConnectionState>((set) => ({
+ connection: null,
+ begin: (workspaceID, connectionID) => set({
+ connection: { workspaceID, connectionID, installationID: "" },
+ }),
+ complete: (payload) => {
+ const event = GitHubConnectionEventSchema.safeParse(payload);
+ if (!event.success) return;
+ const { installation, connection_id: connectionID } = event.data;
+ set((state) => {
+ const pending = state.connection;
+ if (
+ !pending || pending.installationID ||
+ pending.workspaceID !== installation.workspace_id ||
+ (pending.connectionID && pending.connectionID !== connectionID)
+ ) return state;
+ return { connection: { ...pending, installationID: installation.id } };
+ });
+ },
+ reset: (workspaceID) => set((state) =>
+ workspaceID && state.connection?.workspaceID !== workspaceID
+ ? state
+ : { connection: null },
+ ),
+}));
diff --git a/packages/core/github/index.ts b/packages/core/github/index.ts
index 7ccaeb708c..3cd7fd7330 100644
--- a/packages/core/github/index.ts
+++ b/packages/core/github/index.ts
@@ -5,3 +5,5 @@ export * from "./settings";
export * from "./use-github-settings";
export * from "./repo-ref";
export * from "./stars";
+export * from "./connection-event";
+export * from "./connection-store";
diff --git a/packages/core/realtime/provider.tsx b/packages/core/realtime/provider.tsx
index b7f63824f1..b1ee65aa25 100644
--- a/packages/core/realtime/provider.tsx
+++ b/packages/core/realtime/provider.tsx
@@ -20,6 +20,7 @@ import {
subscribeToCurrentSlug,
} from "../platform/workspace-storage";
import { useLocalSearchIndexSync } from "../search-index/hooks";
+import { useGitHubConnectionStore } from "../github/connection-store";
import { createLogger } from "../logger";
import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
@@ -71,6 +72,8 @@ export function WSProvider({
const wsId = useSyncExternalStore(subscribeToCurrentSlug, getCurrentWsId, () => null);
const [wsClient, setWsClient] = useState<WSClient | null>(null);
+ useEffect(() => () => useGitHubConnectionStore.getState().reset(), [user?.id]);
+
// Depend on identity primitives instead of the object reference so a parent
// re-render that passes a new `{ platform, version, os }` literal does not
// tear down and reconnect the WS when nothing about the identity actually
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 4a7d4ef744..102d744c63 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -17,6 +17,7 @@ import { issueStatusKeys } from "../issue-statuses/queries";
import { issueWorkflowKeys } from "../issue-workflows/queries";
import { issueViewKeys } from "../issue-views/queries";
import { issueViewPrefKeys } from "../issue-views/preferences";
+import { useGitHubConnectionStore } from "../github/connection-store";
import {
markWorkspaceDeletePending,
unmarkWorkspaceDeletePending,
@@ -84,6 +85,25 @@ describe("useRealtimeSync — ws instance change", () => {
invalidateSpy = vi.spyOn(qc, "invalidateQueries");
});
+ it("receives a GitHub handoff without a settings-page subscriber and removes its listener on teardown", () => {
+ const ws = createMockWs();
+ const unsubscribe = vi.fn();
+ vi.mocked(ws.on).mockImplementation((event) =>
+ event === "github_installation:created" ? unsubscribe : () => {},
+ );
+ const { unmount } = renderHook(() => useRealtimeSync(ws, stores), {
+ wrapper: createWrapper(qc),
+ });
+ const handler = vi.mocked(ws.on).mock.calls.find(([name]) => name === "github_installation:created")?.[1];
+ expect(handler).toBeDefined();
+ useGitHubConnectionStore.getState().begin("ws-1", "own-connection");
+ act(() => handler!({ installation: { id: "install-1", workspace_id: "ws-1" }, connection_id: "own-connection" }));
+ expect(useGitHubConnectionStore.getState().connection?.installationID).toBe("install-1");
+ unmount();
+ expect(unsubscribe).toHaveBeenCalled();
+ useGitHubConnectionStore.getState().reset();
+ });
+
it("skips invalidation on first non-null ws instance", () => {
const ws = createMockWs();
renderHook(() => useRealtimeSync(ws, stores), {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 4a1e5012dd..95065f3fe1 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -32,6 +32,7 @@ import {
agentTasksKeys,
} from "../agents/queries";
import { githubKeys } from "../github/queries";
+import { useGitHubConnectionStore } from "../github/connection-store";
import { larkKeys } from "../lark/queries";
import { slackKeys } from "../slack/queries";
import { dingtalkKeys } from "../dingtalk/queries";
@@ -1152,6 +1153,10 @@ export function useRealtimeSync(
// Filtering by actor_id would block other tabs of the same user.
// Instead, both mutations and WS handlers use dedup checks to be idempotent.
+ const unsubGitHubInstallationCreated = ws.on("github_installation:created", (payload) => {
+ useGitHubConnectionStore.getState().complete(payload);
+ });
+
const unsubIssueUpdated = ws.on("issue:updated", (p) => {
const payload = p as IssueUpdatedPayload;
const { issue } = payload;
@@ -1923,6 +1928,7 @@ export function useRealtimeSync(
return () => {
unsubAny();
+ unsubGitHubInstallationCreated();
unsubIssueUpdated();
unsubIssueCreated();
unsubIssueDeleted();
diff --git a/packages/core/types/github.ts b/packages/core/types/github.ts
index f785009bbc..dc56e4eb89 100644
--- a/packages/core/types/github.ts
+++ b/packages/core/types/github.ts
@@ -172,6 +172,7 @@ export interface ListGitHubInstallationsResponse {
}
export interface GitHubConnectResponse {
+ connection_id?: string;
/** The GitHub App install URL the browser should open. Empty when `configured` is false. */
url?: string;
configured: boolean;
@@ -189,6 +190,7 @@ export interface GitHubRepository {
}
export interface ListGitHubRepositoriesResponse {
+ repository_selection?: "all" | "selected" | "unknown";
repositories: GitHubRepository[];
total_count: number;
next_page: number | null;
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 1ed63bb5c3..afd6cdfb5f 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1374,7 +1374,9 @@
"github_load_more": "Load more",
"github_selected_count": "{{count}} selected",
"github_cancel": "Cancel",
- "github_import": "Add repositories",
+ "github_import": "Add {{count}} repositories",
+ "github_import_one": "Add {{count}} repository",
+ "github_import_other": "Add {{count}} repositories",
"save": "Save",
"saving": "Saving...",
"saved_hint": "All changes saved",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index b3794cfb7b..84f531102e 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -1374,7 +1374,9 @@
"github_load_more": "Cargar más",
"github_selected_count": "{{count}} seleccionados",
"github_cancel": "Cancelar",
- "github_import": "Añadir repositorios",
+ "github_import": "Añadir {{count}} repositorios",
+ "github_import_one": "Añadir {{count}} repositorio",
+ "github_import_other": "Añadir {{count}} repositorios",
"save": "Guardar",
"saving": "Guardando...",
"saved_hint": "Todos los cambios guardados",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index a9d6409930..d2c63c3bd9 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -1374,7 +1374,9 @@
"github_load_more": "Charger plus",
"github_selected_count": "{{count}} sélectionnés",
"github_cancel": "Annuler",
- "github_import": "Ajouter les dépôts",
+ "github_import": "Ajouter {{count}} dépôts",
+ "github_import_one": "Ajouter {{count}} dépôt",
+ "github_import_other": "Ajouter {{count}} dépôts",
"save": "Enregistrer",
"saving": "Enregistrement...",
"saved_hint": "Toutes les modifications sont enregistrées",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 4d1ea5b72d..d7d46c68ea 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1364,7 +1364,8 @@
"github_load_more": "さらに読み込む",
"github_selected_count": "{{count}} 件選択",
"github_cancel": "キャンセル",
- "github_import": "リポジトリを追加",
+ "github_import": "{{count}} 件のリポジトリを追加",
+ "github_import_other": "{{count}} 件のリポジトリを追加",
"save": "保存",
"saving": "保存中...",
"saved_hint": "すべての変更を保存しました",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index cbac30aafe..b751032fcf 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1107,7 +1107,8 @@
"github_load_more": "더 불러오기",
"github_selected_count": "{{count}}개 선택",
"github_cancel": "취소",
- "github_import": "저장소 추가",
+ "github_import": "저장소 {{count}}개 추가",
+ "github_import_other": "저장소 {{count}}개 추가",
"save": "저장",
"saving": "저장하는 중...",
"saved_hint": "모든 변경사항 저장됨",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 566116e8d0..9ee1d39e3a 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -1393,7 +1393,11 @@
"github_load_more": "Загрузить ещё",
"github_selected_count": "Выбрано: {{count}}",
"github_cancel": "Отмена",
- "github_import": "Добавить репозитории",
+ "github_import": "Добавить {{count}} репозиториев",
+ "github_import_one": "Добавить {{count}} репозиторий",
+ "github_import_other": "Добавить {{count}} репозиториев",
+ "github_import_few": "Добавить {{count}} репозитория",
+ "github_import_many": "Добавить {{count}} репозиториев",
"save": "Сохранить",
"saving": "Сохранение...",
"saved_hint": "Все изменения сохранены",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index f02a6e155e..d297f8cdb9 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1364,7 +1364,8 @@
"github_load_more": "加载更多",
"github_selected_count": "已选择 {{count}} 个",
"github_cancel": "取消",
- "github_import": "添加仓库",
+ "github_import": "添加 {{count}} 个仓库",
+ "github_import_other": "添加 {{count}} 个仓库",
"save": "保存",
"saving": "保存中...",
"saved_hint": "所有改动已保存",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 340b07647a..51c03221ee 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -1364,7 +1364,8 @@
"github_load_more": "載入更多",
"github_selected_count": "已選擇 {{count}} 個",
"github_cancel": "取消",
- "github_import": "新增倉庫",
+ "github_import": "新增 {{count}} 個倉庫",
+ "github_import_other": "新增 {{count}} 個倉庫",
"save": "儲存",
"saving": "儲存中...",
"saved_hint": "所有改動已儲存",
diff --git a/packages/views/settings/components/code-tab.test.tsx b/packages/views/settings/components/code-tab.test.tsx
index fdcd982fbf..3e8cb9a8e0 100644
--- a/packages/views/settings/components/code-tab.test.tsx
+++ b/packages/views/settings/components/code-tab.test.tsx
@@ -9,7 +9,7 @@ import enSettings from "../../locales/en/settings.json";
const mockUpdateWorkspace = vi.hoisted(() => vi.fn());
const mockDeleteInstallation = vi.hoisted(() => vi.fn());
-const mockGetConnectURL = vi.hoisted(() => vi.fn());
+const mockConnectGitHub = vi.hoisted(() => vi.fn());
const mockInvalidate = vi.hoisted(() => vi.fn());
const workspaceRef = vi.hoisted(() => ({
@@ -66,11 +66,14 @@ vi.mock("@multica/core/api", () => ({
api: {
updateWorkspace: mockUpdateWorkspace,
deleteGitHubInstallation: mockDeleteInstallation,
- getGitHubConnectURL: mockGetConnectURL,
+ getGitHubConnectURL: mockConnectGitHub,
},
}));
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
// The repository list and self-hosted rows have their own tests.
+vi.mock("./use-connect-github", () => ({
+ useConnectGitHub: () => ({ connecting: false, connect: mockConnectGitHub, connectedInstallationID: "", reset: vi.fn() }),
+}));
vi.mock("./repositories-section", () => ({ RepositoriesSection: () => null }));
vi.mock("./code-vcs", () => ({ VCSConnectionRows: () => <div>VCS rows</div> }));
// The merge rule editor has its own test on the statuses it offers.
@@ -121,19 +124,12 @@ function connect() {
}
describe("CodeTab — GitHub", () => {
- it("offers to connect GitHub and opens the install flow", async () => {
- mockGetConnectURL.mockResolvedValue({ configured: true, url: "https://github.com/apps/x" });
- const open = vi.spyOn(window, "open").mockImplementation(() => null);
+ it("offers to connect GitHub through the shared connection action", async () => {
const user = userEvent.setup();
render(<CodeTab />, { wrapper: Wrapper });
-
expect(screen.getByText("Not connected")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Connect GitHub" }));
-
- await waitFor(() =>
- expect(open).toHaveBeenCalledWith("https://github.com/apps/x", "_blank", "noopener"),
- );
- open.mockRestore();
+ expect(mockConnectGitHub).toHaveBeenCalledOnce();
});
it("names the account and who connected it", () => {
diff --git a/packages/views/settings/components/code-tab.tsx b/packages/views/settings/components/code-tab.tsx
index 2c26038bd4..a3d8ff6e78 100644
--- a/packages/views/settings/components/code-tab.tsx
+++ b/packages/views/settings/components/code-tab.tsx
@@ -44,6 +44,7 @@ import { GitHubMark } from "./github-mark";
import { VCSConnectionRows } from "./code-vcs";
import { HostMark, HostStatus } from "./code-host";
import { RepositoriesSection } from "./repositories-section";
+import { useConnectGitHub } from "./use-connect-github";
import { PRMergeStatusRow } from "./pr-merge-status-row";
type GitHubSettingsKey =
@@ -81,7 +82,8 @@ export function CodeTab() {
const flags = deriveGitHubSettings(workspace);
const [savingKey, setSavingKey] = useState<GitHubSettingsKey | null>(null);
- const [connecting, setConnecting] = useState(false);
+ const githubConnection = useConnectGitHub(wsId);
+ const { connecting, connect: handleConnect } = githubConnection;
const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
const [disconnecting, setDisconnecting] = useState(false);
@@ -104,22 +106,6 @@ export function CodeTab() {
}
}
- async function handleConnect() {
- setConnecting(true);
- try {
- const resp = await api.getGitHubConnectURL(wsId);
- if (!resp.configured || !resp.url) {
- toast.error(t(($) => $.github.toast_not_configured));
- return;
- }
- window.open(resp.url, "_blank", "noopener");
- } catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.github.toast_open_failed));
- } finally {
- setConnecting(false);
- }
- }
-
async function handleDisconnect() {
if (!disconnectTarget || disconnecting) return;
setDisconnecting(true);
@@ -262,7 +248,7 @@ export function CodeTab() {
</SettingsCard>
</SettingsSection>
- <RepositoriesSection />
+ <RepositoriesSection connection={githubConnection} />
<SettingsSection
title={t(($) => $.code.pr_linking_title)}
diff --git a/packages/views/settings/components/repositories-section.test.tsx b/packages/views/settings/components/repositories-section.test.tsx
index 7c2dcbeefb..fff2dce5e7 100644
--- a/packages/views/settings/components/repositories-section.test.tsx
+++ b/packages/views/settings/components/repositories-section.test.tsx
@@ -7,7 +7,7 @@ import enCommon from "../../locales/en/common.json";
import enSettings from "../../locales/en/settings.json";
const mockUpdateWorkspace = vi.hoisted(() => vi.fn());
-const mockGetGitHubConnectURL = vi.hoisted(() => vi.fn());
+const mockConnectGitHub = vi.hoisted(() => vi.fn());
const mockNavReplace = vi.hoisted(() => vi.fn());
const mockToastError = vi.hoisted(() => vi.fn());
const workspaceRef = vi.hoisted(() => ({
@@ -44,6 +44,7 @@ const githubRepositoriesRef = vi.hoisted(() => ({
default_branch: string;
}[],
}));
+const repositorySelectionRef = vi.hoisted(() => ({ current: "unknown" }));
const searchParamsRef = vi.hoisted(() => ({
current: new URLSearchParams("tab=code"),
}));
@@ -54,6 +55,7 @@ vi.mock("@tanstack/react-query", () => ({
data: {
pages: [
{
+ repository_selection: repositorySelectionRef.current,
repositories: githubRepositoriesRef.current,
total_count: githubRepositoriesRef.current.length,
next_page: null,
@@ -84,7 +86,6 @@ vi.mock("@multica/core/workspace/queries", () => ({
vi.mock("@multica/core/api", () => ({
api: {
updateWorkspace: mockUpdateWorkspace,
- getGitHubConnectURL: mockGetGitHubConnectURL,
},
}));
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: mockToastError } }));
@@ -99,6 +100,13 @@ vi.mock("../../navigation", () => ({
import { RepositoriesSection, repositoryIdentity } from "./repositories-section";
+const connection = {
+ connecting: false,
+ connect: mockConnectGitHub,
+ connectedInstallationID: "",
+ reset: vi.fn(),
+};
+
const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
function Wrapper({ children }: { children: ReactNode }) {
@@ -126,7 +134,9 @@ beforeEach(() => {
};
githubQueryStateRef.current = { isPending: false, isFetching: false };
githubRepositoriesRef.current = [];
+ repositorySelectionRef.current = "unknown";
searchParamsRef.current = new URLSearchParams("tab=code");
+ connection.connectedInstallationID = "";
mockUpdateWorkspace.mockImplementation(async (_id: string, payload: object) => ({
...workspaceRef.current,
...payload,
@@ -139,7 +149,7 @@ async function openAddMenu(user: ReturnType<typeof userEvent.setup>) {
describe("RepositoriesSection", () => {
it("lists repositories as read-only rows with their description", () => {
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
expect(screen.getByText("https://github.com/multica-ai/multica")).toBeInTheDocument();
expect(screen.getByText("Main app")).toBeInTheDocument();
@@ -148,7 +158,7 @@ describe("RepositoriesSection", () => {
it("adds a repository from the dialog in one request", async () => {
const user = userEvent.setup();
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await openAddMenu(user);
await user.click(await screen.findByRole("menuitem", { name: "Enter a URL..." }));
@@ -179,7 +189,7 @@ describe("RepositoriesSection", () => {
it("refuses a repository that is already listed under another URL form", async () => {
const user = userEvent.setup();
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await openAddMenu(user);
await user.click(await screen.findByRole("menuitem", { name: "Enter a URL..." }));
@@ -196,7 +206,7 @@ describe("RepositoriesSection", () => {
it("keeps the dialog open with the input when saving fails", async () => {
mockUpdateWorkspace.mockRejectedValueOnce(new Error("boom"));
const user = userEvent.setup();
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await user.click(screen.getByRole("button", { name: /Actions for https:\/\/github.com\/multica-ai\/multica/ }));
await user.click(await screen.findByRole("menuitem", { name: "Edit" }));
@@ -213,7 +223,7 @@ describe("RepositoriesSection", () => {
it("removes a repository only after confirmation", async () => {
const user = userEvent.setup();
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await user.click(screen.getByRole("button", { name: /Actions for https:\/\/github.com\/multica-ai\/multica/ }));
await user.click(await screen.findByRole("menuitem", { name: "Delete repository" }));
@@ -231,39 +241,24 @@ describe("RepositoriesSection", () => {
it("hides every write affordance from members", () => {
roleRef.current = "member";
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
expect(screen.queryByRole("button", { name: /Add repository/ })).toBeNull();
expect(screen.queryByRole("button", { name: /Actions for/ })).toBeNull();
});
- it("starts GitHub connection with the signed repository return target", async () => {
- mockGetGitHubConnectURL.mockResolvedValue({
- configured: true,
- url: "https://github.com/apps/multica/installations/new",
- });
- const open = vi.spyOn(window, "open").mockImplementation(() => null);
+ it("starts GitHub connection through the shared handler", async () => {
const user = userEvent.setup();
- render(<RepositoriesSection />, { wrapper: Wrapper });
-
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await openAddMenu(user);
await user.click(await screen.findByRole("menuitem", { name: /Connect GitHub/ }));
-
- await waitFor(() => {
- expect(mockGetGitHubConnectURL).toHaveBeenCalledWith("workspace-1", "repositories");
- expect(open).toHaveBeenCalledWith(
- "https://github.com/apps/multica/installations/new",
- "_blank",
- "noopener",
- );
- });
- open.mockRestore();
+ expect(mockConnectGitHub).toHaveBeenCalledOnce();
});
it("explains why GitHub import is unavailable when browsing is not configured", async () => {
githubRef.current = { ...githubRef.current, repository_browse_configured: false };
const user = userEvent.setup();
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await openAddMenu(user);
const item = await screen.findByRole("menuitem", { name: /Connect GitHub/ });
@@ -303,7 +298,7 @@ describe("RepositoriesSection", () => {
},
];
const user = userEvent.setup();
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await openAddMenu(user);
await user.click(await screen.findByRole("menuitem", { name: /Choose from GitHub/ }));
@@ -315,7 +310,7 @@ describe("RepositoriesSection", () => {
).toBe(true);
await user.click(checkboxes[1]!);
- await user.click(screen.getByRole("button", { name: "Add repositories" }));
+ await user.click(screen.getByRole("button", { name: "Add 1 repository" }));
await waitFor(() => {
expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
@@ -334,7 +329,7 @@ describe("RepositoriesSection", () => {
};
searchParamsRef.current = new URLSearchParams("tab=repositories&github_connected=1");
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
expect(
await screen.findByRole("heading", { name: "Choose GitHub repositories" }),
@@ -342,10 +337,46 @@ describe("RepositoriesSection", () => {
expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=repositories");
});
+ it.each(["selected", "all", "unknown"])("preselects only explicitly selected authorizations (%s) for the returned installation", async (selection) => {
+ const user = userEvent.setup();
+ githubRef.current.installations = [
+ { id: "old-install", account_login: "old-org" },
+ { id: "new-install", account_login: "new-org" },
+ ];
+ repositorySelectionRef.current = selection;
+ githubRepositoriesRef.current = [
+ { id: 1, full_name: "new-org/api", clone_url: "https://github.com/new-org/api.git", html_url: "https://github.com/new-org/api", description: null, private: true, archived: false, default_branch: "main" },
+ { id: 2, full_name: "new-org/archived", clone_url: "https://github.com/new-org/archived.git", html_url: "https://github.com/new-org/archived", description: null, private: true, archived: true, default_branch: "main" },
+ ];
+ searchParamsRef.current = new URLSearchParams("tab=code&github_connected=1&github_installation=new-install");
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
+ const checkbox = await screen.findByRole("checkbox", { name: /new-org\/api/ });
+ if (selection === "selected") {
+ await waitFor(() => expect(checkbox).toBeChecked());
+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();
+ await user.click(checkbox);
+ expect(checkbox).not.toBeChecked();
+ expect(screen.getByRole("button", { name: "Add 0 repositories" })).toBeDisabled();
+ } else {
+ expect(checkbox).not.toBeChecked();
+ }
+ expect(screen.getByRole("checkbox", { name: /new-org\/archived/ })).not.toBeChecked();
+ expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=code");
+ });
+
+ it("opens the picker for the installation completed in the desktop window", async () => {
+ githubRef.current.installations = [{ id: "new-install", account_login: "new-org" }];
+ connection.connectedInstallationID = "new-install";
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
+ expect(await screen.findByRole("heading", { name: "Choose GitHub repositories" })).toBeInTheDocument();
+ expect(connection.reset).toHaveBeenCalled();
+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();
+ });
+
it("clears the GitHub callback query after an empty installation result", async () => {
searchParamsRef.current = new URLSearchParams("tab=repositories&github_connected=1");
- render(<RepositoriesSection />, { wrapper: Wrapper });
+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });
await waitFor(() => {
expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=repositories");
diff --git a/packages/views/settings/components/repositories-section.tsx b/packages/views/settings/components/repositories-section.tsx
index 634c695784..9fc119fc28 100644
--- a/packages/views/settings/components/repositories-section.tsx
+++ b/packages/views/settings/components/repositories-section.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import {
ChevronDown,
FolderGit2,
@@ -72,6 +72,7 @@ import type {
import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { SettingsCard, SettingsSection } from "./settings-layout";
+import type { useConnectGitHub } from "./use-connect-github";
import { GitHubMark } from "./github-mark";
const EMPTY_REPOSITORIES: WorkspaceRepo[] = [];
@@ -131,7 +132,7 @@ interface RepositoryDraft {
* and editing happen in a dialog that saves on confirm, so a half-typed URL
* is never persisted and every change is one deliberate request.
*/
-export function RepositoriesSection() {
+export function RepositoriesSection({ connection }: { connection: ReturnType<typeof useConnectGitHub> }) {
const { t } = useT("settings");
const workspace = useCurrentWorkspace();
const wsId = useWorkspaceId();
@@ -144,7 +145,15 @@ export function RepositoriesSection() {
const [draft, setDraft] = useState<RepositoryDraft | null>(null);
const [saving, setSaving] = useState(false);
const [pendingRemovalIndex, setPendingRemovalIndex] = useState<number | null>(null);
- const [connectingGitHub, setConnectingGitHub] = useState(false);
+ const {
+ connecting: connectingGitHub,
+ connect: connectGitHub,
+ connectedInstallationID,
+ reset: resetConnection,
+ } = connection;
+ const [preselectInstallationID, setPreselectInstallationID] = useState("");
+ const preselectedRepositoryIDs = useRef(new Set<number>());
+ const handledCallback = useRef("");
const [githubPickerOpen, setGitHubPickerOpen] = useState(false);
const [selectedInstallationID, setSelectedInstallationID] = useState("");
const [selectedRepositories, setSelectedRepositories] = useState<
@@ -215,6 +224,8 @@ export function RepositoriesSection() {
// error). Open the picker once the installation list reflects the new
// install, then drop the one-shot params so a refresh does not repeat it.
useEffect(() => {
+ const callbackKey = navigation.searchParams.toString();
+ if (handledCallback.current === callbackKey) return;
const connected = navigation.searchParams.get("github_connected") === "1";
const githubError = navigation.searchParams.get("github_error");
if ((!connected && !githubError) || !canManageWorkspace) return;
@@ -225,11 +236,17 @@ export function RepositoriesSection() {
return;
}
+ handledCallback.current = callbackKey;
if (githubError) {
toast.error(t(($) => $.repositories.github_connect_failed));
} else if (githubInstallations.length > 0 && githubBrowseConfigured) {
- setSelectedInstallationID(githubInstallations[0]!.id);
- setGitHubPickerOpen(true);
+ const installationID = navigation.searchParams.get("github_installation") ?? githubInstallations[0]!.id;
+ if (githubInstallations.some((installation) => installation.id === installationID)) {
+ setSelectedInstallationID(installationID);
+ setPreselectInstallationID(installationID);
+ preselectedRepositoryIDs.current.clear();
+ setGitHubPickerOpen(true);
+ }
} else if (githubInstallations.length > 0) {
toast.error(t(($) => $.repositories.github_browse_not_configured));
}
@@ -237,6 +254,7 @@ export function RepositoriesSection() {
const next = new URLSearchParams(navigation.searchParams);
next.delete("github_connected");
next.delete("github_error");
+ next.delete("github_installation");
const search = next.toString();
navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}`);
}, [
@@ -249,6 +267,55 @@ export function RepositoriesSection() {
t,
]);
+ useEffect(() => {
+ const installationID = connectedInstallationID;
+ if (!installationID || !canManageWorkspace || githubInstallationsPending || githubInstallationsFetching) return;
+ if (!githubInstallations.some((installation) => installation.id === installationID)) return;
+ if (githubBrowseConfigured) {
+ setSelectedInstallationID(installationID);
+ setPreselectInstallationID(installationID);
+ preselectedRepositoryIDs.current.clear();
+ setGitHubPickerOpen(true);
+ } else {
+ toast.error(t(($) => $.repositories.github_browse_not_configured));
+ }
+ resetConnection();
+ }, [connectedInstallationID, resetConnection, canManageWorkspace, githubInstallations, githubInstallationsPending, githubInstallationsFetching, githubBrowseConfigured, t]);
+
+ const preselectingRepositories = githubPickerOpen &&
+ selectedInstallationID === preselectInstallationID &&
+ githubRepositoriesQuery.data?.pages[0]?.repository_selection === "selected";
+
+ const {
+ hasNextPage,
+ isFetchingNextPage,
+ isError: repositoriesError,
+ fetchNextPage,
+ } = githubRepositoriesQuery;
+ useEffect(() => {
+ if (preselectingRepositories && hasNextPage &&
+ !isFetchingNextPage && !repositoriesError) {
+ void fetchNextPage();
+ }
+ }, [preselectingRepositories, hasNextPage, isFetchingNextPage, repositoriesError, fetchNextPage]);
+
+ useEffect(() => {
+ if (!githubPickerOpen || selectedInstallationID !== preselectInstallationID ||
+ githubRepositoriesQuery.data?.pages[0]?.repository_selection !== "selected") return;
+ const additions = githubRepositories.filter((repository) => {
+ if (preselectedRepositoryIDs.current.has(repository.id)) return false;
+ preselectedRepositoryIDs.current.add(repository.id);
+ const identity = repositoryIdentity(repository.clone_url);
+ return !repository.archived && !!identity && !existingRepositoryIdentities.has(identity);
+ });
+ if (additions.length) {
+ setSelectedRepositories((current) => new Map([
+ ...current,
+ ...additions.map((repository) => [repository.id, repository] as const),
+ ]));
+ }
+ }, [githubPickerOpen, selectedInstallationID, preselectInstallationID, githubRepositoriesQuery.data, githubRepositories, existingRepositoryIdentities]);
+
const persist = async (next: WorkspaceRepo[]) => {
if (!workspace) return false;
setSaving(true);
@@ -310,28 +377,10 @@ export function RepositoriesSection() {
setGitHubPickerOpen(true);
};
- const connectGitHub = async () => {
- setConnectingGitHub(true);
- try {
- const response = await api.getGitHubConnectURL(wsId, "repositories");
- if (!response.configured || !response.url) {
- toast.error(t(($) => $.repositories.github_not_configured));
- return;
- }
- window.open(response.url, "_blank", "noopener");
- } catch (error) {
- toast.error(
- error instanceof Error
- ? error.message
- : t(($) => $.repositories.github_connect_failed),
- );
- } finally {
- setConnectingGitHub(false);
- }
- };
-
const closeGitHubPicker = () => {
setGitHubPickerOpen(false);
+ setPreselectInstallationID("");
+ preselectedRepositoryIDs.current.clear();
setSelectedRepositories(new Map());
setRepositorySearch("");
};
@@ -762,10 +811,10 @@ export function RepositoriesSection() {
</Button>
<Button
onClick={() => void importGitHubRepositories()}
- disabled={selectedRepositories.size === 0 || saving}
+ disabled={selectedRepositories.size === 0 || saving || (preselectingRepositories && (githubRepositoriesQuery.hasNextPage || githubRepositoriesQuery.isFetchingNextPage))}
aria-busy={saving || undefined}
>
- {t(($) => $.repositories.github_import)}
+ {t(($) => $.repositories.github_import, { count: selectedRepositories.size })}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/packages/views/settings/components/use-connect-github.test.tsx b/packages/views/settings/components/use-connect-github.test.tsx
new file mode 100644
index 0000000000..bb574eb939
--- /dev/null
+++ b/packages/views/settings/components/use-connect-github.test.tsx
@@ -0,0 +1,96 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import { useGitHubConnectionStore } from "@multica/core/github";
+
+const mocks = vi.hoisted(() => ({
+ connect: vi.fn(),
+ open: vi.fn(),
+ desktop: false,
+}));
+vi.mock("@multica/core/api", () => ({ api: { getGitHubConnectURL: mocks.connect } }));
+vi.mock("../../platform", () => ({
+ isDesktopShell: () => mocks.desktop,
+ openExternal: mocks.open,
+}));
+vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "Connection failed" }) }));
+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+
+import { useConnectGitHub } from "./use-connect-github";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useGitHubConnectionStore.getState().reset();
+ mocks.desktop = false;
+ mocks.connect.mockResolvedValue({ configured: true, url: "https://github.com/apps/test/installations/new", connection_id: "desktop-nonce" });
+});
+
+it("uses the same browser tab from the shared connection action", async () => {
+ const { result } = renderHook(() => useConnectGitHub("ws-1"));
+ await act(() => result.current.connect());
+ expect(mocks.connect).toHaveBeenCalledWith("ws-1", { desktop: false });
+ expect(mocks.open).toHaveBeenCalledWith("https://github.com/apps/test/installations/new", { webTarget: "same-tab" });
+ act(() => useGitHubConnectionStore.getState().complete({ installation: { id: "install-1", workspace_id: "ws-1" }, connection_id: "desktop-nonce" }));
+ expect(result.current.connectedInstallationID).toBe("");
+});
+
+it("completes only the desktop connection initiated in this workspace and window", async () => {
+ mocks.desktop = true;
+ const { result } = renderHook(() => useConnectGitHub("ws-1"));
+ const event = { installation: { id: "install-1", workspace_id: "ws-1" }, connection_id: "desktop-nonce" };
+ act(() => useGitHubConnectionStore.getState().complete(event));
+ expect(result.current.connectedInstallationID).toBe("");
+ await act(() => result.current.connect());
+ act(() => useGitHubConnectionStore.getState().complete({ ...event, connection_id: "another-window" }));
+ act(() => useGitHubConnectionStore.getState().complete({ ...event, installation: { ...event.installation, workspace_id: "ws-2" } }));
+ act(() => useGitHubConnectionStore.getState().complete({ malformed: true }));
+ expect(result.current.connectedInstallationID).toBe("");
+ act(() => useGitHubConnectionStore.getState().complete(event));
+ await waitFor(() => expect(result.current.connectedInstallationID).toBe("install-1"));
+ act(() => result.current.reset());
+ act(() => useGitHubConnectionStore.getState().complete(event));
+ expect(result.current.connectedInstallationID).toBe("");
+});
+
+it("does not open a browser when GitHub is unconfigured", async () => {
+ mocks.connect.mockResolvedValue({ configured: false });
+ const { result } = renderHook(() => useConnectGitHub("ws-1"));
+ await act(() => result.current.connect());
+ expect(mocks.open).not.toHaveBeenCalled();
+ expect(result.current.connecting).toBe(false);
+});
+
+it("continues a desktop connection after leaving and returning to Code settings", async () => {
+ mocks.desktop = true;
+ const original = renderHook(() => useConnectGitHub("ws-1"));
+ await act(() => original.result.current.connect());
+ original.unmount();
+
+ const returned = renderHook(() => useConnectGitHub("ws-1"));
+ act(() => useGitHubConnectionStore.getState().complete({
+ installation: { id: "install-1", workspace_id: "ws-1" },
+ connection_id: "desktop-nonce",
+ }));
+ expect(returned.result.current.connectedInstallationID).toBe("install-1");
+});
+
+it("retains completion received while Code settings is unmounted and consumes it only once", async () => {
+ mocks.desktop = true;
+ const original = renderHook(() => useConnectGitHub("ws-1"));
+ await act(() => original.result.current.connect());
+ original.unmount();
+ act(() => useGitHubConnectionStore.getState().complete({
+ installation: { id: "install-1", workspace_id: "ws-1" },
+ connection_id: "desktop-nonce",
+ }));
+
+ const otherWorkspace = renderHook(() => useConnectGitHub("ws-2"));
+ expect(otherWorkspace.result.current.connectedInstallationID).toBe("");
+ act(() => otherWorkspace.result.current.reset());
+ otherWorkspace.unmount();
+ const returned = renderHook(() => useConnectGitHub("ws-1"));
+ expect(returned.result.current.connectedInstallationID).toBe("install-1");
+ act(() => returned.result.current.reset());
+ returned.unmount();
+ const reopened = renderHook(() => useConnectGitHub("ws-1"));
+ expect(reopened.result.current.connectedInstallationID).toBe("");
+});
diff --git a/packages/views/settings/components/use-connect-github.ts b/packages/views/settings/components/use-connect-github.ts
new file mode 100644
index 0000000000..764213c25e
--- /dev/null
+++ b/packages/views/settings/components/use-connect-github.ts
@@ -0,0 +1,39 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { toast } from "sonner";
+import { api } from "@multica/core/api";
+import { useGitHubConnectionStore } from "@multica/core/github";
+import { isDesktopShell, openExternal } from "../../platform";
+import { useT } from "../../i18n";
+
+export function useConnectGitHub(wsId: string) {
+ const { t } = useT("settings");
+ const [connecting, setConnecting] = useState(false);
+ const connectedInstallationID = useGitHubConnectionStore((state) =>
+ state.connection?.workspaceID === wsId ? state.connection.installationID : "",
+ );
+
+ const connect = async () => {
+ setConnecting(true);
+ try {
+ const response = await api.getGitHubConnectURL(wsId, { desktop: isDesktopShell() });
+ if (!response.configured || !response.url) {
+ toast.error(t(($) => $.github.toast_not_configured));
+ return;
+ }
+ if (isDesktopShell()) {
+ useGitHubConnectionStore.getState().begin(wsId, response.connection_id);
+ }
+ openExternal(response.url, { webTarget: "same-tab" });
+ } catch (error) {
+ useGitHubConnectionStore.getState().reset(wsId);
+ toast.error(error instanceof Error ? error.message : t(($) => $.github.toast_open_failed));
+ } finally {
+ setConnecting(false);
+ }
+ };
+
+ const reset = useCallback(() => useGitHubConnectionStore.getState().reset(wsId), [wsId]);
+ return { connecting, connect, connectedInstallationID, reset };
+}
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 5556179769..da018f385f 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -37,11 +37,7 @@ import (
// point App-authenticated calls at an httptest server without touching GitHub.
var githubAPIBase = "https://api.github.com"
-const (
- githubReturnToGitHub = "github"
- githubReturnToRepositories = "repositories"
- githubAPIResponseLimit = 4 << 20
-)
+const githubAPIResponseLimit = 4 << 20
// ── Response shapes ─────────────────────────────────────────────────────────
@@ -144,8 +140,9 @@ type GitHubPullRequestResponse struct {
}
type GitHubConnectResponse struct {
- URL string `json:"url"`
- Configured bool `json:"configured"`
+ ConnectionID string `json:"connection_id,omitempty"`
+ URL string `json:"url"`
+ Configured bool `json:"configured"`
}
type GitHubRepositoryResponse struct {
@@ -160,9 +157,10 @@ type GitHubRepositoryResponse struct {
}
type GitHubRepositoriesResponse struct {
- Repositories []GitHubRepositoryResponse `json:"repositories"`
- TotalCount int64 `json:"total_count"`
- NextPage *int `json:"next_page"`
+ RepositorySelection string `json:"repository_selection,omitempty"`
+ Repositories []GitHubRepositoryResponse `json:"repositories"`
+ TotalCount int64 `json:"total_count"`
+ NextPage *int `json:"next_page"`
}
func githubInstallationToResponse(i db.GithubInstallation) GitHubInstallationResponse {
@@ -389,38 +387,35 @@ func isGitHubRepositoryBrowseConfigured() bool {
// install flow so the setup callback can recover the workspace without
// trusting query params alone. Format: "<workspaceID>.<nonce>.<sigHex>".
func signState(workspaceID string) (string, error) {
- return signStateForReturn(workspaceID, githubReturnToGitHub)
+ return signGitHubState(workspaceID, false)
}
-func signStateForReturn(workspaceID, returnTo string) (string, error) {
+func signGitHubState(workspaceID string, desktop bool) (string, error) {
secret := githubWebhookSecret()
if secret == "" {
return "", errors.New("github integration is not configured")
}
- if !isAllowedGitHubReturnTo(returnTo) {
- return "", errors.New("invalid github return target")
- }
nonceBytes := make([]byte, 12)
if _, err := rand.Read(nonceBytes); err != nil {
return "", err
}
nonce := hex.EncodeToString(nonceBytes)
- payload := workspaceID + "." + nonce
- if returnTo != githubReturnToGitHub {
- payload = workspaceID + "." + returnTo + "." + nonce
+ // Keep the three-part format readable by installed clients and older servers.
+ if desktop {
+ nonce = "desktop-" + nonce
}
+ payload := workspaceID + "." + nonce
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(payload))
- sig := hex.EncodeToString(mac.Sum(nil))
- return payload + "." + sig, nil
+ return payload + "." + hex.EncodeToString(mac.Sum(nil)), nil
}
func verifyState(token string) (string, bool) {
- workspaceID, _, ok := verifyStateWithReturn(token)
+ workspaceID, _, ok := verifyGitHubState(token)
return workspaceID, ok
}
-func verifyStateWithReturn(token string) (workspaceID, returnTo string, ok bool) {
+func verifyGitHubState(token string) (workspaceID, connectionID string, ok bool) {
secret := githubWebhookSecret()
if secret == "" {
return "", "", false
@@ -429,36 +424,21 @@ func verifyStateWithReturn(token string) (workspaceID, returnTo string, ok bool)
if len(parts) != 3 && len(parts) != 4 {
return "", "", false
}
- workspaceID = parts[0]
- returnTo = githubReturnToGitHub
- nonceIndex := 1
- if len(parts) == 4 {
- returnTo = parts[1]
- nonceIndex = 2
- if !isAllowedGitHubReturnTo(returnTo) {
- return "", "", false
- }
+ // Accept in-flight links from before the Code settings page was unified.
+ if len(parts) == 4 && parts[1] != "github" && parts[1] != "repositories" {
+ return "", "", false
}
- sig := parts[nonceIndex+1]
- payload := strings.Join(parts[:nonceIndex+1], ".")
+ payload := strings.Join(parts[:len(parts)-1], ".")
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(payload))
- expected := hex.EncodeToString(mac.Sum(nil))
- if !hmac.Equal([]byte(expected), []byte(sig)) {
+ if !hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))), []byte(parts[len(parts)-1])) {
return "", "", false
}
- return workspaceID, returnTo, true
-}
-
-func isAllowedGitHubReturnTo(returnTo string) bool {
- return returnTo == githubReturnToGitHub || returnTo == githubReturnToRepositories
+ return parts[0], parts[len(parts)-2], true
}
-func githubSettingsURL(frontend, returnTo string) string {
- if !isAllowedGitHubReturnTo(returnTo) {
- returnTo = githubReturnToGitHub
- }
- return strings.TrimRight(frontend, "/") + "/settings?tab=" + url.QueryEscape(returnTo)
+func githubSettingsURL(frontend string) string {
+ return strings.TrimRight(frontend, "/") + "/settings?tab=code"
}
// GitHubConnect (GET /api/workspaces/{id}/github/connect) returns the URL the
@@ -473,16 +453,8 @@ func (h *Handler) GitHubConnect(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, GitHubConnectResponse{Configured: false})
return
}
- returnTo := strings.TrimSpace(r.URL.Query().Get("return_to"))
- if returnTo == "" {
- returnTo = githubReturnToGitHub
- }
- if !isAllowedGitHubReturnTo(returnTo) {
- writeError(w, http.StatusBadRequest, "invalid return target")
- return
- }
slug := githubAppSlug()
- state, err := signStateForReturn(workspaceID, returnTo)
+ state, err := signGitHubState(workspaceID, r.URL.Query().Get("desktop") == "1")
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to sign state")
return
@@ -492,17 +464,13 @@ func (h *Handler) GitHubConnect(w http.ResponseWriter, r *http.Request) {
url.PathEscape(slug),
url.QueryEscape(state),
)
- writeJSON(w, http.StatusOK, GitHubConnectResponse{URL: installURL, Configured: true})
+ writeJSON(w, http.StatusOK, GitHubConnectResponse{URL: installURL, Configured: true, ConnectionID: strings.Split(state, ".")[1]})
}
// GitHubSetupCallback (GET /api/github/setup) handles the redirect GitHub
// sends after a user installs (or re-authorizes) the App. We expect
// ?installation_id=<id>&state=<signed token>. We persist the installation
-// row (workspace ↔ installation_id mapping), then bounce the user back to
-// the new Settings → GitHub tab in the web app (RFC MUL-2414 §4.1). The
-// previous destination was the catch-all Settings page, which after the
-// GitHub-tab split would land users on the default profile tab instead of
-// the place that shows the connection they just completed.
+// row (workspace ↔ installation_id mapping), then returns to Code settings.
func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
installationIDStr := q.Get("installation_id")
@@ -511,18 +479,17 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
if frontend == "" {
frontend = "http://localhost:3000"
}
- settingsURL := githubSettingsURL(frontend, githubReturnToGitHub)
+ settingsURL := githubSettingsURL(frontend)
if state == "" {
http.Redirect(w, r, settingsURL+"&github_error=missing_params", http.StatusFound)
return
}
- workspaceID, returnTo, ok := verifyStateWithReturn(state)
+ workspaceID, connectionID, ok := verifyGitHubState(state)
if !ok {
http.Redirect(w, r, settingsURL+"&github_error=invalid_state", http.StatusFound)
return
}
- settingsURL = githubSettingsURL(frontend, returnTo)
if installationIDStr == "" {
http.Redirect(w, r, settingsURL+"&github_error=missing_params", http.StatusFound)
return
@@ -537,6 +504,12 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, settingsURL+"&github_error=bad_workspace", http.StatusFound)
return
}
+ workspace, err := h.Queries.GetWorkspace(r.Context(), wsUUID)
+ if err != nil {
+ http.Redirect(w, r, settingsURL+"&github_error=bad_workspace", http.StatusFound)
+ return
+ }
+ settingsURL = strings.TrimRight(frontend, "/") + "/" + url.PathEscape(workspace.Slug) + "/settings?tab=code"
// Resolve the installation against GitHub's API to capture display info.
// If the App auth is not configured we still create the row with the
// minimum we know; webhook events will refresh it as soon as one fires.
@@ -573,9 +546,15 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
return
}
h.publish(protocol.EventGitHubInstallationCreated, workspaceID, "system", "", map[string]any{
- "installation": githubInstallationToBroadcast(inst),
+ "installation": githubInstallationToBroadcast(inst),
+ "connection_id": connectionID,
})
- http.Redirect(w, r, settingsURL+"&github_connected=1", http.StatusFound)
+ if strings.HasPrefix(connectionID, "desktop-") {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = io.WriteString(w, `<!doctype html><html lang="en"><meta charset="utf-8"><title>GitHub connected</title><body><h1>GitHub connected</h1><p>Return to Multica to confirm your repositories. You can close this tab.</p></body></html>`)
+ return
+ }
+ http.Redirect(w, r, settingsURL+"&github_connected=1&github_installation="+url.QueryEscape(uuidToString(inst.ID)), http.StatusFound)
}
func (h *Handler) consumePendingGitHubInstallation(ctx context.Context, inst db.GithubInstallation) (db.GithubInstallation, error) {
@@ -857,7 +836,8 @@ func fetchGitHubInstallationRepositories(
return GitHubRepositoriesResponse{}, fmt.Errorf("create installation token: github status %d", tokenResp.StatusCode)
}
var tokenBody struct {
- Token string `json:"token"`
+ Token string `json:"token"`
+ RepositorySelection string `json:"repository_selection"`
}
if err := json.NewDecoder(io.LimitReader(tokenResp.Body, githubAPIResponseLimit)).Decode(&tokenBody); err != nil {
return GitHubRepositoriesResponse{}, fmt.Errorf("decode installation token: %w", err)
@@ -904,8 +884,9 @@ func fetchGitHubInstallationRepositories(
return GitHubRepositoriesResponse{}, fmt.Errorf("decode installation repositories: %w", err)
}
out := GitHubRepositoriesResponse{
- Repositories: make([]GitHubRepositoryResponse, 0, len(body.Repositories)),
- TotalCount: body.TotalCount,
+ RepositorySelection: tokenBody.RepositorySelection,
+ Repositories: make([]GitHubRepositoryResponse, 0, len(body.Repositories)),
+ TotalCount: body.TotalCount,
}
for _, repository := range body.Repositories {
out.Repositories = append(out.Repositories, GitHubRepositoryResponse(repository))
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index 917af991cd..1cc28f9c68 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -291,100 +291,120 @@ func TestStateRoundTrip(t *testing.T) {
}
}
-func TestStateRoundTripWithRepositoryReturnTarget(t *testing.T) {
+func TestGitHubStateDesktopAndLegacyLinks(t *testing.T) {
t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret-123")
wsID := "11111111-2222-3333-4444-555555555555"
-
- tok, err := signStateForReturn(wsID, githubReturnToRepositories)
+ token, err := signGitHubState(wsID, true)
if err != nil {
- t.Fatalf("signStateForReturn: %v", err)
- }
- if parts := strings.Split(tok, "."); len(parts) != 4 {
- t.Fatalf("repository return state has %d parts, want 4", len(parts))
- }
- gotWorkspaceID, gotReturnTo, ok := verifyStateWithReturn(tok)
- if !ok {
- t.Fatal("verifyStateWithReturn rejected a freshly-signed token")
- }
- if gotWorkspaceID != wsID || gotReturnTo != githubReturnToRepositories {
- t.Errorf(
- "verifyStateWithReturn() = (%q, %q), want (%q, %q)",
- gotWorkspaceID,
- gotReturnTo,
- wsID,
- githubReturnToRepositories,
- )
- }
-
- tampered := strings.Replace(tok, ".repositories.", ".github.", 1)
- if _, _, ok := verifyStateWithReturn(tampered); ok {
- t.Error("tampered return target should fail verification")
+ t.Fatal(err)
+ }
+ workspaceID, connectionID, ok := verifyGitHubState(token)
+ if !ok || workspaceID != wsID || !strings.HasPrefix(connectionID, "desktop-") || len(strings.Split(token, ".")) != 3 {
+ t.Fatalf("desktop state = %q, %q, %v", workspaceID, connectionID, ok)
+ }
+ if _, _, ok := verifyGitHubState(strings.Replace(token, "desktop-", "web-", 1)); ok {
+ t.Fatal("tampered client marker verified")
+ }
+ for _, target := range []string{"github", "repositories"} {
+ payload := wsID + "." + target + ".old-nonce"
+ mac := hmac.New(sha256.New, []byte("test-secret-123"))
+ mac.Write([]byte(payload))
+ token := payload + "." + hex.EncodeToString(mac.Sum(nil))
+ if got, ok := verifyState(token); !ok || got != wsID {
+ t.Fatalf("legacy %s rejected", target)
+ }
}
}
-func TestGitHubConnectRepositoryReturnTarget(t *testing.T) {
+func TestGitHubConnectUsesUnifiedState(t *testing.T) {
t.Setenv("GITHUB_APP_SLUG", "multica-test")
t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret-123")
wsID := "11111111-2222-3333-4444-555555555555"
-
- req := httptest.NewRequest(
- http.MethodGet,
- "/api/workspaces/"+wsID+"/github/connect?return_to=repositories",
- nil,
- )
- req = withURLParam(req, "id", wsID)
- rec := httptest.NewRecorder()
- (&Handler{}).GitHubConnect(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("GitHubConnect: got %d (%s)", rec.Code, rec.Body.String())
+ for _, platform := range []string{"web", "legacy-desktop", "desktop"} {
+ req := withURLParam(httptest.NewRequest(http.MethodGet, "/api/workspaces/"+wsID+"/github/connect?return_to=repositories", nil), "id", wsID)
+ req.Header.Set(middleware.HeaderClientPlatform, "desktop")
+ if platform == "desktop" {
+ req.URL.RawQuery += "&desktop=1"
+ }
+ rec := httptest.NewRecorder()
+ (&Handler{}).GitHubConnect(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("connect: %d %s", rec.Code, rec.Body.String())
+ }
+ var body GitHubConnectResponse
+ if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
+ t.Fatal(err)
+ }
+ installURL, err := url.Parse(body.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ workspaceID, connectionID, ok := verifyGitHubState(installURL.Query().Get("state"))
+ if !ok || workspaceID != wsID || connectionID != body.ConnectionID || strings.HasPrefix(connectionID, "desktop-") != (platform == "desktop") {
+ t.Fatalf("%s state = %q, %q, %v", platform, workspaceID, connectionID, ok)
+ }
}
- var body GitHubConnectResponse
- if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
- t.Fatalf("decode connect response: %v", err)
+}
+
+func TestGitHubSetupCallbackReturnsToInitiatingClient(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("handler fixture requires a database")
}
- installURL, err := url.Parse(body.URL)
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "callback-test-secret")
+ t.Setenv("FRONTEND_ORIGIN", "https://app.multica.test")
+ t.Setenv("GITHUB_APP_ID", "")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "")
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(w, http.StatusOK, map[string]any{"account": map[string]any{"login": "example-org", "type": "Organization"}})
+ }))
+ t.Cleanup(srv.Close)
+ oldBase := githubAPIBase
+ githubAPIBase = srv.URL
+ t.Cleanup(func() { githubAPIBase = oldBase })
+ workspace, err := testHandler.Queries.GetWorkspace(context.Background(), parseUUID(testWorkspaceID))
if err != nil {
- t.Fatalf("parse install URL: %v", err)
- }
- _, returnTo, ok := verifyStateWithReturn(installURL.Query().Get("state"))
- if !ok || returnTo != githubReturnToRepositories {
- t.Fatalf("signed return target = %q, valid=%v, want repositories", returnTo, ok)
+ t.Fatal(err)
}
-
- badReq := httptest.NewRequest(
- http.MethodGet,
- "/api/workspaces/"+wsID+"/github/connect?return_to=https://evil.example",
- nil,
- )
- badReq = withURLParam(badReq, "id", wsID)
- badRec := httptest.NewRecorder()
- (&Handler{}).GitHubConnect(badRec, badReq)
- if badRec.Code != http.StatusBadRequest {
- t.Fatalf("invalid return target: got %d, want 400", badRec.Code)
+ installationID := time.Now().UnixNano()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ })
+ for _, desktop := range []bool{false, true} {
+ state, err := signGitHubState(testWorkspaceID, desktop)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&state=%s", installationID, url.QueryEscape(state)), nil)
+ rec := httptest.NewRecorder()
+ testHandler.GitHubSetupCallback(rec, req)
+ if desktop {
+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Return to Multica") || rec.Header().Get("Location") != "" {
+ t.Fatalf("desktop callback: %d %s", rec.Code, rec.Body.String())
+ }
+ } else {
+ location, err := url.Parse(rec.Header().Get("Location"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rec.Code != http.StatusFound || location.Path != "/"+workspace.Slug+"/settings" || location.Query().Get("tab") != "code" || location.Query().Get("github_installation") == "" {
+ t.Fatalf("web callback: %d %s", rec.Code, location)
+ }
+ }
}
}
-func TestGitHubSetupCallbackRepositoryReturnTarget(t *testing.T) {
+func TestGitHubSetupCallbackUnifiedErrorTarget(t *testing.T) {
t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret-123")
t.Setenv("FRONTEND_ORIGIN", "https://app.multica.test/")
- wsID := "11111111-2222-3333-4444-555555555555"
- state, err := signStateForReturn(wsID, githubReturnToRepositories)
+ state, err := signState("11111111-2222-3333-4444-555555555555")
if err != nil {
- t.Fatalf("signStateForReturn: %v", err)
+ t.Fatal(err)
}
-
- req := httptest.NewRequest(
- http.MethodGet,
- "/api/github/setup?installation_id=not-a-number&state="+url.QueryEscape(state),
- nil,
- )
+ req := httptest.NewRequest(http.MethodGet, "/api/github/setup?installation_id=not-a-number&state="+url.QueryEscape(state), nil)
rec := httptest.NewRecorder()
(&Handler{}).GitHubSetupCallback(rec, req)
- if rec.Code != http.StatusFound {
- t.Fatalf("GitHubSetupCallback: got %d, want 302", rec.Code)
- }
- if got := rec.Header().Get("Location"); got != "https://app.multica.test/settings?tab=repositories&github_error=bad_installation_id" {
- t.Fatalf("redirect = %q, want repository settings error", got)
+ if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://app.multica.test/settings?tab=code&github_error=bad_installation_id" {
+ t.Fatalf("callback: %d %s", rec.Code, rec.Header().Get("Location"))
}
}
@@ -2426,7 +2446,7 @@ func TestFetchGitHubInstallationRepositories(t *testing.T) {
http.Error(w, "overbroad token permissions", http.StatusBadRequest)
return
}
- writeJSON(w, http.StatusCreated, map[string]any{"token": "installation-secret"})
+ writeJSON(w, http.StatusCreated, map[string]any{"token": "installation-secret", "repository_selection": "selected"})
case r.Method == http.MethodGet && r.URL.Path == "/installation/repositories":
if got := r.Header.Get("Authorization"); got != "Bearer installation-secret" {
http.Error(w, "bad installation token", http.StatusUnauthorized)
@@ -2470,6 +2490,9 @@ func TestFetchGitHubInstallationRepositories(t *testing.T) {
if err != nil {
t.Fatalf("fetchGitHubInstallationRepositories: %v", err)
}
+ if got.RepositorySelection != "selected" {
+ t.Fatalf("repository selection = %q", got.RepositorySelection)
+ }
if len(got.Repositories) != 1 {
t.Fatalf("repositories = %d, want 1", len(got.Repositories))
}