feat(github): support per-workspace GitHub App registrations (#1810)

This commit is contained in:
Carlos Florêncio
2026-07-26 10:39:08 +01:00
committed by GitHub
parent bc218dfbbe
commit 75abf779ed
347 changed files with 36471 additions and 2896 deletions
@@ -0,0 +1,137 @@
"use client";
import { useEffect, useState } from "react";
import { IconExternalLink, IconPlus } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Spinner } from "@kandev/ui/spinner";
import { useToast } from "@/components/toast-provider";
import { useGitHubAppRegistrations } from "@/hooks/domains/github/use-github-app-registrations";
import { GitHubAppCreateForm } from "./github-app-create-form";
import { GitHubAppImportForm } from "./github-app-import-form";
import { GitHubAppRegistrationList } from "./github-app-registration-list";
type AppView = "choose" | "import" | "create";
type RegistrationHook = ReturnType<typeof useGitHubAppRegistrations>;
export function GitHubAppConnectionPanel({ workspaceId }: { workspaceId: string }) {
const registrations = useGitHubAppRegistrations(workspaceId);
const [view, setView] = useState<AppView>("choose");
const { selectedId, setSelectedId, selectedRegistration } = useAppRegistrationSelection(
workspaceId,
registrations,
);
const { toast } = useToast();
useEffect(() => {
setView("choose");
}, [workspaceId]);
async function install() {
if (!selectedRegistration || selectedRegistration.status !== "active") return;
try {
const response = await registrations.startInstall(selectedRegistration.id);
const url = response.url ?? response.URL;
if (!url) throw new Error("GitHub did not return an installation URL");
window.location.assign(url);
} catch (error) {
toast({
description: error instanceof Error ? error.message : "App installation failed",
variant: "error",
});
}
}
if (view === "import") {
return (
<div className="space-y-4">
<BackButton onClick={() => setView("choose")} />
<GitHubAppImportForm
workspaceId={workspaceId}
registrations={registrations}
onImported={(registrationId) => {
setSelectedId(registrationId);
setView("choose");
}}
/>
</div>
);
}
if (view === "create") {
return (
<div className="space-y-4">
<BackButton onClick={() => setView("choose")} />
<GitHubAppCreateForm workspaceId={workspaceId} registrations={registrations} />
</div>
);
}
return (
<div className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-medium">Choose a GitHub App</h3>
<p className="text-xs leading-5 text-muted-foreground">
Use an App when automation needs its own identity, short-lived tokens, and
repository-level installation control. Setup is more involved and requires a publicly
reachable HTTPS URL.
</p>
</div>
{registrations.loading ? (
<div className="flex min-h-11 items-center gap-2 text-sm text-muted-foreground">
<Spinner className="h-4 w-4" /> Loading registered Apps...
</div>
) : (
<GitHubAppRegistrationList
registrations={registrations.registrations}
value={selectedId}
onChange={setSelectedId}
/>
)}
{registrations.error && <p className="text-xs text-destructive">{registrations.error}</p>}
<div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
<Button
disabled={selectedRegistration?.status !== "active" || registrations.mutating}
onClick={() => void install()}
className="h-11 cursor-pointer"
data-testid="github-app-install-button"
>
{registrations.mutating && <Spinner className="mr-2 h-4 w-4" />}
Install for this workspace
<IconExternalLink className="ml-2 h-4 w-4" />
</Button>
<Button variant="outline" className="h-11 cursor-pointer" onClick={() => setView("import")}>
<IconPlus className="mr-2 h-4 w-4" /> Add existing App
</Button>
<Button variant="outline" className="h-11 cursor-pointer" onClick={() => setView("create")}>
<IconPlus className="mr-2 h-4 w-4" /> Create new App
</Button>
</div>
<p className="text-xs leading-5 text-muted-foreground">
A registration can be reused across workspaces, or you can keep work and personal Apps
separate. Each workspace selects and installs its own credential.
</p>
</div>
);
}
function useAppRegistrationSelection(workspaceId: string, registrations: RegistrationHook) {
const [selectedId, setSelectedId] = useState("");
useEffect(() => setSelectedId(""), [workspaceId]);
useEffect(() => {
if (!registrations.loaded) return;
setSelectedId((current) => {
const currentRegistration = registrations.registrations.find(({ id }) => id === current);
if (currentRegistration?.status === "active") return current;
if (registrations.selected?.status === "active") return registrations.selected.id;
return registrations.registrations.find(({ status }) => status === "active")?.id ?? "";
});
}, [registrations.loaded, registrations.registrations, registrations.selected]);
const selectedRegistration = registrations.registrations.find(({ id }) => id === selectedId);
return { selectedId, setSelectedId, selectedRegistration };
}
function BackButton({ onClick }: { onClick: () => void }) {
return (
<Button variant="ghost" className="h-11 cursor-pointer px-2" onClick={onClick}>
Back to registered Apps
</Button>
);
}
@@ -0,0 +1,227 @@
"use client";
import { useEffect, useState } from "react";
import { IconExternalLink } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
import { Spinner } from "@kandev/ui/spinner";
import { useToast } from "@/components/toast-provider";
import type { StartGitHubAppManifestResponse } from "@/lib/types/github";
import {
appRegistrationError,
defaultVisibility,
submitManifestToGitHub,
validateRegistrationBasics,
type AppSetupErrors,
} from "./github-app-onboarding-model";
import { GitHubAppPolicyDialog } from "./github-app-policy-dialog";
import { GitHubAppVisibilityField } from "./github-app-visibility-field";
import type { useGitHubAppRegistrations } from "@/hooks/domains/github/use-github-app-registrations";
type RegistrationHook = ReturnType<typeof useGitHubAppRegistrations>;
export function GitHubAppCreateForm({
workspaceId,
registrations,
}: {
workspaceId: string;
registrations: RegistrationHook;
}) {
const [displayName, setDisplayName] = useState("");
const [ownerType, setOwnerType] = useState<"user" | "organization">("organization");
const [ownerLogin, setOwnerLogin] = useState("");
const [publicBaseUrl, setPublicBaseUrl] = useState("");
const [visibility, setVisibility] = useState(defaultVisibility);
const [errors, setErrors] = useState<AppSetupErrors>({});
const [handoff, setHandoff] = useState<StartGitHubAppManifestResponse | null>(null);
const { toast } = useToast();
useEffect(() => {
setDisplayName("");
setOwnerType("organization");
setOwnerLogin("");
setPublicBaseUrl("");
setVisibility(defaultVisibility);
setErrors({});
setHandoff(null);
}, [workspaceId]);
async function prepare(event: React.FormEvent) {
event.preventDefault();
const basics = validateRegistrationBasics({
displayName,
ownerType,
ownerLogin,
publicBaseUrl,
});
setErrors(basics.errors);
if (!basics.publicBaseUrl || Object.keys(basics.errors).length) return;
try {
setHandoff(
await registrations.startManifest({
display_name: basics.displayName,
owner_type: ownerType,
owner_login: basics.ownerLogin,
visibility,
public_base_url: basics.publicBaseUrl,
}),
);
} catch (error) {
const detail = appRegistrationError(error);
toast({ description: detail?.error ?? "GitHub App setup could not start", variant: "error" });
}
}
if (handoff) {
return <ManifestHandoff handoff={handoff} onEdit={() => setHandoff(null)} />;
}
return (
<CreateAppFields
displayName={displayName}
ownerType={ownerType}
ownerLogin={ownerLogin}
publicBaseUrl={publicBaseUrl}
visibility={visibility}
errors={errors}
mutating={registrations.mutating}
onDisplayName={setDisplayName}
onOwnerType={setOwnerType}
onOwnerLogin={setOwnerLogin}
onPublicBaseUrl={setPublicBaseUrl}
onVisibility={setVisibility}
onSubmit={prepare}
/>
);
}
function ManifestHandoff({
handoff,
onEdit,
}: {
handoff: StartGitHubAppManifestResponse;
onEdit: () => void;
}) {
return (
<div className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-medium">GitHub is ready to create the App</h3>
<p className="text-xs leading-5 text-muted-foreground">
GitHub will show the generated permissions and ask you to confirm. Returning from GitHub
adds the registration; installing it for this workspace remains an explicit step.
</p>
</div>
<div className="flex flex-col gap-2 sm:flex-row">
<Button
className="h-11 cursor-pointer"
onClick={() => submitManifestToGitHub(handoff.registration_url, handoff.manifest)}
>
Continue on GitHub
<IconExternalLink className="ml-2 h-4 w-4" />
</Button>
<Button variant="outline" className="h-11 cursor-pointer" onClick={onEdit}>
Edit details
</Button>
</div>
</div>
);
}
type CreateFieldsProps = {
displayName: string;
ownerType: "user" | "organization";
ownerLogin: string;
publicBaseUrl: string;
visibility: "private" | "public";
errors: AppSetupErrors;
mutating: boolean;
onDisplayName: (value: string) => void;
onOwnerType: (value: "user" | "organization") => void;
onOwnerLogin: (value: string) => void;
onPublicBaseUrl: (value: string) => void;
onVisibility: (value: "private" | "public") => void;
onSubmit: (event: React.FormEvent) => void;
};
function CreateAppFields(props: CreateFieldsProps) {
return (
<form onSubmit={props.onSubmit} className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-medium">Create a GitHub App</h3>
<p className="text-xs leading-5 text-muted-foreground">
Kandev generates the exact App policy. You confirm creation on GitHub; Kandev then stores
this registration so it can be selected by a workspace.
</p>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Name in Kandev" error={props.errors.displayName}>
<Input
className="h-11"
value={props.displayName}
onChange={(event) => props.onDisplayName(event.target.value)}
/>
</Field>
<Field label="GitHub owner login" error={props.errors.ownerLogin}>
<Input
className="h-11"
value={props.ownerLogin}
onChange={(event) => props.onOwnerLogin(event.target.value)}
/>
</Field>
</div>
<RadioGroup
value={props.ownerType}
onValueChange={(value) => props.onOwnerType(value as CreateFieldsProps["ownerType"])}
className="flex min-h-11 flex-wrap items-center gap-5"
>
<Label className="flex cursor-pointer items-center gap-2">
<RadioGroupItem value="organization" /> Organization
</Label>
<Label className="flex cursor-pointer items-center gap-2">
<RadioGroupItem value="user" /> Personal account
</Label>
</RadioGroup>
<Field label="Public Kandev URL" error={props.errors.publicBaseUrl}>
<Input
className="h-11"
type="url"
placeholder="https://kandev.example.com"
value={props.publicBaseUrl}
onChange={(event) => props.onPublicBaseUrl(event.target.value)}
/>
</Field>
<p className="text-xs text-muted-foreground">
GitHub must reach this HTTPS origin for signed webhooks and callbacks.
</p>
<GitHubAppVisibilityField value={props.visibility} onChange={props.onVisibility} />
<div className="flex flex-col gap-2 sm:flex-row">
<Button type="submit" disabled={props.mutating} className="h-11 cursor-pointer">
{props.mutating && <Spinner className="mr-2 h-4 w-4" />}
Prepare App on GitHub
<IconExternalLink className="ml-2 h-4 w-4" />
</Button>
<GitHubAppPolicyDialog />
</div>
</form>
);
}
function Field({
label,
error,
children,
}: {
label: string;
error?: string;
children: React.ReactNode;
}) {
return (
<Label className="block space-y-1.5">
<span>{label}</span>
{children}
{error && <span className="block text-xs font-normal text-destructive">{error}</span>}
</Label>
);
}
@@ -0,0 +1,131 @@
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
import { Textarea } from "@kandev/ui/textarea";
import type { GitHubAppOwnerType, GitHubAppVisibility } from "@/lib/types/github";
import type { AppSetupErrors } from "./github-app-onboarding-model";
export type GitHubAppImportValues = {
displayName: string;
ownerLogin: string;
ownerType: GitHubAppOwnerType;
publicBaseUrl: string;
visibility: GitHubAppVisibility;
appId: string;
clientId: string;
clientSecret: string;
privateKey: string;
webhookSecret: string;
slug: string;
};
type Update = (name: keyof GitHubAppImportValues, value: string) => void;
export function GitHubAppImportIdentityFields({
values,
errors,
update,
}: {
values: GitHubAppImportValues;
errors: AppSetupErrors;
update: Update;
}) {
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Name in Kandev" error={errors.displayName}>
<Input
className="h-11"
value={values.displayName}
onChange={(e) => update("displayName", e.target.value)}
/>
</Field>
<Field label="GitHub App slug" error={errors.slug}>
<Input
className="h-11"
value={values.slug}
onChange={(e) => update("slug", e.target.value)}
/>
</Field>
<Field label="GitHub owner login" error={errors.ownerLogin}>
<Input
className="h-11"
value={values.ownerLogin}
onChange={(e) => update("ownerLogin", e.target.value)}
/>
</Field>
</div>
<RadioGroup
value={values.ownerType}
onValueChange={(value) => update("ownerType", value)}
className="flex min-h-11 flex-wrap items-center gap-5"
>
<Label className="flex cursor-pointer items-center gap-2">
<RadioGroupItem value="Organization" /> Organization
</Label>
<Label className="flex cursor-pointer items-center gap-2">
<RadioGroupItem value="User" /> Personal account
</Label>
</RadioGroup>
</div>
);
}
export function GitHubAppImportSecretFields({
values,
errors,
update,
}: {
values: GitHubAppImportValues;
errors: AppSetupErrors;
update: Update;
}) {
const labels = {
appId: "App ID",
clientId: "Client ID",
clientSecret: "Client secret",
webhookSecret: "Webhook secret",
} as const;
return (
<div className="grid gap-3 sm:grid-cols-2">
{(Object.keys(labels) as (keyof typeof labels)[]).map((name) => (
<Field key={name} label={labels[name]} error={errors[name]}>
<Input
className="h-11"
type={name.includes("Secret") || name === "webhookSecret" ? "password" : "text"}
autoComplete="off"
value={values[name]}
onChange={(event) => update(name, event.target.value)}
/>
</Field>
))}
<div className="sm:col-span-2">
<Field label="Private key (.pem)" error={errors.privateKey}>
<Textarea
className="min-h-28 font-mono text-xs"
value={values.privateKey}
onChange={(event) => update("privateKey", event.target.value)}
/>
</Field>
</div>
</div>
);
}
function Field({
label,
error,
children,
}: {
label: string;
error?: string;
children: React.ReactNode;
}) {
return (
<Label className="block space-y-1.5">
<span>{label}</span>
{children}
{error && <span className="block text-xs font-normal text-destructive">{error}</span>}
</Label>
);
}
@@ -0,0 +1,61 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ToastProvider } from "@/components/toast-provider";
import type { PrepareGitHubAppImportResponse } from "@/lib/types/github";
import { GitHubAppImportForm } from "./github-app-import-form";
afterEach(() => cleanup());
const preparation: PrepareGitHubAppImportResponse = {
registration_id: "registration-1",
public_base_url: "https://kandev.example",
manifest_callback_url: "https://kandev.example/manifest/callback",
install_callback_url: "https://kandev.example/install/callback",
personal_callback_url: "https://kandev.example/personal/callback",
webhook_url: "https://kandev.example/webhook",
setup_url: "https://kandev.example/install/callback",
permissions: { contents: "write" },
events: ["installation"],
expires_at: "2026-07-22T00:00:00Z",
};
describe("GitHubAppImportForm", () => {
it("clears imported secrets when setup starts over", async () => {
const registrations = {
mutating: false,
prepareImport: vi.fn().mockResolvedValue(preparation),
importRegistration: vi.fn(),
};
render(
<ToastProvider>
<GitHubAppImportForm
workspaceId="workspace-1"
registrations={registrations as never}
onImported={vi.fn()}
/>
</ToastProvider>,
);
fireEvent.change(screen.getByLabelText("Public Kandev URL"), {
target: { value: "https://kandev.example" },
});
fireEvent.click(screen.getByRole("button", { name: "Generate setup instructions" }));
const clientSecret = await screen.findByLabelText("Client secret");
fireEvent.change(clientSecret, { target: { value: "client-secret" } });
fireEvent.change(screen.getByLabelText("Webhook secret"), {
target: { value: "webhook-secret" },
});
fireEvent.change(screen.getByLabelText("Private key (.pem)"), {
target: { value: "private-key" },
});
fireEvent.click(screen.getByRole("button", { name: "Start over" }));
fireEvent.click(screen.getByRole("button", { name: "Generate setup instructions" }));
await waitFor(() => {
expect((screen.getByLabelText("Client secret") as HTMLInputElement).value).toBe("");
expect((screen.getByLabelText("Webhook secret") as HTMLInputElement).value).toBe("");
expect((screen.getByLabelText("Private key (.pem)") as HTMLTextAreaElement).value).toBe("");
});
});
});
@@ -0,0 +1,254 @@
"use client";
import { useEffect, useState } from "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 type { useGitHubAppRegistrations } from "@/hooks/domains/github/use-github-app-registrations";
import type { GitHubAppOwnerType, PrepareGitHubAppImportResponse } from "@/lib/types/github";
import {
appRegistrationError,
defaultVisibility,
githubAppSettingsURL,
normalizePublicBaseUrl,
validateImportSecrets,
validateRegistrationBasics,
type AppSetupErrors,
} from "./github-app-onboarding-model";
import { GitHubAppImportGuide } from "./github-app-import-guide";
import {
GitHubAppImportIdentityFields,
GitHubAppImportSecretFields,
type GitHubAppImportValues,
} from "./github-app-import-fields";
import { GitHubAppVisibilityField } from "./github-app-visibility-field";
type RegistrationHook = ReturnType<typeof useGitHubAppRegistrations>;
export function GitHubAppImportForm({
workspaceId,
registrations,
onImported,
}: {
workspaceId: string;
registrations: RegistrationHook;
onImported: (registrationId: string) => void;
}) {
const [preparation, setPreparation] = useState<PrepareGitHubAppImportResponse | null>(null);
const [values, setValues] = useState(initialValues);
const [errors, setErrors] = useState<AppSetupErrors>({});
const { toast } = useToast();
useEffect(() => {
setPreparation(null);
setValues(initialValues);
setErrors({});
}, [workspaceId]);
const update = (name: keyof typeof values, value: string) =>
setValues((current) => ({ ...current, [name]: value }));
async function prepare(event: React.FormEvent) {
event.preventDefault();
const nextErrors: AppSetupErrors = {};
const publicBaseUrl = normalizePublicBaseUrl(values.publicBaseUrl, nextErrors);
setErrors(nextErrors);
if (!publicBaseUrl) return;
try {
setPreparation(await registrations.prepareImport({ public_base_url: publicBaseUrl }));
} catch (error) {
showError(error, "Import setup could not start", toast);
}
}
async function submit(event: React.FormEvent) {
event.preventDefault();
if (!preparation) return;
const ownerType = values.ownerType as GitHubAppOwnerType;
const basics = validateRegistrationBasics({ ...values, ownerType });
const secrets = validateImportSecrets(values);
const nextErrors = { ...basics.errors, ...secrets.errors };
setErrors(nextErrors);
if (!basics.publicBaseUrl || Object.keys(nextErrors).length) return;
try {
const imported = await registrations.importRegistration({
registration_id: preparation.registration_id,
display_name: basics.displayName,
github_host: "github.com",
app_id: secrets.appId,
client_id: values.clientId.trim(),
client_secret: values.clientSecret,
private_key: values.privateKey.trim(),
webhook_secret: values.webhookSecret,
slug: values.slug.trim(),
owner_login: basics.ownerLogin,
owner_type: ownerType,
visibility: values.visibility,
public_base_url: basics.publicBaseUrl,
});
setValues(clearImportSecrets);
toast({
description: "GitHub App imported. It is ready to install.",
variant: "success",
});
onImported(imported.id);
} catch (error) {
showError(error, "GitHub App could not be imported", toast);
}
}
if (!preparation) {
return (
<PrepareImportForm
publicBaseUrl={values.publicBaseUrl}
error={errors.publicBaseUrl}
mutating={registrations.mutating}
onPublicBaseUrl={(value) => update("publicBaseUrl", value)}
onSubmit={prepare}
/>
);
}
const settingsUrl = importSettingsUrl(values);
const startOver = () => {
setPreparation(null);
setErrors({});
setValues(clearImportSecrets);
};
return (
<PreparedImportForm
preparation={preparation}
settingsUrl={settingsUrl}
values={values}
errors={errors}
mutating={registrations.mutating}
update={update}
onVisibility={(visibility) => setValues((current) => ({ ...current, visibility }))}
onStartOver={startOver}
onSubmit={submit}
/>
);
}
function PrepareImportForm(props: {
publicBaseUrl: string;
error?: string;
mutating: boolean;
onPublicBaseUrl: (value: string) => void;
onSubmit: (event: React.FormEvent) => void;
}) {
return (
<form onSubmit={props.onSubmit} className="space-y-3">
<div className="space-y-1">
<h3 className="text-sm font-medium">Add an existing GitHub App</h3>
<p className="text-xs leading-5 text-muted-foreground">
Kandev first reserves exact callback and webhook URLs, then guides you through GitHub's
App settings. Existing workspace access is unchanged until you install the imported App.
</p>
</div>
<Field label="Public Kandev URL" error={props.error}>
<Input
className="h-11"
type="url"
placeholder="https://kandev.example.com"
value={props.publicBaseUrl}
onChange={(event) => props.onPublicBaseUrl(event.target.value)}
/>
</Field>
<Button type="submit" disabled={props.mutating} className="h-11 cursor-pointer">
{props.mutating && <Spinner className="mr-2 h-4 w-4" />}
Generate setup instructions
</Button>
</form>
);
}
type PreparedImportProps = {
preparation: PrepareGitHubAppImportResponse;
settingsUrl?: string;
values: GitHubAppImportValues;
errors: AppSetupErrors;
mutating: boolean;
update: (name: keyof GitHubAppImportValues, value: string) => void;
onVisibility: (value: "private" | "public") => void;
onStartOver: () => void;
onSubmit: (event: React.FormEvent) => void;
};
function PreparedImportForm(props: PreparedImportProps) {
return (
<form onSubmit={props.onSubmit} className="space-y-5">
<GitHubAppImportIdentityFields
values={props.values}
errors={props.errors}
update={props.update}
/>
<GitHubAppImportGuide preparation={props.preparation} settingsUrl={props.settingsUrl} />
<GitHubAppVisibilityField value={props.values.visibility} onChange={props.onVisibility} />
<GitHubAppImportSecretFields
values={props.values}
errors={props.errors}
update={props.update}
/>
<div className="flex flex-col gap-2 sm:flex-row">
<Button type="submit" disabled={props.mutating} className="h-11 cursor-pointer">
{props.mutating && <Spinner className="mr-2 h-4 w-4" />}
Verify and import App
</Button>
<Button
type="button"
variant="outline"
className="h-11 cursor-pointer"
onClick={props.onStartOver}
>
Start over
</Button>
</div>
</form>
);
}
const initialValues: GitHubAppImportValues = {
displayName: "",
ownerLogin: "",
ownerType: "Organization" as GitHubAppOwnerType,
publicBaseUrl: "",
visibility: defaultVisibility,
appId: "",
clientId: "",
clientSecret: "",
privateKey: "",
webhookSecret: "",
slug: "",
};
function clearImportSecrets(values: GitHubAppImportValues): GitHubAppImportValues {
return { ...values, clientSecret: "", privateKey: "", webhookSecret: "" };
}
function importSettingsUrl(values: GitHubAppImportValues) {
if (!values.ownerLogin.trim() || !values.slug.trim()) return undefined;
return githubAppSettingsURL(values.ownerType, values.ownerLogin, values.slug);
}
function showError(error: unknown, fallback: string, toast: ReturnType<typeof useToast>["toast"]) {
const detail = appRegistrationError(error);
toast({ description: detail?.error ?? fallback, variant: "error" });
}
function Field({
label,
error,
children,
}: {
label: string;
error?: string;
children: React.ReactNode;
}) {
return (
<Label className="block space-y-1.5">
<span>{label}</span>
{children}
{error && <span className="block text-xs font-normal text-destructive">{error}</span>}
</Label>
);
}
@@ -0,0 +1,43 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import type { PrepareGitHubAppImportResponse } from "@/lib/types/github";
import { GitHubAppImportGuide } from "./github-app-import-guide";
afterEach(() => cleanup());
const preparation: PrepareGitHubAppImportResponse = {
registration_id: "registration-1",
public_base_url: "https://kandev.example",
manifest_callback_url: "https://kandev.example/manifest/callback",
install_callback_url: "https://kandev.example/install/callback",
personal_callback_url: "https://kandev.example/personal/callback",
webhook_url: "https://kandev.example/webhook",
setup_url: "https://kandev.example/install/callback",
permissions: { contents: "write" },
events: ["installation"],
expires_at: "2026-07-22T00:00:00Z",
};
describe("GitHubAppImportGuide", () => {
it("shows the exact existing-App settings and operational requirements", () => {
render(
<GitHubAppImportGuide
preparation={preparation}
settingsUrl="https://github.com/organizations/acme/settings/apps/work-app"
/>,
);
expect(screen.getByText("Homepage URL")).toBeTruthy();
expect(screen.getByText("User authorization callback URL")).toBeTruthy();
expect(screen.getByText("Setup URL")).toBeTruthy();
expect(screen.getByText("Webhook URL")).toBeTruthy();
expect(screen.getByText(/application\/json/)).toBeTruthy();
expect(screen.getByText(/SSL verification enabled/)).toBeTruthy();
expect(screen.queryByText("https://kandev.example/manifest/callback")).toBeNull();
});
it("does not link to generic settings before the App identity is known", () => {
render(<GitHubAppImportGuide preparation={preparation} />);
const button = screen.getByRole("button", { name: "Open GitHub App settings" });
expect((button as HTMLButtonElement).disabled).toBe(true);
});
});
@@ -0,0 +1,88 @@
"use client";
import { useState } from "react";
import { IconCheck, IconCopy, IconExternalLink } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
import type { PrepareGitHubAppImportResponse } from "@/lib/types/github";
import { GitHubAppPolicyDialog } from "./github-app-policy-dialog";
const urlLabels: [keyof PrepareGitHubAppImportResponse, string][] = [
["public_base_url", "Homepage URL"],
["personal_callback_url", "User authorization callback URL"],
["setup_url", "Setup URL"],
["webhook_url", "Webhook URL"],
];
export function GitHubAppImportGuide({
preparation,
settingsUrl,
}: {
preparation: PrepareGitHubAppImportResponse;
settingsUrl?: string;
}) {
const { copy } = useCopyToClipboard();
const [copied, setCopied] = useState("");
async function copyValue(value: string) {
await copy(value);
setCopied(value);
}
return (
<section className="space-y-3" aria-label="GitHub App configuration instructions">
<div className="space-y-1">
<h3 className="text-sm font-medium">Configure the existing App on GitHub</h3>
<p className="text-xs leading-5 text-muted-foreground">
Set these exact URLs, create a client secret and webhook secret, and download a private
key. This one-time setup expires {new Date(preparation.expires_at).toLocaleString()}.
</p>
<p className="text-xs leading-5 text-muted-foreground">
For webhooks, choose <strong>application/json</strong> as the content type and keep SSL
verification enabled.
</p>
</div>
<div className="divide-y rounded-md border">
{urlLabels.map(([key, label]) => {
const value = String(preparation[key]);
return (
<div key={key} className="space-y-1 p-3">
<div className="text-xs font-medium text-muted-foreground">{label}</div>
<div className="flex min-w-0 items-center gap-2">
<code className="min-w-0 flex-1 break-all text-xs">{value}</code>
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11 shrink-0 cursor-pointer"
aria-label={`Copy ${label}`}
onClick={() => void copyValue(value)}
>
{copied === value ? (
<IconCheck className="h-4 w-4 text-green-500" />
) : (
<IconCopy className="h-4 w-4" />
)}
</Button>
</div>
</div>
);
})}
</div>
<div className="flex flex-col gap-2 sm:flex-row">
{settingsUrl ? (
<Button asChild variant="outline" className="h-11 cursor-pointer">
<a href={settingsUrl} target="_blank" rel="noreferrer">
Open GitHub App settings
<IconExternalLink className="ml-2 h-4 w-4" />
</a>
</Button>
) : (
<Button type="button" variant="outline" className="h-11" disabled>
Open GitHub App settings
<IconExternalLink className="ml-2 h-4 w-4" />
</Button>
)}
<GitHubAppPolicyDialog permissions={preparation.permissions} events={preparation.events} />
</div>
</section>
);
}
@@ -0,0 +1,67 @@
import { describe, expect, it, vi } from "vitest";
import {
callbackNotice,
defaultVisibility,
githubAppSettingsURL,
normalizePublicBaseUrl,
submitManifestToGitHub,
validateImportSecrets,
validateRegistrationBasics,
} from "./github-app-onboarding-model";
describe("GitHub App onboarding model", () => {
it("requires a public HTTPS origin", () => {
for (const value of ["http://kandev.example", "https://localhost", "https://host.test/path"]) {
const errors = {};
expect(normalizePublicBaseUrl(value, errors)).toBeNull();
expect(errors).toHaveProperty("publicBaseUrl");
}
expect(normalizePublicBaseUrl("https://kandev.example/", {})).toBe("https://kandev.example");
});
it("validates registration identity and imported secrets", () => {
const basics = validateRegistrationBasics({
displayName: " Work App ",
ownerType: "Organization",
ownerLogin: "acme-inc",
publicBaseUrl: "https://kandev.example",
});
expect(basics).toMatchObject({ displayName: "Work App", ownerLogin: "acme-inc", errors: {} });
expect(
validateImportSecrets({
appId: "42",
clientId: "client",
clientSecret: "secret",
privateKey: "key",
webhookSecret: "hook",
slug: "work-app",
}).errors,
).toEqual({});
expect(defaultVisibility).toBe("private");
});
it("maps callback results and account-specific App settings URLs", () => {
expect(callbackNotice("app_connected").tone).toBe("success");
expect(callbackNotice("github_app_registration_cancelled").tone).toBe("info");
expect(callbackNotice("unknown").tone).toBe("error");
expect(githubAppSettingsURL("Organization", "acme", "work-app")).toBe(
"https://github.com/organizations/acme/settings/apps/work-app",
);
expect(githubAppSettingsURL("User", "octocat", "personal-app")).toBe(
"https://github.com/settings/apps/personal-app",
);
});
it("posts the generated manifest to GitHub without exposing it in a URL", () => {
const submit = vi
.spyOn(HTMLFormElement.prototype, "submit")
.mockImplementation(() => undefined);
submitManifestToGitHub("https://github.com/settings/apps/new", { name: "Kandev" });
const form = document.body.querySelector("form");
expect(form?.method).toBe("POST");
expect(form?.action).toBe("https://github.com/settings/apps/new");
expect(form?.querySelector("input")?.value).toBe('{"name":"Kandev"}');
submit.mockRestore();
form?.remove();
});
});
@@ -0,0 +1,148 @@
import { ApiError } from "@/lib/api/client";
import type {
GitHubAppManifestOwnerType,
GitHubAppOwnerType,
GitHubAppRegistrationErrorBody,
GitHubAppVisibility,
} from "@/lib/types/github";
const ownerPattern = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
const slugPattern = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,98}[A-Za-z0-9])?$/;
export type AppSetupErrors = Partial<
Record<
| "displayName"
| "ownerLogin"
| "publicBaseUrl"
| "appId"
| "clientId"
| "clientSecret"
| "privateKey"
| "webhookSecret"
| "slug",
string
>
>;
export function normalizePublicBaseUrl(rawValue: string, errors: AppSetupErrors) {
let url: URL;
try {
url = new URL(rawValue.trim());
} catch {
errors.publicBaseUrl = "Enter a public HTTPS origin.";
return null;
}
if (url.protocol !== "https:" || url.username || url.password) {
errors.publicBaseUrl = "Enter a public HTTPS origin.";
return null;
}
if (url.hostname === "localhost" || url.hostname.endsWith(".localhost")) {
errors.publicBaseUrl = "Enter a public host, not localhost.";
return null;
}
if ((url.pathname && url.pathname !== "/") || url.search || url.hash) {
errors.publicBaseUrl = "Enter an origin without a path, query, or fragment.";
return null;
}
return url.origin;
}
export function validateRegistrationBasics(input: {
displayName: string;
ownerType: GitHubAppManifestOwnerType | GitHubAppOwnerType;
ownerLogin: string;
publicBaseUrl: string;
}) {
const errors: AppSetupErrors = {};
const displayName = input.displayName.trim();
const ownerLogin = input.ownerLogin.trim();
if (!displayName || displayName.length > 100)
errors.displayName = "Enter a name up to 100 characters.";
if (!ownerPattern.test(ownerLogin)) errors.ownerLogin = "Enter a valid GitHub account login.";
const publicBaseUrl = normalizePublicBaseUrl(input.publicBaseUrl, errors);
return { displayName, ownerLogin, publicBaseUrl, errors };
}
export function validateImportSecrets(input: {
appId: string;
clientId: string;
clientSecret: string;
privateKey: string;
webhookSecret: string;
slug: string;
}) {
const errors: AppSetupErrors = {};
const appId = Number(input.appId);
if (!Number.isSafeInteger(appId) || appId <= 0) errors.appId = "Enter the numeric GitHub App ID.";
if (!input.clientId.trim()) errors.clientId = "Enter the App client ID.";
if (!input.clientSecret) errors.clientSecret = "Enter the App client secret.";
if (!input.privateKey.trim()) errors.privateKey = "Paste the App private key.";
if (!input.webhookSecret) errors.webhookSecret = "Enter the webhook secret.";
if (!slugPattern.test(input.slug.trim())) errors.slug = "Enter the GitHub App slug.";
return { appId, errors };
}
export function submitManifestToGitHub(registrationUrl: string, manifest: unknown) {
const form = document.createElement("form");
form.method = "POST";
form.action = registrationUrl;
const input = document.createElement("input");
input.type = "hidden";
input.name = "manifest";
input.value = JSON.stringify(manifest);
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
export type CallbackNotice = {
tone: "success" | "info" | "error";
title: string;
description: string;
};
export function callbackNotice(code: string): CallbackNotice {
if (code === "app_registered")
return {
tone: "success",
title: "GitHub App added",
description: "The App is ready to select and install for this workspace.",
};
if (code === "app_connected")
return {
tone: "success",
title: "GitHub App connected",
description: "Workspace automation now uses the verified App installation.",
};
if (code === "personal_connected")
return {
tone: "success",
title: "GitHub identity connected",
description: "My GitHub now uses your verified personal identity.",
};
if (code === "github_app_registration_cancelled")
return {
tone: "info",
title: "GitHub App setup cancelled",
description: "The existing workspace connection was not changed.",
};
return {
tone: "error",
title: "GitHub setup was not completed",
description: "The GitHub response could not be verified. Review the connection and try again.",
};
}
export function appRegistrationError(error: unknown) {
if (!(error instanceof ApiError) || !error.body || typeof error.body !== "object") return null;
return error.body as GitHubAppRegistrationErrorBody;
}
export function githubAppSettingsURL(ownerType: GitHubAppOwnerType, owner: string, slug: string) {
if (!owner || !slug) return "https://github.com/settings/apps";
return ownerType === "Organization"
? `https://github.com/organizations/${encodeURIComponent(owner)}/settings/apps/${encodeURIComponent(slug)}`
: `https://github.com/settings/apps/${encodeURIComponent(slug)}`;
}
export const defaultVisibility: GitHubAppVisibility = "private";
@@ -0,0 +1,90 @@
"use client";
import { IconShieldCheck } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@kandev/ui/dialog";
export const githubAppPermissions: Record<string, "read" | "write"> = {
actions: "read",
administration: "read",
checks: "read",
contents: "write",
issues: "write",
members: "read",
metadata: "read",
pull_requests: "write",
statuses: "read",
workflows: "write",
};
export const githubAppEvents = [
"installation",
"installation_repositories",
"github_app_authorization",
];
function title(value: string) {
return value.replaceAll("_", " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
export function GitHubAppPolicyDialog({
permissions = githubAppPermissions,
events = githubAppEvents,
}: {
permissions?: Record<string, "read" | "write">;
events?: string[];
}) {
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="outline" className="h-11 cursor-pointer">
<IconShieldCheck className="mr-2 h-4 w-4" />
Review permissions
</Button>
</DialogTrigger>
<DialogContent className="flex max-h-[80dvh] flex-col overflow-hidden sm:max-w-lg">
<DialogHeader className="shrink-0">
<DialogTitle>Required GitHub App policy</DialogTitle>
<DialogDescription>
An imported App must have at least these repository permissions and subscribed events.
</DialogDescription>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto overscroll-contain">
<section>
<h3 className="mb-2 text-sm font-medium">Repository permissions</h3>
<div className="divide-y rounded-md border">
{Object.entries(permissions)
.sort(([left], [right]) => left.localeCompare(right))
.map(([name, level]) => (
<div
key={name}
className="flex min-h-11 items-center justify-between gap-3 px-3 text-sm"
>
<span className="min-w-0 break-words">{title(name)}</span>
<span className="shrink-0 capitalize text-muted-foreground">{level}</span>
</div>
))}
</div>
</section>
<section>
<h3 className="mb-2 text-sm font-medium">Subscribed events</h3>
<div className="divide-y rounded-md border">
{events.map((event) => (
<div key={event} className="flex min-h-11 items-center px-3 text-sm">
{title(event)}
</div>
))}
</div>
</section>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,76 @@
import { IconAlertTriangle, IconCheck } from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Label } from "@kandev/ui/label";
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
import type { GitHubAppRegistrationCatalogItem } from "@/lib/types/github";
import { cn } from "@/lib/utils";
export function GitHubAppRegistrationList({
registrations,
value,
onChange,
}: {
registrations: GitHubAppRegistrationCatalogItem[];
value: string;
onChange: (registrationId: string) => void;
}) {
if (!registrations.length) {
return (
<div className="rounded-md border border-dashed p-4 text-sm text-muted-foreground">
No GitHub Apps are registered yet. Add an existing App or create one below.
</div>
);
}
return (
<RadioGroup value={value} onValueChange={onChange} className="space-y-2">
{registrations.map((registration) => (
<Label
key={registration.id}
htmlFor={`github-app-${registration.id}`}
className={cn(
"flex min-h-20 cursor-pointer items-start gap-3 rounded-md border p-3",
value === registration.id && "border-primary bg-muted/30",
)}
>
<RadioGroupItem
id={`github-app-${registration.id}`}
value={registration.id}
className="mt-1"
/>
<span className="min-w-0 flex-1 space-y-1">
<span className="flex min-w-0 flex-wrap items-center gap-2">
<span className="break-words text-sm font-medium">{registration.display_name}</span>
<Badge variant="outline" className="capitalize">
{registration.visibility}
</Badge>
{registration.status === "invalid" && (
<Badge variant="destructive">Needs attention</Badge>
)}
{registration.selected && (
<Badge variant="secondary">
<IconCheck className="mr-1 h-3 w-3" /> In use
</Badge>
)}
</span>
<span className="block break-words text-xs font-normal text-muted-foreground">
{registration.owner_login}/{registration.slug} ·{" "}
{registration.source === "managed" ? "Created by Kandev" : "Imported"}
</span>
{registration.shared && (
<span className="flex items-start gap-1.5 text-xs font-normal leading-5 text-amber-600 dark:text-amber-400">
<IconAlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
Used by {registration.workspace_binding_count} workspaces. Editing or deleting it
affects all of them.
</span>
)}
{registration.status === "invalid" && (
<span className="block text-xs font-normal leading-5 text-destructive">
{registration.last_error || "The stored App credentials are unavailable."}
</span>
)}
</span>
</Label>
))}
</RadioGroup>
);
}
@@ -0,0 +1,41 @@
import { Label } from "@kandev/ui/label";
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
import type { GitHubAppVisibility } from "@/lib/types/github";
export function GitHubAppVisibilityField({
value,
onChange,
}: {
value: GitHubAppVisibility;
onChange: (value: GitHubAppVisibility) => void;
}) {
return (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">Who can install this App?</legend>
<RadioGroup
value={value}
onValueChange={(next) => onChange(next as GitHubAppVisibility)}
className="grid gap-2 sm:grid-cols-2"
>
<Label className="flex min-h-20 cursor-pointer items-start gap-3 rounded-md border p-3">
<RadioGroupItem value="private" className="mt-0.5" />
<span>
<span className="block text-sm font-medium">Only the App owner</span>
<span className="block text-xs font-normal leading-5 text-muted-foreground">
Best for personal or company-internal automation.
</span>
</span>
</Label>
<Label className="flex min-h-20 cursor-pointer items-start gap-3 rounded-md border p-3">
<RadioGroupItem value="public" className="mt-0.5" />
<span>
<span className="block text-sm font-medium">Other GitHub accounts</span>
<span className="block text-xs font-normal leading-5 text-muted-foreground">
Allows installation elsewhere. It does not publish to Marketplace or grant repos.
</span>
</span>
</Label>
</RadioGroup>
</fieldset>
);
}
@@ -0,0 +1,74 @@
import { IconBrandGithub, IconKey, IconTerminal2 } from "@tabler/icons-react";
import { Label } from "@kandev/ui/label";
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
import { cn } from "@/lib/utils";
export type GitHubAutomationMethod = "pat" | "cli" | "app";
const methods = [
{
value: "pat" as const,
label: "Personal access token",
description: "Simple and portable, but automation is attributed to your personal account.",
icon: IconKey,
},
{
value: "cli" as const,
label: "GitHub CLI account",
description: "Reuse one named account already authenticated on this Kandev host.",
icon: IconTerminal2,
},
{
value: "app" as const,
label: "GitHub App",
description: "Isolated, short-lived credentials with explicit repository access.",
icon: IconBrandGithub,
},
];
export function GitHubAuthMethodList({
value,
onChange,
}: {
value: GitHubAutomationMethod;
onChange: (value: GitHubAutomationMethod) => void;
}) {
return (
<RadioGroup
value={value}
onValueChange={(next) => onChange(next as GitHubAutomationMethod)}
className="grid gap-2 sm:grid-cols-3"
aria-label="Connection method"
>
{methods.map((method) => {
const Icon = method.icon;
return (
<Label
key={method.value}
htmlFor={`github-method-${method.value}`}
className={cn(
"flex min-h-24 cursor-pointer items-start gap-3 rounded-md border p-3",
"transition-colors hover:bg-muted/40",
value === method.value && "border-primary bg-muted/30",
)}
>
<RadioGroupItem
id={`github-method-${method.value}`}
value={method.value}
className="mt-0.5"
/>
<span className="min-w-0 space-y-1">
<span className="flex items-center gap-2 text-sm font-medium">
<Icon className="h-4 w-4 shrink-0" />
{method.label}
</span>
<span className="block text-xs font-normal leading-5 text-muted-foreground">
{method.description}
</span>
</span>
</Label>
);
})}
</RadioGroup>
);
}
@@ -0,0 +1,35 @@
"use client";
import { IconAlertTriangle, IconCheck, IconInfoCircle } from "@tabler/icons-react";
import { Alert, AlertDescription, AlertTitle } from "@kandev/ui/alert";
import { useSearchParams } from "@/lib/routing/client-router";
import { parseGitHubCallbackResult } from "@/hooks/domains/github/use-github-app-registrations";
import { callbackNotice } from "./github-app-onboarding-model";
import { cn } from "@/lib/utils";
export function GitHubCallbackNotice({ workspaceId }: { workspaceId: string }) {
const search = useSearchParams();
const result = parseGitHubCallbackResult(search, workspaceId);
if (!result) return null;
const notice = callbackNotice(result.code);
const Icon = noticeIcon(notice.tone);
return (
<Alert
className={cn(
notice.tone === "success" && "border-green-500/40",
notice.tone === "error" && "border-destructive/50",
)}
data-testid="github-callback-notice"
>
<Icon className="h-4 w-4" />
<AlertTitle>{notice.title}</AlertTitle>
<AlertDescription>{notice.description}</AlertDescription>
</Alert>
);
}
function noticeIcon(tone: "success" | "info" | "error") {
if (tone === "success") return IconCheck;
if (tone === "info") return IconInfoCircle;
return IconAlertTriangle;
}
@@ -0,0 +1,105 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button } from "@kandev/ui/button";
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 type { GitHubCLIAccount } from "@/lib/types/github";
export function GitHubCLIForm({
workspaceId,
onSaved,
}: {
workspaceId: string;
onSaved: () => void;
}) {
const [accounts, setAccounts] = useState<GitHubCLIAccount[]>([]);
const [selected, setSelected] = useState("");
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const { toast } = useToast();
useEffect(() => {
let current = true;
setAccounts([]);
setSelected("");
setLoading(true);
setSaving(false);
fetchGitHubCLIAccounts(workspaceId, { cache: "no-store" })
.then((items) => {
if (!current) return;
setAccounts(items);
const preferred =
items.find((item) => item.selected) ?? items.find((item) => item.active) ?? items[0];
setSelected(preferred ? `${preferred.host}\n${preferred.login}` : "");
})
.catch(() => current && setAccounts([]))
.finally(() => current && setLoading(false));
return () => {
current = false;
};
}, [workspaceId]);
const account = useMemo(() => {
const [host, login] = selected.split("\n");
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]);
return (
<div className="space-y-3">
<div className="space-y-1">
<Label htmlFor="github-cli-account">GitHub CLI account</Label>
<p className="text-xs text-muted-foreground">
Choose the exact account. Kandev does not silently follow the CLI's active-account change.
</p>
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-stretch">
<Select value={selected} onValueChange={setSelected} disabled={loading || !accounts.length}>
<SelectTrigger id="github-cli-account" className="min-h-11 min-w-0 flex-1">
<SelectValue placeholder={loading ? "Loading accounts..." : "No gh accounts found"} />
</SelectTrigger>
<SelectContent>
{accounts.map((item) => (
<SelectItem key={`${item.host}:${item.login}`} value={`${item.host}\n${item.login}`}>
{item.login} ({item.host}){item.active ? " - active" : ""}
</SelectItem>
))}
</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>
{!accounts.length && !loading && (
<p className="text-xs text-muted-foreground">
Sign in with <code>gh auth login</code>, then reopen this dialog.
</p>
)}
</div>
);
}
@@ -0,0 +1,210 @@
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 { GitHubAppRegistrationCatalogItem, GitHubStatus } from "@/lib/types/github";
import { GitHubAppConnectionPanel } from "./github-app-connection-panel";
import { GitHubConnectionDialog } from "./github-connection-dialog";
const mocks = vi.hoisted(() => ({
mobile: false,
registrations: [] as GitHubAppRegistrationCatalogItem[],
}));
const changeConnectionLabel = "Change connection";
const registrationDisplayName = "Work automation";
const githubAppLabel = "GitHub App";
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
useResponsiveBreakpoint: () => ({ isMobile: mocks.mobile }),
}));
vi.mock("@/hooks/domains/github/use-github-app-registrations", () => ({
useGitHubAppRegistrations: (workspaceId: string) => ({
workspaceId,
catalog: { workspace_id: workspaceId, registrations: mocks.registrations },
registrations: mocks.registrations,
selected: mocks.registrations.find((item) => item.selected) ?? null,
loaded: true,
loading: false,
error: null,
mutating: false,
refresh: vi.fn(),
startManifest: vi.fn(),
prepareImport: vi.fn(),
importRegistration: vi.fn(),
rename: vi.fn(),
remove: vi.fn(),
startInstall: vi.fn(),
}),
}));
vi.mock("./github-app-import-form", () => ({
GitHubAppImportForm: ({ onImported }: { onImported: (registrationId: string) => void }) => (
<button onClick={() => onImported("registration-1")}>Complete test import</button>
),
}));
const status: GitHubStatus = {
workspace_id: "workspace-1",
automation: {
workspace_id: "workspace-1",
source: "pat",
github_host: "github.com",
login: "octocat",
status: "active",
credential_generation: 1,
},
personal: null,
authenticated: true,
username: "octocat",
auth_method: "pat",
token_configured: true,
required_scopes: [],
};
const registration: GitHubAppRegistrationCatalogItem = {
id: "registration-1",
source: "managed",
display_name: registrationDisplayName,
github_host: "github.com",
app_id: 42,
client_id: "Iv1.test",
slug: "work-automation",
owner_login: "acme",
owner_type: "Organization",
visibility: "private",
public_base_url: "https://kandev.example",
credential_generation: 1,
status: "active",
webhook_status: "verified",
created_at: "2026-07-21T00:00:00Z",
updated_at: "2026-07-21T00:00:00Z",
selected: true,
binding_count: 3,
workspace_binding_count: 2,
shared: true,
manifest_callback_url: "https://kandev.example/manifest/callback",
install_callback_url: "https://kandev.example/install/callback",
personal_callback_url: "https://kandev.example/personal/callback",
webhook_url: "https://kandev.example/webhook",
};
function view(workspaceId = "workspace-1") {
return render(
<ToastProvider>
<GitHubConnectionDialog
status={{ ...status, workspace_id: workspaceId }}
workspaceId={workspaceId}
onSaved={vi.fn()}
/>
</ToastProvider>,
);
}
beforeEach(() => {
mocks.mobile = false;
mocks.registrations = [registration];
});
afterEach(() => cleanup());
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(screen.getByLabelText("Connection method")).toBeTruthy();
expect(screen.getAllByText("Personal access token")).not.toHaveLength(0);
expect(screen.getByText("GitHub CLI account")).toBeTruthy();
fireEvent.click(screen.getByText(githubAppLabel, { selector: "span" }));
expect(await screen.findByText(registrationDisplayName)).toBeTruthy();
expect(screen.getByText(/Used by 2 workspaces/)).toBeTruthy();
expect(screen.getByRole("button", { name: /Install for this workspace/ })).toBeTruthy();
expect(screen.getByRole("button", { name: "Add existing App" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Create new App" })).toBeTruthy();
expect(screen.queryByTestId("github-app-system-setup-link")).toBeNull();
});
it("renders one bounded mobile drawer with a single scroll body", async () => {
mocks.mobile = true;
view();
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
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();
});
it("returns to the registration catalog after importing an App", async () => {
view();
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
fireEvent.click(await screen.findByText(githubAppLabel, { selector: "span" }));
fireEvent.click(screen.getByRole("button", { name: "Add existing App" }));
fireEvent.click(screen.getByRole("button", { name: "Complete test import" }));
expect(await screen.findByText(registrationDisplayName)).toBeTruthy();
const installButton = screen.getByRole("button", { name: /Install for this workspace/ });
expect((installButton as HTMLButtonElement).disabled).toBe(false);
});
it("does not install invalid App registrations", async () => {
mocks.registrations = [
{
...registration,
status: "invalid",
last_error: "Credentials could not be restored.",
},
];
view();
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
fireEvent.click(await screen.findByText(githubAppLabel, { selector: "span" }));
expect(await screen.findByText("Needs attention")).toBeTruthy();
expect(screen.getByText("Credentials could not be restored.")).toBeTruthy();
expect(
(screen.getByRole("button", { name: /Install for this workspace/ }) as HTMLButtonElement)
.disabled,
).toBe(true);
});
it("clears a selected App when it disappears from the catalog", async () => {
const rendered = render(
<ToastProvider>
<GitHubAppConnectionPanel workspaceId="workspace-1" />
</ToastProvider>,
);
expect(
(screen.getByRole("button", { name: /Install for this workspace/ }) as HTMLButtonElement)
.disabled,
).toBe(false);
mocks.registrations = [];
rendered.rerender(
<ToastProvider>
<GitHubAppConnectionPanel workspaceId="workspace-1" />
</ToastProvider>,
);
await waitFor(() =>
expect(
(screen.getByRole("button", { name: /Install for this workspace/ }) as HTMLButtonElement)
.disabled,
).toBe(true),
);
});
it("closes and resets local setup state when the workspace changes", async () => {
const rendered = view();
fireEvent.click(screen.getByRole("button", { name: changeConnectionLabel }));
fireEvent.click(await screen.findByText(githubAppLabel, { selector: "span" }));
expect(await screen.findByText(registrationDisplayName)).toBeTruthy();
rendered.rerender(
<ToastProvider>
<GitHubConnectionDialog
status={{ ...status, workspace_id: "workspace-2" }}
workspaceId="workspace-2"
onSaved={vi.fn()}
/>
</ToastProvider>,
);
await waitFor(() => expect(screen.queryByTestId("github-connection-desktop")).toBeNull());
});
});
@@ -0,0 +1,141 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { IconPlug } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@kandev/ui/dialog";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@kandev/ui/drawer";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
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";
function methodForStatus(status: GitHubStatus): GitHubAutomationMethod {
if (status.automation?.source === "github_app_installation") return "app";
if (status.automation?.source === "gh_cli") return "cli";
return "pat";
}
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,
}: {
status: GitHubStatus;
workspaceId: string;
onSaved: () => void;
}) {
const [open, setOpen] = useState(false);
const [method, setMethod] = useState<GitHubAutomationMethod>(() => methodForStatus(status));
const { isMobile } = useResponsiveBreakpoint();
const connected = Boolean(status.automation);
useEffect(() => {
setOpen(false);
setMethod(methodForStatus(status));
}, [status, workspaceId]);
const saved = useCallback(() => {
onSaved();
setOpen(false);
}, [onSaved]);
const openChange = useCallback(
(next: boolean) => {
if (next) setMethod(methodForStatus(status));
setOpen(next);
},
[status],
);
const trigger = (
<Button variant={connected ? "outline" : "default"} className="h-11 cursor-pointer">
<IconPlug className="mr-2 h-4 w-4" />
{connected ? "Change connection" : "Connect GitHub"}
</Button>
);
const body = (
<ConnectionBody
method={method}
workspaceId={workspaceId}
onMethodChange={setMethod}
onSaved={saved}
/>
);
if (isMobile) {
return (
<Drawer open={open} onOpenChange={openChange}>
<DrawerTrigger asChild>{trigger}</DrawerTrigger>
<DrawerContent
data-testid="github-connection-mobile"
className="h-[calc(100dvh-16px-env(safe-area-inset-bottom,0px))] max-h-[calc(100dvh-16px-env(safe-area-inset-bottom,0px))] overflow-hidden"
>
<DrawerHeader className="shrink-0 border-b text-left">
<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>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={openChange}>
<DialogTrigger asChild>{trigger}</DialogTrigger>
<DialogContent
data-testid="github-connection-desktop"
className="flex max-h-[85dvh] flex-col overflow-hidden sm:max-w-2xl"
>
<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>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,89 @@
"use client";
import { useCallback, 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,
}: {
workspaceId: string;
onSaved: () => void;
}) {
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-1">
<Label htmlFor="github-workspace-token">Personal access token</Label>
<p className="text-xs text-muted-foreground">
Kandev stores this token for this workspace. GitHub records actions as the token owner.
</p>
</div>
<div className="flex flex-col gap-2 sm:flex-row sm:items-stretch">
<div className="relative min-w-0 flex-1">
<Input
id="github-workspace-token"
type={visible ? "text" : "password"}
value={token}
onChange={(event) => setToken(event.target.value)}
placeholder="ghp_xxxxxxxxxxxx"
autoComplete="off"
className="h-11 pr-11 font-mono"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-11 w-11 cursor-pointer"
onClick={() => setVisible((current) => !current)}
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>
);
}
@@ -0,0 +1,88 @@
"use client";
import { IconAlertTriangle, IconCheck, IconShieldCheck, IconX } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@kandev/ui/dialog";
import type { GitHubStatus } from "@/lib/types/github";
type PermissionState = {
name: string;
available: boolean;
};
function formatCapability(value: string) {
return value.replaceAll("_", " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
function permissionStates(status: GitHubStatus): PermissionState[] {
const permissions = new Map<string, boolean>(
Object.entries(status.automation?.capabilities ?? {}),
);
for (const permission of [
...(status.automation?.missing_capabilities ?? []),
...(status.automation?.missing_permissions ?? []),
]) {
permissions.set(permission, false);
}
return Array.from(permissions, ([name, available]) => ({ name, available })).sort((a, b) =>
a.name.localeCompare(b.name),
);
}
export function GitHubPermissionsDialog({ status }: { status: GitHubStatus }) {
if (status.automation?.source !== "github_app_installation") return null;
const permissions = permissionStates(status);
if (permissions.length === 0) return null;
const missingCount = permissions.filter((permission) => !permission.available).length;
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="outline" className="h-11 cursor-pointer">
{missingCount > 0 ? (
<IconAlertTriangle className="mr-2 h-4 w-4 text-amber-500" />
) : (
<IconShieldCheck className="mr-2 h-4 w-4" />
)}
View permissions
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>GitHub App permissions</DialogTitle>
<DialogDescription>
Permissions available to Kandev through this workspace's GitHub App installation.
</DialogDescription>
</DialogHeader>
<div className="max-h-[55vh] divide-y overflow-y-auto" data-testid="github-capabilities">
{permissions.map((permission) => (
<div key={permission.name} className="flex min-h-11 items-center gap-3 py-2 text-sm">
{permission.available ? (
<IconCheck className="h-4 w-4 shrink-0 text-green-500" />
) : (
<IconX className="h-4 w-4 shrink-0 text-destructive" />
)}
<span className="min-w-0 flex-1 break-words">
{formatCapability(permission.name)}
</span>
<span
className={
permission.available ? "text-muted-foreground" : "font-medium text-destructive"
}
>
{permission.available ? "Available" : "Missing"}
</span>
</div>
))}
</div>
</DialogContent>
</Dialog>
);
}
+15 -12
View File
@@ -8,7 +8,8 @@ import { Separator } from "@kandev/ui/separator";
import { TooltipProvider } from "@kandev/ui/tooltip";
import { useToast } from "@/components/toast-provider";
import { SettingsSection } from "@/components/settings/settings-section";
import { GitHubStatusCard } from "./github-status";
import { GitHubAutomationSettings, GitHubPersonalSettings } from "./github-status";
import { GitHubCallbackNotice } from "./github-callback-notice";
import { ReviewWatchTable } from "./review-watch-table";
import { ReviewWatchDialog } from "./review-watch-dialog";
import { IssueWatchTable } from "./issue-watch-table";
@@ -236,7 +237,7 @@ function useIssueWatchActions(workspaceId?: string | null) {
};
}
export function GitHubConnectionSection() {
export function GitHubConnectionSection({ workspaceId }: { workspaceId: string }) {
return (
<>
<div>
@@ -248,18 +249,20 @@ export function GitHubConnectionSection() {
GitHub Integration
</h2>
<p className="text-sm text-muted-foreground mt-1">
Connect Kandev to GitHub. Authentication is shared across all workspaces; PR/issue
watchers and presets are configured per workspace.
Choose the automation and personal identities used by this workspace.
</p>
</div>
<Separator />
<SettingsSection title="Connection Status" description="GitHub authentication status">
<Card>
<CardContent className="py-3">
<GitHubStatusCard />
</CardContent>
</Card>
<GitHubCallbackNotice workspaceId={workspaceId} />
<SettingsSection
title="Workspace GitHub access"
description="Credential used for repository sync, watches, and managed agent git and gh commands. Executor profile tokens take precedence."
>
<GitHubAutomationSettings workspaceId={workspaceId} />
</SettingsSection>
<div className="pr-16 sm:pr-0">
<GitHubPersonalSettings workspaceId={workspaceId} />
</div>
</>
);
}
@@ -267,6 +270,7 @@ export function GitHubConnectionSection() {
function PerWorkspaceSection({ workspaceId }: { workspaceId: string }) {
return (
<div className="space-y-8">
<GitHubConnectionSection workspaceId={workspaceId} />
<ReviewWatchSection workspaceId={workspaceId} />
<IssueWatchSection workspaceId={workspaceId} />
<GitHubRepoScopeSection workspaceId={workspaceId} />
@@ -286,8 +290,7 @@ type GitHubIntegrationPageProps = {
export function GitHubIntegrationPage({ workspaceId }: GitHubIntegrationPageProps = {}) {
return (
<TooltipProvider>
<div className="space-y-8">
<GitHubConnectionSection />
<div className="space-y-8 lg:pr-16">
<WorkspaceScopedSection workspaceId={workspaceId}>
{(ws) => <PerWorkspaceSection key={ws} workspaceId={ws} />}
</WorkspaceScopedSection>
@@ -0,0 +1,64 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ToastProvider } from "@/components/toast-provider";
import type { GitHubStatus } from "@/lib/types/github";
import { GitHubPersonalSettings } from "./github-status";
const mocks = vi.hoisted(() => ({ status: null as GitHubStatus | null }));
vi.mock("@/hooks/domains/github/use-github-status", () => ({
useGitHubStatus: () => ({ status: mocks.status, loaded: true, loading: false, refresh: vi.fn() }),
}));
afterEach(() => cleanup());
function renderPersonal() {
return render(
<ToastProvider>
<GitHubPersonalSettings workspaceId="workspace-1" />
</ToastProvider>,
);
}
function status(source: "pat" | "gh_cli" | "github_app_installation"): GitHubStatus {
return {
workspace_id: "workspace-1",
automation: {
workspace_id: "workspace-1",
source,
github_host: "github.com",
login: "octocat",
status: "active",
credential_generation: 1,
},
personal: null,
app_available: source === "github_app_installation",
effective_personal_actor: {
kind: "human",
source,
login: "octocat",
workspace_id: "workspace-1",
},
authenticated: true,
username: "octocat",
auth_method: source,
token_configured: source === "pat",
required_scopes: [],
};
}
describe("GitHubPersonalSettings", () => {
it.each(["pat", "gh_cli"] as const)("explains the shared human 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.queryByRole("button", { name: /Connect identity/ })).toBeNull();
});
it("offers a separate identity only for App automation", () => {
mocks.status = status("github_app_installation");
renderPersonal();
expect(screen.getByRole("button", { name: /Connect identity/ })).toBeTruthy();
expect(screen.getByText(/never given to managed agents/)).toBeTruthy();
});
});
+380 -343
View File
@@ -1,376 +1,413 @@
"use client";
import { useState, useCallback } from "react";
import { useCallback, useState } from "react";
import {
IconBrandGithub,
IconCheck,
IconChevronDown,
IconChevronRight,
IconInfoCircle,
IconX,
IconExternalLink,
IconRefresh,
IconKey,
IconTrash,
IconEye,
IconEyeOff,
IconTerminal2,
IconX,
} from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible";
import { Input } from "@kandev/ui/input";
import { Spinner } from "@kandev/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useAppStore } from "@/components/state-provider";
import { useGitHubStatus } from "@/hooks/domains/github/use-github-status";
import { SettingsSection } from "@/components/settings/settings-section";
import { useToast } from "@/components/toast-provider";
import { configureGitHubToken, clearGitHubToken } from "@/lib/api/domains/github-api";
import type { AuthDiagnostics } from "@/lib/types/github";
import { GitHubRateLimitDisplay } from "./github-rate-limit";
import { HostShellDialog } from "@/components/settings/host-shell-dialog";
import { useGitHubStatus } from "@/hooks/domains/github/use-github-status";
import { useGitHubAppRegistrations } from "@/hooks/domains/github/use-github-app-registrations";
import {
disconnectGitHubPersonal,
disconnectGitHubWorkspace,
startGitHubPersonalConnect,
} from "@/lib/api/domains/github-api";
import { getGitHubPersonalIdentityState } from "@/lib/github-auth";
import type {
GitHubConnectionSource,
GitHubConnectionState,
GitHubStatus,
GitHubAppRegistrationCatalogItem,
} from "@/lib/types/github";
import { GitHubConnectionDialog } from "./github-connection-dialog";
import { GitHubPermissionsDialog } from "./github-permissions-dialog";
function DiagnosticsOutput({ diagnostics }: { diagnostics: AuthDiagnostics }) {
return (
<div className="mt-3 space-y-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<code className="bg-muted px-1.5 py-0.5 rounded">{diagnostics.command}</code>
<Badge
variant={diagnostics.exit_code === 0 ? "secondary" : "destructive"}
className="text-xs"
>
exit code: {diagnostics.exit_code}
</Badge>
</div>
{diagnostics.exit_code !== 0 && (
<p className="text-xs text-muted-foreground">
A non-zero exit code means the command failed. Review the output below for details.
</p>
)}
<pre className="text-xs bg-muted/50 border rounded-md p-3 overflow-x-auto whitespace-pre-wrap max-h-48">
{diagnostics.output.trim()}
</pre>
</div>
);
}
function TokenConfigForm({ onSuccess }: { onSuccess: () => void }) {
const [token, setToken] = useState("");
const [showToken, setShowToken] = useState(false);
const [saving, setSaving] = useState(false);
const { toast } = useToast();
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault();
if (!token.trim()) return;
setSaving(true);
try {
await configureGitHubToken(token.trim());
toast({ description: "GitHub token configured successfully", variant: "success" });
setToken("");
onSuccess();
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to configure token";
toast({ description: message, variant: "error" });
} finally {
setSaving(false);
}
},
[token, toast, onSuccess],
);
return (
<form onSubmit={handleSubmit} className="space-y-3">
<div className="flex gap-2">
<div className="relative flex-1">
<Input
type={showToken ? "text" : "password"}
placeholder="ghp_xxxxxxxxxxxx"
value={token}
onChange={(e) => setToken(e.target.value)}
className="pr-8 font-mono text-sm"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0 cursor-pointer"
onClick={() => setShowToken(!showToken)}
>
{showToken ? (
<IconEyeOff className="h-3.5 w-3.5" />
) : (
<IconEye className="h-3.5 w-3.5" />
)}
</Button>
</div>
<Button
type="submit"
size="sm"
disabled={!token.trim() || saving}
className="cursor-pointer"
>
{saving ? <Spinner className="h-4 w-4" /> : <IconKey className="h-4 w-4 mr-1" />}
Configure
</Button>
</div>
<p className="text-xs text-muted-foreground">
Create a{" "}
<a
href="https://github.com/settings/tokens/new?scopes=repo,read:org&description=Kandev"
target="_blank"
rel="noopener noreferrer"
className="underline cursor-pointer"
>
Personal Access Token
</a>{" "}
with <code className="bg-muted px-1 rounded">repo</code> and{" "}
<code className="bg-muted px-1 rounded">read:org</code> scopes.
</p>
</form>
);
}
type StatusForNotConnected = {
diagnostics?: AuthDiagnostics;
const sourceLabels: Record<GitHubConnectionSource, string> = {
pat: "Personal access token",
gh_cli: "GitHub CLI",
github_app_installation: "GitHub App",
legacy_shared: "Legacy shared connection",
};
function NotConnectedView({
status,
refresh,
ghAuthOpen,
setGhAuthOpen,
}: {
status: StatusForNotConnected | null;
refresh: () => void;
ghAuthOpen: boolean;
setGhAuthOpen: (open: boolean) => void;
}) {
// gh installed → CLI sign-in is the recommended path (browser-driven OAuth,
// no PAT to manage). When it's missing we drop to PAT-only.
const ghInstalled = useAppStore((state) =>
state.availableAgents.tools.some((t) => t.name === "gh" && t.available),
);
const [tokenOpen, setTokenOpen] = useState(false);
const [diagOpen, setDiagOpen] = useState(false);
function connectionLabel(status: GitHubStatus): string {
const connection = status.automation;
if (!connection) return "";
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<IconX className="h-4 w-4 text-red-500" />
<span className="text-sm font-medium">Not connected to GitHub</span>
<Button variant="ghost" size="sm" onClick={refresh} className="cursor-pointer h-6 px-2">
<IconRefresh className="h-3.5 w-3.5" />
Refresh
</Button>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="ml-auto text-muted-foreground hover:text-foreground cursor-help"
aria-label="Authentication methods"
>
<IconInfoCircle className="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent className="max-w-xs">
<p className="text-xs">
Kandev also accepts a <code>GITHUB_TOKEN</code> environment variable on startup. The
UI options below cover the common cases.
</p>
</TooltipContent>
</Tooltip>
</div>
connection.actor?.login ??
connection.login ??
connection.installation_account_login ??
"GitHub App"
);
}
{ghInstalled ? (
<PrimaryCLISignIn onClick={() => setGhAuthOpen(true)} />
function automationActor(status: GitHubStatus): string | null {
if (!status.authenticated) return null;
return status.automation?.actor?.login ?? null;
}
function StatusLine({ status }: { status: GitHubStatus }) {
const connection = status.automation;
if (!connection) {
return (
<div className="flex items-center gap-2 text-sm">
<IconX className="h-4 w-4 shrink-0 text-destructive" />
<span>No automation connection</span>
</div>
);
}
const actor = automationActor(status);
const active = connection.status === "active" && actor !== null;
return (
<div className="flex min-w-0 flex-wrap items-center gap-2 text-sm">
{active ? (
<IconCheck className="h-4 w-4 shrink-0 text-green-500" />
) : (
<CLIUnavailableHint />
<IconX className="h-4 w-4 shrink-0 text-destructive" />
)}
<Collapsible open={tokenOpen} onOpenChange={setTokenOpen}>
<CollapsibleTrigger asChild>
<button
type="button"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground cursor-pointer"
>
{tokenOpen ? (
<IconChevronDown className="h-3 w-3" />
) : (
<IconChevronRight className="h-3 w-3" />
)}
{ghInstalled ? "Use a personal access token instead" : "Configure GitHub token"}
</button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-2">
{/* TokenConfigForm already renders the "Create a Personal Access
Token with repo + read:org scopes" hint below its input. */}
<TokenConfigForm onSuccess={refresh} />
</CollapsibleContent>
</Collapsible>
{status?.diagnostics && (
<DiagnosticsDisclosure
diagnostics={status.diagnostics}
open={diagOpen}
onOpenChange={setDiagOpen}
/>
)}
<HostShellDialog
open={ghAuthOpen}
onOpenChange={setGhAuthOpen}
initialInput={"gh auth login\n"}
onClose={refresh}
/>
<span className="min-w-0 break-words font-medium">
{actor ??
(connection.status === "active" ? "Authentication unavailable" : connectionLabel(status))}
</span>
<Badge variant={active ? "secondary" : "destructive"}>
{sourceLabels[connection.source]}
</Badge>
{connection.status !== "active" && <Badge variant="outline">{connection.status}</Badge>}
</div>
);
}
function DiagnosticsDisclosure({
diagnostics,
open,
onOpenChange,
async function redirectFrom(start: () => Promise<{ url?: string; URL?: string }>) {
const response = await start();
const url = response.url ?? response.URL;
if (!url) throw new Error("GitHub did not return a redirect URL");
window.location.assign(url);
}
function errorMessage(error: unknown, fallback: string) {
return error instanceof Error ? error.message : fallback;
}
function AutomationStatusSummary({
status,
app,
}: {
diagnostics: AuthDiagnostics;
open: boolean;
onOpenChange: (open: boolean) => void;
status: GitHubStatus;
app?: GitHubAppRegistrationCatalogItem;
}) {
const appAutomation = status.automation?.source === "github_app_installation";
return (
<div className="min-w-0 space-y-1">
<StatusLine status={status} />
<AutomationActorExplanation status={status} appAutomation={appAutomation} />
{appAutomation && <AppRegistrationDetails app={app} />}
{!appAutomation && <HumanIdentityExplanation status={status} />}
<AutomationError status={status} />
</div>
);
}
function AutomationActorExplanation({
status,
appAutomation,
}: {
status: GitHubStatus;
appAutomation: boolean;
}) {
const actor = status.automation?.actor?.login;
if (!status.authenticated || !actor) return null;
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>
);
}
function AppRegistrationDetails({ app }: { app?: GitHubAppRegistrationCatalogItem }) {
if (!app) return null;
return (
<>
<div className="flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span className="break-words">{app.display_name}</span>
<Badge variant="outline" className="capitalize">
{app.visibility}
</Badge>
<Badge variant="outline" className="capitalize">
Webhook {app.webhook_status}
</Badge>
<span>{app.source === "managed" ? "Created by Kandev" : "Imported"}</span>
</div>
{app.shared && (
<p className="text-xs text-amber-600 dark:text-amber-400">
This App registration is shared by {app.workspace_binding_count} workspaces. Registration
changes affect every workspace using it; installation access remains workspace-specific.
</p>
)}
</>
);
}
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>;
}
function AutomationActions({
status,
workspaceId,
busy,
onDisconnect,
onRefresh,
}: {
status: GitHubStatus;
workspaceId: string;
busy: boolean;
onDisconnect: () => void;
onRefresh: () => void;
}) {
return (
<Collapsible open={open} onOpenChange={onOpenChange}>
<CollapsibleTrigger asChild>
<button
type="button"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground cursor-pointer"
>
{open ? (
<IconChevronDown className="h-3 w-3" />
) : (
<IconChevronRight className="h-3 w-3" />
)}
Diagnostics (<code className="bg-muted px-1 rounded">{diagnostics.command}</code>, exit{" "}
{diagnostics.exit_code})
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<DiagnosticsOutput diagnostics={diagnostics} />
</CollapsibleContent>
</Collapsible>
);
}
function PrimaryCLISignIn({ onClick }: { onClick: () => void }) {
return (
<div className="rounded-md border border-primary/40 bg-primary/5 p-4 space-y-3">
<div className="space-y-1">
<p className="text-sm font-medium">Sign in with the GitHub CLI</p>
<p className="text-xs text-muted-foreground">
Recommended. Opens a terminal that runs{" "}
<code className="bg-muted px-1 rounded">gh auth login</code> with browser-based
authentication.
</p>
</div>
<div className="flex flex-wrap gap-2">
<GitHubPermissionsDialog status={status} />
<GitHubConnectionDialog status={status} workspaceId={workspaceId} onSaved={onRefresh} />
<Button
size="default"
onClick={onClick}
className="cursor-pointer"
data-testid="github-gh-auth-login"
variant="outline"
size="icon"
onClick={onRefresh}
className="h-11 w-11 cursor-pointer"
aria-label="Refresh GitHub connection"
>
<IconTerminal2 className="h-4 w-4 mr-2" />
Open terminal and sign in
<IconRefresh className="h-4 w-4" />
</Button>
</div>
);
}
function CLIUnavailableHint() {
return (
<div className="rounded-md border bg-muted/30 p-3 text-xs text-muted-foreground">
<p>
The <code className="bg-muted px-1 rounded">gh</code> CLI is not installed on this host - a
personal access token is the only sign-in option available here. To install it later, see{" "}
<a
href="https://cli.github.com"
target="_blank"
rel="noopener noreferrer"
className="underline hover:text-foreground cursor-pointer"
{status.automation && (
<Button
variant="outline"
onClick={onDisconnect}
disabled={busy}
className="h-11 cursor-pointer text-destructive"
>
cli.github.com
</a>
.
</p>
</div>
);
}
export function GitHubStatusCard() {
const { status, loaded, loading, refresh } = useGitHubStatus();
const { toast } = useToast();
const [clearing, setClearing] = useState(false);
const [ghAuthOpen, setGhAuthOpen] = useState(false);
const handleClearToken = useCallback(async () => {
setClearing(true);
try {
await clearGitHubToken();
toast({ description: "GitHub token removed", variant: "success" });
refresh();
} catch {
toast({ description: "Failed to clear token", variant: "error" });
} finally {
setClearing(false);
}
}, [toast, refresh]);
if (loading || !loaded) {
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Spinner className="h-4 w-4" />
Checking GitHub connection...
</div>
);
}
if (!status || !status.authenticated) {
return (
<NotConnectedView
status={status}
refresh={refresh}
ghAuthOpen={ghAuthOpen}
setGhAuthOpen={setGhAuthOpen}
/>
);
}
return (
<div className="space-y-3">
<div className="flex items-center gap-2">
<IconCheck className="h-4 w-4 text-green-500" />
<span className="text-sm">
Connected as <strong>{status.username}</strong>
</span>
<Badge variant="secondary" className="text-xs">
{status.auth_method === "gh_cli" ? "gh CLI" : "PAT"}
</Badge>
{status.token_configured && (
<Button
variant="ghost"
size="sm"
onClick={handleClearToken}
disabled={clearing}
className="cursor-pointer h-6 px-2 text-muted-foreground hover:text-destructive"
title="Remove configured token"
>
{clearing ? <Spinner className="h-3.5 w-3.5" /> : <IconTrash className="h-3.5 w-3.5" />}
</Button>
)}
</div>
{status.token_configured && (
<p className="text-xs text-muted-foreground">
Token stored in secrets. This token is used by remote agents for GitHub operations.
</p>
<IconTrash className="mr-2 h-4 w-4" />
Disconnect
</Button>
)}
<GitHubRateLimitDisplay info={status.rate_limit} />
</div>
);
}
export function GitHubAutomationSettings({ workspaceId }: { workspaceId: string }) {
const { status, loaded, loading, refresh } = useGitHubStatus(workspaceId);
const appRegistrations = useGitHubAppRegistrations(workspaceId);
const [busy, setBusy] = useState(false);
const { toast } = useToast();
const disconnect = useCallback(async () => {
setBusy(true);
try {
await disconnectGitHubWorkspace(workspaceId);
toast({ description: "Workspace GitHub connection removed", variant: "success" });
refresh();
} catch (error) {
toast({
description: error instanceof Error ? error.message : "Disconnect failed",
variant: "error",
});
} finally {
setBusy(false);
}
}, [refresh, toast, workspaceId]);
if (!loaded || loading || !status) return <LoadingStatus />;
const activeRegistrationId =
status.app_registration?.id ?? status.automation?.app_registration_id;
const activeApp = appRegistrations.registrations.find((item) => item.id === activeRegistrationId);
return (
<div
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} />
<AutomationActions
status={status}
workspaceId={workspaceId}
busy={busy}
onDisconnect={disconnect}
onRefresh={refresh}
/>
</div>
);
}
type PersonalIdentityView = {
active: boolean;
actor: string;
personalActive: boolean;
status: GitHubConnectionState | null;
};
function personalIdentityView(status: GitHubStatus): PersonalIdentityView {
const identity = getGitHubPersonalIdentityState(status);
return {
active: identity.active,
actor: identity.actor,
personalActive: identity.personalOAuthActive,
status: status.personal?.status ?? null,
};
}
function PersonalIdentityStatus({ view }: { view: PersonalIdentityView }) {
return (
<div className="flex min-w-0 flex-wrap items-center gap-2 text-sm">
{view.active ? (
<IconCheck className="h-4 w-4 text-green-500" />
) : (
<IconX className="h-4 w-4 text-destructive" />
)}
<span className="break-words font-medium">{view.actor}</span>
{view.personalActive && <Badge variant="secondary">Personal OAuth</Badge>}
{view.status && view.status !== "active" && (
<Badge variant="destructive">{view.status}</Badge>
)}
</div>
);
}
function PersonalIdentityActions({
status,
busy,
onConnect,
onDisconnect,
}: {
status: GitHubStatus;
busy: boolean;
onConnect: () => void;
onDisconnect: () => void;
}) {
return (
<div className="flex flex-col gap-2 sm:flex-row">
{status.app_available && status.automation?.source === "github_app_installation" && (
<Button disabled={busy} onClick={onConnect} className="h-11 cursor-pointer">
<IconBrandGithub className="mr-2 h-4 w-4" />
{status.personal ? "Reconnect identity" : "Connect identity"}
<IconExternalLink className="ml-2 h-4 w-4" />
</Button>
)}
{status.personal && (
<Button
variant="outline"
onClick={onDisconnect}
disabled={busy}
className="h-11 cursor-pointer text-destructive"
>
<IconTrash className="mr-2 h-4 w-4" />
Disconnect
</Button>
)}
</div>
);
}
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>
);
}
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>
);
}
const disconnect = async () => {
setBusy(true);
try {
await disconnectGitHubPersonal(workspaceId);
toast({ description: "Personal GitHub identity disconnected", variant: "success" });
refresh();
} catch (error) {
toast({
description: error instanceof Error ? error.message : "Disconnect failed",
variant: "error",
});
} finally {
setBusy(false);
}
};
const connect = () => {
void redirectFrom(() => startGitHubPersonalConnect(workspaceId)).catch((error: unknown) =>
toast({
description: errorMessage(error, "Identity connection failed"),
variant: "error",
}),
);
};
return (
<SettingsSection
title="My GitHub identity"
description="Optionally connect your GitHub user for My GitHub and human-attributed actions. This identity is never given to managed agents; workspace automation continues as the App."
>
<div className="space-y-4" data-testid="github-personal-identity">
<PersonalIdentityStatus view={view} />
{status.personal?.last_error && (
<p className="text-xs text-destructive">{status.personal.last_error}</p>
)}
<PersonalIdentityActions
status={status}
busy={busy}
onConnect={connect}
onDisconnect={disconnect}
/>
</div>
</SettingsSection>
);
}
function LoadingStatus() {
return (
<div className="flex min-h-11 items-center gap-2 text-sm text-muted-foreground">
<Spinner className="h-4 w-4" />
Checking GitHub connection...
</div>
);
}
/** Compatibility export used by older settings entrypoints. */
export function GitHubStatusCard({ workspaceId }: { workspaceId: string }) {
return <GitHubAutomationSettings workspaceId={workspaceId} />;
}
@@ -7,6 +7,7 @@ import { PRCIPopover } from "@/components/github/pr-ci-popover";
import { getPRStatusColor, pickDefaultPR } from "@/components/github/pr-task-icon";
import { prIdentitySlug } from "@/components/github/pr-utils";
import { usePRFeedbackBackgroundSync } from "@/hooks/domains/github/use-pr-ci-popover";
import { useAppStore } from "@/components/state-provider";
import type { TaskPR } from "@/lib/types/github";
/**
@@ -15,7 +16,8 @@ import type { TaskPR } from "@/lib/types/github";
* PR (keyed by id) so the hook count stays stable as the list changes.
*/
function PRFeedbackWarmer({ pr }: { pr: TaskPR }) {
usePRFeedbackBackgroundSync(pr);
const workspaceId = useAppStore((state) => state.workspaces.activeId);
usePRFeedbackBackgroundSync(workspaceId, pr);
return null;
}
@@ -25,6 +25,7 @@ import { prStatusKey, usePRStatuses } from "./use-pr-statuses";
import { PRRowTaskIndicator } from "./pr-row-task-indicator";
type PRListProps = {
workspaceId: string | null;
items: GitHubPR[];
loading: boolean;
error: string | null;
@@ -150,8 +151,16 @@ function PRRow({
);
}
function PRListBody({ loading, error, items, presets, onStartTask, prKeyToTasks }: PRListProps) {
const statuses = usePRStatuses(items);
function PRListBody({
workspaceId,
loading,
error,
items,
presets,
onStartTask,
prKeyToTasks,
}: PRListProps) {
const statuses = usePRStatuses(workspaceId, items);
if (loading) {
return (
<div className="flex justify-center py-10">
@@ -206,7 +206,7 @@ export function QuickTaskLauncher({
if (!open) onClose();
};
const handleSuccess = (task: Task) => {
if (payload?.kind === "pr") {
if (payload?.kind === "pr" && workspaceId) {
const repositoryId = pickRepositoryIdForPR(
task.repositories,
payload.pr,
@@ -216,6 +216,7 @@ export function QuickTaskLauncher({
// missing GH client) shouldn't block navigation — the existing
// branch-based poller will still try once the agent starts.
void createTaskPR({
workspace_id: workspaceId,
task_id: task.id,
repository_id: repositoryId,
pr_url: prURL(payload.pr),
@@ -22,10 +22,11 @@ type FetchArgs = {
customQuery: string;
repoFilter: string;
page: number;
workspaceId: string | null;
workspaceId: string;
};
type UseGitHubSearchOptions = {
enabled?: boolean;
kind: SearchKind;
presets: PresetOption[];
preset: string;
@@ -51,6 +52,7 @@ export function buildParams(
}
export function useGitHubSearch<T extends GitHubPR | GitHubIssue>({
enabled = true,
kind,
presets,
preset,
@@ -122,13 +124,18 @@ export function useGitHubSearch<T extends GitHubPR | GitHubIssue>({
);
useEffect(() => {
if (!enabled || !workspaceId) {
requestSeq.current += 1;
setState({ items: [], loading: false, error: null, lastFetchedAt: null, total: 0 });
return;
}
void fetchData({ preset, customQuery, repoFilter, page, workspaceId });
}, [fetchData, preset, customQuery, repoFilter, page, workspaceId]);
}, [enabled, fetchData, preset, customQuery, repoFilter, page, workspaceId]);
const refresh = useCallback(
() => fetchData({ preset, customQuery, repoFilter, page, workspaceId }),
[fetchData, preset, customQuery, repoFilter, page, workspaceId],
);
const refresh = useCallback(() => {
if (!enabled || !workspaceId) return Promise.resolve();
return fetchData({ preset, customQuery, repoFilter, page, workspaceId });
}, [enabled, fetchData, preset, customQuery, repoFilter, page, workspaceId]);
return { ...state, page, setPage, pageSize: SEARCH_PAGE_SIZE, refresh };
}
@@ -5,8 +5,13 @@ import type { GitHubPR, GitHubPRStatus } from "@/lib/types/github";
const getPRStatusesBatch = vi.fn();
vi.mock("@/lib/api/domains/github-api", () => ({
getPRStatusesBatch: (refs: { owner: string; repo: string; number: number }[]) =>
getPRStatusesBatch(refs) as Promise<{ statuses: Record<string, GitHubPRStatus> }>,
getPRStatusesBatch: (
workspaceId: string,
refs: { owner: string; repo: string; number: number }[],
) =>
getPRStatusesBatch(workspaceId, refs) as Promise<{
statuses: Record<string, GitHubPRStatus>;
}>,
}));
import { prStatusKey, usePRStatuses } from "./use-pr-statuses";
@@ -60,7 +65,7 @@ describe("usePRStatuses", () => {
});
it("skips fetch when prs list is empty", () => {
renderHook(() => usePRStatuses([]));
renderHook(() => usePRStatuses("ws-1", []));
expect(getPRStatusesBatch).not.toHaveBeenCalled();
});
@@ -69,7 +74,7 @@ describe("usePRStatuses", () => {
getPRStatusesBatch.mockResolvedValueOnce({
statuses: { "acme/widget#7": makeStatus(pr) },
});
const { result } = renderHook(() => usePRStatuses([pr]));
const { result } = renderHook(() => usePRStatuses("ws-1", [pr]));
await waitFor(() => {
expect(result.current.size).toBe(1);
});
@@ -81,7 +86,7 @@ describe("usePRStatuses", () => {
getPRStatusesBatch.mockResolvedValue({
statuses: { "acme/widget#7": makeStatus(pr) },
});
const { rerender, result } = renderHook(({ prs }) => usePRStatuses(prs), {
const { rerender, result } = renderHook(({ prs }) => usePRStatuses("ws-1", prs), {
initialProps: { prs: [pr] },
});
await waitFor(() => expect(result.current.size).toBe(1));
@@ -102,7 +107,7 @@ describe("usePRStatuses", () => {
getPRStatusesBatch.mockResolvedValue({
statuses: { "acme/widget#7": makeStatus(pr1), "acme/widget#8": makeStatus(pr2) },
});
const { rerender } = renderHook(({ prs }) => usePRStatuses(prs), {
const { rerender } = renderHook(({ prs }) => usePRStatuses("ws-1", prs), {
initialProps: { prs: [pr1] },
});
await waitFor(() => expect(getPRStatusesBatch).toHaveBeenCalledTimes(1));
@@ -115,7 +120,7 @@ describe("usePRStatuses", () => {
getPRStatusesBatch.mockResolvedValueOnce({
statuses: { "acme/widget#7": makeStatus(pr) },
});
const { result, rerender } = renderHook(({ prs }) => usePRStatuses(prs), {
const { result, rerender } = renderHook(({ prs }) => usePRStatuses("ws-1", prs), {
initialProps: { prs: [pr] },
});
await waitFor(() => expect(result.current.size).toBe(1));
@@ -13,7 +13,10 @@ export function prStatusKey(owner: string, repo: string, number: number): string
// prStatusKey(owner, repo, number). When the PR list changes (new page,
// different preset) we refetch; the backend caches per-PR so fast
// pagination stays cheap.
export function usePRStatuses(prs: GitHubPR[]): Map<string, GitHubPRStatus> {
export function usePRStatuses(
workspaceId: string | null,
prs: GitHubPR[],
): Map<string, GitHubPRStatus> {
const [statuses, setStatuses] = useState<Map<string, GitHubPRStatus>>(new Map());
// `completedKey` is set only after a fetch resolves (success or failure), so
// a transient error can be retried on the next render, and React Strict
@@ -22,7 +25,10 @@ export function usePRStatuses(prs: GitHubPR[]): Map<string, GitHubPRStatus> {
// completedKey stays empty and the second mount retries.
const completedKey = useRef<string>("");
const key = prs.map((p) => prStatusKey(p.repo_owner, p.repo_name, p.number)).join(",");
const key =
workspaceId && prs.length > 0
? `${workspaceId}:${prs.map((p) => prStatusKey(p.repo_owner, p.repo_name, p.number)).join(",")}`
: "";
// We deliberately depend only on `key`: `prs` gets a new array identity on
// every render, and including it would cancel an in-flight request whose
@@ -30,7 +36,11 @@ export function usePRStatuses(prs: GitHubPR[]): Map<string, GitHubPRStatus> {
// authoritative content signal; when it matches we reuse the latest `prs`
// closure for building request refs.
useEffect(() => {
if (key === "") return;
if (key === "") {
completedKey.current = "";
setStatuses(new Map());
return;
}
if (completedKey.current === key) return;
const refs: PRStatusRef[] = prs.map((p) => ({
owner: p.repo_owner,
@@ -38,7 +48,7 @@ export function usePRStatuses(prs: GitHubPR[]): Map<string, GitHubPRStatus> {
number: p.number,
}));
let cancelled = false;
getPRStatusesBatch(refs)
getPRStatusesBatch(workspaceId!, refs)
.then((resp) => {
if (cancelled) return;
completedKey.current = key;
@@ -55,7 +65,7 @@ export function usePRStatuses(prs: GitHubPR[]): Map<string, GitHubPRStatus> {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
}, [key, workspaceId]);
return statuses;
}
@@ -13,7 +13,7 @@ const hookMocks = vi.hoisted(() => ({
}));
vi.mock("@/hooks/domains/github/use-github-status", () => ({
useGitHubStatus: vi.fn(),
useGitHubStatus: () => ({ status: null }),
}));
vi.mock("@/hooks/domains/github/use-pr-ci-popover", () => ({
+7 -4
View File
@@ -545,11 +545,14 @@ export function PRCIPopover({
enabled: boolean;
onOpenDetailPanel?: () => void;
}) {
const ghStatus = useAppStore((s) => s.githubStatus.status);
const workspaceId = useAppStore((s) => s.workspaces.activeId);
const { status: ghStatus } = useGitHubStatus(workspaceId);
const authLost = ghStatus !== null && !ghStatus.authenticated;
// Trigger an initial status load from the same hook the rest of the app uses.
useGitHubStatus();
const { feedback, isFetching, lastUpdatedAt, refetch } = usePRCIPopover(pr, enabled && !authLost);
const { feedback, isFetching, lastUpdatedAt, refetch } = usePRCIPopover(
workspaceId,
pr,
enabled && !authLost,
);
const onAddAsContext = useAddCheckToContext(pr);
return (
+112 -101
View File
@@ -1,6 +1,8 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { createElement, useEffect } from "react";
import { TooltipProvider } from "@kandev/ui/tooltip";
import { StateProvider } from "@/components/state-provider";
import type { AppState } from "@/lib/state/store";
import { afterEach, describe, it, expect, vi } from "vitest";
import {
PRDetailContent,
@@ -33,10 +35,6 @@ vi.mock("@/lib/api/domains/github-review-api", () => ({
requestPRReviewers: reviewMocks.requestReviewers,
submitPRReview: reviewMocks.submitReview,
}));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: { setTaskPR: () => void }) => unknown) =>
selector({ setTaskPR: vi.fn() }),
}));
vi.mock("@/lib/state/slices/comments", () => ({
isPRFeedbackComment: () => false,
useCommentsStore: (
@@ -141,18 +139,20 @@ function ReviewRequestHarness({
onReady,
requestedReviewers = [],
reviews = [],
workspaceId = "workspace-1",
}: {
onReady: (reviewRequest: ReturnType<typeof usePRScopedReviewRequest>) => void;
requestedReviewers?: { login: string; type: "user" }[];
reviews?: PRReview[];
workspaceId?: string | null;
}) {
const reviewRequest = usePRScopedReviewRequest(
makeTaskPR(),
const reviewRequest = usePRScopedReviewRequest(makeTaskPR(), {
workspaceId,
requestedReviewers,
reviews,
vi.fn(),
vi.fn(),
);
refresh: vi.fn(),
toast: vi.fn(),
});
useEffect(() => onReady(reviewRequest), [onReady, reviewRequest]);
return null;
}
@@ -168,14 +168,23 @@ function dismissedReview(id = 1): PRReview {
};
}
function renderPRDetail() {
return render(
createElement(
const TEST_INITIAL_STATE = {
workspaces: { activeId: "workspace-1" },
} as unknown as Partial<AppState>;
function prDetailTree(taskPR = makeTaskPR()) {
return createElement(StateProvider, {
initialState: TEST_INITIAL_STATE,
children: createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
createElement(PRDetailContent, { taskPR, sessionId: "session-1" }),
),
);
});
}
function renderPRDetail(taskPR = makeTaskPR()) {
return render(prDetailTree(taskPR));
}
describe("shouldHideApproveButton", () => {
@@ -195,6 +204,12 @@ describe("shouldHideApproveButton", () => {
expect(shouldHideApproveButton(makeTaskPR({ author_login: "alice" }), null, " ")).toBe(true);
});
it("allows App-attributed approval when a mutation actor is available", () => {
expect(shouldHideApproveButton(makeTaskPR({ author_login: "alice" }), null, null, true)).toBe(
false,
);
});
it("hides when current user authored the PR (case-insensitive)", () => {
expect(shouldHideApproveButton(makeTaskPR({ author_login: "Alice" }), null, "alice")).toBe(
true,
@@ -251,13 +266,7 @@ describe("PRDetailContent deferred re-request", () => {
feedbackMocks.value = makeFeedback({ reviews: [dismissedReview()] });
reviewMocks.requestReviewers.mockResolvedValue({ requested: true });
render(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
renderPRDetail();
await act(async () => {
fireEvent.click(screen.getByTestId(RE_REQUEST_BUTTON));
@@ -266,6 +275,13 @@ describe("PRDetailContent deferred re-request", () => {
await waitFor(() => {
expect(screen.getByTestId(PENDING_REVIEWER)).not.toBeNull();
});
expect(reviewMocks.requestReviewers).toHaveBeenCalledWith(
"o",
"r",
1,
["octocat"],
"workspace-1",
);
expect(screen.queryByTestId(RE_REQUEST_BUTTON)).toBeNull();
});
});
@@ -275,23 +291,11 @@ describe("PRDetailContent remount lifecycle", () => {
feedbackMocks.value = makeFeedback({ reviews: [dismissedReview()] });
reviewMocks.requestReviewers.mockReturnValue(new Promise(() => undefined));
const firstPanel = render(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
const firstPanel = renderPRDetail();
fireEvent.click(screen.getByTestId(RE_REQUEST_BUTTON));
firstPanel.unmount();
render(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
renderPRDetail();
fireEvent.click(screen.getByTestId(RE_REQUEST_BUTTON));
expect(reviewMocks.requestReviewers).toHaveBeenCalledOnce();
@@ -319,13 +323,7 @@ describe("PRDetailContent optimistic review reconciliation", () => {
},
],
});
view.rerender(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
view.rerender(prDetailTree());
await waitFor(() => {
expect(screen.queryByTestId(PENDING_REVIEWER)).toBeNull();
@@ -354,13 +352,7 @@ describe("PRDetailContent same-timestamp review reconciliation", () => {
},
],
});
view.rerender(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
view.rerender(prDetailTree());
await waitFor(() => expect(screen.queryByTestId(PENDING_REVIEWER)).toBeNull());
expect(screen.getByTestId("pr-submitted-review-octocat")).not.toBeNull();
@@ -373,13 +365,7 @@ describe("PRDetailContent confirmed review request", () => {
reviews: [dismissedReview()],
});
reviewMocks.requestReviewers.mockResolvedValue({ requested: true });
const view = render(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
const view = renderPRDetail();
await act(async () => {
fireEvent.click(screen.getByTestId(RE_REQUEST_BUTTON));
});
@@ -397,25 +383,13 @@ describe("PRDetailContent confirmed review request", () => {
},
],
});
view.rerender(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
view.rerender(prDetailTree());
await waitFor(() => {
expect(screen.getByTestId(PENDING_REVIEWER)).not.toBeNull();
});
feedbackMocks.value = makeFeedback({ reviews: [dismissedReview()] });
view.rerender(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
view.rerender(prDetailTree());
await waitFor(() => {
expect(screen.getByTestId(RE_REQUEST_BUTTON)).not.toBeNull();
@@ -444,6 +418,70 @@ describe("PRDetailContent same-tick re-request", () => {
});
});
describe("PRDetailContent workspace-scoped requests", () => {
it("does not issue a cross-workspace request when no active workspace is available", async () => {
let reRequest: (reviewer: string) => Promise<void> = async () => undefined;
render(
createElement(ReviewRequestHarness, {
workspaceId: null,
onReady: (request) => {
reRequest = request.reRequest;
},
}),
);
await act(async () => reRequest("octocat"));
expect(reviewMocks.requestReviewers).not.toHaveBeenCalled();
});
it("keeps same-PR requests and optimistic reconciliation isolated by workspace", async () => {
reviewMocks.requestReviewers.mockResolvedValue({ requested: true });
let reviewRequest: ReturnType<typeof usePRScopedReviewRequest> | undefined;
const onReady = (value: ReturnType<typeof usePRScopedReviewRequest>) => {
reviewRequest = value;
};
const view = render(
createElement(ReviewRequestHarness, { onReady, workspaceId: "workspace-a" }),
);
await act(async () => reviewRequest?.reRequest("octocat"));
expect(reviewRequest?.requestedReviewers).toEqual([{ login: "octocat", type: "user" }]);
view.rerender(createElement(ReviewRequestHarness, { onReady, workspaceId: "workspace-b" }));
expect(reviewRequest?.requestedReviewers).toEqual([]);
await act(async () => reviewRequest?.reRequest("octocat"));
expect(reviewMocks.requestReviewers).toHaveBeenNthCalledWith(
1,
"o",
"r",
1,
["octocat"],
"workspace-a",
);
expect(reviewMocks.requestReviewers).toHaveBeenNthCalledWith(
2,
"o",
"r",
1,
["octocat"],
"workspace-b",
);
view.rerender(
createElement(ReviewRequestHarness, {
onReady,
workspaceId: "workspace-b",
requestedReviewers: [{ login: "octocat", type: "user" }],
}),
);
view.rerender(createElement(ReviewRequestHarness, { onReady, workspaceId: "workspace-a" }));
expect(reviewRequest?.requestedReviewers).toEqual([{ login: "octocat", type: "user" }]);
});
});
describe("PRDetailContent persistent request expiry", () => {
it("keeps an unresolved request locked beyond the optimistic expiry window", () => {
vi.useFakeTimers();
@@ -454,13 +492,7 @@ describe("PRDetailContent persistent request expiry", () => {
const view = renderPRDetail();
fireEvent.click(screen.getByTestId(RE_REQUEST_BUTTON));
act(() => vi.advanceTimersByTime(5 * 60 * 1000));
view.rerender(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
view.rerender(prDetailTree());
expect(screen.getByTestId(RE_REQUEST_BUTTON).hasAttribute("disabled")).toBe(true);
vi.useRealTimers();
@@ -491,13 +523,7 @@ describe("PRDetailContent persistent request expiry", () => {
feedbackMocks.value = makeFeedback({
pr: { requested_reviewers: [{ login: "octocat", type: "user" }] },
});
view.rerender(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
view.rerender(prDetailTree());
await act(async () => undefined);
expect(vi.getTimerCount()).toBe(0);
@@ -600,13 +626,7 @@ describe("PRDetailContent PR identity changes", () => {
feedbackMocks.value = makeFeedback({ reviews: [dismissedReview()] });
reviewMocks.requestReviewers.mockResolvedValue({ requested: true });
const view = render(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, { taskPR: makeTaskPR(), sessionId: "session-1" }),
),
);
const view = renderPRDetail();
await act(async () => {
fireEvent.click(screen.getByTestId(RE_REQUEST_BUTTON));
});
@@ -614,16 +634,7 @@ describe("PRDetailContent PR identity changes", () => {
expect(screen.getByTestId(PENDING_REVIEWER)).not.toBeNull();
});
view.rerender(
createElement(
TooltipProvider,
undefined,
createElement(PRDetailContent, {
taskPR: makeTaskPR({ pr_number: 2 }),
sessionId: "session-1",
}),
),
);
view.rerender(prDetailTree(makeTaskPR({ pr_number: 2 })));
expect(screen.getByTestId(RE_REQUEST_BUTTON)).not.toBeNull();
});
+36 -12
View File
@@ -20,10 +20,11 @@ import { useActiveTaskPR, useTaskPR } from "@/hooks/domains/github/use-task-pr";
import { prPanelLabel, prTaskKey } from "@/components/github/pr-utils";
import { usePRFeedback } from "@/hooks/domains/github/use-pr-feedback";
import { useGitHubStatus } from "@/hooks/domains/github/use-github-status";
import { getGitHubMutationActor } from "@/lib/github-auth";
import { useCommentsStore, isPRFeedbackComment } from "@/lib/state/slices/comments";
import type { PRFeedbackComment } from "@/lib/state/slices/comments";
import { useToast } from "@/components/toast-provider";
import { submitPRReview } from "@/lib/api/domains/github-review-api";
import { submitPRReview } from "@/lib/api/domains/github-pr-api";
import type { TaskPR, PRFeedback } from "@/lib/types/github";
import {
formatTimeAgo,
@@ -236,11 +237,12 @@ export function shouldHideApproveButton(
taskPR: TaskPR,
feedback: PRFeedback | null,
currentUser: string | null,
hasMutationActor = !!currentUser?.trim(),
): boolean {
const liveState = feedback?.pr.state ?? taskPR.state;
if (liveState !== "open") return true;
const normalizedUser = currentUser?.trim().toLowerCase();
if (!normalizedUser) return true;
if (!normalizedUser) return !hasMutationActor;
const prAuthor = feedback?.pr.author_login ?? taskPR.author_login;
if (prAuthor?.trim().toLowerCase() === normalizedUser) return true;
return (
@@ -255,10 +257,12 @@ export function shouldShowReRequestReviewAction(prState: string, reviewState: st
}
function ApproveButton({
workspaceId,
taskPR,
feedback,
onRefresh,
}: {
workspaceId: string | null;
taskPR: TaskPR;
feedback: PRFeedback | null;
onRefresh: () => void;
@@ -271,13 +275,19 @@ function ApproveButton({
// no identity to compare against the PR author.
const { status } = useGitHubStatus();
const currentUser = status?.username ?? null;
const mutationActor = getGitHubMutationActor(status);
if (shouldHideApproveButton(taskPR, feedback, currentUser)) return null;
if (shouldHideApproveButton(taskPR, feedback, currentUser, !!mutationActor)) return null;
const handleApprove = async () => {
if (!workspaceId) return;
setSubmitting(true);
try {
await submitPRReview(taskPR.owner, taskPR.repo, taskPR.pr_number, "APPROVE");
await submitPRReview(
workspaceId,
{ owner: taskPR.owner, repo: taskPR.repo, number: taskPR.pr_number },
"APPROVE",
);
toast({ description: "PR approved", variant: "success" });
onRefresh();
} catch (e) {
@@ -300,22 +310,28 @@ function ApproveButton({
disabled={submitting}
>
<IconCheck className="h-3.5 w-3.5" />
{submitting ? "Approving..." : "Approve PR"}
{submitting ? "Approving..." : `Approve as ${mutationActor}`}
</Button>
);
}
export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; sessionId: string }) {
const { feedback, loading, refresh } = usePRFeedback(taskPR.owner, taskPR.repo, taskPR.pr_number);
const workspaceId = useAppStore((state) => state.workspaces.activeId);
const { feedback, loading, refresh } = usePRFeedback(
workspaceId,
taskPR.owner,
taskPR.repo,
taskPR.pr_number,
);
const { addAsContext } = useAddPRFeedbackAsContext(sessionId, taskPR.pr_number);
const { toast } = useToast();
const reviewRequest = usePRScopedReviewRequest(
taskPR,
feedback?.pr.requested_reviewers ?? [],
feedback?.reviews ?? [],
const reviewRequest = usePRScopedReviewRequest(taskPR, {
workspaceId,
requestedReviewers: feedback?.pr.requested_reviewers ?? [],
reviews: feedback?.reviews ?? [],
refresh,
toast,
);
});
useSyncLivePRState(taskPR, feedback);
@@ -351,6 +367,7 @@ export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; session
return (
<div className="flex flex-col h-full">
<PRHeader
workspaceId={workspaceId}
taskPR={taskPR}
feedback={feedback}
metrics={metrics}
@@ -517,6 +534,7 @@ function HeaderStatsLine({ taskPR, metrics }: { taskPR: TaskPR; metrics: PRPanel
}
function PRHeader({
workspaceId,
taskPR,
feedback,
metrics,
@@ -525,6 +543,7 @@ function PRHeader({
onResolveConflicts,
conflictQueued,
}: {
workspaceId: string | null;
taskPR: TaskPR;
feedback: PRFeedback | null;
metrics: PRPanelMetrics;
@@ -546,7 +565,12 @@ function PRHeader({
<div className="flex-1 min-w-0">
<HeaderTitleRow taskPR={taskPR} loading={loading} onRefresh={onRefresh} />
</div>
<ApproveButton taskPR={taskPR} feedback={feedback} onRefresh={onRefresh} />
<ApproveButton
workspaceId={workspaceId}
taskPR={taskPR}
feedback={feedback}
onRefresh={onRefresh}
/>
<PRMergeButton taskPR={taskPR} onMerged={onRefresh} />
</div>
<div className="flex items-center gap-1.5 flex-wrap">
+112 -66
View File
@@ -9,12 +9,65 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@kandev/ui/dropdown-menu";
import { useAppStore } from "@/components/state-provider";
import { useToast } from "@/components/toast-provider";
import { useGitHubStatus } from "@/hooks/domains/github/use-github-status";
import { useRepoMergeMethods } from "@/hooks/domains/github/use-repo-merge-methods";
import { mergePR } from "@/lib/api/domains/github-api";
import { getGitHubMutationActor } from "@/lib/github-auth";
import type { MergeMethod, TaskPR } from "@/lib/types/github";
import { isPRReadyToMerge } from "./pr-task-icon";
function MutationActor({ actor }: { actor: string | null }) {
if (!actor) return null;
return <span className="text-[11px] text-muted-foreground">as {actor}</span>;
}
function CompactMergeButton({
label,
disabled,
actor,
onPrimaryClick,
extraMethods,
onPickMethod,
}: Omit<MergeButtonShellProps, "compact">) {
return (
<div className="flex flex-col gap-1.5">
<button
type="button"
data-testid="pr-merge-button"
onClick={onPrimaryClick}
disabled={disabled}
className="inline-flex w-full items-center justify-center gap-1.5 rounded-md bg-green-600 px-2 py-1.5 text-xs font-medium text-white shadow-sm transition-colors hover:bg-green-700 disabled:cursor-default disabled:opacity-60 cursor-pointer"
>
<IconGitMerge className="h-3.5 w-3.5" />
{label}
</button>
{extraMethods.length > 0 && (
<div className="flex items-center justify-center gap-1 text-[11px] text-muted-foreground">
<span>or</span>
{extraMethods.map((method) => (
<button
key={method}
type="button"
data-testid={`pr-merge-method-${method}`}
disabled={disabled}
onClick={(event) => {
event.stopPropagation();
onPickMethod(method);
}}
className="cursor-pointer rounded px-1.5 py-0.5 font-medium hover:bg-muted hover:text-foreground disabled:cursor-default disabled:opacity-60"
>
{mergeShortLabel(method)}
</button>
))}
</div>
)}
<MutationActor actor={actor} />
</div>
);
}
// Renders nothing unless the PR is fully green (CI success + mergeable +
// approval or no-review-needed). When `useRepoMergeMethods` hasn't yet
// returned the repo's allowed methods (loading, failure, or expired cache)
@@ -37,7 +90,10 @@ export function PRMergeButton({
// state="merged" — otherwise the button briefly re-enables during the async
// refresh window and a double-click would hit the GitHub API again.
const [merged, setMerged] = useState(false);
const methods = useRepoMergeMethods(taskPR.owner, taskPR.repo);
const workspaceId = useAppStore((state) => state.workspaces.activeId);
const methods = useRepoMergeMethods(workspaceId, taskPR.owner, taskPR.repo);
const { status } = useGitHubStatus(workspaceId);
const mutationActor = getGitHubMutationActor(status);
// If the same component instance ever renders a different PR (e.g. the user
// switches the active task while the panel/popover stays mounted), the
@@ -59,9 +115,10 @@ export function PRMergeButton({
const primary = pickPrimaryMethod(allowed);
const runMerge = async (method?: MergeMethod) => {
if (!workspaceId) return;
setMerging(true);
try {
await mergePR(taskPR.owner, taskPR.repo, taskPR.pr_number, method);
await mergePR(workspaceId, taskPR.owner, taskPR.repo, taskPR.pr_number, method);
setMerged(true);
toast({ description: "PR merged", variant: "success" });
onMerged?.();
@@ -86,6 +143,7 @@ export function PRMergeButton({
compact={compact}
label={merging ? "Merging..." : mergeLabel(primary)}
disabled={merging}
actor={mutationActor}
onPrimaryClick={handlePrimary}
extraMethods={allowed.filter((m) => m !== primary)}
onPickMethod={(m) => void runMerge(m)}
@@ -93,21 +151,25 @@ export function PRMergeButton({
);
}
type MergeButtonShellProps = {
compact: boolean;
label: string;
disabled: boolean;
actor: string | null;
onPrimaryClick: (e: React.MouseEvent) => void;
extraMethods: MergeMethod[];
onPickMethod: (m: MergeMethod) => void;
};
function MergeButtonShell({
compact,
label,
disabled,
actor,
onPrimaryClick,
extraMethods,
onPickMethod,
}: {
compact: boolean;
label: string;
disabled: boolean;
onPrimaryClick: (e: React.MouseEvent) => void;
extraMethods: MergeMethod[];
onPickMethod: (m: MergeMethod) => void;
}) {
}: MergeButtonShellProps) {
// Compact (hover popover): a single full-width primary button plus quiet
// "or <method>" links for the alternates. Deliberately avoids a dropdown —
// its menu renders in a detached portal that closes the hover popover the
@@ -115,38 +177,14 @@ function MergeButtonShell({
// every action inside the popover's own DOM.
if (compact) {
return (
<div className="flex flex-col gap-1.5">
<button
type="button"
data-testid="pr-merge-button"
onClick={onPrimaryClick}
disabled={disabled}
className="inline-flex w-full items-center justify-center gap-1.5 rounded-md bg-green-600 px-2 py-1.5 text-xs font-medium text-white shadow-sm transition-colors hover:bg-green-700 disabled:cursor-default disabled:opacity-60 cursor-pointer"
>
<IconGitMerge className="h-3.5 w-3.5" />
{label}
</button>
{extraMethods.length > 0 && (
<div className="flex items-center justify-center gap-1 text-[11px] text-muted-foreground">
<span>or</span>
{extraMethods.map((m) => (
<button
key={m}
type="button"
data-testid={`pr-merge-method-${m}`}
disabled={disabled}
onClick={(e) => {
e.stopPropagation();
onPickMethod(m);
}}
className="cursor-pointer rounded px-1.5 py-0.5 font-medium hover:bg-muted hover:text-foreground disabled:cursor-default disabled:opacity-60"
>
{mergeShortLabel(m)}
</button>
))}
</div>
)}
</div>
<CompactMergeButton
label={label}
disabled={disabled}
actor={actor}
onPrimaryClick={onPrimaryClick}
extraMethods={extraMethods}
onPickMethod={onPickMethod}
/>
);
}
@@ -165,33 +203,41 @@ function MergeButtonShell({
);
if (!showDropdown) {
return <span className="self-end">{primaryBtn}</span>;
return (
<span className="flex flex-col items-end gap-1 self-end">
{primaryBtn}
<MutationActor actor={actor} />
</span>
);
}
return (
<span className="self-end inline-flex">
{primaryBtn}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
data-testid="pr-merge-button-more"
aria-label="Choose merge method"
disabled={disabled}
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center rounded-r-md border-l border-green-700/40 bg-green-600 px-2 text-white hover:bg-green-700 dark:bg-green-600 dark:hover:bg-green-500 disabled:opacity-60 cursor-pointer"
>
<IconChevronDown className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-auto">
{extraMethods.map((m) => (
<DropdownMenuItem key={m} onSelect={() => onPickMethod(m)}>
{mergeLabel(m)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<span className="flex flex-col items-end gap-1 self-end">
<span className="inline-flex">
{primaryBtn}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
data-testid="pr-merge-button-more"
aria-label="Choose merge method"
disabled={disabled}
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center rounded-r-md border-l border-green-700/40 bg-green-600 px-2 text-white hover:bg-green-700 dark:bg-green-600 dark:hover:bg-green-500 disabled:opacity-60 cursor-pointer"
>
<IconChevronDown className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-auto">
{extraMethods.map((m) => (
<DropdownMenuItem key={m} onSelect={() => onPickMethod(m)}>
{mergeLabel(m)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</span>
<MutationActor actor={actor} />
</span>
);
}
@@ -28,6 +28,7 @@ import { usePRFeedbackBackgroundSync } from "@/hooks/domains/github/use-pr-ci-po
import { PR_CI_DESKTOP_POPOVER_SCROLL_CLASS, PRCIPopover } from "@/components/github/pr-ci-popover";
import { useTaskCIAutomationOptions } from "@/hooks/domains/github/use-task-ci-options";
import { MultiPRCIPopover } from "@/components/github/multi-pr-ci-popover";
import { useAppStore } from "@/components/state-provider";
import {
hasPRChecksInProgressForDisplay,
hasPRChecksPassedForDisplay,
@@ -165,6 +166,7 @@ function useChipPopoverInteractions() {
* CI chip would be redundant.
*/
export function PRStatusChip({ taskId }: { taskId: string | null }) {
const workspaceId = useAppStore((state) => state.workspaces.activeId);
const { prs } = useTaskPR(taskId);
const { options: automationOptions } = useTaskCIAutomationOptions(taskId);
// Defensive Array.isArray: a partial hydration can briefly seed the store
@@ -180,7 +182,7 @@ export function PRStatusChip({ taskId }: { taskId: string | null }) {
// popover will actually open first (worst-status via pickDefaultPR — for a
// single PR that's just the PR itself); the remaining PRs in a multi-PR
// task warm when the popover opens.
usePRFeedbackBackgroundSync(pickDefaultPR(openPRs));
usePRFeedbackBackgroundSync(workspaceId, pickDefaultPR(openPRs));
if (openPRs.length === 0) return null;
if (openPRs.length === 1)
return (
@@ -36,24 +36,36 @@ type RepoFilterSelectorProps = {
workspaceId?: string;
};
function useGitHubOrgs() {
function useGitHubOrgs(workspaceId: string | undefined) {
const [orgs, setOrgs] = useState<GitHubOrg[]>([]);
const [loading, setLoading] = useState(true);
const fetchedRef = useRef(false);
useEffect(() => {
if (fetchedRef.current) return;
fetchedRef.current = true;
listUserOrgs()
.then((r) => setOrgs(r.orgs ?? []))
.catch(() => setOrgs([]))
.finally(() => setLoading(false));
}, []);
if (!workspaceId) {
setOrgs([]);
setLoading(false);
return;
}
let cancelled = false;
setLoading(true);
listUserOrgs(workspaceId)
.then((r) => {
if (!cancelled) setOrgs(r.orgs ?? []);
})
.catch(() => {
if (!cancelled) setOrgs([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [workspaceId]);
return { orgs, loading };
}
function useRepoSearch(org: string, query: string) {
function useRepoSearch(workspaceId: string | undefined, org: string, query: string) {
const [searchState, setSearchState] = useState<{
results: GitHubRepoInfo[];
loading: boolean;
@@ -63,15 +75,23 @@ function useRepoSearch(org: string, query: string) {
useEffect(() => {
clearTimeout(timerRef.current);
if (!org) return;
if (!workspaceId || !org) return;
let cancelled = false;
timerRef.current = setTimeout(() => {
setSearchState((prev) => ({ ...prev, loading: true, org }));
searchOrgRepos(org, query || undefined)
.then((r) => setSearchState({ results: r.repos ?? [], loading: false, org }))
.catch(() => setSearchState({ results: [], loading: false, org }));
searchOrgRepos(workspaceId, org, query || undefined)
.then((r) => {
if (!cancelled) setSearchState({ results: r.repos ?? [], loading: false, org });
})
.catch(() => {
if (!cancelled) setSearchState({ results: [], loading: false, org });
});
}, 300);
return () => clearTimeout(timerRef.current);
}, [org, query]);
return () => {
cancelled = true;
clearTimeout(timerRef.current);
};
}, [workspaceId, org, query]);
// Clear results when org becomes empty (derived, not in effect)
const results = org ? searchState.results : [];
@@ -214,10 +234,12 @@ function OrgBadges({
}
function RepoSearchCombobox({
workspaceId,
disabled,
scope,
onAdd,
}: {
workspaceId: string | undefined;
disabled: boolean;
scope: GitHubWorkspaceSettings | null;
onAdd: (owner: string, name: string) => void;
@@ -228,7 +250,7 @@ function RepoSearchCombobox({
const slashIdx = value.indexOf("/");
const org = slashIdx > 0 ? value.slice(0, slashIdx) : "";
const query = slashIdx > 0 ? value.slice(slashIdx + 1) : "";
const { results, loading: searchLoading } = useRepoSearch(org, query);
const { results, loading: searchLoading } = useRepoSearch(workspaceId, org, query);
const filteredResults = useMemo(
() => results.filter((repo) => repoAllowedByScope(scope, repo.owner, repo.name)).slice(0, 10),
[results, scope],
@@ -308,7 +330,7 @@ export function RepoFilterSelector({
onSelectedReposChange,
workspaceId,
}: RepoFilterSelectorProps) {
const { orgs, loading: orgsLoading } = useGitHubOrgs();
const { orgs, loading: orgsLoading } = useGitHubOrgs(workspaceId);
const scope = useWorkspaceRepoScope(workspaceId);
const scopedOrgs = useMemo(
() => orgs.filter((org) => orgAllowedByScope(scope, org.login)),
@@ -383,7 +405,12 @@ export function RepoFilterSelector({
</div>
)}
<RepoSearchCombobox disabled={allRepos} scope={scope} onAdd={addRepo} />
<RepoSearchCombobox
workspaceId={workspaceId}
disabled={allRepos}
scope={scope}
onAdd={addRepo}
/>
<SelectedFilters repos={selectedRepos} onRemove={removeFilter} disabled={allRepos} />
</>
@@ -8,6 +8,14 @@ type Toast = (message: {
variant: "error" | "success";
}) => void;
type ReviewRequestOptions = {
workspaceId: string | null;
requestedReviewers: RequestedReviewer[];
reviews: PRReview[];
refresh: () => void;
toast: Toast;
};
type ReviewBaseline = Pick<PRReview, "id" | "author" | "created_at" | "state">;
type RequestEntry = {
@@ -30,8 +38,15 @@ function normalizeLogin(login: string) {
return login.trim().toLowerCase();
}
function prIdentity(taskPR: TaskPR) {
return `${taskPR.owner.toLowerCase()}:${taskPR.repo.toLowerCase()}:${taskPR.pr_number}`;
function normalizeWorkspaceId(workspaceId: string) {
return workspaceId.trim().toLowerCase();
}
function prIdentity(workspaceId: string | null, taskPR: TaskPR) {
if (!workspaceId) return null;
const normalizedWorkspaceId = normalizeWorkspaceId(workspaceId);
if (!normalizedWorkspaceId) return null;
return `${normalizedWorkspaceId}:${taskPR.owner.toLowerCase()}:${taskPR.repo.toLowerCase()}:${taskPR.pr_number}`;
}
function entryKey(identity: string, reviewer: string) {
@@ -175,12 +190,9 @@ export function clearPRReviewRequestRegistryForTests() {
export function usePRScopedReviewRequest(
taskPR: TaskPR,
requestedReviewers: RequestedReviewer[],
reviews: PRReview[],
refresh: () => void,
toast: Toast,
{ workspaceId, requestedReviewers, reviews, refresh, toast }: ReviewRequestOptions,
) {
const identity = prIdentity(taskPR);
const identity = prIdentity(workspaceId, taskPR);
useSyncExternalStore(
subscribe,
() => revision,
@@ -188,16 +200,31 @@ export function usePRScopedReviewRequest(
);
useEffect(() => {
if (!identity) return;
reconcile(identity, requestedReviewers, reviews);
}, [identity, requestedReviewers, reviews]);
const reRequest = useCallback(
async (reviewer: string) => {
if (!workspaceId || !identity) {
toast({
title: "Failed to re-request review",
description: "Select a workspace before requesting review.",
variant: "error",
});
return;
}
const baseline = latestReview(reviews, reviewer);
const operationId = beginRequest(identity, reviewer, baseline);
if (operationId === null) return;
try {
await requestPRReviewers(taskPR.owner, taskPR.repo, taskPR.pr_number, [reviewer]);
await requestPRReviewers(
taskPR.owner,
taskPR.repo,
taskPR.pr_number,
[reviewer],
workspaceId,
);
} catch (error) {
finishRequest(identity, reviewer, operationId, false);
toast({
@@ -215,10 +242,10 @@ export function usePRScopedReviewRequest(
// The request remains optimistic until the bounded registry expires or server data resolves it.
}
},
[identity, refresh, reviews, taskPR.owner, taskPR.pr_number, taskPR.repo, toast],
[identity, refresh, reviews, taskPR.owner, taskPR.pr_number, taskPR.repo, toast, workspaceId],
);
const activeEntries = getEntries(identity);
const activeEntries = identity ? getEntries(identity) : [];
const requestingReviewers = activeEntries
.filter((entry) => entry.status === "requesting")
.map((entry) => entry.reviewer);