[codex] Add issue subtree pause, cancel, and restore controls (#4332)

## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies.
> - This branch extends the issue control-plane so board operators can
pause, cancel, and later restore whole issue subtrees while keeping
descendant execution and wake behavior coherent.
> - That required new hold state in the database, shared contracts,
server routes/services, and issue detail UI controls so subtree actions
are durable and auditable instead of ad hoc.
> - While this branch was in flight, `master` advanced with new
environment lifecycle work, including a new `0065_environments`
migration.
> - Before opening the PR, this branch had to be rebased onto
`paperclipai/paperclip:master` without losing the existing
subtree-control work or leaving conflicting migration numbering behind.
> - This pull request rebases the subtree pause/cancel/restore feature
cleanly onto current `master`, renumbers the hold migration to
`0066_issue_tree_holds`, and preserves the full branch diff in a single
PR.
> - The benefit is that reviewers get one clean, mergeable PR for the
subtree-control feature instead of stale branch history with migration
conflicts.

## What Changed

- Added durable issue subtree hold data structures, shared
API/types/validators, server routes/services, and UI flows for subtree
pause, cancel, and restore operations.
- Added server and UI coverage for subtree previewing, hold
creation/release, dependency-aware scheduling under holds, and issue
detail subtree controls.
- Rebased the branch onto current `paperclipai/paperclip:master` and
renumbered the branch migration from `0065_issue_tree_holds` to
`0066_issue_tree_holds` so it no longer conflicts with upstream
`0065_environments`.
- Added a small follow-up commit that makes restore requests return `200
OK` explicitly while keeping pause/cancel hold creation at `201
Created`, and updated the route test to match that contract.

## Verification

- `pnpm --filter @paperclipai/db typecheck`
- `pnpm --filter @paperclipai/shared typecheck`
- `pnpm --filter @paperclipai/server typecheck`
- `pnpm --filter @paperclipai/ui typecheck`
- `cd server && pnpm exec vitest run
src/__tests__/issue-tree-control-routes.test.ts
src/__tests__/issue-tree-control-service.test.ts
src/__tests__/issue-tree-control-service-unit.test.ts
src/__tests__/heartbeat-dependency-scheduling.test.ts`
- `cd ui && pnpm exec vitest run src/components/IssueChatThread.test.tsx
src/pages/IssueDetail.test.tsx`

## Risks

- This is a broad cross-layer change touching DB/schema, shared
contracts, server orchestration, and UI; regressions are most likely
around subtree status restoration or wake suppression/resume edge cases.
- The migration was renumbered during PR prep to avoid the new upstream
`0065_environments` conflict. Reviewers should confirm the final
`0066_issue_tree_holds` ordering is the only hold-related migration that
lands.
- The issue-tree restore endpoint now responds with `200` instead of
relying on implicit behavior, which is semantically better for a restore
operation but still changes an API detail that clients or tests could
have assumed.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex coding agent in the Paperclip Codex runtime (GPT-5-class
tool-using coding model; exact deployment ID/context window is not
exposed inside this session).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta
2026-04-23 14:51:46 -05:00
committed by GitHub
parent 854fa81757
commit f98c348e2b
31 changed files with 4753 additions and 22 deletions

View File

@@ -1,6 +1,7 @@
import type {
AskUserQuestionsAnswer,
Approval,
CreateIssueTreeHold,
DocumentRevision,
FeedbackTargetType,
FeedbackTrace,
@@ -11,7 +12,11 @@ import type {
IssueDocument,
IssueLabel,
IssueThreadInteraction,
IssueTreeControlPreview,
IssueTreeHold,
IssueWorkProduct,
PreviewIssueTreeControl,
ReleaseIssueTreeHold,
UpsertIssueDocument,
} from "@paperclipai/shared";
import { api } from "./client";
@@ -79,6 +84,41 @@ export const issuesApi = {
api.post<Issue>(`/companies/${companyId}/issues`, data),
update: (id: string, data: Record<string, unknown>) =>
api.patch<IssueUpdateResponse>(`/issues/${id}`, data),
previewTreeControl: (id: string, data: PreviewIssueTreeControl) =>
api.post<IssueTreeControlPreview>(`/issues/${id}/tree-control/preview`, data),
createTreeHold: (id: string, data: CreateIssueTreeHold) =>
api.post<{ hold: IssueTreeHold; preview: IssueTreeControlPreview }>(`/issues/${id}/tree-holds`, data),
getTreeHold: (id: string, holdId: string) =>
api.get<IssueTreeHold>(`/issues/${id}/tree-holds/${holdId}`),
listTreeHolds: (
id: string,
filters?: {
status?: "active" | "released";
mode?: "pause" | "resume" | "cancel" | "restore";
includeMembers?: boolean;
},
) => {
const params = new URLSearchParams();
if (filters?.status) params.set("status", filters.status);
if (filters?.mode) params.set("mode", filters.mode);
if (filters?.includeMembers) params.set("includeMembers", "true");
const qs = params.toString();
return api.get<IssueTreeHold[]>(`/issues/${id}/tree-holds${qs ? `?${qs}` : ""}`);
},
getTreeControlState: (id: string) =>
api.get<{
activePauseHold: {
holdId: string;
rootIssueId: string;
issueId: string;
isRoot: boolean;
mode: "pause";
reason: string | null;
releasePolicy: { strategy: "manual" | "after_active_runs_finish"; note?: string | null } | null;
} | null;
}>(`/issues/${id}/tree-control/state`),
releaseTreeHold: (id: string, holdId: string, data: ReleaseIssueTreeHold) =>
api.post<IssueTreeHold>(`/issues/${id}/tree-holds/${holdId}/release`, data),
remove: (id: string) => api.delete<Issue>(`/issues/${id}`),
checkout: (id: string, agentId: string) =>
api.post<Issue>(`/issues/${id}/checkout`, {

View File

@@ -571,6 +571,73 @@ describe("IssueChatThread", () => {
});
});
it("shows deferred wake badge only for hold-deferred queued comments", () => {
const root = createRoot(container);
act(() => {
root.render(
<MemoryRouter>
<IssueChatThread
comments={[{
id: "comment-hold",
companyId: "company-1",
issueId: "issue-1",
authorAgentId: null,
authorUserId: "user-1",
body: "Need a quick update",
queueState: "queued",
queueReason: "hold",
createdAt: new Date("2026-04-06T12:00:00.000Z"),
updatedAt: new Date("2026-04-06T12:00:00.000Z"),
}]}
linkedRuns={[]}
timelineEvents={[]}
liveRuns={[]}
onAdd={async () => {}}
showComposer={false}
enableLiveTranscriptPolling={false}
/>
</MemoryRouter>,
);
});
expect(container.textContent).toContain("Deferred wake");
act(() => {
root.render(
<MemoryRouter>
<IssueChatThread
comments={[{
id: "comment-active-run",
companyId: "company-1",
issueId: "issue-1",
authorAgentId: null,
authorUserId: "user-1",
body: "Queue behind active run",
queueState: "queued",
queueReason: "active_run",
createdAt: new Date("2026-04-06T12:01:00.000Z"),
updatedAt: new Date("2026-04-06T12:01:00.000Z"),
}]}
linkedRuns={[]}
timelineEvents={[]}
liveRuns={[]}
onAdd={async () => {}}
showComposer={false}
enableLiveTranscriptPolling={false}
/>
</MemoryRouter>,
);
});
expect(container.textContent).toContain("Queued");
expect(container.textContent).not.toContain("Deferred wake");
act(() => {
root.unmount();
});
});
it("stores and restores the composer draft per issue key", () => {
vi.useFakeTimers();
const root = createRoot(container);

View File

@@ -227,6 +227,7 @@ interface IssueChatComposerProps {
mentions?: MentionOption[];
agentMap?: Map<string, Agent>;
composerDisabledReason?: string | null;
composerHint?: string | null;
issueStatus?: string;
}
@@ -265,6 +266,7 @@ interface IssueChatThreadProps {
suggestedAssigneeValue?: string;
mentions?: MentionOption[];
composerDisabledReason?: string | null;
composerHint?: string | null;
showComposer?: boolean;
showJumpToLatest?: boolean;
emptyMessage?: string;
@@ -1153,6 +1155,8 @@ function IssueChatUserMessage({ message }: { message: ThreadMessage }) {
const authorName = typeof custom.authorName === "string" ? custom.authorName : null;
const authorUserId = typeof custom.authorUserId === "string" ? custom.authorUserId : null;
const queued = custom.queueState === "queued" || custom.clientStatus === "queued";
const queueReason = typeof custom.queueReason === "string" ? custom.queueReason : null;
const queueBadgeLabel = queueReason === "hold" ? "\u23f8 Deferred wake" : "Queued";
const pending = custom.clientStatus === "pending";
const queueTargetRunId = typeof custom.queueTargetRunId === "string" ? custom.queueTargetRunId : null;
const [copied, setCopied] = useState(false);
@@ -1189,7 +1193,7 @@ function IssueChatUserMessage({ message }: { message: ThreadMessage }) {
{queued ? (
<div className="mb-1.5 flex items-center gap-2">
<span className="inline-flex items-center rounded-full border border-amber-400/60 bg-amber-100/70 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-amber-800 dark:border-amber-400/40 dark:bg-amber-500/20 dark:text-amber-200">
Queued
{queueBadgeLabel}
</span>
{queueTargetRunId && onInterruptQueued ? (
<Button
@@ -1910,6 +1914,7 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
mentions = [],
agentMap,
composerDisabledReason = null,
composerHint = null,
issueStatus,
}, forwardedRef) {
const api = useAui();
@@ -2068,6 +2073,12 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
contentClassName="min-h-[72px] max-h-[28dvh] overflow-y-auto pr-1 text-sm scrollbar-auto-hide"
/>
{composerHint ? (
<div className="inline-flex items-center rounded-full border border-border/70 bg-muted/30 px-2 py-1 text-[11px] text-muted-foreground">
{composerHint}
</div>
) : null}
<div className="flex flex-wrap items-center justify-end gap-3">
{(onImageUpload || onAttachImage) ? (
<div className="mr-auto flex items-center gap-3">
@@ -2168,6 +2179,7 @@ export function IssueChatThread({
suggestedAssigneeValue,
mentions = [],
composerDisabledReason = null,
composerHint = null,
showComposer = true,
showJumpToLatest,
emptyMessage,
@@ -2468,6 +2480,7 @@ export function IssueChatThread({
mentions={mentions}
agentMap={agentMap}
composerDisabledReason={composerDisabledReason}
composerHint={composerHint}
issueStatus={issueStatus}
/>
</div>

View File

@@ -52,10 +52,11 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible";
import { CircleDot, Plus, ArrowUpDown, Layers, Check, ChevronRight, List, ListTree, Columns3, User, Search } from "lucide-react";
import { CircleDot, Plus, ArrowUpDown, Layers, Check, ChevronRight, List, ListTree, Columns3, User, Search, CircleSlash2 } from "lucide-react";
import { KanbanBoard } from "./KanbanBoard";
import { buildIssueTree, countDescendants } from "../lib/issue-tree";
import { buildSubIssueDefaultsForViewer } from "../lib/subIssueDefaults";
import { statusBadge } from "../lib/status-colors";
import type { Issue, Project } from "@paperclipai/shared";
const ISSUE_SEARCH_DEBOUNCE_MS = 250;
const ISSUE_SEARCH_RESULT_LIMIT = 200;
@@ -208,6 +209,8 @@ interface IssuesListProps {
baseCreateIssueDefaults?: Record<string, unknown>;
createIssueLabel?: string;
enableRoutineVisibilityFilter?: boolean;
mutedIssueIds?: Set<string>;
issueBadgeById?: Map<string, string>;
onSearchChange?: (search: string) => void;
onUpdateIssue: (id: string, data: Record<string, unknown>) => void;
}
@@ -291,6 +294,8 @@ export function IssuesList({
baseCreateIssueDefaults,
createIssueLabel,
enableRoutineVisibilityFilter = false,
mutedIssueIds,
issueBadgeById,
onSearchChange,
onUpdateIssue,
}: IssuesListProps) {
@@ -945,6 +950,8 @@ export function IssuesList({
const useDeferredRowRendering = !(hasChildren && isExpanded);
const issueProject = issue.projectId ? projectById.get(issue.projectId) ?? null : null;
const parentIssue = issue.parentId ? issueById.get(issue.parentId) ?? null : null;
const issueBadge = issueBadgeById?.get(issue.id);
const isMutedIssue = mutedIssueIds?.has(issue.id) === true;
const assigneeUserProfile = issue.assigneeUserId
? companyUserProfileMap.get(issue.assigneeUserId) ?? null
: null;
@@ -979,11 +986,32 @@ export function IssuesList({
<IssueRow
issue={issue}
issueLinkState={issueLinkState}
titleSuffix={hasChildren && !isExpanded ? (
<span className="ml-1.5 text-xs text-muted-foreground">
({totalDescendants} sub-task{totalDescendants !== 1 ? "s" : ""})
</span>
) : undefined}
titleSuffix={(
<>
{hasChildren && !isExpanded ? (
<span className="ml-1.5 text-xs text-muted-foreground">
({totalDescendants} sub-task{totalDescendants !== 1 ? "s" : ""})
</span>
) : null}
{issueBadge ? (
issueBadge === "Paused" ? (
<span
className={cn("ml-1.5 inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium", statusBadge.paused)}
aria-label="Paused"
title="Paused"
>
<CircleSlash2 className="h-3 w-3" />
Paused
</span>
) : (
<span className="ml-1.5 inline-flex items-center rounded-full border border-amber-500/40 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300">
{issueBadge}
</span>
)
) : null}
</>
)}
className={isMutedIssue ? "opacity-70" : undefined}
mobileLeading={
hasChildren ? (
<button type="button" onClick={toggleCollapse}>

View File

@@ -30,6 +30,7 @@ export interface IssueChatComment extends IssueComment {
clientStatus?: "pending" | "queued";
queueState?: "queued";
queueTargetRunId?: string | null;
queueReason?: "hold" | "active_run" | "other";
}
export interface IssueChatLinkedRun {
@@ -315,6 +316,7 @@ function createCommentMessage(args: {
clientStatus: comment.clientStatus ?? null,
queueState: comment.queueState ?? null,
queueTargetRunId: comment.queueTargetRunId ?? null,
queueReason: comment.queueReason ?? null,
interruptedRunId: comment.interruptedRunId ?? null,
};

File diff suppressed because it is too large Load Diff

View File

@@ -65,6 +65,7 @@ import { IssueChatThread, type IssueChatComposerHandle } from "../components/Iss
import { IssueContinuationHandoff } from "../components/IssueContinuationHandoff";
import { IssueDocumentsSection } from "../components/IssueDocumentsSection";
import { IssuesList } from "../components/IssuesList";
import { AgentIcon } from "../components/AgentIconPicker";
import { IssueReferenceActivitySummary } from "../components/IssueReferenceActivitySummary";
import { IssueRelatedWorkPanel } from "../components/IssueRelatedWorkPanel";
import { IssueProperties } from "../components/IssueProperties";
@@ -85,6 +86,15 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sh
import { Skeleton } from "@/components/ui/skeleton";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { formatIssueActivityAction } from "@/lib/activity-format";
import { buildIssuePropertiesPanelKey } from "../lib/issue-properties-panel-key";
import { shouldRenderRichSubIssuesSection } from "../lib/issue-detail-subissues";
@@ -102,11 +112,14 @@ import {
MessageSquare,
MoreHorizontal,
MoreVertical,
PauseCircle,
Paperclip,
PlayCircle,
Plus,
Repeat,
SlidersHorizontal,
Trash2,
XCircle,
} from "lucide-react";
import {
getClosedIsolatedExecutionWorkspaceMessage,
@@ -122,6 +135,7 @@ import {
type IssueThreadInteraction,
type RequestConfirmationInteraction,
type SuggestTasksInteraction,
type IssueTreeControlMode,
} from "@paperclipai/shared";
type CommentReassignment = IssueCommentReassignment;
@@ -132,10 +146,32 @@ type IssueDetailComment = (IssueComment | OptimisticIssueComment) & {
interruptedRunId?: string | null;
queueState?: "queued";
queueTargetRunId?: string | null;
queueReason?: "hold" | "active_run" | "other";
};
const FEEDBACK_TERMS_URL = import.meta.env.VITE_FEEDBACK_TERMS_URL?.trim() || "https://paperclip.ing/tos";
const ISSUE_COMMENT_PAGE_SIZE = 50;
const TREE_CONTROL_MODE_LABEL: Record<IssueTreeControlMode, string> = {
pause: "Pause subtree",
resume: "Resume subtree",
cancel: "Cancel subtree",
restore: "Restore subtree",
};
const TREE_CONTROL_MODE_HELP_TEXT: Record<IssueTreeControlMode, string> = {
pause: "Pause active execution in this issue subtree until an explicit resume.",
resume: "Release the active subtree pause hold so held work can continue.",
cancel: "Cancel non-terminal issues in this subtree and stop queued/running work where possible.",
restore: "Restore issues cancelled by this subtree operation so work can resume.",
};
function treeControlPreviewErrorCopy(error: unknown): string {
if (error instanceof ApiError) {
if (error.status === 403) return "Only board users can preview subtree controls.";
if (error.status === 409) return "Preview is stale because subtree hold state changed. Retry to refresh.";
if (error.status === 422) return "This subtree action is currently invalid for the selected issues.";
}
return error instanceof Error ? error.message : "Unable to load preview.";
}
function resolveRunningIssueRun(
activeRun: ActiveRunForIssue | null | undefined,
@@ -532,6 +568,8 @@ type IssueDetailChatTabProps = {
suggestedAssigneeValue: string;
mentions: MentionOption[];
composerDisabledReason: string | null;
composerHint: string | null;
queuedCommentReason: "hold" | "active_run" | "other";
onVote: (
commentId: string,
vote: "up" | "down",
@@ -582,6 +620,8 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
suggestedAssigneeValue,
mentions,
composerDisabledReason,
composerHint,
queuedCommentReason,
onVote,
onAdd,
onImageUpload,
@@ -695,11 +735,20 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
...nextComment,
queueState: "queued" as const,
queueTargetRunId: runningIssueRun?.id ?? nextComment.queueTargetRunId ?? null,
queueReason: queuedCommentReason,
};
}
return nextComment;
});
}, [comments, liveRunIds, locallyQueuedCommentRunIds, resolvedActivity, resolvedLinkedRuns, runningIssueRun]);
}, [
comments,
liveRunIds,
locallyQueuedCommentRunIds,
queuedCommentReason,
resolvedActivity,
resolvedLinkedRuns,
runningIssueRun,
]);
const timelineEvents = useMemo(
() => extractIssueTimelineEvents(resolvedActivity),
[resolvedActivity],
@@ -746,6 +795,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
suggestedAssigneeValue={suggestedAssigneeValue}
mentions={mentions}
composerDisabledReason={composerDisabledReason}
composerHint={composerHint}
onVote={onVote}
onAdd={onAdd}
imageUploadHandler={onImageUpload}
@@ -974,6 +1024,11 @@ export function IssueDetail() {
const [attachmentDragActive, setAttachmentDragActive] = useState(false);
const [galleryOpen, setGalleryOpen] = useState(false);
const [galleryIndex, setGalleryIndex] = useState(0);
const [treeControlOpen, setTreeControlOpen] = useState(false);
const [treeControlMode, setTreeControlMode] = useState<IssueTreeControlMode>("pause");
const [treeControlReason, setTreeControlReason] = useState("");
const [treeControlWakeAgentsOnResume, setTreeControlWakeAgentsOnResume] = useState(false);
const [treeControlCancelConfirmed, setTreeControlCancelConfirmed] = useState(false);
const [optimisticComments, setOptimisticComments] = useState<OptimisticIssueComment[]>([]);
const [locallyQueuedCommentRunIds, setLocallyQueuedCommentRunIds] = useState<Map<string, string>>(() => new Map());
const [pendingCommentComposerFocusKey, setPendingCommentComposerFocusKey] = useState(0);
@@ -1113,6 +1168,16 @@ export function IssueDetail() {
enabled: !!selectedCompanyId,
});
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
const { data: boardAccess } = useQuery({
queryKey: queryKeys.access.currentBoardAccess,
queryFn: () => accessApi.getCurrentBoardAccess(),
enabled: !!session?.user?.id,
retry: false,
});
const canManageTreeControl = Boolean(
selectedCompanyId
&& boardAccess?.companyIds?.includes(selectedCompanyId),
);
const { data: feedbackVotes } = useQuery({
queryKey: queryKeys.issues.feedbackVotes(issueId!),
queryFn: () => issuesApi.listFeedbackVotes(issueId!),
@@ -1146,6 +1211,54 @@ export function IssueDetail() {
[issuePluginDetailSlots],
);
const activePluginTab = issuePluginTabItems.find((item) => item.value === detailTab) ?? null;
const {
data: treeControlPreview,
isFetching: treeControlPreviewLoading,
error: treeControlPreviewError,
refetch: refetchTreeControlPreview,
} = useQuery({
queryKey: [
"issues",
"tree-control-preview",
issueId ?? "pending",
treeControlMode,
],
queryFn: () =>
issuesApi.previewTreeControl(issueId!, {
mode: treeControlMode,
releasePolicy: {
strategy: "manual",
},
}),
enabled: treeControlOpen && !!issueId && canManageTreeControl,
staleTime: 0,
retry: false,
});
const { data: treeControlState } = useQuery({
queryKey: ["issues", "tree-control-state", issueId ?? "pending"],
queryFn: () => issuesApi.getTreeControlState(issueId!),
enabled: !!issueId && canManageTreeControl,
retry: false,
});
const { data: activeRootPauseHolds = [] } = useQuery({
queryKey: ["issues", "tree-holds", issueId ?? "pending", "active-pause-with-members"],
queryFn: () =>
issuesApi.listTreeHolds(issueId!, {
status: "active",
mode: "pause",
includeMembers: true,
}),
enabled: !!issueId && treeControlState?.activePauseHold?.isRoot === true,
});
const { data: activeCancelHolds = [] } = useQuery({
queryKey: ["issues", "tree-holds", issueId ?? "pending", "active-cancel"],
queryFn: () =>
issuesApi.listTreeHolds(issueId!, {
status: "active",
mode: "cancel",
}),
enabled: !!issueId && canManageTreeControl,
});
const agentMap = useMemo(() => {
const map = new Map<string, Agent>();
@@ -1384,6 +1497,81 @@ export function IssueDetail() {
}
},
});
const executeTreeControl = useMutation({
mutationFn: async () => {
if (treeControlMode === "resume") {
const pauseHoldId = treeControlState?.activePauseHold?.holdId;
if (!pauseHoldId) {
throw new Error("No active subtree pause hold is available to resume.");
}
const releasedHold = await issuesApi.releaseTreeHold(issueId!, pauseHoldId, {
reason: treeControlReason.trim() || null,
metadata: {
wakeAgents: treeControlWakeAgentsOnResume,
},
});
return { kind: "release" as const, hold: releasedHold };
}
const created = await issuesApi.createTreeHold(issueId!, {
mode: treeControlMode,
reason: treeControlReason.trim() || null,
releasePolicy: {
strategy: "manual",
...(treeControlMode === "pause" ? { note: "full_pause" } : {}),
},
...(treeControlMode === "restore"
? { metadata: { wakeAgents: treeControlWakeAgentsOnResume } }
: {}),
});
return { kind: "create" as const, hold: created.hold, preview: created.preview };
},
onSuccess: async (result) => {
const modeLabel = TREE_CONTROL_MODE_LABEL[result.hold.mode];
const cancelCount = result.preview?.totals.activeRuns ?? 0;
pushToast({
title: result.kind === "release"
? "Subtree resumed"
: result.hold.mode === "pause"
? "Subtree paused"
: `${modeLabel} applied`,
body: result.kind === "release"
? (result.hold.releaseReason?.trim() || "Active subtree pause released.")
: result.hold.mode === "pause"
? `Subtree paused. ${cancelCount} run${cancelCount === 1 ? "" : "s"} cancelled.`
: result.hold.reason?.trim()
? result.hold.reason
: "Subtree control applied.",
});
setTreeControlOpen(false);
setTreeControlReason("");
setTreeControlWakeAgentsOnResume(false);
setTreeControlCancelConfirmed(false);
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!) }),
queryClient.invalidateQueries({ queryKey: queryKeys.issues.liveRuns(issueId!) }),
queryClient.invalidateQueries({ queryKey: queryKeys.issues.activeRun(issueId!) }),
queryClient.invalidateQueries({ queryKey: queryKeys.issues.runs(issueId!) }),
queryClient.invalidateQueries({ queryKey: ["issues", "tree-control-state", issueId ?? "pending"] }),
queryClient.invalidateQueries({ queryKey: ["issues", "tree-holds", issueId ?? "pending"] }),
queryClient.invalidateQueries({ queryKey: ["issues", "tree-control-preview", issueId ?? "pending"] }),
]);
if (selectedCompanyId) {
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(selectedCompanyId) }),
...(issue?.id
? [queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByParent(selectedCompanyId, issue.id) })]
: []),
]);
}
},
onError: (err) => {
pushToast({
title: "Unable to apply subtree control",
body: err instanceof Error ? err.message : "Please try again.",
tone: "error",
});
},
});
const handleIssuePropertiesUpdate = useCallback((data: Record<string, unknown>) => {
updateIssue.mutate(data);
}, [updateIssue.mutate]);
@@ -2372,6 +2560,60 @@ export function IssueDetail() {
await answerInteraction.mutateAsync({ interaction, answers });
}, [answerInteraction]);
const treePreviewAffectedIssues = useMemo(
() => (treeControlPreview?.issues ?? []).filter((candidate) => !candidate.skipped),
[treeControlPreview],
);
const treePreviewDisplayIssues = useMemo(
() => {
const previewIssues = treeControlPreview?.issues ?? [];
if (treeControlMode !== "pause") {
return previewIssues.filter((candidate) => !candidate.skipped);
}
return previewIssues.filter((candidate) => !candidate.skipped || candidate.skipReason === "terminal_status");
},
[treeControlMode, treeControlPreview],
);
const activePauseHold = treeControlState?.activePauseHold ?? null;
const activeRootPauseHoldsForDisplay = useMemo(
() => activePauseHold?.isRoot === true ? activeRootPauseHolds : [],
[activePauseHold?.isRoot, activeRootPauseHolds],
);
const heldIssueIds = useMemo(() => {
const ids = new Set<string>();
for (const hold of activeRootPauseHoldsForDisplay) {
for (const member of hold.members ?? []) {
if (member.skipped) continue;
ids.add(member.issueId);
}
}
return ids;
}, [activeRootPauseHoldsForDisplay]);
const mutedChildIssueIds = useMemo(() => {
const ids = new Set<string>();
for (const child of childIssues) {
if (heldIssueIds.has(child.id)) ids.add(child.id);
}
return ids;
}, [childIssues, heldIssueIds]);
const childPauseBadgeById = useMemo(() => {
const badges = new Map<string, string>();
for (const child of childIssues) {
if (!heldIssueIds.has(child.id)) continue;
badges.set(child.id, "Paused");
}
return badges;
}, [childIssues, heldIssueIds]);
const activePauseHoldRoot = useMemo(() => {
if (!activePauseHold) return null;
if (activePauseHold.rootIssueId === issue?.id) return issue ?? null;
return issue?.ancestors?.find((ancestor) => ancestor.id === activePauseHold.rootIssueId) ?? null;
}, [activePauseHold, issue]);
const activeRootPauseHold = useMemo(
() => activeRootPauseHoldsForDisplay.find((hold) => hold.id === activePauseHold?.holdId) ?? null,
[activePauseHold?.holdId, activeRootPauseHoldsForDisplay],
);
if (isLoading) return <IssueDetailLoadingState headerSeed={issueHeaderSeed} />;
if (error) return <p className="text-sm text-destructive">{error.message}</p>;
if (!issue) return null;
@@ -2408,6 +2650,55 @@ export function IssueDetail() {
};
const hasAttachments = attachmentList.length > 0;
const treePreviewWarnings = treeControlPreview?.warnings ?? [];
const heldDescendantCount = activeRootPauseHold?.members?.filter((member) => member.depth > 0 && !member.skipped).length
?? Math.max(heldIssueIds.size - 1, 0);
const canShowSubtreeControls = canManageTreeControl && childIssues.length > 0;
const canResumeSubtree = canShowSubtreeControls && activePauseHold?.isRoot === true;
const canRestoreSubtree = canShowSubtreeControls && activeCancelHolds.length > 0;
const previewAffectedIssueCount = treePreviewAffectedIssues.length;
const previewAffectedAgentCount = treeControlPreview?.totals.affectedAgents ?? 0;
const treeControlPrimaryButtonLabel =
treeControlMode === "pause"
? "Pause and stop work"
: treeControlMode === "cancel"
? `Cancel ${previewAffectedIssueCount} issues`
: treeControlMode === "restore"
? `Restore ${previewAffectedIssueCount} issues`
: "Resume subtree";
const treePreviewAffectedIssueRows = treePreviewDisplayIssues.map((candidate) => ({
candidate,
issue: {
...issue,
id: candidate.id,
identifier: candidate.identifier,
title: candidate.title,
status: candidate.status,
parentId: candidate.parentId,
assigneeAgentId: candidate.assigneeAgentId,
assigneeUserId: candidate.assigneeUserId,
executionRunId: candidate.activeRun?.id ?? null,
} satisfies Issue,
}));
const treePreviewAffectedAgentRows = (treeControlPreview?.affectedAgents ?? [])
.map((previewAgent) => ({
...previewAgent,
agent: agentMap.get(previewAgent.agentId) ?? null,
}))
.sort((a, b) => (a.agent?.name ?? a.agentId).localeCompare(b.agent?.name ?? b.agentId));
const pausedComposerHint = activePauseHold
? (
issue.assigneeAgentId
? `Sending this comment will wake ${agentMap.get(issue.assigneeAgentId)?.name ?? "the assignee"} for triage while the subtree remains paused.`
: "Assign an agent to wake them for triage while the subtree remains paused."
)
: null;
const composerHint = pausedComposerHint;
const queuedCommentReason: "hold" | "active_run" | "other" = "active_run";
const canApplyTreeControl =
Boolean(treeControlPreview)
&& !treeControlPreviewLoading
&& (treeControlMode !== "cancel" || (treeControlReason.trim().length > 0 && treeControlCancelConfirmed));
const attachmentUploadButton = (
<>
<input
@@ -2473,6 +2764,73 @@ export function IssueDetail() {
This issue is hidden
</div>
)}
{activePauseHold && (
<div className="rounded-md border border-amber-500/35 bg-amber-500/10 p-3 text-sm text-amber-800 dark:text-amber-200">
{activePauseHold.isRoot ? (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">Subtree pause is active.</span>
<span className="text-xs text-amber-900/80 dark:text-amber-100/80">
Root and descendant execution is held until resume. Human comments can still wake assignees for triage.
</span>
</div>
<div className="text-xs text-amber-900/80 dark:text-amber-100/80">
{heldDescendantCount} descendant{heldDescendantCount === 1 ? "" : "s"} held
{activeRootPauseHold?.createdAt ? ` · started ${relativeTime(activeRootPauseHold.createdAt)}` : ""}
</div>
{canShowSubtreeControls ? (
<div className="flex flex-wrap items-center gap-2">
<Button
size="sm"
onClick={() => {
setTreeControlMode("resume");
setTreeControlWakeAgentsOnResume(true);
setTreeControlOpen(true);
}}
>
Resume subtree
</Button>
<Button
variant="outline"
size="sm"
onClick={() => {
setTreeControlMode("resume");
setTreeControlWakeAgentsOnResume(true);
setTreeControlOpen(true);
}}
>
View affected ({heldDescendantCount})
</Button>
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive"
onClick={() => {
setTreeControlMode("cancel");
setTreeControlCancelConfirmed(false);
setTreeControlOpen(true);
}}
>
Cancel subtree...
</Button>
</div>
) : null}
</div>
) : (
<div className="text-xs">
This issue is paused by ancestor{" "}
{activePauseHoldRoot?.identifier ? (
<Link to={createIssueDetailPath(activePauseHoldRoot.identifier)} className="underline">
{activePauseHoldRoot.identifier}
</Link>
) : (
activePauseHold.rootIssueId.slice(0, 8)
)}
. Resume from the root issue to deliver deferred work.
</div>
)}
</div>
)}
<div className="space-y-3">
<div className="flex items-center gap-2 min-w-0 flex-wrap">
@@ -2601,11 +2959,80 @@ export function IssueDetail() {
<Popover open={moreOpen} onOpenChange={setMoreOpen}>
<PopoverTrigger asChild>
<Button variant="ghost" size="icon-xs" className="shrink-0">
<Button
variant="ghost"
size="icon-xs"
className="shrink-0"
aria-label="More issue actions"
title="More issue actions"
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setMoreOpen(true);
}
}}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-44 p-1" align="end">
<PopoverContent className="w-52 p-1" align="end">
{canShowSubtreeControls ? (
<>
<button
className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"
onClick={() => {
setTreeControlMode("pause");
setTreeControlCancelConfirmed(false);
setTreeControlOpen(true);
setMoreOpen(false);
}}
>
<PauseCircle className="h-3 w-3" />
Pause subtree...
</button>
{canResumeSubtree ? (
<button
className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"
onClick={() => {
setTreeControlMode("resume");
setTreeControlWakeAgentsOnResume(true);
setTreeControlOpen(true);
setMoreOpen(false);
}}
>
<PlayCircle className="h-3 w-3" />
Resume subtree
</button>
) : null}
<button
className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-destructive"
onClick={() => {
setTreeControlMode("cancel");
setTreeControlCancelConfirmed(false);
setTreeControlOpen(true);
setMoreOpen(false);
}}
>
<XCircle className="h-3 w-3" />
Cancel subtree...
</button>
{canRestoreSubtree ? (
<button
className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"
onClick={() => {
setTreeControlMode("restore");
setTreeControlWakeAgentsOnResume(false);
setTreeControlCancelConfirmed(false);
setTreeControlOpen(true);
setMoreOpen(false);
}}
>
<Repeat className="h-3 w-3" />
Restore subtree...
</button>
) : null}
</>
) : null}
<button
className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-destructive"
onClick={() => {
@@ -2701,6 +3128,8 @@ export function IssueDetail() {
agents={agents}
projects={projects}
liveIssueIds={liveIssueIds}
mutedIssueIds={mutedChildIssueIds}
issueBadgeById={childPauseBadgeById}
projectId={issue.projectId ?? undefined}
viewStateKey={`paperclip:issue-detail:${issue.id}:subissues-view`}
issueLinkState={resolvedIssueDetailState ?? location.state}
@@ -2940,6 +3369,8 @@ export function IssueDetail() {
suggestedAssigneeValue={suggestedAssigneeValue}
mentions={mentionOptions}
composerDisabledReason={commentComposerDisabledReason}
composerHint={composerHint}
queuedCommentReason={queuedCommentReason}
onVote={handleCommentVote}
onAdd={handleChatAdd}
onImageUpload={handleCommentImageUpload}
@@ -2994,6 +3425,157 @@ export function IssueDetail() {
)}
</Tabs>
<Dialog open={treeControlOpen} onOpenChange={setTreeControlOpen}>
<DialogContent className="flex max-h-[calc(100dvh-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[560px]">
<DialogHeader className="border-b border-border/60 px-6 pb-4 pr-12 pt-6">
<DialogTitle>{TREE_CONTROL_MODE_LABEL[treeControlMode]}</DialogTitle>
<DialogDescription>
{TREE_CONTROL_MODE_HELP_TEXT[treeControlMode]}
</DialogDescription>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto overscroll-contain px-6 py-4">
{treeControlMode === "cancel" ? (
<div className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-xs text-destructive">
Cancelling a subtree is destructive. Non-terminal issues will be marked cancelled, and running or queued work will be interrupted where possible.
</div>
) : null}
<div className="space-y-1.5">
<label className="text-xs text-muted-foreground">
{treeControlMode === "cancel" ? "Reason (required)" : "Reason (optional)"}
</label>
<Textarea
value={treeControlReason}
onChange={(event) => setTreeControlReason(event.target.value)}
placeholder="Explain why this subtree control is being applied..."
className="min-h-[88px]"
/>
</div>
{(treeControlMode === "resume" || treeControlMode === "restore") ? (
<div className="space-y-2">
<label className="flex items-start gap-2 text-sm">
<input
type="checkbox"
className="mt-0.5"
disabled={previewAffectedAgentCount === 0}
checked={treeControlWakeAgentsOnResume}
onChange={(event) => setTreeControlWakeAgentsOnResume(event.target.checked)}
/>
<span>
<span className="block font-medium">Wake affected agents ({previewAffectedAgentCount})</span>
<span className="text-xs text-muted-foreground">
{previewAffectedAgentCount === 0
? "No assigned agents are eligible to wake from this preview."
: "Wake assigned agents after this operation completes."}
</span>
</span>
</label>
{treeControlWakeAgentsOnResume && treePreviewAffectedAgentRows.length > 0 ? (
<div className="max-h-32 space-y-1 overflow-y-auto overscroll-contain">
{treePreviewAffectedAgentRows.map(({ agentId, agent }) => (
<div key={agentId} className="flex items-center gap-2 rounded-sm px-1 py-1 text-sm hover:bg-accent/50">
<span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background">
<AgentIcon icon={agent?.icon} className="h-3.5 w-3.5 text-muted-foreground" />
</span>
<span className="min-w-0 flex-1 truncate">{agent?.name ?? agentId.slice(0, 8)}</span>
</div>
))}
</div>
) : null}
</div>
) : null}
{treeControlMode === "cancel" ? (
<label className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-sm">
<input
type="checkbox"
className="mt-0.5"
checked={treeControlCancelConfirmed}
onChange={(event) => setTreeControlCancelConfirmed(event.target.checked)}
/>
<span>I understand this will cancel {previewAffectedIssueCount} issues.</span>
</label>
) : null}
<div className="space-y-2">
{treeControlPreviewLoading ? (
<div className="space-y-2">
<Skeleton className="h-4 w-40" />
<Skeleton className="h-3 w-full" />
<Skeleton className="h-3 w-4/5" />
<Skeleton className="h-3 w-2/3" />
</div>
) : treeControlPreviewError ? (
<div className="space-y-2">
<p className="text-xs text-destructive">{treeControlPreviewErrorCopy(treeControlPreviewError)}</p>
<Button
variant="outline"
size="sm"
onClick={() => {
void refetchTreeControlPreview();
}}
>
Retry preview
</Button>
</div>
) : treeControlPreview ? (
<div className="space-y-2">
{treePreviewWarnings.length > 0 ? (
<div className="space-y-1">
{treePreviewWarnings.map((warning) => (
<p key={warning.code} className="text-xs text-amber-700 dark:text-amber-300">
{warning.message}
</p>
))}
</div>
) : null}
{treePreviewAffectedIssueRows.length > 0 ? (
<div className="max-h-56 overflow-y-auto overscroll-contain">
{treePreviewAffectedIssueRows.map(({ candidate, issue: previewIssue }) => (
<div key={candidate.id} style={candidate.depth > 0 ? { paddingLeft: `${Math.min(candidate.depth, 6) * 14}px` } : undefined}>
<Link
to={createIssueDetailPath(candidate.identifier ?? candidate.id)}
issuePrefetch={previewIssue}
className={cn(
"group flex items-start gap-2 border-b border-border py-2 pl-1 pr-2 text-sm no-underline text-inherit transition-colors last:border-b-0 hover:bg-accent/50 sm:items-center",
candidate.skipped && "opacity-60",
)}
>
<StatusIcon status={candidate.status} />
<span className="shrink-0 font-mono text-xs text-muted-foreground">
{candidate.identifier ?? candidate.id.slice(0, 8)}
</span>
<span className="min-w-0 flex-1 truncate">{candidate.title}</span>
{candidate.skipped && candidate.skipReason === "terminal_status" ? (
<span className="shrink-0 text-xs text-muted-foreground">Complete</span>
) : null}
</Link>
</div>
))}
</div>
) : null}
</div>
) : (
<p className="text-xs text-muted-foreground">Preview unavailable.</p>
)}
</div>
</div>
<DialogFooter className="border-t border-border/60 bg-background px-6 py-4">
<Button variant="outline" onClick={() => setTreeControlOpen(false)} disabled={executeTreeControl.isPending}>
Close
</Button>
<Button
onClick={() => executeTreeControl.mutate()}
disabled={executeTreeControl.isPending || !canApplyTreeControl}
variant={treeControlMode === "cancel" ? "destructive" : "default"}
>
{executeTreeControl.isPending ? "Applying..." : treeControlPrimaryButtonLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Mobile properties drawer */}
<Sheet open={mobilePropsOpen} onOpenChange={setMobilePropsOpen}>
<SheetContent side="bottom" className="max-h-[85dvh] pb-[env(safe-area-inset-bottom)]">