Skip to content

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

Go

fix(create-issue): preserve parent_issue_id through Create with agent flow (MUL-2534) (#3083)

Bohan Jiang17714c3ad13c
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 52092b8b49..efe944b252 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -526,6 +526,7 @@ export class ApiClient {
squad_id?: string;
prompt: string;
project_id?: string | null;
+ parent_issue_id?: string | null;
}): Promise<{ task_id: string }> {
return this.fetch("/api/issues/quick-create", {
method: "POST",
diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.json
index f76c0c8fe6..c13f16a215 100644
--- a/packages/views/locales/en/modals.json
+++ b/packages/views/locales/en/modals.json
@@ -185,7 +185,8 @@
"toast_sent": "Sent to agent — you'll get an inbox notification when it's done",
"error_agent_unavailable_fallback": "Agent is unavailable. Pick another agent.",
"error_daemon_version": "This agent's daemon CLI ({{current}}) is below the required {{min}}. Upgrade the daemon to use Create with agent.",
- "error_unknown": "Failed to submit. Try again."
+ "error_unknown": "Failed to submit. Try again.",
+ "sub_issue_of": "Sub-issue of {{identifier}}"
}
}
}
diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.json
index 872f8ccd10..e6c5ebffe7 100644
--- a/packages/views/locales/zh-Hans/modals.json
+++ b/packages/views/locales/zh-Hans/modals.json
@@ -185,7 +185,8 @@
"toast_sent": "已交给智能体——完成后会在收件箱通知你",
"error_agent_unavailable_fallback": "智能体不可用,请换一个。",
"error_daemon_version": "该智能体的守护进程 CLI({{current}})低于要求的 {{min}}。请升级守护进程后再使用通过智能体创建。",
- "error_unknown": "提交失败,请重试。"
+ "error_unknown": "提交失败,请重试。",
+ "sub_issue_of": "作为 {{identifier}} 的子 issue"
}
}
}
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index 2b4d88c8c6..a0940b9830 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -564,6 +564,50 @@ describe("CreateIssueModal", () => {
);
});
+ // Manual → agent must forward parent_issue_id when the modal was opened
+ // from "Add sub issue". Before this, the agent panel received no parent
+ // context and the new issue was filed as a standalone — silently dropping
+ // the sub-issue intent set by openCreateSubIssue. The parent_issue_identifier
+ // tags along so the agent panel can render a "Sub-issue of MUL-XX" chip
+ // without an extra round-trip.
+ //
+ // The identifier fallback matters here: the mocked issueDetailOptions
+ // resolves to null (parent query not hydrated), so without the
+ // `data.parent_issue_identifier` fallback the agent chip would render as
+ // "Sub-issue of " with an empty tail. The UUID alone still wires the
+ // sub-issue relationship correctly, but the visible affordance breaks.
+ it("forwards parent_issue_id and falls back to seeded identifier when switching to agent mode", async () => {
+ const user = userEvent.setup();
+ const onSwitchMode = vi.fn();
+
+ renderModal(
+ <ManualCreatePanel
+ onClose={vi.fn()}
+ onSwitchMode={onSwitchMode}
+ data={{
+ parent_issue_id: "parent-uuid-1",
+ parent_issue_identifier: "MUL-2534",
+ }}
+ isExpanded={false}
+ setIsExpanded={vi.fn()}
+ backlogHintIssueId={null}
+ setBacklogHintIssueId={vi.fn()}
+ />,
+ );
+
+ await user.type(screen.getByPlaceholderText("Issue title"), "Refactor auth");
+ await user.click(screen.getByRole("button", { name: /Switch to Agent/i }));
+
+ expect(onSwitchMode).toHaveBeenCalledTimes(1);
+ expect(onSwitchMode.mock.calls[0]?.[0]).toEqual(
+ expect.objectContaining({
+ prompt: "Refactor auth",
+ parent_issue_id: "parent-uuid-1",
+ parent_issue_identifier: "MUL-2534",
+ }),
+ );
+ });
+
// Start date is a low-frequency field — by default it lives behind the
// ⋯ overflow menu and is not rendered inline. Clicking the overflow
// entry opens it (and mounts the inline pill so the popover has an
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 8ec579d22d..69283205da 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -352,6 +352,10 @@ export function ManualCreatePanel({
// Forward squad picks alongside agent picks so the agent panel honors
// the actor the user already chose — otherwise a squad selection silently
// falls back to the persisted actor / first visible agent on flip.
+ // parent_issue_id rides through the same carry channel: the modal opener
+ // (openCreateSubIssue) seeded it on the manual panel, and the agent panel
+ // needs it so the new issue is still created as a sub-issue when the user
+ // flips from "Add sub issue" → "Create with agent".
const switchToAgent = () => {
const desc = descEditorRef.current?.getMarkdown()?.trim() ?? "";
const prompt = [title.trim(), desc].filter(Boolean).join("\n\n");
@@ -361,6 +365,14 @@ export function ManualCreatePanel({
// duplicate content on every round-trip.
setDraft({ title: "", description: "" });
setLastMode("agent");
+ // Prefer the hydrated identifier from `parentIssue`, but fall back to the
+ // identifier the modal opener seeded on `data`. Without the fallback, a
+ // flip that happens before the issue detail query resolves drops the
+ // identifier and the agent chip renders as "Sub-issue of " with an empty
+ // tail. The UUID alone still wires the sub-issue relationship correctly;
+ // this only affects the display affordance.
+ const carryParentIdentifier =
+ parentIssue?.identifier ?? (data?.parent_issue_identifier as string | undefined);
onSwitchMode?.({
prompt,
...(assigneeId && assigneeType === "agent"
@@ -369,6 +381,8 @@ export function ManualCreatePanel({
? { squad_id: assigneeId }
: {}),
...(projectId ? { project_id: projectId } : {}),
+ ...(parentIssueId ? { parent_issue_id: parentIssueId } : {}),
+ ...(carryParentIdentifier ? { parent_issue_identifier: carryParentIdentifier } : {}),
});
};
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index 7547887dec..ba2c70b58c 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -413,4 +413,54 @@ describe("AgentCreatePanel", () => {
expect(mockSetLastProjectId).not.toHaveBeenCalled();
});
+
+ // When the modal was opened from "Add sub issue" on an existing issue,
+ // the manual panel transfers parent_issue_id through the `data` payload
+ // on switch-to-agent. The agent panel must forward that UUID to the
+ // quick-create API silently — without surfacing a parent picker — so the
+ // new issue is filed as a sub-issue. Dropping parent_issue_id here was
+ // the original bug; this locks the wiring in.
+ it("forwards parent_issue_id from the carry payload to the quick-create API", async () => {
+ const user = userEvent.setup();
+
+ renderPanel({
+ onClose: vi.fn(),
+ isExpanded: false,
+ setIsExpanded: vi.fn(),
+ data: {
+ parent_issue_id: "parent-uuid-1",
+ parent_issue_identifier: "MUL-2534",
+ },
+ });
+
+ // Sub-issue context chip is visible so the user knows the new issue
+ // will be filed as a sub-issue.
+ expect(screen.getByTestId("agent-sub-issue-chip")).toBeInTheDocument();
+
+ const editor = screen.getByPlaceholderText(
+ 'Tell the agent what to do, e.g. "let Bohan fix the inbox loading slowness in the Web project"',
+ );
+ await user.clear(editor);
+ await user.type(editor, "Investigate the regression");
+
+ await user.click(screen.getByRole("button", { name: /^Create \(/i }));
+
+ await waitFor(() => {
+ expect(mockQuickCreateIssue).toHaveBeenCalledWith({
+ agent_id: "agent-1",
+ prompt: "Investigate the regression",
+ project_id: undefined,
+ parent_issue_id: "parent-uuid-1",
+ });
+ });
+ });
+
+ // The sub-issue chip is purely opt-in context — it only appears when the
+ // modal was opened from an "Add sub issue" entry. A plain quick-create
+ // (no parent in data) must NOT render the chip; otherwise users would see
+ // a stray badge on every quick-create.
+ it("does not render the sub-issue chip when no parent is seeded", () => {
+ renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
+ expect(screen.queryByTestId("agent-sub-issue-chip")).toBeNull();
+ });
});
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index 7da62199f6..783fa3a024 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -201,6 +201,16 @@ export function AgentCreatePanel({
return seed ?? null;
});
+ // Parent-issue context — seeded by `openCreateSubIssue` when the modal is
+ // opened from the "Add sub issue" entry on an existing issue. We carry it
+ // through (not as an editable form field) so a manual→agent flip preserves
+ // the sub-issue intent; the agent panel never exposes this as a picker.
+ // Identifier is best-effort display context only — the UUID is the
+ // authoritative reference the backend/agent uses for `--parent <uuid>`.
+ const parentIssueId = (data?.parent_issue_id as string | undefined) ?? undefined;
+ const parentIssueIdentifier =
+ (data?.parent_issue_identifier as string | undefined) ?? undefined;
+
// Stale-id sweep. Once the project list query has actually resolved
// (`isSuccess` — distinct from "data is the empty default during loading"),
// a `projectId` that isn't in the list means the project was deleted in
@@ -280,6 +290,7 @@ export function AgentCreatePanel({
: { squad_id: actor.id }),
prompt: md,
project_id: projectId ?? undefined,
+ parent_issue_id: parentIssueId,
});
setLastActor(actor.type, actor.id);
setLastProjectId(projectId);
@@ -358,11 +369,17 @@ export function AgentCreatePanel({
: {}),
});
setLastMode("manual");
- // Hand the picked project to the manual panel through the same `data`
- // channel that already carries agent_id / parent_issue_id. The manual
- // panel reads `data.project_id` on mount; this preserves the user's
- // selection across the mode flip without piping a third store through.
- onSwitchMode?.(projectId ? { project_id: projectId } : null);
+ // Hand the picked project and the parent-issue context to the manual
+ // panel through the same `data` channel that already carries agent_id /
+ // parent_issue_id. The manual panel reads these on mount; this preserves
+ // the user's selection (and the sub-issue intent seeded by
+ // openCreateSubIssue) across the mode flip without piping a third store
+ // through.
+ const carry: Record<string, unknown> = {};
+ if (projectId) carry.project_id = projectId;
+ if (parentIssueId) carry.parent_issue_id = parentIssueId;
+ if (parentIssueIdentifier) carry.parent_issue_identifier = parentIssueIdentifier;
+ onSwitchMode?.(Object.keys(carry).length > 0 ? carry : null);
};
return (
@@ -467,7 +484,14 @@ export function AgentCreatePanel({
owns only the project (status / priority / assignee / due-date are
inferred from the prompt), so it's a single pill. The pick is
persisted per-workspace via useQuickCreateStore.lastProjectId so
- users targeting one project skip retyping "in project X". */}
+ users targeting one project skip retyping "in project X".
+ When the modal was opened from "Add sub issue" on an existing
+ issue, a read-only chip on the same row tells the user that the
+ new issue will be filed as a sub-issue of that parent — the agent
+ handles the wiring silently, but surfacing the relationship
+ avoids "where did this end up?" surprise. We deliberately keep
+ it non-editable: changing the parent is a `Set parent` action on
+ the parent itself, not a knob in the quick-create flow. */}
<div className="flex items-center gap-1.5 px-4 pb-2 shrink-0 flex-wrap">
<ProjectPicker
projectId={projectId}
@@ -475,6 +499,19 @@ export function AgentCreatePanel({
triggerRender={<PillButton />}
align="start"
/>
+ {parentIssueId && (
+ <span
+ data-testid="agent-sub-issue-chip"
+ className="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground"
+ title={t(($) => $.create_issue.agent.sub_issue_of, {
+ identifier: parentIssueIdentifier ?? "",
+ })}
+ >
+ {t(($) => $.create_issue.agent.sub_issue_of, {
+ identifier: parentIssueIdentifier ?? "",
+ })}
+ </span>
+ )}
</div>
{/* Footer */}
diff --git a/server/cmd/server/quick_create_subscriber_test.go b/server/cmd/server/quick_create_subscriber_test.go
index 9193de1c19..b694cc2591 100644
--- a/server/cmd/server/quick_create_subscriber_test.go
+++ b/server/cmd/server/quick_create_subscriber_test.go
@@ -37,6 +37,7 @@ func TestQuickCreateCompletion_SubscribesRequester(t *testing.T) {
pgtype.UUID{},
"please file a bug",
pgtype.UUID{},
+ pgtype.UUID{},
)
if err != nil {
t.Fatalf("EnqueueQuickCreateTask: %v", err)
@@ -110,6 +111,7 @@ func TestQuickCreateFailure_DoesNotSubscribeRequester(t *testing.T) {
pgtype.UUID{},
"another bug",
pgtype.UUID{},
+ pgtype.UUID{},
)
if err != nil {
t.Fatalf("EnqueueQuickCreateTask: %v", err)
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index dfb7e1aea5..196f9ee0a0 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -105,6 +105,18 @@ func buildQuickCreatePrompt(task Task) string {
} else {
b.WriteString("- **project**: omit. The platform will route the issue to the workspace default.\n")
}
+ // parent — pinned by the modal when the user opened it from "Add sub
+ // issue" on an existing issue. Pass the UUID (never the identifier) so
+ // the create lands the sub-issue under the right parent even when the
+ // workspace prefix changes; the identifier is included in the prose
+ // purely as human-readable context for the agent.
+ if task.ParentIssueID != "" {
+ if task.ParentIssueIdentifier != "" {
+ fmt.Fprintf(&b, "- **parent**: required for this run. Pass `--parent %q` so the new issue is filed as a sub-issue of %s (the user opened quick-create from that issue's \"Add sub issue\" entry). Do not infer a different parent from the prompt text — the modal entry point is authoritative.\n", task.ParentIssueID, task.ParentIssueIdentifier)
+ } else {
+ fmt.Fprintf(&b, "- **parent**: required for this run. Pass `--parent %q` so the new issue is filed as a sub-issue of the parent the user picked in the quick-create modal. Do not infer a different parent from the prompt text — the modal entry point is authoritative.\n", task.ParentIssueID)
+ }
+ }
b.WriteString("- **status**: omit (defaults to `todo`).\n")
b.WriteString("- **attachments**: do NOT pass `--attachment`. The flag only accepts LOCAL file paths. Any image URL in the user input is already markdown — keep it inline in `--description` instead.\n\n")
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index 828c890398..06e433d632 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -154,6 +154,55 @@ func TestBuildQuickCreatePromptProjectPinning(t *testing.T) {
}
}
+// TestBuildQuickCreatePromptParentPinning verifies that when the user
+// opened quick-create from "Add sub issue" on an existing issue, the prompt
+// instructs the agent to pass `--parent <uuid>` so the new issue is filed
+// as a sub-issue. The frontend already seeds parent_issue_id silently
+// through the manual→agent switch, so this is the last hop that has to
+// hold up — without the prompt instruction the agent would create a
+// standalone issue and the sub-issue relationship would be silently
+// dropped.
+func TestBuildQuickCreatePromptParentPinning(t *testing.T) {
+ const (
+ parentID = "33333333-2222-1111-4444-555555555555"
+ parentIdentifier = "MUL-2534"
+ )
+ out := buildQuickCreatePrompt(Task{
+ QuickCreatePrompt: "fix the login button color",
+ ParentIssueID: parentID,
+ ParentIssueIdentifier: parentIdentifier,
+ })
+ mustContain := []string{
+ "--parent \"" + parentID + "\"",
+ parentIdentifier,
+ "modal entry point is authoritative",
+ "filed as a sub-issue",
+ }
+ for _, s := range mustContain {
+ if !strings.Contains(out, s) {
+ t.Errorf("buildQuickCreatePrompt with parent missing %q\n--- output ---\n%s", s, out)
+ }
+ }
+
+ // When only the UUID is available (identifier lookup failed on claim),
+ // the agent must still get the --parent instruction so the sub-issue
+ // intent isn't silently dropped.
+ uuidOnly := buildQuickCreatePrompt(Task{
+ QuickCreatePrompt: "fix the login button color",
+ ParentIssueID: parentID,
+ })
+ if !strings.Contains(uuidOnly, "--parent \""+parentID+"\"") {
+ t.Errorf("buildQuickCreatePrompt with parent UUID only must still pin --parent, got:\n%s", uuidOnly)
+ }
+
+ // Without a parent, the prompt must NOT mention --parent at all — a
+ // plain quick-create run should not start filing sub-issues.
+ plain := buildQuickCreatePrompt(Task{QuickCreatePrompt: "fix the login button color"})
+ if strings.Contains(plain, "--parent") {
+ t.Errorf("buildQuickCreatePrompt without parent must NOT mention --parent, got:\n%s", plain)
+ }
+}
+
// TestBuildPromptSquadLeaderNoActionForMemberTrigger verifies that the
// squad leader no_action prohibition is injected in the per-turn prompt
// regardless of whether the triggering comment was posted by an agent or
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 897576dc71..e1d66c54d8 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -67,6 +67,8 @@ type Task struct {
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
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 9b7f96a1b3..484902a36b 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -201,6 +201,8 @@ type AgentTaskResponse struct {
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
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
+ ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context
// RequestingUserName + RequestingUserProfileDescription mirror the user
// the agent is acting on behalf of (see daemon/types.go). v1 sources them
// from the runtime owner so they're populated for daemon runtimes and
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index ccb1d3f657..356aeda490 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1446,6 +1446,32 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
}
}
+ // Parent-issue resolution for quick-create tasks opened from
+ // "Add sub issue". The handler already verified workspace
+ // membership at submit time; here we re-fetch to pull the
+ // human-readable identifier (e.g. MUL-123) the agent will
+ // reference in the prompt. If the parent was deleted between
+ // submit and claim we surface the UUID anyway — the agent
+ // still passes `--parent <uuid>` and the server-side create
+ // will fail loud, which is a better outcome than silently
+ // dropping the sub-issue intent.
+ if qc.ParentIssueID != "" {
+ resp.ParentIssueID = qc.ParentIssueID
+ if parentUUID, err := util.ParseUUID(qc.ParentIssueID); err == nil {
+ if wsUUID, wsErr := util.ParseUUID(qc.WorkspaceID); wsErr == nil {
+ parent, perr := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
+ ID: parentUUID,
+ WorkspaceID: wsUUID,
+ })
+ if perr == nil && parent.ID.Valid {
+ if ws, werr := h.Queries.GetWorkspace(r.Context(), wsUUID); werr == nil {
+ resp.ParentIssueIdentifier = ws.IssuePrefix + "-" + strconv.Itoa(int(parent.Number))
+ }
+ }
+ }
+ }
+ }
+
// Squad-leader briefing injection for quick-create tasks. When
// the user picked a squad in the modal, the task runs on the
// squad's leader agent (resolved by the handler). Surface the
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 2e86d937e8..d081a8b8b1 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -1592,11 +1592,18 @@ func (h *Handler) ChildIssueProgress(w http.ResponseWriter, r *http.Request) {
// the agent's `multica issue create` invocation passes `--project <uuid>`
// instead of letting it default. The frontend remembers the user's last
// pick per workspace, so frequent users skip retyping "in project X".
+//
+// ParentIssueID is optional and is set by the "Add sub issue" entry point
+// when the modal is opened from an existing issue. The agent passes it
+// through as `--parent <uuid>` so the new issue is filed as a sub-issue,
+// keeping the sub-issue intent of the entry point regardless of whether
+// the user submits via manual or agent mode.
type QuickCreateIssueRequest struct {
- AgentID string `json:"agent_id,omitempty"`
- SquadID string `json:"squad_id,omitempty"`
- Prompt string `json:"prompt"`
- ProjectID string `json:"project_id,omitempty"`
+ AgentID string `json:"agent_id,omitempty"`
+ SquadID string `json:"squad_id,omitempty"`
+ Prompt string `json:"prompt"`
+ ProjectID string `json:"project_id,omitempty"`
+ ParentIssueID string `json:"parent_issue_id,omitempty"`
}
// QuickCreateIssueResponse echoes the queued task id so the frontend can
@@ -1743,7 +1750,28 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {
projectUUID = pid
}
- task, err := h.TaskService.EnqueueQuickCreateTask(r.Context(), wsUUID, requesterUUID, agentUUID, squadUUID, prompt, projectUUID)
+ // Optional parent_issue_id — validate same-workspace membership just like
+ // the regular CreateIssue path. Frontend seeds this from the "Add sub
+ // issue" entry, but the handler re-checks so a forged request can't
+ // smuggle a foreign parent UUID through.
+ var parentIssueUUID pgtype.UUID
+ if strings.TrimSpace(req.ParentIssueID) != "" {
+ pid, ok := parseUUIDOrBadRequest(w, req.ParentIssueID, "parent_issue_id")
+ if !ok {
+ return
+ }
+ parent, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
+ ID: pid,
+ WorkspaceID: wsUUID,
+ })
+ if err != nil || !parent.ID.Valid {
+ writeError(w, http.StatusBadRequest, "parent issue not found in this workspace")
+ return
+ }
+ parentIssueUUID = pid
+ }
+
+ task, err := h.TaskService.EnqueueQuickCreateTask(r.Context(), wsUUID, requesterUUID, agentUUID, squadUUID, prompt, projectUUID, parentIssueUUID)
if err != nil {
slog.Warn("quick-create enqueue failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to enqueue quick-create task")
diff --git a/server/internal/handler/quick_create_parent_test.go b/server/internal/handler/quick_create_parent_test.go
new file mode 100644
index 0000000000..41a09ac74a
--- /dev/null
+++ b/server/internal/handler/quick_create_parent_test.go
@@ -0,0 +1,202 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// TestQuickCreateIssueParentTrustBoundary locks the server-side trust boundary
+// for the optional parent_issue_id field on POST /api/issues/quick-create.
+//
+// The frontend seeds parent_issue_id from the "Add sub issue" entry point and
+// otherwise leaves it empty. The handler is the trust boundary: a forged
+// request must not be able to smuggle a foreign parent UUID through to the
+// quick-create task context, and the same-workspace happy path must thread
+// the resolved UUID into QuickCreateContext.ParentIssueID so the daemon claim
+// step can resolve the identifier and emit `--parent <uuid>` in the prompt.
+//
+// Three branches are covered:
+//
+// 1. Same-workspace parent → 202 Accepted, task enqueued with
+// QuickCreateContext.ParentIssueID populated.
+// 2. Foreign-workspace parent → 400 Bad Request, no task enqueued.
+// 3. Bogus UUID parent → 400 Bad Request, no task enqueued.
+func TestQuickCreateIssueParentTrustBoundary(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ // Resolve the seeded runtime + agent for this workspace, then bump the
+ // runtime metadata to a CLI version that clears MinQuickCreateCLIVersion.
+ // The seed runtime uses metadata '{}'::jsonb which would otherwise trip
+ // the daemon-version gate before we ever reach the parent_issue_id check.
+ var runtimeID, agentID string
+ if err := testPool.QueryRow(ctx,
+ `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&runtimeID); err != nil {
+ t.Fatalf("fetch runtime: %v", err)
+ }
+ if err := testPool.QueryRow(ctx,
+ `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&agentID); err != nil {
+ t.Fatalf("fetch agent: %v", err)
+ }
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_runtime SET metadata = jsonb_build_object('cli_version', $1::text) WHERE id = $2`,
+ agent.MinQuickCreateCLIVersion, runtimeID,
+ ); err != nil {
+ t.Fatalf("bump runtime cli_version: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `UPDATE agent_runtime SET metadata = '{}'::jsonb WHERE id = $1`, runtimeID)
+ })
+
+ // Same-workspace parent — must be accepted and threaded through.
+ var localParentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+ VALUES ($1, 'quick-create parent (local)', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&localParentID); err != nil {
+ t.Fatalf("create local parent issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, localParentID)
+ })
+
+ // Foreign-workspace parent — must be rejected.
+ var foreignWorkspaceID, foreignUserID, foreignParentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id
+ `, "QuickCreate Foreign", "[email protected]").Scan(&foreignUserID); err != nil {
+ t.Fatalf("create foreign user: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, foreignUserID)
+ })
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ($1, $2, $3, $4) RETURNING id
+ `, "QuickCreate Foreign WS", "quickcreate-foreign-ws", "", "QCF").Scan(&foreignWorkspaceID); err != nil {
+ t.Fatalf("create foreign workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)
+ })
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+ VALUES ($1, 'quick-create parent (foreign)', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, foreignWorkspaceID, foreignUserID).Scan(&foreignParentID); err != nil {
+ t.Fatalf("create foreign parent issue: %v", err)
+ }
+ // The foreign workspace cleanup above cascades, but the issue row also
+ // needs a direct cleanup in case workspace deletion ordering changes.
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, foreignParentID)
+ })
+
+ // Helper for the "must not enqueue" assertions. Each rejection subtest
+ // snapshots the count immediately before the request and re-checks after
+ // so sibling subtests (and their t.Cleanup deletions) can't false-positive
+ // or false-negative this assertion.
+ countQuickCreateTasks := func(t *testing.T) int {
+ t.Helper()
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT COUNT(*) FROM agent_task_queue WHERE agent_id = $1 AND context->>'type' = 'quick_create'`,
+ agentID,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count quick-create tasks: %v", err)
+ }
+ return count
+ }
+
+ t.Run("same workspace parent enqueues with context", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/quick-create", map[string]any{
+ "agent_id": agentID,
+ "prompt": "Create a follow-up issue for the local parent",
+ "parent_issue_id": localParentID,
+ })
+ testHandler.QuickCreateIssue(w, req)
+ if w.Code != http.StatusAccepted {
+ t.Fatalf("expected 202, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp QuickCreateIssueResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, resp.TaskID)
+ })
+
+ // QuickCreateContext.ParentIssueID must contain the resolved UUID —
+ // the daemon claim step reads this field to attach the parent
+ // identifier and to inject `--parent <uuid>` into the prompt.
+ var contextJSON []byte
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT context FROM agent_task_queue WHERE id = $1`, resp.TaskID,
+ ).Scan(&contextJSON); err != nil {
+ t.Fatalf("load task context: %v", err)
+ }
+ var qc service.QuickCreateContext
+ if err := json.Unmarshal(contextJSON, &qc); err != nil {
+ t.Fatalf("unmarshal context: %v", err)
+ }
+ if qc.Type != service.QuickCreateContextType {
+ t.Fatalf("expected type=%q, got %q", service.QuickCreateContextType, qc.Type)
+ }
+ if qc.ParentIssueID != localParentID {
+ t.Fatalf("expected parent_issue_id=%q in context, got %q", localParentID, qc.ParentIssueID)
+ }
+ })
+
+ t.Run("foreign workspace parent is rejected", func(t *testing.T) {
+ before := countQuickCreateTasks(t)
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/quick-create", map[string]any{
+ "agent_id": agentID,
+ "prompt": "Try to smuggle a foreign parent",
+ "parent_issue_id": foreignParentID,
+ })
+ testHandler.QuickCreateIssue(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for foreign parent, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := countQuickCreateTasks(t); got != before {
+ // Any increase means the foreign-parent request enqueued a
+ // task despite the 400 — the trust boundary leaked.
+ t.Fatalf("foreign parent must not enqueue a task: expected %d quick-create tasks, got %d", before, got)
+ }
+ })
+
+ t.Run("bogus uuid parent is rejected", func(t *testing.T) {
+ before := countQuickCreateTasks(t)
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/quick-create", map[string]any{
+ "agent_id": agentID,
+ "prompt": "Try a malformed parent UUID",
+ "parent_issue_id": "not-a-uuid",
+ })
+ testHandler.QuickCreateIssue(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for bogus parent, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := countQuickCreateTasks(t); got != before {
+ t.Fatalf("bogus parent must not enqueue a task: expected %d quick-create tasks, got %d", before, got)
+ }
+ })
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 5031b7b286..4304ae711c 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -530,6 +530,13 @@ type QuickCreateContext struct {
WorkspaceID string `json:"workspace_id"`
ProjectID string `json:"project_id,omitempty"`
SquadID string `json:"squad_id,omitempty"`
+ // ParentIssueID is the optional UUID of the parent issue the new issue
+ // should be filed under. Set when the user opens the modal from "Add
+ // sub issue" on an existing issue; the daemon claim handler resolves the
+ // parent's identifier and the prompt template instructs the agent to
+ // pass `--parent <uuid>` so the sub-issue relationship is preserved
+ // across the manual→agent mode flip.
+ ParentIssueID string `json:"parent_issue_id,omitempty"`
}
// QuickCreateContextType marks a task as a quick-create job.
@@ -550,7 +557,11 @@ const QuickCreateContextType = "quick_create"
// The handler has already resolved it to the squad's leader agent for
// agentID; the squadID hint is stamped into the task context so the daemon
// claim handler can inject the squad-leader briefing on dispatch.
-func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, requesterID pgtype.UUID, agentID, squadID pgtype.UUID, prompt string, projectID pgtype.UUID) (db.AgentTaskQueue, error) {
+//
+// parentIssueID is optional (zero-valued pgtype.UUID when the user didn't
+// open the modal from "Add sub issue"). The handler is responsible for
+// validating it belongs to the same workspace before passing it in.
+func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, requesterID pgtype.UUID, agentID, squadID pgtype.UUID, prompt string, projectID, parentIssueID pgtype.UUID) (db.AgentTaskQueue, error) {
agent, err := s.Queries.GetAgent(ctx, agentID)
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)
@@ -574,6 +585,9 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, r
if squadID.Valid {
payload.SquadID = util.UUIDToString(squadID)
}
+ if parentIssueID.Valid {
+ payload.ParentIssueID = util.UUIDToString(parentIssueID)
+ }
contextJSON, err := json.Marshal(payload)
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("marshal quick-create context: %w", err)
@@ -596,6 +610,7 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, r
"requester_id", util.UUIDToString(requesterID),
"workspace_id", util.UUIDToString(workspaceID),
"project_id", payload.ProjectID,
+ "parent_issue_id", payload.ParentIssueID,
)
// Match every other Enqueue* path: kick the daemon WS so the task
// gets claimed promptly instead of waiting for the next 30 s poll