Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(server): surface real reason for failed quick-create (MUL-5268) (#5898)
Bohan Jiang4581e9ee7634
diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsxindex 5cef60e925..e6a27c9b06 100644--- a/apps/mobile/components/inbox/detail-label.tsx+++ b/apps/mobile/components/inbox/detail-label.tsx@@ -64,6 +64,7 @@ const TYPE_LABEL: Record<InboxItemType, string> = {reaction_added: "Reaction added",quick_create_done: "Quick-create done",quick_create_failed: "Quick-create failed",+ quick_create_unconfirmed: "Quick-create needs a check",};// due_date is a calendar day — format timezone-safely (no offset day shift).@@ -145,6 +146,13 @@ export function InboxDetailLabel({const detail = singleLine(details.error) || singleLine(item.body);return detail ? `Failed: ${detail}` : TYPE_LABEL[item.type];}+ // Mirrors packages/views/inbox/components/inbox-detail-label.tsx: the+ // unconfirmed outcome deliberately drops the "Failed:" prefix, because+ // the issue may actually have been created.+ case "quick_create_unconfirmed": {+ const detail = singleLine(details.error) || singleLine(item.body);+ return detail || TYPE_LABEL[item.type];+ }default:return TYPE_LABEL[item.type] ?? item.type;}diff --git a/apps/mobile/lib/inbox-display.ts b/apps/mobile/lib/inbox-display.tsindex df18f2b1dd..f9e2b70adb 100644--- a/apps/mobile/lib/inbox-display.ts+++ b/apps/mobile/lib/inbox-display.ts@@ -41,7 +41,10 @@ export function getInboxDisplayTitle(item: InboxItem): string {const prompt = singleLine(details.original_prompt);if (prompt) return prompt;}- if (item.type === "quick_create_failed") {+ // Both non-success quick-create outcomes surface the user's original input+ // as the row title. Mirrors isQuickCreateOutcome in+ // packages/views/inbox/components/inbox-display.ts.+ if (item.type === "quick_create_failed" || item.type === "quick_create_unconfirmed") {const prompt = singleLine(details.original_prompt);if (prompt) return prompt;}diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.tsindex d074c2554b..a5b5025e7c 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -20,7 +20,11 @@ export type InboxItemType =| "agent_completed"| "reaction_added"| "quick_create_done"- | "quick_create_failed";+ | "quick_create_failed"+ // Quick create whose outcome could not be verified. Distinct from+ // quick_create_failed because it must NOT be rendered with failure framing:+ // the issue may actually have been created.+ | "quick_create_unconfirmed";/*** One workspace's unread inbox count in the cross-workspace summarydiff --git a/packages/views/inbox/components/inbox-detail-label.test.tsx b/packages/views/inbox/components/inbox-detail-label.test.tsxnew file mode 100644index 0000000000..4400bbbd3e--- /dev/null+++ b/packages/views/inbox/components/inbox-detail-label.test.tsx@@ -0,0 +1,87 @@+import { render } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import type { InboxItem } from "@multica/core/types";+import en from "../../locales/en/inbox.json";+import { InboxDetailLabel } from "./inbox-detail-label";++vi.mock("../../issues/components", () => ({+ StatusIcon: () => null,+ PriorityIcon: () => null,+}));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: () => "Someone" }),+}));++// Resolve accessors against the REAL en locale rather than a stub, so this+// test fails if the unconfirmed case is ever re-pointed at a label that+// carries failure wording.+vi.mock("../../i18n", () => ({+ useT: () => ({+ t: (accessor: (dict: unknown) => string, params?: Record<string, string>) => {+ const template = accessor(en);+ if (!params) return template;+ return template.replace(/\{\{(\w+)\}\}/g, (_, key: string) => params[key] ?? "");+ },+ }),+}));++function item(overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: "workspace-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "agent",+ actor_id: "agent-1",+ type: "new_comment",+ severity: "info",+ issue_id: null,+ title: "Quick create needs a check",+ body: null,+ issue_status: null,+ read: false,+ archived: false,+ created_at: "2026-07-27T08:00:00Z",+ details: null,+ ...overrides,+ };+}++describe("InboxDetailLabel quick-create outcomes", () => {+ const detail = "Couldn't confirm whether the issue was created.";++ it("does not frame an unconfirmed outcome as a failure", () => {+ // GH #5885 follow-up: reusing quick_create_failed rendered this row as+ // "Failed: Couldn't confirm...", asserting a failure never observed.+ const { container } = render(+ <InboxDetailLabel item={item({ type: "quick_create_unconfirmed", details: { error: detail } })} />,+ );++ expect(container.textContent).toBe(detail);+ expect(container.textContent).not.toMatch(/failed/i);+ });++ it("still frames a confirmed failure as a failure", () => {+ const { container } = render(+ <InboxDetailLabel+ item={item({+ type: "quick_create_failed",+ details: { error: "an active issue already exists: JKY-30 (blocked)" },+ })}+ />,+ );++ expect(container.textContent).toBe(+ "Failed: an active issue already exists: JKY-30 (blocked)",+ );+ });++ it("falls back to the neutral type label when an unconfirmed row has no detail", () => {+ const { container } = render(+ <InboxDetailLabel item={item({ type: "quick_create_unconfirmed" })} />,+ );++ expect(container.textContent).toBe(en.types.quick_create_unconfirmed);+ expect(container.textContent).not.toMatch(/failed/i);+ });+});diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsxindex 804b0ffd36..982731287d 100644--- a/packages/views/inbox/components/inbox-detail-label.tsx+++ b/packages/views/inbox/components/inbox-detail-label.tsx@@ -5,7 +5,7 @@ import { formatDateOnly } from "@multica/core/issues/date";import { useActorName } from "@multica/core/workspace/hooks";import { StatusIcon, PriorityIcon } from "../../issues/components";import type { InboxItem, InboxItemType, IssueStatus, IssuePriority } from "@multica/core/types";-import { getQuickCreateFailureDetail } from "./inbox-display";+import { getQuickCreateOutcomeDetail } from "./inbox-display";import { useT } from "../../i18n";// Hook returning the inbox-item type → human label map. Replaces the@@ -32,6 +32,7 @@ export function useTypeLabels(): Record<InboxItemType, string> {reaction_added: t(($) => $.types.reaction_added),quick_create_done: t(($) => $.types.quick_create_done),quick_create_failed: t(($) => $.types.quick_create_failed),+ quick_create_unconfirmed: t(($) => $.types.quick_create_unconfirmed),};}@@ -107,10 +108,17 @@ export function InboxDetailLabel({ item }: { item: InboxItem }) {return <span>{typeLabels[item.type]}</span>;}case "quick_create_failed": {- const detail = getQuickCreateFailureDetail(item);+ const detail = getQuickCreateOutcomeDetail(item);if (detail) return <span>{t(($) => $.labels.failed_with_detail, { detail })}</span>;return <span>{typeLabels[item.type]}</span>;}+ case "quick_create_unconfirmed": {+ // Deliberately NOT the failed_with_detail label: the outcome is unknown,+ // so the detail is shown as-is with no "Failed:" framing.+ const detail = getQuickCreateOutcomeDetail(item);+ if (detail) return <span>{detail}</span>;+ return <span>{typeLabels[item.type]}</span>;+ }default:return <span>{typeLabels[item.type] ?? item.type}</span>;}diff --git a/packages/views/inbox/components/inbox-display.test.ts b/packages/views/inbox/components/inbox-display.test.tsindex c1fd89c34c..28c7bf9848 100644--- a/packages/views/inbox/components/inbox-display.test.ts+++ b/packages/views/inbox/components/inbox-display.test.ts@@ -2,7 +2,8 @@ import { describe, expect, it } from "vitest";import type { InboxItem } from "@multica/core/types";import {getInboxDisplayTitle,- getQuickCreateFailureDetail,+ getQuickCreateOutcomeDetail,+ isQuickCreateOutcome,stripQuickCreatePrefix,} from "./inbox-display";@@ -73,8 +74,31 @@ describe("inbox display helpers", () => {details: { error: "CLI failed\nwith exit status 1" },});- expect(getQuickCreateFailureDetail(failedItem)).toBe(+ expect(getQuickCreateOutcomeDetail(failedItem)).toBe("CLI failed with exit status 1",);});++ it("treats both non-success quick-create outcomes as recoverable rows", () => {+ // Drives the original-prompt box and the "Edit as advanced form" recovery+ // affordance in inbox-page.tsx — the unconfirmed row must keep both.+ expect(isQuickCreateOutcome("quick_create_failed")).toBe(true);+ expect(isQuickCreateOutcome("quick_create_unconfirmed")).toBe(true);+ expect(isQuickCreateOutcome("quick_create_done")).toBe(false);+ expect(isQuickCreateOutcome("new_comment")).toBe(false);+ });++ it("uses the original prompt as the unconfirmed quick-create row title", () => {+ const unconfirmedItem = item({+ type: "quick_create_unconfirmed",+ title: "Quick create needs a check",+ body: "Couldn't confirm whether the issue was created.",+ issue_id: null,+ details: { original_prompt: "File a bug about\nthe flaky test" },+ });++ expect(getInboxDisplayTitle(unconfirmedItem)).toBe(+ "File a bug about the flaky test",+ );+ });});diff --git a/packages/views/inbox/components/inbox-display.ts b/packages/views/inbox/components/inbox-display.tsindex 8ffc944766..6128bfffd6 100644--- a/packages/views/inbox/components/inbox-display.ts+++ b/packages/views/inbox/components/inbox-display.ts@@ -35,7 +35,7 @@ export function getInboxDisplayTitle(item: InboxItem): string {if (prompt) return prompt;}- if (item.type === "quick_create_failed") {+ if (isQuickCreateOutcome(item.type)) {const prompt = singleLine(details.original_prompt);if (prompt) return prompt;}@@ -43,7 +43,16 @@ export function getInboxDisplayTitle(item: InboxItem): string {return item.title;}-export function getQuickCreateFailureDetail(item: InboxItem): string {+/**+ * The two non-success quick-create outcomes. They share a row shape (original+ * prompt + recovery affordance) but must never share failure wording: the+ * unconfirmed outcome means we could not verify the result, not that it failed.+ */+export function isQuickCreateOutcome(type: InboxItem["type"]): boolean {+ return type === "quick_create_failed" || type === "quick_create_unconfirmed";+}++export function getQuickCreateOutcomeDetail(item: InboxItem): string {const details = item.details ?? {};return singleLine(details.error) || singleLine(item.body);}diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex d39eba6a27..081d0df048 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -61,7 +61,7 @@ import { useTimeAgo } from "./inbox-list-item";import { InboxList } from "./inbox-list";import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";import { useTypeLabels } from "./inbox-detail-label";-import { getInboxDisplayTitle } from "./inbox-display";+import { getInboxDisplayTitle, isQuickCreateOutcome } from "./inbox-display";import { useT } from "../../i18n";export function InboxPage() {@@ -462,7 +462,7 @@ export function InboxPage() {{selected.body}</div>)}- {selected.type === "quick_create_failed" && selected.details?.original_prompt && (+ {isQuickCreateOutcome(selected.type) && selected.details?.original_prompt && (<div className="mt-4 rounded-md border bg-muted/40 p-3"><p className="text-xs font-medium text-muted-foreground">{t(($) => $.detail.original_input)}@@ -471,7 +471,7 @@ export function InboxPage() {</div>)}<div className="mt-4 flex gap-2">- {selected.type === "quick_create_failed" && (+ {isQuickCreateOutcome(selected.type) && (<Buttonsize="sm"onClick={() => {diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex f40c912391..d5349b8498 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -49,7 +49,8 @@"agent_completed": "Agent completed","reaction_added": "Reacted","quick_create_done": "Created with agent",- "quick_create_failed": "Create with agent failed"+ "quick_create_failed": "Create with agent failed",+ "quick_create_unconfirmed": "Create with agent unconfirmed"},"labels": {"set_status_to": "Set status to",diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex 8eb7c00b08..6a4d3c342f 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -49,7 +49,8 @@"agent_completed": "エージェントが完了","reaction_added": "リアクションあり","quick_create_done": "エージェントで作成",- "quick_create_failed": "エージェントでの作成に失敗"+ "quick_create_failed": "エージェントでの作成に失敗",+ "quick_create_unconfirmed": "エージェントでの作成結果は未確認"},"labels": {"set_status_to": "ステータスを変更:",diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex 1ae6b3d4e2..a1eb3d1568 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -49,7 +49,8 @@"agent_completed": "에이전트 완료됨","reaction_added": "반응 추가됨","quick_create_done": "에이전트로 생성됨",- "quick_create_failed": "에이전트 생성 실패"+ "quick_create_failed": "에이전트 생성 실패",+ "quick_create_unconfirmed": "에이전트 생성 결과 미확인"},"labels": {"set_status_to": "상태 변경:",diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex e3060eb8f7..29907d0cf5 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -49,7 +49,8 @@"agent_completed": "智能体已完成","reaction_added": "添加了表情反应","quick_create_done": "通过智能体创建",- "quick_create_failed": "通过智能体创建失败"+ "quick_create_failed": "通过智能体创建失败",+ "quick_create_unconfirmed": "通过智能体创建结果未确认"},"labels": {"set_status_to": "状态设为",diff --git a/server/cmd/server/quick_create_subscriber_test.go b/server/cmd/server/quick_create_subscriber_test.goindex 6a05bbb7f1..23b078e1eb 100644--- a/server/cmd/server/quick_create_subscriber_test.go+++ b/server/cmd/server/quick_create_subscriber_test.go@@ -2,8 +2,12 @@ package mainimport ("context"+ "encoding/json"+ "errors"+ "strings""testing"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/service"@@ -156,3 +160,365 @@ func TestQuickCreateFailure_DoesNotSubscribeRequester(t *testing.T) {t.Fatalf("expected no subscriber rows for failed quick-create, got %d", leaked)}}++// TestQuickCreateFailure_SurfacesAgentOutput locks in the fix for GH #5885: when+// a quick-create agent's `multica issue create` call fails (e.g. the active-+// duplicate guard rejects it), the failure inbox must carry the agent's real+// final output — which the prompt requires to be the CLI error — instead of the+// opaque "agent finished without creating an issue".+func TestQuickCreateFailure_SurfacesAgentOutput(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ bus := events.New()+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)++ var agentID string+ if err := testPool.QueryRow(ctx,+ `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,+ testWorkspaceID,+ ).Scan(&agentID); err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }++ task, err := taskSvc.EnqueueQuickCreateTask(ctx,+ parseUUID(testWorkspaceID),+ parseUUID(testUserID),+ parseUUID(agentID),+ pgtype.UUID{},+ "file that same bug again",+ "",+ "",+ pgtype.UUID{},+ pgtype.UUID{},+ nil,+ )+ if err != nil {+ t.Fatalf("EnqueueQuickCreateTask: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)+ deleteInboxForTask(task.ID)+ })++ if _, err := testPool.Exec(ctx,+ `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`,+ task.ID,+ ); err != nil {+ t.Fatalf("dispatch task: %v", err)+ }+ if _, err := queries.StartAgentTask(ctx, task.ID); err != nil {+ t.Fatalf("StartAgentTask: %v", err)+ }++ // No issue is created; the agent exits with the CLI duplicate error as its+ // only output (per the quick-create prompt contract).+ const agentErr = "Error: an active issue already exists: JKY-30 (blocked). Pass --allow-duplicate to override."+ result, _ := json.Marshal(map[string]any{"output": agentErr})+ if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {+ t.Fatalf("CompleteTask: %v", err)+ }++ body, errDetail, _ := requireQuickCreateOutcomeInbox(t, task.ID, "quick_create_failed")++ if !strings.Contains(errDetail, "JKY-30") {+ t.Fatalf("expected failure detail to carry the agent's real error, got %q", errDetail)+ }+ if strings.Contains(errDetail, "agent finished without creating an issue") {+ t.Fatalf("failure detail regressed to the generic message: %q", errDetail)+ }+ if !strings.Contains(body, "JKY-30") {+ t.Fatalf("expected inbox body to carry the agent's real error, got %q", body)+ }+}++// TestQuickCreateLookupFault_WritesUnconfirmedInbox is the regression for the+// silent-drop path: when the completion lookup itself faults (transient DB+// error rather than pgx.ErrNoRows), the task is already completed and nothing+// re-runs this reconciliation. Returning without writing would strand the+// requester with NO inbox result at all. The run must still end with a+// terminal notification — and one that does NOT assert a failure we never+// observed, nor reuse the agent's output as if it were the confirmed reason.+func TestQuickCreateLookupFault_WritesUnconfirmedInbox(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ bus := events.New()+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)++ var agentID string+ if err := testPool.QueryRow(ctx,+ `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,+ testWorkspaceID,+ ).Scan(&agentID); err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }++ task, err := taskSvc.EnqueueQuickCreateTask(ctx,+ parseUUID(testWorkspaceID),+ parseUUID(testUserID),+ parseUUID(agentID),+ pgtype.UUID{},+ "file a bug while the db is flaky",+ "",+ "",+ pgtype.UUID{},+ pgtype.UUID{},+ nil,+ )+ if err != nil {+ t.Fatalf("EnqueueQuickCreateTask: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)+ deleteInboxForTask(task.ID)+ })++ if _, err := testPool.Exec(ctx,+ `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`,+ task.ID,+ ); err != nil {+ t.Fatalf("dispatch task: %v", err)+ }+ if _, err := queries.StartAgentTask(ctx, task.ID); err != nil {+ t.Fatalf("StartAgentTask: %v", err)+ }++ // Completion runs against a Queries whose origin lookup always faults. The+ // completion transaction is unaffected (runInTx binds queries to the tx),+ // and the inbox write still goes to the real pool — so a missing inbox row+ // can only mean the code dropped the notification.+ faulting := service.NewTaskService(+ db.New(failGetIssueByOriginDB{DBTX: testPool, err: errors.New("simulated transient db fault")}),+ testPool, nil, bus,+ )++ // The agent DID emit a duplicate-style error, but with the lookup faulted we+ // cannot confirm it is the reason — it must not be presented as such.+ result, _ := json.Marshal(map[string]any{+ "output": "Error: an active issue already exists: JKY-30 (blocked).",+ })+ if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {+ t.Fatalf("CompleteTask: %v", err)+ }++ body, errDetail, title := requireQuickCreateOutcomeInbox(t, task.ID, "quick_create_unconfirmed")++ if !strings.Contains(body, "Couldn't confirm") {+ t.Fatalf("expected the neutral unconfirmed wording, got body %q", body)+ }+ if title == "Quick create failed" {+ t.Fatalf("unconfirmed outcome must not be titled as a definite failure, got %q", title)+ }+ // The agent's output is not evidence of the outcome here — the lookup never+ // completed, so surfacing it would assert a cause we did not verify.+ if strings.Contains(body, "JKY-30") || strings.Contains(errDetail, "JKY-30") {+ t.Fatalf("unconfirmed outcome must not reuse the agent output as the reason: body=%q detail=%q", body, errDetail)+ }+}++// TestQuickCreateFailure_RedactsAgentOutput locks in that the newly-surfaced+// data source (the agent's final output) is scrubbed before it is stored on the+// inbox row. Agent output is untrusted text that can contain whatever the run+// echoed, so credentials must never land in the notification.+func TestQuickCreateFailure_RedactsAgentOutput(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ bus := events.New()+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)++ var agentID string+ if err := testPool.QueryRow(ctx,+ `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,+ testWorkspaceID,+ ).Scan(&agentID); err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }++ task, err := taskSvc.EnqueueQuickCreateTask(ctx,+ parseUUID(testWorkspaceID),+ parseUUID(testUserID),+ parseUUID(agentID),+ pgtype.UUID{},+ "file a bug and leak a token",+ "",+ "",+ pgtype.UUID{},+ pgtype.UUID{},+ nil,+ )+ if err != nil {+ t.Fatalf("EnqueueQuickCreateTask: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)+ deleteInboxForTask(task.ID)+ })++ if _, err := testPool.Exec(ctx,+ `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`,+ task.ID,+ ); err != nil {+ t.Fatalf("dispatch task: %v", err)+ }+ if _, err := queries.StartAgentTask(ctx, task.ID); err != nil {+ t.Fatalf("StartAgentTask: %v", err)+ }++ // Fake, non-functional token shaped like a real GitHub PAT.+ const fakeToken = "ghp_0123456789abcdefghijklmnopqrstuvwxyzAB"+ result, _ := json.Marshal(map[string]any{+ "output": "Error: create failed while authenticating with " + fakeToken,+ })+ if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {+ t.Fatalf("CompleteTask: %v", err)+ }++ body, errDetail, _ := requireQuickCreateOutcomeInbox(t, task.ID, "quick_create_failed")++ if strings.Contains(body, fakeToken) || strings.Contains(errDetail, fakeToken) {+ t.Fatal("agent output reached the inbox row unredacted")+ }+ if !strings.Contains(body, "[REDACTED GITHUB TOKEN]") {+ t.Fatalf("expected the token to be replaced by a redaction placeholder, got %q", body)+ }+}++// TestQuickCreateLookupCancelled_StillWritesUnconfirmedInbox covers the+// cancel/timeout shape of the lookup fault, which the plain-error case cannot:+// when GetIssueByOrigin fails because the caller's context was cancelled or+// timed out, reusing that same context for the notification write would fail it+// for the identical reason and leave the user with nothing. The terminal write+// must be detached from the caller's cancellation.+func TestQuickCreateLookupCancelled_StillWritesUnconfirmedInbox(t *testing.T) {+ setupCtx := context.Background()+ queries := db.New(testPool)+ bus := events.New()+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)++ var agentID string+ if err := testPool.QueryRow(setupCtx,+ `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,+ testWorkspaceID,+ ).Scan(&agentID); err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }++ task, err := taskSvc.EnqueueQuickCreateTask(setupCtx,+ parseUUID(testWorkspaceID),+ parseUUID(testUserID),+ parseUUID(agentID),+ pgtype.UUID{},+ "file a bug while the request is cancelled",+ "",+ "",+ pgtype.UUID{},+ pgtype.UUID{},+ nil,+ )+ if err != nil {+ t.Fatalf("EnqueueQuickCreateTask: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)+ deleteInboxForTask(task.ID)+ })++ if _, err := testPool.Exec(setupCtx,+ `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`,+ task.ID,+ ); err != nil {+ t.Fatalf("dispatch task: %v", err)+ }+ if _, err := queries.StartAgentTask(setupCtx, task.ID); err != nil {+ t.Fatalf("StartAgentTask: %v", err)+ }++ // The completion transaction runs on a healthy context; the context dies at+ // the moment of the origin lookup, exactly as a cancelled request would.+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ faulting := service.NewTaskService(+ db.New(cancelOnGetIssueByOriginDB{DBTX: testPool, cancel: cancel}),+ testPool, nil, bus,+ )++ result, _ := json.Marshal(map[string]any{"output": "Error: something went wrong"})+ if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false); err != nil {+ t.Fatalf("CompleteTask: %v", err)+ }+ if ctx.Err() == nil {+ t.Fatal("test setup is wrong: the context should have been cancelled during the lookup")+ }++ body, _, _ := requireQuickCreateOutcomeInbox(t, task.ID, "quick_create_unconfirmed")+ if !strings.Contains(body, "Couldn't confirm") {+ t.Fatalf("expected the neutral unconfirmed wording, got %q", body)+ }+}++// requireQuickCreateOutcomeInbox returns (body, details.error, title) for the+// quick-create outcome notification of the given type belonging to taskID,+// failing the test when none exists. Scoping by task id keeps+// concurrent/ordering-sensitive cases from reading a sibling test's row; the+// type is asserted because the failed and unconfirmed outcomes must never+// collapse into one another (clients frame them differently).+func requireQuickCreateOutcomeInbox(t *testing.T, taskID pgtype.UUID, inboxType string) (string, string, string) {+ t.Helper()+ var body, errDetail, title string+ err := testPool.QueryRow(context.Background(), `+ SELECT COALESCE(body, ''), COALESCE(details->>'error', ''), title+ FROM inbox_item+ WHERE recipient_type = 'member' AND recipient_id = $1+ AND type = $3+ AND details->>'task_id' = $2::text+ ORDER BY created_at DESC+ LIMIT 1+ `, testUserID, taskID, inboxType).Scan(&body, &errDetail, &title)+ if err != nil {+ t.Fatalf("expected a %s notification for the task, got none: %v", inboxType, err)+ }+ return body, errDetail, title+}++func deleteInboxForTask(taskID pgtype.UUID) {+ testPool.Exec(context.Background(),+ `DELETE FROM inbox_item WHERE details->>'task_id' = $1::text`, taskID)+}++// failGetIssueByOriginDB delegates every statement to the real pool except the+// quick-create completion lookup, which it fails with a non-ErrNoRows error to+// simulate a transient DB fault on exactly that query. Everything else —+// including the inbox write the assertion depends on — still hits the real DB.+type failGetIssueByOriginDB struct {+ db.DBTX+ err error+}++func (f failGetIssueByOriginDB) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {+ // sqlc keeps the `-- name: <Query>` header in the generated SQL constant,+ // so this matches that one query and nothing else.+ if strings.Contains(sql, "name: GetIssueByOrigin") {+ return errRow{err: f.err}+ }+ return f.DBTX.QueryRow(ctx, sql, args...)+}++// cancelOnGetIssueByOriginDB cancels the caller's context at the moment of the+// origin lookup and fails it with context.Canceled — the shape a cancelled or+// timed-out request actually produces, where every later use of that same+// context is doomed too.+type cancelOnGetIssueByOriginDB struct {+ db.DBTX+ cancel context.CancelFunc+}++func (f cancelOnGetIssueByOriginDB) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {+ if strings.Contains(sql, "name: GetIssueByOrigin") {+ f.cancel()+ return errRow{err: context.Canceled}+ }+ return f.DBTX.QueryRow(ctx, sql, args...)+}++type errRow struct{ err error }++func (r errRow) Scan(...any) error { return r.err }diff --git a/server/internal/service/quick_create_failure_detail_test.go b/server/internal/service/quick_create_failure_detail_test.gonew file mode 100644index 0000000000..773fd2cb3f--- /dev/null+++ b/server/internal/service/quick_create_failure_detail_test.go@@ -0,0 +1,81 @@+package service++import (+ "strings"+ "testing"+)++// TestQuickCreateFailureDetail pins the reason-extraction that turns the opaque+// "agent finished without creating an issue" inbox into the concrete CLI error+// the quick-create agent actually emitted (GH #5885).+func TestQuickCreateFailureDetail(t *testing.T) {+ t.Parallel()++ t.Run("real CLI error passes through", func(t *testing.T) {+ t.Parallel()+ out := "Error: an active issue already exists: JKY-30 (blocked)."+ result := []byte(`{"output":"` + out + `"}`)+ if got := quickCreateFailureDetail(result); got != out {+ t.Fatalf("expected passthrough of the CLI error\n got: %q\nwant: %q", got, out)+ }+ })++ t.Run("empty output yields empty so caller uses its generic default", func(t *testing.T) {+ t.Parallel()+ if got := quickCreateFailureDetail([]byte(`{"output":""}`)); got != "" {+ t.Fatalf("expected empty detail for empty output, got %q", got)+ }+ })++ t.Run("whitespace-only output yields empty", func(t *testing.T) {+ t.Parallel()+ if got := quickCreateFailureDetail([]byte(`{"output":" \n "}`)); got != "" {+ t.Fatalf("expected empty detail for whitespace output, got %q", got)+ }+ })++ t.Run("missing output field yields empty", func(t *testing.T) {+ t.Parallel()+ if got := quickCreateFailureDetail([]byte(`{"task_id":"abc"}`)); got != "" {+ t.Fatalf("expected empty detail when output absent, got %q", got)+ }+ })++ t.Run("malformed json yields empty", func(t *testing.T) {+ t.Parallel()+ if got := quickCreateFailureDetail([]byte(`not json`)); got != "" {+ t.Fatalf("expected empty detail for malformed json, got %q", got)+ }+ })++ t.Run("literal backslash-n is decoded to real newlines", func(t *testing.T) {+ t.Parallel()+ // The daemon may deliver an Output carrying 2-char `\n` sequences; they+ // must render as real line breaks, matching the comment-fallback path.+ result := []byte(`{"output":"line one\\nline two"}`)+ got := quickCreateFailureDetail(result)+ if got != "line one\nline two" {+ t.Fatalf("expected decoded newline, got %q", got)+ }+ })++ t.Run("oversized output is dropped to a safe generic notice", func(t *testing.T) {+ t.Parallel()+ // A runaway raw-stream dump must not have its tool-trace head surfaced+ // as the failure reason (same concern as GH #5455).+ huge := strings.Repeat("x", maxQuickCreateFailureDetailRunes+1)+ result := []byte(`{"output":"` + huge + `"}`)+ if got := quickCreateFailureDetail(result); got != quickCreateOversizedFailureDetail {+ t.Fatalf("expected oversized notice, got %d-rune body", len(got))+ }+ })++ t.Run("output exactly at the cap passes through", func(t *testing.T) {+ t.Parallel()+ body := strings.Repeat("x", maxQuickCreateFailureDetailRunes)+ result := []byte(`{"output":"` + body + `"}`)+ if got := quickCreateFailureDetail(result); got != body {+ t.Fatalf("expected body at cap to pass through, got %d runes", len(got))+ }+ })+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 9483b79db1..73b7a14a2a 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -2771,7 +2771,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu// the requester's workspace since the task started — more robust than// parsing the agent's stdout for an identifier.if qc, ok := s.parseQuickCreateContext(task); ok {- s.notifyQuickCreateCompleted(ctx, task, qc)+ s.notifyQuickCreateCompleted(ctx, task, qc, result)}// For chat tasks, broadcast chat:done AFTER commit. The single assistant@@ -4310,6 +4310,40 @@ func (s *TaskService) parseQuickCreateContext(task db.AgentTaskQueue) (QuickCreareturn qc, true}+// maxQuickCreateFailureDetailRunes bounds the failure reason lifted from a+// quick-create task's final output. A genuine CLI error (a duplicate message,+// a validation error) is short; an output far larger than this is a runaway+// raw-stream dump whose head is process narration rather than the real reason+// (same failure mode as GH #5455), so it is dropped to a generic notice rather+// than surfaced as the error.+const maxQuickCreateFailureDetailRunes = 2000++const quickCreateOversizedFailureDetail = "Quick create failed, but the agent's output was too large to show the reason safely. Check the task's execution log for details."++// quickCreateFailureDetail extracts a user-facing failure reason from a+// quick-create task's final output. The quick-create prompt instructs the agent+// to exit with the CLI error as its only output when `multica issue create`+// fails, so this normally carries the real reason (e.g. an active-duplicate+// message naming the existing issue). Returns "" when there is no usable output+// so the caller falls back to a generic message; redaction is applied by+// notifyQuickCreateFailed.+func quickCreateFailureDetail(result []byte) string {+ var payload protocol.TaskCompletedPayload+ if err := json.Unmarshal(result, &payload); err != nil {+ return ""+ }+ // Same unescape as the comment-fallback path: literal `\n` sequences from+ // agent stdout become real newlines before the reason reaches the user.+ body := strings.TrimSpace(util.UnescapeBackslashEscapes(payload.Output))+ if body == "" {+ return ""+ }+ if utf8.RuneCountInString(body) > maxQuickCreateFailureDetailRunes {+ return quickCreateOversizedFailureDetail+ }+ return body+}+// notifyQuickCreateCompleted writes a success inbox notification to the// requester pointing at the issue the agent just created. The issue is// stamped with origin_type=quick_create + origin_id=<task_id> by the@@ -4317,7 +4351,7 @@ func (s *TaskService) parseQuickCreateContext(task db.AgentTaskQueue) (QuickCrea// deterministic — robust against the same agent creating other issues in// parallel (e.g. assignment task running while max_concurrent_tasks > 1// permits another quick-create alongside it).-func (s *TaskService) notifyQuickCreateCompleted(ctx context.Context, task db.AgentTaskQueue, qc QuickCreateContext) {+func (s *TaskService) notifyQuickCreateCompleted(ctx context.Context, task db.AgentTaskQueue, qc QuickCreateContext, result []byte) {requesterID, err := util.ParseUUID(qc.RequesterID)if err != nil {slog.Warn("quick-create completion: invalid requester id", "task_id", util.UUIDToString(task.ID), "error", err)@@ -4334,14 +4368,38 @@ func (s *TaskService) notifyQuickCreateCompleted(ctx context.Context, task db.AgOriginID: task.ID,})if err != nil {- // No issue created — agent ran to completion but the CLI call must- // have failed. Surface as a failure inbox so the user sees something.+ if !errors.Is(err, pgx.ErrNoRows) {+ // The lookup itself failed (DB fault, timeout, …), not a confirmed+ // "no issue": the agent may well have created the issue, so a+ // failure inbox would misreport it. But the task is already+ // completed and nothing retries this reconciliation, so returning+ // silently would end the run with NO inbox result at all. Write a+ // neutral, terminal notification instead — the user always gets a+ // result, and it never asserts a failure we did not observe.+ slog.Error("quick-create completion: issue lookup failed, writing unconfirmed inbox",+ "task_id", util.UUIDToString(task.ID),+ "agent_id", util.UUIDToString(task.AgentID),+ "workspace_id", qc.WorkspaceID,+ "error", err,+ )+ s.notifyQuickCreateUnconfirmed(ctx, task, qc)+ return+ }+ // No issue created — the agent ran to completion but the CLI create+ // call must have failed (most often the active-duplicate guard). The+ // quick-create prompt tells the agent to exit with the CLI error as its+ // only output, so prefer that as the failure reason instead of a+ // generic string; fall back to notifyQuickCreateFailed's own default+ // when the output is empty. This is what turns the opaque "agent+ // finished without creating an issue" into the concrete reason (#5885).+ detail := quickCreateFailureDetail(result)slog.Warn("quick-create completion: no issue found, writing failure inbox","task_id", util.UUIDToString(task.ID),"agent_id", util.UUIDToString(task.AgentID),"workspace_id", qc.WorkspaceID,+ "has_detail", detail != "",)- s.notifyQuickCreateFailed(ctx, task, qc, "agent finished without creating an issue")+ s.notifyQuickCreateFailed(ctx, task, qc, detail)return}@@ -4422,11 +4480,62 @@ func (s *TaskService) notifyQuickCreateCompleted(ctx context.Context, task db.Ags.publishQuickCreateInbox(item, qc.WorkspaceID, util.UUIDToString(task.AgentID), issue.Status)}+// Inbox types for the two non-success quick-create outcomes. They are distinct+// because clients render them differently: the failed type carries an explicit+// "Failed:" framing, which must not be applied to an outcome we could not+// verify. Older clients that predate the unconfirmed type fall through their+// existing default branch and render the row's title/body unchanged, which is+// already the neutral wording.+const (+ inboxTypeQuickCreateFailed = "quick_create_failed"+ inboxTypeQuickCreateUnconfirmed = "quick_create_unconfirmed"+)+// notifyQuickCreateFailed writes a failure inbox notification carrying the// original prompt + agent ID so the frontend can render an "Edit as// advanced form" entry that pre-fills the legacy create-issue modal-// without asking the user to retype.+// without asking the user to retype. Use this only when the run is KNOWN not+// to have produced an issue; when that is merely unverified, use+// notifyQuickCreateUnconfirmed so the user is not told a definite failure.func (s *TaskService) notifyQuickCreateFailed(ctx context.Context, task db.AgentTaskQueue, qc QuickCreateContext, errMsg string) {+ if errMsg == "" {+ errMsg = "Quick create did not finish successfully"+ }+ s.writeQuickCreateOutcomeInbox(ctx, task, qc, inboxTypeQuickCreateFailed, "Quick create failed", errMsg)+}++// quickCreateUnconfirmedDetail is the user-facing message for a quick-create+// run whose outcome could not be verified (the completion lookup itself+// failed). It must not claim failure: the agent may well have created the+// issue. It points at the one safe next step instead — check before retrying,+// so a retry cannot silently produce the duplicate the guard exists to prevent.+const quickCreateUnconfirmedDetail = "Couldn't confirm whether the issue was created. Check your recent issues before retrying — creating it again may produce a duplicate."++// notifyQuickCreateUnconfirmed writes a NEUTRAL terminal notification for a+// quick-create run whose outcome is unverified. The task is already completed+// and nothing re-runs this reconciliation, so returning without writing here+// would strand the requester with no inbox result at all — the failure mode+// this exists to prevent.+//+// It uses its own inbox type rather than reusing quick_create_failed: every+// client renders the failed type with a "Failed:" prefix, which would assert a+// failure we never observed no matter how neutral the title and body are.+// Severity stays action_required because the user does need to look.+func (s *TaskService) notifyQuickCreateUnconfirmed(ctx context.Context, task db.AgentTaskQueue, qc QuickCreateContext) {+ s.writeQuickCreateOutcomeInbox(ctx, task, qc, inboxTypeQuickCreateUnconfirmed, "Quick create needs a check", quickCreateUnconfirmedDetail)+}++// quickCreateNotifyTimeout bounds the detached terminal-notification write in+// writeQuickCreateOutcomeInbox. Long enough for a healthy DB round-trip, short+// enough that a wedged pool cannot pin the completion goroutine.+const quickCreateNotifyTimeout = 5 * time.Second++// writeQuickCreateOutcomeInbox writes the shared inbox row used by both+// non-success outcomes (known failure and unverified outcome). Callers own the+// user-facing wording and the row type; the row shape — original prompt, agent+// id, redacted message — is identical so the frontend's recovery affordance+// keeps working for both.+func (s *TaskService) writeQuickCreateOutcomeInbox(ctx context.Context, task db.AgentTaskQueue, qc QuickCreateContext, inboxType, title, errMsg string) {requesterID, err := util.ParseUUID(qc.RequesterID)if err != nil {return@@ -4435,9 +4544,15 @@ func (s *TaskService) notifyQuickCreateFailed(ctx context.Context, task db.Agentif err != nil {return}- if errMsg == "" {- errMsg = "Quick create did not finish successfully"- }+ // The task is already committed as completed and nothing retries this+ // notification, so it must not die with the caller's context. This matters+ // most on the unconfirmed path: the completion lookup may have failed+ // precisely BECAUSE ctx was cancelled or timed out, and reusing that ctx+ // would fail the write for the same reason — leaving the user with no+ // result at all, the exact silent drop this path exists to prevent. Detach+ // from cancellation, but keep a bound so a wedged DB cannot pin us.+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), quickCreateNotifyTimeout)+ defer cancel()details, _ := json.Marshal(map[string]any{"task_id": util.UUIDToString(task.ID),"agent_id": util.UUIDToString(task.AgentID),@@ -4448,10 +4563,10 @@ func (s *TaskService) notifyQuickCreateFailed(ctx context.Context, task db.AgentWorkspaceID: workspaceID,RecipientType: "member",RecipientID: requesterID,- Type: "quick_create_failed",+ Type: inboxType,Severity: "action_required",IssueID: pgtype.UUID{},- Title: "Quick create failed",+ Title: title,Body: pgtype.Text{String: redact.Text(errMsg), Valid: true},ActorType: pgtype.Text{String: "agent", Valid: true},ActorID: task.AgentID,