Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-3416: Issue pre-trigger preview + Handoff Note (#4383)

Naiyuan Qing4ab335b8a5e5
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index dd326db9fe..b44e1f69ec 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -31,6 +31,8 @@ import type {
IssueSubscriber,
Comment,
CommentTriggerPreview,
+ IssueTriggerPreview,
+ IssueTriggerPreviewParams,
Reaction,
IssueReaction,
Workspace,
@@ -140,6 +142,7 @@ import {
ChildIssuesResponseSchema,
CommentsListSchema,
CommentTriggerPreviewSchema,
+ IssueTriggerPreviewSchema,
CloudRuntimeNodeListSchema,
CloudRuntimeNodeSchema,
CreateAgentFromTemplateResponseSchema,
@@ -686,6 +689,26 @@ export class ApiClient {
});
}
+ /** Dry-run the unified run-enqueue predicate for a prospective issue write
+ * (create / single assign / single status / batch). Returns the runs that
+ * would start; no side effect. The four entry points consult this instead
+ * of re-implementing the rule (MUL-3375). */
+ async previewIssueTrigger(params: IssueTriggerPreviewParams): Promise<IssueTriggerPreview> {
+ const raw = await this.fetch<unknown>("/api/issues/preview-trigger", {
+ method: "POST",
+ body: JSON.stringify({
+ ...(params.issueIds?.length ? { issue_ids: params.issueIds } : {}),
+ ...(params.isCreate ? { is_create: true } : {}),
+ ...(params.assigneeType ? { assignee_type: params.assigneeType } : {}),
+ ...(params.assigneeId ? { assignee_id: params.assigneeId } : {}),
+ ...(params.status ? { status: params.status } : {}),
+ }),
+ });
+ return parseWithFallback(raw, IssueTriggerPreviewSchema, { triggers: [], total_count: 0 }, {
+ endpoint: "POST /api/issues/preview-trigger",
+ });
+ }
+
async listTimeline(issueId: string): Promise<TimelineEntry[]> {
const raw = await this.fetch<unknown>(
`/api/issues/${issueId}/timeline`,
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 4823c5116f..98fa475ec3 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -6,6 +6,7 @@ import {
DashboardUsageDailyListSchema,
DuplicateIssueErrorBodySchema,
EMPTY_USER,
+ IssueTriggerPreviewSchema,
ListIssuesResponseSchema,
RuntimeHourlyActivityListSchema,
RuntimeUsageByAgentListSchema,
@@ -90,6 +91,80 @@ describe("IssueSchema (via ListIssuesResponseSchema)", () => {
});
});
+// POST /api/issues/preview-trigger feeds this schema through parseWithFallback
+// in client.previewIssueTrigger with fallback { triggers: [], total_count: 0 }
+// (MUL-3375). The four entry points read it to decide "will this start a run",
+// so malformed / missing / null drift must degrade to "nothing will start"
+// rather than throw into the picker/modal.
+const PREVIEW_FALLBACK = { triggers: [], total_count: 0 };
+const PREVIEW_ENDPOINT = { endpoint: "POST /api/issues/preview-trigger" };
+
+describe("IssueTriggerPreviewSchema", () => {
+ it("parses a well-formed response", () => {
+ const parsed = IssueTriggerPreviewSchema.parse({
+ triggers: [
+ { issue_id: "i1", agent_id: "a1", source: "assign", handoff_supported: true },
+ { issue_id: "i2", agent_id: "a2", source: "status", handoff_supported: false },
+ ],
+ total_count: 2,
+ });
+ expect(parsed.total_count).toBe(2);
+ expect(parsed.triggers).toHaveLength(2);
+ expect(parsed.triggers[0]).toMatchObject({ issue_id: "i1", agent_id: "a1", source: "assign", handoff_supported: true });
+ });
+
+ it("defaults missing top-level fields (empty / older backend)", () => {
+ const parsed = IssueTriggerPreviewSchema.parse({});
+ expect(parsed.triggers).toEqual([]);
+ expect(parsed.total_count).toBe(0);
+ });
+
+ it("defaults missing optional item fields, keeping required issue_id", () => {
+ const parsed = IssueTriggerPreviewSchema.parse({ triggers: [{ issue_id: "i1" }], total_count: 1 });
+ expect(parsed.triggers[0]).toEqual({
+ issue_id: "i1",
+ agent_id: "",
+ source: "",
+ handoff_supported: false,
+ });
+ });
+
+ it("parseWithFallback returns the fallback for a malformed shape (triggers not an array)", () => {
+ const parsed = parseWithFallback(
+ { triggers: "nope", total_count: 1 },
+ IssueTriggerPreviewSchema,
+ PREVIEW_FALLBACK,
+ PREVIEW_ENDPOINT,
+ );
+ expect(parsed).toEqual(PREVIEW_FALLBACK);
+ });
+
+ it("parseWithFallback returns the fallback when an item drops the required issue_id", () => {
+ const parsed = parseWithFallback(
+ { triggers: [{ agent_id: "a1", source: "assign" }], total_count: 1 },
+ IssueTriggerPreviewSchema,
+ PREVIEW_FALLBACK,
+ PREVIEW_ENDPOINT,
+ );
+ expect(parsed).toEqual(PREVIEW_FALLBACK);
+ });
+
+ it("parseWithFallback returns the fallback for a wrong-typed total_count", () => {
+ const parsed = parseWithFallback(
+ { triggers: [], total_count: "5" },
+ IssueTriggerPreviewSchema,
+ PREVIEW_FALLBACK,
+ PREVIEW_ENDPOINT,
+ );
+ expect(parsed).toEqual(PREVIEW_FALLBACK);
+ });
+
+ it("parseWithFallback returns the fallback for null / non-object bodies", () => {
+ expect(parseWithFallback(null, IssueTriggerPreviewSchema, PREVIEW_FALLBACK, PREVIEW_ENDPOINT)).toEqual(PREVIEW_FALLBACK);
+ expect(parseWithFallback("oops", IssueTriggerPreviewSchema, PREVIEW_FALLBACK, PREVIEW_ENDPOINT)).toEqual(PREVIEW_FALLBACK);
+ });
+});
+
describe("TimelineEntriesSchema", () => {
it("preserves source_task_id for agent failure comments", () => {
const parsed = TimelineEntriesSchema.parse([
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 57060958aa..e78fb3dafe 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -220,6 +220,18 @@ export const CommentTriggerPreviewSchema = z.object({
agents: z.array(CommentTriggerPreviewAgentSchema).default([]),
}).loose();
+const IssueTriggerPreviewItemSchema = z.object({
+ issue_id: z.string(),
+ agent_id: z.string().default(""),
+ source: z.string().default(""),
+ handoff_supported: z.boolean().default(false),
+}).loose();
+
+export const IssueTriggerPreviewSchema = z.object({
+ triggers: z.array(IssueTriggerPreviewItemSchema).default([]),
+ total_count: z.number().default(0),
+}).loose();
+
// Metadata is primitive-only by API/DB contract. Stay lenient on shape:
// unknown keys land as `unknown` to a caller, but the field itself defaults
// to {} so consumers never need to nil-guard `issue.metadata`.
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 129991108e..c25e586ca3 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -230,6 +230,11 @@ export function useUpdateIssue() {
mutationFn: ({ id, ...data }: { id: string } & UpdateIssueRequest) =>
api.updateIssue(id, data),
onMutate: ({ id, ...data }) => {
+ // suppress_run / handoff_note are write-time control fields, not Issue
+ // columns — they steer enqueue/injection on the server and must never be
+ // written into the query cache (MUL-3375). Strip them from the patch; the
+ // mutationFn above still sends the full payload to the API.
+ const { suppress_run: _suppressRun, handoff_note: _handoffNote, ...patch } = data;
// Fire-and-forget cancelQueries — keeps onMutate synchronous so the
// cache update happens in the same tick as mutate(). Awaiting would
// yield to the event loop, letting @dnd-kit reset its visual state
@@ -267,16 +272,16 @@ export function useUpdateIssue() {
: undefined;
for (const [key, cached] of prevLists) {
- if (cached) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(cached, id, data));
+ if (cached) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(cached, id, patch));
}
qc.setQueryData<Issue>(issueKeys.detail(wsId, id), (old) =>
- old ? { ...old, ...data } : old,
+ old ? { ...old, ...patch } : old,
);
if (parentId) {
qc.setQueryData<Issue[]>(
issueKeys.children(wsId, parentId),
(old) =>
- old?.map((c) => (c.id === id ? { ...c, ...data } : c)),
+ old?.map((c) => (c.id === id ? { ...c, ...patch } : c)),
);
}
return { prevLists, prevDetail, prevChildren, parentId, id };
@@ -450,6 +455,10 @@ export function useBatchUpdateIssues() {
// batch edit on a My-Issues board had no optimistic effect and relied
// entirely on the settle refetch. Filter to bucketed (byStatus) caches so
// grouped/flat caches under the same prefix are skipped.
+ //
+ // Control fields steer the server; they are not Issue columns and must
+ // not enter the cache (MUL-3375). mutationFn still sends them.
+ const { suppress_run: _suppressRun, handoff_note: _handoffNote, ...patch } = updates;
await qc.cancelQueries({ queryKey: issueKeys.list(wsId) });
await qc.cancelQueries({ queryKey: issueKeys.myAll(wsId) });
const prevLists = [
@@ -460,7 +469,7 @@ export function useBatchUpdateIssues() {
);
for (const [key, cached] of prevLists) {
let next = cached;
- for (const id of ids) next = patchIssueInBuckets(next, id, updates);
+ for (const id of ids) next = patchIssueInBuckets(next, id, patch);
qc.setQueryData<ListIssuesCache>(key, next);
}
@@ -479,7 +488,7 @@ export function useBatchUpdateIssues() {
affectedParentIds.add(parentId);
prevChildren.set(parentId, data);
qc.setQueryData<Issue[]>(issueKeys.children(wsId, parentId), (old) =>
- old?.map((c) => (idSet.has(c.id) ? { ...c, ...updates } : c)),
+ old?.map((c) => (idSet.has(c.id) ? { ...c, ...patch } : c)),
);
}
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index 50c963f5a8..ee1c3bb827 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -83,6 +83,14 @@ export const issueKeys = {
/** PREFIX for invalidation — the composer hook appends parent + content signature. */
commentTriggerPreview: (issueId: string) =>
[...issueKeys.commentTriggerPreviewAll(), issueId] as const,
+ /** Prefix across all issue-trigger previews (assign/status/create/batch).
+ * WS task lifecycle events invalidate here so the answer revalidates when an
+ * agent's queue state changes (the status source's pending dedup makes it
+ * queue-dependent, mirroring commentTriggerPreviewAll). */
+ issueTriggerPreviewAll: () => ["issues", "issue-trigger-preview"] as const,
+ /** PREFIX — the picker hook appends a signature of the prospective write. */
+ issueTriggerPreview: (signature: string) =>
+ [...issueKeys.issueTriggerPreviewAll(), signature] as const,
reactionsAll: () => ["issues", "reactions"] as const,
reactions: (issueId: string) =>
[...issueKeys.reactionsAll(), issueId] as const,
diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.ts
index 6e1db7cac4..cb4aae4be7 100644
--- a/packages/core/modals/store.ts
+++ b/packages/core/modals/store.ts
@@ -12,7 +12,7 @@ type ModalType =
| "issue-set-parent"
| "issue-add-child"
| "issue-delete-confirm"
- | "issue-backlog-agent-hint"
+ | "issue-run-confirm"
| null;
interface ModalStore {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 14378a206c..bc40e9ad2e 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -517,6 +517,11 @@ export function useRealtimeSync(
// open composer's chips (e.g. an agent finishing its run becomes
// triggerable again mid-typing).
qc.invalidateQueries({ queryKey: issueKeys.commentTriggerPreviewAll() });
+ // Issue-trigger previews (assign/status/create/batch) are queue-
+ // dependent the same way — the status source's pending dedup means a
+ // task finishing changes "will this start a run", so refresh any open
+ // picker/modal preview (MUL-3375).
+ qc.invalidateQueries({ queryKey: issueKeys.issueTriggerPreviewAll() });
},
};
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 2b67521c83..1e76bf1f92 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -37,6 +37,40 @@ export interface UpdateIssueRequest {
* Used by the description editor to register newly uploaded files so they
* surface in `issueAttachments` and keep their preview Eye on refresh. */
attachment_ids?: string[];
+ /** Skip starting the agent run this write would trigger ("暂时不启动",
+ * MUL-3375). The assignee/status change still applies. Control field —
+ * strip from optimistic cache patches; never written onto the Issue. */
+ suppress_run?: boolean;
+ /** Free-text handoff instruction injected into the started run's opening
+ * context (MUL-3375). Only consumed when a run actually starts. Control
+ * field — strip from optimistic cache patches. */
+ handoff_note?: string;
+}
+
+/** Inputs to `POST /api/issues/preview-trigger`. A nil prospective field means
+ * "leave unchanged"; `isCreate` previews a not-yet-persisted issue. */
+export interface IssueTriggerPreviewParams {
+ issueIds?: string[];
+ isCreate?: boolean;
+ assigneeType?: IssueAssigneeType | null;
+ assigneeId?: string | null;
+ status?: IssueStatus;
+}
+
+/** One issue that WILL start a run under the prospective write. `agent_id` is
+ * the runnable agent (squad leader for squads). `handoff_supported` is the
+ * soft-gate signal: false when the target runtime is too old to render a
+ * handoff note (gray the note box; the assignment still works). */
+export interface IssueTriggerPreviewItem {
+ issue_id: string;
+ agent_id: string;
+ source: string;
+ handoff_supported: boolean;
+}
+
+export interface IssueTriggerPreview {
+ triggers: IssueTriggerPreviewItem[];
+ total_count: number;
}
export interface ListIssuesParams {
diff --git a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx
index 7a5d62a37d..5979d6c466 100644
--- a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx
+++ b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx
@@ -131,9 +131,8 @@ describe("useIssueActions", () => {
);
});
- it("assigning an agent to a backlog issue opens the backlog-hint modal", () => {
- const backlogIssue = { ...mockIssue, status: "backlog" } as Issue;
- const { result } = renderHook(() => useIssueActions(backlogIssue), { wrapper });
+ it("assigning an agent routes through the run-confirm modal instead of mutating directly", () => {
+ const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });
act(() => {
result.current.updateField({
@@ -142,23 +141,29 @@ describe("useIssueActions", () => {
});
});
- expect(mockOpenModal).toHaveBeenCalledWith("issue-backlog-agent-hint", {
- issueId: "issue-1",
+ expect(mockOpenModal).toHaveBeenCalledWith("issue-run-confirm", {
+ issueIds: ["issue-1"],
+ mode: "assign",
+ assigneeType: "agent",
+ assigneeId: "agent-1",
});
+ expect(mockUpdateMutate).not.toHaveBeenCalled();
});
- it("does not re-open backlog-hint when the user has dismissed it", () => {
- localStorage.setItem("multica:backlog-agent-hint-dismissed", "true");
- const backlogIssue = { ...mockIssue, status: "backlog" } as Issue;
- const { result } = renderHook(() => useIssueActions(backlogIssue), { wrapper });
+ it("assigning a member applies directly without the run-confirm modal", () => {
+ const { result } = renderHook(() => useIssueActions(mockIssue), { wrapper });
act(() => {
result.current.updateField({
- assignee_type: "agent",
- assignee_id: "agent-1",
+ assignee_type: "member",
+ assignee_id: "user-1",
});
});
+ expect(mockUpdateMutate).toHaveBeenCalledWith(
+ { id: "issue-1", assignee_type: "member", assignee_id: "user-1" },
+ expect.any(Object),
+ );
expect(mockOpenModal).not.toHaveBeenCalled();
});
diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.ts
index 3b0250f943..9d1c027ae1 100644
--- a/packages/views/issues/actions/use-issue-actions.ts
+++ b/packages/views/issues/actions/use-issue-actions.ts
@@ -14,8 +14,6 @@ import { copyText } from "@multica/ui/lib/clipboard";
import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
-const BACKLOG_HINT_LS_KEY = "multica:backlog-agent-hint-dismissed";
-
export interface UseIssueActionsResult {
isPinned: boolean;
updateField: (updates: Partial<UpdateIssueRequest>) => void;
@@ -57,13 +55,29 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
const openModal = useModalStore((s) => s.open);
const issueId = issue?.id ?? null;
- const issueStatus = issue?.status ?? null;
const issueIdentifier = issue?.identifier ?? null;
const issueProjectId = issue?.project_id ?? null;
const updateField = useCallback(
(updates: Partial<UpdateIssueRequest>) => {
if (!issueId) return;
+ // Assigning to an agent/squad may start a run. Route through the
+ // pre-trigger confirm modal (preview + optional handoff note + "暂不开始"),
+ // which applies the change itself — the four entry points share this one
+ // backend-driven flow instead of guessing (MUL-3375). Every other field
+ // change (status, priority, member assign, unassign) applies directly.
+ if (
+ (updates.assignee_type === "agent" || updates.assignee_type === "squad") &&
+ updates.assignee_id
+ ) {
+ openModal("issue-run-confirm", {
+ issueIds: [issueId],
+ mode: "assign",
+ assigneeType: updates.assignee_type,
+ assigneeId: updates.assignee_id,
+ });
+ return;
+ }
updateIssue.mutate(
{ id: issueId, ...updates },
{
@@ -75,19 +89,8 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
),
},
);
- // Hint: assigning an agent to a backlog issue won't trigger execution
- // until the issue is moved to an active status.
- if (
- updates.assignee_type === "agent" &&
- updates.assignee_id &&
- issueStatus === "backlog" &&
- typeof window !== "undefined" &&
- localStorage.getItem(BACKLOG_HINT_LS_KEY) !== "true"
- ) {
- openModal("issue-backlog-agent-hint", { issueId });
- }
},
- [issueId, issueStatus, updateIssue, openModal, t],
+ [issueId, updateIssue, openModal, t],
);
const togglePin = useCallback(() => {
diff --git a/packages/views/issues/components/backlog-agent-hint-dialog.tsx b/packages/views/issues/components/backlog-agent-hint-dialog.tsx
deleted file mode 100644
index 20d63c3268..0000000000
--- a/packages/views/issues/components/backlog-agent-hint-dialog.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { Archive, ArrowRight, Bot, CheckCircle2 } from "lucide-react";
-import {
- AlertDialog,
- AlertDialogContent,
-} from "@multica/ui/components/ui/alert-dialog";
-import { Button } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import { useT } from "../../i18n";
-
-interface BacklogAgentHintDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- onDismissPermanently: () => void;
- onMoveToTodo: () => void;
-}
-
-export function BacklogAgentHintDialog({
- open,
- onOpenChange,
- onDismissPermanently,
- onMoveToTodo,
-}: BacklogAgentHintDialogProps) {
- return (
- <AlertDialog open={open} onOpenChange={onOpenChange}>
- <AlertDialogContent className="w-[calc(100vw-2rem)] !max-w-[480px] gap-0 overflow-hidden rounded-lg p-0">
- <BacklogAgentHintContent
- onKeepInBacklog={() => onOpenChange(false)}
- onDismissPermanently={onDismissPermanently}
- onMoveToTodo={onMoveToTodo}
- />
- </AlertDialogContent>
- </AlertDialog>
- );
-}
-
-interface BacklogAgentHintContentProps {
- onKeepInBacklog: () => void;
- onDismissPermanently: () => void;
- onMoveToTodo: () => void;
-}
-
-export function BacklogAgentHintContent({
- onKeepInBacklog,
- onDismissPermanently,
- onMoveToTodo,
-}: BacklogAgentHintContentProps) {
- const { t } = useT("issues");
- const [dontShowAgain, setDontShowAgain] = useState(false);
-
- const handleKeepInBacklog = () => {
- if (dontShowAgain) onDismissPermanently();
- onKeepInBacklog();
- };
-
- const handleMoveToTodo = () => {
- if (dontShowAgain) onDismissPermanently();
- onMoveToTodo();
- };
-
- return (
- <>
- <div className="px-5 pb-4 pt-5">
- <div className="flex items-start gap-3">
- <div className="mt-0.5 flex size-10 shrink-0 items-center justify-center rounded-lg border bg-muted text-muted-foreground">
- <Bot className="size-4" />
- </div>
- <div className="min-w-0">
- <h2 className="text-base font-semibold">
- {t(($) => $.backlog_hint.title)}
- </h2>
- <p className="mt-1 text-sm leading-5 text-muted-foreground">
- {t(($) => $.backlog_hint.description)}
- </p>
- </div>
- </div>
-
- <div className="mt-4 grid gap-2 rounded-lg border bg-muted/35 p-3 text-sm">
- <div className="flex items-center gap-2 text-muted-foreground">
- <Archive className="size-4 shrink-0" />
- <span className="font-medium text-foreground">{t(($) => $.backlog_hint.row_backlog_label)}</span>
- <span className="text-muted-foreground">{t(($) => $.backlog_hint.row_backlog_hint)}</span>
- </div>
- <div className="flex items-center gap-2 text-muted-foreground">
- <ArrowRight className="size-4 shrink-0" />
- <span className="font-medium text-foreground">{t(($) => $.backlog_hint.row_todo_label)}</span>
- <span className="text-muted-foreground">{t(($) => $.backlog_hint.row_todo_hint)}</span>
- <CheckCircle2 className="ml-auto size-4 shrink-0 text-primary" />
- </div>
- </div>
- </div>
-
- <div className="border-t bg-muted/25 px-5 py-4">
- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <label className="flex min-w-0 cursor-pointer items-center gap-2 text-sm text-muted-foreground">
- <Checkbox
- checked={dontShowAgain}
- onCheckedChange={(next) => setDontShowAgain(next === true)}
- />
- <span className="truncate">{t(($) => $.backlog_hint.dont_show_again)}</span>
- </label>
- <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
- <Button
- type="button"
- variant="outline"
- className="w-full sm:w-auto"
- onClick={handleKeepInBacklog}
- >
- {t(($) => $.backlog_hint.keep_in_backlog)}
- </Button>
- <Button
- type="button"
- className="w-full sm:w-auto"
- onClick={handleMoveToTodo}
- >
- {t(($) => $.backlog_hint.move_to_todo)}
- </Button>
- </div>
- </div>
- </div>
- </>
- );
-}
diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsx
index 9433fd08f2..5f6a3b3a4e 100644
--- a/packages/views/issues/components/batch-action-toolbar.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.tsx
@@ -18,6 +18,7 @@ import type { Issue, UpdateIssueRequest } from "@multica/core/types";
import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";
import { commonIssueFields } from "@multica/core/issues/batch";
import { useBatchUpdateIssues, useBatchDeleteIssues } from "@multica/core/issues/mutations";
+import { useModalStore } from "@multica/core/modals";
import { StatusPicker, PriorityPicker, AssigneePicker } from "./pickers";
import { useT } from "../../i18n";
import { cn } from "@multica/ui/lib/utils";
@@ -60,6 +61,7 @@ export function BatchActionToolbar({
const [deleteOpen, setDeleteOpen] = useState(false);
const batchUpdate = useBatchUpdateIssues();
const batchDelete = useBatchDeleteIssues();
+ const openModal = useModalStore((s) => s.open);
const loading = batchUpdate.isPending || batchDelete.isPending;
if (count === 0) return null;
@@ -79,6 +81,36 @@ export function BatchActionToolbar({
}
};
+ // Status and agent/squad assignment can fan out runs across the selection, so
+ // route them through the pre-trigger confirm modal (aggregate "将启动 N 个" +
+ // collective handoff note for assign + 暂不开始). The modal applies the batch
+ // itself. Priority, member assign, and unassign never start a run — direct.
+ const handleBatchStatus = (updates: Partial<UpdateIssueRequest>) => {
+ if (!updates.status) return;
+ // Backlog is the parking lot — a move into backlog never starts a run
+ // (server/internal/service/issue_trigger.go), so the confirm modal would
+ // only render an empty "won't start" box with a single Apply button. Apply
+ // directly, matching the single-issue status path.
+ if (updates.status === "backlog") {
+ void handleBatchUpdate(updates);
+ return;
+ }
+ openModal("issue-run-confirm", { issueIds: ids, mode: "status", status: updates.status });
+ };
+
+ const handleBatchAssignee = (updates: Partial<UpdateIssueRequest>) => {
+ if ((updates.assignee_type === "agent" || updates.assignee_type === "squad") && updates.assignee_id) {
+ openModal("issue-run-confirm", {
+ issueIds: ids,
+ mode: "assign",
+ assigneeType: updates.assignee_type,
+ assigneeId: updates.assignee_id,
+ });
+ return;
+ }
+ void handleBatchUpdate(updates);
+ };
+
const handleBatchDelete = async () => {
try {
await batchDelete.mutateAsync(ids);
@@ -119,7 +151,7 @@ export function BatchActionToolbar({
{/* Status */}
<StatusPicker
status={common.status}
- onUpdate={handleBatchUpdate}
+ onUpdate={handleBatchStatus}
open={statusOpen}
onOpenChange={setStatusOpen}
triggerRender={<Button variant="ghost" size="sm" disabled={loading} />}
@@ -143,7 +175,7 @@ export function BatchActionToolbar({
assigneeType={common.assignee?.type ?? null}
assigneeId={common.assignee?.id ?? null}
mixed={common.assignee === null}
- onUpdate={handleBatchUpdate}
+ onUpdate={handleBatchAssignee}
open={assigneeOpen}
onOpenChange={setAssigneeOpen}
triggerRender={<Button variant="ghost" size="sm" disabled={loading} />}
diff --git a/packages/views/issues/hooks/use-issue-trigger-preview.ts b/packages/views/issues/hooks/use-issue-trigger-preview.ts
new file mode 100644
index 0000000000..a61c6acc60
--- /dev/null
+++ b/packages/views/issues/hooks/use-issue-trigger-preview.ts
@@ -0,0 +1,79 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { api } from "@multica/core/api";
+import { issueKeys } from "@multica/core/issues/queries";
+import type { IssueAssigneeType, IssueStatus, IssueTriggerPreviewItem } from "@multica/core/types";
+
+export interface UseIssueTriggerPreviewParams {
+ /** Existing issues to evaluate (single assign/status or batch). */
+ issueIds?: string[];
+ /** Preview a not-yet-persisted issue from assignee/status (create modal). */
+ isCreate?: boolean;
+ assigneeType?: IssueAssigneeType | null;
+ assigneeId?: string | null;
+ status?: IssueStatus;
+ /** Caller gate — e.g. only fetch while a picker/modal is open. */
+ enabled?: boolean;
+}
+
+export interface UseIssueTriggerPreviewResult {
+ triggers: IssueTriggerPreviewItem[];
+ totalCount: number;
+ isLoading: boolean;
+ /** True when every trigger's target runtime can render a handoff note, so
+ * the note box is safe to enable. False if any started run would drop it. */
+ handoffSupported: boolean;
+}
+
+const EMPTY: IssueTriggerPreviewItem[] = [];
+
+function previewSignature(params: UseIssueTriggerPreviewParams): string {
+ return JSON.stringify({
+ ids: [...(params.issueIds ?? [])].sort(),
+ create: params.isCreate ?? false,
+ at: params.assigneeType ?? null,
+ aid: params.assigneeId ?? null,
+ status: params.status ?? null,
+ });
+}
+
+/** Reads the unified backend predicate via POST /api/issues/preview-trigger so
+ * the four entry points never re-implement "will this start a run" (MUL-3375).
+ * The answer is queue-dependent (status-source pending dedup), so it is never
+ * cached stale: staleTime 0, and WS task events invalidate issueTriggerPreviewAll. */
+export function useIssueTriggerPreview(
+ params: UseIssueTriggerPreviewParams,
+): UseIssueTriggerPreviewResult {
+ const hasTarget =
+ (!!params.assigneeType && !!params.assigneeId) ||
+ !!params.status ||
+ (params.isCreate ?? false);
+ const enabled = (params.enabled ?? true) && hasTarget;
+
+ const signature = useMemo(() => previewSignature(params), [params]);
+
+ const previewQuery = useQuery({
+ queryKey: issueKeys.issueTriggerPreview(signature),
+ queryFn: () =>
+ api.previewIssueTrigger({
+ issueIds: params.issueIds,
+ isCreate: params.isCreate,
+ assigneeType: params.assigneeType,
+ assigneeId: params.assigneeId,
+ status: params.status,
+ }),
+ enabled,
+ retry: false,
+ staleTime: 0,
+ });
+
+ const triggers = previewQuery.data?.triggers ?? EMPTY;
+ return {
+ triggers,
+ totalCount: previewQuery.data?.total_count ?? 0,
+ isLoading: enabled && previewQuery.isFetching,
+ handoffSupported: triggers.length > 0 && triggers.every((t) => t.handoff_supported === true),
+ };
+}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 6ba87b893a..731a7aa685 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -490,9 +490,6 @@
"row_backlog_label": "Backlog",
"row_backlog_hint": "keeps the agent paused",
"row_todo_label": "Todo",
- "row_todo_hint": "starts the agent",
- "dont_show_again": "Don't show this again",
- "keep_in_backlog": "Keep in Backlog",
- "move_to_todo": "Move to Todo"
+ "row_todo_hint": "starts the agent"
}
}
diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.json
index d359dd840b..dadc661b6e 100644
--- a/packages/views/locales/en/modals.json
+++ b/packages/views/locales/en/modals.json
@@ -50,8 +50,25 @@
"toast_failed": "Failed to add sub-issue",
"toast_success": "Added {{identifier}} as sub-issue"
},
- "backlog_hint": {
- "toast_status_failed": "Failed to update status"
+ "run_confirm": {
+ "title_assign": "Assign and start?",
+ "title_status": "Start working now?",
+ "will_start_named": "Once assigned, {{name}} will start working on this issue right away.",
+ "will_start_named_squad": "Once assigned, {{name}}'s leader will review it and start assigning the work.",
+ "will_start": "This will start work on {{count}} issues right away.",
+ "will_start_squad": "This hands {{count}} issues to the squad's leader to review and assign.",
+ "nothing_assign": "Assigned — won't start working while in Backlog.",
+ "nothing_status": "Won't start working.",
+ "note_label": "Handoff note (optional)",
+ "note_placeholder": "Tell them what matters — scope, focus, or what to avoid…",
+ "note_unsupported": "Their runtime is too old to receive this handoff note; it may not be read.",
+ "start": "Start",
+ "dont_start": "Don't start yet",
+ "apply": "Apply",
+ "toast_failed": "Action failed",
+ "create_will_start": "{{name}} will start working right after creation.",
+ "create_will_start_squad": "{{name}}'s leader will review it and start assigning work right after creation.",
+ "create_parked": "Assigned — won't start working in Backlog."
},
"create_squad": {
"title": "Create Squad",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 0fedf6193c..15c9ba4734 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -471,9 +471,6 @@
"row_backlog_label": "バックログ",
"row_backlog_hint": "エージェントを一時停止のままにします",
"row_todo_label": "未着手",
- "row_todo_hint": "エージェントを開始します",
- "dont_show_again": "今後表示しない",
- "keep_in_backlog": "バックログのままにする",
- "move_to_todo": "未着手に移動"
+ "row_todo_hint": "エージェントを開始します"
}
}
diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.json
index a84ca28641..845a529fa9 100644
--- a/packages/views/locales/ja/modals.json
+++ b/packages/views/locales/ja/modals.json
@@ -50,8 +50,25 @@
"toast_failed": "サブイシューを追加できませんでした",
"toast_success": "{{identifier}} をサブイシューとして追加しました"
},
- "backlog_hint": {
- "toast_status_failed": "ステータスを更新できませんでした"
+ "run_confirm": {
+ "title_assign": "割り当てて開始しますか?",
+ "title_status": "今すぐ作業を開始しますか?",
+ "will_start_named": "割り当てると、{{name}} がすぐにこのイシューの作業を開始します。",
+ "will_start_named_squad": "割り当てると、{{name}} のリーダーが内容を評価し、タスクの割り振りを開始します。",
+ "will_start": "{{count}} 件のイシューの作業をすぐに開始します。",
+ "will_start_squad": "{{count}} 件のイシューをスクワッドのリーダーに渡し、評価して割り振ります。",
+ "nothing_assign": "割り当て済み — バックログ中は作業を開始しません。",
+ "nothing_status": "作業を開始しません。",
+ "note_label": "引き継ぎメモ(任意)",
+ "note_placeholder": "範囲・重点・触れてほしくない点などを一言で…",
+ "note_unsupported": "相手の実行環境が古いため、この引き継ぎメモは読み取れない可能性があります。",
+ "start": "開始",
+ "dont_start": "まだ開始しない",
+ "apply": "適用",
+ "toast_failed": "操作に失敗しました",
+ "create_will_start": "作成後、{{name}} がすぐに作業を開始します。",
+ "create_will_start_squad": "作成後、{{name}} のリーダーが内容を評価し、タスクの割り振りを開始します。",
+ "create_parked": "割り当て済み — バックログでは作業を開始しません。"
},
"create_squad": {
"title": "スクワッドを作成",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 060ad6f060..ed5505a00b 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -489,9 +489,6 @@
"row_backlog_label": "백로그",
"row_backlog_hint": "에이전트를 대기 상태로 유지",
"row_todo_label": "할 일",
- "row_todo_hint": "에이전트 시작",
- "dont_show_again": "다시 보지 않기",
- "keep_in_backlog": "백로그에 두기",
- "move_to_todo": "할 일로 이동"
+ "row_todo_hint": "에이전트 시작"
}
}
diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.json
index 342ffcfa3e..865f80dd11 100644
--- a/packages/views/locales/ko/modals.json
+++ b/packages/views/locales/ko/modals.json
@@ -50,8 +50,25 @@
"toast_failed": "하위 이슈를 추가하지 못했습니다",
"toast_success": "{{identifier}}을(를) 하위 이슈로 추가했습니다"
},
- "backlog_hint": {
- "toast_status_failed": "상태를 업데이트하지 못했습니다"
+ "run_confirm": {
+ "title_assign": "할당하고 시작할까요?",
+ "title_status": "지금 작업을 시작할까요?",
+ "will_start_named": "할당하면 {{name}}이(가) 이 이슈 작업을 바로 시작합니다.",
+ "will_start_named_squad": "할당하면 {{name}}의 리더가 내용을 평가한 뒤 작업 배분을 시작합니다.",
+ "will_start": "{{count}}개 이슈의 작업을 바로 시작합니다.",
+ "will_start_squad": "{{count}}개 이슈를 스쿼드 리더에게 넘겨 평가하고 배분합니다.",
+ "nothing_assign": "할당됨 — 백로그에서는 작업을 시작하지 않습니다.",
+ "nothing_status": "작업을 시작하지 않습니다.",
+ "note_label": "인계 메모 (선택)",
+ "note_placeholder": "범위·핵심·건드리지 말 것 등을 한마디로…",
+ "note_unsupported": "상대 런타임이 오래되어 이 인계 메모를 읽지 못할 수 있습니다.",
+ "start": "시작",
+ "dont_start": "아직 시작 안 함",
+ "apply": "적용",
+ "toast_failed": "작업에 실패했습니다",
+ "create_will_start": "생성 후 {{name}}이(가) 바로 작업을 시작합니다.",
+ "create_will_start_squad": "생성 후 {{name}}의 리더가 내용을 평가한 뒤 작업 배분을 시작합니다.",
+ "create_parked": "할당됨 — 백로그에서는 작업을 시작하지 않습니다."
},
"create_squad": {
"title": "스쿼드 만들기",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index b279a6dd97..ac0f659af6 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -476,9 +476,6 @@
"row_backlog_label": "Backlog",
"row_backlog_hint": "智能体保持暂停",
"row_todo_label": "Todo",
- "row_todo_hint": "启动智能体",
- "dont_show_again": "不再提示",
- "keep_in_backlog": "保持在 Backlog",
- "move_to_todo": "移到 Todo"
+ "row_todo_hint": "启动智能体"
}
}
diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.json
index 96694f08ff..3257ef4c15 100644
--- a/packages/views/locales/zh-Hans/modals.json
+++ b/packages/views/locales/zh-Hans/modals.json
@@ -50,8 +50,25 @@
"toast_failed": "添加子 issue 失败",
"toast_success": "已添加 {{identifier}} 为子 issue"
},
- "backlog_hint": {
- "toast_status_failed": "更新状态失败"
+ "run_confirm": {
+ "title_assign": "指派并开始处理?",
+ "title_status": "现在开始处理?",
+ "will_start_named": "指派后,{{name}} 会立即开始工作。",
+ "will_start_named_squad": "指派后,{{name}} 的队长会评估并开始安排任务。",
+ "will_start": "将立即开始处理 {{count}} 个 issue。",
+ "will_start_squad": "将把 {{count}} 个 issue 交给队长评估并安排。",
+ "nothing_assign": "已指派 —— 在 backlog 中不会开始处理。",
+ "nothing_status": "不会开始处理。",
+ "note_label": "交接说明(可选)",
+ "note_placeholder": "交代一句 —— 范围、重点、或别碰什么……",
+ "note_unsupported": "对方的运行环境版本较旧,这条交接说明可能读不到。",
+ "start": "开始",
+ "dont_start": "暂不开始",
+ "apply": "确定",
+ "toast_failed": "操作失败",
+ "create_will_start": "创建后 {{name}} 会立即开始工作。",
+ "create_will_start_squad": "创建后 {{name}} 的队长会评估并开始安排任务。",
+ "create_parked": "已指派 —— 在 backlog 中不会开始工作。"
},
"create_squad": {
"title": "创建 Squad",
diff --git a/packages/views/modals/backlog-agent-hint.tsx b/packages/views/modals/backlog-agent-hint.tsx
deleted file mode 100644
index 38cc27f97e..0000000000
--- a/packages/views/modals/backlog-agent-hint.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-"use client";
-
-import { toast } from "sonner";
-import { BacklogAgentHintDialog } from "../issues/components/backlog-agent-hint-dialog";
-import { useUpdateIssue } from "@multica/core/issues/mutations";
-import { useT } from "../i18n";
-
-export function BacklogAgentHintModal({
- onClose,
- data,
-}: {
- onClose: () => void;
- data: Record<string, unknown> | null;
-}) {
- const { t } = useT("modals");
- const issueId = (data?.issueId as string) || "";
- const updateIssue = useUpdateIssue();
-
- return (
- <BacklogAgentHintDialog
- open
- onOpenChange={(v) => {
- if (!v) onClose();
- }}
- onDismissPermanently={() => {
- localStorage.setItem("multica:backlog-agent-hint-dismissed", "true");
- }}
- onMoveToTodo={() => {
- if (issueId) {
- updateIssue.mutate(
- { id: issueId, status: "todo" },
- {
- onError: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.backlog_hint.toast_status_failed),
- ),
- },
- );
- }
- onClose();
- }}
- />
- );
-}
diff --git a/packages/views/modals/create-issue-dialog.tsx b/packages/views/modals/create-issue-dialog.tsx
index 58a0ca8cce..7f16d51d15 100644
--- a/packages/views/modals/create-issue-dialog.tsx
+++ b/packages/views/modals/create-issue-dialog.tsx
@@ -26,10 +26,9 @@ import { ManualCreatePanel, manualDialogContentClass } from "./create-issue";
* `onSwitchMode`; the shell stores it as the next panel's `data` so seeding
* works exactly like a fresh open.
*
- * Manual-mode `isExpanded` / `backlogHintIssueId` are lifted up because they
- * drive `DialogContent`'s className — the className lives here in the shell
- * since the Popup is here, but the toggles for those states live in the
- * manual panel body.
+ * Manual-mode `isExpanded` is lifted up because it drives `DialogContent`'s
+ * className — the className lives here in the shell since the Popup is here,
+ * but the toggle for that state lives in the manual panel body.
*/
export function CreateIssueDialog({
onClose,
@@ -44,7 +43,6 @@ export function CreateIssueDialog({
const [mode, setMode] = useState<CreateMode>(initialMode);
const [panelData, setPanelData] = useState(data ?? null);
const [isExpanded, setIsExpanded] = useState(false);
- const [backlogHintIssueId, setBacklogHintIssueId] = useState<string | null>(null);
const switchTo = (next: CreateMode) => (carry?: Record<string, unknown> | null) => {
setLastMode(next);
@@ -69,7 +67,7 @@ export function CreateIssueDialog({
? "!max-w-4xl !w-full !h-5/6"
: "!max-w-xl !w-full !max-h-[80vh]",
)
- : manualDialogContentClass(isExpanded, backlogHintIssueId);
+ : manualDialogContentClass(isExpanded);
return (
<Dialog open onOpenChange={(v) => { if (!v) onClose(); }}>
@@ -93,8 +91,6 @@ export function CreateIssueDialog({
data={panelData}
isExpanded={isExpanded}
setIsExpanded={setIsExpanded}
- backlogHintIssueId={backlogHintIssueId}
- setBacklogHintIssueId={setBacklogHintIssueId}
/>
)}
</DialogContent>
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index 55b12eb885..6815a75841 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -96,6 +96,29 @@ vi.mock("@multica/core/issues/queries", () => ({
}),
}));
+// CreateRunHint's pre-trigger preview + actor-name lookup are exercised in
+// their own suites; here we only need the create form to render without query
+// infra, so stub them to the inert "no run will start" state.
+vi.mock("../issues/hooks/use-issue-trigger-preview", () => ({
+ useIssueTriggerPreview: () => ({
+ triggers: [],
+ totalCount: 0,
+ isLoading: false,
+ handoffSupported: false,
+ }),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: () => "Agent" }),
+}));
+
+// CreateRunHint now renders an ActorAvatar for agent/squad assignees. This
+// suite is about the create form, not the avatar (whose own workspace/presence/
+// navigation hook tree is exercised elsewhere), so stub it inert.
+vi.mock("../common/actor-avatar", () => ({
+ ActorAvatar: () => null,
+}));
+
vi.mock("@multica/core/issues/stores/draft-store", () => ({
useIssueDraftStore: Object.assign(
(selector?: (state: typeof mockDraftStore) => unknown) =>
@@ -601,8 +624,6 @@ describe("CreateIssueModal", () => {
onSwitchMode={onSwitchMode}
isExpanded={false}
setIsExpanded={vi.fn()}
- backlogHintIssueId={null}
- setBacklogHintIssueId={vi.fn()}
/>,
);
@@ -719,8 +740,6 @@ describe("CreateIssueModal", () => {
data={{ project_id: "proj-1" }}
isExpanded={false}
setIsExpanded={vi.fn()}
- backlogHintIssueId={null}
- setBacklogHintIssueId={vi.fn()}
/>,
);
@@ -763,8 +782,6 @@ describe("CreateIssueModal", () => {
}}
isExpanded={false}
setIsExpanded={vi.fn()}
- backlogHintIssueId={null}
- setBacklogHintIssueId={vi.fn()}
/>,
);
@@ -815,8 +832,6 @@ describe("CreateIssueModal", () => {
onSwitchMode={vi.fn()}
isExpanded={false}
setIsExpanded={vi.fn()}
- backlogHintIssueId={null}
- setBacklogHintIssueId={vi.fn()}
/>,
);
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 6f96a684fb..1834724d35 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -37,8 +37,9 @@ import { Switch } from "@multica/ui/components/ui/switch";
import { ContentEditor, type ContentEditorRef, TitleEditor, useFileDropZone, FileDropOverlay } from "../editor";
import { StatusIcon, StatusPicker, PriorityPicker, StagePicker, AssigneePicker, StartDatePicker, DueDatePicker } from "../issues/components";
import { maxSiblingStage } from "../issues/components/pickers/stage-picker";
-import { BacklogAgentHintContent } from "../issues/components/backlog-agent-hint-dialog";
import { ProjectPicker } from "../projects/components/project-picker";
+import { useIssueTriggerPreview } from "../issues/hooks/use-issue-trigger-preview";
+import { useActorName } from "@multica/core/workspace/hooks";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";
@@ -56,6 +57,7 @@ import {
} from "@multica/core/api";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { PillButton } from "../common/pill-button";
+import { ActorAvatar } from "../common/actor-avatar";
import { IssuePickerModal } from "./issue-picker-modal";
import { useT } from "../i18n";
@@ -78,14 +80,102 @@ function toDraftAttachment(attachment: Attachment): Attachment {
// shell's local mode state.
// ---------------------------------------------------------------------------
+// CreateRunHint is the create modal's passive pre-trigger label (MUL-3375 §4):
+// whether saving will start a run, driven by the unified backend predicate
+// (preview, isCreate) — never a frontend guess. No dialog, no blocking.
+//
+// Visually it borrows the comment header's avatar+text line, minus the
+// interactivity — purely a caption, never a link/hover-card. It renders its own
+// reveal band (a grid 0fr→1fr collapse) so it sits on a dedicated row above the
+// property toolbar without reflowing anything: collapsed it is 0px (the flex-1
+// editor absorbs the delta), and it expands only once the predicate resolves,
+// animating straight to the correct copy.
+function CreateRunHint({
+ assigneeType,
+ assigneeId,
+ status,
+}: {
+ assigneeType?: IssueAssigneeType;
+ assigneeId?: string;
+ status: IssueStatus;
+}) {
+ const { t } = useT("modals");
+ const { getActorName } = useActorName();
+ const isAgentLike = assigneeType === "agent" || assigneeType === "squad";
+ const preview = useIssueTriggerPreview({
+ isCreate: true,
+ assigneeType: assigneeType ?? null,
+ assigneeId: assigneeId ?? null,
+ status,
+ enabled: isAgentLike && !!assigneeId,
+ });
+
+ // Reveal only after the predicate resolves so the band animates to the final
+ // copy instead of flashing "parked" before the run preview lands.
+ const ready = isAgentLike && !!assigneeId && !preview.isLoading;
+ const willStart = preview.totalCount > 0;
+ const isSquad = assigneeType === "squad";
+ const triggerAgentId = preview.triggers[0]?.agent_id ?? assigneeId;
+
+ // Avatar + copy mirror the flow. A squad doesn't "work" — its leader
+ // evaluates and delegates — so the squad path keeps the squad as the subject
+ // (avatar + name) and uses the leader-delegates copy. A single agent picks
+ // the issue up directly; a parked issue shows whoever it was assigned to.
+ let avatarType: string;
+ let avatarId: string | undefined;
+ let text: string;
+ if (!willStart) {
+ avatarType = assigneeType ?? "agent";
+ avatarId = assigneeId;
+ text = t(($) => $.run_confirm.create_parked);
+ } else if (isSquad) {
+ avatarType = "squad";
+ avatarId = assigneeId;
+ text = t(($) => $.run_confirm.create_will_start_squad, {
+ name: getActorName("squad", assigneeId ?? ""),
+ });
+ } else {
+ avatarType = "agent";
+ avatarId = triggerAgentId;
+ text = t(($) => $.run_confirm.create_will_start, {
+ name: getActorName("agent", triggerAgentId ?? assigneeId ?? ""),
+ });
+ }
+
+ return (
+ <div
+ className={cn(
+ "grid shrink-0 transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",
+ ready ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
+ )}
+ aria-hidden={!ready}
+ >
+ <div className="overflow-hidden">
+ <div
+ aria-live="polite"
+ className="flex items-center gap-1.5 px-4 pb-1 pt-0.5 text-[0.6875rem] text-muted-foreground"
+ >
+ {avatarId && (
+ <ActorAvatar
+ actorType={avatarType}
+ actorId={avatarId}
+ size={16}
+ profileLink={false}
+ />
+ )}
+ <span className="truncate">{text}</span>
+ </div>
+ </div>
+ </div>
+ );
+}
+
export function ManualCreatePanel({
onClose,
onSwitchMode,
data,
isExpanded,
setIsExpanded,
- backlogHintIssueId,
- setBacklogHintIssueId,
}: {
onClose: () => void;
/** Called with the carry payload to seed the agent panel after switch. */
@@ -96,8 +186,6 @@ export function ManualCreatePanel({
* re-mount the Portal on mode swap and replay the open animation). */
isExpanded: boolean;
setIsExpanded: (v: boolean) => void;
- backlogHintIssueId: string | null;
- setBacklogHintIssueId: (id: string | null) => void;
}) {
const { t } = useT("modals");
const router = useNavigation();
@@ -301,19 +389,16 @@ export function ManualCreatePanel({
setLastAssignee(assigneeType, assigneeId);
setLastMode("manual");
clearDraft();
- const shouldShowBacklogHint =
- status === "backlog" && assigneeType === "agent" && assigneeId &&
- localStorage.getItem("multica:backlog-agent-hint-dismissed") !== "true";
-
- if (shouldShowBacklogHint) {
- setBacklogHintIssueId(issue.id);
- } else if (keepOpen) {
+ // The old post-create "agent paused in Backlog" blocking panel is gone —
+ // a passive inline hint now warns before submit (MUL-3375). Just close or
+ // reset and confirm the create.
+ if (keepOpen) {
resetForNextIssue();
} else {
onClose();
}
- if (!shouldShowBacklogHint) {
+ {
toast.custom((toastId) => (
<div className="bg-popover text-popover-foreground border rounded-lg shadow-lg p-4 w-[360px]">
<div className="flex items-center gap-2 mb-2">
@@ -440,33 +525,6 @@ export function ManualCreatePanel({
return (
<>
- {backlogHintIssueId ? (
- <BacklogAgentHintContent
- onKeepInBacklog={() => {
- setBacklogHintIssueId(null);
- onClose();
- }}
- onDismissPermanently={() => {
- localStorage.setItem("multica:backlog-agent-hint-dismissed", "true");
- }}
- onMoveToTodo={() => {
- updateIssueMutation.mutate(
- { id: backlogHintIssueId, status: "todo" },
- {
- onError: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.backlog_hint.toast_status_failed),
- ),
- },
- );
- setBacklogHintIssueId(null);
- onClose();
- }}
- />
- ) : (
- <>
<DialogTitle className="sr-only">{t(($) => $.create_issue.sr_manual)}</DialogTitle>
{/* Header */}
@@ -539,6 +597,10 @@ export function ManualCreatePanel({
{descDragOver && <FileDropOverlay />}
</div>
+ {/* Pre-trigger preview — a passive caption above the toolbar; reveals
+ when an agent assignee will pick the issue up. */}
+ <CreateRunHint assigneeType={assigneeType} assigneeId={assigneeId} status={status} />
+
{/* Property toolbar */}
<div className="flex items-center gap-1.5 px-4 py-2 shrink-0 flex-wrap">
{/* Status */}
@@ -780,30 +842,21 @@ export function ManualCreatePanel({
)}
</div>
</div>
- </>
- )}
</>
);
}
-/** className for DialogContent in manual mode — depends on isExpanded and the
- * backlog-hint sub-state. Exported so the shell (which now owns the
- * DialogContent) can apply the same visual treatment without duplicating it. */
-export function manualDialogContentClass(
- isExpanded: boolean,
- backlogHintIssueId: string | null,
-) {
+/** className for DialogContent in manual mode — depends on isExpanded.
+ * Exported so the shell (which now owns the DialogContent) can apply the same
+ * visual treatment without duplicating it. */
+export function manualDialogContentClass(isExpanded: boolean) {
return cn(
"p-0 gap-0 flex flex-col overflow-hidden",
"!top-1/2 !left-1/2 !-translate-x-1/2",
- backlogHintIssueId
- ? "!max-w-[480px] !w-[calc(100vw-2rem)] !h-auto !-translate-y-1/2 !transition-none !duration-0"
- : "!transition-all !duration-300 !ease-out",
- !backlogHintIssueId && isExpanded
+ "!transition-all !duration-300 !ease-out",
+ isExpanded
? "!max-w-4xl !w-full !h-5/6 !-translate-y-1/2"
- : !backlogHintIssueId
- ? "!max-w-2xl !w-full !h-96 !-translate-y-1/2"
- : "",
+ : "!max-w-2xl !w-full !h-96 !-translate-y-1/2",
);
}
@@ -817,20 +870,17 @@ export function CreateIssueModal(props: {
data?: Record<string, unknown> | null;
}) {
const [isExpanded, setIsExpanded] = useState(false);
- const [backlogHintIssueId, setBacklogHintIssueId] = useState<string | null>(null);
return (
<DialogRoot open onOpenChange={(v) => { if (!v) props.onClose(); }}>
<DialogContent
finalFocus={false}
showCloseButton={false}
- className={manualDialogContentClass(isExpanded, backlogHintIssueId)}
+ className={manualDialogContentClass(isExpanded)}
>
<ManualCreatePanel
{...props}
isExpanded={isExpanded}
setIsExpanded={setIsExpanded}
- backlogHintIssueId={backlogHintIssueId}
- setBacklogHintIssueId={setBacklogHintIssueId}
/>
</DialogContent>
</DialogRoot>
diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsx
index 92ff13a0dd..b014515cf2 100644
--- a/packages/views/modals/registry.tsx
+++ b/packages/views/modals/registry.tsx
@@ -9,7 +9,7 @@ import { FeedbackModal } from "./feedback";
import { SetParentIssueModal } from "./set-parent-issue";
import { AddChildIssueModal } from "./add-child-issue";
import { DeleteIssueConfirmModal } from "./delete-issue-confirm";
-import { BacklogAgentHintModal } from "./backlog-agent-hint";
+import { RunConfirmModal } from "./run-confirm";
export function ModalRegistry() {
const modal = useModalStore((s) => s.modal);
@@ -37,8 +37,8 @@ export function ModalRegistry() {
return <AddChildIssueModal onClose={close} data={data} />;
case "issue-delete-confirm":
return <DeleteIssueConfirmModal onClose={close} data={data} />;
- case "issue-backlog-agent-hint":
- return <BacklogAgentHintModal onClose={close} data={data} />;
+ case "issue-run-confirm":
+ return <RunConfirmModal onClose={close} data={data} />;
default:
return null;
}
diff --git a/packages/views/modals/run-confirm.test.tsx b/packages/views/modals/run-confirm.test.tsx
new file mode 100644
index 0000000000..fa3c8e04ed
--- /dev/null
+++ b/packages/views/modals/run-confirm.test.tsx
@@ -0,0 +1,144 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { RunConfirmModal } from "./run-confirm";
+
+// --- Controllable preview result ---------------------------------------------
+const previewState = {
+ triggers: [{ issue_id: "issue-1", agent_id: "agent-1", source: "assign", handoff_supported: true }],
+ totalCount: 1,
+ isLoading: false,
+ handoffSupported: true,
+};
+vi.mock("../issues/hooks/use-issue-trigger-preview", () => ({
+ useIssueTriggerPreview: () => previewState,
+}));
+
+const mockUpdate = vi.fn().mockResolvedValue(undefined);
+const mockBatch = vi.fn().mockResolvedValue(undefined);
+vi.mock("@multica/core/issues/mutations", () => ({
+ useUpdateIssue: () => ({ mutateAsync: mockUpdate }),
+ useBatchUpdateIssues: () => ({ mutateAsync: mockBatch }),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: () => "Walt" }),
+}));
+
+vi.mock("../i18n", () => ({
+ useT: () => ({ t: (sel: (x: Record<string, Record<string, string>>) => string) => {
+ // Resolve the accessor against a flat label map so assertions can target text.
+ const labels = {
+ run_confirm: {
+ title_assign: "Assign and start?",
+ title_status: "Start working now?",
+ will_start_named: "start Walt",
+ will_start: "start many",
+ nothing_assign: "no run (backlog)",
+ nothing_status: "no runs",
+ note_label: "Handoff note",
+ note_placeholder: "scope...",
+ note_unsupported: "runtime too old",
+ start: "Start",
+ dont_start: "Don't start yet",
+ apply: "Apply",
+ toast_failed: "failed",
+ create_will_start: "create start",
+ create_parked: "create parked",
+ },
+ };
+ return sel(labels);
+ } }),
+}));
+
+// Keep the ui primitives as light DOM so the logic is what's under test.
+vi.mock("@multica/ui/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogHeader: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogFooter: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogDescription: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+vi.mock("@multica/ui/components/ui/button", () => ({
+ Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props}>{children}</button>
+ ),
+}));
+vi.mock("@multica/ui/components/ui/textarea", () => ({
+ Textarea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => <textarea {...props} />,
+}));
+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+
+beforeEach(() => {
+ mockUpdate.mockClear();
+ mockBatch.mockClear();
+ previewState.triggers = [{ issue_id: "issue-1", agent_id: "agent-1", source: "assign", handoff_supported: true }];
+ previewState.totalCount = 1;
+ previewState.handoffSupported = true;
+});
+
+describe("RunConfirmModal", () => {
+ it("single assign + Start sends the assignee change with the handoff note", async () => {
+ render(
+ <RunConfirmModal
+ onClose={vi.fn()}
+ data={{ issueIds: ["issue-1"], mode: "assign", assigneeType: "agent", assigneeId: "agent-1" }}
+ />,
+ );
+ fireEvent.change(screen.getByPlaceholderText("scope..."), { target: { value: "only login" } });
+ fireEvent.click(screen.getByText("Start"));
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledTimes(1));
+ expect(mockUpdate).toHaveBeenCalledWith({
+ id: "issue-1",
+ assignee_type: "agent",
+ assignee_id: "agent-1",
+ handoff_note: "only login",
+ });
+ expect(mockBatch).not.toHaveBeenCalled();
+ });
+
+ it("'暂不开始' sends suppress_run and no handoff note", async () => {
+ render(
+ <RunConfirmModal
+ onClose={vi.fn()}
+ data={{ issueIds: ["issue-1"], mode: "assign", assigneeType: "agent", assigneeId: "agent-1" }}
+ />,
+ );
+ fireEvent.change(screen.getByPlaceholderText("scope..."), { target: { value: "ignored" } });
+ fireEvent.click(screen.getByText("Don't start yet"));
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledTimes(1));
+ const payload = mockUpdate.mock.calls[0]![0];
+ expect(payload.suppress_run).toBe(true);
+ expect(payload.handoff_note).toBeUndefined();
+ });
+
+ it("disables the note box when the runtime can't render a handoff", () => {
+ previewState.handoffSupported = false;
+ render(
+ <RunConfirmModal
+ onClose={vi.fn()}
+ data={{ issueIds: ["issue-1"], mode: "assign", assigneeType: "agent", assigneeId: "agent-1" }}
+ />,
+ );
+ expect(screen.getByPlaceholderText("scope...")).toBeDisabled();
+ expect(screen.getByText("runtime too old")).toBeInTheDocument();
+ });
+
+ it("batch (N ids) applies via batchUpdate", async () => {
+ previewState.triggers = [
+ { issue_id: "i1", agent_id: "a1", source: "status", handoff_supported: true },
+ { issue_id: "i2", agent_id: "a2", source: "status", handoff_supported: true },
+ ];
+ previewState.totalCount = 2;
+ render(
+ <RunConfirmModal
+ onClose={vi.fn()}
+ data={{ issueIds: ["i1", "i2"], mode: "status", status: "todo" }}
+ />,
+ );
+ fireEvent.click(screen.getByText("Start"));
+ await waitFor(() => expect(mockBatch).toHaveBeenCalledTimes(1));
+ expect(mockBatch).toHaveBeenCalledWith({ ids: ["i1", "i2"], updates: { status: "todo" } });
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/modals/run-confirm.tsx b/packages/views/modals/run-confirm.tsx
new file mode 100644
index 0000000000..f613eb6a58
--- /dev/null
+++ b/packages/views/modals/run-confirm.tsx
@@ -0,0 +1,197 @@
+"use client";
+
+import { useState, type ReactNode } from "react";
+import { toast } from "sonner";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Button } from "@multica/ui/components/ui/button";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import type { IssueAssigneeType, IssueStatus, UpdateIssueRequest } from "@multica/core/types";
+import { useUpdateIssue, useBatchUpdateIssues } from "@multica/core/issues/mutations";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { useIssueTriggerPreview } from "../issues/hooks/use-issue-trigger-preview";
+import { useT } from "../i18n";
+
+const MAX_HANDOFF_NOTE = 2000;
+
+// i18next inlines {{name}} into the sentence, but the actor's position varies by
+// language ("{{name}} 会…" vs "Once assigned, {{name}} will…" vs "{{name}}'s
+// leader…"). Fence the name with a sentinel so we can bold just that span at
+// render time without splitting copy into per-language prefix/suffix keys.
+const NAME_FENCE = "\u0000";
+
+function boldName(text: string): ReactNode {
+ const parts = text.split(NAME_FENCE);
+ if (parts.length !== 3) return text;
+ return (
+ <>
+ {parts[0]}
+ <span className="font-semibold text-foreground">{parts[1]}</span>
+ {parts[2]}
+ </>
+ );
+}
+
+interface RunConfirmData {
+ issueIds?: string[];
+ mode?: "assign" | "status";
+ assigneeType?: IssueAssigneeType;
+ assigneeId?: string;
+ assigneeName?: string;
+ status?: IssueStatus;
+}
+
+/**
+ * Pre-trigger confirmation for issue writes that may start agent runs
+ * (MUL-3375 §4). Shows what the unified backend predicate says will start (via
+ * the preview endpoint — never a frontend guess), lets the user attach a
+ * handoff note (assign only) and choose "暂不开始", then applies the change.
+ * Dismissing the dialog (X / Esc / click-outside) cancels without any write.
+ * Shared by single assign (1 id) and batch assign / batch status (N ids).
+ */
+export function RunConfirmModal({
+ onClose,
+ data,
+}: {
+ onClose: () => void;
+ data: Record<string, unknown> | null;
+}) {
+ const { t } = useT("modals");
+ const { getActorName } = useActorName();
+ const d = (data ?? {}) as RunConfirmData;
+ const issueIds = d.issueIds ?? [];
+ const mode = d.mode ?? "assign";
+
+ const [note, setNote] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ const updateIssue = useUpdateIssue();
+ const batchUpdate = useBatchUpdateIssues();
+
+ const preview = useIssueTriggerPreview({
+ issueIds,
+ assigneeType: d.assigneeType ?? null,
+ assigneeId: d.assigneeId ?? null,
+ status: d.status,
+ enabled: issueIds.length > 0,
+ });
+
+ const willStart = preview.totalCount > 0;
+ const canNote = mode === "assign" && willStart;
+ // Soft gate: an old runtime can't render the note. Disable the box but let
+ // the assignment proceed (MUL-3375 §6.3).
+ const noteDisabled = canNote && !preview.handoffSupported;
+
+ const applyTo = (extra: Partial<UpdateIssueRequest>) => {
+ const base: UpdateIssueRequest =
+ mode === "assign"
+ ? { assignee_type: d.assigneeType ?? null, assignee_id: d.assigneeId ?? null }
+ : { status: d.status };
+ return { ...base, ...extra };
+ };
+
+ const submit = async (suppressRun: boolean) => {
+ if (issueIds.length === 0 || submitting) return;
+ setSubmitting(true);
+ const payload = applyTo({
+ ...(suppressRun ? { suppress_run: true } : {}),
+ ...(!suppressRun && canNote && !noteDisabled && note.trim()
+ ? { handoff_note: note.trim() }
+ : {}),
+ });
+ try {
+ if (issueIds.length === 1) {
+ await updateIssue.mutateAsync({ id: issueIds[0]!, ...payload });
+ } else {
+ await batchUpdate.mutateAsync({ ids: issueIds, updates: payload });
+ }
+ onClose();
+ } catch (err) {
+ toast.error(err instanceof Error && err.message ? err.message : t(($) => $.run_confirm.toast_failed));
+ setSubmitting(false);
+ }
+ };
+
+ // A squad doesn't "work" — its leader evaluates the issue and delegates. The
+ // copy reflects that (see issues.json squad_leader_*). Only knowable in assign
+ // mode, where assigneeType is carried; status-mode triggers expose only the
+ // resolved leader agent, so they stay on the generic copy.
+ const isSquad = mode === "assign" && d.assigneeType === "squad";
+
+ const headline: ReactNode = (() => {
+ if (!willStart) {
+ return mode === "assign"
+ ? t(($) => $.run_confirm.nothing_assign)
+ : t(($) => $.run_confirm.nothing_status);
+ }
+ // Single trigger → name the assignee (bolded), resolved from the preview's
+ // runnable agent (squad leader for squads). Batch → count.
+ if (preview.triggers.length === 1) {
+ if (isSquad) {
+ const name = d.assigneeName ?? getActorName("squad", d.assigneeId ?? "");
+ return boldName(t(($) => $.run_confirm.will_start_named_squad, { name: `${NAME_FENCE}${name}${NAME_FENCE}` }));
+ }
+ const name = d.assigneeName ?? getActorName("agent", preview.triggers[0]!.agent_id);
+ return boldName(t(($) => $.run_confirm.will_start_named, { name: `${NAME_FENCE}${name}${NAME_FENCE}` }));
+ }
+ return isSquad
+ ? t(($) => $.run_confirm.will_start_squad, { count: preview.totalCount })
+ : t(($) => $.run_confirm.will_start, { count: preview.totalCount });
+ })();
+
+ return (
+ <Dialog open onOpenChange={(v) => { if (!v && !submitting) onClose(); }}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ {mode === "assign" ? t(($) => $.run_confirm.title_assign) : t(($) => $.run_confirm.title_status)}
+ </DialogTitle>
+ <DialogDescription>{headline}</DialogDescription>
+ </DialogHeader>
+
+ {canNote ? (
+ <div className="grid gap-1.5">
+ <label className="text-sm font-medium" htmlFor="handoff-note">
+ {t(($) => $.run_confirm.note_label)}
+ </label>
+ <Textarea
+ id="handoff-note"
+ value={note}
+ maxLength={MAX_HANDOFF_NOTE}
+ disabled={noteDisabled || submitting}
+ placeholder={t(($) => $.run_confirm.note_placeholder)}
+ onChange={(e) => setNote(e.target.value)}
+ rows={3}
+ />
+ {noteDisabled ? (
+ <p className="text-xs text-muted-foreground">{t(($) => $.run_confirm.note_unsupported)}</p>
+ ) : null}
+ </div>
+ ) : null}
+
+ <DialogFooter>
+ {willStart ? (
+ <>
+ <Button type="button" variant="outline" disabled={submitting} onClick={() => submit(true)}>
+ {t(($) => $.run_confirm.dont_start)}
+ </Button>
+ <Button type="button" disabled={submitting} onClick={() => submit(false)}>
+ {t(($) => $.run_confirm.start)}
+ </Button>
+ </>
+ ) : (
+ <Button type="button" disabled={submitting} onClick={() => submit(false)}>
+ {t(($) => $.run_confirm.apply)}
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 3ba8cb455a..a969a8830f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -712,6 +712,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.ListIssues)
r.Post("/", h.CreateIssue)
r.Post("/quick-create", h.QuickCreateIssue)
+ r.Post("/preview-trigger", h.PreviewIssueTrigger)
r.Post("/batch-update", h.BatchUpdateIssues)
r.Post("/batch-delete", h.BatchDeleteIssues)
r.Route("/{id}", func(r chi.Router) {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 1695bf0892..387fa81bf5 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -3176,6 +3176,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
AutopilotSource: task.AutopilotSource,
AutopilotTriggerPayload: strings.TrimSpace(string(task.AutopilotTriggerPayload)),
QuickCreatePrompt: task.QuickCreatePrompt,
+ HandoffNote: task.HandoffNote,
IsSquadLeader: strings.Contains(instructions, "## Squad Operating Protocol"),
RequestingUserName: task.RequestingUserName,
RequestingUserProfileDescription: task.RequestingUserProfileDescription,
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index 8be5906cba..8c83cdfc0e 100644
--- a/server/internal/daemon/execenv/context.go
+++ b/server/internal/daemon/execenv/context.go
@@ -503,6 +503,14 @@ func renderIssueContext(provider string, ctx TaskContextForEnv) string {
b.WriteString("**Trigger:** New Assignment\n\n")
}
+ // Assignment handoff note (MUL-3375): the assigner's scoping instruction for
+ // this run. Distinct from a comment — there is no thread to reply to.
+ if ctx.HandoffNote != "" {
+ b.WriteString("## Handoff Note\n\n")
+ b.WriteString("The person who assigned this issue left this instruction for the run. Treat it as scope guidance and follow it before doing anything broader:\n\n")
+ fmt.Fprintf(&b, "> %s\n\n", ctx.HandoffNote)
+ }
+
b.WriteString("## Quick Start\n\n")
fmt.Fprintf(&b, "Run `multica issue get %s --output json` to fetch the full issue details.\n\n", ctx.IssueID)
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 36cdd4001d..4ace0f8947 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -85,6 +85,7 @@ type TaskContextForEnv struct {
AutopilotSource string
AutopilotTriggerPayload string
QuickCreatePrompt string // non-empty for quick-create tasks
+ HandoffNote string // assignment handoff instruction; rendered into issue_context.md (MUL-3375)
IsSquadLeader bool // true when the agent is acting as a squad leader (may exit silently on no_action)
// WorkspaceContext is the workspace-level system prompt (workspace.context
// in the DB). Rendered into the brief as `## Workspace Context` when
diff --git a/server/internal/daemon/execenv/handoff_context_test.go b/server/internal/daemon/execenv/handoff_context_test.go
new file mode 100644
index 0000000000..3f8ca0f667
--- /dev/null
+++ b/server/internal/daemon/execenv/handoff_context_test.go
@@ -0,0 +1,33 @@
+package execenv
+
+import (
+ "strings"
+ "testing"
+)
+
+// TestRenderIssueContext_HandoffNote verifies the handoff note lands in
+// issue_context.md under its own section, distinct from the comment-reply
+// trigger framing.
+func TestRenderIssueContext_HandoffNote(t *testing.T) {
+ note := "Scope to the auth module only."
+ md := renderIssueContext("claude", TaskContextForEnv{IssueID: "issue-1", HandoffNote: note})
+
+ if !strings.Contains(md, "## Handoff Note") {
+ t.Fatalf("expected Handoff Note section:\n%s", md)
+ }
+ if !strings.Contains(md, note) {
+ t.Fatalf("handoff note text missing:\n%s", md)
+ }
+ if !strings.Contains(md, "**Trigger:** New Assignment") {
+ t.Fatalf("handoff note must render under the assignment trigger:\n%s", md)
+ }
+}
+
+// TestRenderIssueContext_NoHandoffNote keeps the assignment context clean when
+// no note is present.
+func TestRenderIssueContext_NoHandoffNote(t *testing.T) {
+ md := renderIssueContext("claude", TaskContextForEnv{IssueID: "issue-1"})
+ if strings.Contains(md, "## Handoff Note") {
+ t.Fatalf("unexpected Handoff Note section when no note set:\n%s", md)
+ }
+}
diff --git a/server/internal/daemon/handoff_prompt_test.go b/server/internal/daemon/handoff_prompt_test.go
new file mode 100644
index 0000000000..0117edf4ae
--- /dev/null
+++ b/server/internal/daemon/handoff_prompt_test.go
@@ -0,0 +1,38 @@
+package daemon
+
+import (
+ "strings"
+ "testing"
+)
+
+// TestBuildPrompt_HandoffNote_AssignmentBranch verifies a handoff note on an
+// issue-assignment task renders through the assignment branch — it appears in
+// the prompt, framed as a handoff (not a comment to reply to), and does not
+// trip the quick-create branch.
+func TestBuildPrompt_HandoffNote_AssignmentBranch(t *testing.T) {
+ note := "Only touch the login flow; do not change payments."
+ out := BuildPrompt(Task{IssueID: "issue-123", HandoffNote: note}, "claude")
+
+ if !strings.Contains(out, note) {
+ t.Fatalf("handoff note missing from prompt:\n%s", out)
+ }
+ if !strings.Contains(out, "handoff note") {
+ t.Fatalf("expected handoff framing in prompt:\n%s", out)
+ }
+ if strings.Contains(out, "quick-create assistant") {
+ t.Fatalf("handoff task must not use the quick-create prompt branch:\n%s", out)
+ }
+ // Still an assignment task: should point the agent at `multica issue get`.
+ if !strings.Contains(out, "multica issue get issue-123") {
+ t.Fatalf("expected assignment prompt body:\n%s", out)
+ }
+}
+
+// TestBuildPrompt_NoHandoffNote_Unchanged verifies the assignment prompt is
+// unchanged when no handoff note is present (no stray handoff framing).
+func TestBuildPrompt_NoHandoffNote_Unchanged(t *testing.T) {
+ out := BuildPrompt(Task{IssueID: "issue-123"}, "claude")
+ if strings.Contains(out, "handoff note") {
+ t.Fatalf("unexpected handoff framing when no note set:\n%s", out)
+ }
+}
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index a1093a0581..f982eba03f 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -30,6 +30,13 @@ func BuildPrompt(task Task, provider string) string {
var b strings.Builder
b.WriteString("You are running as a local coding agent for a Multica workspace.\n\n")
fmt.Fprintf(&b, "Your assigned issue ID is: %s\n\n", task.IssueID)
+ // Assignment handoff (MUL-3375): a free-text instruction the person who
+ // assigned/promoted this issue left for you. Frame it as a handoff, not a
+ // comment to reply to — there is no comment thread to answer here.
+ if task.HandoffNote != "" {
+ b.WriteString("You were handed this issue with a handoff note. Treat it as the assigner's scoping instruction for this run; follow it before doing anything broader, and do not reply to it as if it were a comment:\n\n")
+ fmt.Fprintf(&b, "> %s\n\n", task.HandoffNote)
+ }
fmt.Fprintf(&b, "Start by running `multica issue get %s --output json` to understand your task, then complete it.\n", task.IssueID)
fmt.Fprintf(&b, "For comment history, follow the rule in your runtime workflow file (assignment-triggered tasks treat the read as mandatory). Start with `multica issue comment list %s --recent 10 --output json` to read the 10 most recently active threads, then page older threads via the stderr `Next thread cursor: ...` line and the matching `--before` / `--before-id` until you have enough history. `--since <RFC3339>` is still available for incremental polling and may combine with `--recent`.\n", task.IssueID)
return b.String()
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index aad4eb5e38..52184ede60 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -77,10 +77,12 @@ type Task struct {
AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachments uploaded in the quick-create prompt and bound by issue create
- SquadID string `json:"squad_id,omitempty"` // when the picker was a squad, the squad's UUID; Agent is still the resolved leader
- SquadName string `json:"squad_name,omitempty"` // display name for the picker squad, used in prompt text
- ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under
- ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, used in prompt context
+ HandoffNote string `json:"handoff_note,omitempty"` // assignment handoff instruction; rendered into the opening prompt + issue_context.md
+
+ SquadID string `json:"squad_id,omitempty"` // when the picker was a squad, the squad's UUID; Agent is still the resolved leader
+ SquadName string `json:"squad_name,omitempty"` // display name for the picker squad, used in prompt text
+ ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under
+ ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, used in prompt context
// RequestingUserName + RequestingUserProfileDescription describe the human
// the agent is working on behalf of. v1 sources them from the runtime
// owner (the user who registered the daemon). Empty when the runtime has
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 2ffeae49be..fecb9e9b9a 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -286,6 +286,7 @@ type AgentTaskResponse struct {
AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachment ids uploaded in the quick-create prompt and bound on issue create
+ HandoffNote string `json:"handoff_note,omitempty"` // assignment handoff instruction; rendered into the run's opening prompt + issue_context.md (omitempty so old daemons ignore it)
SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader
SquadName string `json:"squad_name,omitempty"` // display name for the picker squad
ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 70eb901c8a..540dc18eab 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1588,6 +1588,13 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
}
}
+ // Handoff note (MUL-3375): a first-class instruction set when the issue was
+ // assigned/promoted. Surfaced to the daemon so its prompt + issue_context.md
+ // can render the assignment-handoff branch. Empty for all other task kinds.
+ if task.HandoffNote.Valid {
+ resp.HandoffNote = task.HandoffNote.String
+ }
+
// Quick-create task: no issue / chat / autopilot link — workspace and
// prompt come from the task's context JSONB. Resolve workspace from
// there so the isolation check below has something to compare.
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 1ada8c6186..4a5c479239 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2317,6 +2317,17 @@ type UpdateIssueRequest struct {
// editor's preview Eye keeps working past a refresh. Existing bindings
// are idempotent — re-sending the same id is a no-op.
AttachmentIDs []string `json:"attachment_ids"`
+ // SuppressRun, when true, applies the assignee/status change as usual but
+ // skips starting the agent run this write would otherwise trigger
+ // ("暂时不启动" — MUL-3375). It is not an undo: the change takes effect and
+ // the issue can be run later via manual run/rerun. Optional; omitted or
+ // false keeps today's behavior. Mirrors comment suppress_agent_ids.
+ SuppressRun bool `json:"suppress_run,omitempty"`
+ // HandoffNote is an optional free-text instruction injected into the run's
+ // opening context when this write starts an agent/squad run ("交接说明" —
+ // MUL-3375). Only consumed when a run actually starts: SuppressRun=true or
+ // a parked/non-triggering write drops it. Never fabricates a comment.
+ HandoffNote string `json:"handoff_note,omitempty"`
}
func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
@@ -2553,40 +2564,24 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
"creator_id": uuidToString(prevIssue.CreatorID),
})
- // Reconcile task queue when assignee changes.
+ // Reconcile the task queue. Whether this write starts an agent run — and
+ // for whom (agent assignee or squad leader) — is decided by the single
+ // WillEnqueueRun predicate, shared verbatim with the preview endpoint so
+ // the two never drift (MUL-3375). Cancellation on reassignment is a
+ // separate side effect and always runs, independent of the run decision.
if assigneeChanged {
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
-
- if h.shouldEnqueueAgentTask(r.Context(), issue) {
- h.TaskService.EnqueueTaskForIssue(r.Context(), issue)
- }
-
- // Squad assign: trigger the squad leader, respecting the backlog
- // parking-lot rule used by agent assignment.
- if h.shouldEnqueueSquadLeaderOnAssign(r.Context(), issue) {
- h.enqueueSquadLeaderTask(r.Context(), issue, pgtype.UUID{}, actorType, actorID)
- }
}
-
- // Trigger the assigned agent when an issue moves out of backlog. Backlog
- // acts as a parking lot — moving to an active status signals the issue is
- // ready for work. Agent actors are allowed here so the documented
- // serial sub-task workflow works (parent agent finishes Step 1, then
- // promotes Step 2 from backlog→todo, regardless of who Step 2 is
- // assigned to). The only excluded case is the real self-loop: an agent
- // promoting the same issue its current task is running on. Same-agent,
- // cross-issue handoff (Agent A finishing one task and promoting another
- // issue assigned to A) must still fire — that is the documented serial
- // chain.
- if statusChanged && !assigneeChanged &&
- prevIssue.Status == "backlog" && issue.Status != "done" && issue.Status != "cancelled" &&
- !h.isAgentRunningOnIssue(r, actorType, issue) {
- if h.isAgentAssigneeReady(r.Context(), issue) {
- h.TaskService.EnqueueTaskForIssue(r.Context(), issue)
- }
- if h.isSquadLeaderReady(r.Context(), issue) {
- h.enqueueSquadLeaderTask(r.Context(), issue, pgtype.UUID{}, actorType, actorID)
- }
+ if trigger, ok := h.IssueService.WillEnqueueRun(r.Context(),
+ service.IssueTriggerInput{
+ Issue: issue,
+ PrevStatus: prevIssue.Status,
+ AssigneeChanged: assigneeChanged,
+ StatusChanged: statusChanged,
+ },
+ h.issueTriggerWriteProbe(r, actorType, issue),
+ ); ok && !req.SuppressRun {
+ h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, req.HandoffNote)
}
// Cancel active tasks when the issue is cancelled by a user.
@@ -3068,27 +3063,20 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if assigneeChanged {
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
- if h.shouldEnqueueAgentTask(r.Context(), issue) {
- h.TaskService.EnqueueTaskForIssue(r.Context(), issue)
- }
- if h.shouldEnqueueSquadLeaderOnAssign(r.Context(), issue) {
- h.enqueueSquadLeaderTask(r.Context(), issue, pgtype.UUID{}, actorType, actorID)
- }
}
-
- // Trigger agent when moving out of backlog (batch). Mirrors the
- // single-update path above — agent actors are allowed so serial
- // sub-task chains work, and the same task-issue self-loop guard
- // prevents an agent from re-triggering itself on the same issue.
- if statusChanged && !assigneeChanged &&
- prevIssue.Status == "backlog" && issue.Status != "done" && issue.Status != "cancelled" &&
- !h.isAgentRunningOnIssue(r, actorType, issue) {
- if h.isAgentAssigneeReady(r.Context(), issue) {
- h.TaskService.EnqueueTaskForIssue(r.Context(), issue)
- }
- if h.isSquadLeaderReady(r.Context(), issue) {
- h.enqueueSquadLeaderTask(r.Context(), issue, pgtype.UUID{}, actorType, actorID)
- }
+ // Same single predicate as UpdateIssue — batch must not grow its own
+ // copy of the enqueue rule (the historical source of four-entry-point
+ // drift, MUL-3375). suppress_run applies batch-wide.
+ if trigger, ok := h.IssueService.WillEnqueueRun(r.Context(),
+ service.IssueTriggerInput{
+ Issue: issue,
+ PrevStatus: prevIssue.Status,
+ AssigneeChanged: assigneeChanged,
+ StatusChanged: statusChanged,
+ },
+ h.issueTriggerWriteProbe(r, actorType, issue),
+ ); ok && !req.Updates.SuppressRun {
+ h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, req.Updates.HandoffNote)
}
// Cancel active tasks when the issue is cancelled by a user.
diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.go
new file mode 100644
index 0000000000..006e916f30
--- /dev/null
+++ b/server/internal/handler/issue_trigger.go
@@ -0,0 +1,225 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/util"
+ agentver "github.com/multica-ai/multica/server/pkg/agent"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// maxPreviewTriggerIssues caps a single preview request so a pathological
+// selection cannot fan out into thousands of readiness probes.
+const maxPreviewTriggerIssues = 500
+
+// issueTriggerWriteProbe builds the probe the write paths feed to
+// WillEnqueueRun. The private-agent gate is already enforced at the HTTP
+// boundary (validateAssigneePair on assign) and inside enqueueSquadLeaderTask
+// (canEnqueueSquadLeader), so a write must NOT re-run or sink it — it passes
+// allow-all. The self-loop check needs the request's X-Task-ID header.
+func (h *Handler) issueTriggerWriteProbe(r *http.Request, actorType string, issue db.Issue) service.IssueTriggerProbe {
+ return service.IssueTriggerProbe{
+ CanAccessAgent: nil, // allow-all; gate lives at the write boundary
+ IsSelfLoop: func() bool {
+ return h.isAgentRunningOnIssue(r, actorType, issue)
+ },
+ }
+}
+
+// issueTriggerPreviewProbe mirrors the real write-time gates for the read-only
+// preview: the private-agent gate (so preview never leaks a private agent's
+// readiness to a member who cannot see it — matching validateAssigneePair /
+// canEnqueueSquadLeader) and the same self-loop guard.
+func (h *Handler) issueTriggerPreviewProbe(r *http.Request, actorType, actorID, workspaceID string, issue db.Issue) service.IssueTriggerProbe {
+ return service.IssueTriggerProbe{
+ CanAccessAgent: func(agent db.Agent) bool {
+ at := actorType
+ if at == "system" {
+ at = "agent"
+ }
+ return h.canAccessPrivateAgent(r.Context(), agent, at, actorID, workspaceID)
+ },
+ IsSelfLoop: func() bool {
+ return h.isAgentRunningOnIssue(r, actorType, issue)
+ },
+ }
+}
+
+// dispatchIssueRun executes the enqueue side effect for a decision produced by
+// WillEnqueueRun, carrying an optional handoff note into the run's opening
+// context. The squad path still flows through enqueueSquadLeaderTask so the
+// leader access gate and pending dedup stay in one place.
+func (h *Handler) dispatchIssueRun(ctx context.Context, issue db.Issue, trigger service.IssueRunTrigger, actorType, actorID, handoffNote string) {
+ switch trigger.AssigneeType {
+ case "agent":
+ _, _ = h.TaskService.EnqueueTaskForIssueWithHandoff(ctx, issue, handoffNote)
+ case "squad":
+ h.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, actorType, actorID, handoffNote)
+ }
+}
+
+// IssueTriggerPreviewRequest asks "if I apply this assignee and/or status to
+// these issues (or create one), which runs will start". All fields are
+// optional; a nil prospective field means "leave unchanged".
+type IssueTriggerPreviewRequest struct {
+ // IssueIDs are existing issues to evaluate (single assign, single status,
+ // or a batch). Empty with IsCreate=true evaluates a candidate new issue.
+ IssueIDs []string `json:"issue_ids"`
+ // IsCreate previews a not-yet-persisted issue from AssigneeType/ID/Status.
+ IsCreate bool `json:"is_create"`
+ AssigneeType *string `json:"assignee_type"`
+ AssigneeID *string `json:"assignee_id"`
+ Status *string `json:"status"`
+}
+
+// IssueTriggerPreviewItem is one issue that WILL start a run under the
+// prospective write. AgentID is the runnable agent (squad leader for squads).
+// HandoffSupported is the soft-gate signal: false when the target runtime's
+// daemon is too old to render a handoff note, so the UI can gray out the note
+// box rather than silently drop the text. The assignment itself still works.
+type IssueTriggerPreviewItem struct {
+ IssueID string `json:"issue_id"`
+ AgentID string `json:"agent_id"`
+ Source string `json:"source"`
+ HandoffSupported bool `json:"handoff_supported"`
+}
+
+// IssueTriggerPreviewResponse lists every issue that will enqueue plus a total
+// the UI can show directly ("将启动 N 个"). Issues that will NOT start a run are
+// simply absent, so total_count == len(triggers).
+type IssueTriggerPreviewResponse struct {
+ Triggers []IssueTriggerPreviewItem `json:"triggers"`
+ TotalCount int `json:"total_count"`
+}
+
+// PreviewIssueTrigger dry-runs WillEnqueueRun for a prospective issue write and
+// returns the runs that would start, without any side effect. It is the single
+// authority the four entry points (create / single assign / single status /
+// batch) consult so the frontend never re-implements the enqueue rule
+// (MUL-3375). Mirrors PreviewCommentTriggers.
+func (h *Handler) PreviewIssueTrigger(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := h.resolveWorkspaceID(r)
+ if workspaceID == "" {
+ writeError(w, http.StatusBadRequest, "workspace is required")
+ return
+ }
+
+ var req IssueTriggerPreviewRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if len(req.IssueIDs) > maxPreviewTriggerIssues {
+ writeError(w, http.StatusBadRequest, "too many issue_ids")
+ return
+ }
+
+ // Resolve the prospective assignee once — a malformed id is a deterministic
+ // 400, never a silent miscount.
+ var (
+ newAssigneeType pgtype.Text
+ newAssigneeID pgtype.UUID
+ hasNewAssignee bool
+ )
+ if req.AssigneeType != nil && *req.AssigneeType != "" && req.AssigneeID != nil && *req.AssigneeID != "" {
+ id, parseOK := parseUUIDOrBadRequest(w, *req.AssigneeID, "assignee_id")
+ if !parseOK {
+ return
+ }
+ newAssigneeType = pgtype.Text{String: *req.AssigneeType, Valid: true}
+ newAssigneeID = id
+ hasNewAssignee = true
+ }
+
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ resp := IssueTriggerPreviewResponse{Triggers: make([]IssueTriggerPreviewItem, 0)}
+
+ appendTrigger := func(issue db.Issue, in service.IssueTriggerInput) {
+ probe := h.issueTriggerPreviewProbe(r, actorType, actorID, workspaceID, issue)
+ if trigger, ok := h.IssueService.WillEnqueueRun(r.Context(), in, probe); ok {
+ resp.Triggers = append(resp.Triggers, IssueTriggerPreviewItem{
+ IssueID: uuidToString(trigger.IssueID),
+ AgentID: uuidToString(trigger.AgentID),
+ Source: string(trigger.Source),
+ HandoffSupported: h.runtimeSupportsHandoff(r.Context(), trigger.AgentID),
+ })
+ }
+ }
+
+ if req.IsCreate {
+ wsUUID, err := util.ParseUUID(workspaceID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid workspace")
+ return
+ }
+ status := "todo"
+ if req.Status != nil && *req.Status != "" {
+ status = *req.Status
+ }
+ candidate := db.Issue{
+ WorkspaceID: wsUUID,
+ Status: status,
+ AssigneeType: newAssigneeType,
+ AssigneeID: newAssigneeID,
+ }
+ appendTrigger(candidate, service.IssueTriggerInput{Issue: candidate, IsCreate: true})
+ resp.TotalCount = len(resp.Triggers)
+ writeJSON(w, http.StatusOK, resp)
+ return
+ }
+
+ for _, rawID := range req.IssueIDs {
+ issueUUID, err := util.ParseUUID(rawID)
+ if err != nil {
+ continue // malformed id contributes no trigger; deterministic
+ }
+ loaded, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
+ ID: issueUUID,
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ continue // cross-workspace / unknown id contributes no trigger
+ }
+
+ post := loaded
+ in := service.IssueTriggerInput{PrevStatus: loaded.Status}
+ if hasNewAssignee {
+ post.AssigneeType = newAssigneeType
+ post.AssigneeID = newAssigneeID
+ in.AssigneeChanged = loaded.AssigneeType.String != newAssigneeType.String ||
+ uuidToString(loaded.AssigneeID) != uuidToString(newAssigneeID)
+ }
+ if req.Status != nil && *req.Status != "" {
+ post.Status = *req.Status
+ in.StatusChanged = loaded.Status != *req.Status
+ }
+ in.Issue = post
+ appendTrigger(post, in)
+ }
+
+ resp.TotalCount = len(resp.Triggers)
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// runtimeSupportsHandoff reports whether the agent's bound runtime reports a
+// CLI version new enough to render handoff notes. Drives the preview's
+// handoff_supported soft-gate signal. Any resolution failure → false (degrade).
+func (h *Handler) runtimeSupportsHandoff(ctx context.Context, agentID pgtype.UUID) bool {
+ agent, err := h.Queries.GetAgent(ctx, agentID)
+ if err != nil || !agent.RuntimeID.Valid {
+ return false
+ }
+ rt, err := h.Queries.GetAgentRuntime(ctx, agent.RuntimeID)
+ if err != nil {
+ return false
+ }
+ return agentver.HandoffSupported(readRuntimeCLIVersion(rt.Metadata))
+}
diff --git a/server/internal/handler/issue_trigger_preview_test.go b/server/internal/handler/issue_trigger_preview_test.go
new file mode 100644
index 0000000000..22896e5e2d
--- /dev/null
+++ b/server/internal/handler/issue_trigger_preview_test.go
@@ -0,0 +1,278 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// seededReadyAgentID returns a workspace agent that has a runtime bound (the
+// fixture's first agent), so WillEnqueueRun treats it as ready.
+func seededReadyAgentID(t *testing.T) string {
+ t.Helper()
+ var id string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL
+ ORDER BY created_at ASC LIMIT 1
+ `, testWorkspaceID).Scan(&id); err != nil {
+ t.Fatalf("load ready agent: %v", err)
+ }
+ return id
+}
+
+func previewIssueTrigger(t *testing.T, body map[string]any) IssueTriggerPreviewResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/preview-trigger?workspace_id="+testWorkspaceID, body)
+ testHandler.PreviewIssueTrigger(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("PreviewIssueTrigger: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp IssueTriggerPreviewResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode preview: %v", err)
+ }
+ return resp
+}
+
+func createIssueForTest(t *testing.T, body map[string]any) IssueResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, body)
+ testHandler.CreateIssue(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var created IssueResponse
+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {
+ t.Fatalf("decode issue: %v", err)
+ }
+ t.Cleanup(func() {
+ r := withURLParam(newRequest("DELETE", "/api/issues/"+created.ID, nil), "id", created.ID)
+ testHandler.DeleteIssue(httptest.NewRecorder(), r)
+ })
+ return created
+}
+
+func taskCountFor(t *testing.T, issueID, agentID string) int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2
+ `, issueID, agentID).Scan(&n); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ return n
+}
+
+// TestPreviewIssueTrigger_CreateAgentVsBacklog covers the create entry point:
+// an active status with an agent assignee previews one run; the same assignee
+// parked in backlog previews none.
+func TestPreviewIssueTrigger_CreateAgentVsBacklog(t *testing.T) {
+ agentID := seededReadyAgentID(t)
+
+ active := previewIssueTrigger(t, map[string]any{
+ "is_create": true,
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ "status": "todo",
+ })
+ if active.TotalCount != 1 || len(active.Triggers) != 1 {
+ t.Fatalf("active create: expected 1 trigger, got %+v", active)
+ }
+ if active.Triggers[0].AgentID != agentID || active.Triggers[0].Source != "assign" {
+ t.Fatalf("active create: wrong trigger %+v", active.Triggers[0])
+ }
+
+ backlog := previewIssueTrigger(t, map[string]any{
+ "is_create": true,
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ "status": "backlog",
+ })
+ if backlog.TotalCount != 0 {
+ t.Fatalf("backlog create: expected 0 triggers, got %+v", backlog)
+ }
+}
+
+// TestPreviewIssueTrigger_MemberNoTrigger verifies a member assignee never
+// previews a run.
+func TestPreviewIssueTrigger_MemberNoTrigger(t *testing.T) {
+ resp := previewIssueTrigger(t, map[string]any{
+ "is_create": true,
+ "assignee_type": "member",
+ "assignee_id": testUserID,
+ "status": "todo",
+ })
+ if resp.TotalCount != 0 {
+ t.Fatalf("member assignee: expected 0 triggers, got %+v", resp)
+ }
+}
+
+// TestPreviewIssueTrigger_BatchAggregates verifies the batch shape: two
+// agent-assigned issues moving out of backlog preview two distinct runs.
+func TestPreviewIssueTrigger_BatchAggregates(t *testing.T) {
+ agentID := seededReadyAgentID(t)
+ i1 := createIssueForTest(t, map[string]any{"title": "batch preview 1", "status": "backlog", "assignee_type": "agent", "assignee_id": agentID})
+ i2 := createIssueForTest(t, map[string]any{"title": "batch preview 2", "status": "backlog", "assignee_type": "agent", "assignee_id": agentID})
+
+ resp := previewIssueTrigger(t, map[string]any{
+ "issue_ids": []string{i1.ID, i2.ID},
+ "status": "todo",
+ })
+ if resp.TotalCount != 2 {
+ t.Fatalf("batch promote: expected total_count 2, got %+v", resp)
+ }
+ seen := map[string]bool{}
+ for _, tr := range resp.Triggers {
+ if tr.Source != "status" {
+ t.Fatalf("batch promote: expected source=status, got %q", tr.Source)
+ }
+ seen[tr.IssueID] = true
+ }
+ if !seen[i1.ID] || !seen[i2.ID] {
+ t.Fatalf("batch promote: missing an issue in %+v", resp.Triggers)
+ }
+}
+
+// TestPreviewIssueTrigger_MatchesWritePath is the core invariant: when preview
+// says a run will start, the real write path enqueues it; when preview says it
+// won't, the write path enqueues nothing.
+func TestPreviewIssueTrigger_MatchesWritePath(t *testing.T) {
+ agentID := seededReadyAgentID(t)
+
+ // Case 1: preview says assign will start → write path enqueues.
+ issue := createIssueForTest(t, map[string]any{"title": "match write 1", "status": "todo"})
+ pv := previewIssueTrigger(t, map[string]any{
+ "issue_ids": []string{issue.ID},
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ if pv.TotalCount != 1 {
+ t.Fatalf("preview assign: expected 1, got %+v", pv)
+ }
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{"assignee_type": "agent", "assignee_id": agentID}), "id", issue.ID)
+ testHandler.UpdateIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateIssue assign: %d %s", w.Code, w.Body.String())
+ }
+ if got := taskCountFor(t, issue.ID, agentID); got == 0 {
+ t.Fatalf("preview promised a run but write path enqueued none")
+ }
+
+ // Case 2: preview says backlog assign will NOT start → write enqueues none.
+ issue2 := createIssueForTest(t, map[string]any{"title": "match write 2", "status": "backlog"})
+ pv2 := previewIssueTrigger(t, map[string]any{
+ "issue_ids": []string{issue2.ID},
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ "status": "backlog",
+ })
+ if pv2.TotalCount != 0 {
+ t.Fatalf("preview backlog assign: expected 0, got %+v", pv2)
+ }
+ w2 := httptest.NewRecorder()
+ req2 := withURLParam(newRequest("PUT", "/api/issues/"+issue2.ID, map[string]any{"assignee_type": "agent", "assignee_id": agentID}), "id", issue2.ID)
+ testHandler.UpdateIssue(w2, req2)
+ if w2.Code != http.StatusOK {
+ t.Fatalf("UpdateIssue backlog assign: %d %s", w2.Code, w2.Body.String())
+ }
+ if got := taskCountFor(t, issue2.ID, agentID); got != 0 {
+ t.Fatalf("preview said no run for backlog assign but write path enqueued %d", got)
+ }
+}
+
+// TestUpdateIssueSuppressRunSkipsEnqueue verifies suppress_run applies the
+// assignee change but starts no run, while the same write without it does.
+func TestUpdateIssueSuppressRunSkipsEnqueue(t *testing.T) {
+ agentID := seededReadyAgentID(t)
+
+ // Suppressed assign: assignee set, no task.
+ suppressed := createIssueForTest(t, map[string]any{"title": "suppress on", "status": "todo"})
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest("PUT", "/api/issues/"+suppressed.ID, map[string]any{
+ "assignee_type": "agent", "assignee_id": agentID, "suppress_run": true,
+ }), "id", suppressed.ID)
+ testHandler.UpdateIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateIssue suppressed: %d %s", w.Code, w.Body.String())
+ }
+ if got := taskCountFor(t, suppressed.ID, agentID); got != 0 {
+ t.Fatalf("suppress_run=true should not enqueue, got %d tasks", got)
+ }
+
+ // Control: same write without suppress_run enqueues.
+ control := createIssueForTest(t, map[string]any{"title": "suppress off", "status": "todo"})
+ w2 := httptest.NewRecorder()
+ req2 := withURLParam(newRequest("PUT", "/api/issues/"+control.ID, map[string]any{
+ "assignee_type": "agent", "assignee_id": agentID,
+ }), "id", control.ID)
+ testHandler.UpdateIssue(w2, req2)
+ if w2.Code != http.StatusOK {
+ t.Fatalf("UpdateIssue control: %d %s", w2.Code, w2.Body.String())
+ }
+ if got := taskCountFor(t, control.ID, agentID); got == 0 {
+ t.Fatalf("control (no suppress_run) should enqueue, got 0 tasks")
+ }
+}
+
+// TestUpdateIssueHandoffNotePersistsOnTask verifies an assign carrying a
+// handoff_note writes that note onto the enqueued task (the daemon then renders
+// it), while a suppressed assign with a note enqueues nothing at all.
+func TestUpdateIssueHandoffNotePersistsOnTask(t *testing.T) {
+ agentID := seededReadyAgentID(t)
+ note := "Only touch the login flow."
+
+ issue := createIssueForTest(t, map[string]any{"title": "handoff persist", "status": "todo"})
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{
+ "assignee_type": "agent", "assignee_id": agentID, "handoff_note": note,
+ }), "id", issue.ID)
+ testHandler.UpdateIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateIssue with handoff: %d %s", w.Code, w.Body.String())
+ }
+
+ var stored string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT COALESCE(handoff_note, '') FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 ORDER BY created_at DESC LIMIT 1
+ `, issue.ID, agentID).Scan(&stored); err != nil {
+ t.Fatalf("read task handoff_note: %v", err)
+ }
+ if stored != note {
+ t.Fatalf("expected task handoff_note %q, got %q", note, stored)
+ }
+
+ // Suppressed assign with a note: no task at all (no run to inject into).
+ suppressed := createIssueForTest(t, map[string]any{"title": "handoff suppressed", "status": "todo"})
+ w2 := httptest.NewRecorder()
+ req2 := withURLParam(newRequest("PUT", "/api/issues/"+suppressed.ID, map[string]any{
+ "assignee_type": "agent", "assignee_id": agentID, "handoff_note": note, "suppress_run": true,
+ }), "id", suppressed.ID)
+ testHandler.UpdateIssue(w2, req2)
+ if w2.Code != http.StatusOK {
+ t.Fatalf("UpdateIssue suppressed handoff: %d %s", w2.Code, w2.Body.String())
+ }
+ if got := taskCountFor(t, suppressed.ID, agentID); got != 0 {
+ t.Fatalf("suppressed handoff should enqueue no task, got %d", got)
+ }
+}
+
+// TestPreviewIssueTrigger_MalformedBody verifies the endpoint rejects a
+// malformed body with 400 rather than a 500 or a silent empty result.
+func TestPreviewIssueTrigger_MalformedBody(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", "/api/issues/preview-trigger?workspace_id="+testWorkspaceID, strings.NewReader("{not json"))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ testHandler.PreviewIssueTrigger(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("malformed body: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index c94aba5073..66671a159d 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -12,7 +12,6 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
- "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -938,62 +937,31 @@ func commentMentionsAnyone(content string) bool {
return false
}
-// shouldEnqueueSquadLeaderOnAssign returns true when assigning an issue to a
-// squad (or creating an issue pre-assigned to a squad) should immediately
-// trigger the squad leader. Mirrors shouldEnqueueAgentTask: backlog issues
-// are skipped (parking lot), and the leader agent must have a runtime and
-// not be archived.
-func (h *Handler) shouldEnqueueSquadLeaderOnAssign(ctx context.Context, issue db.Issue) bool {
- if issue.Status == "backlog" {
- return false
- }
- return h.isSquadLeaderReady(ctx, issue)
-}
-
-// isSquadLeaderReady returns true when the issue is assigned to a squad whose
-// leader agent can accept work right now. Readiness criteria (archived,
-// runtime bound, runtime online) are shared with the autopilot admission
-// gate via service.AgentReadiness — both paths must move together or one
-// will start enqueueing tasks the other refuses (MUL-2429 RFC §4.b B4).
-func (h *Handler) isSquadLeaderReady(ctx context.Context, issue db.Issue) bool {
- if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {
- return false
- }
- squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
- ID: issue.AssigneeID,
- WorkspaceID: issue.WorkspaceID,
- })
- if err != nil {
- return false
- }
- agent, err := h.Queries.GetAgent(ctx, squad.LeaderID)
- if err != nil {
- return false
- }
- ready, _, err := service.AgentReadiness(ctx, h.Queries, agent)
- if err != nil {
- // Fail closed when we can't tell — same posture as the rest of
- // this function (any error path returns false).
- return false
- }
- return ready
-}
+// The squad-leader assign/promotion readiness decision now lives in the single
+// service.IssueService.WillEnqueueRun predicate (MUL-3375), shared by the issue
+// write paths and the preview endpoint. The former handler-local mirrors
+// (shouldEnqueueSquadLeaderOnAssign / isSquadLeaderReady) were removed to stop
+// the four-entry-point drift. The squad enqueue side effect still flows through
+// enqueueSquadLeaderTask below, which keeps the leader access gate and pending
+// dedup in one place.
// enqueueSquadLeaderTask triggers the squad leader agent for an issue assigned
// to a squad. Assign and backlog-promotion paths use this directly; comment
// paths go through computeCommentAgentTriggers so preview and create share the
// same trigger set.
-func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, authorType, authorID string) {
+// enqueueSquadLeaderTask returns true when it actually enqueued a leader task
+// (so the caller can record a handoff trace only on a real run start).
+func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, authorType, authorID, handoffNote string) bool {
squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
ID: issue.AssigneeID,
WorkspaceID: issue.WorkspaceID,
})
if err != nil {
- return
+ return false
}
if !h.canEnqueueSquadLeader(ctx, squad.LeaderID, authorType, authorID, uuidToString(issue.WorkspaceID)) {
- return
+ return false
}
hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
@@ -1001,14 +969,19 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, tr
AgentID: squad.LeaderID,
})
if err != nil || hasPending {
- return
+ return false
}
- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, squad.LeaderID, triggerCommentID); err != nil {
+ // triggerCommentID is always empty on the assign/promote path; the handoff
+ // note rides its own task column, never trigger_comment_id.
+ _ = triggerCommentID
+ if _, err := h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, handoffNote); err != nil {
slog.Warn("enqueue squad leader task failed",
"issue_id", uuidToString(issue.ID),
"squad_id", uuidToString(squad.ID),
"leader_id", uuidToString(squad.LeaderID),
"error", err)
+ return false
}
+ return true
}
diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.go
new file mode 100644
index 0000000000..647864d33f
--- /dev/null
+++ b/server/internal/service/issue_trigger.go
@@ -0,0 +1,173 @@
+package service
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// RunEnqueueSource identifies which kind of issue write would start an agent
+// run. It is surfaced in preview responses so the UI can explain each trigger.
+type RunEnqueueSource string
+
+const (
+ // RunSourceAssign covers issue creation and assignee changes — the issue
+ // is being handed to an agent/squad. Parks silently on backlog.
+ RunSourceAssign RunEnqueueSource = "assign"
+ // RunSourceStatus covers promoting an already-assigned issue out of
+ // backlog into an active status.
+ RunSourceStatus RunEnqueueSource = "status"
+)
+
+// IssueTriggerProbe carries the request-scoped checks WillEnqueueRun cannot
+// resolve from issue state alone.
+//
+// CanAccessAgent is the private-agent gate. The write paths enforce it at the
+// HTTP boundary (validateAssigneePair on assign, canEnqueueSquadLeader inside
+// the squad enqueue helper) and therefore pass an allow-all probe so the gate
+// is never duplicated or sunk into the service layer. Preview passes the real
+// gate so it never leaks a private agent's readiness to a member who cannot
+// see it. A nil func is treated as allow-all.
+//
+// IsSelfLoop reports whether promoting this issue out of backlog would be the
+// calling agent re-triggering its own running task. Only the status source
+// consults it; create and assign never do. A nil func means "not a self-loop".
+type IssueTriggerProbe struct {
+ CanAccessAgent func(agent db.Agent) bool
+ IsSelfLoop func() bool
+}
+
+// IssueTriggerInput describes one prospective issue write in its post-write
+// shape. AssigneeChanged / StatusChanged mark which fields the write touches;
+// IsCreate marks a brand-new issue (no prior task to cancel, no self-loop).
+type IssueTriggerInput struct {
+ Issue db.Issue
+ PrevStatus string
+ IsCreate bool
+ AssigneeChanged bool
+ StatusChanged bool
+}
+
+// IssueRunTrigger is the resolved decision shared by preview and the write
+// paths. AgentID is the agent that will actually run — the assignee for an
+// agent issue, the squad leader for a squad issue.
+type IssueRunTrigger struct {
+ IssueID pgtype.UUID
+ AgentID pgtype.UUID
+ AssigneeType string
+ Source RunEnqueueSource
+}
+
+func allowAllAgents(db.Agent) bool { return true }
+
+// WillEnqueueRun is the single predicate answering "will this issue write
+// start an agent run, and for whom". It is the one source of truth shared by
+// the issue update / batch-update write paths and the preview endpoint,
+// replacing the per-site copies that drifted (squad omitted, self-loop
+// omitted, four entry points inconsistent — see MUL-3375).
+//
+// It is intentionally a distinct predicate from the comment trigger
+// (shouldEnqueueOnComment): issue writes park on backlog while comments fire
+// in any status. The two only share leaf readiness checks (AgentReadiness,
+// the pending-task dedup), not the top-level decision.
+//
+// The decision must equal the real enqueue conditions so preview never claims
+// a run that the write path then drops. In particular:
+// - assign source (create / assignee change) cancels existing tasks before
+// enqueuing, so a pre-existing pending task is moot — not checked here.
+// - status source (backlog → active) enqueues without cancelling, so a live
+// pending task would be blocked by the (issue_id, agent_id) unique index;
+// reflected by the pending check below.
+func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput, probe IssueTriggerProbe) (IssueRunTrigger, bool) {
+ issue := in.Issue
+ if !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {
+ return IssueRunTrigger{}, false
+ }
+ canAccess := probe.CanAccessAgent
+ if canAccess == nil {
+ canAccess = allowAllAgents
+ }
+
+ var source RunEnqueueSource
+ switch {
+ case in.IsCreate || in.AssigneeChanged:
+ // Backlog is the parking lot: assigning into backlog never starts a run.
+ if issue.Status == "backlog" {
+ return IssueRunTrigger{}, false
+ }
+ source = RunSourceAssign
+ case in.StatusChanged && in.PrevStatus == "backlog" &&
+ issue.Status != "done" && issue.Status != "cancelled":
+ if probe.IsSelfLoop != nil && probe.IsSelfLoop() {
+ return IssueRunTrigger{}, false
+ }
+ source = RunSourceStatus
+ default:
+ return IssueRunTrigger{}, false
+ }
+
+ switch issue.AssigneeType.String {
+ case "agent":
+ agent, err := s.Queries.GetAgent(ctx, issue.AssigneeID)
+ if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ return IssueRunTrigger{}, false
+ }
+ if !canAccess(agent) {
+ return IssueRunTrigger{}, false
+ }
+ if source == RunSourceStatus && s.hasPendingRun(ctx, issue.ID, issue.AssigneeID) {
+ return IssueRunTrigger{}, false
+ }
+ return IssueRunTrigger{
+ IssueID: issue.ID,
+ AgentID: issue.AssigneeID,
+ AssigneeType: "agent",
+ Source: source,
+ }, true
+
+ case "squad":
+ squad, err := s.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: issue.AssigneeID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ return IssueRunTrigger{}, false
+ }
+ leader, err := s.Queries.GetAgent(ctx, squad.LeaderID)
+ if err != nil {
+ return IssueRunTrigger{}, false
+ }
+ ready, _, err := AgentReadiness(ctx, s.Queries, leader)
+ if err != nil || !ready {
+ return IssueRunTrigger{}, false
+ }
+ if !canAccess(leader) {
+ return IssueRunTrigger{}, false
+ }
+ if source == RunSourceStatus && s.hasPendingRun(ctx, issue.ID, squad.LeaderID) {
+ return IssueRunTrigger{}, false
+ }
+ return IssueRunTrigger{
+ IssueID: issue.ID,
+ AgentID: squad.LeaderID,
+ AssigneeType: "squad",
+ Source: source,
+ }, true
+ }
+ return IssueRunTrigger{}, false
+}
+
+// hasPendingRun reports whether the agent already holds a queued or dispatched
+// task for the issue (the (issue_id, agent_id) unique-index slot). Errors fail
+// closed to "pending" so preview never over-promises a run.
+func (s *IssueService) hasPendingRun(ctx context.Context, issueID, agentID pgtype.UUID) bool {
+ pending, err := s.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
+ IssueID: issueID,
+ AgentID: agentID,
+ })
+ if err != nil {
+ return true
+ }
+ return pending
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 8a4073073e..76e679323b 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -434,7 +434,15 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, t
if len(triggerCommentID) > 0 {
commentID = triggerCommentID[0]
}
- return s.enqueueIssueTask(ctx, issue, commentID, false)
+ return s.enqueueIssueTask(ctx, issue, commentID, false, "")
+}
+
+// EnqueueTaskForIssueWithHandoff is the assign/promote variant that carries a
+// handoff note into the run's opening context (MUL-3375). The note rides a
+// dedicated task column; the daemon renders it via the assignment-handoff
+// branch. Empty note behaves exactly like EnqueueTaskForIssue.
+func (s *TaskService) EnqueueTaskForIssueWithHandoff(ctx context.Context, issue db.Issue, handoffNote string) (db.AgentTaskQueue, error) {
+ return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, handoffNote)
}
// enqueueIssueTask is the shared implementation behind EnqueueTaskForIssue
@@ -442,7 +450,7 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, t
// daemon claim handler skips the (agent_id, issue_id) resume lookup — the
// user already judged the prior output bad, a fresh agent session is the
// expected behavior.
-func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
if !issue.AssigneeID.Valid {
slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", "issue has no assignee")
return db.AgentTaskQueue{}, fmt.Errorf("issue has no assignee")
@@ -470,6 +478,7 @@ func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, trig
TriggerCommentID: triggerCommentID,
TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),
ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},
+ HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},
})
if err != nil {
slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", err)
@@ -497,7 +506,7 @@ func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, trig
// Unlike EnqueueTaskForIssue, this takes an explicit agent ID rather than
// deriving it from the issue assignee.
func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, false)
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, false, "")
}
// EnqueueTaskForSquadLeader is the leader-role variant of EnqueueTaskForMention.
@@ -507,10 +516,17 @@ func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue,
// as a worker (do not skip). This matters for agents that are simultaneously
// the leader and a worker of the same squad — see migration 090.
func (s *TaskService) EnqueueTaskForSquadLeader(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true, false)
+ return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true, false, "")
+}
+
+// EnqueueTaskForSquadLeaderWithHandoff is the assign/promote variant carrying a
+// handoff note into the leader run's opening context (MUL-3375). Empty note
+// behaves exactly like EnqueueTaskForSquadLeader.
+func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, handoffNote string) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, false, handoffNote)
}
-func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, forceFreshSession bool) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
agent, err := s.Queries.GetAgent(ctx, agentID)
if err != nil {
slog.Error("mention task enqueue failed: agent not found", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
@@ -534,6 +550,7 @@ func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, ag
TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),
IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},
ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},
+ HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},
})
if err != nil {
slog.Error("mention task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
@@ -1702,9 +1719,9 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool) (db.AgentTaskQueue, error) {
if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&
util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {
- return s.enqueueIssueTask(ctx, issue, triggerCommentID, true)
+ return s.enqueueIssueTask(ctx, issue, triggerCommentID, true, "")
}
- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, isLeader, true)
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, isLeader, true, "")
}
// HandleFailedTasks runs the post-failure side effects for a batch of
diff --git a/server/migrations/122_task_handoff_note.down.sql b/server/migrations/122_task_handoff_note.down.sql
new file mode 100644
index 0000000000..2e23659457
--- /dev/null
+++ b/server/migrations/122_task_handoff_note.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS handoff_note;
diff --git a/server/migrations/122_task_handoff_note.up.sql b/server/migrations/122_task_handoff_note.up.sql
new file mode 100644
index 0000000000..5483f44ae8
--- /dev/null
+++ b/server/migrations/122_task_handoff_note.up.sql
@@ -0,0 +1,6 @@
+-- Handoff note: a first-class, optional free-text instruction attached when an
+-- issue is assigned/promoted to an agent or squad (MUL-3375). The daemon
+-- renders it into the run's opening prompt and issue_context.md via a dedicated
+-- "assignment handoff" branch — NOT by fabricating a comment or reusing
+-- trigger_comment_id. NULL means "no handoff note" (today's behavior).
+ALTER TABLE agent_task_queue ADD COLUMN handoff_note TEXT;
diff --git a/server/pkg/agent/handoff_version_test.go b/server/pkg/agent/handoff_version_test.go
new file mode 100644
index 0000000000..5627c82986
--- /dev/null
+++ b/server/pkg/agent/handoff_version_test.go
@@ -0,0 +1,26 @@
+package agent
+
+import "testing"
+
+func TestHandoffSupported(t *testing.T) {
+ tests := []struct {
+ name string
+ version string
+ want bool
+ }{
+ {"at minimum", MinHandoffCLIVersion, true},
+ {"above minimum", "0.4.0", true},
+ {"below minimum", "0.3.26", false},
+ {"far below", "0.2.21", false},
+ {"empty (unreported)", "", false},
+ {"unparsable", "garbage", false},
+ {"dev git-describe build", "v0.3.0-5-gabc1234", true},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := HandoffSupported(tc.version); got != tc.want {
+ t.Fatalf("HandoffSupported(%q) = %v, want %v", tc.version, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.go
index df0a40de16..93c8dbc3d5 100644
--- a/server/pkg/agent/version.go
+++ b/server/pkg/agent/version.go
@@ -26,6 +26,38 @@ var MinVersions = map[string]string{
// this threshold all fail closed.
const MinQuickCreateCLIVersion = "0.2.21"
+// MinHandoffCLIVersion is the lowest multica CLI version whose daemon renders
+// the assignment handoff note into the run's opening prompt + issue_context.md
+// (MUL-3375). Unlike quick-create this is a SOFT gate: assigning an issue with
+// a note never fails on an old daemon — the assignment still takes effect, the
+// note is simply dropped. The frontend reads HandoffSupported to gray out the
+// note box and warn the user, so they aren't surprised by a silently ignored
+// note. Bump this to the release that actually ships the daemon rendering.
+const MinHandoffCLIVersion = "0.3.28"
+
+// HandoffSupported reports whether a daemon reporting cliVersion is new enough
+// to render handoff notes. Reuses the CheckMinCLIVersion parsing (including the
+// git-describe dev-build exemption) but never errors — a missing/old/unparsable
+// version simply means "not supported", which the soft gate degrades gracefully.
+func HandoffSupported(cliVersion string) bool {
+ d := strings.TrimSpace(cliVersion)
+ if d == "" {
+ return false
+ }
+ if devDescribeRe.MatchString(d) {
+ return true
+ }
+ parsed, err := parseSemver(d)
+ if err != nil {
+ return false
+ }
+ min, err := parseSemver(MinHandoffCLIVersion)
+ if err != nil {
+ return false
+ }
+ return !parsed.lessThan(min)
+}
+
// Errors returned by CheckMinCLIVersion. Callers branch on these to surface
// "needs upgrade" vs "version not reported" with the right user message.
var (
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index bf8e7648c1..a86befb2ac 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -178,7 +178,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -212,6 +212,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -220,7 +221,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -265,6 +266,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -280,7 +282,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Cancels active tasks belonging to a chat session. Called from
@@ -325,6 +327,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -340,7 +343,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -385,6 +388,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -400,7 +404,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -449,6 +453,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -464,7 +469,7 @@ const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComm
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Cancels active tasks whose trigger is the given comment. Called when a
@@ -509,6 +514,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -547,7 +553,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:
@@ -590,6 +596,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -673,7 +680,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type CompleteAgentTaskParams struct {
@@ -719,6 +726,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -813,15 +821,16 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
const createAgentTask = `-- name: CreateAgentTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, force_fresh_session, is_leader_task
+ trigger_summary, force_fresh_session, is_leader_task, handoff_note
)
VALUES (
$1, $2, $3, 'queued', $4, $5,
$6,
COALESCE($7::boolean, FALSE),
- COALESCE($8::boolean, FALSE)
+ COALESCE($8::boolean, FALSE),
+ $9
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type CreateAgentTaskParams struct {
@@ -833,6 +842,7 @@ type CreateAgentTaskParams struct {
TriggerSummary pgtype.Text `json:"trigger_summary"`
ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
IsLeaderTask pgtype.Bool `json:"is_leader_task"`
+ HandoffNote pgtype.Text `json:"handoff_note"`
}
func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams) (AgentTaskQueue, error) {
@@ -845,6 +855,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
arg.TriggerSummary,
arg.ForceFreshSession,
arg.IsLeaderTask,
+ arg.HandoffNote,
)
var i AgentTaskQueue
err := row.Scan(
@@ -875,6 +886,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -882,7 +894,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
const createQuickCreateTask = `-- name: CreateQuickCreateTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context)
VALUES ($1, $2, NULL, 'queued', $3, $4)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type CreateQuickCreateTaskParams struct {
@@ -931,6 +943,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -952,7 +965,7 @@ SELECT
p.is_leader_task
FROM agent_task_queue p
WHERE p.id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Clones a parent task into a fresh queued attempt. Carries forward the
@@ -996,6 +1009,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -1018,7 +1032,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note
`
type ExpireStaleQueuedTasksParams struct {
@@ -1086,6 +1100,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -1106,7 +1121,7 @@ SET status = 'failed',
session_id = COALESCE($4, session_id),
work_dir = COALESCE($5, work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type FailAgentTaskParams struct {
@@ -1163,6 +1178,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -1173,7 +1189,7 @@ SET status = 'failed', completed_at = now(), error = 'task timed out',
failure_reason = 'timeout'
WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => $1::double precision))
OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type FailStaleTasksParams struct {
@@ -1226,6 +1242,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -1313,7 +1330,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
WHERE id = $1
`
@@ -1348,12 +1365,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -1401,6 +1419,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -1830,7 +1849,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -1877,6 +1896,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -1889,7 +1909,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -1931,6 +1951,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -2041,7 +2062,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -2083,6 +2104,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -2095,7 +2117,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -2145,6 +2167,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -2157,7 +2180,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -2199,6 +2222,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -2211,15 +2235,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id FROM (
- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id
+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note FROM (
+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -2283,6 +2307,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -2298,7 +2323,7 @@ const markAgentTaskWaitingLocalDirectory = `-- name: MarkAgentTaskWaitingLocalDi
UPDATE agent_task_queue
SET status = 'waiting_local_directory', wait_reason = $2
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -2346,6 +2371,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -2363,7 +2389,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -2407,6 +2433,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
@@ -2419,7 +2446,7 @@ SET status = 'failed',
failure_reason = 'runtime_recovery',
wait_reason = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -2465,6 +2492,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -2557,7 +2585,7 @@ const startAgentTask = `-- name: StartAgentTask :one
UPDATE agent_task_queue
SET status = 'running', started_at = now(), wait_reason = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -2597,6 +2625,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index fcef44a618..d1907b20e3 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -241,7 +241,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)
VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type CreateAutopilotTaskParams struct {
@@ -292,6 +292,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 67298a4fa3..28d3eeb468 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -90,7 +90,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
const createChatTask = `-- name: CreateChatTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id, initiator_user_id)
VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type CreateChatTaskParams struct {
@@ -138,6 +138,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 1cfbfcd182..18b8b82726 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -99,6 +99,7 @@ type AgentTaskQueue struct {
IsLeaderTask bool `json:"is_leader_task"`
WaitReason pgtype.Text `json:"wait_reason"`
InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ HandoffNote pgtype.Text `json:"handoff_note"`
}
type Attachment struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 2637169e57..3555d57d23 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -75,6 +75,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
@@ -194,7 +195,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -237,6 +238,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.IsLeaderTask,
&i.WaitReason,
&i.InitiatorUserID,
+ &i.HandoffNote,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 0d867f0c1f..cd75a72517 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -136,13 +136,14 @@ ORDER BY created_at DESC;
-- name: CreateAgentTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, force_fresh_session, is_leader_task
+ trigger_summary, force_fresh_session, is_leader_task, handoff_note
)
VALUES (
$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),
sqlc.narg(trigger_summary),
COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),
- COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE)
+ COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),
+ sqlc.narg(handoff_note)
)
RETURNING *;