mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 00:53:38 +02:00
## Thinking Path > - Paperclip manages agent work and the tools each agent can use. > - GitHub bots need their own App identity and restricted repository access. > - Manual App configuration and repeated setup gates make that connection hard to finish. > - GitHub can create an App from a manifest, but people must approve creation and repository access. > - Each Paperclip stack should own configuration, credentials, signature verification, and task admission. > - This change uses Cloud as an encrypted callback and event gateway, then completes setup in the stack. > - GitHub review bots have their own experimental setting. Chat connector opt-in does not control them. ## Linked Issues or Issue Description **What existing behavior does this improve?** Dedicated GitHub App setup, bot settings, and task-scoped GitHub replies. **Current behavior** Users must configure an App, copy credentials, repeat repository selection, and complete manual verification gates. Review settings are hard to scan. Mentions in descriptions can be missed, and automatic completion text can produce an extra GitHub comment. **Proposed behavior** Choose an agent and connect GitHub under a personal account or organization. GitHub asks for creation and installation consent. Paperclip resumes the same draft, stores secrets locally, imports access, verifies delivery, and opens Settings. Each accepted request has one editable App-owned comment for progress and results. Review assessments produce deterministic checks for the reviewed commit. **Breaking changes** GitHub bots require their own default-off experimental opt-in. The setup-method and delegated-agent screens are removed. Per-person automatic-run flags remain readable but are replaced by author filters. Existing connections, direct webhooks, saved restrictions, and manual existing-App recovery remain supported. Companion gateway: https://github.com/paperclipai/paperclip-cloud/pull/688 (merged). The roadmap and related PRs were checked; no duplicate dedicated-App wizard was found. ## What Changed - Add an independent **GitHub review bots** setting across the catalog, routes, identity admission, and task controls. Existing bots continue running when the UI setting is off. - Replace setup with Choose agent and Connect GitHub. Support personal and organization owners, inline low-trust conversion, saved drafts, known organization suggestions, automatic completion, and same-App recovery. - Keep manifests, OAuth PKCE, credential exchange, vault storage, installation verification, and original webhook-signature validation in the stack. Use the Cloud sealed gateway for public callbacks and outbound local delivery. - Add resumable owner metadata in migration 0323. Retry a failed registration renewal through the same durable replacement rather than creating another App route. - Support authorized mentions in issue and PR bodies, comments, inline comments, and review summaries. Preserve attachments, edited-source identity, duplicate protection, and lifecycle invalidation. Filter requests explicitly addressed to another connected bot. - Give agents task-scoped review, comment, and update tools. Update one working comment through progress and final output. Close coalesced requests and recover delayed acknowledgements, including deleted earlier working comments. Preserve automatic replies for legacy connections without saved review configuration. Preserve partial publication evidence and quarantine uncertain automatic fallbacks without blocking Board messages or questions. - Reorganize Settings and Access with rich slash-skill instructions, numeric passing scores, clear automation controls, formal-review tooltips, member and contributor sections, and verified App branding links. Preserve invalid score drafts and automation choices across tabs. - Paginate repositories in 20-row batches with search and a true connection-wide toggle. Batch verification at GitHub's 500-ID token limit. Keep saved repository overrides while hiding their editor. - Give each review a detail URL that remains usable beyond the newest 100 records. Synchronize the manager OpenAPI contracts and add recovery, authorization, UI, and browser regressions. - Reconcile the current master branch and retain its agent avatar, feature catalog, and extracted heartbeat preparation code. Preserve a saved test-drive port and recover from an occupied high port. ## Verification - Focused UI, independent experimental-setting, and CLI tests: 199 passed. - `pnpm -r typecheck`, `pnpm build`, and `pnpm check:token-gates` passed. The broad local Vitest attempt was interrupted after resource timeouts and stale expectations; the affected regressions passed focused reruns. The latest-head full CI matrix passed, including all browser shards, server/chat suites, builds, typechecking, canary packaging, and Docker context integrity. A Docker Hub 429 required a CI retry; it passed without changing the code. - Final review repairs: 127 attachment/event tests and server typecheck passed. All 13 final integration regressions passed under the normal CI timeout, covering legacy reply compatibility, deleted coalesced comments, inline-only review completion, progress edits, and native final recovery. Restart-safe description/review attachments passed the attachment suite. - Final regressions: four reply/lifecycle tests, both native GitHub wait tests, 171 feature-gate/reply-contract tests, the routed review preview, and five scheduler/reply regressions passed. The final fixture repair also passed all six setup-continuation cases and all three complete chat-test shards in CI, covering terminal receipts and retries under the normal CI timeout. One loaded-host receipt run exceeded its local timeout; the exact case passed in an isolated rerun and the complete CI shard. - GitHub integration tests cover personal and organization setup, retry recovery, edited mentions, attachment provenance, coalesced requests, delayed acknowledgements, partial review writes, old review URLs, and company boundaries. - Browser qualification: both GitHub journeys, all five provider setup/management journeys, and the GitHub uncertain-send recovery journey passed. GitHub setup, reconnect, and task replies run with chat disabled; chat enabled alone cannot expose GitHub bots. The disposable qualification database was removed after testing. - Earlier live qualification verified App-owned issue replies, native slash-skill invocation, progress comment edits, and a 5/5 PR review with a passing current-head check in the dedicated permissions-smoke repository. These live checks did not use personal credentials as bot execution authority. ## Risks - Deploy the merged Cloud gateway protocol before the stack update. Each callback and encrypted event must retain the original instance and tenant binding. - Migration 0323 uses idempotent column additions for test installations that already applied the earlier draft migration number. - A verified connection does not prove runtime isolation or a completed review. Runtime checks remain separate. - Required merge checks must be configured in GitHub. A passing numeric score does not formally approve a PR; approval and request-changes tools remain opt-in. - Existing-App credentials cannot silently renew an uncertain manifest exchange. Recovery preserves the existing App, draft, connection, and agent. - Repository changes save immediately. Global toggles affect all currently available repositories, including unloaded rows, without granting new installation access. - A failed or uncertain tool write suppresses automatic fallback text; the governed outbox retains its evidence. Deleted or replaced response comments are not recreated through a personal credential fallback. - GitHub logo upload remains an optional human action in GitHub App settings. Runtime provisioning, delegated setup, screenshot publication, and production push delivery remain deferred. ## Model Used OpenAI Codex, based on GPT-6, with tool use and code execution. The exact runtime model identifier and context size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub references) - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass (focused suites; complete test matrix is checked in CI) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
1120 lines
40 KiB
TypeScript
1120 lines
40 KiB
TypeScript
import { copyTextToClipboard } from "@/lib/clipboard";
|
||
import { useEffect, useId, useRef, useState } from "react";
|
||
import { useQuery } from "@tanstack/react-query";
|
||
import {
|
||
GITHUB_REVIEW_EVENTS,
|
||
type GitHubChatConfiguration,
|
||
type GitHubReviewPolicy,
|
||
type GitHubAllowedPerson,
|
||
} from "@paperclipai/shared";
|
||
import { accessApi } from "@/api/access";
|
||
import { chatEndpointsApi } from "@/api/chatEndpoints";
|
||
import { githubChatApi } from "@/api/githubChat";
|
||
import { useOptionalCompany } from "@/context/CompanyContext";
|
||
import { Button } from "@/components/ui/button";
|
||
import {
|
||
AtSign,
|
||
Check,
|
||
Copy,
|
||
HelpCircle,
|
||
MoreHorizontal,
|
||
Plus,
|
||
} from "lucide-react";
|
||
import {
|
||
DropdownMenu,
|
||
DropdownMenuContent,
|
||
DropdownMenuItem,
|
||
DropdownMenuTrigger,
|
||
} from "@/components/ui/dropdown-menu";
|
||
import { Checkbox } from "@/components/ui/checkbox";
|
||
import {
|
||
Dialog,
|
||
DialogContent,
|
||
DialogDescription,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
} from "@/components/ui/dialog";
|
||
import { GitHubSettingsDisclosure } from "./GitHubSettingsDisclosure";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Textarea } from "@/components/ui/textarea";
|
||
import { MarkdownEditor } from "@/components/MarkdownEditor";
|
||
import { Label } from "@/components/ui/label";
|
||
import { ToggleSwitch } from "@/components/ui/toggle-switch";
|
||
import { Link } from "@/lib/router";
|
||
import {
|
||
Tooltip,
|
||
TooltipContent,
|
||
TooltipTrigger,
|
||
} from "@/components/ui/tooltip";
|
||
|
||
export const githubSelectClass =
|
||
"w-full rounded-md border border-input bg-background px-3 py-2 text-sm";
|
||
const eventLabels = {
|
||
opened: "New pull request",
|
||
synchronize: "Updated commits",
|
||
reopened: "Reopened",
|
||
ready_for_review: "Ready for review",
|
||
mention: "Mention",
|
||
comment: "Follow-up comment",
|
||
};
|
||
function GitHubHelp({
|
||
label,
|
||
children,
|
||
}: {
|
||
label: string;
|
||
children: React.ReactNode;
|
||
}) {
|
||
const [open, setOpen] = useState(false);
|
||
return (
|
||
<Tooltip open={open} onOpenChange={setOpen}>
|
||
<TooltipTrigger asChild>
|
||
<button
|
||
type="button"
|
||
aria-label={`About ${label}`}
|
||
className="inline-flex shrink-0 items-center text-muted-foreground hover:text-foreground"
|
||
onClick={() => setOpen(true)}
|
||
>
|
||
<HelpCircle className="size-4" />
|
||
</button>
|
||
</TooltipTrigger>
|
||
<TooltipContent className="max-w-xs">{children}</TooltipContent>
|
||
</Tooltip>
|
||
);
|
||
}
|
||
|
||
export function GitHubToggle({
|
||
label,
|
||
description,
|
||
help,
|
||
checked,
|
||
onChange,
|
||
ariaLabel,
|
||
disabled,
|
||
}: {
|
||
label: string;
|
||
description?: string;
|
||
help?: string;
|
||
checked: boolean;
|
||
onChange: (checked: boolean) => void;
|
||
ariaLabel?: string;
|
||
disabled?: boolean;
|
||
}) {
|
||
return (
|
||
<div className="flex items-center justify-between gap-4 py-2">
|
||
<div className="min-w-0">
|
||
<div className="flex items-center gap-2">
|
||
<p className="break-words text-sm font-medium">{label}</p>
|
||
{help && <GitHubHelp label={label}>{help}</GitHubHelp>}
|
||
</div>
|
||
{description && (
|
||
<p className="mt-1 text-xs text-muted-foreground">{description}</p>
|
||
)}
|
||
</div>
|
||
<ToggleSwitch
|
||
aria-label={ariaLabel ?? label}
|
||
disabled={disabled}
|
||
checked={checked}
|
||
onCheckedChange={onChange}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
/** Keep separators while typing; the saved policy still contains normalized lists. */
|
||
function GitHubListInput({
|
||
id,
|
||
values,
|
||
separator = "\n",
|
||
onChange,
|
||
}: {
|
||
id: string;
|
||
values: string[];
|
||
separator?: "\n" | ",";
|
||
onChange: (values: string[]) => void;
|
||
}) {
|
||
const joiner = separator === "," ? ", " : "\n";
|
||
const [text, setText] = useState(values.join(joiner));
|
||
const parse = (value: string) =>
|
||
value
|
||
.split(separator)
|
||
.map((item) => item.trim())
|
||
.filter(Boolean);
|
||
useEffect(() => {
|
||
setText((current) =>
|
||
JSON.stringify(parse(current)) === JSON.stringify(values)
|
||
? current
|
||
: values.join(joiner),
|
||
);
|
||
}, [values, separator]);
|
||
const props = {
|
||
id,
|
||
value: text,
|
||
onChange: (
|
||
event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
|
||
) => {
|
||
setText(event.target.value);
|
||
onChange(parse(event.target.value));
|
||
},
|
||
};
|
||
return separator === "\n" ? <Textarea {...props} /> : <Input {...props} />;
|
||
}
|
||
|
||
function GitHubPassingScore({
|
||
value,
|
||
onChange,
|
||
onValidityChange,
|
||
text: controlledText,
|
||
onTextChange,
|
||
}: {
|
||
text?: string;
|
||
onTextChange?: (text: string) => void;
|
||
value: GitHubReviewPolicy["ratingThreshold"];
|
||
onChange: (value: GitHubReviewPolicy["ratingThreshold"]) => void;
|
||
onValidityChange?: (valid: boolean) => void;
|
||
}) {
|
||
const id = useId();
|
||
const [localText, setLocalText] = useState(String(value ?? 5));
|
||
const text = controlledText ?? localText;
|
||
const setText = onTextChange ?? setLocalText;
|
||
const number = Number(text);
|
||
const valid = value === null || (text.trim() !== "" && Number.isInteger(number) && number >= 1 && number <= 5);
|
||
useEffect(() => setLocalText(String(value ?? 5)), [value]);
|
||
useEffect(() => { onValidityChange?.(valid); }, [valid, onValidityChange]);
|
||
return (
|
||
<div className="space-y-3 py-3">
|
||
<Label htmlFor={id}>Passing score</Label>
|
||
<div className="flex flex-wrap items-center gap-4">
|
||
<div className="flex items-center gap-2">
|
||
<Input id={id} type="number" min={1} max={5} step={1} required
|
||
className="w-20" value={text} disabled={value === null}
|
||
aria-invalid={!valid} aria-describedby={`${id}-help${valid ? "" : ` ${id}-error`}`}
|
||
onChange={(event) => {
|
||
const next = event.target.value;
|
||
setText(next);
|
||
const score = Number(next);
|
||
if (next.trim() && Number.isInteger(score) && score >= 1 && score <= 5)
|
||
onChange(score as 1 | 2 | 3 | 4 | 5);
|
||
}} />
|
||
<span className="text-sm text-muted-foreground">out of 5</span>
|
||
</div>
|
||
<Label className="flex items-center gap-2 text-sm font-normal">
|
||
<Checkbox aria-label="Report only" checked={value === null}
|
||
onCheckedChange={(checked) => { setText("5"); onChange(checked === true ? null : 5); }} />
|
||
Report only
|
||
</Label>
|
||
</div>
|
||
{!valid && <p id={`${id}-error`} role="alert" className="text-xs text-destructive">Enter a whole number from 1 to 5.</p>}
|
||
<p id={`${id}-help`} className="text-xs text-muted-foreground">
|
||
{value === null
|
||
? "Publishes a neutral check without a score requirement. GitHub can accept neutral checks for merging."
|
||
: "Paperclip passes the check when a complete review of the latest commit meets this score. Lower scores fail. This does not approve the PR."}
|
||
</p>
|
||
<p className="text-xs text-muted-foreground">
|
||
To block merging, require the <strong>Paperclip Review</strong> check from this App in your GitHub branch rules.{" "}
|
||
<a className="underline hover:text-foreground"
|
||
href="https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/creating-rulesets-for-a-repository"
|
||
target="_blank" rel="noreferrer">Configure on GitHub</a>
|
||
</p>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function GitHubPolicyEditor({
|
||
policy,
|
||
onChange,
|
||
accessHref,
|
||
onValidityChange,
|
||
scoreText,
|
||
onScoreTextChange,
|
||
rememberedAutomaticMode,
|
||
readOnly = false,
|
||
}: {
|
||
accessHref?: string;
|
||
readOnly?: boolean;
|
||
scoreText?: string;
|
||
onScoreTextChange?: (text: string) => void;
|
||
rememberedAutomaticMode?: "linked_authors" | "allowed_authors";
|
||
policy: GitHubReviewPolicy;
|
||
onChange: (policy: GitHubReviewPolicy) => void;
|
||
onValidityChange?: (valid: boolean) => void;
|
||
}) {
|
||
const id = useId();
|
||
const automaticMode = useRef<"linked_authors" | "allowed_authors">(
|
||
"linked_authors",
|
||
);
|
||
if (policy.invocation !== "mentions_only")
|
||
automaticMode.current = policy.invocation;
|
||
const filterField = (
|
||
key:
|
||
| "includeAuthors"
|
||
| "excludeAuthors"
|
||
| "targetBranches"
|
||
| "excludedBranches"
|
||
| "requiredLabels"
|
||
| "excludedLabels"
|
||
| "ignoredPaths",
|
||
label: string,
|
||
help: string,
|
||
) => (
|
||
<div className="space-y-2">
|
||
<Label htmlFor={`${id}-github-${key}`}>{label}</Label>
|
||
<GitHubListInput
|
||
id={`${id}-github-${key}`}
|
||
values={policy[key]}
|
||
onChange={(values) => set(key, values)}
|
||
/>
|
||
<p className="text-xs text-muted-foreground">{help}</p>
|
||
</div>
|
||
);
|
||
const [prompt, setPrompt] = useState<
|
||
(typeof GITHUB_REVIEW_EVENTS)[number] | "issue_opened"
|
||
>("opened");
|
||
const set = <K extends keyof GitHubReviewPolicy>(
|
||
key: K,
|
||
value: GitHubReviewPolicy[K],
|
||
) => onChange({ ...policy, [key]: value });
|
||
return (
|
||
<div className="space-y-8">
|
||
<section
|
||
className="space-y-3"
|
||
aria-labelledby={`${id}-github-instructions-heading`}
|
||
>
|
||
<h2
|
||
id={`${id}-github-instructions-heading`}
|
||
className="text-base font-semibold"
|
||
>
|
||
Instructions
|
||
</h2>
|
||
<MarkdownEditor
|
||
readOnly={readOnly}
|
||
ariaLabel="Agent instructions"
|
||
contentClassName="min-h-32"
|
||
value={policy.instructions}
|
||
placeholder="What should this agent do on GitHub?"
|
||
onChange={(value) => set("instructions", value)}
|
||
/>
|
||
<p className="text-xs text-muted-foreground">
|
||
Included in every GitHub task. Type / to select a skill for the agent
|
||
to use.
|
||
</p>
|
||
<GitHubSettingsDisclosure title="Event-specific instructions">
|
||
<div className="grid gap-3 pt-3">
|
||
<Label htmlFor={`${id}-github-prompt-event`} className="sr-only">
|
||
Event
|
||
</Label>
|
||
<select
|
||
id={`${id}-github-prompt-event`}
|
||
className={githubSelectClass}
|
||
value={prompt}
|
||
onChange={(e) => setPrompt(e.target.value as typeof prompt)}
|
||
>
|
||
{GITHUB_REVIEW_EVENTS.map((event) => (
|
||
<option key={event} value={event}>
|
||
{eventLabels[event]}
|
||
</option>
|
||
))}
|
||
<option value="issue_opened">New issue</option>
|
||
</select>
|
||
<MarkdownEditor
|
||
key={prompt}
|
||
readOnly={readOnly}
|
||
ariaLabel={`${prompt === "issue_opened" ? "New issue" : eventLabels[prompt]} instructions`}
|
||
contentClassName="min-h-32"
|
||
value={
|
||
prompt === "issue_opened"
|
||
? (policy.issueOpenedInstructions ?? "")
|
||
: policy.prompts[prompt]
|
||
}
|
||
onChange={(value) =>
|
||
prompt === "issue_opened"
|
||
? set("issueOpenedInstructions", value)
|
||
: set("prompts", {
|
||
...policy.prompts,
|
||
[prompt]: value,
|
||
})
|
||
}
|
||
/>
|
||
<p className="text-xs text-muted-foreground">
|
||
Added to the main instructions for this event. Type / to select a skill for the agent to use.
|
||
</p>
|
||
</div>
|
||
</GitHubSettingsDisclosure>
|
||
</section>
|
||
<section
|
||
className="space-y-3"
|
||
aria-labelledby={`${id}-github-triggers-heading`}
|
||
>
|
||
<h2
|
||
id={`${id}-github-triggers-heading`}
|
||
className="text-base font-semibold"
|
||
>
|
||
When to run
|
||
</h2>
|
||
<div className="flex items-start gap-3 py-2">
|
||
<AtSign className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
|
||
<div className="space-y-1">
|
||
<p className="text-sm font-medium">When mentioned</p>
|
||
<p className="text-xs text-muted-foreground">
|
||
Authorized people can always @mention this bot.{" "}
|
||
{accessHref && (
|
||
<Link className="underline underline-offset-4" to={accessHref}>
|
||
Manage people in Access
|
||
</Link>
|
||
)}
|
||
</p>
|
||
</div>
|
||
</div>
|
||
<GitHubToggle
|
||
label="Run automatically"
|
||
description="Start work without a mention when an allowed person creates an issue or updates a pull request."
|
||
checked={policy.invocation !== "mentions_only"}
|
||
onChange={(enabled) =>
|
||
set("invocation", enabled ? (rememberedAutomaticMode ?? automaticMode.current) : "mentions_only")
|
||
}
|
||
/>
|
||
{policy.invocation !== "mentions_only" && (
|
||
<div className="space-y-4">
|
||
<div
|
||
className="grid gap-x-6 gap-y-3 sm:grid-cols-2"
|
||
aria-label="Automatic events"
|
||
>
|
||
{GITHUB_REVIEW_EVENTS.slice(0, 4).map((event) => (
|
||
<Label
|
||
key={event}
|
||
className="flex cursor-pointer items-center gap-3 text-sm font-normal"
|
||
>
|
||
<Checkbox
|
||
checked={policy.events.includes(event)}
|
||
onCheckedChange={(enabled) =>
|
||
set(
|
||
"events",
|
||
enabled === true
|
||
? [...new Set([...policy.events, event])]
|
||
: policy.events.filter((value) => value !== event),
|
||
)
|
||
}
|
||
/>
|
||
{eventLabels[event]}
|
||
</Label>
|
||
))}
|
||
<Label className="flex cursor-pointer items-center gap-3 text-sm font-normal">
|
||
<Checkbox
|
||
checked={policy.issueOpened === true}
|
||
onCheckedChange={(enabled) =>
|
||
set("issueOpened", enabled === true)
|
||
}
|
||
/>
|
||
New issues
|
||
</Label>
|
||
</div>
|
||
<p className="text-xs text-muted-foreground">
|
||
Runs for authorized authors in Access. Use the author filters below to limit whose issues and PRs start work.
|
||
</p>
|
||
<GitHubSettingsDisclosure title="Automatic review filters">
|
||
<div>
|
||
<GitHubToggle
|
||
label="Include draft PRs"
|
||
checked={policy.reviewDrafts}
|
||
onChange={(value) => set("reviewDrafts", value)}
|
||
/>
|
||
<GitHubToggle
|
||
label="Include bot authors"
|
||
description="The account also needs a sponsor and external-contributor automatic runs enabled in Access."
|
||
checked={policy.reviewBotAuthors}
|
||
onChange={(value) => set("reviewBotAuthors", value)}
|
||
/>
|
||
</div>
|
||
<GitHubSettingsDisclosure title="Authors">
|
||
<div className="grid gap-4 sm:grid-cols-2">
|
||
{filterField(
|
||
"includeAuthors",
|
||
"Included authors",
|
||
"Leave empty for all authorized authors. One username or glob per line.",
|
||
)}
|
||
{filterField(
|
||
"excludeAuthors",
|
||
"Excluded authors",
|
||
"One username or glob per line.",
|
||
)}
|
||
</div>
|
||
</GitHubSettingsDisclosure>
|
||
<GitHubSettingsDisclosure title="Branches">
|
||
<div className="grid gap-4 sm:grid-cols-2">
|
||
{filterField(
|
||
"targetBranches",
|
||
"Target branches",
|
||
"Leave empty for all branches. Supports * and **.",
|
||
)}
|
||
{filterField(
|
||
"excludedBranches",
|
||
"Excluded branches",
|
||
"Supports * and **.",
|
||
)}
|
||
</div>
|
||
</GitHubSettingsDisclosure>
|
||
<GitHubSettingsDisclosure title="Labels">
|
||
<div className="grid gap-4 sm:grid-cols-2">
|
||
{filterField(
|
||
"requiredLabels",
|
||
"Required labels",
|
||
"All listed labels must be present.",
|
||
)}
|
||
{filterField(
|
||
"excludedLabels",
|
||
"Excluded labels",
|
||
"Any listed label prevents automatic review.",
|
||
)}
|
||
</div>
|
||
</GitHubSettingsDisclosure>
|
||
<p className="text-xs text-muted-foreground">
|
||
Reviews requested by @mention bypass these scheduling filters.
|
||
Repository access and ignored files still apply.
|
||
</p>
|
||
</GitHubSettingsDisclosure>
|
||
</div>
|
||
)}
|
||
</section>
|
||
<section
|
||
className="space-y-3"
|
||
aria-labelledby={`${id}-github-results-heading`}
|
||
>
|
||
<h2
|
||
id={`${id}-github-results-heading`}
|
||
className="text-base font-semibold"
|
||
>
|
||
Review results
|
||
</h2>
|
||
<div className="grid gap-x-8 sm:grid-cols-2">
|
||
<GitHubToggle
|
||
label="Post a review summary"
|
||
checked={policy.publishSummary}
|
||
onChange={(value) => set("publishSummary", value)}
|
||
/>
|
||
<GitHubToggle
|
||
label="Post inline findings"
|
||
checked={policy.publishInline}
|
||
onChange={(value) => set("publishInline", value)}
|
||
/>
|
||
</div>
|
||
<GitHubPassingScore value={policy.ratingThreshold} text={scoreText} onTextChange={onScoreTextChange}
|
||
onChange={(value) => set("ratingThreshold", value)} onValidityChange={onValidityChange} />
|
||
</section>
|
||
<div className="divide-y divide-border">
|
||
<GitHubSettingsDisclosure title="Ignored files">
|
||
{filterField(
|
||
"ignoredPaths",
|
||
"File patterns",
|
||
"Excluded from all reviews, including @mentions. One pattern per line; supports * and **.",
|
||
)}
|
||
</GitHubSettingsDisclosure>
|
||
<GitHubSettingsDisclosure title="Inline comment options">
|
||
<div className="grid gap-4 sm:grid-cols-2">
|
||
<div className="space-y-2">
|
||
<Label htmlFor={`${id}-github-categories`}>
|
||
Finding categories
|
||
</Label>
|
||
<GitHubListInput
|
||
id={`${id}-github-categories`}
|
||
values={policy.findingCategories}
|
||
separator=","
|
||
onChange={(values) => set("findingCategories", values)}
|
||
/>
|
||
</div>
|
||
<div className="space-y-2">
|
||
<Label htmlFor={`${id}-github-severity`}>
|
||
Minimum inline severity
|
||
</Label>
|
||
<select
|
||
id={`${id}-github-severity`}
|
||
className={githubSelectClass}
|
||
value={policy.minimumCommentSeverity}
|
||
onChange={(e) =>
|
||
set(
|
||
"minimumCommentSeverity",
|
||
e.target
|
||
.value as GitHubReviewPolicy["minimumCommentSeverity"],
|
||
)
|
||
}
|
||
>
|
||
<option value="info">Info</option>
|
||
<option value="warning">Warning</option>
|
||
<option value="error">Error</option>
|
||
</select>
|
||
<p className="text-xs text-muted-foreground">
|
||
Hidden findings still count in the assessment.
|
||
</p>
|
||
</div>
|
||
</div>
|
||
</GitHubSettingsDisclosure>
|
||
<GitHubSettingsDisclosure title="Approvals and change requests">
|
||
<p className="text-xs text-muted-foreground">
|
||
Optional formal decisions on GitHub. Scores, comments, and checks
|
||
still work when these are off.
|
||
</p>
|
||
<div>
|
||
<GitHubToggle
|
||
label="Allow approvals"
|
||
help="Lets the agent submit an Approve review on GitHub after a complete assessment. The agent must explicitly choose it; a 5/5 score or passing check does not approve the PR. Off still allows scores, comments, and checks."
|
||
checked={policy.allowApprove}
|
||
onChange={(value) => set("allowApprove", value)}
|
||
/>
|
||
<GitHubToggle
|
||
label="Allow request changes"
|
||
help="Lets the agent submit a Request changes review on GitHub after a complete assessment. This is a formal review decision and may prevent merging under your repository rules. Off still allows findings, comments, and a failing check."
|
||
checked={policy.allowRequestChanges}
|
||
onChange={(value) => set("allowRequestChanges", value)}
|
||
/>
|
||
</div>
|
||
</GitHubSettingsDisclosure>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function GitHubAccessEditor({
|
||
endpointId,
|
||
companyId,
|
||
configuration,
|
||
onChange,
|
||
}: {
|
||
endpointId: string;
|
||
companyId: string;
|
||
configuration: GitHubChatConfiguration;
|
||
onChange: (configuration: GitHubChatConfiguration) => void;
|
||
}) {
|
||
const company = useOptionalCompany()?.companies.find((item) => item.id === companyId);
|
||
const accountLink = useRef<HTMLAnchorElement>(null);
|
||
const [linkCopied, setLinkCopied] = useState(false);
|
||
const [dialog, setDialog] = useState<"member" | "guest" | null>(null);
|
||
const members = useQuery({
|
||
queryKey: ["github-members", companyId],
|
||
queryFn: () => accessApi.listMembers(companyId),
|
||
});
|
||
const links = useQuery({
|
||
queryKey: ["github-linked-members", endpointId],
|
||
queryFn: () => chatEndpointsApi.listPrincipals(endpointId),
|
||
});
|
||
const [login, setLogin] = useState("");
|
||
const [sponsor, setSponsor] = useState(configuration.responsibleUserId);
|
||
const [candidate, setCandidate] = useState<{
|
||
githubUserId: string;
|
||
login: string;
|
||
} | null>(null);
|
||
const [error, setError] = useState("");
|
||
const [lookupError, setLookupError] = useState("");
|
||
const [busy, setBusy] = useState(false);
|
||
const activeMembers = (members.data?.members ?? []).filter(
|
||
(member) =>
|
||
member.status === "active" && member.membershipRole !== "viewer",
|
||
);
|
||
const linkedAccounts = (links.data ?? []).filter(
|
||
(link) => link.status === "linked",
|
||
);
|
||
const responsible = activeMembers.find(
|
||
(member) => member.principalId === configuration.responsibleUserId,
|
||
);
|
||
const memberName = (userId: string) =>
|
||
activeMembers.find((member) => member.principalId === userId)?.user?.name ??
|
||
userId;
|
||
const automatic = configuration.defaults.invocation !== "mentions_only";
|
||
const guestsAutomatic =
|
||
configuration.defaults.invocation === "allowed_authors";
|
||
const guests = configuration.people.filter(
|
||
(person) => person.kind === "guest",
|
||
);
|
||
// Preserve configured members whose identity link was revoked; show why they cannot run.
|
||
const memberRows = [
|
||
...configuration.people.filter((person) => person.kind === "member"),
|
||
...linkedAccounts
|
||
.filter(
|
||
(link) =>
|
||
link.githubUserId &&
|
||
link.paperclipUserId &&
|
||
!configuration.people.some(
|
||
(person) => person.githubUserId === link.githubUserId,
|
||
),
|
||
)
|
||
.map((link): GitHubAllowedPerson => ({
|
||
kind: "member",
|
||
userId: link.paperclipUserId!,
|
||
githubUserId: link.githubUserId!,
|
||
login: link.githubLogin ?? link.externalLabel,
|
||
})),
|
||
];
|
||
const updatePerson = (person: GitHubAllowedPerson) =>
|
||
onChange({
|
||
...configuration,
|
||
people: configuration.people.some(
|
||
(p) => p.githubUserId === person.githubUserId,
|
||
)
|
||
? configuration.people.map((p) =>
|
||
p.githubUserId === person.githubUserId ? person : p,
|
||
)
|
||
: [...configuration.people, person],
|
||
});
|
||
const removePerson = (person: GitHubAllowedPerson) =>
|
||
onChange({
|
||
...configuration,
|
||
people: configuration.people.filter(
|
||
(p) => p.githubUserId !== person.githubUserId,
|
||
),
|
||
});
|
||
const unlink = async (principalId: string) => {
|
||
setBusy(true);
|
||
setError("");
|
||
try {
|
||
await chatEndpointsApi.revokeLink(endpointId, principalId);
|
||
await links.refetch();
|
||
} catch (e) {
|
||
setError(
|
||
e instanceof Error ? e.message : "Could not unlink this account.",
|
||
);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
};
|
||
const peopleRows = (people: GitHubAllowedPerson[]) => (
|
||
<div className="divide-y divide-border">
|
||
{people.map((person) => {
|
||
const identity = linkedAccounts.find(
|
||
(link) => link.githubUserId === person.githubUserId,
|
||
);
|
||
const linked = person.kind === "guest" || Boolean(identity);
|
||
const explicit = configuration.people.some(
|
||
(p) => p.githubUserId === person.githubUserId,
|
||
);
|
||
const mentions =
|
||
person.kind === "guest" ||
|
||
configuration.memberAccess === "all_linked" ||
|
||
explicit;
|
||
const removable = explicit && (person.kind === "guest" || configuration.memberAccess === "selected");
|
||
return (
|
||
<div
|
||
key={person.githubUserId}
|
||
className="flex flex-wrap items-center gap-x-4 gap-y-3 py-4"
|
||
>
|
||
<div className="min-w-0 flex-1 basis-32">
|
||
<p className="break-words text-sm font-medium">@{person.login}</p>
|
||
<p className="text-xs text-muted-foreground">
|
||
{person.kind === "guest"
|
||
? `Sponsored by ${memberName(person.sponsorUserId)}`
|
||
: (identity?.paperclipUserLabel ?? "Company member")}
|
||
</p>
|
||
{!linked && (
|
||
<p className="mt-1 text-xs text-destructive">
|
||
GitHub account needs linking.
|
||
</p>
|
||
)}
|
||
</div>
|
||
<div className="flex items-center gap-5">
|
||
<div className="flex flex-col items-center gap-2">
|
||
<span className="text-xs text-muted-foreground">Mentions</span>
|
||
{person.kind === "guest" ||
|
||
configuration.memberAccess === "all_linked" ? (
|
||
<span
|
||
className="flex h-5 items-center gap-1 text-xs"
|
||
aria-label={`Mentions ${linked ? "allowed" : "unavailable"} for @${person.login}`}
|
||
>
|
||
{linked && (
|
||
<Check className="size-3.5 text-muted-foreground" />
|
||
)}
|
||
{linked ? "Allowed" : "Unlinked"}
|
||
</span>
|
||
) : (
|
||
<ToggleSwitch
|
||
aria-label={`Allow mentions from @${person.login}`}
|
||
checked={mentions}
|
||
disabled={!linked}
|
||
onCheckedChange={(enabled) =>
|
||
enabled ? updatePerson(person) : removePerson(person)
|
||
}
|
||
/>
|
||
)}
|
||
</div>
|
||
{(identity || removable) && <DropdownMenu>
|
||
<DropdownMenuTrigger asChild>
|
||
<Button
|
||
size="icon"
|
||
variant="ghost"
|
||
aria-label={`Manage @${person.login}`}
|
||
>
|
||
<MoreHorizontal className="size-4" />
|
||
</Button>
|
||
</DropdownMenuTrigger>
|
||
<DropdownMenuContent align="end">
|
||
{removable && (
|
||
<DropdownMenuItem onClick={() => removePerson(person)}>
|
||
Remove access
|
||
</DropdownMenuItem>
|
||
)}
|
||
{identity && (
|
||
<DropdownMenuItem
|
||
disabled={busy}
|
||
onClick={() => void unlink(identity.principalId)}
|
||
>
|
||
Unlink GitHub account
|
||
</DropdownMenuItem>
|
||
)}
|
||
</DropdownMenuContent>
|
||
</DropdownMenu>}
|
||
</div>
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
);
|
||
return (
|
||
<section className="space-y-6" aria-label="People">
|
||
<div className="space-y-1">
|
||
<h2 className="text-base font-semibold">People</h2>
|
||
<p className="text-sm text-muted-foreground">
|
||
Choose who can mention this bot and whose activity can start work
|
||
automatically.
|
||
</p>
|
||
</div>
|
||
<section className="space-y-2" aria-label="Company members">
|
||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||
<h3 className="text-sm font-semibold">Company members</h3>
|
||
<Button
|
||
variant="outline"
|
||
size="sm"
|
||
onClick={() => {
|
||
setDialog("member");
|
||
setLinkCopied(false);
|
||
setError("");
|
||
}}
|
||
>
|
||
<Plus className="size-4" />
|
||
Link a member
|
||
</Button>
|
||
</div>
|
||
<GitHubToggle
|
||
label="Allow mentions from all linked members"
|
||
description={
|
||
configuration.memberAccess === "all_linked"
|
||
? `Includes members from ${company?.name ?? "this company"} who link their GitHub account later.`
|
||
: "Only members you enable below can mention this bot."
|
||
}
|
||
checked={configuration.memberAccess === "all_linked"}
|
||
onChange={(enabled) =>
|
||
onChange({
|
||
...configuration,
|
||
memberAccess: enabled ? "all_linked" : "selected",
|
||
})
|
||
}
|
||
/>
|
||
{peopleRows(memberRows)}
|
||
{links.isPending && (
|
||
<p role="status" className="py-4 text-sm text-muted-foreground">
|
||
Loading linked accounts…
|
||
</p>
|
||
)}
|
||
{!links.isPending && !links.isError && memberRows.length === 0 && (
|
||
<p className="py-4 text-sm text-muted-foreground">
|
||
No members linked yet. Link an account to get started.
|
||
</p>
|
||
)}
|
||
<p className="text-xs text-muted-foreground">
|
||
{automatic ? (
|
||
<>
|
||
Automatic runs use the events and author filters in{" "}
|
||
<Link
|
||
className="underline underline-offset-4"
|
||
to={`/apps/chat/${endpointId}/settings`}
|
||
>
|
||
Settings
|
||
</Link>
|
||
.
|
||
</>
|
||
) : (
|
||
<>
|
||
Automatic runs are off in{" "}
|
||
<Link
|
||
className="underline underline-offset-4"
|
||
to={`/apps/chat/${endpointId}/settings`}
|
||
>
|
||
Settings
|
||
</Link>
|
||
. Authorized @mentions still work.
|
||
</>
|
||
)}
|
||
</p>
|
||
</section>
|
||
<section
|
||
className="space-y-2 border-t border-border pt-6"
|
||
aria-label="External contributors"
|
||
>
|
||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||
<h3 className="text-sm font-semibold">External contributors</h3>
|
||
<Button
|
||
variant="outline"
|
||
size="sm"
|
||
onClick={() => {
|
||
setDialog("guest");
|
||
setLookupError("");
|
||
}}
|
||
>
|
||
<Plus className="size-4" />
|
||
Add external contributor
|
||
</Button>
|
||
</div>
|
||
<p className="text-xs text-muted-foreground">
|
||
Allow specific GitHub users with a member as their sponsor. They
|
||
receive restricted access, without company membership or the sponsor’s
|
||
personal credentials.
|
||
</p>
|
||
{peopleRows(guests)}
|
||
{guests.length > 0 && (
|
||
<GitHubToggle
|
||
label="Allow automatic runs for external contributors"
|
||
description={
|
||
automatic
|
||
? "Authorized contributors can trigger the events and author filters configured in Settings."
|
||
: "Turn on automatic runs in Settings first. Mentions remain available."
|
||
}
|
||
checked={guestsAutomatic}
|
||
disabled={!automatic}
|
||
onChange={(enabled) =>
|
||
onChange({
|
||
...configuration,
|
||
defaults: {
|
||
...configuration.defaults,
|
||
invocation: enabled ? "allowed_authors" : "linked_authors",
|
||
},
|
||
})
|
||
}
|
||
/>
|
||
)}
|
||
</section>
|
||
<GitHubSettingsDisclosure title="Automatic task responsibility">
|
||
<div className="space-y-2">
|
||
{activeMembers.length === 1 && responsible ? (
|
||
<p className="text-sm">
|
||
Responsible member: {memberName(configuration.responsibleUserId)}
|
||
</p>
|
||
) : (
|
||
<>
|
||
<Label htmlFor="github-responsible">Responsible member</Label>
|
||
<select
|
||
id="github-responsible"
|
||
className={githubSelectClass}
|
||
value={configuration.responsibleUserId}
|
||
onChange={(e) =>
|
||
onChange({
|
||
...configuration,
|
||
responsibleUserId: e.target.value,
|
||
})
|
||
}
|
||
>
|
||
{!responsible && (
|
||
<option value={configuration.responsibleUserId}>
|
||
{configuration.responsibleUserId || "Select a member"}
|
||
</option>
|
||
)}
|
||
{activeMembers.map((member) => (
|
||
<option key={member.principalId} value={member.principalId}>
|
||
{member.user?.name ??
|
||
member.user?.email ??
|
||
member.principalId}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</>
|
||
)}
|
||
<p className="text-xs text-muted-foreground">
|
||
The member accountable for automatically created Paperclip tasks.
|
||
GitHub authors remain recorded separately. This grants no access to
|
||
the member’s personal credentials.
|
||
</p>
|
||
</div>
|
||
</GitHubSettingsDisclosure>
|
||
{error && (
|
||
<p role="alert" className="text-sm text-destructive">
|
||
{error}
|
||
</p>
|
||
)}
|
||
{(members.error || links.error) && (
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<p role="alert" className="text-sm text-destructive">
|
||
Could not load members or linked accounts.
|
||
</p>
|
||
<Button
|
||
variant="link"
|
||
size="sm"
|
||
onClick={() => {
|
||
void members.refetch();
|
||
void links.refetch();
|
||
}}
|
||
>
|
||
Try again
|
||
</Button>
|
||
</div>
|
||
)}
|
||
<Dialog
|
||
open={dialog !== null}
|
||
onOpenChange={(open) => {
|
||
if (!open) setDialog(null);
|
||
}}
|
||
>
|
||
<DialogContent>
|
||
<DialogHeader>
|
||
<DialogTitle>
|
||
{dialog === "member"
|
||
? "Link a company member"
|
||
: "Add external contributor"}
|
||
</DialogTitle>
|
||
<DialogDescription>
|
||
{dialog === "member"
|
||
? "Each member confirms their own GitHub identity. Share this link with an existing company member, or link your own account."
|
||
: "Allow a GitHub user to mention this bot. A company member must sponsor their restricted access."}
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
{dialog === "member" ? (
|
||
<>
|
||
<Button
|
||
variant="outline"
|
||
aria-label="Copy account linking URL"
|
||
onClick={() => {
|
||
if (accountLink.current)
|
||
void copyTextToClipboard(accountLink.current.href).then(
|
||
() => setLinkCopied(true),
|
||
() =>
|
||
setError(
|
||
"Could not copy the link. Open account linking and copy the address.",
|
||
),
|
||
);
|
||
}}
|
||
>
|
||
<Copy className="size-4" />
|
||
{linkCopied ? "Copied" : "Copy invitation link"}
|
||
</Button>
|
||
<Link
|
||
ref={accountLink}
|
||
to={`/apps/chat/connect?provider=github&resume=${endpointId}&stage=identity`}
|
||
className="text-sm underline underline-offset-4"
|
||
>
|
||
Link your account
|
||
</Link>
|
||
{error && (
|
||
<p role="alert" className="text-sm text-destructive">
|
||
{error}
|
||
</p>
|
||
)}
|
||
</>
|
||
) : (
|
||
<>
|
||
<div className="space-y-2">
|
||
<Label htmlFor="github-guest-login">GitHub username</Label>
|
||
<div className="flex gap-2">
|
||
<Input
|
||
id="github-guest-login"
|
||
value={login}
|
||
placeholder="octocat"
|
||
disabled={busy}
|
||
onChange={(e) => {
|
||
setLogin(e.target.value);
|
||
setCandidate(null);
|
||
setLookupError("");
|
||
}}
|
||
/>
|
||
<Button
|
||
variant="outline"
|
||
disabled={busy || !login.trim()}
|
||
onClick={async () => {
|
||
setBusy(true);
|
||
setLookupError("");
|
||
setCandidate(null);
|
||
try {
|
||
setCandidate(
|
||
await githubChatApi.lookup(endpointId, login),
|
||
);
|
||
} catch (e) {
|
||
setLookupError(
|
||
e instanceof Error ? e.message : "Lookup failed",
|
||
);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}}
|
||
>
|
||
{busy ? "Looking up…" : "Look up"}
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
<div className="space-y-2">
|
||
<Label htmlFor="github-guest-sponsor">Sponsor</Label>
|
||
<select
|
||
id="github-guest-sponsor"
|
||
className={githubSelectClass}
|
||
value={sponsor}
|
||
onChange={(e) => setSponsor(e.target.value)}
|
||
>
|
||
{!activeMembers.some(
|
||
(member) => member.principalId === sponsor,
|
||
) && <option value={sponsor}>Select a member</option>}
|
||
{activeMembers.map((member) => (
|
||
<option key={member.principalId} value={member.principalId}>
|
||
{member.user?.name ?? member.principalId}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
{candidate && (
|
||
<p role="status" className="text-sm">
|
||
{configuration.people.some(
|
||
(p) => p.githubUserId === candidate.githubUserId,
|
||
) ||
|
||
linkedAccounts.some(
|
||
(link) => link.githubUserId === candidate.githubUserId,
|
||
)
|
||
? `@${candidate.login} is already listed in People.`
|
||
: `Found @${candidate.login}. They will be able to mention the bot after you save.`}
|
||
</p>
|
||
)}
|
||
{lookupError && (
|
||
<p role="alert" className="text-sm text-destructive">
|
||
{lookupError}
|
||
</p>
|
||
)}
|
||
<DialogFooter className="flex-row justify-between sm:justify-between">
|
||
<Button variant="ghost" onClick={() => setDialog(null)}>
|
||
Cancel
|
||
</Button>
|
||
<Button
|
||
disabled={
|
||
!candidate ||
|
||
!activeMembers.some(
|
||
(member) => member.principalId === sponsor,
|
||
) ||
|
||
configuration.people.some(
|
||
(p) => p.githubUserId === candidate.githubUserId,
|
||
) ||
|
||
linkedAccounts.some(
|
||
(link) => link.githubUserId === candidate.githubUserId,
|
||
)
|
||
}
|
||
onClick={() => {
|
||
if (candidate) {
|
||
updatePerson({
|
||
...candidate,
|
||
kind: "guest",
|
||
sponsorUserId: sponsor,
|
||
permissionProfile: "restricted",
|
||
});
|
||
setDialog(null);
|
||
setCandidate(null);
|
||
setLogin("");
|
||
}
|
||
}}
|
||
>
|
||
Add contributor
|
||
</Button>
|
||
</DialogFooter>
|
||
</>
|
||
)}
|
||
</DialogContent>
|
||
</Dialog>
|
||
</section>
|
||
);
|
||
}
|