feat(auth): separate source control write permissions (#9787)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-10-06 20:30:11 -07:00
1 parent 28ce9d1c17
commit 2eda8ac6a3
59 files changed
+3628 -315

No files matched your search

@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
/**
* The comment half of the floating composer: a remark on the pull request itself, optionally
* the one that closes or reopens it. The popover around it belongs to PullRequestComposer.
@@ -6,7 +7,6 @@ import type { EnvironmentId, PullRequestDetailView, PullRequestRef } from "@t3to
import { SendIcon } from "lucide-react";
import { useState, type RefObject } from "react";
import { useAtomCommand } from "~/state/use-atom-command";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { Button } from "../ui/button";
@@ -38,7 +38,9 @@ export function PullRequestCommentForm({
}) {
const [body, setBody] = useState("");
const [submitting, setSubmitting] = useState<"comment" | "close" | "reopen" | null>(null);
const postComment = useAtomCommand(pullRequestEnvironment.comment, { reportFailure: false });
const postComment = useAtomCommand(pullRequestEnvironment.comment, {
reportFailure: false,
});
const followUpAction =
detail.state === "open" &&
detail.capabilities.actions.includes("close") &&
@@ -24,6 +24,11 @@ const { newThread, prepareThread, refresh, Wrapper, Trigger } = vi.hoisted(() =>
</>
),
}));
vi.mock("~/state/session", async (original) => ({
...(await original<typeof import("~/state/session")>()),
useEnvironmentScope: () => true,
readEnvironmentScope: () => true,
}));
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));
vi.mock("~/state/server", () => ({ primaryServerKeybindingsAtom: {} }));
vi.mock("~/state/entities", () => ({ useProjects: () => [], useServerConfigs: () => new Map() }));
@@ -39,7 +44,7 @@ vi.mock("~/hooks/useSettings", () => ({
vi.mock("~/hooks/useLiveRefresh", () => ({ useLiveRefresh: () => {} }));
vi.mock("~/hooks/useHandleNewThread", () => ({ useNewThreadHandler: () => newThread }));
vi.mock("~/lib/sourceControlActions", () => ({
usePreparePullRequestThreadAction: () => ({ run: prepareThread }),
usePreparePullRequestThreadAction: () => ({ run: prepareThread, isAllowed: true, error: null }),
}));
vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
vi.mock("~/state/pullRequests", async (importOriginal) => ({
@@ -5,6 +5,8 @@ import { RefreshIcon } from "~/components/ui/refresh-icon";
import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
type EnvironmentId,
type PullRequestAction,
type PullRequestMergeMethod,
@@ -70,6 +72,7 @@ import type { ReviewCommentContext } from "~/reviewCommentContext";
import { useProjects, useServerConfigs } from "~/state/entities";
import { useEnvironments } from "~/state/environments";
import { useEnvironmentQuery } from "~/state/query";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useLiveRefresh } from "~/hooks/useLiveRefresh";
import {
pullRequestEnvironment,
@@ -578,6 +581,7 @@ export function PullRequestDetailPanel({
// Which handoff is preparing, keyed so a per-finding button can say "Preparing..." on itself
// alone. One at a time whatever the key: they all check the same pull request out.
const [handoff, setHandoff] = useState<string | null>(null);
const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
const detailQuery = useEnvironmentQuery(
pullRequestEnvironment.detail({ environmentId, input: reference }),
);
@@ -690,6 +694,25 @@ export function PullRequestDetailPanel({
? null
: {
...coreDetail,
capabilities: canWriteSourceControl
? coreDetail.capabilities
: {
...coreDetail.capabilities,
reactions: false,
edit: { changeRequest: false, comment: false },
},
viewerPermissions: canWriteSourceControl
? coreDetail.viewerPermissions
: {
...coreDetail.viewerPermissions,
actions: [],
comment: false,
resolve: false,
verdicts: [],
requestReviewers: false,
updateMethods: [],
labels: false,
},
author: activity?.author ?? coreDetail.author,
reviewers: activity?.reviewers ?? coreDetail.reviewers,
comments: activity?.comments ?? [],
@@ -699,7 +722,7 @@ export function PullRequestDetailPanel({
commits: activity?.commits ?? [],
reactions: activity?.reactions ?? [],
},
[activity, coreDetail],
[activity, canWriteSourceControl, coreDetail],
);
const handoffSummary = detail ?? sharedSummary;
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
@@ -857,8 +880,12 @@ export function PullRequestDetailPanel({
appliedForcedToken.current = forcedRefreshToken;
void refreshFromHost();
}, [forcedRefreshToken, refreshFromHost]);
const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
const postComment = useAtomCommand(pullRequestEnvironment.comment, { reportFailure: false });
const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
reportFailure: false,
});
const postComment = useAtomCommand(pullRequestEnvironment.comment, {
reportFailure: false,
});
// Which action is in flight, not merely that one is: every control here is disabled while any
// of them runs, but only the button that was pressed may say what it is doing.
const [pendingAction, setPendingAction] = useState<PullRequestAction | null>(null);
@@ -912,6 +939,7 @@ export function PullRequestDetailPanel({
const actingEnvironmentId = acting?.environmentId ?? environmentId;
const checkoutRoot =
acting?.workspaceRoot ?? detail?.workspaceRoot ?? project?.workspaceRoot ?? null;
const canOperateThread = useEnvironmentScope(actingEnvironmentId, AuthOrchestrationOperateScope);
const prepareThread = usePreparePullRequestThreadAction({
environmentId: actingEnvironmentId,
cwd: checkoutRoot,
@@ -973,13 +1001,13 @@ export function PullRequestDetailPanel({
method?: PullRequestMergeMethod,
updateMethod?: PullRequestUpdateMethod,
) => {
if (pendingAction !== null) return false;
if (!canWriteSourceControl || pendingAction !== null) return false;
setPendingAction(action);
return finishAction(action, method, updateMethod);
};
const performCommentAction = async (body: string, action: "close" | "reopen") => {
if (pendingAction !== null) return { commentPosted: false };
if (!canWriteSourceControl || pendingAction !== null) return { commentPosted: false };
setPendingAction(action);
const commentResult = await postComment({
environmentId,
@@ -999,7 +1027,7 @@ export function PullRequestDetailPanel({
const saveTitle = async (next: string) => {
const title = next.trim();
if (detail === null || titleSaving) return;
if (!canWriteSourceControl || detail === null || titleSaving) return;
if (title.length === 0 || title === detail.title) {
setTitleScope(null);
return;
@@ -1030,6 +1058,8 @@ export function PullRequestDetailPanel({
};
const attachTarget = composerDraftTarget ?? null;
const canPrepareWorktree = prepareThread.isAllowed && canOperateThread;
const canFixFindings = attachTarget !== null || canPrepareWorktree;
const handoffLabels = pullRequestHandoffLabels(attachTarget !== null);
const writeTaskToComposer = (target: ScopedThreadRef | DraftId, task: ThreadTask) => {
@@ -1158,6 +1188,18 @@ export function PullRequestDetailPanel({
return;
}
if (checkoutRoot === null) return;
if (
!prepareThread.isAllowed ||
!readEnvironmentScope(actingEnvironmentId, AuthSourceControlWriteScope)
) {
return;
}
if (
mode === "worktree" &&
!readEnvironmentScope(actingEnvironmentId, AuthOrchestrationOperateScope)
) {
return;
}
setHandoff(kind);
// The menu closes on the press and takes its "Preparing..." label with it, so this is the
// only thing answering for the checkout. It carries no timeout of its own: a loading toast
@@ -1528,7 +1570,7 @@ export function PullRequestDetailPanel({
<TooltipPopup>Check out this pull request</TooltipPopup>
</Tooltip>
<MenuPopup align="end" side="bottom">
<MenuItem onClick={() => startCheckout("worktree")}>
<MenuItem disabled={!canPrepareWorktree} onClick={() => startCheckout("worktree")}>
<GitBranchIcon className="mt-1 size-3.5 shrink-0 self-start" />
<span className="flex min-w-0 flex-col">
<span>In a separate worktree</span>
@@ -1537,7 +1579,7 @@ export function PullRequestDetailPanel({
</span>
</span>
</MenuItem>
<MenuItem onClick={() => startCheckout("local")}>
<MenuItem disabled={!prepareThread.isAllowed} onClick={() => startCheckout("local")}>
<FolderGit2Icon className="mt-1 size-3.5 shrink-0 self-start" />
<span className="flex min-w-0 flex-col">
<span>In this repository</span>
@@ -2016,7 +2058,10 @@ export function PullRequestDetailPanel({
</span>
</span>
</MenuItem>
<MenuItem disabled={handoff !== null} onClick={startFixFindings}>
<MenuItem
disabled={handoff !== null || !canFixFindings}
onClick={startFixFindings}
>
<HammerIcon className="size-3.5" />
{handoff === "findings" ? "Preparing..." : handoffLabels.fixFindings}
</MenuItem>
@@ -2383,7 +2428,9 @@ export function PullRequestDetailPanel({
<Button
size="xs"
variant="outline"
disabled={titleSaving || titleDraft.trim().length === 0}
disabled={
!canWriteSourceControl || titleSaving || titleDraft.trim().length === 0
}
onClick={() => void saveTitle(titleDraft)}
>
{titleSaving ? "Saving..." : "Save"}
@@ -2706,7 +2753,7 @@ export function PullRequestDetailPanel({
pendingFinding={handoff}
fixFindingLabel={handoffLabels.fixFinding}
fixCheckLabel={handoffLabels.fixCheck}
onFixFinding={startFixFinding}
{...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
onRefresh={refreshDetail}
onRefreshChecks={refreshFromHost}
/>
@@ -2746,7 +2793,7 @@ export function PullRequestDetailPanel({
onSelectedCommitChange={selectCodeCommit}
pendingFinding={handoff}
fixFindingLabel={handoffLabels.fixFinding}
onFixFinding={startFixFinding}
{...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
onRefresh={refreshDetail}
refreshToken={codeRefreshToken}
/>
@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
/**
* Putting a label on, and taking one off, from the row that says which it already wears.
*
@@ -11,7 +12,6 @@ import { useMemo, useState } from "react";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useEnvironmentQuery } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { toastManager } from "../ui/toast";
@@ -48,7 +48,9 @@ export function PullRequestLabelPicker({
const candidatesQuery = useEnvironmentQuery(
open ? pullRequestEnvironment.labelCandidates({ environmentId, input: reference }) : null,
);
const setLabels = useAtomCommand(pullRequestEnvironment.setLabels, { reportFailure: false });
const setLabels = useAtomCommand(pullRequestEnvironment.setLabels, {
reportFailure: false,
});
const candidates = useMemo(
() => (candidatesQuery.data?.candidates ?? []).filter((entry) => matches(entry, query)),
@@ -0,0 +1,148 @@
import { AuthSourceControlWriteScope, EnvironmentId } from "@t3tools/contracts";
import { act } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
const permissions = vi.hoisted(() => ({
allowed: new Set<string>(),
listeners: new Set<() => void>(),
}));
vi.mock("~/state/session", async () => {
const { useSyncExternalStore } = await import("react");
const canWrite = (environmentId: string, scope: string) =>
scope === AuthSourceControlWriteScope && permissions.allowed.has(environmentId);
return {
readEnvironmentScope: canWrite,
useEnvironmentScope: (environmentId: string, scope: string) =>
useSyncExternalStore(
(listener) => {
permissions.listeners.add(listener);
return () => permissions.listeners.delete(listener);
},
() => canWrite(environmentId, scope),
),
};
});
vi.mock("~/lib/utils", () => ({ cn: () => "" }));
vi.mock("../ui/button", () => ({ Button: "button" }));
vi.mock("../ui/textarea", () => ({ Textarea: "textarea" }));
vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
vi.mock("./PullRequestMarkdown", () => ({ PullRequestMarkdown: "article" }));
import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
const primary = EnvironmentId.make("primary");
const secondary = EnvironmentId.make("secondary");
let renderer: ReactTestRenderer | undefined;
const onSave = vi.fn<(next: string) => void>();
const onCancel = vi.fn<() => void>();
beforeEach(() => {
permissions.allowed.clear();
permissions.listeners.clear();
renderer = undefined;
onSave.mockReset();
onCancel.mockReset();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
});
afterEach(async () => {
await act(() => renderer?.unmount());
vi.unstubAllGlobals();
});
async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
await act(() => {
renderer = create(
<PullRequestMarkdownEditor
value={options?.value ?? "Original description"}
cwd="/repo"
environmentId={secondary}
label="Pull request description"
saving={false}
allowEmpty={options?.allowEmpty ?? false}
onSave={onSave}
onCancel={onCancel}
/>,
);
});
}
function saveHandler(): () => void {
return renderer!.root.findByProps({ children: "Save" }).props.onClick;
}
async function grant(allowed: boolean) {
await act(() => {
if (allowed) permissions.allowed.add(secondary);
else permissions.allowed.delete(secondary);
permissions.listeners.forEach((listener) => listener());
});
}
it("does not save a secondary environment's description using the primary grant", async () => {
permissions.allowed.add(primary);
await openEditor();
await act(() => saveHandler()());
expect(onSave).not.toHaveBeenCalled();
});
it("rejects a retained Save callback when the grant changes before React updates", async () => {
permissions.allowed.add(secondary);
await openEditor();
const save = saveHandler();
permissions.allowed.delete(secondary);
await act(() => save());
expect(onSave).not.toHaveBeenCalled();
});
it("keeps an edited draft through revocation and saves it after access returns without remounting", async () => {
permissions.allowed.add(secondary);
await openEditor();
await act(() => {
renderer!.root.findByType("textarea").props.onChange({
target: { value: "Keep these unsaved edits" },
});
});
await grant(false);
await act(() => saveHandler()());
expect(onSave).not.toHaveBeenCalled();
await grant(true);
await act(() => saveHandler()());
expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
});
it("saves with source-control permission alone", async () => {
permissions.allowed.add(secondary);
await openEditor();
await act(() => saveHandler()());
expect(onSave).toHaveBeenCalledExactlyOnceWith("Original description");
});
it("allows clearing a description only after a pending grant becomes available", async () => {
await openEditor({ value: "", allowEmpty: true });
await act(() => saveHandler()());
expect(onSave).not.toHaveBeenCalled();
await grant(true);
await act(() => saveHandler()());
expect(onSave).toHaveBeenCalledExactlyOnceWith("");
});
it("keeps cancelling a local edit available without a write grant", async () => {
await openEditor();
await act(() => renderer!.root.findByProps({ children: "Cancel" }).props.onClick());
expect(onCancel).toHaveBeenCalledOnce();
expect(onSave).not.toHaveBeenCalled();
});
@@ -1,7 +1,12 @@
import { useState } from "react";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import {
AuthSourceControlWriteScope,
type EnvironmentId,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { cn } from "~/lib/utils";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { Button } from "../ui/button";
import { Textarea } from "../ui/textarea";
@@ -43,6 +48,7 @@ export function PullRequestMarkdownEditor({
readonly onSave: (next: string) => void;
readonly onCancel: () => void;
}) {
const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
const [draft, setDraft] = useState(value);
const [preview, setPreview] = useState(false);
// The words this draft started from. React keeps a component instance wherever the same
@@ -55,7 +61,7 @@ export function PullRequestMarkdownEditor({
setDraft(value);
}
const empty = draft.trim().length === 0;
const saveDisabled = saving || (empty && !allowEmpty);
const saveDisabled = !canWriteSourceControl || saving || (empty && !allowEmpty);
return (
<div
@@ -70,7 +76,12 @@ export function PullRequestMarkdownEditor({
) {
event.preventDefault();
event.stopPropagation();
if (!saveDisabled && !event.repeat) onSave(draft);
if (
!saveDisabled &&
!event.repeat &&
readEnvironmentScope(environmentId, AuthSourceControlWriteScope)
)
onSave(draft);
return;
}
if (event.key !== "Escape" || saving) return;
@@ -119,7 +130,20 @@ export function PullRequestMarkdownEditor({
<Button size="xs" variant="ghost" disabled={saving} onClick={onCancel}>
Cancel
</Button>
<Button size="xs" variant="outline" disabled={saveDisabled} onClick={() => onSave(draft)}>
<Button
size="xs"
variant="outline"
disabled={!canWriteSourceControl || saving || (empty && !allowEmpty)}
onClick={() => {
if (
!readEnvironmentScope(environmentId, AuthSourceControlWriteScope) ||
saving ||
(empty && !allowEmpty)
)
return;
onSave(draft);
}}
>
{saving ? "Saving..." : "Save"}
</Button>
</div>
@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
import type {
EnvironmentId,
PullRequestReaction,
@@ -9,7 +10,6 @@ import { useState } from "react";
import { cn } from "~/lib/utils";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { toastManager } from "../ui/toast";
@@ -58,7 +58,9 @@ export function PullRequestReactionBar({
readonly signature: string;
readonly values: ReadonlyMap<PullRequestReactionContent, boolean>;
}>({ signature: "", values: EMPTY_PENDING });
const setReaction = useAtomCommand(pullRequestEnvironment.setReaction, { reportFailure: false });
const setReaction = useAtomCommand(pullRequestEnvironment.setReaction, {
reportFailure: false,
});
const signature = reactionsSignature(reactions);
const values = pending.signature === signature ? pending.values : EMPTY_PENDING;
@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
/**
* The review half of the floating composer: the summary and the verdict that sends it, together
* with whatever line comments the review is holding. The count of those lives on the composer's
@@ -9,7 +10,6 @@ import { CheckIcon, MessageSquareIcon, XCircleIcon } from "lucide-react";
import { useState, type ReactNode, type RefObject } from "react";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { Button } from "../ui/button";
import { Select, SelectItem, SelectPopup, SelectTrigger } from "../ui/select";
@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
/**
* Asking someone to review, from the row that says who is already reviewing.
*
@@ -15,7 +16,6 @@ import { useMemo, useState } from "react";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useEnvironmentQuery } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { toastManager } from "../ui/toast";
@@ -1,4 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import type { PullRequestAction } from "@t3tools/contracts";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useUiStateStore } from "~/uiStateStore";
import { Button } from "../ui/button";
import { Spinner } from "../ui/spinner";
@@ -37,6 +39,9 @@ export function PullRequestSpeedActions<Entry extends PullRequestSpeedActionEntr
sweeping?: boolean;
onCloseSweepStart?: (entry: Entry, event: PointerEvent) => void;
}) {
const canWrite = useAtomValue(
pullRequestEnvironment.runAction.permissionAtom(entry.environmentId),
);
const resolveProjectDefault = usePullRequestDefaultMergeMethodResolver(
entry.environmentId,
entry.projectId,
@@ -90,7 +95,7 @@ export function PullRequestSpeedActions<Entry extends PullRequestSpeedActionEntr
<Button
variant={action === "close" ? "destructive-outline" : "outline"}
size="xs"
disabled={busy || (action === "merge" && entry.stack !== undefined)}
disabled={!canWrite || busy || (action === "merge" && entry.stack !== undefined)}
aria-label={`${label} #${entry.number}`}
onClick={() => void perform(action)}
onPointerDown={(event) => {
@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
import type {
EnvironmentId,
PullRequestComment,
@@ -16,7 +17,6 @@ import {
} from "lucide-react";
import { useRef, useState, type ReactNode } from "react";
import { useAtomCommand } from "~/state/use-atom-command";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { cn } from "~/lib/utils";
import { useOpenLink } from "~/browser/useOpenLink";
@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
import type {
EnvironmentId,
PullRequestActor,
@@ -18,7 +19,6 @@ import { useState, type ReactNode } from "react";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { Button } from "../ui/button";
@@ -1,3 +1,4 @@
import { useAtomCommand } from "~/state/use-atom-command";
/**
* The actions a pull request offers, extracted from the detail panel so smaller surfaces — the
* thread details panel's pull request row — perform them through the very same code. Two callers
@@ -31,7 +32,6 @@ import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
import type { ReviewCommentContext } from "~/reviewCommentContext";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { toastManager } from "../ui/toast";
import { handoffPrompt, handoffReviewComments, readableFailure } from "./pullRequestDetail.logic";
@@ -140,7 +140,9 @@ export function usePullRequestActionRunner({
/** Small surfaces resolve repository settings on the click, not for every visible row. */
resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
}) {
const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
reportFailure: false,
});
const [actionPending, setActionPending] = useState(false);
const pendingRef = useRef(false);