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

+3
View File
@@ -264,6 +264,7 @@ export function BranchPickerRefItem({
projectCwd: activeProjectCwd,
index,
value,
disabled,
onClick,
onContextMenu,
}: {
@@ -271,6 +272,7 @@ export function BranchPickerRefItem({
projectCwd: string | null;
index: number;
value?: string;
disabled?: boolean;
onClick: ComponentProps<typeof ComboboxItem>["onClick"];
onContextMenu?: ComponentProps<typeof ComboboxItem>["onContextMenu"];
}) {
@@ -288,6 +290,7 @@ export function BranchPickerRefItem({
: null;
return (
<ComboboxItem
disabled={disabled}
hideIndicator
key={itemValue}
index={index}
@@ -8,7 +8,14 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
type ContextMenuItem,
type EnvironmentId,
type VcsRef,
type ThreadId,
} from "@t3tools/contracts";
import { ChevronDownIcon, GitBranchIcon } from "lucide-react";
import {
useCallback,
@@ -30,6 +37,7 @@ import { useOpenPrLink } from "../lib/openPullRequestLink";
import { usePaginatedBranches } from "../state/queries";
import { useProject, useThreadShell } from "../state/entities";
import { useEnvironmentQuery } from "../state/query";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { threadEnvironment } from "../state/threads";
import { useAtomCommand } from "../state/use-atom-command";
import { vcsEnvironment } from "../state/vcs";
@@ -110,6 +118,8 @@ export function BranchToolbarBranchSelector({
onComposerFocusRequest,
}: BranchToolbarBranchSelectorProps) {
const composerFloatingLayerProps = useComposerMenuProps();
const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
@@ -153,6 +163,8 @@ export function BranchToolbarBranchSelector({
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
const branchCwd = activeWorktreePath ?? activeProjectCwd;
const hasServerThread = serverThread !== null;
const canUpdateThreadBranch = !hasServerThread || canOperateThread;
const canChangeThreadBranch = canWriteSourceControl && canUpdateThreadBranch;
const effectiveEnvMode =
effectiveEnvModeOverride ??
resolveEffectiveEnvMode({
@@ -166,7 +178,12 @@ export function BranchToolbarBranchSelector({
// ---------------------------------------------------------------------------
const setThreadBranch = useCallback(
(branch: string | null, worktreePath: string | null, automatic = false) => {
if (!activeThreadId || !activeProject) return;
if (
!activeThreadId ||
!activeProject ||
(hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
)
return;
if (serverSession && worktreePath !== activeWorktreePath) {
void stopThreadSession({
environmentId,
@@ -273,8 +290,11 @@ export function BranchToolbarBranchSelector({
const isSelectingWorktreeBase =
effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
const checkoutPullRequestItemValue =
prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
canChangeThreadBranch && prReference && onCheckoutPullRequestRequest
? `__checkout_pull_request__:${prReference}`
: null;
const canCreateBranch =
canChangeThreadBranch && !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
// The ref is created under its sanitized name, so the collision check has to
// use that name too. Matching on the raw query would offer to create a ref
// that already exists whenever sanitizing changes the name.
@@ -392,6 +412,20 @@ export function BranchToolbarBranchSelector({
);
const runBranchAction = (action: () => Promise<void>) => {
if (
!readEnvironmentScope(environmentId, AuthSourceControlWriteScope) ||
(hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
) {
// The menu already closed when the item was chosen; explain the no-op.
toastManager.add(
stackedThreadToast({
type: "error",
title: "Action unavailable",
description: "This connection cannot change the thread's branch.",
}),
);
return;
}
startBranchActionTransition(async () => {
await action();
branchRefState.refresh();
@@ -400,7 +434,7 @@ export function BranchToolbarBranchSelector({
};
const selectBranch = (refName: VcsRef) => {
if (!branchCwd || !activeProjectCwd || isBranchActionPending) return;
if (!canUpdateThreadBranch || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
if (isSelectingWorktreeBase) {
setThreadBranch(refName.name, null);
@@ -461,6 +495,7 @@ export function BranchToolbarBranchSelector({
};
const createRef = (rawName: string) => {
if (!canChangeThreadBranch) return;
const name = sanitizeNewRefName(rawName);
if (!branchCwd || !name || isBranchActionPending) return;
@@ -647,6 +682,17 @@ export function BranchToolbarBranchSelector({
projectCwd={activeProjectCwd}
index={index}
value={itemValue}
disabled={
!canUpdateThreadBranch ||
(!canWriteSourceControl &&
!isSelectingWorktreeBase &&
(!activeProjectCwd ||
!resolveBranchSelectionTarget({
activeProjectCwd,
activeWorktreePath,
refName,
}).reuseExistingWorktree))
}
onClick={() => selectPickerItem(itemValue)}
onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
/>
+20 -8
View File
@@ -50,6 +50,7 @@ import { useAttachmentUploadStore } from "../lib/attachmentUploadQueue";
import {
AuthOrchestrationOperateScope,
AuthSettingsWriteScope,
AuthSourceControlWriteScope,
type AssistantCitation,
type ChatFileAttachment,
CommandId,
@@ -397,6 +398,7 @@ import { useEnvironmentDisconnectDelay } from "../hooks/useEnvironmentDisconnect
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
import { useEnvironmentQuery } from "../state/query";
import { useEnvironmentScope } from "~/state/session";
import {
environmentServerConfigsAtom,
primaryServerAvailableEditorsAtom,
@@ -559,11 +561,7 @@ import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/at
import { appAtomRegistry } from "../rpc/atomRegistry";
import { fileAttachmentCapabilityBlockReason } from "./chat/composerAttachmentFiles";
import { assetEnvironment } from "../state/assets";
import {
readEnvironmentScope,
readPreparedConnection,
useEnvironmentScope,
} from "../state/session";
import { readEnvironmentScope, readPreparedConnection } from "../state/session";
import { useAtomCommand } from "../state/use-atom-command";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
@@ -1577,6 +1575,7 @@ export default function ChatView(props: ChatViewProps) {
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, {
reportFailure: false,
@@ -2164,7 +2163,7 @@ export default function ChatView(props: ChatViewProps) {
(isServerThread ? activeThread?.runtimeMode : undefined) ??
defaultRuntimeMode;
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
const canCheckoutPullRequestIntoThread = canWriteSourceControl && isLocalDraftThread;
const activeThreadId = activeThread?.id ?? null;
// Prefer the larger of turn-item-committed ids and projection messages so
// env lock does not unlock while turn items lag projection hydration.
@@ -7161,6 +7160,7 @@ export default function ChatView(props: ChatViewProps) {
});
}, [activeBranchMismatchKey, showBranchMismatchBanner]);
const handleSwitchCheckoutToThread = useCallback(async () => {
if (!canWriteSourceControl) return;
if (
!activeProjectCwd ||
!activeThread ||
@@ -7191,6 +7191,10 @@ export default function ChatView(props: ChatViewProps) {
return;
}
if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
setIsRestoringThreadBranch(false);
return;
}
const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
if (nextBranch !== activeThread.branch) {
const updateResult = await updateThreadMetadata({
@@ -7216,6 +7220,7 @@ export default function ChatView(props: ChatViewProps) {
setIsRestoringThreadBranch(false);
scheduleComposerFocus();
}, [
canWriteSourceControl,
activeProjectCwd,
activeThread,
environmentId,
@@ -7622,12 +7627,17 @@ export default function ChatView(props: ChatViewProps) {
selectedProvider,
]);
const handleRestoreThreadBranch = useCallback(() => {
if (!canWriteSourceControl) return;
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
setBranchRestoreConfirmOpen(true);
return;
}
void handleSwitchCheckoutToThread();
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
}, [
canWriteSourceControl,
gitStatusQuery.data?.hasWorkingTreeChanges,
handleSwitchCheckoutToThread,
]);
const feedbackBannerItems = useMemo(
() =>
feedbackSubmissions.flatMap((submission) => {
@@ -7722,7 +7732,7 @@ export default function ChatView(props: ChatViewProps) {
<Button
size="xs"
variant="ghost"
disabled={isRestoringThreadBranch}
disabled={!canWriteSourceControl || isRestoringThreadBranch}
onClick={handleRestoreThreadBranch}
>
{isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
@@ -7740,6 +7750,7 @@ export default function ChatView(props: ChatViewProps) {
activeBranchMismatchKey,
activeThreadShell,
serverRuntime?.usageLimitResetAt,
canWriteSourceControl,
feedbackBannerItems,
limitRecoveryBanner,
handleRestoreThreadBranch,
@@ -11654,6 +11665,7 @@ export default function ChatView(props: ChatViewProps) {
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
variant="default"
disabled={!canWriteSourceControl}
onClick={() => {
setBranchRestoreConfirmOpen(false);
void handleSwitchCheckoutToThread();
+45 -4
View File
@@ -30,6 +30,8 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
type DesktopWslState,
type EnvironmentId,
type EnvironmentMachineKind,
@@ -103,6 +105,7 @@ import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { serverEnvironment } from "../state/server";
import { threadEnvironment } from "../state/threads";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { sourceControlEnvironment } from "../state/sourceControl";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
@@ -1039,6 +1042,7 @@ function OpenCommandPaletteDialog(props: {
[addProjectEnvironmentOptions, environments],
);
const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
const canCreateProject = useEnvironmentScope(browseEnvironmentId, AuthOrchestrationOperateScope);
const browseEnvironment =
environments.find((environment) => environment.environmentId === browseEnvironmentId) ?? null;
// A desktop-local secondary backend (today: the WSL backend). The picker is
@@ -2418,6 +2422,16 @@ function OpenCommandPaletteDialog(props: {
return;
}
if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Cannot add project",
description: "This connection cannot add projects.",
}),
);
return;
}
const projectId = newProjectId();
const createResult = await createProject({
environmentId: input.environmentId,
@@ -2607,9 +2621,20 @@ function OpenCommandPaletteDialog(props: {
}
const rawDestination = (destinationPathInput ?? query).trim();
if (rawDestination.length === 0 || isRemoteProjectCloning) {
if (
!readEnvironmentScope(addProjectCloneFlow.environmentId, AuthSourceControlWriteScope) ||
!readEnvironmentScope(addProjectCloneFlow.environmentId, AuthOrchestrationOperateScope)
) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone unavailable",
description: "This connection needs permission to write source control and add projects.",
}),
);
return;
}
if (rawDestination.length === 0 || isRemoteProjectCloning) return;
if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) {
toastManager.add(
@@ -2948,9 +2973,21 @@ function OpenCommandPaletteDialog(props: {
getCommandPaletteInputPlaceholder(paletteMode));
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
const canWriteSourceControl = useEnvironmentScope(
addProjectCloneFlow?.environmentId ?? null,
AuthSourceControlWriteScope,
);
const canCreateClonedProject = useEnvironmentScope(
addProjectCloneFlow?.environmentId ?? null,
AuthOrchestrationOperateScope,
);
const canCloneProject = canWriteSourceControl && canCreateClonedProject;
const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm";
const canSubmitBrowsePath =
isBrowsing &&
!relativePathNeedsActiveProject &&
canCreateProject &&
(!isCloneDestinationStep || canCloneProject) &&
canCreateProjectInEnvironment(browseEnvironment?.connection.phase);
const willCreateProjectPath =
canSubmitBrowsePath &&
@@ -2960,7 +2997,6 @@ function OpenCommandPaletteDialog(props: {
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
const useMetaForMod = isMacPlatform(navigator.platform);
const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm";
const submitActionLabel = isCloneDestinationStep
? willCreateProjectPath
? "Create & Clone"
@@ -3327,9 +3363,10 @@ function OpenCommandPaletteDialog(props: {
className="absolute inset-e-2.5 top-1/2 -translate-y-1/2"
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
disabled={
!canCreateProject ||
!canCreateProjectInEnvironment(browseEnvironment?.connection.phase) ||
relativePathNeedsActiveProject ||
(isCloneDestinationStep && isRemoteProjectPending)
(isCloneDestinationStep && (!canCloneProject || isRemoteProjectPending))
}
onMouseDown={(event) => {
event.preventDefault();
@@ -3355,7 +3392,11 @@ function OpenCommandPaletteDialog(props: {
</KbdGroup>
</TooltipTrigger>
<TooltipPopup side="top">
{submitActionLabel} ({addShortcutLabel})
{isCloneDestinationStep && !canCloneProject
? "This connection needs permission to write source control and add projects."
: canCreateProject
? `${submitActionLabel} (${addShortcutLabel})`
: "This connection cannot add projects."}
</TooltipPopup>
</Tooltip>
) : null;
@@ -0,0 +1,295 @@
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
EnvironmentId,
ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
scopes: new Set<string>(),
primaryScopes: new Set<string>(),
shell: { branch: "main" } as { branch: string } | null,
detail: null as { branch: string } | null,
draft: null as { branch: string; worktreePath: null; envMode: "local" } | null,
branch: "main",
commits: 0,
metadataRequests: [] as { environmentId: string; branch: string }[],
afterGitAction: undefined as (() => void) | undefined,
run: null as ((input: { action: "commit"; featureBranch?: boolean }) => Promise<void>) | null,
}));
vi.mock("react", async (importOriginal) => ({
...(await importOriginal<typeof import("react")>()),
useCallback: (callback: unknown) => callback,
useMemo: (factory: () => unknown) => factory(),
useState: (initial: unknown) => [typeof initial === "function" ? initial() : initial, () => {}],
useRef: (current: unknown) => ({ current }),
useEffect: () => {},
useEffectEvent: (callback: typeof state.run) => {
state.run = callback;
return callback;
},
}));
vi.mock("@effect/atom-react", () => ({
useAtomValue: (atom: unknown) => (atom === "vcs-state" ? { isRunning: false } : null),
}));
vi.mock("~/state/entities", () => ({
useThreadProjection: (ref: unknown) =>
ref === null || state.detail === null ? null : { projection: { thread: state.detail } },
useThreadShell: () => state.shell,
}));
vi.mock("~/state/session", () => ({
useEnvironmentScope: (environmentId: unknown, scope: string) =>
(environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope),
readEnvironmentScope: (environmentId: unknown, scope: string) =>
(environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope),
}));
vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
vi.mock("~/state/server", () => ({ serverEnvironment: { configValueAtom: () => null } }));
vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: {} }));
vi.mock("~/state/vcs", () => ({
vcsEnvironment: { status: () => null },
vcsActionManager: { stateAtom: () => "vcs-state" },
}));
vi.mock("~/state/threads", () => ({
threadEnvironment: {
updateMetadata: async ({
environmentId,
input,
}: {
environmentId: string;
input: { branch: string };
}) => {
state.metadataRequests.push({ environmentId, branch: input.branch });
if (!state.scopes.has(AuthOrchestrationOperateScope))
return AsyncResult.failure(Cause.fail(new Error("Task denied")));
if (state.shell) state.shell.branch = input.branch;
if (state.detail) state.detail.branch = input.branch;
return AsyncResult.success(undefined);
},
},
}));
vi.mock("~/state/query", () => ({
useEnvironmentQuery: () => ({
data: {
isRepo: true,
refName: "main",
isDefaultRef: false,
hasPrimaryRemote: true,
hasWorkingTreeChanges: true,
workingTree: { files: [{ path: "file.ts", status: "modified" }] },
},
error: null,
}),
}));
vi.mock("~/composerDraftStore", () => ({
useComposerDraftStore: (
select: (store: {
getDraftSession: () => typeof state.draft;
getDraftThreadByRef: () => typeof state.draft;
setDraftThreadContext: (_target: unknown, input: { branch: string }) => void;
}) => unknown,
) =>
select({
getDraftSession: () => state.draft,
getDraftThreadByRef: () => state.draft,
setDraftThreadContext: (_target, input) => {
if (state.draft) state.draft.branch = input.branch;
},
}),
}));
vi.mock("~/lib/sourceControlActions", () => ({
useSourceControlActionRunning: () => false,
useVcsInitAction: () => ({}),
useVcsPullAction: () => ({}),
useSourceControlPublishRepositoryAction: () => ({}),
useGitStackedAction: () => ({
run: async ({ featureBranch }: { featureBranch?: boolean }) => {
state.commits += 1;
if (featureBranch) state.branch = "feature";
state.afterGitAction?.();
return {
_tag: "Success",
value: {
branch: featureBranch
? { status: "created", name: "feature" }
: { status: "skipped_not_requested" },
toast: { title: "Committed", description: "Committed", cta: { kind: "none" } },
},
};
},
}),
}));
vi.mock("~/lib/utils", () => ({ cn: () => "", randomUUID: () => "action" }));
vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => () => {} }));
vi.mock("~/lib/openPullRequestLink", () => ({ useOpenPrLink: () => () => {} }));
vi.mock("~/components/ui/toast", () => ({
stackedThreadToast: (input: unknown) => input,
toastManager: { add: () => "toast", update: () => {}, close: () => {} },
}));
vi.mock("~/components/ui/dialog", () => ({
Dialog: "Dialog",
DialogDescription: "DialogDescription",
DialogFooter: "DialogFooter",
DialogHeader: "DialogHeader",
DialogPanel: "DialogPanel",
DialogPopup: "DialogPopup",
DialogTitle: "DialogTitle",
}));
vi.mock("~/components/ui/group", () => ({ Group: "Group", GroupSeparator: "GroupSeparator" }));
vi.mock("~/components/ui/menu", () => ({
Menu: "Menu",
MenuItem: "MenuItem",
MenuItemLabel: "MenuItemLabel",
MenuPopup: "MenuPopup",
MenuTrigger: "MenuTrigger",
}));
vi.mock("~/components/ui/popover", () => ({
Popover: "Popover",
PopoverPopup: "PopoverPopup",
PopoverTrigger: "PopoverTrigger",
}));
vi.mock("~/components/ui/tooltip", () => ({
Tooltip: "Tooltip",
TooltipPopup: "TooltipPopup",
TooltipTrigger: "TooltipTrigger",
}));
vi.mock("~/components/ui/button", () => ({ Button: "Button" }));
vi.mock("~/components/ui/checkbox", () => ({ Checkbox: "Checkbox" }));
vi.mock("~/components/ui/input", () => ({ Input: "Input" }));
vi.mock("~/components/ui/radio-group", () => ({ RadioGroup: "RadioGroup" }));
vi.mock("~/components/ui/scroll-area", () => ({ ScrollArea: "ScrollArea" }));
vi.mock("~/components/ui/spinner", () => ({ Spinner: "Spinner" }));
vi.mock("~/components/ui/textarea", () => ({ Textarea: "Textarea" }));
vi.mock("~/components/ui/toggle", () => ({ toggleVariants: () => "" }));
vi.mock("./AnimatedHeight", () => ({ AnimatedHeight: "AnimatedHeight" }));
import GitActionsControl from "./GitActionsControl";
function renderActions() {
GitActionsControl({
gitCwd: "/repo",
activeThreadRef: {
environmentId: EnvironmentId.make("environment"),
threadId: ThreadId.make("thread"),
},
});
if (!state.run) throw new Error("Git action missing");
return state.run;
}
describe("Git actions while thread details load", () => {
beforeEach(() => {
state.scopes = new Set([AuthSourceControlWriteScope]);
state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
state.shell = { branch: "main" };
state.detail = null;
state.draft = null;
state.branch = "main";
state.commits = 0;
state.metadataRequests = [];
state.afterGitAction = undefined;
state.run = null;
});
it("does not create a feature branch for a server thread without task permission", async () => {
await renderActions()({ action: "commit", featureBranch: true });
expect(state.branch).toBe("main");
expect(state.commits).toBe(0);
expect(state.shell?.branch).toBe("main");
});
it("commits and synchronizes the server thread before details finish loading", async () => {
state.primaryScopes.clear();
state.scopes.add(AuthOrchestrationOperateScope);
await renderActions()({ action: "commit", featureBranch: true });
expect(state.branch).toBe("feature");
expect(state.commits).toBe(1);
expect(state.shell?.branch).toBe("feature");
expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
});
it("synchronizes archived thread detail after its shell disappears", async () => {
state.scopes.add(AuthOrchestrationOperateScope);
state.detail = { branch: "main" };
renderActions();
state.shell = null;
await renderActions()({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.branch).toBe("feature");
expect(state.detail.branch).toBe("feature");
expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
});
it("requires task permission before changing an archived thread's branch", async () => {
state.shell = null;
state.detail = { branch: "main" };
await renderActions()({ action: "commit", featureBranch: true });
expect(state.commits).toBe(0);
expect(state.detail.branch).toBe("main");
expect(state.metadataRequests).toEqual([]);
});
it("uses the current shell branch when cached detail names the new branch", async () => {
state.scopes.add(AuthOrchestrationOperateScope);
state.detail = { branch: "feature" };
await renderActions()({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.shell?.branch).toBe("feature");
expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
});
it("synchronizes a retained callback after the thread grant is gained", async () => {
const run = renderActions();
state.scopes.add(AuthOrchestrationOperateScope);
await run({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.shell?.branch).toBe("feature");
expect(state.metadataRequests).toHaveLength(1);
});
it.each([
[AuthOrchestrationOperateScope, false],
[AuthSourceControlWriteScope, true],
] as const)(
"uses the fresh task grant after Git finishes, revoking %s",
async (revokedScope, syncsThread) => {
state.scopes.add(AuthOrchestrationOperateScope);
state.afterGitAction = () => state.scopes.delete(revokedScope);
await renderActions()({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.branch).toBe("feature");
expect(state.shell?.branch).toBe(syncsThread ? "feature" : "main");
expect(state.metadataRequests).toHaveLength(syncsThread ? 1 : 0);
},
);
it("keeps ordinary commits available while details load", async () => {
await renderActions()({ action: "commit" });
expect(state.commits).toBe(1);
expect(state.branch).toBe("main");
});
it("keeps feature-branch commits available for a local draft", async () => {
state.shell = null;
state.draft = { branch: "main", worktreePath: null, envMode: "local" };
await renderActions()({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.draft.branch).toBe("feature");
expect(state.metadataRequests).toEqual([]);
});
});
+61 -17
View File
@@ -1,6 +1,10 @@
import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
import { useAtomValue } from "@effect/atom-react";
import { type ScopedThreadRef } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
type ScopedThreadRef,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -108,7 +112,8 @@ import {
useVcsInitAction,
useVcsPullAction,
} from "~/lib/sourceControlActions";
import { useThreadShell } from "~/state/entities";
import { useThreadProjection, useThreadShell } from "~/state/entities";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { useEnvironmentQuery } from "~/state/query";
import { serverEnvironment } from "~/state/server";
import { sourceControlEnvironment } from "~/state/sourceControl";
@@ -630,14 +635,19 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
] as const;
const canSubmitPublishRepository = useMemo(() => {
if (!selectedPublishProviderReadiness.ready) return false;
if (!publishRepositoryAction.isAllowed || !selectedPublishProviderReadiness.ready) return false;
if (publishRepositoryAction.isPending) return false;
const repositoryParts = publishRepository.trim().split("/");
const owner = repositoryParts[0]?.trim() ?? "";
const rest = repositoryParts.slice(1);
const name = rest.join("/").trim();
return owner.length > 0 && name.length > 0;
}, [publishRepository, publishRepositoryAction.isPending, selectedPublishProviderReadiness]);
}, [
publishRepository,
publishRepositoryAction.isAllowed,
publishRepositoryAction.isPending,
selectedPublishProviderReadiness,
]);
const submitPublishRepository = useCallback(() => {
if (!canSubmitPublishRepository) {
@@ -1070,6 +1080,11 @@ export default function GitActionsControl({
);
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
const successScopeKey = `${activeEnvironmentId ?? ""}\u0000${gitCwd ?? ""}`;
const canWriteSourceControl = useEnvironmentScope(
activeEnvironmentId,
AuthSourceControlWriteScope,
);
const canOperateThread = useEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope);
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(activeEnvironmentId));
const openInPreferredEditor = useOpenInPreferredEditor(
activeEnvironmentId,
@@ -1079,7 +1094,7 @@ export default function GitActionsControl({
() => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
[activeThreadRef],
);
const activeServerThread = useThreadShell(activeThreadRef);
const activeServerThreadShell = useThreadShell(activeThreadRef);
const openPrLink = useOpenPrLink(activeThreadRef ?? undefined);
const activeDraftThread = useComposerDraftStore((store) =>
draftId
@@ -1088,6 +1103,13 @@ export default function GitActionsControl({
? store.getDraftThreadByRef(activeThreadRef)
: null,
);
const activeServerThreadProjection = useThreadProjection(
activeDraftThread !== null && activeServerThreadShell === null ? null : activeThreadRef,
);
const activeServerThread =
activeServerThreadShell ?? activeServerThreadProjection?.projection.thread ?? null;
const isLocalDraftThread = activeDraftThread !== null && activeServerThread === null;
const canChangeThreadBranch = canWriteSourceControl && (isLocalDraftThread || canOperateThread);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
@@ -1120,7 +1142,10 @@ export default function GitActionsControl({
}
if (activeServerThread) {
if (activeServerThread.branch === branch) {
if (
!readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) ||
activeServerThread.branch === branch
) {
return;
}
@@ -1248,9 +1273,11 @@ export default function GitActionsControl({
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultRef, hasPrimaryRemote),
[gitStatusForActions, hasPrimaryRemote, isDefaultRef, isGitActionRunning],
);
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const quickActionDisabledReason = !canWriteSourceControl
? "This connection cannot change source control."
: quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const gitActionProgress = resolveGitActionProgressPresentation(vcsActionState);
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
? resolveDefaultBranchActionDialogCopy({
@@ -1304,6 +1331,14 @@ export default function GitActionsControl({
featureBranch = false,
filePaths,
}: RunGitActionWithToastInput) => {
if (
activeEnvironmentId === null ||
!readEnvironmentScope(activeEnvironmentId, AuthSourceControlWriteScope) ||
(featureBranch &&
!isLocalDraftThread &&
!readEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope))
)
return;
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.refName ?? null;
const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
@@ -1459,7 +1494,7 @@ export default function GitActionsControl({
};
const checkoutFeatureBranchAndContinuePendingAction = () => {
if (!pendingDefaultBranchAction) return;
if (!canChangeThreadBranch || !pendingDefaultBranchAction) return;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
@@ -1473,7 +1508,7 @@ export default function GitActionsControl({
};
const runDialogActionOnNewBranch = () => {
if (!isCommitDialogOpen) return;
if (!canChangeThreadBranch || !isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
@@ -1616,7 +1651,8 @@ export default function GitActionsControl({
[gitCwd, openInPreferredEditor, threadToastData],
);
const canPublishRepository = isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
const canPublishRepository =
canWriteSourceControl && isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
const initializeGit = () => {
void (async () => {
@@ -1683,7 +1719,7 @@ export default function GitActionsControl({
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
key={`${item.id}-${item.label}`}
disabled={item.disabled}
disabled={!canWriteSourceControl || item.disabled}
onClick={() => {
openDialogForMenuItem(item);
}}
@@ -1777,7 +1813,7 @@ export default function GitActionsControl({
variant={isPanel ? "ghost" : "outline"}
part="row"
panel={isPanel}
disabled={initAction.isPending}
disabled={!canWriteSourceControl || initAction.isPending}
onClick={initializeGit}
>
<GitBranchPlusIcon className="size-3.5" aria-hidden />
@@ -1855,7 +1891,7 @@ export default function GitActionsControl({
size="xs"
part="primary"
panel={isPanel}
disabled={isGitActionRunning || quickAction.disabled}
disabled={!canWriteSourceControl || isGitActionRunning || quickAction.disabled}
onClick={runQuickAction}
>
<GitQuickActionIcon
@@ -2035,6 +2071,8 @@ export default function GitActionsControl({
<button
type="button"
className="flex min-w-0 flex-1 items-center justify-between gap-3 text-left"
disabled={!canOperateThread}
aria-label={`Open ${file.path} in editor`}
onClick={() => openChangedFileInEditor(file.path)}
>
<StartTruncatedPath
@@ -2102,12 +2140,16 @@ export default function GitActionsControl({
<Button
variant="outline"
size="sm"
disabled={noneSelected}
disabled={!canChangeThreadBranch || noneSelected}
onClick={runDialogActionOnNewBranch}
>
Commit on new branch
</Button>
<Button size="sm" disabled={noneSelected} onClick={runDialogAction}>
<Button
size="sm"
disabled={!canWriteSourceControl || noneSelected}
onClick={runDialogAction}
>
Commit
</Button>
</DialogFooter>
@@ -2151,6 +2193,7 @@ export default function GitActionsControl({
variant="outline"
size="sm-multiline"
onClick={continuePendingDefaultBranchAction}
disabled={!canWriteSourceControl}
>
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
</Button>
@@ -2158,6 +2201,7 @@ export default function GitActionsControl({
className="w-full max-w-full sm:w-auto"
size="sm-multiline"
onClick={checkoutFeatureBranchAndContinuePendingAction}
disabled={!canChangeThreadBranch}
>
Check out feature branch & continue
</Button>
@@ -0,0 +1,273 @@
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
EnvironmentId,
ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { isValidElement, type ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
canOperate: false,
canWriteSourceControl: true,
hookValues: [] as unknown[],
hookIndex: 0,
tracks: 0,
resets: 0,
manager: { operation: null as string | null, error: null, isRunning: false },
interrupted: false,
pendingResponse: undefined as Promise<void> | undefined,
openChanges: [] as boolean[],
checkouts: [] as string[],
setupScripts: 0,
prepared: [] as { branch: string; worktreePath: string | null }[],
}));
vi.mock("react", async (importOriginal) => ({
...(await importOriginal<typeof import("react")>()),
useCallback: (callback: unknown) => callback,
useMemo: (factory: () => unknown) => factory(),
useState: (initial: unknown) => {
const index = state.hookIndex++;
if (index === state.hookValues.length) state.hookValues.push(initial);
return [state.hookValues[index], (value: unknown) => (state.hookValues[index] = value)];
},
useRef: (current: unknown) => ({ current }),
useEffect: () => {},
}));
vi.mock("@tanstack/react-pacer", () => ({
useDebouncedValue: (value: unknown) => [value, { state: { isPending: false } }],
}));
vi.mock("~/state/session", () => ({
useEnvironmentScope: (_environmentId: unknown, scope: string) =>
scope === AuthOrchestrationOperateScope
? state.canOperate
: scope === AuthSourceControlWriteScope && state.canWriteSourceControl,
readEnvironmentScope: (_environmentId: unknown, scope: string) =>
scope === AuthOrchestrationOperateScope
? state.canOperate
: scope === AuthSourceControlWriteScope && state.canWriteSourceControl,
}));
vi.mock("~/lib/sourceControlActions", async () => {
const { usePreparePullRequestThreadAction } = await vi.importActual<
typeof import("~/state/sourceControlActions")
>("~/state/sourceControlActions");
return {
readCachedPullRequestResolution: () => null,
usePullRequestResolution: () => ({
data: { pullRequest: { number: 123, title: "Pull request", state: "open" } },
}),
usePreparePullRequestThreadAction,
};
});
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.manager }));
vi.mock("~/rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
vi.mock("~/state/use-atom-command", () => ({
useAtomCommand: (command: unknown) => command,
}));
vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: {} }));
vi.mock("~/state/git", () => ({
gitEnvironment: {
preparePullRequestThread: async ({
input: { mode, threadId },
}: {
input: { mode: string; threadId?: string };
}) => {
state.checkouts.push(mode);
if (mode === "worktree" && threadId) state.setupScripts += 1;
await state.pendingResponse;
if (state.interrupted) return AsyncResult.failure(Cause.interrupt());
return AsyncResult.success({
branch: "feature/pr",
worktreePath: mode === "worktree" ? "/worktree" : null,
});
},
},
}));
vi.mock("~/lib/utils", () => ({ cn: () => "" }));
vi.mock("~/state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) }));
vi.mock("~/state/vcs", () => ({
vcsEnvironment: { status: () => null },
vcsActionManager: {
stateAtom: () => "vcs-state",
track: (_registry: unknown, _target: unknown, _input: unknown, execute: () => unknown) => {
state.tracks += 1;
return execute();
},
resetError: () => state.resets++,
},
}));
vi.mock("./ui/button", () => ({ Button: "Button" }));
vi.mock("./ui/input", () => ({ Input: "Input" }));
vi.mock("./ui/spinner", () => ({ Spinner: "Spinner" }));
vi.mock("./ui/dialog", () => ({
Dialog: "Dialog",
DialogDescription: "DialogDescription",
DialogFooter: "DialogFooter",
DialogHeader: "DialogHeader",
DialogPanel: "DialogPanel",
DialogPopup: "DialogPopup",
DialogTitle: "DialogTitle",
}));
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
function findAction(node: ReactNode, label: string): (() => unknown) | null {
if (Array.isArray(node)) {
for (const child of node) {
const action = findAction(child, label);
if (action) return action;
}
return null;
}
if (!isValidElement<{ children?: ReactNode; onClick?: () => unknown }>(node)) return null;
if (node.props.children === label) return node.props.onClick ?? null;
return findAction(node.props.children, label);
}
function renderDialog() {
state.hookIndex = 0;
return PullRequestThreadDialog({
open: true,
environmentId: EnvironmentId.make("environment"),
threadId: ThreadId.make("thread"),
cwd: "/repo",
initialReference: "123",
onOpenChange: (open) => state.openChanges.push(open),
onPrepared: (input) => {
state.prepared.push(input);
},
});
}
function prepareAction(label: "Local" | "Worktree") {
const action = findAction(renderDialog(), label);
if (!action) throw new Error(`${label} action missing`);
return action;
}
function visibleText(node: ReactNode): string {
if (Array.isArray(node)) return node.map(visibleText).join(" ");
if (typeof node === "string" || typeof node === "number") return String(node);
return isValidElement<{ children?: ReactNode }>(node) ? visibleText(node.props.children) : "";
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((complete) => {
resolve = complete;
});
return { promise, resolve };
}
describe("pull request worktree permissions", () => {
beforeEach(() => {
state.canOperate = false;
state.canWriteSourceControl = true;
state.hookValues = [];
state.hookIndex = 0;
state.tracks = 0;
state.resets = 0;
state.manager = { operation: null, error: null, isRunning: false };
state.interrupted = false;
state.pendingResponse = undefined;
state.openChanges = [];
state.checkouts = [];
state.setupScripts = 0;
state.prepared = [];
});
it("does not prepare a worktree or run setup with only source-control permission", async () => {
await prepareAction("Worktree")();
expect(state.checkouts).toEqual([]);
expect(state.setupScripts).toBe(0);
expect(state.prepared).toEqual([]);
});
it("prepares the worktree and thread when task permission is also granted", async () => {
state.canOperate = true;
await prepareAction("Worktree")();
expect(state.checkouts).toEqual(["worktree"]);
expect(state.setupScripts).toBe(1);
expect(state.prepared).toEqual([{ branch: "feature/pr", worktreePath: "/worktree" }]);
});
it("rechecks task permission before invoking a retained worktree action", async () => {
state.canOperate = true;
const prepare = prepareAction("Worktree");
state.canOperate = false;
await prepare();
expect(state.checkouts).toEqual([]);
expect(state.setupScripts).toBe(0);
});
it("keeps local checkout available without task permission", async () => {
await prepareAction("Local")();
expect(state.checkouts).toEqual(["local"]);
expect(state.setupScripts).toBe(0);
expect(state.prepared).toEqual([{ branch: "feature/pr", worktreePath: null }]);
});
it.each(["Local", "Worktree"] as const)(
"shows the returned scope denial for a retained %s callback without starting a checkout",
async (label) => {
state.canOperate = true;
state.manager = { operation: "pull", error: null, isRunning: true };
const prepare = prepareAction(label);
state.canWriteSourceControl = false;
await prepare();
expect(visibleText(renderDialog())).toContain(
"This connection cannot change source control.",
);
expect(state.checkouts).toEqual([]);
expect(state.setupScripts).toBe(0);
expect(state.prepared).toEqual([]);
expect(state.openChanges).toEqual([]);
expect(state.tracks).toBe(0);
expect(state.manager).toEqual({ operation: "pull", error: null, isRunning: true });
},
);
it("clears a returned error when a newly authorized retry starts, then completes normally", async () => {
const prepare = prepareAction("Local");
state.canWriteSourceControl = false;
await prepare();
expect(visibleText(renderDialog())).toContain("This connection cannot change source control.");
state.canWriteSourceControl = true;
const response = deferred<void>();
state.pendingResponse = response.promise;
const completion = prepareAction("Local")();
expect(visibleText(renderDialog())).not.toContain(
"This connection cannot change source control.",
);
expect(state.checkouts).toEqual(["local"]);
expect(state.prepared).toEqual([]);
response.resolve(undefined);
await completion;
expect(state.prepared).toEqual([{ branch: "feature/pr", worktreePath: null }]);
expect(state.openChanges).toEqual([false]);
});
it("keeps interrupted preparations quiet and preserves error reset behavior", async () => {
state.interrupted = true;
const before = visibleText(renderDialog());
await prepareAction("Local")();
expect(visibleText(renderDialog())).toBe(before);
expect(state.resets).toBe(1);
expect(state.prepared).toEqual([]);
expect(state.openChanges).toEqual([]);
});
});
@@ -1,5 +1,12 @@
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
import {
AuthOrchestrationOperateScope,
type EnvironmentId,
type ThreadId,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -12,6 +19,7 @@ import { cn } from "~/lib/utils";
import { parsePullRequestReference } from "~/pullRequestReference";
import { getSourceControlPresentation } from "~/sourceControlPresentation";
import { useEnvironmentQuery } from "~/state/query";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { vcsEnvironment } from "~/state/vcs";
import { Button } from "./ui/button";
import {
@@ -49,6 +57,7 @@ export function PullRequestThreadDialog({
const [reference, setReference] = useState(initialReference ?? "");
const [referenceDirty, setReferenceDirty] = useState(false);
const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
const [prepareErrorMessage, setPrepareErrorMessage] = useState<string | null>(null);
const [debouncedReference, referenceDebouncer] = useDebouncedValue(
reference,
{ wait: 450 },
@@ -102,6 +111,7 @@ export function PullRequestThreadDialog({
);
}, [parsedReference, sourceControlScope]);
const preparePullRequestThreadAction = usePreparePullRequestThreadAction(sourceControlScope);
const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const liveResolvedPullRequest =
parsedReference !== null && parsedReference === parsedDebouncedReference
@@ -131,6 +141,13 @@ export function PullRequestThreadDialog({
const handleConfirm = useCallback(
async (mode: "local" | "worktree") => {
if (!preparePullRequestThreadAction.isAllowed) return;
if (
mode === "worktree" &&
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
) {
return;
}
if (!parsedReference) {
setReferenceDirty(true);
return;
@@ -138,6 +155,7 @@ export function PullRequestThreadDialog({
if (!parsedReference || !resolvedPullRequest || !cwd) {
return;
}
setPrepareErrorMessage(null);
setPreparingMode(mode);
const result = await preparePullRequestThreadAction.run({
reference: parsedReference,
@@ -148,6 +166,13 @@ export function PullRequestThreadDialog({
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
preparePullRequestThreadAction.resetError();
} else {
const error = squashAtomCommandFailure(result);
setPrepareErrorMessage(
error instanceof Error
? error.message
: `Failed to prepare ${terminology.singular} thread.`,
);
}
return;
}
@@ -159,11 +184,13 @@ export function PullRequestThreadDialog({
},
[
cwd,
environmentId,
onOpenChange,
onPrepared,
parsedReference,
preparePullRequestThreadAction,
resolvedPullRequest,
terminology.singular,
threadId,
],
);
@@ -177,6 +204,7 @@ export function PullRequestThreadDialog({
: null;
const errorMessage =
validationMessage ??
prepareErrorMessage ??
(resolvedPullRequest === null && pullRequestResolution.error
? pullRequestResolution.error
: preparePullRequestThreadAction.error instanceof Error
@@ -273,10 +301,9 @@ export function PullRequestThreadDialog({
type="button"
size="sm"
variant="outline"
onClick={() => {
void handleConfirm("local");
}}
onClick={() => handleConfirm("local")}
disabled={
!preparePullRequestThreadAction.isAllowed ||
!cwd ||
!resolvedPullRequest ||
isResolving ||
@@ -288,10 +315,10 @@ export function PullRequestThreadDialog({
<Button
type="button"
size="sm"
onClick={() => {
void handleConfirm("worktree");
}}
onClick={() => handleConfirm("worktree")}
disabled={
!preparePullRequestThreadAction.isAllowed ||
!canOperateThread ||
!cwd ||
!resolvedPullRequest ||
isResolving ||
+183 -61
View File
@@ -1,3 +1,4 @@
import { type EnvironmentId } from "@t3tools/contracts";
import { ThreadHoverCard, ThreadHoverCardPopup } from "./ThreadHoverCard";
import { CollapsibleSectionHeader } from "./ui/collapsible-section-header";
import { setThreadChangeRequestSnapshot } from "./ThreadStatusIndicators";
@@ -52,6 +53,7 @@ import {
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import {
AuthOrchestrationOperateScope,
type EnvironmentMachineKind,
type ScopedThreadRef,
type ThreadId,
@@ -158,7 +160,8 @@ import { vcsEnvironment } from "../state/vcs";
import { threadEnvironment } from "../state/threads";
import { useEnvironmentQuery } from "../state/query";
import { useThreadSearch } from "../state/queries";
import { useAtomCommand } from "../state/use-atom-command";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
import {
buildThreadRouteParams,
resolveActiveThreadRouteRef,
@@ -170,7 +173,11 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { cn } from "~/lib/utils";
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge";
import { buildDraftActionMenuItems, buildThreadActionMenuItems } from "./threadActionMenu.logic";
import {
buildDraftActionMenuItems,
buildThreadActionMenuItems,
threadActionRequiresOperate,
} from "./threadActionMenu.logic";
import {
animateSidebarLayoutChanges,
applySidebarThreadDrop,
@@ -296,6 +303,26 @@ const WORKING_SHELF_EXPANDED_KEY = "t3code:sidebar:working-expanded";
// Module scope keeps the inbox order across routes that unmount the sidebar.
const inboxReturns = createInboxReturnTracker();
function canOperateThreads(
threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,
): boolean {
return threads.every((thread) =>
readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope),
);
}
function checkThreadOperations(
threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,
): boolean {
if (canOperateThreads(threads)) return true;
toastManager.add({
type: "error",
title: "Thread action unavailable",
description: "This connection cannot change one or more selected threads.",
});
return false;
}
function compactSidebarTimeLabel(label: string): string {
if (label === "just now") return "now";
return label.endsWith(" ago") ? label.slice(0, -4) : label;
@@ -619,11 +646,13 @@ function SortableThreadRow(props: {
id: string;
disabled: boolean;
contextDrag: boolean;
environmentId: EnvironmentId;
children: (bag: SortableThreadRowBag) => ReactNode;
}) {
const canOperateThread = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope);
const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: props.id,
disabled: { draggable: props.disabled },
disabled: { draggable: props.disabled || !canOperateThread },
animateLayoutChanges: animateSidebarLayoutChanges,
});
// dnd-kit memoizes each field but not the bag, so the memoized row would
@@ -1173,6 +1202,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
[thread.environmentId, thread.id],
);
const threadKey = scopedThreadKey(threadRef);
const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
useEffect(() => {
if (!canOperateThread && isRenaming) onCancelRename();
}, [canOperateThread, isRenaming, onCancelRename]);
const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(props.isActive);
const isRegeneratingTitle = thread.titleRegeneration != null;
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
@@ -1389,7 +1422,14 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
);
const handleDoubleClick = useCallback(
(event: ReactMouseEvent) => {
if (isRenaming || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
if (
!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) ||
isRenaming ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
if ((event.target as HTMLElement).closest("button, a, input")) return;
@@ -1497,7 +1537,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
// Snooze is offered only where it can succeed: capability-gated and never
// on blocked-on-you work or queued turns (the server rejects both).
const showSnoozeButton =
props.snoozeSupported && canSnooze(thread, { now: new Date().toISOString() });
canOperateThread &&
props.snoozeSupported &&
canSnooze(thread, { now: new Date().toISOString() });
const showHoverActions =
(canOperateThread && props.settlementSupported) || showSnoozeButton || hasUnsentDraft;
// If the thread becomes blocked while the popover is open, the button
// unmounts without firing onOpenChange(false). Deriving the flag keeps a
// stale true from permanently hiding the status label / pinning the
@@ -1600,52 +1644,53 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
isActive: props.isActive,
});
const title = isRenaming ? (
<input
autoFocus
value={renamingTitle}
aria-label="Thread title"
onChange={(event) => onRenameTitleChange(event.target.value)}
onFocus={(event) => event.currentTarget.select()}
onKeyDown={handleRenameKeyDown}
onBlur={handleRenameBlur}
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground"
/>
) : (
<span
aria-hidden
className={cn(
"min-w-0 flex-1 text-sm transition-opacity motion-reduce:transition-none",
shouldRecede ? "font-normal" : "font-medium",
variant === "card"
? cn(
"truncate",
shouldRecede
? "text-secondary-label"
: isUnread || isWoke || status === "input"
? "text-foreground"
: status === "failed"
? "text-foreground/95"
: "text-foreground/90",
)
: cn(
"truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",
shouldRecede
? "text-secondary-label/70"
: props.isActive || isWoke || status === "input"
? "text-foreground"
: isUnread
? "text-muted-foreground"
: "text-secondary-label/70",
),
isRegeneratingTitle && "opacity-55",
)}
>
{thread.title}
</span>
);
const title =
isRenaming && canOperateThread ? (
<input
autoFocus
value={renamingTitle}
aria-label="Thread title"
onChange={(event) => onRenameTitleChange(event.target.value)}
onFocus={(event) => event.currentTarget.select()}
onKeyDown={handleRenameKeyDown}
onBlur={handleRenameBlur}
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground"
/>
) : (
<span
aria-hidden
className={cn(
"min-w-0 flex-1 text-sm transition-opacity motion-reduce:transition-none",
shouldRecede ? "font-normal" : "font-medium",
variant === "card"
? cn(
"truncate",
shouldRecede
? "text-secondary-label"
: isUnread || isWoke || status === "input"
? "text-foreground"
: status === "failed"
? "text-foreground/95"
: "text-foreground/90",
)
: cn(
"truncate group-focus-within/sidebar-row:text-foreground group-hover/sidebar-row:text-foreground",
shouldRecede
? "text-secondary-label/70"
: props.isActive || isWoke || status === "input"
? "text-foreground"
: isUnread
? "text-muted-foreground"
: "text-secondary-label/70",
),
isRegeneratingTitle && "opacity-55",
)}
>
{thread.title}
</span>
);
const accessibleTitle = isRenaming ? null : <span className="sr-only">{thread.title}</span>;
// Stacks show their layer count; multiple unrelated links show their total count.
@@ -1706,7 +1751,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
const showPin =
props.isPinned && (!sortable?.isDragging || (props.dragOverPinned && props.dropVerb === null));
const pinIndicator = showPin ? (
props.pinningSupported && !sortable?.isDragging ? (
props.pinningSupported && canOperateThread && !sortable?.isDragging ? (
<Tooltip>
<TooltipTrigger
render={
@@ -2350,7 +2395,7 @@ export default function Sidebar() {
archiveThread,
deleteThread,
} = useThreadActions();
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
@@ -3180,6 +3225,7 @@ export default function Sidebar() {
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const startThreadRename = useCallback((threadRef: ScopedThreadRef, title: string) => {
if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
setRenamingThreadKey(scopedThreadKey(threadRef));
setRenamingTitle(title);
}, []);
@@ -3187,6 +3233,7 @@ export default function Sidebar() {
const commitThreadRename = useCallback(
(threadRef: ScopedThreadRef, title: string, originalTitle: string) => {
void (async () => {
if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
const trimmed = title.trim();
setRenamingThreadKey(null);
if (trimmed.length === 0) {
@@ -3960,6 +4007,17 @@ export default function Sidebar() {
: plan.kind === "reorder-pinned" || plan.kind === "move-active"
? plan.assignments
: [];
// A drop rewrites the dragged row and every row it renumbers, so all of
// them must be writable before any of them changes.
if (
!checkThreadOperations(
[activeKey, ...assignments.map(({ id }) => id)].flatMap((key) => {
const thread = threadByKey.get(key);
return thread ? [thread] : [];
}),
)
)
return;
const drop = {
key: activeKey,
sourceSection: activeSection,
@@ -4174,6 +4232,9 @@ export default function Sidebar() {
const thread = threadByKeyRef.current.get(threadKey);
return thread ? [thread] : [];
});
const settlingThreads = selectedThreads.filter(
(thread) => thread.settledOverride !== "settled",
);
const canSnoozeSelection = selectedThreads.every(
(thread) =>
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true &&
@@ -4206,31 +4267,73 @@ export default function Sidebar() {
const clicked = await settlePromise(() =>
api.contextMenu.show(
[
...(unpinMenuItem ? [unpinMenuItem] : []),
{ id: "settle", label: `Settle (${count})` },
...(unpinMenuItem
? [{ ...unpinMenuItem, disabled: !canOperateThreads(pinnedSelectedThreads) }]
: []),
{
id: "settle",
label: `Settle (${count})`,
disabled: settlingThreads.length === 0 || !canOperateThreads(settlingThreads),
},
...(canSnoozeSelection
? [
{
id: "snooze",
label: `Snooze (${count})`,
disabled: !canOperateThreads(selectedThreads),
children: [
...snoozePresets.map((preset) => ({
id: `snooze:${preset.id}`,
label: `${preset.label} (${preset.whenLabel})`,
disabled: !canOperateThreads(selectedThreads),
})),
{ id: "snooze:custom", label: "Custom…", separatorBefore: true },
{
id: "snooze:custom",
label: "Custom…",
separatorBefore: true,
disabled: !canOperateThreads(selectedThreads),
},
],
},
]
: []),
...(titleRegenerationMenuItem ? [titleRegenerationMenuItem] : []),
...(titleRegenerationMenuItem
? [
{
...titleRegenerationMenuItem,
disabled:
titleRegenerationMenuItem.disabled ||
!canOperateThreads(regeneratableTitleThreads),
},
]
: []),
{ id: "mark-unread", label: `Mark unread (${count})` },
{ id: "delete", label: `Delete (${count})`, destructive: true },
{
id: "delete",
label: `Delete (${count})`,
destructive: true,
disabled: !canOperateThreads(selectedThreads),
},
],
position,
),
);
if (clicked._tag === "Failure") return;
if (clicked._tag === "Failure" || clicked.value === null) return;
const actionTargets =
clicked.value === "unpin"
? pinnedSelectedThreads
: clicked.value === "regenerate-title"
? regeneratableTitleThreads
: clicked.value === "settle"
? settlingThreads.flatMap((thread) => {
const current = threadByKeyRef.current.get(
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
);
return current && current.settledOverride !== "settled" ? [current] : [];
})
: selectedThreads;
if (clicked.value === "settle" && actionTargets.length === 0) return;
if (clicked.value !== "mark-unread" && !checkThreadOperations(actionTargets)) return;
if (clicked.value?.startsWith("snooze:")) {
const preset =
clicked.value === "snooze:custom"
@@ -4303,7 +4406,11 @@ export default function Sidebar() {
return;
}
if (clicked.value === "settle") {
settleThreads(threadKeys);
settleThreads(
actionTargets.map((thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
),
);
clearSelection();
return;
}
@@ -4328,6 +4435,15 @@ export default function Sidebar() {
);
if (confirmed._tag === "Failure" || !confirmed.value) return;
}
if (
!checkThreadOperations(
threadKeys.flatMap((threadKey) => {
const thread = threadByKeyRef.current.get(threadKey);
return thread ? [thread] : [];
}),
)
)
return;
const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({
entries: threadKeys.map((threadKey) => ({ threadKey })),
delete: async ({ threadKey }, deletedThreadKeys) => {
@@ -4469,6 +4585,10 @@ export default function Sidebar() {
const clicked = await settlePromise(() =>
api.contextMenu.show(
buildThreadActionMenuItems({
canOperate: readEnvironmentScope(
threadRef.environmentId,
AuthOrchestrationOperateScope,
),
branch: thread.branch ?? null,
projectFilter: threadProjectGroup
? {
@@ -4495,7 +4615,8 @@ export default function Sidebar() {
position,
),
);
if (clicked._tag === "Failure") return;
if (clicked._tag === "Failure" || clicked.value === null) return;
if (threadActionRequiresOperate(clicked.value) && !checkThreadOperations([thread])) return;
if (clicked.value?.startsWith("snooze:")) {
const preset =
clicked.value === "snooze:custom"
@@ -5228,6 +5349,7 @@ export default function Sidebar() {
key={threadKey}
id={threadKey}
contextDrag={isContextDrag}
environmentId={thread.environmentId}
disabled={
renamingThreadKey === threadKey ||
section === "working" ||
+30 -7
View File
@@ -1,4 +1,8 @@
import { type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
type EnvironmentId,
type ThreadId,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import {
@@ -23,6 +27,8 @@ import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
import { readLocalApi } from "~/localApi";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useOrchestrationCommand } from "../../state/use-orchestration-command";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { ProjectFavicon } from "../ProjectFavicon";
import {
WorkspaceBreadcrumb,
@@ -81,7 +87,11 @@ export const ChatHeader = memo(function ChatHeader({
() => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
[activeThreadEnvironmentId, activeThreadId],
);
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
const canOperateThread = useEnvironmentScope(
activeThreadEnvironmentId,
AuthOrchestrationOperateScope,
);
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
// Inline rename, keyed by thread: navigating away drops an in-progress
@@ -94,23 +104,36 @@ export const ChatHeader = memo(function ChatHeader({
} | null>(null);
if (
renaming !== null &&
(renaming.threadId !== activeThreadId || renaming.environmentId !== activeThreadEnvironmentId)
(renaming.threadId !== activeThreadId ||
renaming.environmentId !== activeThreadEnvironmentId ||
!canOperateThread)
) {
setRenaming(null);
}
const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
const renamingTitle =
canOperateThread &&
renaming?.threadId === activeThreadId &&
renaming.environmentId === activeThreadEnvironmentId
? renaming.title
: null;
const renameCommittedRef = useRef(false);
const startRename = useCallback(() => {
if (
!isServerThread ||
!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)
)
return;
renameCommittedRef.current = false;
setRenaming({
threadId: activeThreadId,
environmentId: activeThreadEnvironmentId,
threadId: activeThreadId,
title: activeThreadTitle,
});
}, [activeThreadEnvironmentId, activeThreadId, activeThreadTitle]);
}, [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, isServerThread]);
const commitRename = useCallback(
(title: string) => {
setRenaming(null);
if (!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)) return;
const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
if (resolution.action === "reject-empty") {
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
@@ -303,7 +326,7 @@ export const ChatHeader = memo(function ChatHeader({
aria-label={`Thread actions for ${activeThreadTitle}`}
aria-haspopup="menu"
onClick={openMenuFromTitle}
onDoubleClick={handleTitleDoubleClick}
onDoubleClick={canOperateThread ? handleTitleDoubleClick : undefined}
onBlur={cancelPendingTitleMenu}
className="group/thread-title inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
/>
@@ -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);
@@ -31,6 +31,7 @@ import {
AuthRelayReadScope,
AuthRelayWriteScope,
AuthReviewWriteScope,
AuthSourceControlWriteScope,
AuthStandardClientScopes,
AuthTerminalOperateScope,
type AuthClientSession,
@@ -259,6 +260,11 @@ const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
title: "Use terminals",
description: "Create terminals and send input to running shells.",
},
{
scope: AuthSourceControlWriteScope,
title: "Change source control",
description: "Commit, push, manage branches and repositories, and change pull requests.",
},
{
scope: AuthReviewWriteScope,
title: "Write reviews",
@@ -7,6 +7,7 @@ import {
} from "./threadActionMenu.logic";
const baseState: ThreadActionMenuState = {
canOperate: true,
branch: null,
projectFilter: null,
isPinned: false,
@@ -39,6 +40,57 @@ function allIds(state: ThreadActionMenuState): string[] {
}
describe("buildThreadActionMenuItems", () => {
it.each([false, true])(
"disables both lifecycle directions without permission (reversed: %s)",
(reversed) => {
const items = buildThreadActionMenuItems({
...baseState,
canOperate: false,
isPinned: reversed,
isSettled: reversed,
isSnoozed: reversed,
});
const expected = reversed
? [
"unpin",
"unsettle",
"unsnooze",
"rename",
"regenerate-title",
"auto-settle",
"archive",
"delete",
]
: [
"pin",
"settle",
"snooze",
"rename",
"regenerate-title",
"auto-settle",
"archive",
"delete",
];
expect(items.filter((item) => item.disabled).map((item) => item.id)).toEqual(expected);
expect(
items.find((item) => item.id === "snooze")?.children?.every((child) => child.disabled) ??
true,
).toBe(true);
},
);
it("preserves local actions and restores mutations after a grant", () => {
const denied = buildThreadActionMenuItems({ ...baseState, canOperate: false, branch: "main" });
expect(denied.filter((item) => !item.disabled).map((item) => item.id)).toEqual([
"new-thread-on-branch",
"mark-unread",
"copy",
"project-settings",
]);
const allowed = buildThreadActionMenuItems({ ...baseState, canOperate: true });
expect(allowed.every((item) => !item.disabled)).toBe(true);
});
it("hides lifecycle items when the environment lacks the capabilities", () => {
expect(
ids({
@@ -70,6 +70,7 @@ export function buildDraftActionMenuItems(options: {
}
export interface ThreadActionMenuState {
readonly canOperate: boolean;
readonly branch: string | null;
/**
* Project scoping for the thread list. Null on surfaces with no scoped
@@ -100,6 +101,19 @@ export interface ThreadActionMenuState {
readonly snoozePresets: ReadonlyArray<SnoozePreset>;
}
/** Local navigation, read markers, and copying remain available to read-only clients. */
export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean {
return ![
"new-thread-on-branch",
"project-settings",
"mark-unread",
"copy",
"copy-path",
"copy-branch",
"copy-thread-id",
].includes(action);
}
/**
* Single source for the per-thread action menu: the sidebar row's right-click
* menu and the chat header menu share labels, ordering, and capability gating.
@@ -108,7 +122,7 @@ export interface ThreadActionMenuState {
export function buildThreadActionMenuItems(
state: ThreadActionMenuState,
): ReadonlyArray<ContextMenuItem<ThreadActionMenuId>> {
return [
const items: ReadonlyArray<ContextMenuItem<ThreadActionMenuId>> = [
...(state.branch
? [
{
@@ -235,4 +249,17 @@ export function buildThreadActionMenuItems(
icon: "trash",
},
];
return state.canOperate
? items
: items.map((item) =>
threadActionRequiresOperate(item.id)
? {
...item,
disabled: true,
...(item.children
? { children: item.children.map((child) => ({ ...child, disabled: true })) }
: {}),
}
: item,
);
}
@@ -0,0 +1,221 @@
import {
AuthOrchestrationOperateScope,
EnvironmentId,
ThreadId,
type ContextMenuItem,
} from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { ThreadActionMenuId } from "../components/threadActionMenu.logic";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((complete) => {
resolve = complete;
});
return { promise, resolve };
}
const state = vi.hoisted(() => ({
granted: new Set<string>(),
effects: [] as string[],
completed: deferred<void>(),
show: vi.fn<
(
items: ReadonlyArray<ContextMenuItem<ThreadActionMenuId>>,
position: { x: number; y: number },
) => Promise<ThreadActionMenuId | null>
>(),
}));
function recordEffect(action: string) {
state.effects.push(action);
state.completed.resolve();
}
vi.mock("../components/CustomSnoozeDialog", () => ({ requestCustomSnooze: vi.fn() }));
vi.mock("react", () => ({
useCallback: (callback: unknown) => callback,
useMemo: (factory: () => unknown) => factory(),
}));
vi.mock("@tanstack/react-router", () => ({
useRouter: () => ({ navigate: async () => recordEffect("project-settings") }),
}));
vi.mock("../state/session", () => ({
readEnvironmentScope: (environmentId: string, scope: string) =>
scope === AuthOrchestrationOperateScope && state.granted.has(environmentId),
}));
vi.mock("../state/entities", () => ({
readEnvironmentSupportsAutoSettleOptOut: () => true,
readEnvironmentSupportsPinning: () => true,
readEnvironmentSupportsSettlement: () => true,
readEnvironmentSupportsSnooze: () => true,
readEnvironmentSupportsTitleRegeneration: () => true,
readThreadShell: () => ({
id: "thread",
environmentId: "secondary",
projectId: "project",
title: "Thread",
branch: "main",
worktreePath: null,
runtime: null,
latestRun: null,
}),
useProjects: () => [{ id: "project", environmentId: "secondary" }],
}));
vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "primary" }));
vi.mock("../state/threads", () => ({ threadEnvironment: { updateMetadata: "metadata" } }));
vi.mock("../state/use-atom-command", () => ({
useAtomCommand: () => async () => {
recordEffect("metadata");
return AsyncResult.success(undefined);
},
}));
vi.mock("../localApi", () => ({
readLocalApi: () => ({
contextMenu: { show: state.show, close: () => {} },
dialogs: {
confirm: async () => {
recordEffect("confirm");
return false;
},
},
}),
}));
vi.mock("../logicalProject", () => ({
deriveLogicalProjectKeyFromSettings: () => "project",
derivePhysicalProjectKey: () => "project",
selectProjectGroupingSettings: () => ({}),
}));
vi.mock("../sidebarProjectGrouping", () => ({
buildPhysicalToLogicalProjectKeyMap: () => new Map(),
}));
vi.mock("../uiStateStore", () => ({
useUiStateStore: (select: (store: unknown) => unknown) =>
select({
markThreadUnread: () => recordEffect("mark-unread"),
}),
}));
vi.mock("../components/ui/toast", () => ({
stackedThreadToast: (toast: unknown) => toast,
toastManager: { add: () => state.completed.resolve() },
}));
vi.mock("../components/Sidebar.snooze", () => ({
resolveSnoozePresets: () => [
{ id: "hour", label: "In 1 hour", whenLabel: "3 PM", snoozedUntil: "2099-01-01T00:00:00Z" },
],
snoozeWakeDescription: () => "later",
}));
vi.mock("./useCopyToClipboard", () => ({
useCopyToClipboard: () => ({ copyToClipboard: () => recordEffect("copy") }),
}));
vi.mock("./useHandleNewThread", () => ({
useNewThreadHandler: () => async () => recordEffect("draft"),
}));
vi.mock("./useSettings", () => ({
useClientSettings: (select: (settings: unknown) => unknown) =>
select({
confirmThreadDelete: true,
confirmThreadArchive: true,
timestampFormat: "12-hour",
}),
}));
vi.mock("./useThreadActions", () => ({
useThreadActions: () =>
Object.fromEntries(
[
"markThreadUnread",
"settleThread",
"unsettleThread",
"snoozeThread",
"unsnoozeThread",
"pinThread",
"confirmAndUnpinThread",
"archiveThread",
"deleteThread",
].map((action) => [
action,
async () => {
recordEffect(action === "markThreadUnread" ? "mark-unread" : action);
return AsyncResult.success(undefined);
},
]),
),
}));
import { useThreadActionMenu } from "./useThreadActionMenu";
const target = {
environmentId: EnvironmentId.make("secondary"),
threadId: ThreadId.make("thread"),
};
const position = { x: 10, y: 20 };
const createMenu = () =>
useThreadActionMenu({
threadRef: target,
projectCwd: "/project",
onStartRename: () => recordEffect("rename"),
});
beforeEach(() => {
state.granted = new Set(["primary"]);
state.effects = [];
state.completed = deferred<void>();
state.show.mockReset().mockResolvedValue(null);
});
describe("thread menu permissions", () => {
it("disables mutations for a denied secondary environment", () => {
createMenu().openMenu(position);
const items = state.show.mock.calls[0]![0];
expect(items.find((item) => item.id === "rename")?.disabled).toBe(true);
expect(items.find((item) => item.id === "delete")?.disabled).toBe(true);
expect(items.find((item) => item.id === "copy")?.disabled).not.toBe(true);
});
it("allows the target grant even when the primary environment is denied", () => {
state.granted = new Set(["secondary"]);
createMenu().openMenu(position);
expect(state.show.mock.calls[0]![0].find((item) => item.id === "rename")?.disabled).not.toBe(
true,
);
});
it("refreshes availability when a retained menu opener gains permission", () => {
const menu = createMenu();
menu.openMenu(position);
expect(state.show.mock.calls[0]![0].find((item) => item.id === "rename")?.disabled).toBe(true);
state.granted.add("secondary");
menu.openMenu(position);
expect(state.show.mock.calls[1]![0].find((item) => item.id === "rename")?.disabled).not.toBe(
true,
);
});
it.each(["rename", "regenerate-title", "delete", "pin", "settle", "archive"] as const)(
"%s rechecks after the native menu closes",
async (action) => {
state.granted.add("secondary");
const choice = deferred<ThreadActionMenuId | null>();
state.show.mockReturnValue(choice.promise);
createMenu().openMenu(position);
state.granted.delete("secondary");
choice.resolve(action);
await state.completed.promise;
expect(state.effects).toEqual([]);
},
);
it.each([
["new-thread-on-branch", "draft"],
["copy-thread-id", "copy"],
["mark-unread", "mark-unread"],
["project-settings", "project-settings"],
] as const)("keeps %s available without task permission", async (action, effect) => {
state.show.mockResolvedValue(action);
createMenu().openMenu(position);
await state.completed.promise;
expect(state.effects).toEqual([effect]);
});
});
+20 -3
View File
@@ -7,18 +7,24 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
type ScopedThreadRef,
type ThreadId,
} from "@t3tools/contracts";
import { useRouter } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import { resolveSnoozePresets } from "../components/Sidebar.snooze";
import {
buildThreadActionMenuItems,
threadActionRequiresOperate,
type ThreadActionMenuId,
} from "../components/threadActionMenu.logic";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { threadEnvironment } from "../state/threads";
import { useAtomCommand } from "../state/use-atom-command";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { readEnvironmentScope } from "../state/session";
import {
readEnvironmentSupportsAutoSettleOptOut,
readEnvironmentSupportsPinning,
@@ -94,7 +100,7 @@ export function useThreadActionMenu(input: {
deleteThread,
markThreadUnread,
} = useThreadActions();
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const handleNewThread = useNewThreadHandler();
@@ -142,6 +148,7 @@ export function useThreadActionMenu(input: {
const isRegeneratingTitle = thread.titleRegeneration != null;
const snoozePresets = resolveSnoozePresets(now, timestampFormat);
const items = buildThreadActionMenuItems({
canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
branch: thread.branch ?? null,
projectFilter: null,
isPinned: thread.pinnedAt != null,
@@ -157,6 +164,16 @@ export function useThreadActionMenu(input: {
const clicked = await settlePromise(() => api.contextMenu.show(items, position));
if (clicked._tag === "Failure" || clicked.value === null) return;
const action: ThreadActionMenuId = clicked.value;
if (
threadActionRequiresOperate(action) &&
!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
) {
failureToast(
"Thread action unavailable",
new Error("This connection cannot change threads."),
);
return;
}
if (action.startsWith("snooze:")) {
const preset =
action === "snooze:custom"
@@ -0,0 +1,354 @@
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
EnvironmentAuthorizationError,
EnvironmentId,
ProjectId,
ThreadId,
type ScopedThreadRef,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((complete) => {
resolve = complete;
});
return { promise, resolve };
}
const state = vi.hoisted(() => ({
scopes: new Map<string, Set<string>>(),
threads: [] as {
environmentId: EnvironmentId;
id: ThreadId;
projectId: ProjectId;
title: string;
worktreePath: string | null;
session: { status: "ready" | "stopped" } | null;
latestTurn: null;
}[],
requests: [] as { action: string; environmentId: string; input: { threadId?: string } }[],
localEffects: [] as string[],
confirm: vi.fn<(message: string) => Promise<boolean>>(),
toasts: [] as string[],
afterRequest: undefined as ((action: string) => void) | undefined,
sessionLookupFails: false,
}));
vi.mock("react", () => ({
useCallback: (callback: unknown) => callback,
useMemo: (factory: () => unknown) => factory(),
useRef: (current: unknown) => ({ current }),
}));
vi.mock("@tanstack/react-router", () => ({
useRouter: () => ({ state: { matches: [] }, navigate: async () => {} }),
}));
vi.mock("../state/session", () => ({
environmentSession: { sessionStateAtom: "session" },
readEnvironmentScope: (environmentId: string, scope: string) =>
state.scopes.get(environmentId)?.has(scope) === true,
}));
vi.mock("../state/use-atom-command", () => ({
useAtomCommand:
(action: string) =>
async (request: { environmentId: string; input: { threadId?: string } }) => {
state.requests.push({ action, ...request });
const scope =
action === "removeWorktree" ? AuthSourceControlWriteScope : AuthOrchestrationOperateScope;
if (!state.scopes.get(request.environmentId)?.has(scope)) {
return AsyncResult.failure(Cause.fail(new Error("Server denied the request")));
}
state.afterRequest?.(action);
return AsyncResult.success(undefined);
},
}));
vi.mock("../state/use-atom-query-runner", () => ({
useAtomQueryRunner: () => async (environmentId: string) =>
state.sessionLookupFails
? AsyncResult.failure(Cause.fail(new Error("Session lookup failed")))
: AsyncResult.success({
authenticated: true,
scopes: [...(state.scopes.get(environmentId) ?? [])],
}),
}));
vi.mock("../state/threads", () => ({
threadEnvironment: Object.fromEntries(
[
"archive",
"unarchive",
"delete",
"settle",
"unsettle",
"pin",
"unpin",
"reorderPin",
"snooze",
"unsnooze",
"stopSession",
].map((action) => [action, action]),
),
}));
vi.mock("../state/vcs", () => ({
vcsEnvironment: { removeWorktree: "removeWorktree", refreshStatus: "refreshStatus" },
}));
vi.mock("../state/entities", () => ({
readEnvironmentSupportsPinning: () => true,
readEnvironmentSupportsPinReorder: () => true,
readEnvironmentSupportsSettlement: () => true,
readEnvironmentSupportsSnooze: () => true,
readThreadShell: (ref: ScopedThreadRef) =>
state.threads.find(
(thread) => thread.environmentId === ref.environmentId && thread.id === ref.threadId,
) ?? null,
readThreadShells: () => state.threads,
readEnvironmentThreadRefs: (environmentId: EnvironmentId) =>
state.threads
.filter((thread) => thread.environmentId === environmentId)
.map((thread) => ({ environmentId, threadId: thread.id })),
readProject: () => ({ workspaceRoot: "/project" }),
}));
vi.mock("../components/Sidebar.logic", () => ({
getFallbackThreadIdAfterDelete: () => null,
pinOrderKeyBetween: () => "a",
}));
vi.mock("../composerDraftStore", () => ({
useComposerDraftStore: (select: (store: unknown) => unknown) =>
select({
clearDraftThread: () => state.localEffects.push("clear-draft"),
clearProjectDraftThreadById: () => state.localEffects.push("clear-project-draft"),
}),
}));
vi.mock("../terminalUiStateStore", () => ({
useTerminalUiStateStore: (select: (store: unknown) => unknown) =>
select({
clearTerminalUiState: () => state.localEffects.push("clear-terminal-ui"),
}),
}));
vi.mock("../uiStateStore", () => ({
useUiStateStore: (select: (store: unknown) => unknown) =>
select({
markThreadVisited: () => state.localEffects.push("mark-visited"),
}),
}));
vi.mock("../lib/archivedThreadsState", () => ({
refreshArchivedThreadsForEnvironment: () => state.localEffects.push("refresh-archive"),
}));
vi.mock("../lib/composerDraftUploads", () => ({
releaseComposerDraftUploads: () => state.localEffects.push("release-uploads"),
}));
vi.mock("../localApi", () => ({
readLocalApi: () => ({ dialogs: { confirm: state.confirm } }),
}));
vi.mock("../threadRoutes", () => ({
resolveThreadRouteRef: () => null,
buildThreadRouteParams: (ref: ScopedThreadRef) => ref,
}));
vi.mock("../components/ui/toast", () => ({
stackedThreadToast: (toast: unknown) => toast,
toastManager: {
add: (toast: { title?: string }) => {
if (toast.title) state.toasts.push(toast.title);
},
},
}));
vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => async () => {} }));
vi.mock("./useSettings", () => ({
useClientSettings: (select: (settings: unknown) => unknown) =>
select({
sidebarThreadSortOrder: "createdAt",
confirmThreadDelete: true,
confirmThreadUnpin: true,
}),
}));
import { useThreadActions } from "./useThreadActions";
const primary = EnvironmentId.make("primary");
const secondary = EnvironmentId.make("secondary");
const target = { environmentId: secondary, threadId: ThreadId.make("thread") };
type ThreadActions = ReturnType<typeof useThreadActions>;
const operations = [
{
name: "archive",
run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.archiveThread(ref),
},
{
name: "unarchive",
run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unarchiveThread(ref),
},
{
name: "settle",
run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.settleThread(ref),
},
{
name: "unsettle",
run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsettleThread(ref),
},
{
name: "snooze",
run: (actions: ThreadActions, ref: ScopedThreadRef) =>
actions.snoozeThread(ref, "2099-01-01T00:00:00Z"),
},
{
name: "unsnooze",
run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsnoozeThread(ref),
},
{ name: "pin", run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.pinThread(ref) },
{
name: "unpin",
run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unpinThread(ref),
},
{
name: "reorderPin",
run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.reorderPinnedThread(ref, "b"),
},
] as const;
beforeEach(() => {
state.scopes = new Map([
[primary, new Set([AuthOrchestrationOperateScope])],
[secondary, new Set<string>()],
]);
state.threads = [
{
environmentId: secondary,
id: target.threadId,
projectId: ProjectId.make("project"),
title: "Thread",
worktreePath: null,
session: null,
latestTurn: null,
},
];
state.requests = [];
state.localEffects = [];
state.confirm.mockReset().mockResolvedValue(true);
state.toasts = [];
state.afterRequest = undefined;
state.sessionLookupFails = false;
});
describe("thread action permissions", () => {
it.each(operations)("$name requires the target environment's grant", async ({ run }) => {
const result = await run(useThreadActions(), target);
expect(result._tag).toBe("Failure");
expect(state.requests).toEqual([]);
expect(state.localEffects).toEqual([]);
});
it.each(operations)("$name rechecks a retained callback after revocation", async ({ run }) => {
state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
const actions = useThreadActions();
state.scopes.get(secondary)!.clear();
await run(actions, target);
expect(state.requests).toEqual([]);
});
it.each(operations)(
"$name works after the target gains only task permission",
async ({ name, run }) => {
const actions = useThreadActions();
state.scopes.get(primary)!.clear();
state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
expect((await run(actions, target))._tag).toBe("Success");
expect(state.requests).toEqual([
expect.objectContaining({ action: name, environmentId: secondary }),
]);
},
);
it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
"%s blocks a forbidden confirmation",
async (action) => {
await useThreadActions()[action](target);
expect(state.confirm).not.toHaveBeenCalled();
expect(state.requests).toEqual([]);
},
);
it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
"%s rechecks after the confirmation",
async (action) => {
state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
const confirmation = deferred<boolean>();
state.confirm.mockReturnValue(confirmation.promise);
const result = useThreadActions()[action](target);
expect(state.confirm).toHaveBeenCalledOnce();
state.scopes.get(secondary)!.clear();
confirmation.resolve(true);
await result;
expect(state.requests).toEqual([]);
expect(state.localEffects).toEqual([]);
},
);
it("identifies the missing task scope when thread deletion is denied", async () => {
const result = await useThreadActions().deleteThread(target);
expect(result._tag).toBe("Failure");
if (result._tag !== "Failure") throw new Error("Expected permission denial");
const error = Cause.squash<unknown>(result.cause);
expect(error).toBeInstanceOf(EnvironmentAuthorizationError);
expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope });
expect(state.requests).toEqual([]);
expect(state.localEffects).toEqual([]);
});
it("deletes an archived thread only with its own environment's grant", async () => {
state.threads = [];
const actions = useThreadActions();
await actions.deleteThread(target);
expect(state.requests).toEqual([]);
state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
expect((await actions.deleteThread(target))._tag).toBe("Success");
expect(state.requests).toEqual([
expect.objectContaining({ action: "delete", environmentId: secondary }),
]);
});
it("stops before delete and local cleanup when permission is revoked during session stop", async () => {
state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
state.threads[0]!.session = { status: "ready" };
state.afterRequest = () => state.scopes.get(secondary)!.clear();
expect((await useThreadActions().deleteThread(target))._tag).toBe("Failure");
expect(state.requests.map((request) => request.action)).toEqual(["stopSession"]);
expect(state.localEffects).toEqual([]);
});
it.each([
{ reason: "without source-control permission", sessionLookupFails: false },
{ reason: "when the permission lookup fails", sessionLookupFails: true },
])("deletes a worktree thread and keeps its worktree $reason", async ({ sessionLookupFails }) => {
state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
state.threads[0]!.worktreePath = "/worktrees/thread";
state.sessionLookupFails = sessionLookupFails;
expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
expect(state.confirm).not.toHaveBeenCalled();
expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
expect(state.localEffects).toContain("clear-terminal-ui");
});
it("does not request worktree removal after its grant is revoked during delete", async () => {
state.scopes
.get(secondary)!
.add(AuthOrchestrationOperateScope)
.add(AuthSourceControlWriteScope);
state.threads[0]!.worktreePath = "/worktrees/thread";
state.afterRequest = () => state.scopes.get(secondary)!.delete(AuthSourceControlWriteScope);
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
try {
// The thread is already gone, so cleanup reports itself in a toast
// instead of failing the deletion.
const result = await useThreadActions().deleteThread(target);
expect(result._tag).toBe("Success");
expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
expect(state.toasts).toContain("Failed to delete worktree");
expect(state.localEffects).toContain("clear-terminal-ui");
} finally {
consoleError.mockRestore();
}
});
});
+81 -34
View File
@@ -7,7 +7,14 @@ import {
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
EnvironmentAuthorizationError,
EnvironmentId,
type ScopedThreadRef,
ThreadId,
} from "@t3tools/contracts";
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
@@ -17,6 +24,7 @@ import { useCallback, useMemo, useRef } from "react";
import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic";
import { useComposerDraftStore } from "../composerDraftStore";
import { environmentSession, readEnvironmentScope } from "../state/session";
import { terminalEnvironment } from "../state/terminal";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentServerConfigsAtom } from "../state/server";
@@ -49,6 +57,8 @@ import { useClientSettings } from "./useSettings";
import * as ThreadUndo from "./threadUndo";
import { showThreadUndoNotice } from "./showThreadUndoNotice";
import { useAtomCommand } from "../state/use-atom-command";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
export class ThreadArchiveBlockedError extends Schema.TaggedError<ThreadArchiveBlockedError>()(
"ThreadArchiveBlockedError",
@@ -243,49 +253,64 @@ export function useAcknowledgeThreadWoke() {
);
}
function threadOperationFailure(target: ScopedThreadRef) {
return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
? null
: AsyncResult.failure(
Cause.fail(
new EnvironmentAuthorizationError({
message: "This connection cannot change threads.",
requiredScope: AuthOrchestrationOperateScope,
}),
),
);
}
export function useThreadActions() {
const closeTerminal = useAtomCommand(terminalEnvironment.close);
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
const archiveThreadMutation = useOrchestrationCommand(threadEnvironment.archive, {
reportFailure: false,
});
const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
const unarchiveThreadMutation = useOrchestrationCommand(threadEnvironment.unarchive, {
reportFailure: false,
});
const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
const deleteThreadMutation = useOrchestrationCommand(threadEnvironment.delete, {
reportFailure: false,
});
const settleThreadMutation = useAtomCommand(threadEnvironment.settle, {
const settleThreadMutation = useOrchestrationCommand(threadEnvironment.settle, {
reportFailure: false,
});
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
reportFailure: false,
});
const pinThreadMutation = useAtomCommand(threadEnvironment.pin, {
const pinThreadMutation = useOrchestrationCommand(threadEnvironment.pin, {
reportFailure: false,
});
const unpinThreadMutation = useAtomCommand(threadEnvironment.unpin, {
const unpinThreadMutation = useOrchestrationCommand(threadEnvironment.unpin, {
reportFailure: false,
});
const setThreadAutoSettleMutation = useAtomCommand(threadEnvironment.setAutoSettle, {
const setThreadAutoSettleMutation = useOrchestrationCommand(threadEnvironment.setAutoSettle, {
reportFailure: false,
});
const reorderPinnedThreadMutation = useAtomCommand(threadEnvironment.reorderPin, {
const reorderPinnedThreadMutation = useOrchestrationCommand(threadEnvironment.reorderPin, {
reportFailure: false,
});
const reorderActiveThreadMutation = useAtomCommand(threadEnvironment.reorderActive, {
const reorderActiveThreadMutation = useOrchestrationCommand(threadEnvironment.reorderActive, {
reportFailure: false,
});
const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
const snoozeThreadMutation = useOrchestrationCommand(threadEnvironment.snooze, {
reportFailure: false,
});
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
reportFailure: false,
});
const markThreadUnread = useMarkThreadUnread();
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
});
const loadSessionState = useAtomQueryRunner(environmentSession.sessionStateAtom, {
reportFailure: false,
});
const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
reportFailure: false,
});
@@ -412,6 +437,8 @@ export function useThreadActions() {
const deleteThread = useCallback(
async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
const permissionFailure = threadOperationFailure(target);
if (permissionFailure) return permissionFailure;
const resolved = resolveThreadTarget(target);
if (!resolved) {
// Thread not in main store (e.g. archived thread) — dispatch delete directly.
@@ -456,13 +483,22 @@ export function useThreadActions() {
const environmentConfig = appAtomRegistry
.get(environmentServerConfigsAtom)
.get(threadRef.environmentId);
// A Scratch thread's folder is not a git worktree, and deleting the
// thread keeps its files.
const canDeleteWorktree =
const localApi = readLocalApi();
let canDeleteWorktree = false;
if (
orphanedWorktreePath !== null &&
threadProject !== null &&
!isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot);
const localApi = readLocalApi();
!isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot) &&
localApi
) {
const sessionResult = await loadSessionState(threadRef.environmentId);
const permissionFailure = threadOperationFailure(threadRef);
if (permissionFailure) return permissionFailure;
canDeleteWorktree =
sessionResult._tag === "Success" &&
sessionResult.value.authenticated &&
sessionResult.value.scopes?.includes(AuthSourceControlWriteScope) === true;
}
let shouldDeleteWorktree = false;
const environmentSettings = environmentConfig?.settings;
const automaticWorktreeCleanup = environmentSettings
@@ -493,11 +529,6 @@ export function useThreadActions() {
});
}
await closeTerminal({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, deleteHistory: true },
});
const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
const currentRouteThreadRef = getCurrentRouteThreadRef();
const shouldNavigateToFallback =
@@ -546,14 +577,26 @@ export function useThreadActions() {
return deleteResult;
}
const removeResult = await removeWorktree({
environmentId: threadRef.environmentId,
input: {
cwd: threadProject.workspaceRoot,
path: orphanedWorktreePath,
force: true,
},
});
const removeResult = readEnvironmentScope(
threadRef.environmentId,
AuthSourceControlWriteScope,
)
? await removeWorktree({
environmentId: threadRef.environmentId,
input: {
cwd: threadProject.workspaceRoot,
path: orphanedWorktreePath,
force: true,
},
})
: AsyncResult.failure(
Cause.fail(
new EnvironmentAuthorizationError({
message: "This connection can no longer remove worktrees.",
requiredScope: AuthSourceControlWriteScope,
}),
),
);
const refreshResult =
removeResult._tag === "Success"
? await refreshVcsStatus({
@@ -597,9 +640,9 @@ export function useThreadActions() {
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalUiState,
closeTerminal,
deleteThreadMutation,
getCurrentRouteThreadRef,
loadSessionState,
refreshVcsStatus,
removeWorktree,
router,
@@ -797,6 +840,8 @@ export function useThreadActions() {
const confirmAndUnpinThread = useCallback(
async (target: ScopedThreadRef) => {
const permissionFailure = threadOperationFailure(target);
if (permissionFailure) return permissionFailure;
const localApi = readLocalApi();
const resolved = resolveThreadTarget(target);
const confirmationResult = await requestThreadUnpinConfirmation({
@@ -930,6 +975,8 @@ export function useThreadActions() {
const confirmAndDeleteThread = useCallback(
async (target: ScopedThreadRef) => {
const permissionFailure = threadOperationFailure(target);
if (permissionFailure) return permissionFailure;
const localApi = readLocalApi();
const resolved = resolveThreadTarget(target);
@@ -20,6 +20,11 @@ const router = vi.hoisted(() => ({
navigate: vi.fn(async () => {}),
state: { matches: [{ params: {} as Record<string, string> }] },
}));
vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
vi.mock("../state/session", async (original) => ({
...(await original<typeof import("../state/session")>()),
readEnvironmentScope: () => true,
}));
vi.mock("react", async (original) => ({
...(await original<typeof import("react")>()),
useCallback: (callback: unknown) => callback,
@@ -0,0 +1,209 @@
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
EnvironmentId,
ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
scopes: new Map<string, Set<string>>(),
requests: [] as { action: string; environmentId: string | null }[],
}));
vi.mock("react", () => ({ useCallback: (callback: unknown) => callback }));
vi.mock("@effect/atom-react", () => ({
useAtomValue: () => ({ operation: null, error: null, isRunning: false }),
}));
vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
vi.mock("./session", () => ({
useEnvironmentScope: (environmentId: string, scope: string) =>
state.scopes.get(environmentId)?.has(scope) === true,
readEnvironmentScope: (environmentId: string, scope: string) =>
state.scopes.get(environmentId)?.has(scope) === true,
}));
vi.mock("./query", () => ({ useEnvironmentQuery: () => ({ refresh: () => {} }) }));
vi.mock("./use-atom-command", () => ({
useAtomCommand:
(command: { action: string; environmentId?: string }) =>
async (input: { environmentId?: string }) => {
state.requests.push({
action: command.action,
environmentId: input.environmentId ?? command.environmentId ?? null,
});
return AsyncResult.success({});
},
}));
vi.mock("./vcs", () => ({
vcsEnvironment: { init: { action: "init" }, pull: { action: "pull" }, status: () => "status" },
vcsActionManager: {
stateAtom: () => "state",
resetError: () => {},
track: (_registry: unknown, _target: unknown, _input: unknown, execute: () => unknown) =>
execute(),
runStackedAction: (scope: { environmentId: string }) => ({ action: "stack", ...scope }),
},
}));
vi.mock("./sourceControl", () => ({
sourceControlEnvironment: { publishRepository: { action: "publish" } },
}));
vi.mock("./git", () => ({
gitEnvironment: { preparePullRequestThread: { action: "prepare" } },
}));
import {
useGitStackedAction,
usePreparePullRequestThreadAction,
useSourceControlPublishRepositoryAction,
useVcsInitAction,
useVcsPullAction,
} from "./sourceControlActions";
const primary = EnvironmentId.make("primary");
const secondary = EnvironmentId.make("secondary");
const scope = { environmentId: secondary, cwd: "/repo" };
const threadId = ThreadId.make("thread");
const cases = [
{
name: "init",
create: () => {
const action = useVcsInitAction(scope);
return { isAllowed: action.isAllowed, run: () => action.run() };
},
},
{
name: "pull",
create: () => {
const action = useVcsPullAction(scope);
return { isAllowed: action.isAllowed, run: () => action.run() };
},
},
{
name: "stack",
create: () => {
const action = useGitStackedAction(scope);
return {
isAllowed: action.isAllowed,
run: () => action.run({ actionId: "action", action: "commit" }),
};
},
},
{
name: "publish",
create: () => {
const action = useSourceControlPublishRepositoryAction(scope);
return {
isAllowed: action.isAllowed,
run: () =>
action.run({
provider: "github",
repository: "owner/repo",
visibility: "private",
remoteName: "origin",
protocol: "ssh",
}),
};
},
},
{
name: "prepare",
create: () => {
const action = usePreparePullRequestThreadAction(scope);
return {
isAllowed: action.isAllowed,
run: () => action.run({ reference: "1", mode: "local" }),
};
},
},
] as const;
beforeEach(() => {
state.scopes = new Map([
[primary, new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope])],
[secondary, new Set<string>()],
]);
state.requests = [];
});
describe("source control callback grants", () => {
it.each(cases)("$name uses the selected environment's permission", async ({ create }) => {
const action = create();
expect(action.isAllowed).toBe(false);
expect((await action.run())._tag).toBe("Failure");
expect(state.requests).toEqual([]);
});
it.each(cases)("$name rejects a retained callback after revocation", async ({ create }) => {
state.scopes.get(secondary)!.add(AuthSourceControlWriteScope);
const action = create();
expect(action.isAllowed).toBe(true);
state.scopes.get(secondary)!.clear();
expect((await action.run())._tag).toBe("Failure");
expect(state.requests).toEqual([]);
expect(create().isAllowed).toBe(false);
});
it.each(cases)("$name accepts a retained callback after a grant", async ({ name, create }) => {
const action = create();
expect(action.isAllowed).toBe(false);
state.scopes.get(primary)!.clear();
state.scopes.get(secondary)!.add(AuthSourceControlWriteScope);
expect((await action.run())._tag).toBe("Success");
expect(state.requests).toEqual([{ action: name, environmentId: secondary }]);
expect(create().isAllowed).toBe(true);
});
});
describe("pull request worktree attachment permission", () => {
it.each([
["local", threadId, false, true],
["worktree", undefined, false, true],
["worktree", threadId, false, false],
["worktree", threadId, true, true],
] as const)(
"mode %s / thread %s / task grant %s",
async (mode, attachedThreadId, operate, allowed) => {
state.scopes.get(secondary)!.add(AuthSourceControlWriteScope);
if (operate) state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
const result = await usePreparePullRequestThreadAction(scope).run({
reference: "1",
mode,
...(attachedThreadId !== undefined ? { threadId: attachedThreadId } : {}),
});
expect(result._tag).toBe(allowed ? "Success" : "Failure");
expect(state.requests).toHaveLength(allowed ? 1 : 0);
if (result._tag === "Failure") {
expect(Cause.squash(result.cause)).toMatchObject({
requiredScope: AuthOrchestrationOperateScope,
});
}
},
);
it.each([false, true])(
"reads the fresh task grant before attaching a worktree: %s",
async (allowed) => {
state.scopes.get(secondary)!.add(AuthSourceControlWriteScope);
if (!allowed) state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
const action = usePreparePullRequestThreadAction(scope);
if (allowed) state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
else state.scopes.get(secondary)!.delete(AuthOrchestrationOperateScope);
const result = await action.run({ reference: "1", mode: "worktree", threadId });
expect(result._tag).toBe(allowed ? "Success" : "Failure");
expect(state.requests).toHaveLength(allowed ? 1 : 0);
},
);
it("still requires source-control permission when the task grant is present", async () => {
state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
const result = await usePreparePullRequestThreadAction(scope).run({
reference: "1",
mode: "worktree",
threadId,
});
expect(result._tag).toBe("Failure");
expect(state.requests).toEqual([]);
});
});
+44 -7
View File
@@ -9,12 +9,15 @@ import {
type VcsActionOperation,
type RunVcsStackedActionInput,
} from "@t3tools/client-runtime/state/vcs";
import type {
EnvironmentId,
GitResolvePullRequestResult,
SourceControlCloneProtocol,
SourceControlRepositoryVisibility,
ThreadId,
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
EnvironmentAuthorizationError,
type EnvironmentId,
type GitResolvePullRequestResult,
type SourceControlCloneProtocol,
type SourceControlRepositoryVisibility,
type ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
@@ -24,6 +27,7 @@ import { useCallback } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { gitEnvironment } from "./git";
import { useEnvironmentQuery } from "./query";
import { readEnvironmentScope, useEnvironmentScope } from "./session";
import { sourceControlEnvironment } from "./sourceControl";
import { useAtomCommand } from "./use-atom-command";
import { vcsActionManager, vcsEnvironment } from "./vcs";
@@ -45,11 +49,15 @@ interface SourceControlActionState<
R extends AtomCommandResult<unknown, unknown>,
> {
readonly isPending: boolean;
readonly isAllowed: boolean;
readonly error: unknown;
readonly run: (
...args: TArgs
) => Promise<
AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R> | VcsActionUnavailableError>
AtomCommandResult<
AtomCommandSuccess<R>,
AtomCommandFailure<R> | VcsActionUnavailableError | EnvironmentAuthorizationError
>
>;
readonly resetError: () => void;
}
@@ -73,6 +81,7 @@ function useAction<
readonly onSuccess?: () => void;
readonly managedExternally?: boolean;
}): SourceControlActionState<TArgs, R> {
const isAllowed = useEnvironmentScope(input.scope.environmentId, AuthSourceControlWriteScope);
const operation = ACTION_OPERATION[input.kind];
const state = useAtomValue(vcsActionManager.stateAtom(input.scope));
const ownsState = state.operation === operation;
@@ -83,6 +92,19 @@ function useAction<
const run = useCallback(
async (...args: TArgs) => {
if (
input.scope.environmentId === null ||
!readEnvironmentScope(input.scope.environmentId, AuthSourceControlWriteScope)
) {
return AsyncResult.failure<never, EnvironmentAuthorizationError>(
Cause.fail(
new EnvironmentAuthorizationError({
requiredScope: AuthSourceControlWriteScope,
message: "This connection cannot change source control.",
}),
),
);
}
const execute = async (): Promise<
AtomCommandResult<AtomCommandSuccess<R>, AtomCommandFailure<R>>
> => {
@@ -108,6 +130,7 @@ function useAction<
);
return {
isAllowed,
error: ownsState ? state.error : null,
isPending: ownsState && state.isRunning,
resetError,
@@ -307,6 +330,20 @@ export function usePreparePullRequestThreadAction(scope: SourceControlActionScop
),
);
}
if (
input.mode === "worktree" &&
input.threadId !== undefined &&
!readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
) {
return AsyncResult.failure<never, EnvironmentAuthorizationError>(
Cause.fail(
new EnvironmentAuthorizationError({
requiredScope: AuthOrchestrationOperateScope,
message: "This connection cannot change threads.",
}),
),
);
}
return preparePullRequestThread({
environmentId: target.environmentId,
input: {