feat(github): unify workspace GitHub access (#2084)

This commit is contained in:
Carlos Florêncio
2026-07-31 19:20:49 +01:00
committed by GitHub
parent 1c267cf527
commit aeb7c62e49
27 changed files with 1573 additions and 419 deletions
@@ -0,0 +1,68 @@
"use client";
import { useState, type ReactNode } from "react";
import { IconInfoCircle } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@kandev/ui/drawer";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useTouchDrawer } from "@/hooks/use-compact-task-chrome";
export function GitHubAccessHelp({
label,
title,
description,
content,
}: {
label: string;
title: string;
description: string;
content?: ReactNode;
}) {
const usesTouchDrawer = useTouchDrawer();
const [open, setOpen] = useState(false);
const button = (
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11 shrink-0 cursor-pointer text-muted-foreground sm:h-6 sm:w-6"
aria-haspopup={usesTouchDrawer ? "dialog" : undefined}
aria-expanded={usesTouchDrawer ? open : undefined}
aria-label={label}
>
<IconInfoCircle className="h-4 w-4" />
</Button>
);
const trigger = usesTouchDrawer ? (
<DrawerTrigger asChild>{button}</DrawerTrigger>
) : (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent side="top" align="start" className="max-w-[320px] text-xs leading-relaxed">
{content ?? description}
</TooltipContent>
</Tooltip>
);
return (
<Drawer open={open} onOpenChange={setOpen}>
{trigger}
<DrawerContent>
<DrawerHeader>
<DrawerTitle>{title}</DrawerTitle>
<DrawerDescription className={content ? "sr-only" : undefined}>
{description}
</DrawerDescription>
</DrawerHeader>
{content && <div className="px-4 pb-4">{content}</div>}
</DrawerContent>
</Drawer>
);
}
@@ -6,13 +6,6 @@ import { cn } from "@/lib/utils";
export type GitHubAutomationMethod = "pat" | "cli" | "app";
const methods = [
{
value: "pat" as const,
label: "Personal access token",
description:
"Stored encrypted by Kandev. Workspace automation and managed task GitHub HTTPS/gh act as your account.",
icon: IconKey,
},
{
value: "cli" as const,
label: "GitHub CLI account",
@@ -20,6 +13,13 @@ const methods = [
"Resolved from one named host account when needed. Managed tasks receive a scoped brokered identity; host Git is not inherited unless selected below.",
icon: IconTerminal2,
},
{
value: "pat" as const,
label: "Personal access token",
description:
"Stored encrypted by Kandev. Workspace automation and managed task GitHub HTTPS/gh act as your account.",
icon: IconKey,
},
{
value: "app" as const,
label: "GitHub App",
@@ -5,17 +5,14 @@ import { GitHubCLIForm } from "./github-cli-form";
const mocks = vi.hoisted(() => ({
fetchAccounts: vi.fn(),
setConnection: vi.fn(),
}));
vi.mock("@/lib/api/domains/github-api", () => ({
fetchGitHubCLIAccounts: mocks.fetchAccounts,
setGitHubWorkspaceConnection: mocks.setConnection,
}));
beforeEach(() => {
mocks.fetchAccounts.mockReset();
mocks.setConnection.mockReset();
});
afterEach(() => cleanup());
@@ -26,7 +23,7 @@ describe("GitHubCLIForm", () => {
render(
<ToastProvider>
<GitHubCLIForm workspaceId="workspace-1" onSaved={vi.fn()} />
<GitHubCLIForm workspaceId="workspace-1" onAccountChange={vi.fn()} />
</ToastProvider>,
);
@@ -41,11 +38,33 @@ describe("GitHubCLIForm", () => {
render(
<ToastProvider>
<GitHubCLIForm workspaceId="workspace-1" onSaved={vi.fn()} />
<GitHubCLIForm workspaceId="workspace-1" onAccountChange={vi.fn()} />
</ToastProvider>,
);
expect(await screen.findByText(/Sign in with/)).toBeTruthy();
expect(screen.queryByRole("alert")).toBeNull();
});
it("reports the preferred account without requiring a second action", async () => {
const account = {
host: "github.com",
login: "octocat",
active: true,
selected: true,
state: "active",
};
const onAccountChange = vi.fn();
mocks.fetchAccounts.mockResolvedValue([account]);
render(
<ToastProvider>
<GitHubCLIForm workspaceId="workspace-1" onAccountChange={onAccountChange} />
</ToastProvider>,
);
expect(await screen.findByText(/octocat/)).toBeTruthy();
expect(onAccountChange).toHaveBeenLastCalledWith(account);
expect(screen.queryByRole("button", { name: "Use account" })).toBeNull();
});
});
+17 -35
View File
@@ -1,12 +1,9 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button } from "@kandev/ui/button";
import { useEffect, useMemo, useRef, useState } from "react";
import { Label } from "@kandev/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { Spinner } from "@kandev/ui/spinner";
import { useToast } from "@/components/toast-provider";
import { fetchGitHubCLIAccounts, setGitHubWorkspaceConnection } from "@/lib/api/domains/github-api";
import { fetchGitHubCLIAccounts } from "@/lib/api/domains/github-api";
import type { GitHubCLIAccount } from "@/lib/types/github";
function GitHubCLIAccountNotice({
@@ -41,17 +38,19 @@ function accountPlaceholder(loading: boolean, loadError: string | null) {
export function GitHubCLIForm({
workspaceId,
onSaved,
onAccountChange,
disabled,
}: {
workspaceId: string;
onSaved: () => void;
onAccountChange: (account: GitHubCLIAccount | null) => void;
disabled?: boolean;
}) {
const [accounts, setAccounts] = useState<GitHubCLIAccount[]>([]);
const [selected, setSelected] = useState("");
const [loadError, setLoadError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const { toast } = useToast();
const onAccountChangeRef = useRef(onAccountChange);
onAccountChangeRef.current = onAccountChange;
useEffect(() => {
let current = true;
@@ -59,7 +58,7 @@ export function GitHubCLIForm({
setSelected("");
setLoadError(null);
setLoading(true);
setSaving(false);
onAccountChangeRef.current(null);
fetchGitHubCLIAccounts(workspaceId, { cache: "no-store" })
.then((items) => {
if (!current) return;
@@ -86,26 +85,9 @@ export function GitHubCLIForm({
return accounts.find((item) => item.host === host && item.login === login);
}, [accounts, selected]);
const connect = useCallback(async () => {
if (!account) return;
setSaving(true);
try {
await setGitHubWorkspaceConnection(workspaceId, {
source: "gh_cli",
host: account.host,
login: account.login,
});
toast({ description: `Connected ${account.login} for this workspace`, variant: "success" });
onSaved();
} catch (error) {
toast({
description: error instanceof Error ? error.message : "Connection failed",
variant: "error",
});
} finally {
setSaving(false);
}
}, [account, onSaved, toast, workspaceId]);
useEffect(() => {
onAccountChangeRef.current(account ?? null);
}, [account]);
return (
<div className="space-y-3">
@@ -116,7 +98,11 @@ export function GitHubCLIForm({
</p>
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-stretch">
<Select value={selected} onValueChange={setSelected} disabled={loading || !accounts.length}>
<Select
value={selected}
onValueChange={setSelected}
disabled={disabled || loading || !accounts.length}
>
<SelectTrigger id="github-cli-account" className="min-h-11 min-w-0 flex-1">
<SelectValue placeholder={accountPlaceholder(loading, loadError)} />
</SelectTrigger>
@@ -128,10 +114,6 @@ export function GitHubCLIForm({
))}
</SelectContent>
</Select>
<Button onClick={connect} disabled={!account || saving} className="h-11 cursor-pointer">
{saving && <Spinner className="mr-2 h-4 w-4" />}
Use account
</Button>
</div>
<GitHubCLIAccountNotice
loadError={loadError}
@@ -1,6 +1,8 @@
import { useState } from "react";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ToastProvider } from "@/components/toast-provider";
import type { TaskGitCredentialsState } from "@/hooks/domains/github/use-task-git-credentials";
import type { GitHubAppRegistrationCatalogItem, GitHubStatus } from "@/lib/types/github";
import { GitHubAppConnectionPanel } from "./github-app-connection-panel";
import { GitHubConnectionDialog } from "./github-connection-dialog";
@@ -8,11 +10,21 @@ import { GitHubConnectionDialog } from "./github-connection-dialog";
const mocks = vi.hoisted(() => ({
mobile: false,
registrations: [] as GitHubAppRegistrationCatalogItem[],
setConnection: vi.fn(),
}));
const changeConnectionLabel = "Change connection";
const registrationDisplayName = "Work automation";
const githubAppLabel = "GitHub App";
const saveChangesLabel = "Save changes";
const WORKSPACE_ID = "workspace-1";
const DESKTOP_CONNECTION_TEST_ID = "github-connection-desktop";
const taskAccess: TaskGitCredentialsState = {
mode: "managed",
loading: false,
error: false,
save: vi.fn(),
};
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
useResponsiveBreakpoint: () => ({ isMobile: mocks.mobile }),
@@ -44,10 +56,15 @@ vi.mock("./github-app-import-form", () => ({
),
}));
vi.mock("@/lib/api/domains/github-api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/api/domains/github-api")>()),
setGitHubWorkspaceConnection: mocks.setConnection,
}));
const status: GitHubStatus = {
workspace_id: "workspace-1",
workspace_id: WORKSPACE_ID,
automation: {
workspace_id: "workspace-1",
workspace_id: WORKSPACE_ID,
source: "pat",
github_host: "github.com",
login: "octocat",
@@ -89,21 +106,107 @@ const registration: GitHubAppRegistrationCatalogItem = {
webhook_url: "https://kandev.example/webhook",
};
function view(workspaceId = "workspace-1") {
function view(workspaceId = WORKSPACE_ID, currentTaskAccess = taskAccess) {
const onSaved = vi.fn();
return render(
<ToastProvider>
<GitHubConnectionDialog
status={{ ...status, workspace_id: workspaceId }}
workspaceId={workspaceId}
onSaved={vi.fn()}
onSaved={onSaved}
taskAccess={currentTaskAccess}
/>
</ToastProvider>,
);
}
function PartialSaveHarness() {
const [mode, setMode] = useState<TaskGitCredentialsState["mode"]>("managed");
const save = vi.fn(async (nextMode: TaskGitCredentialsState["mode"]) => {
setMode(nextMode);
return true;
});
return (
<ToastProvider>
<GitHubConnectionDialog
status={status}
workspaceId={WORKSPACE_ID}
onSaved={vi.fn()}
taskAccess={{ mode, loading: false, error: false, save }}
/>
</ToastProvider>
);
}
beforeEach(() => {
mocks.mobile = false;
mocks.registrations = [registration];
mocks.setConnection.mockReset();
mocks.setConnection.mockResolvedValue(status.automation);
});
describe("GitHubConnectionDialog task access", () => {
it("saves connection and task access drafts with one action", async () => {
const save = vi.fn().mockResolvedValue(true);
const rendered = view(WORKSPACE_ID, { ...taskAccess, save });
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
const dialog = await screen.findByTestId(DESKTOP_CONNECTION_TEST_ID);
const executor = screen
.getByTestId("github-task-access-option-executor")
.querySelector('[role="radio"]')!;
fireEvent.click(executor);
fireEvent.change(screen.getByLabelText("Personal access token"), {
target: { value: "ghp_replacement" },
});
expect(screen.queryByRole("button", { name: "Connect token" })).toBeNull();
expect(screen.queryByRole("button", { name: "Save task access" })).toBeNull();
expect(screen.getAllByRole("button", { name: saveChangesLabel })).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: saveChangesLabel }));
await waitFor(() =>
expect(mocks.setConnection).toHaveBeenCalledWith(WORKSPACE_ID, {
source: "pat",
token: "ghp_replacement",
}),
);
expect(save).toHaveBeenCalledWith("executor");
await waitFor(() => expect(dialog.getAttribute("data-state")).toBe("closed"));
expect(rendered.baseElement.textContent).toContain("GitHub access settings saved");
});
it("does not report a discarded task access save as successful", async () => {
const save = vi.fn().mockResolvedValue(false);
view(WORKSPACE_ID, { ...taskAccess, save });
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
const dialog = await screen.findByTestId(DESKTOP_CONNECTION_TEST_ID);
const executor = screen
.getByTestId("github-task-access-option-executor")
.querySelector('[role="radio"]')!;
fireEvent.click(executor);
fireEvent.click(screen.getByRole("button", { name: saveChangesLabel }));
await waitFor(() => expect(save).toHaveBeenCalledWith("executor"));
expect(screen.queryByText("GitHub access settings saved")).toBeNull();
expect(dialog.getAttribute("data-state")).toBe("open");
});
it("preserves a failed PAT draft when task access saves successfully", async () => {
mocks.setConnection.mockRejectedValue(new Error("Token rejected"));
render(<PartialSaveHarness />);
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
const token = screen.getByLabelText("Personal access token") as HTMLInputElement;
fireEvent.change(token, { target: { value: "ghp_retry_me" } });
fireEvent.click(
screen.getByTestId("github-task-access-option-executor").querySelector('[role="radio"]')!,
);
fireEvent.click(screen.getByRole("button", { name: saveChangesLabel }));
await screen.findByText(/Some settings were saved/);
expect(token.value).toBe("ghp_retry_me");
});
});
afterEach(() => cleanup());
@@ -111,7 +214,7 @@ describe("GitHubConnectionDialog", () => {
it("uses a method list and shows workspace App choices and sharing impact", async () => {
view();
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
expect(await screen.findByTestId("github-connection-desktop")).toBeTruthy();
expect(await screen.findByTestId(DESKTOP_CONNECTION_TEST_ID)).toBeTruthy();
expect(screen.getByLabelText("Connection method")).toBeTruthy();
expect(screen.getAllByText("Personal access token")).not.toHaveLength(0);
expect(screen.getByText("GitHub CLI account")).toBeTruthy();
@@ -132,7 +235,7 @@ describe("GitHubConnectionDialog", () => {
const drawer = await screen.findByTestId("github-connection-mobile");
expect(drawer.className).toContain("100dvh");
expect(drawer.querySelectorAll(".overflow-y-auto")).toHaveLength(1);
expect(screen.queryByTestId("github-connection-desktop")).toBeNull();
expect(screen.queryByTestId(DESKTOP_CONNECTION_TEST_ID)).toBeNull();
});
it("returns to the registration catalog after importing an App", async () => {
@@ -202,9 +305,10 @@ describe("GitHubConnectionDialog", () => {
status={{ ...status, workspace_id: "workspace-2" }}
workspaceId="workspace-2"
onSaved={vi.fn()}
taskAccess={taskAccess}
/>
</ToastProvider>,
);
await waitFor(() => expect(screen.queryByTestId("github-connection-desktop")).toBeNull());
await waitFor(() => expect(screen.queryByTestId(DESKTOP_CONNECTION_TEST_ID)).toBeNull());
});
});
@@ -20,11 +20,10 @@ import {
DrawerTrigger,
} from "@kandev/ui/drawer";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import type { TaskGitCredentialsState } from "@/hooks/domains/github/use-task-git-credentials";
import type { GitHubStatus } from "@/lib/types/github";
import { GitHubAuthMethodList, type GitHubAutomationMethod } from "./github-auth-method-list";
import { GitHubAppConnectionPanel } from "./github-app-connection-panel";
import { GitHubCLIForm } from "./github-cli-form";
import { GitHubPATForm } from "./github-pat-form";
import type { GitHubAutomationMethod } from "./github-auth-method-list";
import { GitHubConnectionSettingsForm } from "./github-connection-settings-form";
function methodForStatus(status: GitHubStatus): GitHubAutomationMethod {
if (status.automation?.source === "github_app_installation") return "app";
@@ -35,37 +34,16 @@ function methodForStatus(status: GitHubStatus): GitHubAutomationMethod {
const description =
"This workspace uses one credential for repository sync, watches, background jobs, and managed agent GitHub access. Executor profile credentials can still take precedence.";
function ConnectionBody({
method,
workspaceId,
onMethodChange,
onSaved,
}: {
method: GitHubAutomationMethod;
workspaceId: string;
onMethodChange: (method: GitHubAutomationMethod) => void;
onSaved: () => void;
}) {
return (
<div className="space-y-5">
<GitHubAuthMethodList value={method} onChange={onMethodChange} />
<div className="border-t pt-5">
{method === "pat" && <GitHubPATForm workspaceId={workspaceId} onSaved={onSaved} />}
{method === "cli" && <GitHubCLIForm workspaceId={workspaceId} onSaved={onSaved} />}
{method === "app" && <GitHubAppConnectionPanel workspaceId={workspaceId} />}
</div>
</div>
);
}
export function GitHubConnectionDialog({
status,
workspaceId,
onSaved,
taskAccess,
}: {
status: GitHubStatus;
workspaceId: string;
onSaved: () => void;
taskAccess: TaskGitCredentialsState;
}) {
const [open, setOpen] = useState(false);
const [method, setMethod] = useState<GitHubAutomationMethod>(() => methodForStatus(status));
@@ -73,14 +51,13 @@ export function GitHubConnectionDialog({
const connected = Boolean(status.automation);
useEffect(() => {
setOpen(false);
setMethod(methodForStatus(status));
}, [status, workspaceId]);
}, [status]);
const saved = useCallback(() => {
onSaved();
useEffect(() => {
setOpen(false);
}, [onSaved]);
}, [workspaceId]);
const openChange = useCallback(
(next: boolean) => {
if (next) setMethod(methodForStatus(status));
@@ -95,11 +72,16 @@ export function GitHubConnectionDialog({
</Button>
);
const body = (
<ConnectionBody
<GitHubConnectionSettingsForm
status={status}
method={method}
workspaceId={workspaceId}
open={open}
onMethodChange={setMethod}
onSaved={saved}
onSaved={onSaved}
onComplete={() => setOpen(false)}
taskAccess={taskAccess}
isMobile={isMobile}
/>
);
@@ -115,9 +97,7 @@ export function GitHubConnectionDialog({
<DrawerTitle>{connected ? "Change GitHub connection" : "Connect GitHub"}</DrawerTitle>
<DrawerDescription>{description}</DrawerDescription>
</DrawerHeader>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pb-[calc(1rem+env(safe-area-inset-bottom,0px))] pt-4">
{body}
</div>
{body}
</DrawerContent>
</Drawer>
);
@@ -128,13 +108,13 @@ export function GitHubConnectionDialog({
<DialogTrigger asChild>{trigger}</DialogTrigger>
<DialogContent
data-testid="github-connection-desktop"
className="flex max-h-[85dvh] flex-col overflow-hidden sm:max-w-2xl"
className="flex max-h-[85dvh] flex-col overflow-hidden sm:max-w-4xl"
>
<DialogHeader className="shrink-0">
<DialogTitle>{connected ? "Change GitHub connection" : "Connect GitHub"}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1">{body}</div>
{body}
</DialogContent>
</Dialog>
);
@@ -0,0 +1,283 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@kandev/ui/button";
import { Spinner } from "@kandev/ui/spinner";
import { useToast } from "@/components/toast-provider";
import type { TaskGitCredentialsState } from "@/hooks/domains/github/use-task-git-credentials";
import {
setGitHubWorkspaceConnection,
type SetGitHubConnectionRequest,
} from "@/lib/api/domains/github-api";
import type {
GitHubAutomationConnection,
GitHubCLIAccount,
GitHubStatus,
TaskGitCredentialsMode,
} from "@/lib/types/github";
import { cn } from "@/lib/utils";
import { GitHubAppConnectionPanel } from "./github-app-connection-panel";
import { GitHubAuthMethodList, type GitHubAutomationMethod } from "./github-auth-method-list";
import { GitHubCLIForm } from "./github-cli-form";
import { GitHubPATForm } from "./github-pat-form";
import { GitHubTaskAccessForm } from "./github-task-credentials-section";
function methodForStatus(status: GitHubStatus): GitHubAutomationMethod {
if (status.automation?.source === "github_app_installation") return "app";
if (status.automation?.source === "gh_cli") return "cli";
return "pat";
}
function errorMessage(error: unknown) {
return error instanceof Error ? error.message : "The settings could not be saved";
}
function runSaveOperations({
workspaceId,
connectionRequest,
taskMode,
saveTask,
}: {
workspaceId: string;
connectionRequest: SetGitHubConnectionRequest | null;
taskMode: TaskGitCredentialsMode | null;
saveTask: TaskGitCredentialsState["save"];
}) {
const operations: Promise<unknown>[] = [];
if (connectionRequest) {
operations.push(setGitHubWorkspaceConnection(workspaceId, connectionRequest));
}
if (taskMode) {
operations.push(
saveTask(taskMode).then((saved) => {
if (!saved) throw new Error("The workspace changed before task access was saved");
}),
);
}
return Promise.allSettled(operations);
}
function buildConnectionRequest({
method,
currentMethod,
token,
cliAccount,
automation,
}: {
method: GitHubAutomationMethod;
currentMethod: GitHubAutomationMethod;
token: string;
cliAccount: GitHubCLIAccount | null;
automation?: GitHubAutomationConnection | null;
}): SetGitHubConnectionRequest | null {
if (method === "pat" && token.trim()) return { source: "pat", token: token.trim() };
if (
method === "cli" &&
cliAccount &&
(currentMethod !== "cli" ||
automation?.github_host !== cliAccount.host ||
automation.login !== cliAccount.login)
) {
return { source: "gh_cli", host: cliAccount.host, login: cliAccount.login };
}
return null;
}
type SettingsFormProps = {
status: GitHubStatus;
method: GitHubAutomationMethod;
workspaceId: string;
open: boolean;
onMethodChange: (method: GitHubAutomationMethod) => void;
onSaved: () => void;
onComplete: () => void;
taskAccess: TaskGitCredentialsState;
isMobile: boolean;
};
function useConnectionSettingsDraft({
status,
method,
workspaceId,
open,
onSaved,
onComplete,
taskAccess,
}: SettingsFormProps) {
const [token, setToken] = useState("");
const [cliAccount, setCLIAccount] = useState<GitHubCLIAccount | null>(null);
const [taskMode, setTaskMode] = useState<TaskGitCredentialsMode>(taskAccess.mode);
const [saving, setSaving] = useState(false);
const activeWorkspaceId = useRef(workspaceId);
const { toast } = useToast();
activeWorkspaceId.current = workspaceId;
useEffect(() => {
if (!open) return;
setToken("");
setSaving(false);
}, [open, workspaceId]);
useEffect(() => {
if (open) setTaskMode(taskAccess.mode);
}, [open, taskAccess.mode, workspaceId]);
const currentMethod = methodForStatus(status);
const taskDirty = taskMode !== taskAccess.mode;
const connectionRequest = useMemo(
() =>
buildConnectionRequest({
method,
currentMethod,
token,
cliAccount,
automation: status.automation,
}),
[cliAccount, currentMethod, method, status.automation, token],
);
const methodNeedsWorkflow = method === "app" && currentMethod !== "app";
const connectionInvalid =
(method === "pat" && currentMethod !== "pat" && !token.trim()) ||
(method === "cli" && !cliAccount) ||
methodNeedsWorkflow;
const canSave =
!saving &&
!taskAccess.loading &&
!taskAccess.error &&
!connectionInvalid &&
(Boolean(connectionRequest) || taskDirty);
const save = useCallback(async () => {
if (!canSave) return;
const savingWorkspaceId = workspaceId;
setSaving(true);
const results = await runSaveOperations({
workspaceId,
connectionRequest,
taskMode: taskDirty ? taskMode : null,
saveTask: taskAccess.save,
});
if (activeWorkspaceId.current !== savingWorkspaceId) return;
setSaving(false);
const failures = results.filter(
(result): result is PromiseRejectedResult => result.status === "rejected",
);
const successes = results.length - failures.length;
if (successes > 0) onSaved();
if (failures.length === 0) {
setToken("");
toast({ description: "GitHub access settings saved", variant: "success" });
onComplete();
return;
}
const detail = errorMessage(failures[0].reason);
toast({
description:
successes > 0 ? `Some settings were saved, but another change failed: ${detail}` : detail,
variant: "error",
});
}, [
canSave,
connectionRequest,
onComplete,
onSaved,
taskAccess,
taskDirty,
taskMode,
toast,
workspaceId,
]);
return {
token,
setToken,
setCLIAccount,
taskMode,
setTaskMode,
saving,
methodNeedsWorkflow,
canSave,
save,
};
}
export function GitHubConnectionSettingsForm(props: SettingsFormProps) {
const { method, workspaceId, onMethodChange, taskAccess, isMobile } = props;
const {
token,
setToken,
setCLIAccount,
taskMode,
setTaskMode,
saving,
methodNeedsWorkflow,
canSave,
save,
} = useConnectionSettingsDraft(props);
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
<div
data-testid="github-connection-scroll"
className={cn(
"min-h-0 flex-1 overflow-y-auto overscroll-contain pb-8",
isMobile ? "px-4 pt-4" : "pr-1",
)}
>
<div className="space-y-5">
<GitHubAuthMethodList value={method} onChange={onMethodChange} />
<div className="border-t pt-5">
{method === "pat" && (
<GitHubPATForm
workspaceId={workspaceId}
value={token}
onChange={setToken}
disabled={saving}
/>
)}
{method === "cli" && (
<GitHubCLIForm
workspaceId={workspaceId}
onAccountChange={setCLIAccount}
disabled={saving}
/>
)}
{method === "app" && <GitHubAppConnectionPanel workspaceId={workspaceId} />}
</div>
<GitHubTaskAccessForm
taskAccess={taskAccess}
value={taskMode}
onChange={setTaskMode}
disabled={saving}
/>
{methodNeedsWorkflow && (
<p className="text-xs leading-5 text-muted-foreground">
Install a GitHub App above to change the workspace connection. Task access can be
saved after the installation finishes.
</p>
)}
</div>
</div>
<div
data-testid="github-connection-scroll-fade"
aria-hidden="true"
className="pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-popover to-transparent"
/>
</div>
<div
data-testid="github-connection-footer"
className={cn(
"flex shrink-0 justify-end border-t bg-popover pt-3",
isMobile ? "px-4 pb-[calc(0.75rem+env(safe-area-inset-bottom,0px))]" : "pb-0",
)}
>
<Button
type="button"
disabled={!canSave}
onClick={save}
className="h-11 w-full cursor-pointer sm:w-auto"
data-dialog-default-action
>
{saving && <Spinner className="mr-2 h-4 w-4" />}
{saving ? "Saving changes…" : "Save changes"}
</Button>
</div>
</div>
);
}
+13 -41
View File
@@ -1,56 +1,30 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useEffect, useState } from "react";
import { IconEye, IconEyeOff } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { Spinner } from "@kandev/ui/spinner";
import { useToast } from "@/components/toast-provider";
import { setGitHubWorkspaceConnection } from "@/lib/api/domains/github-api";
export function GitHubPATForm({
workspaceId,
onSaved,
value,
onChange,
disabled,
}: {
workspaceId: string;
onSaved: () => void;
value: string;
onChange: (value: string) => void;
disabled?: boolean;
}) {
const [token, setToken] = useState("");
const [visible, setVisible] = useState(false);
const [saving, setSaving] = useState(false);
const { toast } = useToast();
useEffect(() => {
setToken("");
setVisible(false);
setSaving(false);
}, [workspaceId]);
const submit = useCallback(
async (event: React.FormEvent) => {
event.preventDefault();
if (!token.trim()) return;
setSaving(true);
try {
await setGitHubWorkspaceConnection(workspaceId, { source: "pat", token: token.trim() });
setToken("");
toast({ description: "Workspace GitHub token connected", variant: "success" });
onSaved();
} catch (error) {
toast({
description: error instanceof Error ? error.message : "Connection failed",
variant: "error",
});
} finally {
setSaving(false);
}
},
[onSaved, toast, token, workspaceId],
);
return (
<form onSubmit={submit} className="space-y-3">
<div className="space-y-3">
<div className="space-y-1">
<Label htmlFor="github-workspace-token">Personal access token</Label>
<p className="text-xs text-muted-foreground">
@@ -62,10 +36,11 @@ export function GitHubPATForm({
<Input
id="github-workspace-token"
type={visible ? "text" : "password"}
value={token}
onChange={(event) => setToken(event.target.value)}
value={value}
onChange={(event) => onChange(event.target.value)}
placeholder="ghp_xxxxxxxxxxxx"
autoComplete="off"
disabled={disabled}
className="h-11 pr-11 font-mono"
/>
<Button
@@ -74,16 +49,13 @@ export function GitHubPATForm({
size="icon"
className="absolute right-0 top-0 h-11 w-11 cursor-pointer"
onClick={() => setVisible((current) => !current)}
disabled={disabled}
aria-label={visible ? "Hide token" : "Show token"}
>
{visible ? <IconEyeOff className="h-4 w-4" /> : <IconEye className="h-4 w-4" />}
</Button>
</div>
<Button type="submit" disabled={!token.trim() || saving} className="h-11 cursor-pointer">
{saving && <Spinner className="mr-2 h-4 w-4" />}
Connect token
</Button>
</div>
</form>
</div>
);
}
@@ -5,11 +5,12 @@ import { formatDistanceToNow } from "date-fns";
import { IconAlertTriangle } from "@tabler/icons-react";
import { Alert, AlertDescription } from "@kandev/ui/alert";
import type { GitHubRateLimitInfo, GitHubRateLimitSnapshot } from "@/lib/types/github";
import { GitHubAccessHelp } from "./github-access-help";
const RESOURCE_LABELS: Record<string, string> = {
core: "REST",
graphql: "GraphQL",
search: "Search",
const RESOURCE_LABELS: Record<string, { label: string; unit: string }> = {
core: { label: "API rate limit", unit: "requests" },
graphql: { label: "GraphQL query limit", unit: "points" },
search: { label: "Search limit", unit: "requests" },
};
// useTickNow re-renders every intervalMs and exposes a stable now-value so the
@@ -60,28 +61,52 @@ export function GitHubRateLimitDisplay({ info }: { info?: GitHubRateLimitInfo })
if (snapshots.length === 0) return null;
const exhausted = snapshots.filter((s) => isExhausted(s, now));
return (
<GitHubAccessHelp
label="Show GitHub API limits"
title="GitHub API limits"
description="Current GitHub API rate and query limits for this workspace connection."
content={<RateLimitDetails snapshots={snapshots} exhausted={exhausted} />}
/>
);
}
function RateLimitDetails({
snapshots,
exhausted,
}: {
snapshots: GitHubRateLimitSnapshot[];
exhausted: GitHubRateLimitSnapshot[];
}) {
return (
<div className="space-y-2" data-testid="github-rate-limit-display">
{exhausted.length > 0 && (
<Alert variant="destructive" data-testid="github-rate-limit-exhausted">
<IconAlertTriangle className="h-4 w-4" />
<AlertDescription className="text-sm">
GitHub API rate limit exhausted on{" "}
{exhausted.map((s) => RESOURCE_LABELS[s.resource] ?? s.resource).join(", ")}. Background
PR/issue checks are paused until the limit resets {formatReset(latestReset(exhausted))}.
<AlertDescription className="text-xs">
GitHub API access is exhausted for{" "}
{exhausted
.map((snapshot) => RESOURCE_LABELS[snapshot.resource]?.label ?? snapshot.resource)
.join(", ")}
. Background PR and issue checks are paused until the last limit resets{" "}
{formatReset(latestReset(exhausted))}.
</AlertDescription>
</Alert>
)}
<div className="text-xs text-muted-foreground flex flex-wrap gap-x-4 gap-y-1">
{snapshots.map((snap) => {
const label = RESOURCE_LABELS[snap.resource] ?? snap.resource;
const limit = snap.limit > 0 ? snap.limit : "?";
const reset = formatReset(snap);
<div className="space-y-1 text-xs text-muted-foreground">
{snapshots.map((snapshot) => {
const resource = RESOURCE_LABELS[snapshot.resource] ?? {
label: snapshot.resource,
unit: "requests",
};
const limit = snapshot.limit > 0 ? snapshot.limit.toLocaleString("en-US") : "unknown";
const reset = formatReset(snapshot);
return (
<span key={snap.resource} data-testid={`github-rate-limit-${snap.resource}`}>
{label}: <strong>{snap.remaining}</strong>/{limit}
<p key={snapshot.resource} data-testid={`github-rate-limit-${snapshot.resource}`}>
<span className="font-medium text-foreground">{resource.label}:</span>{" "}
{snapshot.remaining.toLocaleString("en-US")} of {limit} {resource.unit} remaining
{reset ? ` · resets ${reset}` : ""}
</span>
</p>
);
})}
</div>
@@ -17,7 +17,6 @@ import { IssueWatchDialog } from "./issue-watch-dialog";
import { ActionPresetsSection } from "./action-presets-section";
import { DefaultQueriesSection } from "./default-queries-section";
import { GitHubRepoScopeSection } from "./github-repo-scope-section";
import { GitHubTaskCredentialsSection } from "./github-task-credentials-section";
import { PRStatsPanel } from "./pr-stats";
import { useReviewWatches } from "@/hooks/domains/github/use-review-watches";
import { useIssueWatches } from "@/hooks/domains/github/use-issue-watches";
@@ -275,7 +274,6 @@ function PerWorkspaceSection({ workspaceId }: { workspaceId: string }) {
<ReviewWatchSection workspaceId={workspaceId} />
<IssueWatchSection workspaceId={workspaceId} />
<GitHubRepoScopeSection workspaceId={workspaceId} />
<GitHubTaskCredentialsSection workspaceId={workspaceId} />
<ActionPresetsSection workspaceId={workspaceId} />
<SettingsSection title="PR Analytics" description="Pull request activity for this workspace.">
<PRStatsPanel workspaceId={workspaceId} />
@@ -47,11 +47,11 @@ function status(source: "pat" | "gh_cli" | "github_app_installation"): GitHubSta
}
describe("GitHubPersonalSettings", () => {
it.each(["pat", "gh_cli"] as const)("explains the shared human identity for %s", (source) => {
it.each(["pat", "gh_cli"] as const)("does not separate the shared identity for %s", (source) => {
mocks.status = status(source);
renderPersonal();
expect(screen.getByText("My GitHub identity")).toBeTruthy();
expect(screen.getByText(/same human account selected for workspace access/)).toBeTruthy();
expect(screen.queryByText("My GitHub identity")).toBeNull();
expect(screen.queryByTestId("github-personal-identity")).toBeNull();
expect(screen.queryByRole("button", { name: /Connect identity/ })).toBeNull();
});
+42 -42
View File
@@ -16,6 +16,10 @@ import { SettingsSection } from "@/components/settings/settings-section";
import { useToast } from "@/components/toast-provider";
import { useGitHubStatus } from "@/hooks/domains/github/use-github-status";
import { useGitHubAppRegistrations } from "@/hooks/domains/github/use-github-app-registrations";
import {
useTaskGitCredentials,
type TaskGitCredentialsState,
} from "@/hooks/domains/github/use-task-git-credentials";
import {
disconnectGitHubPersonal,
disconnectGitHubWorkspace,
@@ -29,7 +33,10 @@ import type {
GitHubAppRegistrationCatalogItem,
} from "@/lib/types/github";
import { GitHubConnectionDialog } from "./github-connection-dialog";
import { GitHubAccessHelp } from "./github-access-help";
import { GitHubPermissionsDialog } from "./github-permissions-dialog";
import { GitHubRateLimitDisplay } from "./github-rate-limit";
import { GitHubTaskAccessSummary } from "./github-task-credentials-section";
const sourceLabels: Record<GitHubConnectionSource, string> = {
pat: "Personal access token",
@@ -81,6 +88,7 @@ function StatusLine({ status }: { status: GitHubStatus }) {
{sourceLabels[connection.source]}
</Badge>
{connection.status !== "active" && <Badge variant="outline">{connection.status}</Badge>}
<GitHubRateLimitDisplay info={status.rate_limit} />
</div>
);
}
@@ -99,9 +107,11 @@ function errorMessage(error: unknown, fallback: string) {
function AutomationStatusSummary({
status,
app,
taskAccess,
}: {
status: GitHubStatus;
app?: GitHubAppRegistrationCatalogItem;
taskAccess: Omit<TaskGitCredentialsState, "save">;
}) {
const appAutomation = status.automation?.source === "github_app_installation";
return (
@@ -109,8 +119,8 @@ function AutomationStatusSummary({
<StatusLine status={status} />
<AutomationActorExplanation status={status} appAutomation={appAutomation} />
{appAutomation && <AppRegistrationDetails app={app} />}
{!appAutomation && <HumanIdentityExplanation status={status} />}
<AutomationError status={status} />
<GitHubTaskAccessSummary {...taskAccess} />
</div>
);
}
@@ -124,12 +134,25 @@ function AutomationActorExplanation({
}) {
const actor = status.automation?.actor?.login;
if (!status.authenticated || !actor) return null;
const humanIdentity = status.effective_personal_actor?.kind === "human";
return (
<p className="text-xs text-muted-foreground">
{appAutomation
? `Kandev-managed operations use the GitHub App installed for ${actor}.`
: `Kandev-managed operations act as ${actor}.`}
</p>
<div className="flex items-start gap-1 text-xs text-muted-foreground">
<GitHubAccessHelp
label="Explain workspace GitHub identity"
title="Workspace GitHub identity"
description="Kandev uses this workspace connection for repository sync, watches, background jobs, and managed agent GitHub commands. With a PAT or GitHub CLI account, My GitHub and actions you trigger use the same human identity."
/>
<div className="min-w-0 space-y-1 pt-3 sm:pt-1">
<p>
{appAutomation
? `Kandev-managed operations use the GitHub App installed for ${actor}.`
: `Kandev-managed operations act as ${actor}.`}
</p>
{!appAutomation && humanIdentity && (
<p>This account also powers My GitHub and user-triggered actions.</p>
)}
</div>
</div>
);
}
@@ -157,15 +180,6 @@ function AppRegistrationDetails({ app }: { app?: GitHubAppRegistrationCatalogIte
);
}
function HumanIdentityExplanation({ status }: { status: GitHubStatus }) {
if (status.effective_personal_actor?.kind !== "human") return null;
return (
<p className="text-xs text-muted-foreground">
This account also powers My GitHub and user-triggered actions.
</p>
);
}
function AutomationError({ status }: { status: GitHubStatus }) {
if (!status.automation?.last_error) return null;
return <p className="text-xs text-destructive">{status.automation.last_error}</p>;
@@ -177,17 +191,24 @@ function AutomationActions({
busy,
onDisconnect,
onRefresh,
taskAccess,
}: {
status: GitHubStatus;
workspaceId: string;
busy: boolean;
onDisconnect: () => void;
onRefresh: () => void;
taskAccess: TaskGitCredentialsState;
}) {
return (
<div className="flex flex-wrap gap-2">
<GitHubPermissionsDialog status={status} />
<GitHubConnectionDialog status={status} workspaceId={workspaceId} onSaved={onRefresh} />
<GitHubConnectionDialog
status={status}
workspaceId={workspaceId}
onSaved={onRefresh}
taskAccess={taskAccess}
/>
<Button
variant="outline"
size="icon"
@@ -215,6 +236,7 @@ function AutomationActions({
export function GitHubAutomationSettings({ workspaceId }: { workspaceId: string }) {
const { status, loaded, loading, refresh } = useGitHubStatus(workspaceId);
const appRegistrations = useGitHubAppRegistrations(workspaceId);
const taskAccess = useTaskGitCredentials(workspaceId);
const [busy, setBusy] = useState(false);
const { toast } = useToast();
const disconnect = useCallback(async () => {
@@ -241,13 +263,14 @@ export function GitHubAutomationSettings({ workspaceId }: { workspaceId: string
className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"
data-testid="github-workspace-automation"
>
<AutomationStatusSummary status={status} app={activeApp} />
<AutomationStatusSummary status={status} app={activeApp} taskAccess={taskAccess} />
<AutomationActions
status={status}
workspaceId={workspaceId}
busy={busy}
onDisconnect={disconnect}
onRefresh={refresh}
taskAccess={taskAccess}
/>
</div>
);
@@ -326,34 +349,11 @@ export function GitHubPersonalSettings({ workspaceId }: { workspaceId: string })
const { status, loaded, loading, refresh } = useGitHubStatus(workspaceId);
const [busy, setBusy] = useState(false);
const { toast } = useToast();
if (!loaded || loading || !status) {
return (
<SettingsSection
title="My GitHub identity"
description="Connect your GitHub user for My GitHub and human-attributed actions. Without it, automation continues as the App."
>
<LoadingStatus />
</SettingsSection>
);
}
if (!loaded || loading || !status) return null;
const view = personalIdentityView(status);
const appAutomation = status.automation?.source === "github_app_installation";
if (!status.automation) return null;
if (!appAutomation) {
return (
<SettingsSection
title="My GitHub identity"
description="My GitHub and human-attributed actions use the same human account selected for workspace access. Choose a different PAT or GitHub CLI account by changing the workspace connection."
>
<div className="space-y-2" data-testid="github-personal-identity">
<PersonalIdentityStatus view={view} />
<p className="text-xs text-muted-foreground">
A separate personal identity is only needed when workspace automation uses a GitHub App.
</p>
</div>
</SettingsSection>
);
}
if (!appAutomation) return null;
const disconnect = async () => {
setBusy(true);
try {
@@ -1,162 +1,108 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { IconInfoCircle } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { CardContent } from "@kandev/ui/card";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@kandev/ui/drawer";
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { SettingsCard } from "@/components/settings/settings-card";
import { SettingsSection } from "@/components/settings/settings-section";
import { useSettingsSaveContributor } from "@/components/settings/settings-save-provider";
import { useToast } from "@/components/toast-provider";
import { useTouchDrawer } from "@/hooks/use-compact-task-chrome";
import {
fetchGitHubWorkspaceSettings,
updateGitHubWorkspaceSettings,
} from "@/lib/api/domains/github-api";
import type { TaskGitCredentialsState } from "@/hooks/domains/github/use-task-git-credentials";
import type { TaskGitCredentialsMode } from "@/lib/types/github";
import { GitHubAccessHelp } from "./github-access-help";
const deliveryHelp =
"PAT, named GitHub CLI, and GitHub App connections choose Kandev's workspace automation identity. In managed mode Kandev brokers that identity to the task for GitHub HTTPS and gh. Inherit executor credentials leaves task Git and gh to the selected executor. An explicit executor-profile GH_TOKEN or GITHUB_TOKEN takes precedence in managed mode.";
const taskAccessLabels: Record<TaskGitCredentialsMode, string> = {
managed: "Managed workspace credentials",
executor: "Inherit executor Git credentials",
};
function TaskCredentialsHelp() {
const usesDrawer = useTouchDrawer();
const [open, setOpen] = useState(false);
const button = (
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11 cursor-pointer text-muted-foreground sm:h-7 sm:w-7"
aria-label="Explain task Git credentials"
>
<IconInfoCircle className="h-4 w-4" />
</Button>
);
const trigger = <DrawerTrigger asChild>{button}</DrawerTrigger>;
export function GitHubTaskAccessSummary({
mode,
loading,
error,
}: Omit<TaskGitCredentialsState, "save">) {
let value = taskAccessLabels[mode];
if (loading) value = "Loading task access…";
if (error) value = "Task access unavailable";
return (
<Drawer open={open} onOpenChange={setOpen}>
{usesDrawer ? (
trigger
) : (
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent className="max-w-[320px] text-xs leading-relaxed">
{deliveryHelp}
</TooltipContent>
</Tooltip>
<div
className="flex items-center gap-1 text-xs text-muted-foreground"
data-testid="github-task-access-summary"
>
<GitHubAccessHelp
label="Explain task Git access"
title="Task Git access"
description="Controls how newly launched tasks authenticate to GitHub for Git HTTPS and gh commands. Managed workspace credentials use Kandev's workspace connection; executor credentials use the selected executor's Git or SSH setup."
/>
<span>
<span className="font-medium text-foreground">Task access: </span>
{value}
</span>
</div>
);
}
export function GitHubTaskAccessForm({
taskAccess,
value,
onChange,
disabled,
}: {
taskAccess: TaskGitCredentialsState;
value: TaskGitCredentialsMode;
onChange: (value: TaskGitCredentialsMode) => void;
disabled?: boolean;
}) {
return (
<section className="space-y-4 border-t pt-5" data-testid="github-task-access-settings">
<div className="space-y-1">
<div className="flex items-center gap-1">
<h3 className="text-sm font-medium">Task Git access</h3>
<GitHubAccessHelp
label="Explain how managed task credentials work"
title="How managed task credentials work"
description="With Managed workspace credentials, Kandev configures agentctl as Git's credential helper inside newly launched task processes. When Git requests credentials for an attached GitHub HTTPS repository, the helper redeems a task- and repository-scoped broker lease. The credential is returned to Git on demand and is not written to the repository or Git config. The gh command uses Kandev's broker-aware shim. Executor inheritance skips both and uses credentials visible in the selected executor. Changes apply to new task launches and the next resume, not already-running processes."
/>
</div>
<p className="text-xs leading-5 text-muted-foreground">
Choose how newly launched tasks authenticate to GitHub. This does not change the workspace
automation connection above.
</p>
</div>
<RadioGroup
value={value}
onValueChange={(nextValue) => onChange(nextValue as TaskGitCredentialsMode)}
disabled={taskAccess.loading || taskAccess.error || disabled}
className="gap-2"
>
<label
className="flex min-h-11 cursor-pointer items-start gap-3 rounded-md border p-3"
data-testid="github-task-access-option-managed"
>
<RadioGroupItem value="managed" className="mt-0.5" />
<span>
<span className="font-medium">Managed workspace credentials</span>
<span className="mt-1 block text-xs leading-5 text-muted-foreground">
Kandev brokers the workspace PAT, named GitHub CLI account, or App identity to this
task for GitHub HTTPS and gh.
</span>
</span>
</label>
<label
className="flex min-h-11 cursor-pointer items-start gap-3 rounded-md border p-3"
data-testid="github-task-access-option-executor"
>
<RadioGroupItem value="executor" className="mt-0.5" />
<span>
<span className="font-medium">Inherit executor Git credentials</span>
<span className="mt-1 block text-xs leading-5 text-muted-foreground">
Local and Worktree tasks use host-visible Git or SSH credentials. Docker, SSH, and
cloud tasks use credentials configured in that executor.
</span>
</span>
</label>
</RadioGroup>
<p className="text-xs leading-5 text-muted-foreground">
An executor-profile GH_TOKEN or GITHUB_TOKEN overrides managed workspace credentials for
that task.
</p>
{taskAccess.error && (
<p className="text-sm text-destructive">Unable to load the current task access setting.</p>
)}
<DrawerContent>
<DrawerHeader>
<DrawerTitle>How task Git credentials work</DrawerTitle>
<DrawerDescription>{deliveryHelp}</DrawerDescription>
</DrawerHeader>
</DrawerContent>
</Drawer>
);
}
export function GitHubTaskCredentialsSection({ workspaceId }: { workspaceId: string }) {
const { toast } = useToast();
const [mode, setMode] = useState<TaskGitCredentialsMode>("managed");
const [baseline, setBaseline] = useState<TaskGitCredentialsMode>("managed");
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
setLoading(true);
void fetchGitHubWorkspaceSettings(workspaceId)
.then((settings) => {
if (!cancelled) {
const next = settings.task_git_credentials_mode ?? "managed";
setMode(next);
setBaseline(next);
}
})
.catch(() => {
if (!cancelled)
toast({ description: "Failed to load task Git credential settings", variant: "error" });
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [toast, workspaceId]);
const save = useCallback(async () => {
try {
const updated = await updateGitHubWorkspaceSettings({
workspace_id: workspaceId,
task_git_credentials_mode: mode,
});
const next = updated.task_git_credentials_mode ?? "managed";
setBaseline(next);
setMode((current) => (current === mode ? next : current));
toast({ description: "Task Git credential settings saved", variant: "success" });
} catch {
toast({ description: "Failed to save task Git credential settings", variant: "error" });
throw new Error("Failed to save task Git credential settings");
}
}, [mode, toast, workspaceId]);
const dirty = mode !== baseline;
useSettingsSaveContributor({
id: `github-task-credentials:${workspaceId}`,
revision: mode,
isDirty: dirty,
canSave: !loading,
save,
discard: () => setMode(baseline),
});
return (
<SettingsSection
title="Task Git credentials"
description="Choose how task processes authenticate to GitHub. This does not change Kandev's workspace automation identity."
action={<TaskCredentialsHelp />}
>
<SettingsCard isDirty={dirty}>
<CardContent className="space-y-4 py-4">
<RadioGroup
value={mode}
onValueChange={(value) => setMode(value as TaskGitCredentialsMode)}
disabled={loading}
data-testid="github-task-credentials-mode"
>
<label className="flex cursor-pointer items-start gap-3 rounded-md border p-3">
<RadioGroupItem value="managed" className="mt-0.5" />
<span>
<span className="font-medium">Managed workspace credentials</span>
<span className="mt-1 block text-sm text-muted-foreground">
Kandev brokers the workspace PAT, named GitHub CLI account, or App identity to
this task for GitHub HTTPS and gh.
</span>
</span>
</label>
<label className="flex cursor-pointer items-start gap-3 rounded-md border p-3">
<RadioGroupItem value="executor" className="mt-0.5" />
<span>
<span className="font-medium">Inherit executor Git credentials</span>
<span className="mt-1 block text-sm text-muted-foreground">
Local and Worktree tasks use host-visible Git or SSH credentials. Docker, SSH, and
cloud tasks use credentials configured in that executor.
</span>
</span>
</label>
</RadioGroup>
<p className="text-xs text-muted-foreground">
An executor-profile GH_TOKEN or GITHUB_TOKEN overrides managed workspace credentials for
that task.
</p>
</CardContent>
</SettingsCard>
</SettingsSection>
</section>
);
}