Skip to content

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

Go

fix(chat): defer cancellation-time finalization until the task transcript is stable (#5246)

YYClaw9eddcaff100b
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 21f39b91e3..3fa1410808 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { ApiClient, ApiError } from "./client";
+import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY } from "./client";
afterEach(() => {
vi.unstubAllGlobals();
@@ -724,6 +724,25 @@ describe("ApiClient", () => {
});
});
+ // The server only defers the empty-transcript judgment — and so only
+ // withholds the synchronous restore — for clients that advertise this
+ // capability (#5219). Drop the header and this client is treated as a
+ // pre-#5219 build, quietly losing the deferred path it actually implements.
+ it("advertises the durable draft-restore capability", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(taskResponse), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").cancelTaskById("task-1");
+
+ const init = fetchMock.mock.calls[0]?.[1] as { headers: Record<string, string> };
+ expect(init.headers["X-Client-Capabilities"]).toBe(CHAT_DRAFT_RESTORE_CAPABILITY);
+ });
+
it("treats a null cancelled chat message as absent", async () => {
vi.stubGlobal(
"fetch",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 90592a04fa..389c71bedb 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -71,6 +71,7 @@ import type {
ChatPinnedAgent,
ChatMessage,
ChatMessagesPage,
+ ChatDraftRestoresResponse,
ChatPendingTask,
PendingChatTasksResponse,
HasPendingChatTasksResponse,
@@ -155,6 +156,7 @@ import {
AgentTemplateSummaryListSchema,
AttachmentResponseSchema,
CancelTaskResponseSchema,
+ ChatDraftRestoresResponseSchema,
ChildIssuesResponseSchema,
CommentsListSchema,
CommentTriggerPreviewSchema,
@@ -223,6 +225,7 @@ import {
EMPTY_BILLING_CHECKOUT_SESSION_STATUS,
EMPTY_CREATE_BILLING_PORTAL_SESSION_RESPONSE,
EMPTY_CANCEL_TASK_RESPONSE,
+ EMPTY_CHAT_DRAFT_RESTORES,
CreateFeedbackResponseSchema,
EMPTY_CREATE_FEEDBACK_RESPONSE,
InboxUnreadSummarySchema,
@@ -298,6 +301,13 @@ export class PreviewUnsupportedError extends Error {
}
}
+/**
+ * Advertised in X-Client-Capabilities so the server knows this client can
+ * recover a cancelled prompt from the durable draft-restore row (#5219).
+ * Must stay in sync with protocol.AppCapabilityChatDraftRestoreV1.
+ */
+export const CHAT_DRAFT_RESTORE_CAPABILITY = "chat-draft-restore-v1";
+
export class ApiClient {
private baseUrl: string;
private token: string | null = null;
@@ -1915,6 +1925,33 @@ export class ApiClient {
return this.fetch(`/api/chat/sessions/${sessionId}/pending-task`);
}
+ /**
+ * Pending deferred-cancellation draft restores for a session (#5219).
+ * A 404 means the backend predates the endpoint — treat as "nothing
+ * pending" so older servers never error the composer.
+ */
+ async listChatDraftRestores(sessionId: string): Promise<ChatDraftRestoresResponse> {
+ let raw: unknown;
+ try {
+ raw = await this.fetch<unknown>(`/api/chat/sessions/${sessionId}/draft-restores`);
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 404) {
+ return { restores: [] };
+ }
+ throw err;
+ }
+ return parseWithFallback(raw, ChatDraftRestoresResponseSchema, EMPTY_CHAT_DRAFT_RESTORES, {
+ endpoint: "GET /api/chat/sessions/{id}/draft-restores",
+ });
+ }
+
+ /** Idempotent consume — deleting an already-consumed restore is a 204 no-op. */
+ async consumeChatDraftRestore(sessionId: string, restoreId: string): Promise<void> {
+ await this.fetch(`/api/chat/sessions/${sessionId}/draft-restores/${restoreId}`, {
+ method: "DELETE",
+ });
+ }
+
async listPendingChatTasks(): Promise<PendingChatTasksResponse> {
return this.fetch(`/api/chat/pending-tasks`);
}
@@ -1927,8 +1964,15 @@ export class ApiClient {
await this.fetch(`/api/chat/sessions/${sessionId}/read`, { method: "POST" });
}
+ // Advertises the durable draft-restore capability (#5219). The server only
+ // defers the empty-transcript judgment — and therefore only withholds the
+ // synchronous restore from the response — for clients that send this; without
+ // it we would be treated as a pre-#5219 client and get the legacy behaviour.
async cancelTaskById(taskId: string): Promise<CancelTaskResponse> {
- const raw = await this.fetch<unknown>(`/api/tasks/${taskId}/cancel`, { method: "POST" });
+ const raw = await this.fetch<unknown>(`/api/tasks/${taskId}/cancel`, {
+ method: "POST",
+ headers: { "X-Client-Capabilities": CHAT_DRAFT_RESTORE_CAPABILITY },
+ });
return parseWithFallback(raw, CancelTaskResponseSchema, EMPTY_CANCEL_TASK_RESPONSE, {
endpoint: "POST /api/tasks/{taskId}/cancel",
});
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 855b08c763..92c9874557 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -5,8 +5,10 @@ import {
DashboardAgentRunTimeListSchema,
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
+ ChatDraftRestoresResponseSchema,
CreateFeedbackResponseSchema,
DuplicateIssueErrorBodySchema,
+ EMPTY_CHAT_DRAFT_RESTORES,
EMPTY_CREATE_FEEDBACK_RESPONSE,
EMPTY_INBOX_UNREAD_SUMMARY,
EMPTY_SEARCH_PROJECTS_RESPONSE,
@@ -259,6 +261,53 @@ describe("AgentTaskListSchema", () => {
});
});
+describe("ChatDraftRestoresResponseSchema", () => {
+ it("parses a well-formed response with attachments", () => {
+ const parsed = parseWithFallback(
+ {
+ restores: [
+ {
+ id: "msg-1",
+ chat_session_id: "s-1",
+ task_id: "t-1",
+ content: "run the thing",
+ attachments: [{ id: "att-1", filename: "notes.txt" }],
+ created_at: "2026-07-01T00:00:00Z",
+ },
+ ],
+ },
+ ChatDraftRestoresResponseSchema,
+ EMPTY_CHAT_DRAFT_RESTORES,
+ { endpoint: "test" },
+ );
+ expect(parsed.restores).toHaveLength(1);
+ expect(parsed.restores[0]?.content).toBe("run the thing");
+ expect(parsed.restores[0]?.attachments?.[0]?.id).toBe("att-1");
+ });
+
+ it("defaults a missing restores array instead of crashing the composer", () => {
+ const parsed = parseWithFallback(
+ {},
+ ChatDraftRestoresResponseSchema,
+ EMPTY_CHAT_DRAFT_RESTORES,
+ { endpoint: "test" },
+ );
+ expect(parsed.restores).toEqual([]);
+ });
+
+ it("falls back to the empty response on a malformed row", () => {
+ // A row without the consume key (id) is unusable — the whole response
+ // falls back and the durable rows simply stay pending server-side.
+ const parsed = parseWithFallback(
+ { restores: [{ chat_session_id: "s-1", content: 42 }] },
+ ChatDraftRestoresResponseSchema,
+ EMPTY_CHAT_DRAFT_RESTORES,
+ { endpoint: "test" },
+ );
+ expect(parsed).toEqual(EMPTY_CHAT_DRAFT_RESTORES);
+ });
+});
+
describe("CreateFeedbackResponseSchema", () => {
const ENDPOINT = { endpoint: "POST /api/feedback" };
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index ce9cc1fb84..0a789e9201 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -12,6 +12,7 @@ import type {
BillingTopupsPage,
BillingTransactionsPage,
CancelTaskResponse,
+ ChatDraftRestoresResponse,
CreateAgentFromTemplateResponse,
CreateBillingCheckoutSessionResponse,
CreateBillingPortalSessionResponse,
@@ -642,6 +643,29 @@ export const CancelTaskResponseSchema = AgentTaskSchema.extend({
.transform((value) => value ?? undefined),
}).loose();
+// Deferred-cancellation draft restores
+// (`GET /api/chat/sessions/{id}/draft-restores`, #5219) feed the composer
+// directly: `content` becomes the draft text, `attachments` re-bind on
+// re-send, and `id` is the consume key. A malformed response falls back to
+// an empty list — the durable row stays pending server-side, so nothing is
+// lost by skipping a fetch.
+const ChatDraftRestoreSchema = z.object({
+ id: z.string(),
+ chat_session_id: z.string(),
+ task_id: z.string().optional(),
+ content: z.string().default(""),
+ attachments: z.array(AttachmentSchema).optional(),
+ created_at: z.string().optional(),
+}).loose();
+
+export const ChatDraftRestoresResponseSchema = z.object({
+ restores: z.array(ChatDraftRestoreSchema).default([]),
+}).loose();
+
+export const EMPTY_CHAT_DRAFT_RESTORES: ChatDraftRestoresResponse = {
+ restores: [],
+};
+
export const EMPTY_CANCEL_TASK_RESPONSE: CancelTaskResponse = {
id: "",
agent_id: "",
diff --git a/packages/core/chat/mutations.test.tsx b/packages/core/chat/mutations.test.tsx
index 088250665b..df582fe62a 100644
--- a/packages/core/chat/mutations.test.tsx
+++ b/packages/core/chat/mutations.test.tsx
@@ -8,7 +8,7 @@ import type { ReactNode } from "react";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
-import { useSetChatSessionArchived } from "./mutations";
+import { useConsumeChatDraftRestore, useSetChatSessionArchived } from "./mutations";
import { chatKeys } from "./queries";
import type { ChatSession } from "../types";
@@ -125,3 +125,69 @@ describe("useSetChatSessionArchived", () => {
expect(row.has_unread).toBe(true);
});
});
+
+// The consume DELETE is the last step of a durable draft restore (#5219), and
+// mutations are `retry: false` app-wide — a single dropped request would leave
+// the row behind, to be re-offered later. The endpoint is idempotent, so this
+// one retries instead of giving up on the first failure.
+describe("useConsumeChatDraftRestore", () => {
+ let qc: QueryClient;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ qc = new QueryClient();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("retries a lost consume until the server acknowledges it", async () => {
+ const consumeChatDraftRestore = vi
+ .fn<(sessionId: string, restoreId: string) => Promise<void>>()
+ .mockRejectedValueOnce(new Error("network"))
+ .mockResolvedValueOnce(undefined);
+ setApiInstance({ consumeChatDraftRestore } as unknown as ApiClient);
+
+ const onSuccess = vi.fn();
+ const { result } = renderHook(() => useConsumeChatDraftRestore(), {
+ wrapper: createWrapper(qc),
+ });
+
+ act(() => {
+ result.current.mutate({ sessionId: "s1", restoreId: "r1" }, { onSuccess });
+ });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000);
+ });
+
+ expect(consumeChatDraftRestore).toHaveBeenCalledTimes(2);
+ expect(onSuccess).toHaveBeenCalledTimes(1);
+ });
+
+ it("drops the row from the cache immediately so it is not re-offered", async () => {
+ const consumeChatDraftRestore = vi.fn().mockResolvedValue(undefined);
+ setApiInstance({ consumeChatDraftRestore } as unknown as ApiClient);
+ qc.setQueryData(chatKeys.draftRestores("s1"), {
+ restores: [
+ { id: "r1", chat_session_id: "s1", content: "keep me" },
+ { id: "r2", chat_session_id: "s1", content: "other" },
+ ],
+ });
+
+ const { result } = renderHook(() => useConsumeChatDraftRestore(), {
+ wrapper: createWrapper(qc),
+ });
+ act(() => {
+ result.current.mutate({ sessionId: "s1", restoreId: "r1" });
+ });
+
+ const cached = qc.getQueryData(chatKeys.draftRestores("s1")) as {
+ restores: { id: string }[];
+ };
+ expect(cached.restores.map((r) => r.id)).toEqual(["r2"]);
+ });
+});
diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.ts
index cdb8f9a5e6..c273e3819a 100644
--- a/packages/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -3,10 +3,47 @@ import { api } from "../api";
import { useWorkspaceId } from "../hooks";
import { chatKeys, sortChatSessions } from "./queries";
import { createLogger } from "../logger";
-import type { ChatSession, ChatPinnedAgent } from "../types";
+import type { ChatSession, ChatPinnedAgent, ChatDraftRestoresResponse } from "../types";
const logger = createLogger("chat.mut");
+/**
+ * Consume a deferred-cancellation draft restore (#5219) after the composer has
+ * applied it. The endpoint is idempotent, so consuming twice — or consuming a
+ * row a previous attempt already deleted — is safe, which is what lets this
+ * retry at all (mutations are `retry: false` app-wide).
+ *
+ * A lost consume must never re-restore a prompt the user has since sent, so the
+ * "applied" decision is not carried by this request: the caller records it in
+ * the persisted ledger (`markDraftRestoreApplied`) before firing, and reconciles
+ * any row that outlives its ledger entry by consuming it again. This mutation
+ * only has to make that reconciliation converge quickly.
+ */
+export function useConsumeChatDraftRestore() {
+ const qc = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ sessionId, restoreId }: { sessionId: string; restoreId: string }) =>
+ api.consumeChatDraftRestore(sessionId, restoreId),
+ retry: 3,
+ retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 8000),
+ onMutate: ({ sessionId, restoreId }) => {
+ qc.setQueryData<ChatDraftRestoresResponse>(
+ chatKeys.draftRestores(sessionId),
+ (old) =>
+ old
+ ? { ...old, restores: old.restores.filter((r) => r.id !== restoreId) }
+ : old,
+ );
+ },
+ onError: (err, { sessionId, restoreId }) => {
+ // Exhausted the retries. The draft is safe (it is in the composer) and the
+ // ledger keeps the row from being re-offered; the next mount reconciles it.
+ logger.warn("consumeChatDraftRestore.error", { sessionId, restoreId, err });
+ },
+ });
+}
+
/** Pin an agent to the quick-agent bar (optimistic append). */
export function usePinChatAgent() {
const qc = useQueryClient();
diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.ts
index 8793530efb..63ca4a0c6b 100644
--- a/packages/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -21,6 +21,9 @@ export const chatKeys = {
messagesPage: (sessionId: string) => [...chatKeys.messagesPageAll(), sessionId] as const,
pendingTaskAll: () => ["chat", "pending-task"] as const,
pendingTask: (sessionId: string) => [...chatKeys.pendingTaskAll(), sessionId] as const,
+ draftRestoresAll: () => ["chat", "draft-restores"] as const,
+ /** Durable deferred-cancellation draft restores for a session (#5219). */
+ draftRestores: (sessionId: string) => [...chatKeys.draftRestoresAll(), sessionId] as const,
/** Aggregate of in-flight chat tasks for the current user — FAB reads this. */
pendingTasks: (wsId: string) => [...chatKeys.all(wsId), "pending-tasks"] as const,
/** Per-user pinned agents for the quick-agent bar. */
@@ -140,6 +143,26 @@ export function pendingChatTaskOptions(sessionId: string) {
});
}
+/**
+ * Durable deferred-cancellation draft restores for a session (#5219).
+ * staleTime 0 deliberately overrides the app-wide Infinity default: this is
+ * the recovery path for a client that MISSED the chat:cancel_finalized
+ * broadcast, so it must actually refetch on every composer mount (an
+ * Infinity-fresh cache would pin the first result forever). WS reconnects
+ * additionally invalidate chatKeys.draftRestoresAll() in useRealtimeSync,
+ * and the initiator's realtime handler invalidates this key when the event
+ * does arrive. The response is tiny (usually empty), so the extra fetches
+ * are negligible.
+ */
+export function chatDraftRestoresOptions(sessionId: string) {
+ return queryOptions({
+ queryKey: chatKeys.draftRestores(sessionId),
+ queryFn: () => api.listChatDraftRestores(sessionId),
+ enabled: !!sessionId,
+ staleTime: 0,
+ });
+}
+
/**
* Timeline for a single task — rendered by both the live chat view (while a
* task is running) and AssistantMessage (for completed tasks). WS
diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.ts
index 227cbea0f1..762977eaf1 100644
--- a/packages/core/chat/store.test.ts
+++ b/packages/core/chat/store.test.ts
@@ -138,3 +138,51 @@ describe("chat store — floating window preference", () => {
expect(storage.getItem("multica:chat:floatingChatEnabled")).toBe("true");
});
});
+
+// The ledger is what makes a durable draft restore (#5219) apply at most once.
+// A consume request can be lost — retries exhausted, app closed mid-flight — and
+// the row then comes back on the next fetch. Without a record that survives the
+// reload, the prompt would be restored into the composer a second time, after
+// the user has already sent it.
+describe("chat store — applied draft-restore ledger", () => {
+ it("survives a reload so a lost consume cannot re-offer the restore", () => {
+ const storage = memStorage();
+ const store = createChatStore({ storage });
+
+ store.getState().markDraftRestoreApplied("restore-1");
+ expect(store.getState().appliedDraftRestoreIds).toEqual(["restore-1"]);
+
+ const reloaded = createChatStore({ storage });
+ expect(reloaded.getState().appliedDraftRestoreIds).toEqual(["restore-1"]);
+ });
+
+ it("is idempotent and drops the entry once the row is confirmed gone", () => {
+ const store = createChatStore({ storage: memStorage() });
+
+ store.getState().markDraftRestoreApplied("restore-1");
+ store.getState().markDraftRestoreApplied("restore-1");
+ expect(store.getState().appliedDraftRestoreIds).toEqual(["restore-1"]);
+
+ store.getState().forgetDraftRestoreApplied("restore-1");
+ expect(store.getState().appliedDraftRestoreIds).toEqual([]);
+ });
+
+ // Every entry in here is an unconfirmed consume: its row is still on the
+ // server. Evicting one to cap the ledger would re-arm the restore it was
+ // suppressing — the next fetch offers an already-applied prompt again and the
+ // user can send it twice. Only server confirmation may compact this.
+ it("never evicts an unconfirmed entry, however many pile up", () => {
+ const store = createChatStore({ storage: memStorage() });
+ for (let i = 0; i < 60; i++) store.getState().markDraftRestoreApplied(`r-${i}`);
+
+ const ids = store.getState().appliedDraftRestoreIds;
+ expect(ids).toHaveLength(60);
+ expect(ids[0]).toBe("r-0");
+ expect(ids[59]).toBe("r-59");
+
+ // The one exit: the server confirmed the row is gone.
+ store.getState().forgetDraftRestoreApplied("r-0");
+ expect(store.getState().appliedDraftRestoreIds).toHaveLength(59);
+ expect(store.getState().appliedDraftRestoreIds[0]).toBe("r-1");
+ });
+});
diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.ts
index 20b37e4841..127c197af2 100644
--- a/packages/core/chat/store.ts
+++ b/packages/core/chat/store.ts
@@ -12,6 +12,29 @@ const SESSION_STORAGE_KEY = "multica:chat:activeSessionId";
const DRAFTS_KEY = "multica:chat:drafts";
/** Draft attachment records per workspace: { [sessionId]: Attachment[] }. */
const DRAFT_ATTACHMENTS_KEY = "multica:chat:draft-attachments";
+/**
+ * Ids of durable draft restores (#5219) this client has already written into a
+ * composer. Persisted, because the server-side consume that follows can be lost
+ * (retries exhausted, the app closed mid-flight) and the row would then be
+ * re-offered on the next fetch — re-restoring a prompt the user has since sent.
+ * The ledger makes the hand-off at-most-once regardless: an id in here is never
+ * offered again, only reconciled (consumed again) until the row is gone.
+ */
+const APPLIED_RESTORES_KEY = "multica:chat:applied-draft-restores";
+/**
+ * Local restore requests waiting to reach a composer, queued per session (#5219).
+ *
+ * These are the restores with NO server copy — a send that failed, or a cancel
+ * that answered synchronously. The send already cleared the persisted draft, so
+ * this queue is the only place their text exists. It is persisted for exactly
+ * that reason: a request the composer cannot act on yet (the user is looking at
+ * another session, or has work in progress in this one) must survive an unmount,
+ * a refresh, or a close, and be re-offered when they come back.
+ *
+ * Durable restores (which have a server row) deliberately do NOT go in here —
+ * they are refetchable, so dropping one loses nothing.
+ */
+const PENDING_SEND_RESTORES_KEY = "multica:chat:pending-send-restores";
/** Placeholder sessionId for a chat that hasn't been created yet. */
export const DRAFT_NEW_SESSION = "__new__";
@@ -96,6 +119,68 @@ function readDraftAttachments(storage: StorageAdapter, key: string): Record<stri
}
}
+function readAppliedRestores(storage: StorageAdapter, key: string): string[] {
+ const raw = storage.getItem(key);
+ if (!raw) return [];
+ try {
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((id): id is string => typeof id === "string");
+ } catch {
+ return [];
+ }
+}
+
+function writeAppliedRestores(storage: StorageAdapter, key: string, ids: string[]) {
+ if (ids.length === 0) storage.removeItem(key);
+ else storage.setItem(key, JSON.stringify(ids));
+}
+
+function isPendingSendRestore(value: unknown): value is PendingSendRestore {
+ if (typeof value !== "object" || value === null) return false;
+ const v = value as { id?: unknown; content?: unknown; sessionId?: unknown };
+ return (
+ typeof v.id === "string" && typeof v.content === "string" && typeof v.sessionId === "string"
+ );
+}
+
+function readPendingSendRestores(
+ storage: StorageAdapter,
+ key: string,
+): Record<string, PendingSendRestore[]> {
+ const raw = storage.getItem(key);
+ if (!raw) return {};
+ try {
+ const parsed = JSON.parse(raw);
+ if (typeof parsed !== "object" || parsed === null) return {};
+ const out: Record<string, PendingSendRestore[]> = {};
+ for (const [sessionId, value] of Object.entries(parsed)) {
+ if (!Array.isArray(value)) continue;
+ const queued = value.filter(isPendingSendRestore).map((r) => ({
+ ...r,
+ attachments: Array.isArray(r.attachments) ? r.attachments.filter(isAttachmentDraft) : [],
+ }));
+ if (queued.length > 0) out[sessionId] = queued;
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
+
+function writePendingSendRestores(
+ storage: StorageAdapter,
+ key: string,
+ queues: Record<string, PendingSendRestore[]>,
+) {
+ const pruned: Record<string, PendingSendRestore[]> = {};
+ for (const [k, v] of Object.entries(queues)) {
+ if (v.length > 0) pruned[k] = v;
+ }
+ if (Object.keys(pruned).length === 0) storage.removeItem(key);
+ else storage.setItem(key, JSON.stringify(pruned));
+}
+
function writeDraftAttachments(
storage: StorageAdapter,
key: string,
@@ -132,6 +217,19 @@ export interface ChatTimelineItem {
created_at?: string;
}
+/**
+ * A restore with no server copy, waiting for a composer that can take it. Its
+ * text exists nowhere else, so it lives in persisted storage until it is applied
+ * (see PENDING_SEND_RESTORES_KEY).
+ */
+export interface PendingSendRestore {
+ id: string;
+ content: string;
+ attachments?: Attachment[];
+ /** The session whose composer this belongs to. Never empty. */
+ sessionId: string;
+}
+
export interface ChatState {
isOpen: boolean;
/** Settings preference: is the floating chat window available at all. */
@@ -142,6 +240,10 @@ export interface ChatState {
inputDrafts: Record<string, string>;
/** Attachment rows referenced by each input draft. */
inputDraftAttachments: Record<string, Attachment[]>;
+ /** Durable draft restores already written into a composer (#5219). */
+ appliedDraftRestoreIds: string[];
+ /** Server-less restores waiting for their session's composer, per session (#5219). */
+ pendingSendRestores: Record<string, PendingSendRestore[]>;
/** Raw user-chosen size — no clamp applied. UI layer clamps at render time. */
chatWidth: number;
chatHeight: number;
@@ -156,6 +258,14 @@ export interface ChatState {
setInputDraftAttachments: (sessionId: string, attachments: Attachment[]) => void;
addInputDraftAttachment: (sessionId: string, attachment: Attachment) => void;
clearInputDraft: (sessionId: string) => void;
+ /** Record that a durable restore reached the composer; survives a reload. */
+ markDraftRestoreApplied: (restoreId: string) => void;
+ /** Drop the ledger entry once the server row is confirmed gone. */
+ forgetDraftRestoreApplied: (restoreId: string) => void;
+ /** Queue a server-less restore for its session; survives unmount/refresh. */
+ enqueuePendingSendRestore: (restore: PendingSendRestore) => void;
+ /** Drop a queued restore once its text is safely in the (persisted) draft. */
+ dequeuePendingSendRestore: (sessionId: string, restoreId: string) => void;
/** Persist raw size and auto-exit expanded mode. */
setChatSize: (width: number, height: number) => void;
setExpanded: (expanded: boolean) => void;
@@ -191,6 +301,8 @@ export function createChatStore(options: ChatStoreOptions) {
selectedAgentId: storage.getItem(wsKey(AGENT_STORAGE_KEY)),
inputDrafts: readDrafts(storage, wsKey(DRAFTS_KEY)),
inputDraftAttachments: readDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY)),
+ appliedDraftRestoreIds: readAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY)),
+ pendingSendRestores: readPendingSendRestores(storage, wsKey(PENDING_SEND_RESTORES_KEY)),
chatWidth: Number(storage.getItem(CHAT_WIDTH_KEY)) || CHAT_DEFAULT_W,
chatHeight: Number(storage.getItem(CHAT_HEIGHT_KEY)) || CHAT_DEFAULT_H,
isExpanded: storage.getItem(wsKey(CHAT_EXPANDED_KEY)) === "true",
@@ -227,6 +339,59 @@ export function createChatStore(options: ChatStoreOptions) {
storage.setItem(wsKey(AGENT_STORAGE_KEY), id);
set({ selectedAgentId: id });
},
+ // Append-only until the server confirms. There is deliberately no capacity
+ // cap: every entry in here is an UNconfirmed consume, and evicting one
+ // silently re-arms the restore it was suppressing — the row is still on the
+ // server, so the next fetch would offer an already-applied prompt again and
+ // the user could send it twice. Entries leave only through
+ // forgetDraftRestoreApplied, i.e. only once the row is provably gone, which
+ // bounds the ledger by the number of restores whose consume is still failing.
+ markDraftRestoreApplied: (restoreId) => {
+ const current = get().appliedDraftRestoreIds;
+ if (current.includes(restoreId)) return;
+ const next = [...current, restoreId];
+ writeAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY), next);
+ set({ appliedDraftRestoreIds: next });
+ },
+ /** Called only on a confirmed consume: the server row is gone. */
+ forgetDraftRestoreApplied: (restoreId) => {
+ const current = get().appliedDraftRestoreIds;
+ if (!current.includes(restoreId)) return;
+ const next = current.filter((id) => id !== restoreId);
+ writeAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY), next);
+ set({ appliedDraftRestoreIds: next });
+ },
+ // Queued per session, not in one shared slot: a request for a session the
+ // user is not looking at must never hold the composer's only restore slot
+ // (it would starve the session they ARE looking at), and it has no server
+ // copy to fall back on, so it cannot simply be dropped either. FIFO, so two
+ // failures against the same session are both recovered, oldest first.
+ enqueuePendingSendRestore: (restore) => {
+ if (!restore.sessionId || !restore.id) return;
+ const current = get().pendingSendRestores;
+ const existing = current[restore.sessionId] ?? [];
+ if (existing.some((r) => r.id === restore.id)) return;
+ logger.info("enqueuePendingSendRestore", {
+ sessionId: restore.sessionId,
+ restoreId: restore.id,
+ });
+ const next = { ...current, [restore.sessionId]: [...existing, restore] };
+ writePendingSendRestores(storage, wsKey(PENDING_SEND_RESTORES_KEY), next);
+ set({ pendingSendRestores: next });
+ },
+ /** Only after the text has landed in the draft, which is itself persisted. */
+ dequeuePendingSendRestore: (sessionId, restoreId) => {
+ const current = get().pendingSendRestores;
+ const existing = current[sessionId];
+ if (!existing?.some((r) => r.id === restoreId)) return;
+ logger.info("dequeuePendingSendRestore", { sessionId, restoreId });
+ const remaining = existing.filter((r) => r.id !== restoreId);
+ const next = { ...current };
+ if (remaining.length > 0) next[sessionId] = remaining;
+ else delete next[sessionId];
+ writePendingSendRestores(storage, wsKey(PENDING_SEND_RESTORES_KEY), next);
+ set({ pendingSendRestores: next });
+ },
setInputDraft: (sessionId, draft) => {
// Debug level — onUpdate fires on every keystroke.
logger.debug("setInputDraft", { sessionId, length: draft.length });
@@ -306,6 +471,8 @@ export function createChatStore(options: ChatStoreOptions) {
selectedAgentId: nextAgent,
inputDrafts: nextDrafts,
inputDraftAttachments: nextDraftAttachments,
+ appliedDraftRestoreIds: readAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY)),
+ pendingSendRestores: readPendingSendRestores(storage, wsKey(PENDING_SEND_RESTORES_KEY)),
});
});
diff --git a/packages/core/realtime/index.ts b/packages/core/realtime/index.ts
index 5769933afd..639c9ae683 100644
--- a/packages/core/realtime/index.ts
+++ b/packages/core/realtime/index.ts
@@ -1,5 +1,5 @@
export { WSProvider, useWS } from "./provider";
export type { WSProviderProps } from "./provider";
export { useWSEvent, useWSReconnect } from "./hooks";
-export { useRealtimeSync } from "./use-realtime-sync";
+export { useRealtimeSync, removeChatMessageFromCaches } from "./use-realtime-sync";
export type { RealtimeSyncStores } from "./use-realtime-sync";
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 6084a0f3c4..612de3584c 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -108,9 +108,9 @@ describe("useRealtimeSync — ws instance change", () => {
rerender({ ws: ws2 });
// Should have called invalidateQueries for all workspace-scoped keys
- // (15 workspace-scoped + 6 per-issue prefixes + 4 per-chat prefixes
- // + 1 workspaceKeys.list() + 1 cross-workspace inbox unread summary = 27 calls)
- expect(invalidateSpy).toHaveBeenCalledTimes(27);
+ // (15 workspace-scoped + 6 per-issue prefixes + 5 per-chat prefixes
+ // + 1 workspaceKeys.list() + 1 cross-workspace inbox unread summary = 28 calls)
+ expect(invalidateSpy).toHaveBeenCalledTimes(28);
});
it("does not re-invalidate when rerendered with the same ws instance", () => {
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index 0358dc5bdb..5ea79ac819 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -17,6 +17,7 @@ import type {
Workspace,
} from "../types";
import {
+ applyChatCancelFinalizedToCache,
applyChatDoneToCache,
applyChatSessionUpdatedToCache,
applyWorkspaceUpdatedToCache,
@@ -248,6 +249,151 @@ describe("invalidateChatMessageQueries", () => {
});
});
+describe("applyChatCancelFinalizedToCache", () => {
+ function cancelledUserMessage(): ChatMessage {
+ return {
+ id: "msg-cancelled-user",
+ chat_session_id: sessionId,
+ role: "user",
+ content: "run the thing",
+ task_id: taskId,
+ created_at: "2026-05-13T05:00:00Z",
+ };
+ }
+
+ const draftRestoresKey = chatKeys.draftRestores(sessionId);
+
+ it("inserts the late Stopped. assistant row on a stopped outcome", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [cancelledUserMessage()]);
+
+ applyChatCancelFinalizedToCache(qc, {
+ outcome: "stopped",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-stopped",
+ content: "Stopped.",
+ created_at: "2026-05-13T05:00:05Z",
+ elapsed_ms: 5000,
+ });
+
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([
+ cancelledUserMessage(),
+ {
+ id: "msg-stopped",
+ chat_session_id: sessionId,
+ role: "assistant",
+ content: "Stopped.",
+ task_id: taskId,
+ created_at: "2026-05-13T05:00:05Z",
+ elapsed_ms: 5000,
+ message_kind: "message",
+ },
+ ]);
+ });
+
+ it("removes the user message and clears the pending task on a restored outcome", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [cancelledUserMessage()]);
+ qc.setQueryData<ChatPendingTask>(pendingKey, {
+ task_id: taskId,
+ status: "running",
+ });
+
+ applyChatCancelFinalizedToCache(qc, {
+ outcome: "restored",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-cancelled-user",
+ });
+
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([]);
+ expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({});
+ });
+
+ it("invalidates the draft-restores query for the initiator", () => {
+ const qc = createQueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ applyChatCancelFinalizedToCache(
+ qc,
+ {
+ outcome: "restored",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-cancelled-user",
+ initiator_user_id: "user-initiator",
+ },
+ "user-initiator",
+ );
+
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: draftRestoresKey });
+ });
+
+ it("does not fetch the restore for a non-initiator recipient of the broadcast", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [cancelledUserMessage()]);
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ applyChatCancelFinalizedToCache(
+ qc,
+ {
+ outcome: "restored",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-cancelled-user",
+ initiator_user_id: "user-initiator",
+ },
+ "user-someone-else",
+ );
+
+ // The bubble is still dropped for cache consistency, but the restore
+ // fetch (and thus the private prompt) stays with the initiator.
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([]);
+ expect(invalidate).not.toHaveBeenCalledWith({ queryKey: draftRestoresKey });
+ });
+
+ it("fails closed when the event omits initiator_user_id", () => {
+ const qc = createQueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ applyChatCancelFinalizedToCache(
+ qc,
+ {
+ outcome: "restored",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-cancelled-user",
+ },
+ "user-initiator",
+ );
+
+ // Nothing is lost by skipping the eager fetch: the durable restore is
+ // still picked up on the next composer mount / reconnect refetch.
+ expect(invalidate).not.toHaveBeenCalledWith({ queryKey: draftRestoresKey });
+ });
+
+ it("still settles the caches when a restored outcome carries no message id", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [cancelledUserMessage()]);
+ qc.setQueryData<ChatPendingTask>(pendingKey, {
+ task_id: taskId,
+ status: "running",
+ });
+
+ applyChatCancelFinalizedToCache(qc, {
+ outcome: "restored",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ });
+
+ // No id to surgically remove — the list is left to the invalidation
+ // refetch — but the pending indicator still clears.
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([cancelledUserMessage()]);
+ expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({});
+ });
+});
+
describe("refetchPendingChatAggregate (cross-session pending leak guard)", () => {
const wsId = "ws-1";
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 8dd5c0878c..3bb1692fc8 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -81,6 +81,7 @@ import type {
TaskFailedPayload,
TaskCancelledPayload,
ChatDonePayload,
+ ChatCancelFinalizedPayload,
ChatMessage,
ChatPendingTask,
ChatMessagesPage,
@@ -236,6 +237,91 @@ export function applyChatSessionUpdatedToCache(
});
}
+function removeChatMessageFromPageCache(
+ qc: QueryClient,
+ sessionId: string,
+ messageId: string,
+) {
+ qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
+ chatKeys.messagesPage(sessionId),
+ (old) => {
+ if (!old) return old;
+ return {
+ ...old,
+ pages: old.pages.map((page) => ({
+ ...page,
+ messages: page.messages.filter((m) => m.id !== messageId),
+ })),
+ };
+ },
+ );
+}
+
+export function removeChatMessageFromCaches(
+ qc: QueryClient,
+ sessionId: string,
+ messageId: string,
+) {
+ qc.setQueryData<ChatMessage[]>(
+ chatKeys.messages(sessionId),
+ (old) => old?.filter((m) => m.id !== messageId) ?? old,
+ );
+ removeChatMessageFromPageCache(qc, sessionId, messageId);
+}
+
+/**
+ * Apply a chat:cancel_finalized event (#5219): the deferred outcome of a
+ * cancelled chat task, settled after the daemon's transcript flush.
+ *
+ * - outcome "stopped": a late "Stopped." assistant row was persisted —
+ * insert it exactly like a chat:done message.
+ * - outcome "restored": the triggering user message was deleted — drop it
+ * from the caches. The deleted prompt itself never rides this
+ * workspace-wide broadcast: it is durable server-side and only the
+ * initiator's client refetches it through the creator-authorized
+ * draft-restores query, which the session's composer applies and consumes.
+ *
+ * The draft-restores invalidation is gated to the task's initiator and fails
+ * closed when initiator_user_id is missing — nothing is lost either way,
+ * because the durable restore is fetched again on the next composer mount or
+ * network reconnect. Cache patches stay unconditional — they are no-ops for
+ * anyone not viewing the session.
+ */
+export function applyChatCancelFinalizedToCache(
+ qc: QueryClient,
+ payload: ChatCancelFinalizedPayload,
+ currentUserId?: string,
+) {
+ const sessionId = payload.chat_session_id;
+ if (!sessionId) return;
+ if (payload.outcome === "stopped") {
+ applyChatDoneToCache(qc, {
+ chat_session_id: sessionId,
+ task_id: payload.task_id,
+ message_id: payload.message_id,
+ content: payload.content,
+ elapsed_ms: payload.elapsed_ms,
+ created_at: payload.created_at,
+ message_kind: payload.message_kind,
+ });
+ return;
+ }
+ if (payload.outcome === "restored") {
+ if (payload.message_id) {
+ removeChatMessageFromCaches(qc, sessionId, payload.message_id);
+ }
+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ invalidateChatMessageQueries(qc, sessionId);
+ const isInitiator =
+ !!payload.initiator_user_id &&
+ !!currentUserId &&
+ payload.initiator_user_id === currentUserId;
+ if (isInitiator) {
+ void qc.invalidateQueries({ queryKey: chatKeys.draftRestores(sessionId) });
+ }
+ }
+}
+
/**
* Apply a workspace:updated event directly to the cached workspace list.
* If the incoming `issue_prefix` differs from what's currently cached, also
@@ -433,6 +519,10 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {
qc.invalidateQueries({ queryKey: chatKeys.messagesPageAll() });
qc.invalidateQueries({ queryKey: chatKeys.pendingTaskAll() });
qc.invalidateQueries({ queryKey: chatKeys.taskMessagesAll() });
+ // A chat:cancel_finalized broadcast missed while disconnected is exactly
+ // what the durable draft-restore rows exist for (#5219) — re-pull them so
+ // a mounted composer recovers the prompt without a remount.
+ qc.invalidateQueries({ queryKey: chatKeys.draftRestoresAll() });
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
}
@@ -667,8 +757,8 @@ export function useRealtimeSync(
"subscriber:added", "subscriber:removed",
"daemon:heartbeat",
// Chat events are handled explicitly below; do not double-invalidate.
- "chat:message", "chat:done", "chat:session_read", "chat:session_deleted",
- "chat:session_updated",
+ "chat:message", "chat:done", "chat:cancel_finalized", "chat:session_read",
+ "chat:session_deleted", "chat:session_updated",
// task:message stays out of the prefix path because it fires per
// streamed message during a long run — invalidating the snapshot on
// every message would flood the network. Specific chat handlers below
@@ -1033,6 +1123,24 @@ export function useRealtimeSync(
invalidateSessionLists();
});
+ // Deferred cancellation outcome (#5219): the server settles the
+ // empty/non-empty judgment only after the daemon's transcript flush, so
+ // this event arrives seconds after the cancel HTTP response — nothing
+ // else re-fetches at that point.
+ const unsubChatCancelFinalized = ws.on("chat:cancel_finalized", (p) => {
+ const payload = p as ChatCancelFinalizedPayload;
+ chatWsLogger.info("chat:cancel_finalized (global)", {
+ task_id: payload.task_id,
+ chat_session_id: payload.chat_session_id,
+ outcome: payload.outcome,
+ });
+ applyChatCancelFinalizedToCache(qc, payload, authStore.getState().user?.id);
+ if (payload.outcome === "stopped") {
+ // A Stopped. assistant row just landed → session previews change.
+ invalidateSessionLists();
+ }
+ });
+
// Chat task lifecycle writethrough: keep `chatKeys.pendingTask(sessionId)`
// synchronized with the server state machine via setQueryData rather than
// invalidate-refetch. Same pattern as task:message — the WS payload
@@ -1248,6 +1356,7 @@ export function useRealtimeSync(
unsubTaskMessage();
unsubChatMessage();
unsubChatDone();
+ unsubChatCancelFinalized();
unsubTaskQueued();
unsubTaskDispatch();
unsubTaskRunning();
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index 2f261052bb..ad38379a5a 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -154,6 +154,32 @@ export interface CancelTaskResponse extends AgentTask {
cancelled_chat_message?: CancelledChatMessage;
}
+/**
+ * One durable draft restore from GET /api/chat/sessions/{id}/draft-restores
+ * (#5219): a deferred cancellation settled as empty-transcript after the
+ * cancel HTTP response had returned, so the deleted prompt is held
+ * server-side until the creator's client applies it to the composer and
+ * consumes it (DELETE, idempotent). The chat:cancel_finalized event is only
+ * an invalidation hint for this fetch.
+ */
+export interface ChatDraftRestore {
+ /** The deleted user chat message id — stable dedup and consume key. */
+ id: string;
+ chat_session_id: string;
+ task_id?: string;
+ content: string;
+ /**
+ * Attachments detached from the deleted message so a restored draft can
+ * re-bind them on re-send.
+ */
+ attachments?: import("./attachment").Attachment[];
+ created_at?: string;
+}
+
+export interface ChatDraftRestoresResponse {
+ restores: ChatDraftRestore[];
+}
+
/**
* Response from GET /api/chat/sessions/{id}/pending-task.
* All fields are absent when the session has no in-flight task.
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 7dd314274c..bb0c0624da 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -54,6 +54,7 @@ export type WSEventType =
| "issue_reaction:removed"
| "chat:message"
| "chat:done"
+ | "chat:cancel_finalized"
| "chat:session_read"
| "chat:session_deleted"
| "chat:session_updated"
@@ -357,6 +358,36 @@ export interface ChatDonePayload {
message_kind?: import("./chat").ChatMessageKind;
}
+/**
+ * Deferred outcome of a cancelled chat task (#5219). The cancel HTTP response
+ * cannot carry it — the empty/non-empty judgment settles only after the
+ * daemon's transcript flush — so the server broadcasts it here instead:
+ * outcome "stopped" describes a freshly-persisted "Stopped." assistant row
+ * (ChatDonePayload-shaped fields), outcome "restored" is a content-free
+ * invalidation hint — the deleted prompt itself is durable server-side and
+ * the initiator's client fetches it from the creator-authorized
+ * draft-restores endpoint. All fields beyond the discriminator are optional —
+ * treat defensively and fall back to a refetch.
+ */
+export interface ChatCancelFinalizedPayload {
+ outcome: "stopped" | "restored";
+ chat_session_id: string;
+ task_id: string;
+ /**
+ * The user who triggered the cancelled task. Only this user's client needs
+ * to refetch draft restores; treat a missing value as "not me" (fail
+ * closed — the durable restore is still picked up on the next session
+ * open).
+ */
+ initiator_user_id?: string;
+ message_id?: string;
+ /** "Stopped." assistant row fields — set only for outcome "stopped". */
+ content?: string;
+ message_kind?: import("./chat").ChatMessageKind;
+ created_at?: string;
+ elapsed_ms?: number;
+}
+
export interface ChatSessionReadPayload {
chat_session_id: string;
}
@@ -452,6 +483,7 @@ export interface WSEventPayloadMap {
"activity:created": ActivityCreatedPayload;
"chat:message": ChatMessageEventPayload;
"chat:done": ChatDonePayload;
+ "chat:cancel_finalized": ChatCancelFinalizedPayload;
"chat:session_read": ChatSessionReadPayload;
"chat:session_deleted": ChatSessionDeletedPayload;
"chat:session_updated": unknown;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 2cfa7e6403..0cb0ec61c3 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -92,6 +92,8 @@ export type {
SendChatMessageResponse,
CancelledChatMessage,
CancelTaskResponse,
+ ChatDraftRestore,
+ ChatDraftRestoresResponse,
} from "./chat";
export type { StorageAdapter } from "./storage";
export type {
diff --git a/packages/views/agents/components/agent-creation-studio.test.ts b/packages/views/agents/components/agent-creation-studio.test.ts
index 34d86fee9f..50191cb90c 100644
--- a/packages/views/agents/components/agent-creation-studio.test.ts
+++ b/packages/views/agents/components/agent-creation-studio.test.ts
@@ -6,6 +6,7 @@ import {
encodeBuilderInput,
mergeBuilderDraft,
parseBuilderDraft,
+ pickBuilderRestore,
stripBuilderDraft,
type AgentDraft,
} from "./agent-creation-studio";
@@ -75,6 +76,39 @@ Return findings."}</agent_draft>`;
);
});
+ // The builder chat is a real chat_session, so cancelling a started-but-empty
+ // run defers the empty/non-empty judgment (#5219): the cancel response carries
+ // no restore_to_input and the prompt arrives later as a durable draft-restore
+ // row holding the ENCODED message. Handing that to the composer raw would show
+ // the user a wall of JSON instead of the sentence they typed.
+ it("decodes a durable draft restore before the builder composer adopts it", () => {
+ const encoded = encodeBuilderInput(
+ "Create a release manager",
+ draft(),
+ [],
+ [],
+ { id: "runtime-1", name: "Codex", provider: "codex" },
+ [],
+ );
+
+ expect(pickBuilderRestore(null, { id: "msg-1", content: encoded })).toEqual({
+ id: "msg-1",
+ content: "Create a release manager",
+ });
+ expect(pickBuilderRestore(null, null)).toBeNull();
+ });
+
+ // The synchronous answer (task never started) is already decoded and already
+ // in hand; it must not be displaced by a durable row for the same cancel.
+ it("prefers the synchronous cancel answer over a durable restore", () => {
+ expect(
+ pickBuilderRestore(
+ { id: "msg-1", content: "Create a release manager" },
+ { id: "msg-1", content: "should not win" },
+ ),
+ ).toEqual({ id: "msg-1", content: "Create a release manager" });
+ });
+
it("merges safe fields and rejects unknown workspace references", () => {
const result = mergeBuilderDraft(
draft(),
diff --git a/packages/views/agents/components/agent-creation-studio.tsx b/packages/views/agents/components/agent-creation-studio.tsx
index b9168fa624..8cc41722fc 100644
--- a/packages/views/agents/components/agent-creation-studio.tsx
+++ b/packages/views/agents/components/agent-creation-studio.tsx
@@ -54,7 +54,9 @@ import { Input } from "@multica/ui/components/ui/input";
import { Textarea } from "@multica/ui/components/ui/textarea";
import { cn } from "@multica/ui/lib/utils";
import { AvatarUploadControl } from "../../common/avatar-upload-control";
+import { useAppForeground } from "../../common/use-app-foreground";
import { ChatInput } from "../../chat/components/chat-input";
+import { useChatDraftRestore } from "../../chat/components/use-chat-draft-restore";
import {
ChatMessageList,
ChatMessageSkeleton,
@@ -155,6 +157,28 @@ export function AgentCreationStudio() {
const appliedAssistantMessageRef = useRef<string | null>(null);
const builderSessionIdRef = useRef("");
+ // The builder chat is a real chat_session, so cancelling a started-but-empty
+ // run defers the empty/non-empty judgment exactly as it does in the main chat
+ // (#5219): stopBuilder's response carries no restore_to_input, and the prompt
+ // arrives later as a durable chat_draft_restore row. Without this hook the
+ // studio composer would simply never see it. The two sources are exclusive —
+ // the synchronous cancel answers immediately, the durable one lands after the
+ // daemon acks — so whichever exists is handed to the composer.
+ //
+ // Gated on app foreground: this studio is a dedicated route, so being mounted
+ // means the surface is on screen, but a backgrounded tab must not fetch/apply/
+ // consume a restore the user is waiting on elsewhere. It recovers on its next
+ // fetch once the tab is refocused.
+ const appForeground = useAppForeground();
+ const {
+ restoreDraftRequest: durableRestoreRequest,
+ handleRestoreDraftApplied: handleDurableRestoreApplied,
+ } = useChatDraftRestore(builderSessionId || null, appForeground);
+ const builderRestoreRequest = useMemo(
+ () => pickBuilderRestore(builderRestoreDraft, durableRestoreRequest),
+ [builderRestoreDraft, durableRestoreRequest],
+ );
+
useEffect(() => {
builderSessionIdRef.current = builderSessionId;
}, [builderSessionId]);
@@ -734,8 +758,14 @@ export function AgentCreationStudio() {
runtimeOnline={selectedRuntime?.status === "online"}
onSend={sendBuilderMessage}
onStop={() => void stopBuilder()}
- restoreDraftRequest={builderRestoreDraft}
- onRestoreDraftConsumed={() => setBuilderRestoreDraft(null)}
+ restoreDraftRequest={builderRestoreRequest}
+ onRestoreDraftApplied={() => {
+ if (builderRestoreDraft) {
+ setBuilderRestoreDraft(null);
+ return;
+ }
+ handleDurableRestoreApplied();
+ }}
error={builderError}
/>
<div className="min-h-0 overflow-y-auto border-l bg-muted/10">
@@ -1230,7 +1260,7 @@ function BuilderConversation({
onSend,
onStop,
restoreDraftRequest,
- onRestoreDraftConsumed,
+ onRestoreDraftApplied,
error,
}: {
sessionId: string;
@@ -1241,7 +1271,7 @@ function BuilderConversation({
onSend: (content: string) => Promise<boolean>;
onStop: () => void;
restoreDraftRequest: { id: string; content: string } | null;
- onRestoreDraftConsumed: () => void;
+ onRestoreDraftApplied: () => void;
error: string | null;
}) {
const { t } = useT("agents");
@@ -1331,7 +1361,7 @@ function BuilderConversation({
draftKeyOverride={draftKey}
editorKeyOverride={draftKey}
restoreDraftRequest={restoreDraftRequest}
- onRestoreDraftConsumed={onRestoreDraftConsumed}
+ onRestoreDraftApplied={onRestoreDraftApplied}
/>
</section>
);
@@ -1531,6 +1561,35 @@ export function decodeBuilderInput(content: string): string {
}
}
+export interface BuilderRestore {
+ id: string;
+ content: string;
+}
+
+/**
+ * Chooses which cancelled prompt the builder composer should adopt (#5219).
+ *
+ * Two sources, never both: cancelling a task the daemon never started answers
+ * synchronously (`cancelled_chat_message.restore_to_input`), while cancelling a
+ * started-but-empty one defers the judgment and delivers the prompt later as a
+ * durable chat_draft_restore row. The durable copy is the raw chat_message
+ * content, i.e. still in the builder's encoded wire form, so it is decoded here
+ * exactly as the synchronous path decodes its own.
+ *
+ * The session id is deliberately not carried over: the builder composer keys its
+ * draft by `agent-builder:<id>`, so ChatInput's session guard would never match
+ * a raw session id — and it does not need to, since this composer only ever
+ * shows the builder session.
+ */
+export function pickBuilderRestore(
+ synchronous: BuilderRestore | null,
+ durable: { id: string; content: string } | null,
+): BuilderRestore | null {
+ if (synchronous) return synchronous;
+ if (!durable) return null;
+ return { id: durable.id, content: decodeBuilderInput(durable.content) };
+}
+
export function mergeBuilderDraft(
current: AgentDraft,
payload: BuilderDraftPayload,
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index 102a6cd073..b0b17e8432 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -251,7 +251,7 @@ export function ChatPage() {
<ChatInput
onSend={c.handleSend}
restoreDraftRequest={c.restoreDraftRequest}
- onRestoreDraftConsumed={c.handleRestoreDraftConsumed}
+ onRestoreDraftApplied={c.handleRestoreDraftApplied}
onUploadFile={c.handleUploadFile}
onStop={c.handleStop}
isRunning={!!c.pendingTaskId}
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index e2c4f92580..70143dd9b2 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -205,6 +205,14 @@ function renderInput(props: Partial<React.ComponentProps<typeof ChatInput>> = {}
return { onSend, onUploadFile };
}
+function element(props: Partial<React.ComponentProps<typeof ChatInput>>) {
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatInput onSend={vi.fn()} onUploadFile={vi.fn()} agentName="Multica" {...props} />
+ </I18nProvider>
+ );
+}
+
describe("ChatInput focusRequest", () => {
it("focuses the editor when focusRequest becomes a non-zero value (new chat)", () => {
const { rerender } = render(
@@ -413,13 +421,13 @@ describe("ChatInput attachment wiring", () => {
describe("ChatInput async send", () => {
it("restores a cancelled empty run draft into the editor", async () => {
- const onRestoreDraftConsumed = vi.fn();
+ const onRestoreDraftApplied = vi.fn();
renderInput({
restoreDraftRequest: {
id: "msg-restored",
content: "bring this back",
},
- onRestoreDraftConsumed,
+ onRestoreDraftApplied,
});
await waitFor(() => {
@@ -428,29 +436,81 @@ describe("ChatInput async send", () => {
"bring this back",
);
expect(editorProps.last?.defaultValue).toBe("bring this back");
- expect(onRestoreDraftConsumed).toHaveBeenCalledTimes(1);
+ // The single terminal transition — the owner may now delete the server row.
+ expect(onRestoreDraftApplied).toHaveBeenCalledTimes(1);
});
});
- it("consumes a restore request even when an existing draft blocks restore", async () => {
+ // A restore the composer cannot apply yet must NOT be reported as done: the
+ // owner keeps it pending (and the durable row un-consumed) and this composer
+ // stays willing to take it. Marking it terminal here was the bug — the restore
+ // was never re-offered for the rest of the component\'s life.
+ it("waits — does not report — while an existing draft blocks the restore", async () => {
const state = useChatStore.getState() as unknown as {
inputDrafts: Record<string, string>;
setInputDraft: ReturnType<typeof vi.fn>;
};
state.inputDrafts["__draft_new__:agent-1"] = "already typing";
- const onRestoreDraftConsumed = vi.fn();
+ const onRestoreDraftApplied = vi.fn();
+
+ const { rerender } = render(
+ element({
+ restoreDraftRequest: { id: "msg-restored", content: "bring this back" },
+ onRestoreDraftApplied,
+ }),
+ );
+
+ await waitFor(() => {
+ expect(editorProps.last?.defaultValue).toBe("already typing");
+ });
+ expect(onRestoreDraftApplied).not.toHaveBeenCalled();
+ expect(state.setInputDraft).not.toHaveBeenCalledWith(
+ "__draft_new__:agent-1",
+ "bring this back",
+ );
+
+ // The user sends/clears what they were typing: the same restore, still
+ // pending, now lands.
+ state.inputDrafts["__draft_new__:agent-1"] = "";
+ rerender(
+ element({
+ restoreDraftRequest: { id: "msg-restored", content: "bring this back" },
+ onRestoreDraftApplied,
+ }),
+ );
+
+ await waitFor(() => {
+ expect(state.setInputDraft).toHaveBeenCalledWith(
+ "__draft_new__:agent-1",
+ "bring this back",
+ );
+ expect(onRestoreDraftApplied).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it("holds the restore when the draft has staged attachments but no text", async () => {
+ const state = useChatStore.getState() as unknown as {
+ inputDraftAttachments: Record<string, { id: string }[]>;
+ setInputDraft: ReturnType<typeof vi.fn>;
+ setInputDraftAttachments: ReturnType<typeof vi.fn>;
+ };
+ state.inputDraftAttachments["__draft_new__:agent-1"] = [{ id: "att-staged" }];
+ const onRestoreDraftApplied = vi.fn();
renderInput({
restoreDraftRequest: {
id: "msg-restored",
content: "bring this back",
},
- onRestoreDraftConsumed,
+ onRestoreDraftApplied,
});
await waitFor(() => {
- expect(onRestoreDraftConsumed).toHaveBeenCalledTimes(1);
+ expect(editorProps.last).toBeTruthy();
});
+ expect(onRestoreDraftApplied).not.toHaveBeenCalled();
+ // The staged attachment list must never be replaced by the restore.
+ expect(state.setInputDraftAttachments).not.toHaveBeenCalled();
expect(state.setInputDraft).not.toHaveBeenCalledWith(
"__draft_new__:agent-1",
"bring this back",
@@ -562,15 +622,78 @@ describe("ChatInput async send", () => {
// A failed fire-and-forget send must restore into the session it was sent
// FROM, never into whatever session the user navigated to in the meantime.
-describe("ChatInput session-aware restore", () => {
- function element(props: Partial<React.ComponentProps<typeof ChatInput>>) {
- return (
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <ChatInput onSend={vi.fn()} onUploadFile={vi.fn()} agentName="Multica" {...props} />
- </I18nProvider>
- );
+// The send affordance must not hang off `isEmpty` alone. ChatInput does not
+// remount on a session switch and ContentEditor's defaultValue-sync uses
+// emitUpdate:false, so a draft that arrives from the store — a restore parked
+// by useChatDraftRestore, or any draft typed in another session — never moves
+// `isEmpty`. Pinning the button to it left the user staring at their own text
+// with Send greyed out.
+describe("ChatInput send affordance", () => {
+ function sendButton() {
+ const buttons = screen.getAllByRole("button");
+ return buttons[buttons.length - 1]!;
}
+ it("enables Send for a draft that arrived from the store, not from typing", async () => {
+ const state = useChatStore.getState() as unknown as {
+ activeSessionId: string | null;
+ inputDrafts: Record<string, string>;
+ };
+ // Mount on an EMPTY session: isEmpty initializes to true. The bug needs this
+ // instance to survive the session switch — ChatInput is never remounted for
+ // one, so isEmpty keeps the value it took here.
+ state.activeSessionId = "session-a";
+ state.inputDrafts = { "session-b": "the text that failed to send" };
+
+ const { rerender } = render(element({}));
+ expect(sendButton()).toBeDisabled();
+
+ // Switch to the session holding the parked draft. The editor adopts it via
+ // the defaultValue sync (emitUpdate:false → no onUpdate → isEmpty untouched).
+ state.activeSessionId = "session-b";
+ rerender(element({}));
+
+ await waitFor(() => expect(sendButton()).not.toBeDisabled());
+ });
+
+ it("stays disabled when neither the editor nor the draft slot has content", async () => {
+ const state = useChatStore.getState() as unknown as {
+ activeSessionId: string | null;
+ inputDrafts: Record<string, string>;
+ };
+ state.activeSessionId = "session-b";
+ state.inputDrafts = {};
+
+ renderInput();
+
+ await waitFor(() => expect(sendButton()).toBeDisabled());
+ });
+
+ // The neighbouring path a naive "reset isEmpty on draftKey change" fix would
+ // have broken: the first upload in a brand-new chat lazily creates the session,
+ // flipping draftKey from the per-agent slot to the session id mid-compose. The
+ // editor keeps the typed text; the new draft slot is empty. Send must stay live.
+ it("keeps Send enabled when a lazy session create flips the draft key under a typed editor", async () => {
+ const state = useChatStore.getState() as unknown as {
+ activeSessionId: string | null;
+ inputDrafts: Record<string, string>;
+ };
+ state.activeSessionId = null;
+ state.inputDrafts = {};
+
+ const { rerender } = render(element({}));
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "typed before the session existed" } });
+ await waitFor(() => expect(sendButton()).not.toBeDisabled());
+
+ // ensureSession lands: draftKey flips to a slot the draft was never written to.
+ state.activeSessionId = "session-new";
+ rerender(element({}));
+
+ expect(sendButton()).not.toBeDisabled();
+ });
+});
+
+describe("ChatInput session-aware restore", () => {
it("holds a session-scoped restore until the user returns to the source session", async () => {
const state = useChatStore.getState() as unknown as {
activeSessionId: string | null;
@@ -578,15 +701,15 @@ describe("ChatInput session-aware restore", () => {
};
// User is viewing session-b; the failed send belongs to session-a.
state.activeSessionId = "session-b";
- const onRestoreDraftConsumed = vi.fn();
+ const onRestoreDraftApplied = vi.fn();
const props = {
restoreDraftRequest: { id: "r1", content: "from A", sessionId: "session-a" },
- onRestoreDraftConsumed,
+ onRestoreDraftApplied,
};
const { rerender } = render(element(props));
// Pending — must NOT dump A's content into session-b.
- expect(onRestoreDraftConsumed).not.toHaveBeenCalled();
+ expect(onRestoreDraftApplied).not.toHaveBeenCalled();
expect(state.setInputDraft).not.toHaveBeenCalledWith("session-b", "from A");
// User navigates back to the source session → the pending restore fires.
@@ -595,7 +718,7 @@ describe("ChatInput session-aware restore", () => {
await waitFor(() => {
expect(state.setInputDraft).toHaveBeenCalledWith("session-a", "from A");
- expect(onRestoreDraftConsumed).toHaveBeenCalledTimes(1);
+ expect(onRestoreDraftApplied).toHaveBeenCalledTimes(1);
});
});
@@ -605,17 +728,17 @@ describe("ChatInput session-aware restore", () => {
setInputDraft: ReturnType<typeof vi.fn>;
};
state.activeSessionId = "session-a";
- const onRestoreDraftConsumed = vi.fn();
+ const onRestoreDraftApplied = vi.fn();
render(
element({
restoreDraftRequest: { id: "r2", content: "hi A", sessionId: "session-a" },
- onRestoreDraftConsumed,
+ onRestoreDraftApplied,
}),
);
await waitFor(() => {
expect(state.setInputDraft).toHaveBeenCalledWith("session-a", "hi A");
- expect(onRestoreDraftConsumed).toHaveBeenCalledTimes(1);
+ expect(onRestoreDraftApplied).toHaveBeenCalledTimes(1);
});
});
});
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index 5d10a68342..799b0baeb2 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -60,7 +60,14 @@ interface ChatInputProps {
*/
sessionId?: string;
} | null;
- onRestoreDraftConsumed?: () => void;
+ /**
+ * Fired when — and only when — the restore's content/attachments were written
+ * into the draft. A restore the composer cannot apply yet (the user has work
+ * in progress) is NOT reported: it stays pending and lands as soon as the
+ * draft is clear. Owners holding a durable server-side restore (#5219) can
+ * therefore treat this as the single terminal transition and consume the row.
+ */
+ onRestoreDraftApplied?: () => void;
/** Receives a File and returns the attachment row (with id + CDN link).
* The wrapper owner (ChatWindow) lazy-creates a chat_session if needed
* and forwards `chatSessionId` to the upload — chat-input only cares
@@ -102,7 +109,7 @@ interface ChatInputProps {
export function ChatInput({
onSend,
restoreDraftRequest,
- onRestoreDraftConsumed,
+ onRestoreDraftApplied,
onUploadFile,
onStop,
isRunning,
@@ -161,7 +168,17 @@ export function ChatInput({
const clearInputDraft = useChatStore((s) => s.clearInputDraft);
const [isEmpty, setIsEmpty] = useState(!inputDraft.trim());
const [isSubmitting, setIsSubmitting] = useState(false);
- const consumedRestoreIdRef = useRef<string | null>(null);
+ // `isEmpty` tracks the LIVE editor, which the persisted draft lags by a
+ // debounce, so the send affordance cannot be derived from `inputDraft` alone.
+ // But `isEmpty` is never re-derived when the composer switches draft slots
+ // either: ChatInput does not remount on a session switch, and ContentEditor's
+ // defaultValue-sync pushes the incoming draft in with `emitUpdate: false`, so
+ // no onUpdate fires. Read BOTH signals — a draft `isEmpty` has not seen yet (a
+ // restored or parked one, or any persisted draft the user typed in another
+ // session) still enables the button. A false enable costs nothing: handleSend
+ // reads the live editor and bails when it is empty.
+ const hasNothingToSend = isEmpty && !inputDraft.trim();
+ const appliedRestoreIdRef = useRef<string | null>(null);
const editorKey = editorKeyOverride ?? selectedAgentId ?? "no-agent";
// Number of in-flight uploads. We track this explicitly (rather than
// peeking at the editor on every render) so the SubmitButton visibly
@@ -196,10 +213,10 @@ export function ChatInput({
useEffect(() => {
if (!restoreDraftRequest) {
- consumedRestoreIdRef.current = null;
+ appliedRestoreIdRef.current = null;
return;
}
- if (consumedRestoreIdRef.current === restoreDraftRequest.id) return;
+ if (appliedRestoreIdRef.current === restoreDraftRequest.id) return;
// Session-scoped restore: if this draft belongs to a specific session,
// wait until the user is actually viewing it. A fire-and-forget send that
// failed after the user navigated away must not dump its content into the
@@ -208,23 +225,29 @@ export function ChatInput({
if (restoreDraftRequest.sessionId && restoreDraftRequest.sessionId !== draftKey) {
return;
}
- consumedRestoreIdRef.current = restoreDraftRequest.id;
- if (inputDraft.trim()) {
- logger.info("input.restore skipped: draft already has content", {
+ // A draft with text OR staged attachments is user work in progress — never
+ // overwrite either with a restore (the attachment write below replaces the
+ // whole staged list). This is a WAIT, not a decision: the request stays
+ // pending and this effect re-runs on every draft change, so the restore
+ // lands as soon as the user sends or clears what they were typing. Marking
+ // it done here would strand it for the rest of this composer's life.
+ if (inputDraft.trim() || draftAttachments.length > 0) {
+ logger.debug("input.restore waiting: draft has content", {
draftKey,
restoreId: restoreDraftRequest.id,
});
- onRestoreDraftConsumed?.();
return;
}
+ appliedRestoreIdRef.current = restoreDraftRequest.id;
setInputDraft(draftKey, restoreDraftRequest.content);
setInputDraftAttachments(draftKey, restoreDraftRequest.attachments ?? []);
setIsEmpty(!restoreDraftRequest.content.trim());
- onRestoreDraftConsumed?.();
+ onRestoreDraftApplied?.();
}, [
draftKey,
inputDraft,
- onRestoreDraftConsumed,
+ draftAttachments,
+ onRestoreDraftApplied,
restoreDraftRequest,
setInputDraft,
setInputDraftAttachments,
@@ -432,7 +455,7 @@ export function ChatInput({
<div className="absolute bottom-1 right-1.5 flex items-center gap-1">
<SubmitButton
onClick={handleSend}
- disabled={isEmpty || isSubmitting || !!disabled || !!noAgent || pendingUploads > 0}
+ disabled={hasNothingToSend || isSubmitting || !!disabled || !!noAgent || pendingUploads > 0}
loading={isSubmitting}
running={isRunning}
onStop={onStop}
diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsx
index c20d3e1380..d83bda5395 100644
--- a/packages/views/chat/components/chat-thread-list.tsx
+++ b/packages/views/chat/components/chat-thread-list.tsx
@@ -28,7 +28,7 @@ import { useChatStore } from "@multica/core/chat";
import type { Agent, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
import { ActorAvatar } from "../../common/actor-avatar";
import { createLogger } from "@multica/core/logger";
-import { removeChatMessageFromCaches } from "./use-chat-controller";
+import { removeChatMessageFromCaches } from "@multica/core/realtime";
import { useT } from "../../i18n";
const apiLogger = createLogger("chat.api");
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index c53e9ecba4..4eac31a61f 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -47,6 +47,8 @@ import {
useUpdateChatSession,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
+import { removeChatMessageFromCaches } from "@multica/core/realtime";
+import { useChatDraftRestore } from "./use-chat-draft-restore";
import { ChatMessageList, ChatMessageSkeleton } from "./chat-message-list";
import { ChatInput } from "./chat-input";
import { ChatResizeHandles } from "./chat-resize-handles";
@@ -93,38 +95,6 @@ function appendChatMessageToLatestPageCache(
);
}
-function removeChatMessageFromPageCache(
- qc: ReturnType<typeof useQueryClient>,
- sessionId: string,
- messageId: string,
-) {
- qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
- chatKeys.messagesPage(sessionId),
- (old) => {
- if (!old) return old;
- return {
- ...old,
- pages: old.pages.map((page) => ({
- ...page,
- messages: page.messages.filter((m) => m.id !== messageId),
- })),
- };
- },
- );
-}
-
-function removeChatMessageFromCaches(
- qc: ReturnType<typeof useQueryClient>,
- sessionId: string,
- messageId: string,
-) {
- qc.setQueryData<ChatMessage[]>(
- chatKeys.messages(sessionId),
- (old) => old?.filter((m) => m.id !== messageId) ?? old,
- );
- removeChatMessageFromPageCache(qc, sessionId, messageId);
-}
-
function replaceOptimisticChatMessageId(
qc: ReturnType<typeof useQueryClient>,
sessionId: string,
@@ -212,15 +182,20 @@ export function ChatWindow() {
);
const pendingTaskId = pendingTask?.task_id ?? null;
const stopRequestedBeforeTaskRef = useRef(false);
- const [restoreDraftRequest, setRestoreDraftRequest] = useState<{
- id: string;
- content: string;
- attachments?: Attachment[];
- sessionId?: string;
- } | null>(null);
- const handleRestoreDraftConsumed = useCallback(() => {
- setRestoreDraftRequest(null);
- }, []);
+ // Durable deferred-cancellation draft restores (#5219). Same hook as the chat
+ // page controller — the skip/apply/consume/reconcile state machine must not
+ // diverge between the two composers.
+ //
+ // Gated on isOpen AND app foreground: this window stays MOUNTED when closed
+ // (it is only hidden, see isVisible below), and isOpen alone is also true for a
+ // backgrounded browser tab. Its ChatInput would otherwise adopt and consume a
+ // restore with nobody looking at it — stealing the prompt from the composer the
+ // user is actually waiting on, possibly on another device. Only a composer the
+ // user can actually see claims; a re-foregrounded window recovers on its next
+ // fetch. (appForeground also gates auto mark-read below.)
+ const appForeground = useAppForeground();
+ const { restoreDraftRequest, enqueueLocalRestore, handleRestoreDraftApplied } =
+ useChatDraftRestore(activeSessionId, isOpen && appForeground);
// Nonce handed to ChatInput to pull focus into the compose box when a new
// chat starts (⊕ or switching agent). 0 is inert so opening the window on an
// existing session never steals focus.
@@ -333,7 +308,6 @@ export function ChatWindow() {
// assumption: a reply landing while the window is open but the app is
// backgrounded must stay unread so the sidebar badges it (MUL-4485), then
// clears when the user refocuses and this effect re-runs.
- const appForeground = useAppForeground();
const currentHasUnread =
sessions.find((s) => s.id === activeSessionId)?.has_unread ?? false;
useEffect(() => {
@@ -436,7 +410,7 @@ export function ChatWindow() {
if (restored?.restore_to_input) {
removeChatMessageFromCaches(qc, restored.chat_session_id, restored.message_id);
if (options.restoreDraftToInput && restored.chat_session_id === sessionId) {
- setRestoreDraftRequest({
+ enqueueLocalRestore({
id: restored.message_id,
content: restored.content,
attachments: restored.attachments,
@@ -463,7 +437,7 @@ export function ChatWindow() {
return null;
}
},
- [qc],
+ [qc, enqueueLocalRestore],
);
const handleSend = useCallback(
@@ -575,13 +549,14 @@ export function ChatWindow() {
stopRequestedBeforeTaskRef.current = false;
removeChatMessageFromCaches(qc, sessionId, optimistic.id);
qc.setQueryData(chatKeys.pendingTask(sessionId), {});
- setRestoreDraftRequest({
+ enqueueLocalRestore({
id: `send-failed-${optimistic.id}`,
content: finalContent,
attachments: draftAttachments,
- // Restore into the session this was sent from. If the user
- // navigated away (fire-and-forget) the request waits until they
- // return rather than dumping content into another session.
+ // Restore into the session this was sent from. If the user navigated
+ // away (fire-and-forget) the request waits in that session's persisted
+ // queue until they return, rather than dumping content into another
+ // session or dying with this component.
sessionId,
});
toast.error(t(($) => $.input.send_failed_toast));
@@ -638,6 +613,7 @@ export function ChatWindow() {
cancelChatTask,
qc,
setActiveSession,
+ enqueueLocalRestore,
t,
],
);
@@ -862,7 +838,7 @@ export function ChatWindow() {
<ChatInput
onSend={handleSend}
restoreDraftRequest={restoreDraftRequest}
- onRestoreDraftConsumed={handleRestoreDraftConsumed}
+ onRestoreDraftApplied={handleRestoreDraftApplied}
onUploadFile={handleUploadFile}
onStop={handleStop}
isRunning={!!pendingTaskId}
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index 27e39dc84e..e6daf6a846 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -2,6 +2,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
import type { Agent, ChatSession } from "@multica/core/types";
+interface QueuedRestore {
+ id: string;
+ content: string;
+ attachments?: unknown[];
+ sessionId: string;
+}
+
// --- Shared mutable state (hoisted so vi.mock factories can reach it) --------
const h = vi.hoisted(() => {
const store = {
@@ -13,6 +20,34 @@ const h = vi.hoisted(() => {
setSelectedAgentId: vi.fn((id: string | null) => {
store.selectedAgentId = id;
}),
+ appliedDraftRestoreIds: [] as string[],
+ markDraftRestoreApplied: vi.fn((id: string) => {
+ if (!store.appliedDraftRestoreIds.includes(id)) {
+ store.appliedDraftRestoreIds = [...store.appliedDraftRestoreIds, id];
+ }
+ }),
+ forgetDraftRestoreApplied: vi.fn((id: string) => {
+ store.appliedDraftRestoreIds = store.appliedDraftRestoreIds.filter((x) => x !== id);
+ }),
+ // Server-less restores (a failed send, a synchronous cancel) queue per session
+ // and are persisted; the shared slot never holds one for another session.
+ pendingSendRestores: {} as Record<string, QueuedRestore[]>,
+ enqueuePendingSendRestore: vi.fn((r: QueuedRestore) => {
+ const existing = store.pendingSendRestores[r.sessionId] ?? [];
+ if (existing.some((q) => q.id === r.id)) return;
+ store.pendingSendRestores = {
+ ...store.pendingSendRestores,
+ [r.sessionId]: [...existing, r],
+ };
+ }),
+ dequeuePendingSendRestore: vi.fn((sessionId: string, restoreId: string) => {
+ const existing = store.pendingSendRestores[sessionId] ?? [];
+ const remaining = existing.filter((q) => q.id !== restoreId);
+ const next = { ...store.pendingSendRestores };
+ if (remaining.length > 0) next[sessionId] = remaining;
+ else delete next[sessionId];
+ store.pendingSendRestores = next;
+ }),
};
return {
store,
@@ -20,9 +55,14 @@ const h = vi.hoisted(() => {
markReadMutate: vi.fn(),
// Foreground gate for the auto mark-read effect; tests flip it.
appForeground: { value: true },
+ consumeRestoreMutate: vi.fn(),
+ removeFromCaches: vi.fn(),
// useQuery reads these so each test can vary the loaded data.
sessions: [] as ChatSession[],
agents: [] as Agent[],
+ draftRestores: null as
+ | { restores: { id: string; chat_session_id: string; content: string }[] }
+ | null,
};
});
@@ -50,6 +90,7 @@ vi.mock("@multica/core/chat/mutations", () => ({
useCreateChatSession: () => ({ mutateAsync: vi.fn() }),
useMarkChatSessionRead: () => ({ mutate: h.markReadMutate }),
useSetChatSessionArchived: () => ({ mutate: h.archivedMutate }),
+ useConsumeChatDraftRestore: () => ({ mutate: h.consumeRestoreMutate }),
}));
vi.mock("../../common/use-app-foreground", () => ({
useAppForeground: () => h.appForeground.value,
@@ -60,6 +101,9 @@ vi.mock("@multica/core/chat", () => ({
{ getState: () => h.store },
),
}));
+vi.mock("@multica/core/realtime", () => ({
+ removeChatMessageFromCaches: h.removeFromCaches,
+}));
vi.mock("@multica/core/logger", () => ({
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
}));
@@ -77,6 +121,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {
return { data: [{ user_id: "user-1", role: "admin" }] };
}
if (key.includes("sessions")) return { data: h.sessions, isSuccess: true };
+ if (key.includes("draft-restores")) return { data: h.draftRestores };
return { data: null };
},
useInfiniteQuery: () => ({
@@ -305,3 +350,119 @@ describe("useChatController auto mark-read — foreground gating (MUL-4485)", ()
expect(h.markReadMutate).toHaveBeenCalledWith("sU");
});
});
+
+describe("useChatController durable draft restores (#5219)", () => {
+ beforeEach(() => {
+ h.draftRestores = null;
+ h.consumeRestoreMutate.mockClear();
+ h.removeFromCaches.mockClear();
+ h.store.appliedDraftRestoreIds = [];
+ h.store.markDraftRestoreApplied.mockClear();
+ h.store.forgetDraftRestoreApplied.mockClear();
+ h.store.pendingSendRestores = {};
+ h.store.enqueuePendingSendRestore.mockClear();
+ h.store.dequeuePendingSendRestore.mockClear();
+ h.appForeground.value = true;
+ });
+
+ // The reconnect/offline recovery path: no chat:cancel_finalized event was
+ // seen — the restore arrives purely through the draft-restores query on
+ // composer mount, is handed to the composer, and is consumed server-side
+ // only after the composer reports the hand-off complete.
+ it("hands a fetched restore to the composer and consumes it after the hand-off", () => {
+ h.draftRestores = {
+ restores: [{ id: "msg-1", chat_session_id: "sA", content: "run the thing" }],
+ };
+ const result = setup("sA", [sA, sB, sC], [agentA, agentB]);
+
+ expect(result.current.restoreDraftRequest).toEqual({
+ id: "msg-1",
+ content: "run the thing",
+ attachments: undefined,
+ sessionId: "sA",
+ serverRestoreId: "msg-1",
+ });
+ // The deleted bubble may still be cached when the event was missed.
+ expect(h.removeFromCaches).toHaveBeenCalledWith(expect.anything(), "sA", "msg-1");
+ // Not yet consumed: the draft isn't persisted client-side until the
+ // composer takes it.
+ expect(h.consumeRestoreMutate).not.toHaveBeenCalled();
+
+ act(() => {
+ result.current.handleRestoreDraftApplied();
+ });
+
+ // The ledger entry is written BEFORE the request goes out: a consume that
+ // never lands must not let this restore be offered (and re-sent) again.
+ expect(h.store.markDraftRestoreApplied).toHaveBeenCalledWith("msg-1");
+ expect(h.consumeRestoreMutate).toHaveBeenCalledWith(
+ { sessionId: "sA", restoreId: "msg-1" },
+ expect.anything(),
+ );
+ expect(result.current.restoreDraftRequest).toBeNull();
+ });
+
+ // The lost-consume case (#5219 review): the DELETE never reached the server,
+ // so the row comes back on the next fetch — but it was already applied, and
+ // the user may have sent it. It must be reconciled (consumed again), never
+ // re-offered to the composer.
+ it("reconciles a row whose consume was lost instead of re-offering it", () => {
+ h.store.appliedDraftRestoreIds = ["msg-1"];
+ h.draftRestores = {
+ restores: [{ id: "msg-1", chat_session_id: "sA", content: "run the thing" }],
+ };
+ const result = setup("sA", [sA, sB, sC], [agentA, agentB]);
+
+ expect(result.current.restoreDraftRequest).toBeNull();
+ expect(h.consumeRestoreMutate).toHaveBeenCalledWith(
+ { sessionId: "sA", restoreId: "msg-1" },
+ expect.anything(),
+ );
+ });
+
+ it("leaves a restore belonging to another session pending", () => {
+ h.draftRestores = {
+ restores: [{ id: "msg-2", chat_session_id: "sB", content: "other session draft" }],
+ };
+ const result = setup("sA", [sA, sB, sC], [agentA, agentB]);
+
+ expect(result.current.restoreDraftRequest).toBeNull();
+ expect(h.consumeRestoreMutate).not.toHaveBeenCalled();
+ });
+
+ // A backgrounded browser tab still renders this controller. It must not claim a
+ // restore the user is waiting on in a foreground surface — the same silent-theft
+ // hazard the hidden chat window guards against, reached here through the app
+ // foreground gate rather than isOpen.
+ it("does NOT offer or consume a restore while the app is backgrounded", () => {
+ h.appForeground.value = false;
+ h.draftRestores = {
+ restores: [{ id: "msg-1", chat_session_id: "sA", content: "run the thing" }],
+ };
+ const result = setup("sA", [sA, sB, sC], [agentA, agentB]);
+
+ expect(result.current.restoreDraftRequest).toBeNull();
+ expect(h.consumeRestoreMutate).not.toHaveBeenCalled();
+ });
+
+ it("offers the restore once the surface returns to the foreground", () => {
+ h.appForeground.value = false;
+ h.draftRestores = {
+ restores: [{ id: "msg-1", chat_session_id: "sA", content: "run the thing" }],
+ };
+ h.store.activeSessionId = "sA";
+ h.store.selectedAgentId = null;
+ h.sessions = [sA, sB, sC];
+ h.agents = [agentA, agentB];
+ const { result, rerender } = renderHook(() => useChatController());
+
+ expect(result.current.restoreDraftRequest).toBeNull();
+
+ act(() => {
+ h.appForeground.value = true;
+ rerender();
+ });
+
+ expect(result.current.restoreDraftRequest?.serverRestoreId).toBe("msg-1");
+ });
+});
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index e605b05af2..5c19dc17d9 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -29,6 +29,8 @@ import {
useSetChatSessionArchived,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
+import { removeChatMessageFromCaches } from "@multica/core/realtime";
+import { useChatDraftRestore } from "./use-chat-draft-restore";
import { createLogger } from "@multica/core/logger";
import type {
Agent,
@@ -117,38 +119,6 @@ function appendChatMessageToLatestPageCache(
);
}
-function removeChatMessageFromPageCache(
- qc: ReturnType<typeof useQueryClient>,
- sessionId: string,
- messageId: string,
-) {
- qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
- chatKeys.messagesPage(sessionId),
- (old) => {
- if (!old) return old;
- return {
- ...old,
- pages: old.pages.map((page) => ({
- ...page,
- messages: page.messages.filter((m) => m.id !== messageId),
- })),
- };
- },
- );
-}
-
-export function removeChatMessageFromCaches(
- qc: ReturnType<typeof useQueryClient>,
- sessionId: string,
- messageId: string,
-) {
- qc.setQueryData<ChatMessage[]>(
- chatKeys.messages(sessionId),
- (old) => old?.filter((m) => m.id !== messageId) ?? old,
- );
- removeChatMessageFromPageCache(qc, sessionId, messageId);
-}
-
function replaceOptimisticChatMessageId(
qc: ReturnType<typeof useQueryClient>,
sessionId: string,
@@ -237,15 +207,18 @@ export function useChatController(opts?: { isActive?: boolean }) {
);
const pendingTaskId = pendingTask?.task_id ?? null;
const stopRequestedBeforeTaskRef = useRef(false);
- const [restoreDraftRequest, setRestoreDraftRequest] = useState<{
- id: string;
- content: string;
- attachments?: Attachment[];
- sessionId?: string;
- } | null>(null);
- const handleRestoreDraftConsumed = useCallback(() => {
- setRestoreDraftRequest(null);
- }, []);
+ // Durable deferred-cancellation draft restores (#5219). The whole lifecycle —
+ // fetch, offer, skip-and-re-offer, apply, consume, reconcile — lives in this
+ // hook, shared with the floating chat window.
+ //
+ // Gated on isActive AND app foreground: a backgrounded browser tab still renders
+ // this controller, and it must not fetch/apply/consume a restore the user is
+ // waiting on in a foreground surface. It recovers on its next fetch once the
+ // surface is on screen and the app is refocused. (appForeground also gates auto
+ // mark-read below.)
+ const appForeground = useAppForeground();
+ const { restoreDraftRequest, enqueueLocalRestore, handleRestoreDraftApplied } =
+ useChatDraftRestore(activeSessionId, isActive && appForeground);
// Nonce handed to ChatInput to pull focus into the compose box when a new
// chat starts. Bumped by handleNewChat / handleStartNewChat only, so
// selecting an existing chat or a deep link never steals focus.
@@ -325,7 +298,6 @@ export function useChatController(opts?: { isActive?: boolean }) {
// read via cleanup; the store re-check is a belt-and-suspenders guard. Only a
// session that stays active past the tick — a real select, deep link, or
// refresh — is read.
- const appForeground = useAppForeground();
const currentHasUnread =
sessions.find((s) => s.id === activeSessionId)?.has_unread ?? false;
useEffect(() => {
@@ -421,7 +393,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
if (restored?.restore_to_input) {
removeChatMessageFromCaches(qc, restored.chat_session_id, restored.message_id);
if (options.restoreDraftToInput && restored.chat_session_id === sessionId) {
- setRestoreDraftRequest({
+ enqueueLocalRestore({
id: restored.message_id,
content: restored.content,
attachments: restored.attachments,
@@ -448,7 +420,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
return null;
}
},
- [qc],
+ [qc, enqueueLocalRestore],
);
const handleSend = useCallback(
@@ -535,7 +507,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
stopRequestedBeforeTaskRef.current = false;
removeChatMessageFromCaches(qc, sessionId, optimistic.id);
qc.setQueryData(chatKeys.pendingTask(sessionId), {});
- setRestoreDraftRequest({
+ enqueueLocalRestore({
id: `send-failed-${optimistic.id}`,
content: finalContent,
attachments: draftAttachments,
@@ -588,6 +560,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
cancelChatTask,
qc,
setActiveSession,
+ enqueueLocalRestore,
t,
],
);
@@ -711,7 +684,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
fetchOlderMessages,
// draft restore
restoreDraftRequest,
- handleRestoreDraftConsumed,
+ handleRestoreDraftApplied,
// compose-box focus nonce (bumped on new chat)
focusInputRequest,
// actions
diff --git a/packages/views/chat/components/use-chat-draft-restore.test.tsx b/packages/views/chat/components/use-chat-draft-restore.test.tsx
new file mode 100644
index 0000000000..0015a5dcaa
--- /dev/null
+++ b/packages/views/chat/components/use-chat-draft-restore.test.tsx
@@ -0,0 +1,276 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+
+// --- Mocks ------------------------------------------------------------------
+interface QueuedRestore {
+ id: string;
+ content: string;
+ attachments?: unknown[];
+ sessionId: string;
+}
+
+const h = vi.hoisted(() => {
+ const store = {
+ appliedDraftRestoreIds: [] as string[],
+ markDraftRestoreApplied: vi.fn(),
+ forgetDraftRestoreApplied: vi.fn(),
+ inputDrafts: {} as Record<string, string>,
+ inputDraftAttachments: {} as Record<string, unknown[]>,
+ setInputDraft: vi.fn(),
+ setInputDraftAttachments: vi.fn(),
+ // The persisted per-session queue, modelled faithfully: a new object on every
+ // write so the hook's selector sees a fresh reference, and the contents
+ // outlive an unmount exactly as the real (storage-backed) store does.
+ pendingSendRestores: {} as Record<string, QueuedRestore[]>,
+ enqueuePendingSendRestore: vi.fn((r: QueuedRestore) => {
+ const existing = store.pendingSendRestores[r.sessionId] ?? [];
+ if (existing.some((q) => q.id === r.id)) return;
+ store.pendingSendRestores = {
+ ...store.pendingSendRestores,
+ [r.sessionId]: [...existing, r],
+ };
+ }),
+ dequeuePendingSendRestore: vi.fn((sessionId: string, restoreId: string) => {
+ const existing = store.pendingSendRestores[sessionId] ?? [];
+ const remaining = existing.filter((q) => q.id !== restoreId);
+ const next = { ...store.pendingSendRestores };
+ if (remaining.length > 0) next[sessionId] = remaining;
+ else delete next[sessionId];
+ store.pendingSendRestores = next;
+ }),
+ };
+ return {
+ listChatDraftRestores: vi.fn(),
+ consumeChatDraftRestore: vi.fn(),
+ store,
+ };
+});
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ listChatDraftRestores: h.listChatDraftRestores,
+ consumeChatDraftRestore: h.consumeChatDraftRestore,
+ },
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: Object.assign(
+ (sel: (s: typeof h.store) => unknown) => sel(h.store),
+ { getState: () => h.store },
+ ),
+}));
+vi.mock("@multica/core/realtime", () => ({ removeChatMessageFromCaches: vi.fn() }));
+vi.mock("@multica/core/logger", () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+}));
+
+import type { Attachment } from "@multica/core/types";
+import { useChatDraftRestore } from "./use-chat-draft-restore";
+
+function wrapper({ children }: { children: ReactNode }) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+}
+
+const RESTORE = { id: "msg-1", chat_session_id: "sA", content: "run the thing" };
+
+beforeEach(() => {
+ h.listChatDraftRestores.mockReset().mockResolvedValue({ restores: [RESTORE] });
+ h.consumeChatDraftRestore.mockReset().mockResolvedValue(undefined);
+ h.store.appliedDraftRestoreIds = [];
+ h.store.markDraftRestoreApplied.mockReset();
+ h.store.forgetDraftRestoreApplied.mockReset();
+ h.store.inputDrafts = {};
+ h.store.inputDraftAttachments = {};
+ h.store.setInputDraft.mockReset();
+ h.store.setInputDraftAttachments.mockReset();
+ h.store.pendingSendRestores = {};
+ h.store.enqueuePendingSendRestore.mockClear();
+ h.store.dequeuePendingSendRestore.mockClear();
+});
+
+// The restore is user-scoped — every client of the creator can see it, and the
+// first to apply consumes it. That is only safe if the composers that can claim
+// are the ones the user can actually SEE: a chat window stays mounted while
+// closed, and a background claim would consume the row out from under the
+// composer the user is waiting on (here, or on their other device).
+describe("useChatDraftRestore ownership (#5219)", () => {
+ it("does not fetch, offer, or consume from a composer the user cannot see", async () => {
+ const { result } = renderHook(() => useChatDraftRestore("sA", false), { wrapper });
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(h.listChatDraftRestores).not.toHaveBeenCalled();
+ expect(result.current.restoreDraftRequest).toBeNull();
+ expect(h.consumeChatDraftRestore).not.toHaveBeenCalled();
+ });
+
+ // Two clients on the same session, one visible and one hidden: only the
+ // visible one may take the prompt.
+ it("lets the visible composer win the race against a hidden one", async () => {
+ const hidden = renderHook(() => useChatDraftRestore("sA", false), { wrapper });
+ const visible = renderHook(() => useChatDraftRestore("sA", true), { wrapper });
+
+ await waitFor(() => expect(visible.result.current.restoreDraftRequest).not.toBeNull());
+ expect(hidden.result.current.restoreDraftRequest).toBeNull();
+
+ act(() => visible.result.current.handleRestoreDraftApplied());
+
+ // Recorded before the request goes out, and consumed exactly once — by the
+ // client the user was looking at.
+ expect(h.store.markDraftRestoreApplied).toHaveBeenCalledWith("msg-1");
+ await waitFor(() => expect(h.consumeChatDraftRestore).toHaveBeenCalledTimes(1));
+ expect(h.consumeChatDraftRestore).toHaveBeenCalledWith("sA", "msg-1");
+ });
+
+ it("drops an unclaimed offer when the composer is hidden mid-flight", async () => {
+ const { result, rerender } = renderHook(
+ ({ open }: { open: boolean }) => useChatDraftRestore("sA", open),
+ { wrapper, initialProps: { open: true } },
+ );
+
+ await waitFor(() => expect(result.current.restoreDraftRequest).not.toBeNull());
+
+ rerender({ open: false });
+
+ // Never applied → never in the ledger → the server row survives for whichever
+ // composer the user opens next.
+ expect(result.current.restoreDraftRequest).toBeNull();
+ expect(h.store.markDraftRestoreApplied).not.toHaveBeenCalled();
+ expect(h.consumeChatDraftRestore).not.toHaveBeenCalled();
+ });
+});
+
+// ChatInput treats a restore it cannot apply as a WAIT, so a request whose target
+// session the user never returns to would hold the composer's single restore slot
+// forever — starving every durable hand-off for the session they ARE looking at.
+// And a server-less restore (a failed send) has no server copy: parking it in that
+// component-local slot also loses its text on unmount. Both are why server-less
+// restores live in a PERSISTED per-session queue, and the slot only ever holds a
+// request for the session on screen.
+describe("useChatDraftRestore server-less restore queue (#5219)", () => {
+ const sendFailure = (sessionId: string) => ({
+ id: "send-failed-1",
+ content: "the text that failed to send",
+ attachments: [{ id: "att-1" } as Attachment],
+ sessionId,
+ });
+
+ it("queues a restore for a session the user is not looking at, leaving the active session's durable restore free to land", async () => {
+ const { result, rerender } = renderHook(() => useChatDraftRestore("sA", true), { wrapper });
+
+ // The send failed on sB while the user is looking at sA.
+ act(() => result.current.enqueueLocalRestore(sendFailure("sB")));
+ rerender();
+
+ // It is persisted against its own session — not parked in the shared slot, and
+ // not dumped into sB's draft (which the user may be using).
+ expect(h.store.pendingSendRestores.sB).toEqual([sendFailure("sB")]);
+ expect(h.store.setInputDraft).not.toHaveBeenCalled();
+
+ // And sA's durable restore is offered rather than starved.
+ await waitFor(() => expect(result.current.restoreDraftRequest?.serverRestoreId).toBe("msg-1"));
+ });
+
+ // The review's case: the source session's draft slot is occupied, the session on
+ // screen has a durable restore, and the composer unmounts. Neither restore may be
+ // lost, and neither may block the other.
+ it("survives an unmount and is re-offered when the user returns, even with work in progress there", async () => {
+ h.store.inputDrafts = { sB: "work in progress" };
+
+ const first = renderHook(() => useChatDraftRestore("sA", true), { wrapper });
+ act(() => first.result.current.enqueueLocalRestore(sendFailure("sB")));
+ first.rerender();
+
+ // sA is not wedged: its durable restore lands despite sB's pending request.
+ await waitFor(() =>
+ expect(first.result.current.restoreDraftRequest?.serverRestoreId).toBe("msg-1"),
+ );
+
+ // The composer goes away before either is applied.
+ first.unmount();
+
+ // The queue is storage-backed, so the failed text is still there — and the user
+ // returning to sB is offered it, even though sB's draft has their own work in
+ // it (ChatInput then waits for that draft to clear rather than overwrite it).
+ expect(h.store.pendingSendRestores.sB).toEqual([sendFailure("sB")]);
+
+ const second = renderHook(() => useChatDraftRestore("sB", true), { wrapper });
+ await waitFor(() => expect(second.result.current.restoreDraftRequest?.id).toBe("send-failed-1"));
+ expect(second.result.current.restoreDraftRequest?.sessionId).toBe("sB");
+ // Still queued: offered is not applied, and only an applied restore is safe to drop.
+ expect(h.store.pendingSendRestores.sB).toHaveLength(1);
+ });
+
+ it("leaves the queue entry alone until the composer reports the hand-off, then drops it", async () => {
+ const { result, rerender } = renderHook(() => useChatDraftRestore("sB", true), { wrapper });
+
+ act(() => result.current.enqueueLocalRestore(sendFailure("sB")));
+ rerender();
+
+ await waitFor(() => expect(result.current.restoreDraftRequest?.id).toBe("send-failed-1"));
+ expect(h.store.dequeuePendingSendRestore).not.toHaveBeenCalled();
+
+ act(() => result.current.handleRestoreDraftApplied());
+
+ // The text now lives in the persisted draft, so the queue entry has nothing
+ // left to protect. No server row exists, so nothing is consumed.
+ expect(h.store.dequeuePendingSendRestore).toHaveBeenCalledWith("sB", "send-failed-1");
+ expect(h.store.pendingSendRestores.sB).toBeUndefined();
+ expect(h.consumeChatDraftRestore).not.toHaveBeenCalled();
+ expect(result.current.restoreDraftRequest).toBeNull();
+ });
+
+ it("drops — never parks — a durable restore once the user navigates away from its session", async () => {
+ const { result, rerender } = renderHook(
+ ({ session }: { session: string }) => useChatDraftRestore(session, true),
+ { wrapper, initialProps: { session: "sA" } },
+ );
+
+ await waitFor(() => expect(result.current.restoreDraftRequest?.serverRestoreId).toBe("msg-1"));
+
+ // The user moves to another session before the composer took it.
+ rerender({ session: "sB" });
+
+ // It has a server copy: dropping loses nothing and the next fetch re-offers it.
+ // Holding it would starve whatever sB has waiting.
+ await waitFor(() => expect(result.current.restoreDraftRequest).toBeNull());
+ expect(h.store.markDraftRestoreApplied).not.toHaveBeenCalled();
+ expect(h.consumeChatDraftRestore).not.toHaveBeenCalled();
+ });
+});
+
+// A consume whose retries all ran out must not wedge: the row is still on the
+// server and still in the ledger, so the NEXT fetch has to try again. Holding
+// the id in the in-flight set forever would strand it until a full remount.
+describe("useChatDraftRestore reconciliation (#5219)", () => {
+ it("re-consumes a row on the next fetch after the consume failed", async () => {
+ h.store.appliedDraftRestoreIds = ["msg-1"];
+ h.consumeChatDraftRestore.mockRejectedValueOnce(new Error("offline"));
+
+ const { result, rerender } = renderHook(
+ ({ session }: { session: string }) => useChatDraftRestore(session, true),
+ { wrapper, initialProps: { session: "sA" } },
+ );
+
+ // Already applied on this device: reconciled, never re-offered.
+ await waitFor(() => expect(h.consumeChatDraftRestore).toHaveBeenCalledTimes(1));
+ expect(result.current.restoreDraftRequest).toBeNull();
+ expect(h.store.forgetDraftRestoreApplied).not.toHaveBeenCalled();
+
+ // The row is still there on the next fetch — try again, and only now is the
+ // ledger entry safe to drop.
+ rerender({ session: "sB" });
+ rerender({ session: "sA" });
+
+ await waitFor(() => expect(h.consumeChatDraftRestore).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(h.store.forgetDraftRestoreApplied).toHaveBeenCalledWith("msg-1"));
+ expect(result.current.restoreDraftRequest).toBeNull();
+ });
+});
diff --git a/packages/views/chat/components/use-chat-draft-restore.ts b/packages/views/chat/components/use-chat-draft-restore.ts
new file mode 100644
index 0000000000..2dec44362b
--- /dev/null
+++ b/packages/views/chat/components/use-chat-draft-restore.ts
@@ -0,0 +1,246 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { chatDraftRestoresOptions } from "@multica/core/chat/queries";
+import { useConsumeChatDraftRestore } from "@multica/core/chat/mutations";
+import { useChatStore } from "@multica/core/chat";
+import { removeChatMessageFromCaches } from "@multica/core/realtime";
+import type { Attachment } from "@multica/core/types";
+
+/**
+ * A draft the composer is asked to adopt. Two sources feed it:
+ * - a failed send, restoring the user's own text (no `serverRestoreId`);
+ * - a durable deferred-cancellation restore (#5219), which has a server row.
+ */
+export interface RestoreDraftRequest {
+ id: string;
+ content: string;
+ attachments?: Attachment[];
+ /**
+ * Draft slot this restore targets. The composer only applies it while the
+ * user is viewing that session, so a restore never lands in the wrong chat.
+ */
+ sessionId?: string;
+ /** Set for durable restores: the row to delete once the draft is applied. */
+ serverRestoreId?: string;
+}
+
+/**
+ * Owns the durable draft-restore lifecycle for one composer (#5219). Shared by
+ * the chat page controller and the floating chat window — the two entry points
+ * must not drift, because the state machine below is the only thing standing
+ * between a cancelled prompt and losing it.
+ *
+ * Two kinds of restore feed one composer, and they have different failure modes:
+ *
+ * - Durable (a deferred-cancellation row, #5219): the server holds the text, so
+ * an offer that is never taken can simply be dropped and refetched.
+ * - Server-less (a failed send, or a cancel that answered synchronously): the
+ * send already cleared the persisted draft, so this hook's queue is the ONLY
+ * copy of the user's text. It is therefore persisted per session
+ * (pendingSendRestores) from the moment it is created until the composer
+ * reports it applied — never parked in the shared slot, which is component
+ * state and dies with an unmount.
+ *
+ * The single `restoreDraftRequest` slot is only a view onto whichever of those
+ * the composer can act on RIGHT NOW: it never holds a request for a session
+ * other than the one on screen, so a restore for a session the user may never
+ * return to cannot starve the one they are looking at.
+ *
+ * The hand-off is at-most-once and lossless:
+ *
+ * - A restore is offered to the composer, which either applies it (empty draft)
+ * or leaves it alone (the user has work in progress). A skipped restore stays
+ * pending — ChatInput re-evaluates as the draft changes and applies it the
+ * moment the draft is clear. It is never marked done, never consumed, and the
+ * server row (or queue entry) survives.
+ * - Only an applied restore is recorded — in a *persisted* ledger, before the
+ * consume request goes out. A consume that is lost (offline, app closed, retries
+ * exhausted) therefore cannot cause the prompt to be restored a second time
+ * after the user has sent it; the ledger, not the server row, is what makes the
+ * offer at-most-once.
+ * - Any row that outlives its ledger entry is reconciled: the consume is fired
+ * again on every fetch until the row is gone, and the ledger entry is dropped
+ * only when the server confirms it.
+ *
+ * Ownership. The restore belongs to the *user*, not to a device: the endpoints
+ * are creator-authorized, so every client of theirs sees the row until one
+ * consumes it. `enabled` is what decides which composers may take it: a client
+ * only claims a restore into a composer the user can actually see. The cost of
+ * getting this wrong is not a duplicate draft — it is a silent theft, where a
+ * background composer applies (and consumes) the prompt the user is waiting for
+ * on the device in front of them, and the row is gone before they ever see it.
+ * A hidden composer must therefore never take part.
+ *
+ * Two *visible* composers on the same session, however, may both adopt it. That
+ * is a deliberate product decision, not an accident of the implementation:
+ *
+ * - What happens: both write the prompt into their own device-local draft. The
+ * consume DELETE is idempotent, so the first one to reach the server takes the
+ * row and the other's call is a no-op. Nothing is lost; the user sees the
+ * restored prompt on both screens and could send it twice.
+ * - Why we accept it: both composers being visible means the user is looking at
+ * one of them. A restored draft is not a sent message — it sits in the input
+ * until the user presses send — so the worst case is that they see their own
+ * prompt on their other open device and dismiss it there.
+ * - Why not fix it: eliminating it needs a server-side claim/lease keyed on
+ * client identity, taken *before* the local draft is written. That inverts the
+ * ordering this whole state machine is built on (apply first, then consume) and
+ * reopens the hole it exists to close: a client that wins the claim and then
+ * dies — offline, closed, crashed — has taken the row without ever putting the
+ * prompt anywhere, and the text is gone for good. Trading a recoverable
+ * duplicate for an unrecoverable loss is the wrong side of that bet, and a
+ * lease with an expiry to bound the loss buys the duplicate right back.
+ */
+export function useChatDraftRestore(activeSessionId: string | null, enabled = true) {
+ const qc = useQueryClient();
+ const [restoreDraftRequest, setRestoreDraftRequest] = useState<RestoreDraftRequest | null>(null);
+
+ const appliedRestoreIds = useChatStore((s) => s.appliedDraftRestoreIds);
+ const markDraftRestoreApplied = useChatStore((s) => s.markDraftRestoreApplied);
+ const forgetDraftRestoreApplied = useChatStore((s) => s.forgetDraftRestoreApplied);
+ const pendingSendRestores = useChatStore((s) => s.pendingSendRestores);
+ const enqueuePendingSendRestore = useChatStore((s) => s.enqueuePendingSendRestore);
+ const dequeuePendingSendRestore = useChatStore((s) => s.dequeuePendingSendRestore);
+ const consumeDraftRestore = useConsumeChatDraftRestore();
+
+ // The query refetches on composer mount and on network reconnect, and the
+ // initiator's realtime handler invalidates it when chat:cancel_finalized
+ // arrives — so a client that was offline across the broadcast still recovers
+ // the prompt here. Disabled composers do not even fetch: no offer, no claim.
+ const { data: draftRestoresData } = useQuery({
+ ...chatDraftRestoresOptions(activeSessionId ?? ""),
+ enabled: enabled && !!activeSessionId,
+ });
+ const restores = draftRestoresData?.restores;
+
+ // In-flight consumes, so a re-render or a second fetch doesn't fire a duplicate
+ // request for the same row. Released on settle — including on failure, which is
+ // what lets the next fetch reconcile a consume whose retries all ran out.
+ const reconcilingRef = useRef<Set<string>>(new Set());
+ const consume = useCallback(
+ (sessionId: string, restoreId: string) => {
+ reconcilingRef.current.add(restoreId);
+ consumeDraftRestore.mutate(
+ { sessionId, restoreId },
+ {
+ // The row is gone: the ledger entry has nothing left to protect against.
+ onSuccess: () => forgetDraftRestoreApplied(restoreId),
+ onSettled: () => reconcilingRef.current.delete(restoreId),
+ },
+ );
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mutation ref stable
+ [forgetDraftRestoreApplied],
+ );
+
+ // Reconcile rows whose consume never landed. Firing this from the fetched list
+ // (rather than only at apply time) is what closes the lost-consume hole: the
+ // row is re-consumed on the next mount, refetch or reconnect until it is gone.
+ useEffect(() => {
+ if (!enabled || !activeSessionId || !restores) return;
+ for (const r of restores) {
+ if (r.chat_session_id !== activeSessionId) continue;
+ if (!appliedRestoreIds.includes(r.id)) continue;
+ if (reconcilingRef.current.has(r.id)) continue;
+ consume(activeSessionId, r.id);
+ }
+ }, [restores, activeSessionId, appliedRestoreIds, consume, enabled]);
+
+ useEffect(() => {
+ if (!enabled) {
+ // The composer went away (window closed, tab backgrounded). Release the
+ // slot rather than hold an offer nobody can see: a durable request is
+ // refetched, a server-less one is still in its persisted queue. Nothing was
+ // applied, so nothing is lost, and the composer the user IS looking at —
+ // here or on another device — gets to claim it.
+ if (restoreDraftRequest) setRestoreDraftRequest(null);
+ return;
+ }
+ if (!activeSessionId) return;
+ if (restoreDraftRequest) {
+ // One rule for the single slot: it only ever holds a request for the
+ // session on screen. ChatInput treats a request it cannot apply as a WAIT,
+ // so one aimed at a session the user may never return to would otherwise
+ // starve every hand-off for the session they ARE looking at.
+ //
+ // Releasing it costs nothing either way: a durable request has a server row
+ // and is offered again on the next fetch; a server-less one is still in
+ // pendingSendRestores, queued against its own session, and is re-offered
+ // when the user comes back to it.
+ const { sessionId } = restoreDraftRequest;
+ if (!sessionId || sessionId === activeSessionId) return;
+ setRestoreDraftRequest(null);
+ return;
+ }
+ // Server-less restores go first. Both kinds are re-offered until applied, but
+ // this one is the user's own text with no copy anywhere else, so it is the
+ // one to get in front of them soonest. It stays in the queue until ChatInput
+ // reports the hand-off — a request that is merely offered can still be lost.
+ const queued = pendingSendRestores[activeSessionId]?.[0];
+ if (queued) {
+ setRestoreDraftRequest({
+ id: queued.id,
+ content: queued.content,
+ attachments: queued.attachments,
+ sessionId: activeSessionId,
+ });
+ return;
+ }
+ const restore = restores?.find(
+ (r) => r.chat_session_id === activeSessionId && !appliedRestoreIds.includes(r.id),
+ );
+ if (!restore) return;
+ // If this client missed the chat:cancel_finalized event, the deleted bubble
+ // may still sit in the message caches — drop it before restoring.
+ removeChatMessageFromCaches(qc, activeSessionId, restore.id);
+ setRestoreDraftRequest({
+ id: restore.id,
+ content: restore.content ?? "",
+ attachments: restore.attachments,
+ sessionId: activeSessionId,
+ serverRestoreId: restore.id,
+ });
+ }, [
+ restores,
+ activeSessionId,
+ restoreDraftRequest,
+ appliedRestoreIds,
+ pendingSendRestores,
+ qc,
+ enabled,
+ ]);
+
+ /**
+ * A restore with no server copy — a failed send, or a cancel that answered
+ * synchronously. It goes straight into the persisted per-session queue, never
+ * into the shared slot: its text exists nowhere else, so it has to survive an
+ * unmount, and it must not hold the slot hostage for a session the user is not
+ * looking at. The effect above hands it to the composer when they are.
+ */
+ const enqueueLocalRestore = useCallback(
+ (restore: { id: string; content: string; attachments?: Attachment[]; sessionId: string }) => {
+ enqueuePendingSendRestore(restore);
+ },
+ [enqueuePendingSendRestore],
+ );
+
+ /**
+ * The composer wrote the draft. This is the only terminal transition: for a
+ * durable restore, record it in the ledger before consuming; for a server-less
+ * one, drop the queue entry now that its text lives in the (persisted) draft.
+ * A skipped hand-off never reaches here.
+ */
+ const handleRestoreDraftApplied = useCallback(() => {
+ if (!restoreDraftRequest) return;
+ const { id, serverRestoreId, sessionId } = restoreDraftRequest;
+ if (serverRestoreId && sessionId) {
+ markDraftRestoreApplied(serverRestoreId);
+ consume(sessionId, serverRestoreId);
+ } else if (sessionId) {
+ dequeuePendingSendRestore(sessionId, id);
+ }
+ setRestoreDraftRequest(null);
+ }, [restoreDraftRequest, markDraftRestoreApplied, consume, dequeuePendingSendRestore]);
+
+ return { restoreDraftRequest, enqueueLocalRestore, handleRestoreDraftApplied };
+}
diff --git a/server/cmd/server/cors_headers_test.go b/server/cmd/server/cors_headers_test.go
new file mode 100644
index 0000000000..36fcabf9ee
--- /dev/null
+++ b/server/cmd/server/cors_headers_test.go
@@ -0,0 +1,23 @@
+package main
+
+import (
+ "slices"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// The app advertises its capabilities on the cancel request (#5219). Browsers
+// preflight a custom request header, so an entry missing from AllowedHeaders is
+// not a degraded feature — it is a failed request: the cancel never reaches the
+// server, and the user's prompt is lost in a way no server-side test can see.
+func TestCORSAllowedHeaders_IncludeClientCapabilities(t *testing.T) {
+ if !slices.Contains(corsAllowedHeaders, "X-Client-Capabilities") {
+ t.Fatalf("X-Client-Capabilities missing from CORS allowed headers: %v", corsAllowedHeaders)
+ }
+ // Named so the constant and the header travel together: the capability is
+ // useless if the header carrying it cannot cross the preflight.
+ if protocol.AppCapabilityChatDraftRestoreV1 == "" {
+ t.Fatal("AppCapabilityChatDraftRestoreV1 must be a non-empty capability token")
+ }
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 8202962266..3ee7d1751f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -47,6 +47,28 @@ var defaultOrigins = []string{
"http://localhost:5174", // electron-vite dev (fallback port)
}
+// corsAllowedHeaders must list every header the browser clients send. A header
+// missing here fails the preflight, so the request never reaches the handler at
+// all — the failure looks nothing like "the server ignored my header".
+// X-Client-Capabilities in particular was daemon-only (a Go client, never
+// preflighted) until the web app started advertising chat-draft-restore-v1 on
+// cancel.
+var corsAllowedHeaders = []string{
+ "Accept",
+ "Authorization",
+ "Content-Type",
+ "X-Workspace-ID",
+ "X-Workspace-Slug",
+ "X-Request-ID",
+ "X-Agent-ID",
+ "X-Task-ID",
+ "X-CSRF-Token",
+ "X-Client-Platform",
+ "X-Client-Version",
+ "X-Client-OS",
+ "X-Client-Capabilities",
+}
+
func allowedOrigins() []string {
raw := strings.TrimSpace(os.Getenv("CORS_ALLOWED_ORIGINS"))
if raw == "" {
@@ -648,7 +670,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Use(cors.Handler(cors.Options{
AllowedOrigins: origins,
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
- AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Workspace-ID", "X-Workspace-Slug", "X-Request-ID", "X-Agent-ID", "X-Task-ID", "X-CSRF-Token", "X-Client-Platform", "X-Client-Version", "X-Client-OS"},
+ AllowedHeaders: corsAllowedHeaders,
AllowCredentials: true,
MaxAge: 300,
}))
@@ -775,6 +797,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/tasks/{taskId}/usage", h.ReportTaskUsage)
r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)
r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)
+ r.Post("/tasks/{taskId}/cancel-ack", h.AckTaskCancelled)
r.Get("/issues/{issueId}/gc-check", h.GetIssueGCCheck)
r.Get("/chat-sessions/{sessionId}/gc-check", h.GetChatSessionGCCheck)
@@ -1296,6 +1319,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/messages/page", h.ListChatMessagesPage)
r.Get("/pending-task", h.GetPendingChatTask)
r.Post("/read", h.MarkChatSessionRead)
+ // Deferred-cancellation draft restores (#5219):
+ // creator-only fetch + idempotent consume.
+ r.Get("/draft-restores", h.ListChatDraftRestores)
+ r.Delete("/draft-restores/{restoreId}", h.ConsumeChatDraftRestore)
})
})
r.Get("/api/chat/pending-tasks", h.ListPendingChatTasks)
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index f08c8db09c..941e01c13e 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -68,6 +68,14 @@ const (
// ticks and 500 rows/tick we drain 60k rows/hour worst case — plenty
// of headroom for the documented backlog without monopolising DB CPU.
queuedExpireBatchSize = 500
+ // chatFinalizeGraceSeconds is how long a cancelled chat task's deferred
+ // empty/non-empty judgment (#5219) waits for the daemon's cancel-ack
+ // before the sweeper settles it. Covers the daemon's 5s cancellation
+ // poll plus the bounded 10s+12s transcript drain wait (#5210) plus
+ // network slack; past this the daemon is presumed dead or partitioned.
+ chatFinalizeGraceSeconds = 60.0
+ // chatFinalizeBatchSize caps deferred finalizations per tick.
+ chatFinalizeBatchSize = 100
)
// runRuntimeSweeper periodically marks runtimes as offline if their
@@ -93,6 +101,7 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handle
sweepStaleRuntimes(ctx, queries, liveness, taskSvc, bus)
sweepStaleTasks(ctx, queries, taskSvc, bus)
sweepExpiredQueuedTasks(ctx, queries, taskSvc)
+ sweepDeferredChatFinalizations(ctx, queries, taskSvc)
gcRuntimes(ctx, queries, bus)
}
}
@@ -304,6 +313,29 @@ func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *
taskSvc.HandleFailedTasks(ctx, failedTasks)
}
+// sweepDeferredChatFinalizations settles cancelled chat tasks whose deferred
+// empty/non-empty judgment (#5219) never received a daemon cancel-ack within
+// the grace period — the daemon died, was partitioned, or its ack was lost.
+// FinalizeDeferredCancelledChat claims the marker atomically, so racing a
+// late ack is harmless.
+func sweepDeferredChatFinalizations(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService) {
+ rows, err := queries.ListChatFinalizeDeferredExpired(ctx, db.ListChatFinalizeDeferredExpiredParams{
+ GraceSecs: chatFinalizeGraceSeconds,
+ MaxPerTick: chatFinalizeBatchSize,
+ })
+ if err != nil {
+ slog.Warn("chat finalize sweeper: list deferred failed", "error", err)
+ return
+ }
+ if len(rows) == 0 {
+ return
+ }
+ for _, t := range rows {
+ taskSvc.FinalizeDeferredCancelledChat(ctx, t.ID)
+ }
+ slog.Info("chat finalize sweeper: settled deferred cancellations", "count", len(rows))
+}
+
// broadcastFailedTasks is preserved as a thin shim for the integration tests
// in this package. New call sites should use TaskService.HandleFailedTasks
// directly so the side effects (event broadcast, agent reconcile, issue
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index a10d83db43..196866f65c 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -335,6 +335,15 @@ func (c *Client) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID, reas
}, nil)
}
+// AckTaskCancelled tells the server this daemon observed the task's
+// cancellation and has finished flushing the transcript (runner.run only
+// returns after executeAndDrain's drain wait), so the server can settle its
+// deferred chat finalization now instead of waiting out the sweeper grace
+// period (#5219). Idempotent server-side.
+func (c *Client) AckTaskCancelled(ctx context.Context, taskID string) error {
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/cancel-ack", taskID), map[string]any{}, nil)
+}
+
func (c *Client) ReportProgress(ctx context.Context, taskID, summary string, step, total int) error {
return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/progress", taskID), map[string]any{
"summary": summary,
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f60eae29dc..e9486d057d 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -3166,6 +3166,12 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
select {
case <-cancelledByPoll:
taskLog.Info("task cancelled during execution, discarding result")
+ // runner.run has returned, so the transcript flush is complete —
+ // tell the server it can settle its deferred chat finalization
+ // (#5219). Best-effort: the sweeper grace period covers a lost ack.
+ if ackErr := d.client.AckTaskCancelled(ctx, task.ID); ackErr != nil {
+ taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
+ }
return
default:
}
@@ -3193,6 +3199,11 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// signals as the in-flight watcher.
if status, err := d.client.GetTaskStatus(ctx, task.ID); shouldInterruptAgent(status, err) {
taskLog.Info("task cancelled during execution, discarding result", "status", status, "error", err)
+ // Same contract as the poll-cancelled path above: the transcript is
+ // flushed, so let the server settle its deferred chat finalization.
+ if ackErr := d.client.AckTaskCancelled(ctx, task.ID); ackErr != nil {
+ taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
+ }
return
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 9f7b741764..7c66009298 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -3361,3 +3361,138 @@ func TestHermesLaunchArgsAndEnvByScenario(t *testing.T) {
t.Errorf("overlay task must redirect HERMES_HOME to the overlay, got %q", overlayEnv["HERMES_HOME"])
}
}
+
+// TestHandleTask_AcksCancelAfterPollCancelled verifies the daemon posts
+// cancel-ack when the poll goroutine interrupts the run — by then
+// runner.run has returned, so the transcript flush is complete and the
+// server may settle its deferred chat finalization (#5219).
+func TestHandleTask_AcksCancelAfterPollCancelled(t *testing.T) {
+ t.Parallel()
+
+ var callOrder []string
+ var mu sync.Mutex
+ recordCall := func(name string) {
+ mu.Lock()
+ callOrder = append(callOrder, name)
+ mu.Unlock()
+ }
+
+ var statusCallCount atomic.Int64
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/cancel-ack"):
+ recordCall("cancel-ack")
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(r.URL.Path, "/status"):
+ if statusCallCount.Add(1) == 1 {
+ recordCall("poll-status")
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"status":"cancelled"}`))
+ } else {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"status":"running"}`))
+ }
+ default:
+ w.WriteHeader(http.StatusOK)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},
+ cancelPollInterval: 10 * time.Millisecond,
+ }
+
+ d.runner = taskRunnerFunc(func(runCtx context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {
+ <-runCtx.Done()
+ return TaskResult{Status: "aborted"}, nil
+ })
+
+ task := Task{
+ ID: "task-ack-poll",
+ RuntimeID: "rt-1",
+ IssueID: "issue-ack-poll",
+ Agent: &AgentData{Name: "test-agent"},
+ }
+
+ d.handleTask(context.Background(), task, 0)
+
+ mu.Lock()
+ order := make([]string, len(callOrder))
+ copy(order, callOrder)
+ mu.Unlock()
+
+ pollStatusIdx, ackIdx := -1, -1
+ for i, name := range order {
+ switch name {
+ case "poll-status":
+ pollStatusIdx = i
+ case "cancel-ack":
+ ackIdx = i
+ }
+ }
+ if pollStatusIdx == -1 {
+ t.Fatalf("poll goroutine never fired (order: %v)", order)
+ }
+ if ackIdx == -1 {
+ t.Fatalf("cancel-ack was never posted on the poll-cancelled path (order: %v)", order)
+ }
+ if ackIdx < pollStatusIdx {
+ t.Fatalf("cancel-ack before the poll observed the cancellation (order: %v)", order)
+ }
+}
+
+// TestHandleTask_AcksCancelOnPostRunStatusCheck verifies cancel-ack is also
+// posted when the cancellation is only discovered by the pre-completion
+// status check (the run finished before the poll noticed).
+func TestHandleTask_AcksCancelOnPostRunStatusCheck(t *testing.T) {
+ t.Parallel()
+
+ var ackCalls atomic.Int64
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/cancel-ack"):
+ ackCalls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(r.URL.Path, "/status"):
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"status":"cancelled"}`))
+ default:
+ w.WriteHeader(http.StatusOK)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},
+ cancelPollInterval: time.Hour, // disable the poll path; exercise the post-run check
+ }
+
+ d.runner = taskRunnerFunc(func(_ context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {
+ return TaskResult{Status: "completed"}, nil
+ })
+
+ task := Task{
+ ID: "task-ack-postrun",
+ RuntimeID: "rt-1",
+ IssueID: "issue-ack-postrun",
+ Agent: &AgentData{Name: "test-agent"},
+ }
+
+ d.handleTask(context.Background(), task, 0)
+
+ if got := ackCalls.Load(); got != 1 {
+ t.Fatalf("cancel-ack calls = %d, want 1", got)
+ }
+}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 512f71ab0e..4764170ff1 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -1075,7 +1075,22 @@ func (h *Handler) sendAgentWelcomeChat(ctx context.Context, agent db.Agent, crea
if !agent.RuntimeID.Valid {
return // no runtime → the agent can't run; skip the welcome
}
- session, err := h.Queries.CreateChatSession(ctx, db.CreateChatSessionParams{
+ // Create inside a tx that first takes FOR KEY SHARE on the workspace row — the
+ // creator half of the #5219 delete/create protocol, so the intro session cannot
+ // be created into a workspace mid-delete (see LockWorkspaceForChatSessionCreate).
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ slog.Warn("agent welcome: begin tx failed", "agent_id", uuidToString(agent.ID), "error", err)
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+
+ if _, err := qtx.LockWorkspaceForChatSessionCreate(ctx, parseUUID(workspaceID)); err != nil {
+ slog.Warn("agent welcome: lock workspace failed", "agent_id", uuidToString(agent.ID), "error", err)
+ return
+ }
+ session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{
WorkspaceID: parseUUID(workspaceID),
AgentID: agent.ID,
CreatorID: parseUUID(creatorID),
@@ -1086,6 +1101,10 @@ func (h *Handler) sendAgentWelcomeChat(ctx context.Context, agent db.Agent, crea
slog.Warn("agent welcome: create session failed", "agent_id", uuidToString(agent.ID), "error", err)
return
}
+ if err := tx.Commit(ctx); err != nil {
+ slog.Warn("agent welcome: commit session failed", "agent_id", uuidToString(agent.ID), "error", err)
+ return
+ }
if _, err := h.TaskService.EnqueueChatTask(ctx, session, parseUUID(creatorID), false); err != nil {
slog.Warn("agent welcome: enqueue task failed", "chat_session_id", uuidToString(session.ID), "error", err)
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.go
index bf2978bbaa..a2ec35b4b1 100644
--- a/server/internal/handler/agent_builder.go
+++ b/server/internal/handler/agent_builder.go
@@ -2,11 +2,13 @@ package handler
import (
"encoding/json"
+ "errors"
"fmt"
"net/http"
"strings"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/featureflags"
@@ -112,6 +114,18 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Reque
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ // FOR KEY SHARE on the workspace row before creating the builder's chat_session
+ // — the creator half of the #5219 delete/create protocol, so a session cannot
+ // be created into a workspace mid-delete (see LockWorkspaceForChatSessionCreate).
+ if _, err := qtx.LockWorkspaceForChatSessionCreate(r.Context(), workspaceUUID); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "workspace not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock workspace")
+ return
+ }
+
builder, err := qtx.CreateAgentBuilder(r.Context(), db.CreateAgentBuilderParams{
WorkspaceID: workspaceUUID,
Name: fmt.Sprintf(".multica-agent-builder-%s", flowID),
diff --git a/server/internal/handler/cancel_task_by_user_test.go b/server/internal/handler/cancel_task_by_user_test.go
index c9a39534e4..63f28ace92 100644
--- a/server/internal/handler/cancel_task_by_user_test.go
+++ b/server/internal/handler/cancel_task_by_user_test.go
@@ -6,6 +6,9 @@ import (
"net/http"
"net/http/httptest"
"testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
// CancelTaskByUser (POST /api/tasks/{taskId}/cancel) used to key cancellation
@@ -140,6 +143,140 @@ func cancelTaskByUserRequest(t *testing.T, userID, taskID string) *http.Request
return withChatTestWorkspaceCtx(t, req)
}
+// createStartedEmptyChatTask seeds the exact shape the deferred cancel is about:
+// a chat task the daemon has already started (started_at set) whose transcript is
+// still empty, plus the user message that triggered it.
+func createStartedEmptyChatTask(t *testing.T, sessionID, agentID, content string) (taskID, userMessageID string) {
+ t.Helper()
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, chat_session_id, started_at)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, NULL, $2, now())
+ RETURNING id
+ `, agentID, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("create started chat task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id)
+ VALUES ($1, 'user', $2, $3)
+ RETURNING id
+ `, sessionID, content, taskID).Scan(&userMessageID); err != nil {
+ t.Fatalf("create linked user chat message: %v", err)
+ }
+ return taskID, userMessageID
+}
+
+func chatFinalizeDeferredAt(t *testing.T, taskID string) *time.Time {
+ t.Helper()
+ var at *time.Time
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT chat_finalize_deferred_at FROM agent_task_queue WHERE id = $1
+ `, taskID).Scan(&at); err != nil {
+ t.Fatalf("read chat_finalize_deferred_at: %v", err)
+ }
+ return at
+}
+
+// Rollout compatibility (#5219). Clients and server do not upgrade together, and
+// a started-but-empty cancel is the one case where the prompt does NOT come back
+// in the cancel response — it is deferred and later published as a durable
+// draft-restore row, which only a client that knows about chat:cancel_finalized
+// and the draft-restores endpoint can collect. An installed desktop build that
+// predates all of that would read the empty response as "nothing to restore" and
+// silently drop the user's input, so deferral is gated on the client advertising
+// AppCapabilityChatDraftRestoreV1.
+func TestCancelTaskByUser_StartedEmptyChat_WithDraftRestoreCapability_Defers(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "CancelChatDeferCapableAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID, userMessageID := createStartedEmptyChatTask(t, sessionID, agentID, "defer this prompt")
+
+ req := cancelTaskByUserRequest(t, testUserID, taskID)
+ req.Header.Set("X-Client-Capabilities", protocol.AppCapabilityChatDraftRestoreV1)
+ w := httptest.NewRecorder()
+ testHandler.CancelTaskByUser(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CancelTaskByUserResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode cancel response: %v", err)
+ }
+ if resp.CancelledChatMessage != nil {
+ t.Fatalf("capable client must get no synchronous restore, got %#v", resp.CancelledChatMessage)
+ }
+ if chatFinalizeDeferredAt(t, taskID) == nil {
+ t.Fatal("expected the finalize-deferred marker to be set")
+ }
+
+ // The judgment is deferred, so the user message must still be there for the
+ // daemon ack / sweeper to settle.
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM chat_message WHERE id = $1`, userMessageID).Scan(&count); err != nil {
+ t.Fatalf("count user chat message: %v", err)
+ }
+ if count != 1 {
+ t.Fatalf("expected the user message to survive the deferral, got %d rows", count)
+ }
+}
+
+func TestCancelTaskByUser_StartedEmptyChat_LegacyClient_StillGetsSynchronousRestore(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "CancelChatDeferLegacyAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ const userContent = "an old client must not lose this"
+ taskID, userMessageID := createStartedEmptyChatTask(t, sessionID, agentID, userContent)
+
+ // No X-Client-Capabilities: a build that predates the durable restore.
+ w := httptest.NewRecorder()
+ testHandler.CancelTaskByUser(w, cancelTaskByUserRequest(t, testUserID, taskID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CancelTaskByUserResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode cancel response: %v", err)
+ }
+ if resp.CancelledChatMessage == nil {
+ t.Fatal("legacy client must still get the synchronous restore payload")
+ }
+ if resp.CancelledChatMessage.MessageID != userMessageID ||
+ resp.CancelledChatMessage.Content != userContent ||
+ !resp.CancelledChatMessage.RestoreToInput {
+ t.Fatalf("restore payload mismatch: %#v", resp.CancelledChatMessage)
+ }
+ if at := chatFinalizeDeferredAt(t, taskID); at != nil {
+ t.Fatalf("legacy cancel must not defer, marker set at %v", at)
+ }
+
+ // Legacy semantics all the way: the message is settled synchronously, and no
+ // durable restore row is written for a client that could never read it.
+ var messages int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM chat_message WHERE id = $1`, userMessageID).Scan(&messages); err != nil {
+ t.Fatalf("count user chat message: %v", err)
+ }
+ if messages != 0 {
+ t.Fatalf("expected the user message to be deleted synchronously, got %d rows", messages)
+ }
+ var restores int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM chat_draft_restore WHERE chat_session_id = $1`, sessionID).Scan(&restores); err != nil {
+ t.Fatalf("count draft restores: %v", err)
+ }
+ if restores != 0 {
+ t.Fatalf("expected no durable restore for a legacy cancel, got %d", restores)
+ }
+}
+
// TestCancelTaskByUser_RunOnlyAutopilot_Succeeds is the core MUL-2827 fix: a
// run_only autopilot task (issue_id + chat_session_id NULL, only
// autopilot_run_id set) is cancellable by a member of its agent's workspace.
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 1396b34e17..ca40725066 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -1,6 +1,7 @@
package handler
import (
+ "context"
"encoding/json"
"errors"
"log/slog"
@@ -15,6 +16,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
+ "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"
@@ -80,7 +82,29 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {
return
}
- session, err := h.Queries.CreateChatSession(r.Context(), db.CreateChatSessionParams{
+ // Create inside a tx that first takes a FOR KEY SHARE lock on the workspace
+ // row: it conflicts with DeleteWorkspace's FOR UPDATE, so a session cannot be
+ // created into a workspace whose delete is in progress and then be orphaned by
+ // the finalizer after the delete's sweep (#5219 create/delete protocol; see
+ // LockWorkspaceForChatSessionCreate).
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if _, err := qtx.LockWorkspaceForChatSessionCreate(r.Context(), workspaceUUID); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "workspace not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock workspace")
+ return
+ }
+
+ session, err := qtx.CreateChatSession(r.Context(), db.CreateChatSessionParams{
WorkspaceID: workspaceUUID,
AgentID: agentID,
CreatorID: parseUUID(userID),
@@ -91,6 +115,11 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {
return
}
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit chat session create")
+ return
+ }
+
writeJSON(w, http.StatusCreated, chatSessionToResponse(session))
}
@@ -498,6 +527,16 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to delete chat session outbound cards")
return
}
+ // chat_draft_restore is keyed by chat_session_id with no FK either, so its
+ // pending restores are pruned here rather than by a DB cascade (#5219). The
+ // LockChatSessionForDelete above doubles as the deleter half of the
+ // draft-restore protocol: FinalizeDeferredCancelledChat takes the same
+ // chat_session lock before inserting a restore, so it cannot slip one past
+ // this sweep (see LockChatSessionForTask in chat.sql).
+ if err := qtx.DeleteChatDraftRestoresBySession(r.Context(), session.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete chat session draft restores")
+ return
+ }
if err := qtx.DeleteChatSession(r.Context(), db.DeleteChatSessionParams{
ID: session.ID,
@@ -886,6 +925,156 @@ func (h *Handler) MarkChatSessionRead(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
+// ---------------------------------------------------------------------------
+// Deferred-cancellation draft restores (#5219)
+// ---------------------------------------------------------------------------
+
+// ChatDraftRestoreResponse is one recoverable composer draft: a deferred
+// cancellation settled as empty-transcript after the cancel HTTP response
+// returned, so the deleted prompt is persisted server-side until the
+// creator's client applies and consumes it. Attachments are resolved from
+// the stored ids at read time so they carry the normal handler URL policy.
+type ChatDraftRestoreResponse struct {
+ ID string `json:"id"`
+ ChatSessionID string `json:"chat_session_id"`
+ TaskID string `json:"task_id"`
+ Content string `json:"content"`
+ Attachments []AttachmentResponse `json:"attachments,omitempty"`
+ CreatedAt string `json:"created_at"`
+}
+
+type ChatDraftRestoresResponse struct {
+ Restores []ChatDraftRestoreResponse `json:"restores"`
+}
+
+// ListChatDraftRestores returns the session's pending draft restores.
+// Creator-only via loadChatSessionForUser — deliberately not the
+// private-agent gate: the content is the caller's own deleted prompt, and
+// losing agent access must not strand it server-side forever.
+func (h *Handler) ListChatDraftRestores(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ sessionID := chi.URLParam(r, "sessionId")
+
+ session, ok := h.loadChatSessionForUser(w, r, userID, workspaceID, sessionID)
+ if !ok {
+ return
+ }
+
+ rows, err := h.Queries.ListChatDraftRestoresBySession(r.Context(), session.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list draft restores")
+ return
+ }
+
+ var attachmentIDs []pgtype.UUID
+ for _, row := range rows {
+ attachmentIDs = append(attachmentIDs, row.AttachmentIds...)
+ }
+ attachmentsByID := map[string]AttachmentResponse{}
+ if len(attachmentIDs) > 0 {
+ attRows, err := h.Queries.ListAttachmentsByIDs(r.Context(), db.ListAttachmentsByIDsParams{
+ AttachmentIds: attachmentIDs,
+ WorkspaceID: session.WorkspaceID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load draft restore attachments")
+ return
+ }
+ for _, a := range attRows {
+ attachmentsByID[uuidToString(a.ID)] = h.attachmentToResponse(a)
+ }
+ }
+
+ resp := ChatDraftRestoresResponse{Restores: make([]ChatDraftRestoreResponse, 0, len(rows))}
+ for _, row := range rows {
+ item := ChatDraftRestoreResponse{
+ ID: uuidToString(row.ID),
+ ChatSessionID: uuidToString(row.ChatSessionID),
+ TaskID: uuidToString(row.TaskID),
+ Content: row.Content,
+ CreatedAt: timestampToString(row.CreatedAt),
+ }
+ for _, attID := range row.AttachmentIds {
+ if a, ok := attachmentsByID[uuidToString(attID)]; ok {
+ item.Attachments = append(item.Attachments, a)
+ }
+ }
+ resp.Restores = append(resp.Restores, item)
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// ConsumeChatDraftRestore deletes one draft restore after the creator's
+// client applied it. Idempotent: consuming an already-consumed (or never
+// existing) restore still returns 204, so a retried consume after a lost
+// response can't fail the client.
+func (h *Handler) ConsumeChatDraftRestore(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ sessionID := chi.URLParam(r, "sessionId")
+
+ session, ok := h.loadChatSessionForUser(w, r, userID, workspaceID, sessionID)
+ if !ok {
+ return
+ }
+ restoreUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "restoreId"), "restore id")
+ if !ok {
+ return
+ }
+
+ if _, err := h.Queries.DeleteChatDraftRestore(r.Context(), db.DeleteChatDraftRestoreParams{
+ ID: restoreUUID,
+ ChatSessionID: session.ID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to consume draft restore")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// pruneRuntimeAgentChatDraftRestores drops the pending draft restores of every
+// chat_session a runtime teardown is about to remove through the agent cascade
+// (chat_session.agent_id is ON DELETE CASCADE, migration 033). chat_draft_restore
+// has no FK (MUL-3515) and no reaper, so a restore left behind keeps the user's
+// prompt text forever, unreachable and undeletable.
+//
+// Every runtime/agent teardown path must call this in its own transaction and
+// BEFORE deleting the agent rows — the queries join through them. includeSystemAgents
+// mirrors whether the caller also runs DeleteSystemAgentsByRuntime: the
+// runtime-profile teardown deletes only archived agents, and pruning system-agent
+// sessions there would destroy restores whose session survives.
+//
+// The sessions are locked before the sweep: that is the deleter half of the
+// mutual-exclusion protocol with FinalizeDeferredCancelledChat, which would
+// otherwise insert a restore this sweep can no longer see (see LockChatSession*
+// in chat.sql).
+//
+// The workspace teardown has its own copy of this shape (locks, then sweeps
+// inside the DeleteWorkspace CTE) because that statement's prune must stay in
+// the same statement as the workspace row it commits with.
+func pruneRuntimeAgentChatDraftRestores(ctx context.Context, q *db.Queries, runtimeID pgtype.UUID, includeSystemAgents bool) error {
+ if _, err := q.LockChatSessionsByArchivedRuntimeAgents(ctx, runtimeID); err != nil {
+ return err
+ }
+ if err := q.DeleteChatDraftRestoresByArchivedRuntimeAgents(ctx, runtimeID); err != nil {
+ return err
+ }
+ if !includeSystemAgents {
+ return nil
+ }
+ if _, err := q.LockChatSessionsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
+ return err
+ }
+ return q.DeleteChatDraftRestoresBySystemRuntimeAgents(ctx, runtimeID)
+}
+
// PendingChatTasksResponse is the aggregate view consumed by the FAB.
type PendingChatTasksResponse struct {
Tasks []PendingChatTaskItem `json:"tasks"`
@@ -1140,7 +1329,9 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
}
}
- cancelled, err := h.TaskService.CancelTaskWithResult(r.Context(), taskUUID)
+ cancelled, err := h.TaskService.CancelTaskWithResult(r.Context(), taskUUID, service.CancelTaskOptions{
+ ClientSupportsDraftRestore: requestHasClientCapability(r, protocol.AppCapabilityChatDraftRestoreV1),
+ })
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
diff --git a/server/internal/handler/chat_draft_restore_race_test.go b/server/internal/handler/chat_draft_restore_race_test.go
new file mode 100644
index 0000000000..87f957ed66
--- /dev/null
+++ b/server/internal/handler/chat_draft_restore_race_test.go
@@ -0,0 +1,341 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/multica-ai/multica/server/internal/middleware"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// chat_draft_restore has no FK to chat_session (MUL-3515), so an INSERT into it
+// takes no lock on the session, and a deleter's prune only sees what committed
+// before its snapshot. Prune-then-delete alone therefore leaves a window: a
+// restore committed inside it outlives its cascade-deleted session, unreachable
+// and undeletable, with the user's prompt in it (#5219 review).
+//
+// The close is a mutual-exclusion protocol on the chat_session row lock — every
+// deleter locks before it sweeps, FinalizeDeferredCancelledChat locks before it
+// inserts. Each half is useless without the other, so each has its own test
+// below: pin one side, assert the other one blocks.
+
+type draftRestoreRaceFixture struct {
+ workspaceID string
+ chatSessionID string
+ taskID string
+}
+
+// seedDraftRestoreRaceFixture builds a disposable workspace holding one chat
+// task that FinalizeDeferredCancelledChat will settle as "still empty": a
+// deferred marker, an empty transcript, and the triggering user message it turns
+// into a chat_draft_restore row.
+func seedDraftRestoreRaceFixture(t *testing.T, slug string) draftRestoreRaceFixture {
+ t.Helper()
+ ctx := context.Background()
+
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+
+ var wsID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description)
+ VALUES ($1, $2, '')
+ RETURNING id
+ `, "Draft Restore Race", slug).Scan(&wsID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO member (workspace_id, user_id, role)
+ VALUES ($1, $2, 'owner')
+ `, wsID, testUserID); err != nil {
+ t.Fatalf("create owner member: %v", err)
+ }
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, 'Draft Restore Race Runtime', 'cloud', 'isolated_test', 'online', '', '{}'::jsonb, now())
+ RETURNING id
+ `, wsID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, 'Draft Restore Race Agent', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3)
+ RETURNING id
+ `, wsID, runtimeID, testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("create agent: %v", err)
+ }
+
+ var sessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
+ VALUES ($1, $2, $3, 'Draft Restore Race Session', 'active')
+ RETURNING id
+ `, wsID, agentID, testUserID).Scan(&sessionID); err != nil {
+ t.Fatalf("create chat session: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, chat_session_id, status, priority, context, runtime_id,
+ started_at, chat_finalize_deferred_at
+ )
+ VALUES ($1, $2, 'cancelled', 0, '{}'::jsonb, $3, now(), now())
+ RETURNING id
+ `, agentID, sessionID, runtimeID).Scan(&taskID); err != nil {
+ t.Fatalf("create deferred chat task: %v", err)
+ }
+
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id)
+ VALUES ($1, 'user', 'the prompt the cancel ate', $2)
+ `, sessionID, taskID); err != nil {
+ t.Fatalf("create user chat message: %v", err)
+ }
+
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ testPool.Exec(cleanupCtx, `DELETE FROM chat_draft_restore WHERE chat_session_id = $1`, sessionID)
+ testPool.Exec(cleanupCtx, `DELETE FROM workspace WHERE id = $1`, wsID)
+ })
+
+ return draftRestoreRaceFixture{workspaceID: wsID, chatSessionID: sessionID, taskID: taskID}
+}
+
+// waitForBlockedBackend reports whether some backend parked on a lock — the
+// observable proof that the side under test honoured the protocol. It gives up
+// the moment the racing goroutine finishes instead: a side that never blocks
+// skipped its lock, which is the bug these tests exist to catch.
+func waitForBlockedBackend(t *testing.T, done <-chan struct{}) bool {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ select {
+ case <-done:
+ return false
+ default:
+ }
+ var blocked int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM pg_stat_activity
+ WHERE datname = current_database() AND wait_event_type = 'Lock'
+ `).Scan(&blocked); err == nil && blocked > 0 {
+ return true
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ return false
+}
+
+// The writer's half. Without its own chat_session lock the finalizer can commit
+// a restore in the gap between a deleter's lock and that deleter's sweep — the
+// sweep's snapshot predates the commit and the row is stranded. Holding the
+// session lock from another tx is what makes that observable: a finalizer that
+// respects the protocol parks on it; one that doesn't sails past and writes.
+func TestFinalizeDeferredCancelledChat_TakesTheChatSessionLockBeforeInserting(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ f := seedDraftRestoreRaceFixture(t, "handler-tests-draft-restore-race-writer")
+
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin lock holder tx: %v", err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `SELECT id FROM chat_session WHERE id = $1 FOR UPDATE`, f.chatSessionID); err != nil {
+ t.Fatalf("lock chat session: %v", err)
+ }
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ testHandler.TaskService.FinalizeDeferredCancelledChat(context.Background(), parseUUID(f.taskID))
+ }()
+
+ if !waitForBlockedBackend(t, done) {
+ t.Fatal("finalizer settled while the chat_session row was locked: it never took the lock, so nothing stops it from inserting a restore behind a deleter's sweep")
+ }
+
+ // Releasing the lock must let it settle normally — the protocol adds
+ // exclusion, not a dropped restore.
+ if err := tx.Rollback(ctx); err != nil {
+ t.Fatalf("release chat session lock: %v", err)
+ }
+ <-done
+
+ if n := countDraftRestores(t, f.chatSessionID); n != 1 {
+ t.Errorf("expected the finalizer to write 1 restore once the lock cleared, got %d", n)
+ }
+}
+
+// The deleters' half. A restore commits while the workspace teardown is parked
+// on the session lock; the teardown's sweep runs on a snapshot taken after it
+// wins the lock, so it must still see — and remove — that row.
+func TestDeleteWorkspace_SweepsRestoreCommittedByAConcurrentFinalizer(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ f := seedDraftRestoreRaceFixture(t, "handler-tests-draft-restore-race-deleter")
+
+ // A finalizer held open mid-flight: session locked, restore written, not yet
+ // committed. (That the real finalizer takes this lock is pinned by the test
+ // above; here it is the deleter that is under test.)
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin finalizer tx: %v", err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `SELECT id FROM chat_session WHERE id = $1 FOR UPDATE`, f.chatSessionID); err != nil {
+ t.Fatalf("lock chat session: %v", err)
+ }
+ if _, err := tx.Exec(ctx, `
+ INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)
+ VALUES ($1, $2, $3, 'the prompt the cancel ate', '{}'::uuid[])
+ `, uuid.NewString(), f.chatSessionID, f.taskID); err != nil {
+ t.Fatalf("insert draft restore: %v", err)
+ }
+
+ code := make(chan int, 1)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodDelete, fmt.Sprintf("/api/workspaces/%s", f.workspaceID), nil), "id", f.workspaceID)
+ testHandler.DeleteWorkspace(w, req)
+ code <- w.Code
+ }()
+
+ if !waitForBlockedBackend(t, done) {
+ t.Fatal("DeleteWorkspace finished while a finalizer held the session lock: it never took the lock, so its sweep cannot see a restore committed behind it")
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit finalizer tx: %v", err)
+ }
+ <-done
+
+ if got := <-code; got != http.StatusNoContent {
+ t.Fatalf("DeleteWorkspace: expected 204, got %d", got)
+ }
+ if n := countDraftRestores(t, f.chatSessionID); n != 0 {
+ t.Errorf("a restore committed during the teardown survived it (%d row(s)) — orphaned, holding the user's prompt", n)
+ }
+}
+
+// The session locks only cover sessions that exist when the teardown enumerates
+// them. A chat_session created inside the delete window is invisible to that set,
+// so a finalizer could lock it and insert a restore after the sweep's snapshot —
+// and the restore would outlive the workspace cascade exactly like the TOCTOU
+// case above. The window is closed by an EXPLICIT protocol: DeleteWorkspace locks
+// the workspace row FOR UPDATE, and every session creator takes a conflicting
+// FOR KEY SHARE on it (LockWorkspaceForChatSessionCreate) inside its own tx before
+// inserting — so the block does not lean on the chat_session.workspace_id FK's
+// implicit lock, which the codebase is moving off of (MUL-3515).
+//
+// This drives the REAL creator entry point (Handler.CreateChatSession), not a raw
+// INSERT: holding the workspace row FOR UPDATE (the exact lock DeleteWorkspace
+// takes) must park the handler on its explicit lock, and releasing it must let the
+// create proceed. A handler that skipped the lock would sail straight through.
+func TestCreateChatSession_BlocksWhileTheWorkspaceDeleteLockIsHeld(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ f := seedDraftRestoreRaceFixture(t, "handler-tests-draft-restore-race-newsession")
+
+ var agentID string
+ if err := testPool.QueryRow(ctx,
+ `SELECT agent_id FROM chat_session WHERE id = $1`, f.chatSessionID).Scan(&agentID); err != nil {
+ t.Fatalf("read fixture agent: %v", err)
+ }
+ // The fixture's owner member, so the creator request carries a realistic
+ // workspace context for the fixture workspace (not the shared test one).
+ member, err := testHandler.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: parseUUID(testUserID),
+ WorkspaceID: parseUUID(f.workspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load fixture owner member: %v", err)
+ }
+
+ // Hold the workspace row FOR UPDATE — exactly what DeleteWorkspace's
+ // LockWorkspaceForDelete takes at the top of its teardown tx. This holder is
+ // not itself blocked, so the only backend that can park is the creator.
+ holder, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin workspace-lock holder tx: %v", err)
+ }
+ defer holder.Rollback(ctx)
+ if _, err := holder.Exec(ctx, `SELECT id FROM workspace WHERE id = $1 FOR UPDATE`, f.workspaceID); err != nil {
+ t.Fatalf("lock workspace row: %v", err)
+ }
+
+ code := make(chan int, 1)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ w := httptest.NewRecorder()
+ req := newRequestAs(testUserID, http.MethodPost, "/api/chat/sessions", map[string]any{
+ "agent_id": agentID,
+ "title": "Session racing the teardown",
+ })
+ req = req.WithContext(middleware.SetMemberContext(req.Context(), f.workspaceID, member))
+ testHandler.CreateChatSession(w, req)
+ code <- w.Code
+ }()
+
+ if !waitForBlockedBackend(t, done) {
+ t.Fatal("CreateChatSession returned while the workspace delete lock was held: it never took LockWorkspaceForChatSessionCreate, so a session can be created into a workspace mid-delete and its restore can outlive the cascade")
+ }
+
+ // Releasing the delete lock must let the create proceed — the protocol adds
+ // exclusion against an in-progress delete, not a blanket refusal.
+ if err := holder.Rollback(ctx); err != nil {
+ t.Fatalf("release workspace lock: %v", err)
+ }
+ <-done
+ if got := <-code; got != http.StatusCreated {
+ t.Fatalf("CreateChatSession: expected 201 once the delete lock cleared, got %d", got)
+ }
+}
+
+// The settle-against-a-gone-session case the lock protocol produces: the loser
+// of the race finds no session to lock, so it must clear its marker and write
+// nothing rather than strand a restore against a dead id.
+func TestFinalizeDeferredCancelledChat_SkipsTheInsertWhenTheSessionIsGone(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ f := seedDraftRestoreRaceFixture(t, "handler-tests-draft-restore-race-gone")
+
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodDelete, fmt.Sprintf("/api/workspaces/%s", f.workspaceID), nil), "id", f.workspaceID)
+ testHandler.DeleteWorkspace(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteWorkspace: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ testHandler.TaskService.FinalizeDeferredCancelledChat(ctx, parseUUID(f.taskID))
+
+ if n := countDraftRestores(t, f.chatSessionID); n != 0 {
+ t.Errorf("finalizer wrote %d restore(s) for a session that no longer exists", n)
+ }
+}
diff --git a/server/internal/handler/chat_draft_restore_test.go b/server/internal/handler/chat_draft_restore_test.go
new file mode 100644
index 0000000000..2f249e00f0
--- /dev/null
+++ b/server/internal/handler/chat_draft_restore_test.go
@@ -0,0 +1,326 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+)
+
+// withDraftRestoreParams sets both chi URL params in one route context —
+// chaining withURLParam would replace the context and drop the first param.
+func withDraftRestoreParams(req *http.Request, sessionID, restoreID string) *http.Request {
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("sessionId", sessionID)
+ rctx.URLParams.Add("restoreId", restoreID)
+ return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+}
+
+// seedDraftRestore inserts a chat_draft_restore row the way the deferred
+// finalize tx does: id is the deleted user message's id, attachments already
+// detached (chat_message_id NULL).
+func seedDraftRestore(t *testing.T, sessionID, content string, attachmentIDs []string) string {
+ t.Helper()
+ restoreID := uuid.NewString()
+ ids := "{}"
+ if len(attachmentIDs) > 0 {
+ ids = "{"
+ for i, id := range attachmentIDs {
+ if i > 0 {
+ ids += ","
+ }
+ ids += id
+ }
+ ids += "}"
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)
+ VALUES ($1, $2, $3, $4, $5::uuid[])
+ `, restoreID, sessionID, uuid.NewString(), content, ids); err != nil {
+ t.Fatalf("seed draft restore: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_draft_restore WHERE id = $1`, restoreID)
+ })
+ return restoreID
+}
+
+func seedDetachedChatAttachment(t *testing.T, sessionID string) string {
+ t.Helper()
+ var attachmentID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO attachment (
+ workspace_id, chat_session_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ )
+ VALUES ($1, $2, 'member', $3, 'notes.txt', 'https://files.test/notes.txt', 'text/plain', 12)
+ RETURNING id
+ `, testWorkspaceID, sessionID, testUserID).Scan(&attachmentID); err != nil {
+ t.Fatalf("seed detached attachment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, attachmentID)
+ })
+ return attachmentID
+}
+
+// The recovery path the chat:cancel_finalized broadcast cannot guarantee: a
+// creator whose client missed the event fetches the pending restore, gets the
+// prompt content plus re-bindable attachments, and consumes it idempotently.
+func TestChatDraftRestores_CreatorFetchesAndConsumes(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "DraftRestoreAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ attachmentID := seedDetachedChatAttachment(t, sessionID)
+ restoreID := seedDraftRestore(t, sessionID, "run the thing", []string{attachmentID})
+
+ listReq := withURLParam(newRequest(http.MethodGet, "/api/chat/sessions/"+sessionID+"/draft-restores", nil), "sessionId", sessionID)
+ listReq = withChatTestWorkspaceCtx(t, listReq)
+ listW := httptest.NewRecorder()
+ testHandler.ListChatDraftRestores(listW, listReq)
+ if listW.Code != http.StatusOK {
+ t.Fatalf("list: expected 200, got %d: %s", listW.Code, listW.Body.String())
+ }
+ var resp ChatDraftRestoresResponse
+ if err := json.Unmarshal(listW.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode list: %v", err)
+ }
+ if len(resp.Restores) != 1 {
+ t.Fatalf("restores = %d, want 1", len(resp.Restores))
+ }
+ got := resp.Restores[0]
+ if got.ID != restoreID {
+ t.Errorf("id = %q, want %q", got.ID, restoreID)
+ }
+ if got.Content != "run the thing" {
+ t.Errorf("content = %q, want %q", got.Content, "run the thing")
+ }
+ if len(got.Attachments) != 1 || got.Attachments[0].ID != attachmentID {
+ t.Fatalf("attachments = %+v, want the seeded attachment", got.Attachments)
+ }
+ if got.Attachments[0].Filename != "notes.txt" {
+ t.Errorf("attachment filename = %q, want notes.txt", got.Attachments[0].Filename)
+ }
+
+ // Consume twice: both must be 204 (idempotent), and the row must be gone.
+ for i := 0; i < 2; i++ {
+ delReq := withDraftRestoreParams(newRequest(http.MethodDelete, "/api/chat/sessions/"+sessionID+"/draft-restores/"+restoreID, nil), sessionID, restoreID)
+ delReq = withChatTestWorkspaceCtx(t, delReq)
+ delW := httptest.NewRecorder()
+ testHandler.ConsumeChatDraftRestore(delW, delReq)
+ if delW.Code != http.StatusNoContent {
+ t.Fatalf("consume call %d: expected 204, got %d: %s", i+1, delW.Code, delW.Body.String())
+ }
+ }
+
+ listW = httptest.NewRecorder()
+ testHandler.ListChatDraftRestores(listW, withChatTestWorkspaceCtx(t, withURLParam(newRequest(http.MethodGet, "/api/chat/sessions/"+sessionID+"/draft-restores", nil), "sessionId", sessionID)))
+ if listW.Code != http.StatusOK {
+ t.Fatalf("relist: expected 200, got %d", listW.Code)
+ }
+ resp = ChatDraftRestoresResponse{}
+ if err := json.Unmarshal(listW.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode relist: %v", err)
+ }
+ if len(resp.Restores) != 0 {
+ t.Errorf("restores after consume = %d, want 0", len(resp.Restores))
+ }
+}
+
+// Draft restores hold the creator's private prompt: another workspace member
+// must not be able to read or consume them.
+func TestChatDraftRestores_NonCreatorForbidden(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "DraftRestoreOtherAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ restoreID := seedDraftRestore(t, sessionID, "secret prompt", nil)
+
+ var otherUserID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO "user" (name, email)
+ VALUES ('Draft Restore Other', $1)
+ RETURNING id
+ `, fmt.Sprintf("draft-restore-other-%[email protected]", time.Now().UnixNano())).Scan(&otherUserID); err != nil {
+ t.Fatalf("create other user: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO member (workspace_id, user_id, role)
+ VALUES ($1, $2, 'member')
+ `, testWorkspaceID, otherUserID); err != nil {
+ t.Fatalf("create other member: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, otherUserID)
+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, otherUserID)
+ })
+
+ listReq := withURLParam(newRequest(http.MethodGet, "/api/chat/sessions/"+sessionID+"/draft-restores", nil), "sessionId", sessionID)
+ listReq = withChatTestWorkspaceCtx(t, listReq)
+ listReq.Header.Set("X-User-ID", otherUserID)
+ listW := httptest.NewRecorder()
+ testHandler.ListChatDraftRestores(listW, listReq)
+ if listW.Code != http.StatusForbidden {
+ t.Fatalf("list as non-creator: expected 403, got %d: %s", listW.Code, listW.Body.String())
+ }
+
+ delReq := withDraftRestoreParams(newRequest(http.MethodDelete, "/api/chat/sessions/"+sessionID+"/draft-restores/"+restoreID, nil), sessionID, restoreID)
+ delReq = withChatTestWorkspaceCtx(t, delReq)
+ delReq.Header.Set("X-User-ID", otherUserID)
+ delW := httptest.NewRecorder()
+ testHandler.ConsumeChatDraftRestore(delW, delReq)
+ if delW.Code != http.StatusForbidden {
+ t.Fatalf("consume as non-creator: expected 403, got %d: %s", delW.Code, delW.Body.String())
+ }
+
+ var count int
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM chat_draft_restore WHERE id = $1`, restoreID).Scan(&count); err != nil {
+ t.Fatalf("count restore: %v", err)
+ }
+ if count != 1 {
+ t.Errorf("restore row must survive a non-creator consume attempt, count = %d", count)
+ }
+}
+
+// chat_draft_restore has no chat_session FK (MUL-3515), so nothing but
+// DeleteChatSession's own transaction prunes an unconsumed restore.
+func TestDeleteChatSession_PrunesDraftRestores(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "DraftRestorePruneAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ seedDraftRestore(t, sessionID, "unconsumed prompt", nil)
+
+ req := withURLParam(newRequest(http.MethodDelete, "/api/chat/sessions/"+sessionID, nil), "sessionId", sessionID)
+ req = withChatTestWorkspaceCtx(t, req)
+ req.Header.Set("X-User-ID", testUserID)
+ w := httptest.NewRecorder()
+ testHandler.DeleteChatSession(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteChatSession: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM chat_draft_restore WHERE chat_session_id = $1`, sessionID).Scan(&count); err != nil {
+ t.Fatalf("count restores: %v", err)
+ }
+ if count != 0 {
+ t.Errorf("draft restores must be pruned with their session, count = %d", count)
+ }
+}
+
+func countDraftRestores(t *testing.T, sessionID string) int {
+ t.Helper()
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM chat_draft_restore WHERE chat_session_id = $1`, sessionID).Scan(&count); err != nil {
+ t.Fatalf("count restores: %v", err)
+ }
+ return count
+}
+
+// DeleteChatSession is not the only way a chat_session dies: it also cascades
+// from agent (migration 033). Hard-deleting a runtime's archived agents drops
+// their sessions silently, and with no FK on chat_draft_restore the pending
+// restores — each holding the user's prompt — would be stranded forever.
+func TestDeleteAgentRuntime_PrunesDraftRestoresOfCascadedSessions(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID := seedIsolatedRuntime(t, "Runtime With Draft Restore")
+ archivedAgent := seedAgentOnRuntime(t, runtimeID, "Archived Agent With Draft Restore", true)
+ sessionID := createHandlerTestChatSession(t, archivedAgent)
+ seedDraftRestore(t, sessionID, "prompt stranded by the agent cascade", nil)
+
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodDelete, "/api/runtimes/"+runtimeID, nil), "runtimeId", runtimeID)
+ testHandler.DeleteAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("DeleteAgentRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if agentExists(t, archivedAgent) {
+ t.Fatal("archived agent should have been deleted — the cascade under test never ran")
+ }
+ if n := countDraftRestores(t, sessionID); n != 0 {
+ t.Errorf("draft restores of a cascade-deleted session must be pruned, count = %d", n)
+ }
+}
+
+// The workspace cascade, same class. DeleteWorkspace runs outside a transaction
+// (its atomicity comes from being one multi-CTE statement), so the prune has to
+// live inside that statement — this is what guards it.
+func TestDeleteWorkspace_PrunesDraftRestoresOfCascadedSessions(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ const slug = "handler-tests-delete-draft-restores"
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+
+ var wsID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description)
+ VALUES ($1, $2, '')
+ RETURNING id
+ `, "Handler Test Draft Restore Cascade", slug).Scan(&wsID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO member (workspace_id, user_id, role)
+ VALUES ($1, $2, 'owner')
+ `, wsID, testUserID); err != nil {
+ t.Fatalf("create owner member: %v", err)
+ }
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, 'Draft Restore Cascade Runtime', 'cloud', 'isolated_test', 'online', '', '{}'::jsonb, now())
+ RETURNING id
+ `, wsID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, 'Draft Restore Cascade Agent', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3)
+ RETURNING id
+ `, wsID, runtimeID, testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("create agent: %v", err)
+ }
+
+ var sessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
+ VALUES ($1, $2, $3, 'Draft Restore Cascade Session', 'active')
+ RETURNING id
+ `, wsID, agentID, testUserID).Scan(&sessionID); err != nil {
+ t.Fatalf("create chat session: %v", err)
+ }
+ seedDraftRestore(t, sessionID, "prompt stranded by the workspace cascade", nil)
+
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodDelete, "/api/workspaces/"+wsID, nil), "id", wsID)
+ testHandler.DeleteWorkspace(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteWorkspace: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if n := countDraftRestores(t, sessionID); n != 0 {
+ t.Errorf("draft restores of a workspace-cascaded session must be pruned, count = %d", n)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 1e103fa9e5..2fe8e47aaf 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1296,7 +1296,9 @@ func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, cl
)
}
-func requestHasDaemonCapability(r *http.Request, capability string) bool {
+// requestHasClientCapability reports whether the caller advertised a capability
+// in X-Client-Capabilities. Daemons and app clients share the header.
+func requestHasClientCapability(r *http.Request, capability string) bool {
for _, part := range strings.Split(r.Header.Get("X-Client-Capabilities"), ",") {
if strings.TrimSpace(part) == capability {
return true
@@ -1586,7 +1588,7 @@ type claimBuildFailure struct {
func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string) (resp AgentTaskResponse, deliveredCommentIDs []pgtype.UUID, agentSkillCount, builtinSkillCount int, failure *claimBuildFailure) {
// Build response with fresh agent data (name + skills + custom_env + custom_args).
resp = taskToResponse(*task, runtimeWorkspaceID)
- supportsCoalescedComments := requestHasDaemonCapability(r, protocol.DaemonCapabilityCoalescedCommentsV1)
+ supportsCoalescedComments := requestHasClientCapability(r, protocol.DaemonCapabilityCoalescedCommentsV1)
// Empty-but-non-nil so pgx persists '{}' rather than NULL for tasks without
// comment input. Comment tasks replace this with the ids actually embedded
// in the capability-aware response built below.
@@ -1596,7 +1598,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.ConnectedApps = parseRuntimeConnectedAppsForClaim(task.RuntimeConnectedApps, task.ID)
}
if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {
- useSkillRefs := requestHasDaemonCapability(r, protocol.DaemonCapabilitySkillBundlesV1)
+ useSkillRefs := requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1)
var customEnv map[string]string
if agent.CustomEnv != nil {
if err := json.Unmarshal(agent.CustomEnv, &customEnv); err != nil {
@@ -3483,6 +3485,20 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
+// AckTaskCancelled receives the daemon's acknowledgement that it observed a
+// task cancellation and finished flushing the transcript. Settles the chat
+// finalization that CancelTaskWithResult deferred for a started-but-empty
+// transcript (#5219); idempotent when nothing was deferred.
+func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {
+ taskID := chi.URLParam(r, "taskId")
+ task, ok := h.requireDaemonTaskAccess(w, r, taskID)
+ if !ok {
+ return
+ }
+ h.TaskService.FinalizeDeferredCancelledChat(r.Context(), task.ID)
+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
+}
+
func taskMessageToPayload(m db.TaskMessage, taskID, issueID string) protocol.TaskMessagePayload {
var input map[string]any
if m.Input != nil {
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index ebd8b339c8..c52b58f76f 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -20,7 +20,7 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
-func TestRequestHasDaemonCapability(t *testing.T) {
+func TestRequestHasClientCapability(t *testing.T) {
tests := []struct {
name string
header string
@@ -39,8 +39,8 @@ func TestRequestHasDaemonCapability(t *testing.T) {
if tc.header != "" {
req.Header.Set("X-Client-Capabilities", tc.header)
}
- if got := requestHasDaemonCapability(req, protocol.DaemonCapabilityCoalescedCommentsV1); got != tc.want {
- t.Fatalf("requestHasDaemonCapability(%q) = %v, want %v", tc.header, got, tc.want)
+ if got := requestHasClientCapability(req, protocol.DaemonCapabilityCoalescedCommentsV1); got != tc.want {
+ t.Fatalf("requestHasClientCapability(%q) = %v, want %v", tc.header, got, tc.want)
}
})
}
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index ed75819655..2540e6e515 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -4585,3 +4585,121 @@ func TestClaimTaskByRuntime_CommentResumeDefaultOn(t *testing.T) {
t.Errorf("prior_session_id = %q, want %q (comment resume is default-on)", resp.Task.PriorSessionID, priorSession)
}
}
+
+// TestAckTaskCancelled verifies the cancel-ack endpoint settles a deferred
+// chat finalization (marker claimed, Stopped. row written for a transcript
+// that filled in late) and keeps the anti-enumeration shape of
+// requireDaemonTaskAccess for cross-workspace tokens.
+func TestAckTaskCancelled(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+
+ var agentID, runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1
+ `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {
+ t.Fatalf("setup: get agent: %v", err)
+ }
+
+ var chatSessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
+ VALUES ($1, $2, $3, 'cancel ack test')
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("setup: create chat session: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })
+
+ // Cancelled chat task with a pending deferred-finalize marker, plus a
+ // transcript row that landed after the cancel (the daemon's late flush).
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, chat_session_id, status, priority,
+ started_at, completed_at, chat_finalize_deferred_at
+ )
+ VALUES ($1, $2, NULL, $3, 'cancelled', 0, now(), now(), now())
+ RETURNING id
+ `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_message WHERE task_id = $1`, taskID)
+ testPool.Exec(ctx, `DELETE FROM chat_message WHERE task_id = $1`, taskID)
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_message (task_id, seq, type, content)
+ VALUES ($1, 1, 'text', 'late flush')
+ `, taskID); err != nil {
+ t.Fatalf("setup: insert task message: %v", err)
+ }
+
+ // Cross-workspace daemon token must still 404 and leave the marker armed.
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,
+ "00000000-0000-0000-0000-000000000000", "attacker-daemon")
+ req = withURLParam(req, "taskId", taskID)
+ testHandler.AckTaskCancelled(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("AckTaskCancelled with cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+ var deferredAt *time.Time
+ if err := testPool.QueryRow(ctx, `
+ SELECT chat_finalize_deferred_at FROM agent_task_queue WHERE id = $1
+ `, taskID).Scan(&deferredAt); err != nil {
+ t.Fatalf("read marker: %v", err)
+ }
+ if deferredAt == nil {
+ t.Fatal("cross-workspace ack must not claim the marker")
+ }
+
+ // Same-workspace token settles the deferred finalize.
+ w = httptest.NewRecorder()
+ req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,
+ testWorkspaceID, "legit-daemon")
+ req = withURLParam(req, "taskId", taskID)
+ testHandler.AckTaskCancelled(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("AckTaskCancelled same-workspace: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if err := testPool.QueryRow(ctx, `
+ SELECT chat_finalize_deferred_at FROM agent_task_queue WHERE id = $1
+ `, taskID).Scan(&deferredAt); err != nil {
+ t.Fatalf("read marker: %v", err)
+ }
+ if deferredAt != nil {
+ t.Errorf("marker should be claimed, got %v", deferredAt)
+ }
+ var stopped int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM chat_message WHERE task_id = $1 AND role = 'assistant' AND content = 'Stopped.'
+ `, taskID).Scan(&stopped); err != nil {
+ t.Fatalf("count stopped rows: %v", err)
+ }
+ if stopped != 1 {
+ t.Errorf("Stopped. rows = %d, want 1", stopped)
+ }
+
+ // Idempotent: a second ack is a no-op (no duplicate Stopped.).
+ w = httptest.NewRecorder()
+ req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,
+ testWorkspaceID, "legit-daemon")
+ req = withURLParam(req, "taskId", taskID)
+ testHandler.AckTaskCancelled(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("second AckTaskCancelled: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM chat_message WHERE task_id = $1 AND role = 'assistant' AND content = 'Stopped.'
+ `, taskID).Scan(&stopped); err != nil {
+ t.Fatalf("count stopped rows: %v", err)
+ }
+ if stopped != 1 {
+ t.Errorf("Stopped. rows after second ack = %d, want 1", stopped)
+ }
+}
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 19d47df3cb..8f850c71f8 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -779,6 +779,12 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to clean up agent label assignments")
return
}
+ // The agent deletes below cascade away these agents' chat_sessions, and
+ // chat_draft_restore has no FK to follow them (#5219). Prune first.
+ if err := pruneRuntimeAgentChatDraftRestores(r.Context(), qtx, rt.ID, true); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to clean up chat draft restores")
+ return
+ }
if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rt.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")
return
@@ -1046,6 +1052,12 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
writeError(w, http.StatusInternalServerError, "failed to clean up agent label assignments")
return
}
+ // The agent deletes below cascade away these agents' chat_sessions, and
+ // chat_draft_restore has no FK to follow them (#5219). Prune first.
+ if err := pruneRuntimeAgentChatDraftRestores(r.Context(), qtx, rt.ID, true); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to clean up chat draft restores")
+ return
+ }
if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rt.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")
return
diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.go
index 892b4e0a7d..9313ce5111 100644
--- a/server/internal/handler/runtime_profile.go
+++ b/server/internal/handler/runtime_profile.go
@@ -474,6 +474,13 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to clean up agent label assignments")
return
}
+ // chat_session cascades from agent, and chat_draft_restore has no FK to
+ // follow it (#5219). This path deletes only archived agents, so the prune
+ // is scoped to them too — system agents keep their sessions here.
+ if err := pruneRuntimeAgentChatDraftRestores(r.Context(), qtx, rid, false); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to clean up chat draft restores")
+ return
+ }
if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rid); err != nil {
writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")
return
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 7176ced75f..08480bf3d4 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -748,7 +748,42 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
}
}
- if err := h.Queries.DeleteChatPinnedAgentsByWorkspace(r.Context(), requester.WorkspaceID); err != nil {
+ // The teardown runs in one transaction so the chat_session row locks below
+ // are still held when DeleteWorkspace sweeps chat_draft_restore. Without
+ // them, FinalizeDeferredCancelledChat could commit a restore for one of
+ // these sessions after the sweep's snapshot was taken: the session cascades
+ // away, the restore has no FK to follow it (MUL-3515) and no reaper, and the
+ // user's prompt is stranded forever (#5219). The finalizer takes the same
+ // lock before inserting, so it either blocks until the session is gone and
+ // skips the insert, or commits first and the sweep sees its row.
+ //
+ // The workspace row is locked first, because the session locks only cover
+ // sessions that already exist: a CreateChatSession committing inside the
+ // delete window would otherwise slip in a session nobody locked, and its
+ // restore would outlive the cascade the same way. Holding the workspace row
+ // FOR UPDATE blocks that insert on its workspace FK (FOR KEY SHARE).
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ slog.Warn("begin workspace delete tx failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
+ writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if _, err := qtx.LockWorkspaceForDelete(r.Context(), requester.WorkspaceID); err != nil {
+ slog.Warn("lock workspace for delete failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
+ writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ return
+ }
+
+ if _, err := qtx.LockChatSessionsByWorkspace(r.Context(), requester.WorkspaceID); err != nil {
+ slog.Warn("lock workspace chat sessions failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
+ writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ return
+ }
+
+ if err := qtx.DeleteChatPinnedAgentsByWorkspace(r.Context(), requester.WorkspaceID); err != nil {
slog.Warn("delete workspace chat pins failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
writeError(w, http.StatusInternalServerError, "failed to delete workspace")
return
@@ -756,12 +791,18 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
// At this point workspaceMember has resolved → workspaceID is a valid UUID
// (the lookup would have errored otherwise), so reuse the resolved value.
- if err := h.Queries.DeleteWorkspace(r.Context(), requester.WorkspaceID); err != nil {
+ if err := qtx.DeleteWorkspace(r.Context(), requester.WorkspaceID); err != nil {
slog.Warn("delete workspace failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
writeError(w, http.StatusInternalServerError, "failed to delete workspace")
return
}
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Warn("commit workspace delete failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
+ writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ return
+ }
+
slog.Info("workspace deleted", append(logger.RequestAttrs(r), "workspace_id", workspaceID)...)
h.publish(protocol.EventWorkspaceDeleted, workspaceID, "member", requestUserID(r), map[string]any{
"workspace_id": workspaceID,
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index 84fad9b874..cba3e0a835 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -38,6 +38,7 @@ type TxStarter interface {
type SessionQueries interface {
WithTx(tx pgx.Tx) SessionQueries
GetChannelChatSessionBinding(ctx context.Context, arg db.GetChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
+ LockWorkspaceForChatSessionCreate(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error)
CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error)
@@ -58,6 +59,9 @@ func (a dbSessionQueries) WithTx(tx pgx.Tx) SessionQueries {
func (a dbSessionQueries) GetChannelChatSessionBinding(ctx context.Context, arg db.GetChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
return a.q.GetChannelChatSessionBinding(ctx, arg)
}
+func (a dbSessionQueries) LockWorkspaceForChatSessionCreate(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ return a.q.LockWorkspaceForChatSessionCreate(ctx, id)
+}
func (a dbSessionQueries) CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error) {
return a.q.CreateChatSession(ctx, arg)
}
@@ -189,6 +193,13 @@ func (s *ChatSession) createSessionAndBinding(ctx context.Context, in EnsureSess
defer tx.Rollback(ctx)
qtx := s.q.WithTx(tx)
+ // FOR KEY SHARE on the workspace row before creating the session — the creator
+ // half of the #5219 delete/create protocol, so a channel session cannot be
+ // created into a workspace mid-delete (see LockWorkspaceForChatSessionCreate).
+ if _, err := qtx.LockWorkspaceForChatSessionCreate(ctx, in.WorkspaceID); err != nil {
+ return pgtype.UUID{}, fmt.Errorf("lock workspace for chat session create: %w", err)
+ }
+
session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{
WorkspaceID: in.WorkspaceID,
AgentID: in.AgentID,
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index d9b3d6ce66..3b9dd8e565 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -41,6 +41,7 @@ type fakeSessionQueries struct {
messages []string
touched int
replyTargets int
+ lockedWorkspace int // count of LockWorkspaceForChatSessionCreate calls
lastConfig []byte // config of the most recent CreateChannelChatSessionBinding
prevMessage *string // GetMostRecentUserChatMessage result; nil → ErrNoRows
@@ -64,6 +65,11 @@ func (f *fakeSessionQueries) GetChannelChatSessionBinding(_ context.Context, arg
return db.ChannelChatSessionBinding{}, pgx.ErrNoRows
}
+func (f *fakeSessionQueries) LockWorkspaceForChatSessionCreate(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ f.lockedWorkspace++
+ return id, nil
+}
+
func (f *fakeSessionQueries) CreateChatSession(_ context.Context, _ db.CreateChatSessionParams) (db.ChatSession, error) {
f.nextSession++
f.createdSessions++
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index aefa6aa7a6..1d65424673 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1316,10 +1316,27 @@ type CancelTaskResult struct {
CancelledChatMessage *CancelledChatMessageResult
}
+// CancelTaskOptions carries what the caller knows about the client that asked
+// for the cancellation.
+type CancelTaskOptions struct {
+ // ClientSupportsDraftRestore is true when the caller can recover a prompt
+ // through the durable draft-restore path (#5219). Only such a client may be
+ // handed a deferred outcome; for anyone else the empty-transcript judgment
+ // stays synchronous, because the cancel response is their only chance to get
+ // the prompt back. See protocol.AppCapabilityChatDraftRestoreV1.
+ ClientSupportsDraftRestore bool
+}
+
// CancelTask cancels a single task by ID. It broadcasts a task:cancelled event
// so frontends can update immediately.
func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.AgentTaskQueue, error) {
- result, err := s.CancelTaskWithResult(ctx, taskID)
+ // Every caller of this wrapper cancels a non-chat task — issue/autopilot
+ // tasks through the issue-scoped endpoint, plus the daemon and sweeper paths
+ // — so finalizeCancelledChatMessage returns before the gate is even read.
+ // Should a chat task ever reach here, there is no client waiting on a
+ // synchronous restore anyway, and the durable path is the only one that can
+ // hand the prompt back at all.
+ result, err := s.CancelTaskWithResult(ctx, taskID, CancelTaskOptions{ClientSupportsDraftRestore: true})
if err != nil {
return nil, err
}
@@ -1328,7 +1345,7 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.A
// CancelTaskWithResult cancels a single task and returns any chat-specific
// cleanup result needed by user-facing callers.
-func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUID) (*CancelTaskResult, error) {
+func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUID, opts CancelTaskOptions) (*CancelTaskResult, error) {
task, err := s.Queries.CancelAgentTask(ctx, taskID)
if errors.Is(err, pgx.ErrNoRows) {
existing, err := s.Queries.GetAgentTask(ctx, taskID)
@@ -1343,7 +1360,7 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
slog.Info("task cancelled", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
s.captureTaskCancelled(ctx, task)
- cancelledChatMessage := s.finalizeCancelledChatMessage(ctx, task)
+ cancelledChatMessage := s.finalizeCancelledChatMessage(ctx, task, opts)
// Reconcile agent status
s.ReconcileAgentStatus(ctx, task.AgentID)
@@ -1358,7 +1375,7 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
}, nil
}
-func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.AgentTaskQueue) *CancelledChatMessageResult {
+func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.AgentTaskQueue, opts CancelTaskOptions) *CancelledChatMessageResult {
if !task.ChatSessionID.Valid {
return nil
}
@@ -1368,6 +1385,26 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
if err != nil {
return fmt.Errorf("list cancelled chat task messages: %w", err)
}
+ if len(messages) == 0 && task.StartedAt.Valid && opts.ClientSupportsDraftRestore {
+ // A started task's daemon learns of the cancellation by polling
+ // and may still be flushing its transcript tail, so "empty" is
+ // not trustworthy yet. Defer the judgment until the daemon acks
+ // its flush (cancel-ack) or the sweeper grace period expires
+ // (#5219). "Non-empty" needs no deferral: late rows only append.
+ //
+ // Deferring is gated on the client: clients and server do not
+ // upgrade together, and a client that cannot read the durable
+ // restore would take an empty cancel response as "nothing to put
+ // back" and lose the prompt. Such a client falls through to the
+ // legacy synchronous branch below — it keeps the pre-#5219 race
+ // (an in-flight transcript tail can still be misjudged as empty),
+ // which is exactly the behaviour it has against an old server, and
+ // strictly better than dropping the input.
+ if _, err := qtx.MarkChatFinalizeDeferred(ctx, task.ID); err != nil {
+ return fmt.Errorf("mark chat finalize deferred: %w", err)
+ }
+ return nil
+ }
if len(messages) == 0 {
// Detach attachments BEFORE deleting the user message — the
// attachment FK is ON DELETE CASCADE, so deleting first would
@@ -1413,6 +1450,155 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
return cancelled
}
+// FinalizeDeferredCancelledChat settles the empty/non-empty judgment that
+// finalizeCancelledChatMessage deferred for a started-but-empty cancelled
+// chat task (#5219). Called from the daemon's cancel-ack (transcript flush
+// complete) and from the sweeper grace-period fallback; the marker claim is
+// atomic, so concurrent callers cannot finalize the same task twice and a
+// call with no pending marker is a no-op. The settled outcome is broadcast
+// as chat:cancel_finalized since the cancel HTTP response has long returned.
+func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID pgtype.UUID) {
+ var (
+ task db.AgentTaskQueue
+ payload protocol.ChatCancelFinalizedPayload
+ settled bool
+ )
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ // Lock the task's chat_session first. chat_draft_restore has no FK
+ // (MUL-3515), so the insert below takes no lock of its own on the
+ // session — without this, a workspace/agent/session delete that swept
+ // the table just before we commit would leave our restore row (holding
+ // the user's prompt) orphaned forever. The deleters take the same lock
+ // before their sweep, so one of us blocks: either they wait and their
+ // sweep sees our row, or we wait and find no session left to restore
+ // into. Locking the session BEFORE the task claim also fixes the global
+ // lock order (chat_session -> agent_task_queue) that keeps this from
+ // deadlocking against the deleters' cascade.
+ _, err := qtx.LockChatSessionForTask(ctx, taskID)
+ sessionGone := errors.Is(err, pgx.ErrNoRows)
+ if err != nil && !sessionGone {
+ return fmt.Errorf("lock chat session for deferred finalize: %w", err)
+ }
+
+ // Claim the marker inside the settlement tx: a failed settlement then
+ // rolls the claim back so the sweeper can retry, instead of leaving the
+ // task with a cleared marker and no finalized outcome. The row lock
+ // still serializes the daemon ack and the sweeper — the loser's UPDATE
+ // blocks until the winner commits, then matches no row (ErrNoRows) — so
+ // the same task is never finalized twice.
+ claimed, err := qtx.ClaimChatFinalizeDeferred(ctx, taskID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("claim deferred chat finalize: %w", err)
+ }
+ task = claimed
+ if sessionGone {
+ // The session cascaded away (its FK NULLs the column below anyway):
+ // there is no transcript to settle and nowhere to put a restore. The
+ // claim above still cleared the marker, so the sweeper stops retrying.
+ return nil
+ }
+ if !claimed.ChatSessionID.Valid {
+ return nil
+ }
+ settled = true
+ payload.ChatSessionID = util.UUIDToString(claimed.ChatSessionID)
+ payload.TaskID = util.UUIDToString(claimed.ID)
+ payload.InitiatorUserID = util.UUIDToString(claimed.InitiatorUserID)
+
+ messages, err := qtx.ListTaskMessages(ctx, claimed.ID)
+ if err != nil {
+ return fmt.Errorf("list cancelled chat task messages: %w", err)
+ }
+ if len(messages) == 0 {
+ // The transcript stayed empty through the daemon flush: same
+ // outcome as the synchronous empty branch, but the cancel HTTP
+ // response is long gone and the broadcast is best-effort. The
+ // restore is persisted in this same tx and served by the
+ // creator-authorized draft-restores endpoint, so a client that
+ // misses the event recovers it on the next session open; the
+ // event itself carries no content and is only an invalidation
+ // hint.
+ detached, err := qtx.DetachAttachmentsFromUserChatMessageByTask(ctx, claimed.ID)
+ if err != nil {
+ return fmt.Errorf("detach cancelled chat message attachments: %w", err)
+ }
+ deleted, err := qtx.DeleteUserChatMessageByTask(ctx, claimed.ID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ payload.Outcome = ""
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("delete empty cancelled chat user message: %w", err)
+ }
+ attachmentIDs := make([]pgtype.UUID, 0, len(detached))
+ for _, a := range detached {
+ attachmentIDs = append(attachmentIDs, a.ID)
+ }
+ if _, err := qtx.CreateChatDraftRestore(ctx, db.CreateChatDraftRestoreParams{
+ ID: deleted.ID,
+ ChatSessionID: claimed.ChatSessionID,
+ TaskID: claimed.ID,
+ Content: deleted.Content,
+ AttachmentIds: attachmentIDs,
+ }); err != nil {
+ return fmt.Errorf("create chat draft restore: %w", err)
+ }
+ payload.Outcome = protocol.ChatCancelOutcomeRestored
+ payload.MessageID = util.UUIDToString(deleted.ID)
+ return nil
+ }
+ row, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ChatSessionID: claimed.ChatSessionID,
+ Role: "assistant",
+ Content: "Stopped.",
+ TaskID: claimed.ID,
+ ElapsedMs: computeChatElapsedMs(claimed),
+ })
+ if err != nil {
+ return fmt.Errorf("create cancelled chat message: %w", err)
+ }
+ payload.Outcome = protocol.ChatCancelOutcomeStopped
+ payload.MessageID = util.UUIDToString(row.ID)
+ payload.Content = row.Content
+ payload.MessageKind = row.MessageKind
+ if row.CreatedAt.Valid {
+ payload.CreatedAt = row.CreatedAt.Time.UTC().Format(time.RFC3339Nano)
+ }
+ if row.ElapsedMs.Valid {
+ payload.ElapsedMs = row.ElapsedMs.Int64
+ }
+ return nil
+ }); err != nil {
+ slog.Error("failed to finalize deferred cancelled chat",
+ "task_id", util.UUIDToString(taskID),
+ "error", err,
+ )
+ return
+ }
+ if !settled || payload.Outcome == "" {
+ return
+ }
+ s.broadcastChatCancelFinalized(ctx, task, payload)
+}
+
+func (s *TaskService) broadcastChatCancelFinalized(ctx context.Context, task db.AgentTaskQueue, payload protocol.ChatCancelFinalizedPayload) {
+ workspaceID := s.ResolveTaskWorkspaceID(ctx, task)
+ if workspaceID == "" {
+ return
+ }
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventChatCancelFinalized,
+ WorkspaceID: workspaceID,
+ ActorType: "system",
+ ActorID: "",
+ ChatSessionID: util.UUIDToString(task.ChatSessionID),
+ Payload: payload,
+ })
+}
+
// ClaimTask atomically claims the next queued task for an agent,
// respecting max_concurrent_tasks.
func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.AgentTaskQueue, error) {
diff --git a/server/internal/service/task_cancel_finalize_test.go b/server/internal/service/task_cancel_finalize_test.go
new file mode 100644
index 0000000000..1560a5088e
--- /dev/null
+++ b/server/internal/service/task_cancel_finalize_test.go
@@ -0,0 +1,583 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/events"
+ "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"
+)
+
+func newCancelFinalizePool(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Skipf("database unavailable: %v", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ t.Skipf("database unreachable: %v", err)
+ }
+ t.Cleanup(pool.Close)
+ return pool
+}
+
+type cancelFinalizeFixture struct {
+ pool *pgxpool.Pool
+ workspaceID string
+ agentID string
+ chatSessionID string
+ taskID string
+ userMessageID string
+}
+
+// createCancelFinalizeFixture seeds a chat task in the given status with one
+// triggering user chat_message bound to it. started marks the task as picked
+// up by a daemon (started_at set).
+func createCancelFinalizeFixture(t *testing.T, ctx context.Context, pool *pgxpool.Pool, status string, started bool) cancelFinalizeFixture {
+ t.Helper()
+
+ suffix := time.Now().UnixNano()
+ email := fmt.Sprintf("cancel-finalize-%[email protected]", suffix)
+ slug := fmt.Sprintf("cancel-finalize-%d", suffix)
+
+ var userID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO "user" (name, email)
+ VALUES ($1, $2)
+ RETURNING id
+ `, "Cancel Finalize Test", email).Scan(&userID); err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+
+ var workspaceID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id
+ `, "Cancel Finalize Test", slug, "temporary cancel finalize test workspace", "CFT").Scan(&workspaceID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO member (workspace_id, user_id, role)
+ VALUES ($1, $2, 'owner')
+ `, workspaceID, userID); err != nil {
+ t.Fatalf("create member: %v", err)
+ }
+
+ var runtimeID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider,
+ status, device_info, metadata, last_seen_at, visibility, owner_id
+ )
+ VALUES ($1, NULL, $2, 'cloud', 'cancel_finalize_test', 'online', 'test runtime', '{}'::jsonb, now(), 'private', $3)
+ RETURNING id
+ `, workspaceID, "Cancel Finalize Runtime", userID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+
+ var agentID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4)
+ RETURNING id
+ `, workspaceID, "Cancel Finalize Agent", runtimeID, userID).Scan(&agentID); err != nil {
+ t.Fatalf("create agent: %v", err)
+ }
+
+ var chatSessionID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
+ VALUES ($1, $2, $3, 'cancel finalize test')
+ RETURNING id
+ `, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("create chat session: %v", err)
+ }
+
+ startedAt := "NULL"
+ if started {
+ startedAt = "now()"
+ }
+ var taskID string
+ if err := pool.QueryRow(ctx, fmt.Sprintf(`
+ INSERT INTO agent_task_queue (agent_id, chat_session_id, status, priority, context, runtime_id, started_at)
+ VALUES ($1, $2, $3, 0, '{}'::jsonb, $4, %s)
+ RETURNING id
+ `, startedAt), agentID, chatSessionID, status, runtimeID).Scan(&taskID); err != nil {
+ t.Fatalf("create task: %v", err)
+ }
+
+ var userMessageID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id)
+ VALUES ($1, 'user', 'run the thing', $2)
+ RETURNING id
+ `, chatSessionID, taskID).Scan(&userMessageID); err != nil {
+ t.Fatalf("create user chat message: %v", err)
+ }
+
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ pool.Exec(cleanupCtx, `DELETE FROM task_message WHERE task_id = $1`, taskID)
+ pool.Exec(cleanupCtx, `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)
+ pool.Exec(cleanupCtx, `DELETE FROM chat_message WHERE chat_session_id = $1`, chatSessionID)
+ pool.Exec(cleanupCtx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ pool.Exec(cleanupCtx, `DELETE FROM agent WHERE id = $1`, agentID)
+ pool.Exec(cleanupCtx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ pool.Exec(cleanupCtx, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, workspaceID, userID)
+ pool.Exec(cleanupCtx, `DELETE FROM workspace WHERE id = $1`, workspaceID)
+ pool.Exec(cleanupCtx, `DELETE FROM "user" WHERE id = $1`, userID)
+ })
+
+ return cancelFinalizeFixture{
+ pool: pool,
+ workspaceID: workspaceID,
+ agentID: agentID,
+ chatSessionID: chatSessionID,
+ taskID: taskID,
+ userMessageID: userMessageID,
+ }
+}
+
+func (f cancelFinalizeFixture) insertTranscriptRow(t *testing.T, ctx context.Context) {
+ t.Helper()
+ if _, err := f.pool.Exec(ctx, `
+ INSERT INTO task_message (task_id, seq, type, content)
+ VALUES ($1, 1, 'text', 'partial output')
+ `, f.taskID); err != nil {
+ t.Fatalf("insert task message: %v", err)
+ }
+}
+
+func (f cancelFinalizeFixture) chatFinalizeDeferredAt(t *testing.T, ctx context.Context) *time.Time {
+ t.Helper()
+ var deferredAt *time.Time
+ if err := f.pool.QueryRow(ctx, `
+ SELECT chat_finalize_deferred_at FROM agent_task_queue WHERE id = $1
+ `, f.taskID).Scan(&deferredAt); err != nil {
+ t.Fatalf("read chat_finalize_deferred_at: %v", err)
+ }
+ return deferredAt
+}
+
+func (f cancelFinalizeFixture) userMessageExists(t *testing.T, ctx context.Context) bool {
+ t.Helper()
+ var count int
+ if err := f.pool.QueryRow(ctx, `
+ SELECT count(*) FROM chat_message WHERE id = $1
+ `, f.userMessageID).Scan(&count); err != nil {
+ t.Fatalf("count user message: %v", err)
+ }
+ return count > 0
+}
+
+// attachUserMessageAttachment binds an attachment row to the fixture's user
+// message, mirroring a prompt sent with a file.
+func (f cancelFinalizeFixture) attachUserMessageAttachment(t *testing.T, ctx context.Context) string {
+ t.Helper()
+ var attachmentID string
+ if err := f.pool.QueryRow(ctx, `
+ INSERT INTO attachment (
+ workspace_id, chat_session_id, chat_message_id,
+ uploader_type, uploader_id, filename, url, content_type, size_bytes
+ )
+ SELECT $1, $2, $3, 'member', creator_id, 'notes.txt', 'https://files.test/notes.txt', 'text/plain', 12
+ FROM chat_session WHERE id = $2
+ RETURNING id
+ `, f.workspaceID, f.chatSessionID, f.userMessageID).Scan(&attachmentID); err != nil {
+ t.Fatalf("create attachment: %v", err)
+ }
+ return attachmentID
+}
+
+func (f cancelFinalizeFixture) draftRestores(t *testing.T, ctx context.Context) []db.ChatDraftRestore {
+ t.Helper()
+ rows, err := db.New(f.pool).ListChatDraftRestoresBySession(ctx, util.MustParseUUID(f.chatSessionID))
+ if err != nil {
+ t.Fatalf("list draft restores: %v", err)
+ }
+ return rows
+}
+
+func (f cancelFinalizeFixture) assistantMessages(t *testing.T, ctx context.Context) []string {
+ t.Helper()
+ rows, err := f.pool.Query(ctx, `
+ SELECT content FROM chat_message WHERE task_id = $1 AND role = 'assistant' ORDER BY created_at
+ `, f.taskID)
+ if err != nil {
+ t.Fatalf("list assistant messages: %v", err)
+ }
+ defer rows.Close()
+ var contents []string
+ for rows.Next() {
+ var c string
+ if err := rows.Scan(&c); err != nil {
+ t.Fatalf("scan assistant message: %v", err)
+ }
+ contents = append(contents, c)
+ }
+ return contents
+}
+
+// eventRecorder captures chat:cancel_finalized events published on the bus.
+type eventRecorder struct {
+ mu sync.Mutex
+ events []events.Event
+}
+
+func recordCancelFinalizedEvents(bus *events.Bus) *eventRecorder {
+ rec := &eventRecorder{}
+ bus.Subscribe(protocol.EventChatCancelFinalized, func(e events.Event) {
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+ rec.events = append(rec.events, e)
+ })
+ return rec
+}
+
+func (r *eventRecorder) snapshot() []events.Event {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return append([]events.Event(nil), r.events...)
+}
+
+// Cancelled before any daemon started the task: the transcript can never gain
+// rows, so the empty judgment is final and the draft restore stays synchronous.
+func TestCancelTask_NotStarted_RestoresDraftSynchronously(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "queued", false)
+ svc := NewTaskService(db.New(pool), pool, nil, events.New())
+
+ result, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true})
+ if err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+ if result.CancelledChatMessage == nil {
+ t.Fatal("expected a synchronous CancelledChatMessage restore result")
+ }
+ if !result.CancelledChatMessage.RestoreToInput {
+ t.Error("expected RestoreToInput=true")
+ }
+ if result.CancelledChatMessage.Content != "run the thing" {
+ t.Errorf("restored content = %q, want %q", result.CancelledChatMessage.Content, "run the thing")
+ }
+ if f.userMessageExists(t, ctx) {
+ t.Error("user chat message should have been deleted")
+ }
+ if got := f.chatFinalizeDeferredAt(t, ctx); got != nil {
+ t.Errorf("chat_finalize_deferred_at should stay NULL, got %v", got)
+ }
+}
+
+// Cancelled after start with transcript rows already persisted: "non-empty"
+// is monotonic (late rows only append), so the Stopped. outcome stays
+// synchronous.
+func TestCancelTask_StartedNonEmptyTranscript_StopsSynchronously(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ f.insertTranscriptRow(t, ctx)
+ svc := NewTaskService(db.New(pool), pool, nil, events.New())
+
+ result, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true})
+ if err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+ if result.CancelledChatMessage != nil {
+ t.Fatalf("expected no restore result, got %+v", result.CancelledChatMessage)
+ }
+ if got := f.assistantMessages(t, ctx); len(got) != 1 || got[0] != "Stopped." {
+ t.Errorf("assistant messages = %v, want [Stopped.]", got)
+ }
+ if !f.userMessageExists(t, ctx) {
+ t.Error("user chat message should be preserved")
+ }
+ if got := f.chatFinalizeDeferredAt(t, ctx); got != nil {
+ t.Errorf("chat_finalize_deferred_at should stay NULL, got %v", got)
+ }
+}
+
+// Cancelled after start with an empty transcript: the daemon may still be
+// flushing, so no judgment is made — the task is marked deferred instead.
+func TestCancelTask_StartedEmptyTranscript_DefersJudgment(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ svc := NewTaskService(db.New(pool), pool, nil, events.New())
+
+ result, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true})
+ if err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+ if result.CancelledChatMessage != nil {
+ t.Fatalf("expected no synchronous restore result, got %+v", result.CancelledChatMessage)
+ }
+ if !f.userMessageExists(t, ctx) {
+ t.Error("user chat message must not be deleted while deferred")
+ }
+ if got := f.assistantMessages(t, ctx); len(got) != 0 {
+ t.Errorf("no assistant message should exist while deferred, got %v", got)
+ }
+ if got := f.chatFinalizeDeferredAt(t, ctx); got == nil {
+ t.Error("chat_finalize_deferred_at should be set")
+ }
+}
+
+// Deferred finalize with a transcript that stayed empty: the user message is
+// deleted, a durable chat_draft_restore row is persisted in the same tx, and
+// a content-free restored-outcome event is broadcast as an invalidation hint.
+func TestFinalizeDeferredCancelledChat_StillEmpty_RestoresDraft(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ bus := events.New()
+ rec := recordCancelFinalizedEvents(bus)
+ svc := NewTaskService(db.New(pool), pool, nil, bus)
+
+ if _, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+
+ svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))
+
+ if f.userMessageExists(t, ctx) {
+ t.Error("user chat message should have been deleted")
+ }
+ if got := f.chatFinalizeDeferredAt(t, ctx); got != nil {
+ t.Errorf("chat_finalize_deferred_at should be cleared, got %v", got)
+ }
+ restores := f.draftRestores(t, ctx)
+ if len(restores) != 1 {
+ t.Fatalf("expected 1 chat_draft_restore row, got %d", len(restores))
+ }
+ if got := util.UUIDToString(restores[0].ID); got != f.userMessageID {
+ t.Errorf("restore id = %q, want deleted message id %q", got, f.userMessageID)
+ }
+ if restores[0].Content != "run the thing" {
+ t.Errorf("restore content = %q, want %q", restores[0].Content, "run the thing")
+ }
+ if got := util.UUIDToString(restores[0].TaskID); got != f.taskID {
+ t.Errorf("restore task_id = %q, want %q", got, f.taskID)
+ }
+ evts := rec.snapshot()
+ if len(evts) != 1 {
+ t.Fatalf("expected 1 chat:cancel_finalized event, got %d", len(evts))
+ }
+ payload, ok := evts[0].Payload.(protocol.ChatCancelFinalizedPayload)
+ if !ok {
+ t.Fatalf("payload type = %T", evts[0].Payload)
+ }
+ if payload.Outcome != protocol.ChatCancelOutcomeRestored {
+ t.Errorf("outcome = %q, want restored", payload.Outcome)
+ }
+ if payload.MessageID != f.userMessageID {
+ t.Errorf("message_id = %q, want %q", payload.MessageID, f.userMessageID)
+ }
+ if payload.Content != "" {
+ t.Errorf("restored event must not carry the prompt content, got %q", payload.Content)
+ }
+ if payload.ChatSessionID != f.chatSessionID {
+ t.Errorf("chat_session_id = %q, want %q", payload.ChatSessionID, f.chatSessionID)
+ }
+}
+
+// The recoverability guarantee behind the restored outcome: the draft-restore
+// row commits with the settlement tx, so a client that never receives the
+// chat:cancel_finalized broadcast (offline, or the server dies between commit
+// and publish — simulated here by a bus with no subscribers) still finds the
+// restore, with its detached attachment ids, on the next fetch.
+func TestFinalizeDeferredCancelledChat_BroadcastLost_RestoreIsRecoverable(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ attachmentID := f.attachUserMessageAttachment(t, ctx)
+ queries := db.New(pool)
+ svc := NewTaskService(queries, pool, nil, events.New())
+
+ if _, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+
+ svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))
+
+ restores, err := queries.ListChatDraftRestoresBySession(ctx, util.MustParseUUID(f.chatSessionID))
+ if err != nil {
+ t.Fatalf("list draft restores: %v", err)
+ }
+ if len(restores) != 1 {
+ t.Fatalf("expected 1 recoverable draft restore, got %d", len(restores))
+ }
+ if restores[0].Content != "run the thing" {
+ t.Errorf("restore content = %q, want %q", restores[0].Content, "run the thing")
+ }
+ if len(restores[0].AttachmentIds) != 1 || util.UUIDToString(restores[0].AttachmentIds[0]) != attachmentID {
+ t.Errorf("restore attachment_ids = %v, want [%s]", restores[0].AttachmentIds, attachmentID)
+ }
+ // The attachment row itself must have survived the message delete
+ // (detached, so the restored draft can re-bind it on re-send).
+ var chatMessageID *string
+ if err := pool.QueryRow(ctx, `
+ SELECT chat_message_id FROM attachment WHERE id = $1
+ `, attachmentID).Scan(&chatMessageID); err != nil {
+ t.Fatalf("attachment row should survive: %v", err)
+ }
+ if chatMessageID != nil {
+ t.Errorf("attachment should be detached, still bound to %v", *chatMessageID)
+ }
+
+ // Consume is idempotent: first delete claims the row, second is a no-op.
+ for i, want := range []int64{1, 0} {
+ n, err := queries.DeleteChatDraftRestore(ctx, db.DeleteChatDraftRestoreParams{
+ ID: restores[0].ID,
+ ChatSessionID: util.MustParseUUID(f.chatSessionID),
+ })
+ if err != nil {
+ t.Fatalf("consume draft restore (call %d): %v", i+1, err)
+ }
+ if n != want {
+ t.Errorf("consume rows (call %d) = %d, want %d", i+1, n, want)
+ }
+ }
+}
+
+// Deferred finalize after transcript rows landed late: the judgment flips to
+// non-empty, a Stopped. row is written, and a stopped-outcome event is
+// broadcast.
+func TestFinalizeDeferredCancelledChat_RowsLanded_WritesStopped(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ bus := events.New()
+ rec := recordCancelFinalizedEvents(bus)
+ svc := NewTaskService(db.New(pool), pool, nil, bus)
+
+ if _, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+ // The daemon's late flush lands after the cancel commit.
+ f.insertTranscriptRow(t, ctx)
+
+ svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))
+
+ if !f.userMessageExists(t, ctx) {
+ t.Error("user chat message should be preserved")
+ }
+ if got := f.assistantMessages(t, ctx); len(got) != 1 || got[0] != "Stopped." {
+ t.Errorf("assistant messages = %v, want [Stopped.]", got)
+ }
+ if got := f.chatFinalizeDeferredAt(t, ctx); got != nil {
+ t.Errorf("chat_finalize_deferred_at should be cleared, got %v", got)
+ }
+ evts := rec.snapshot()
+ if len(evts) != 1 {
+ t.Fatalf("expected 1 chat:cancel_finalized event, got %d", len(evts))
+ }
+ payload, ok := evts[0].Payload.(protocol.ChatCancelFinalizedPayload)
+ if !ok {
+ t.Fatalf("payload type = %T", evts[0].Payload)
+ }
+ if payload.Outcome != protocol.ChatCancelOutcomeStopped {
+ t.Errorf("outcome = %q, want stopped", payload.Outcome)
+ }
+ if payload.Content != "Stopped." {
+ t.Errorf("content = %q, want Stopped.", payload.Content)
+ }
+ if payload.MessageID == "" {
+ t.Error("message_id should carry the new assistant row id")
+ }
+}
+
+// The marker is an atomic claim: a second finalize call must be a no-op.
+func TestFinalizeDeferredCancelledChat_SecondCallIsNoop(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ bus := events.New()
+ rec := recordCancelFinalizedEvents(bus)
+ svc := NewTaskService(db.New(pool), pool, nil, bus)
+
+ if _, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+ f.insertTranscriptRow(t, ctx)
+
+ svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))
+ svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))
+
+ if got := f.assistantMessages(t, ctx); len(got) != 1 {
+ t.Errorf("assistant messages = %v, want exactly one Stopped.", got)
+ }
+ if got := len(rec.snapshot()); got != 1 {
+ t.Errorf("events = %d, want 1", got)
+ }
+}
+
+// Sweeper query: only markers older than the grace period are returned.
+func TestListChatFinalizeDeferredExpired_HonorsGrace(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ queries := db.New(pool)
+ svc := NewTaskService(queries, pool, nil, events.New())
+
+ if _, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+
+ fresh, err := queries.ListChatFinalizeDeferredExpired(ctx, db.ListChatFinalizeDeferredExpiredParams{
+ GraceSecs: 60,
+ MaxPerTick: 100,
+ })
+ if err != nil {
+ t.Fatalf("list expired: %v", err)
+ }
+ for _, row := range fresh {
+ if util.UUIDToString(row.ID) == f.taskID {
+ t.Fatal("fresh marker must not be returned within the grace period")
+ }
+ }
+
+ if _, err := pool.Exec(ctx, `
+ UPDATE agent_task_queue SET chat_finalize_deferred_at = now() - interval '2 minutes' WHERE id = $1
+ `, f.taskID); err != nil {
+ t.Fatalf("backdate marker: %v", err)
+ }
+
+ expired, err := queries.ListChatFinalizeDeferredExpired(ctx, db.ListChatFinalizeDeferredExpiredParams{
+ GraceSecs: 60,
+ MaxPerTick: 100,
+ })
+ if err != nil {
+ t.Fatalf("list expired: %v", err)
+ }
+ found := false
+ for _, row := range expired {
+ if util.UUIDToString(row.ID) == f.taskID {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("backdated marker should be returned once past the grace period")
+ }
+}
diff --git a/server/migrations/180_task_chat_finalize_deferred.down.sql b/server/migrations/180_task_chat_finalize_deferred.down.sql
new file mode 100644
index 0000000000..f5f5291ee9
--- /dev/null
+++ b/server/migrations/180_task_chat_finalize_deferred.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS chat_finalize_deferred_at;
diff --git a/server/migrations/180_task_chat_finalize_deferred.up.sql b/server/migrations/180_task_chat_finalize_deferred.up.sql
new file mode 100644
index 0000000000..3054281174
--- /dev/null
+++ b/server/migrations/180_task_chat_finalize_deferred.up.sql
@@ -0,0 +1,10 @@
+-- #5219: cancellation-time chat finalization can race the daemon's transcript
+-- flush. When a started chat task is cancelled while its transcript is still
+-- empty, the empty/non-empty judgment is deferred until the daemon acks its
+-- flush (or a sweeper grace period expires). This column is both the pending
+-- marker and the grace-period clock; clearing it doubles as the atomic claim
+-- that keeps the ack path and the sweeper from finalizing the same task twice.
+--
+-- The sweeper index lives in migration 181: agent_task_queue is a hot table,
+-- so the index build must run CONCURRENTLY in its own single-statement file.
+ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS chat_finalize_deferred_at TIMESTAMPTZ;
diff --git a/server/migrations/181_task_chat_finalize_deferred_index.down.sql b/server/migrations/181_task_chat_finalize_deferred_index.down.sql
new file mode 100644
index 0000000000..caf64b65d4
--- /dev/null
+++ b/server/migrations/181_task_chat_finalize_deferred_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_task_chat_finalize_deferred;
diff --git a/server/migrations/181_task_chat_finalize_deferred_index.up.sql b/server/migrations/181_task_chat_finalize_deferred_index.up.sql
new file mode 100644
index 0000000000..a93723b3ff
--- /dev/null
+++ b/server/migrations/181_task_chat_finalize_deferred_index.up.sql
@@ -0,0 +1,9 @@
+-- Partial index over pending deferred finalizations only: the sweeper scans
+-- for rows past the grace period, and the pending set is tiny (cancelled
+-- started-but-empty chat tasks awaiting a daemon ack).
+--
+-- Single-statement migration: CREATE INDEX CONCURRENTLY cannot run inside a
+-- transaction or a multi-command string.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_chat_finalize_deferred
+ ON agent_task_queue (chat_finalize_deferred_at)
+ WHERE chat_finalize_deferred_at IS NOT NULL;
diff --git a/server/migrations/182_chat_draft_restore.down.sql b/server/migrations/182_chat_draft_restore.down.sql
new file mode 100644
index 0000000000..f5bd1f3add
--- /dev/null
+++ b/server/migrations/182_chat_draft_restore.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS chat_draft_restore;
diff --git a/server/migrations/182_chat_draft_restore.up.sql b/server/migrations/182_chat_draft_restore.up.sql
new file mode 100644
index 0000000000..7e3a8bad6c
--- /dev/null
+++ b/server/migrations/182_chat_draft_restore.up.sql
@@ -0,0 +1,28 @@
+-- Durable draft restore for deferred cancellations (#5219). When a cancelled
+-- chat task's transcript settles as empty, the triggering user message is
+-- deleted and its content must return to the creator's composer. The
+-- chat:cancel_finalized broadcast is best-effort, so the restore is persisted
+-- here and served by a creator-authorized endpoint: a client that was offline
+-- across the event fetches it on the next session open and consumes it
+-- (DELETE) once applied.
+--
+-- No foreign keys: new tables enforce their relationships in the application
+-- layer (MUL-3515). DeleteChatSession prunes this table inside its transaction,
+-- alongside the channel_* tables it already prunes there.
+--
+-- id is the deleted user chat message's id: globally unique (it was a
+-- chat_message PK), stable for client-side dedup, and one restore per task is
+-- guaranteed by the atomic deferred-finalize claim.
+--
+-- The chat_session_id lookup index lives in migration 183: every production
+-- index is built CONCURRENTLY in its own single-statement file.
+CREATE TABLE chat_draft_restore (
+ id UUID PRIMARY KEY,
+ chat_session_id UUID NOT NULL,
+ task_id UUID NOT NULL,
+ content TEXT NOT NULL,
+ -- Detached attachment rows the restored draft re-binds; resolved to full
+ -- attachment responses (URL policy included) at read time.
+ attachment_ids UUID[] NOT NULL DEFAULT '{}',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/183_chat_draft_restore_index.down.sql b/server/migrations/183_chat_draft_restore_index.down.sql
new file mode 100644
index 0000000000..0ea8e46c4d
--- /dev/null
+++ b/server/migrations/183_chat_draft_restore_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_chat_draft_restore_session;
diff --git a/server/migrations/183_chat_draft_restore_index.up.sql b/server/migrations/183_chat_draft_restore_index.up.sql
new file mode 100644
index 0000000000..5148fa8470
--- /dev/null
+++ b/server/migrations/183_chat_draft_restore_index.up.sql
@@ -0,0 +1,9 @@
+-- Lookup index for chat_draft_restore.chat_session_id: the creator-authorized
+-- read (ListChatDraftRestoresBySession) and the DeleteChatSession / workspace /
+-- runtime cascade-path prunes all filter by chat_session_id.
+--
+-- Single-statement migration: CREATE INDEX CONCURRENTLY cannot run inside a
+-- transaction or a multi-command string. Split from the table in migration 182
+-- so every production index build runs CONCURRENTLY.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chat_draft_restore_session
+ ON chat_draft_restore (chat_session_id);
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 02b5cf6507..c191ca227f 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -190,7 +190,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -235,6 +235,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -243,7 +244,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -299,6 +300,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -314,7 +316,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Cancels active tasks belonging to a chat session. Called from
@@ -370,6 +372,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -385,7 +388,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -441,6 +444,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -456,7 +460,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -516,6 +520,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -532,7 +537,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -587,6 +592,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -607,9 +613,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at
)
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM cancelled
+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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -618,44 +624,45 @@ type CancelDeferredEscalationsForIssueAgentParams struct {
}
type CancelDeferredEscalationsForIssueAgentRow struct {
- ID pgtype.UUID `json:"id"`
- AgentID pgtype.UUID `json:"agent_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- Status string `json:"status"`
- Priority int32 `json:"priority"`
- DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
- StartedAt pgtype.Timestamptz `json:"started_at"`
- CompletedAt pgtype.Timestamptz `json:"completed_at"`
- Result []byte `json:"result"`
- Error pgtype.Text `json:"error"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- Context []byte `json:"context"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
- Attempt int32 `json:"attempt"`
- MaxAttempts int32 `json:"max_attempts"`
- ParentTaskID pgtype.UUID `json:"parent_task_id"`
- FailureReason pgtype.Text `json:"failure_reason"`
- TriggerSummary pgtype.Text `json:"trigger_summary"`
- ForceFreshSession bool `json:"force_fresh_session"`
- 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"`
- PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`
- SquadID pgtype.UUID `json:"squad_id"`
- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
- EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
- FireAt pgtype.Timestamptz `json:"fire_at"`
- OriginatorUserID pgtype.UUID `json:"originator_user_id"`
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
- CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
- DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
- ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
+ ID pgtype.UUID `json:"id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Status string `json:"status"`
+ Priority int32 `json:"priority"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+ StartedAt pgtype.Timestamptz `json:"started_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ Result []byte `json:"result"`
+ Error pgtype.Text `json:"error"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Context []byte `json:"context"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID pgtype.UUID `json:"parent_task_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ ForceFreshSession bool `json:"force_fresh_session"`
+ 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"`
+ PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
+ DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
+ ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
+ ChatFinalizeDeferredAt pgtype.Timestamptz `json:"chat_finalize_deferred_at"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -706,6 +713,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -722,7 +730,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', '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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -773,6 +781,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -813,7 +822,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type ClaimAgentTaskParams struct {
@@ -872,6 +881,63 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ )
+ return i, err
+}
+
+const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
+UPDATE agent_task_queue
+SET chat_finalize_deferred_at = NULL
+WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
+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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
+`
+
+// Atomically claims the deferred marker so the daemon ack and the sweeper
+// cannot both finalize the same task (double-"Stopped." guard).
+func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, claimChatFinalizeDeferred, id)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1009,7 +1075,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULL
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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CompleteAgentTaskParams struct {
@@ -1066,6 +1132,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1266,7 +1333,7 @@ VALUES (
$14,
$15
)
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CreateAgentTaskParams struct {
@@ -1352,6 +1419,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1370,7 +1438,7 @@ VALUES (
$9,
$10
)
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CreateDeferredAgentTaskParams struct {
@@ -1442,6 +1510,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1457,7 +1526,7 @@ VALUES (
$6,
$7
)
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CreateQuickCreateTaskParams struct {
@@ -1523,6 +1592,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1553,7 +1623,7 @@ SELECT
p.chat_input_task_id
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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CreateRetryTaskParams struct {
@@ -1636,6 +1706,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1672,7 +1743,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, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_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, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at
`
type ExpireStaleQueuedTasksParams struct {
@@ -1751,6 +1822,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -1769,7 +1841,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -1824,6 +1896,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1838,7 +1911,7 @@ SET status = 'failed',
work_dir = COALESCE($5, work_dir),
prepare_lease_expires_at = NULL
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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type FailAgentTaskParams struct {
@@ -1906,6 +1979,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -1930,7 +2004,7 @@ WHERE (
AND r.last_seen_at >= now() - make_interval(secs => $3::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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type FailStaleTasksParams struct {
@@ -2024,6 +2098,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -2159,7 +2234,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
WHERE id = $1
`
@@ -2205,12 +2280,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
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, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_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, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -2269,6 +2345,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -2760,7 +2837,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -2818,6 +2895,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -2830,7 +2908,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -2883,6 +2961,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3000,8 +3079,84 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
return items, nil
}
+const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
+WHERE chat_finalize_deferred_at IS NOT NULL
+ AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
+ORDER BY chat_finalize_deferred_at
+LIMIT $2::int
+`
+
+type ListChatFinalizeDeferredExpiredParams struct {
+ GraceSecs float64 `json:"grace_secs"`
+ MaxPerTick int32 `json:"max_per_tick"`
+}
+
+// Deferred chat finalizations whose grace period elapsed without a daemon
+// ack (dead or partitioned daemon). Batch-capped like the other sweeper
+// queries so one tick can't monopolise the DB.
+func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListChatFinalizeDeferredExpiredParams) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, listChatFinalizeDeferredExpired, arg.GraceSecs, arg.MaxPerTick)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -3054,6 +3209,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3066,7 +3222,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -3127,6 +3283,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3139,7 +3296,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -3202,6 +3359,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3214,7 +3372,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -3267,6 +3425,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3279,15 +3438,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, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_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, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at 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, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_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, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_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, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at 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, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -3362,6 +3521,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3379,7 +3539,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -3439,6 +3599,63 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ )
+ return i, err
+}
+
+const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
+UPDATE agent_task_queue
+SET chat_finalize_deferred_at = now()
+WHERE 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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
+`
+
+// Arms the deferred chat-finalize marker for a cancelled chat task whose
+// empty-transcript judgment must wait for the daemon's flush ack (#5219).
+func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, markChatFinalizeDeferred, id)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -3545,7 +3762,7 @@ SET status = 'queued'
WHERE runtime_id = $1
AND status = 'deferred'
AND fire_at <= now()
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -3596,6 +3813,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3613,7 +3831,7 @@ SET status = 'queued'
WHERE runtime_id = ANY($1::uuid[])
AND status = 'deferred'
AND fire_at <= now()
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all
@@ -3666,6 +3884,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtim
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3692,7 +3911,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -3748,6 +3967,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -3767,7 +3987,7 @@ WHERE id IN (
LIMIT $4::int
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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -3837,6 +4057,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3857,7 +4078,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = 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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -3914,6 +4135,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -3981,7 +4203,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -4037,6 +4259,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
@@ -4135,7 +4358,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = 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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -4186,6 +4409,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.go
index 5f86451aad..fe56bb8cb4 100644
--- a/server/pkg/db/generated/attachment.sql.go
+++ b/server/pkg/db/generated/attachment.sql.go
@@ -593,6 +593,52 @@ func (q *Queries) ListAttachmentsByCommentIDs(ctx context.Context, arg ListAttac
return items, nil
}
+const listAttachmentsByIDs = `-- name: ListAttachmentsByIDs :many
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
+WHERE id = ANY($1::uuid[]) AND workspace_id = $2
+ORDER BY created_at ASC
+`
+
+type ListAttachmentsByIDsParams struct {
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) ListAttachmentsByIDs(ctx context.Context, arg ListAttachmentsByIDsParams) ([]Attachment, error) {
+ rows, err := q.db.Query(ctx, listAttachmentsByIDs, arg.AttachmentIds, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Attachment{}
+ for rows.Next() {
+ var i Attachment
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.CommentID,
+ &i.UploaderType,
+ &i.UploaderID,
+ &i.Filename,
+ &i.Url,
+ &i.ContentType,
+ &i.SizeBytes,
+ &i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
+ &i.TaskID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listAttachmentsByIssue = `-- name: ListAttachmentsByIssue :many
SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id FROM attachment
WHERE issue_id = $1 AND workspace_id = $2
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 108a199af9..ae06911970 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -227,7 +227,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CreateAutopilotTaskParams struct {
@@ -289,6 +289,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 249b1edc41..22ff627ecd 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -31,6 +31,44 @@ func (q *Queries) ChatSessionHasUserMessage(ctx context.Context, chatSessionID p
return has_user_message, err
}
+const createChatDraftRestore = `-- name: CreateChatDraftRestore :one
+INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)
+VALUES ($1, $2, $3, $4, $5)
+RETURNING id, chat_session_id, task_id, content, attachment_ids, created_at
+`
+
+type CreateChatDraftRestoreParams struct {
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Content string `json:"content"`
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+}
+
+// Persists the deferred-cancellation draft restore (#5219) in the same tx
+// that deletes the triggering user message: the chat:cancel_finalized
+// broadcast is best-effort, so an offline client recovers the draft from
+// this row instead. id is the deleted message's id.
+func (q *Queries) CreateChatDraftRestore(ctx context.Context, arg CreateChatDraftRestoreParams) (ChatDraftRestore, error) {
+ row := q.db.QueryRow(ctx, createChatDraftRestore,
+ arg.ID,
+ arg.ChatSessionID,
+ arg.TaskID,
+ arg.Content,
+ arg.AttachmentIds,
+ )
+ var i ChatDraftRestore
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.TaskID,
+ &i.Content,
+ &i.AttachmentIds,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const createChatMessage = `-- name: CreateChatMessage :one
INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms, message_kind)
VALUES ($1, $2, $3, $4, $5, $6, COALESCE($7::text, 'message'))
@@ -131,7 +169,7 @@ VALUES (
$8,
$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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CreateChatTaskParams struct {
@@ -198,10 +236,79 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
+const deleteChatDraftRestore = `-- name: DeleteChatDraftRestore :execrows
+DELETE FROM chat_draft_restore
+WHERE id = $1 AND chat_session_id = $2
+`
+
+type DeleteChatDraftRestoreParams struct {
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+}
+
+// Idempotent consume: deleting an already-consumed restore matches no row.
+func (q *Queries) DeleteChatDraftRestore(ctx context.Context, arg DeleteChatDraftRestoreParams) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteChatDraftRestore, arg.ID, arg.ChatSessionID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const deleteChatDraftRestoresByArchivedRuntimeAgents = `-- name: DeleteChatDraftRestoresByArchivedRuntimeAgents :exec
+DELETE FROM chat_draft_restore
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs
+ JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
+)
+`
+
+// chat_session cascades from agent, so hard-deleting a runtime's archived agents
+// silently drops their sessions — and, without an FK, would strand the pending
+// restores (which still hold the user's prompt text) forever. Prune them in the
+// same tx, BEFORE the agent rows go: the join below needs them. Mirrors
+// DeleteChannelInstallationsByArchivedRuntimeAgents.
+func (q *Queries) DeleteChatDraftRestoresByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChatDraftRestoresByArchivedRuntimeAgents, runtimeID)
+ return err
+}
+
+const deleteChatDraftRestoresBySession = `-- name: DeleteChatDraftRestoresBySession :exec
+DELETE FROM chat_draft_restore
+WHERE chat_session_id = $1
+`
+
+// chat_draft_restore carries no chat_session FK (MUL-3515), so DeleteChatSession
+// prunes its pending restores in the same tx that deletes the session.
+func (q *Queries) DeleteChatDraftRestoresBySession(ctx context.Context, chatSessionID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChatDraftRestoresBySession, chatSessionID)
+ return err
+}
+
+const deleteChatDraftRestoresBySystemRuntimeAgents = `-- name: DeleteChatDraftRestoresBySystemRuntimeAgents :exec
+DELETE FROM chat_draft_restore
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs
+ JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.kind = 'system'
+)
+`
+
+// Same cascade, for the system agents a runtime teardown also hard-deletes
+// (DeleteSystemAgentsByRuntime). Split from the archived-agent prune because the
+// runtime-profile teardown deletes only archived agents: pruning system-agent
+// sessions there would destroy restores whose session survives.
+func (q *Queries) DeleteChatDraftRestoresBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChatDraftRestoresBySystemRuntimeAgents, runtimeID)
+ return err
+}
+
const deleteChatSession = `-- name: DeleteChatSession :exec
DELETE FROM chat_session WHERE id = $1 AND workspace_id = $2
`
@@ -574,6 +681,39 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC
return items, nil
}
+const listChatDraftRestoresBySession = `-- name: ListChatDraftRestoresBySession :many
+SELECT id, chat_session_id, task_id, content, attachment_ids, created_at FROM chat_draft_restore
+WHERE chat_session_id = $1
+ORDER BY created_at ASC
+`
+
+func (q *Queries) ListChatDraftRestoresBySession(ctx context.Context, chatSessionID pgtype.UUID) ([]ChatDraftRestore, error) {
+ rows, err := q.db.Query(ctx, listChatDraftRestoresBySession, chatSessionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChatDraftRestore{}
+ for rows.Next() {
+ var i ChatDraftRestore
+ if err := rows.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.TaskID,
+ &i.Content,
+ &i.AttachmentIds,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listChatInputMessages = `-- name: ListChatInputMessages :many
SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
WHERE task_id = $1 AND role = 'user'
@@ -882,6 +1022,133 @@ func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID)
return id_2, err
}
+const lockChatSessionForTask = `-- name: LockChatSessionForTask :one
+
+SELECT cs.id
+FROM agent_task_queue t
+JOIN chat_session cs ON cs.id = t.chat_session_id
+WHERE t.id = $1
+FOR UPDATE OF cs
+`
+
+// The chat_session row lock is the mutual-exclusion protocol between the
+// draft-restore writer (FinalizeDeferredCancelledChat) and every deleter of a
+// chat_session or one of its cascade parents. Without an FK, an INSERT into
+// chat_draft_restore takes no lock on its session, so a prune-then-delete would
+// otherwise miss a restore committed after its snapshot and strand it — with the
+// user's prompt in it — forever (#5219).
+//
+// The contract, held by all five paths below:
+//
+// deleter: lock the sessions FOR UPDATE -> prune restores -> delete the parent
+// finalizer: lock the session FOR UPDATE -> insert the restore
+//
+// Whoever locks first wins: a finalizer that got there first commits its row
+// before the deleter's prune statement takes its snapshot, so the prune sweeps
+// it; a deleter that got there first leaves no session for the finalizer to
+// lock, so it never inserts.
+//
+// Lock order is chat_session -> agent_task_queue everywhere (the finalizer locks
+// the session before claiming its task) so the deleters' cascade into
+// agent_task_queue cannot deadlock against it.
+//
+// The single-session delete path needs no new query: it already holds
+// LockChatSessionForDelete (same FOR UPDATE row lock) across its prune.
+// The finalizer's half of the protocol. No rows means the session is already
+// gone (its cascade NULLs agent_task_queue.chat_session_id), so there is nothing
+// to lock and nothing to restore into.
+func (q *Queries) LockChatSessionForTask(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockChatSessionForTask, id)
+ var id_2 pgtype.UUID
+ err := row.Scan(&id_2)
+ return id_2, err
+}
+
+const lockChatSessionsByArchivedRuntimeAgents = `-- name: LockChatSessionsByArchivedRuntimeAgents :many
+SELECT cs.id FROM chat_session cs
+JOIN agent a ON a.id = cs.agent_id
+WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
+ORDER BY cs.id
+FOR UPDATE OF cs
+`
+
+func (q *Queries) LockChatSessionsByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, lockChatSessionsByArchivedRuntimeAgents, runtimeID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const lockChatSessionsBySystemRuntimeAgents = `-- name: LockChatSessionsBySystemRuntimeAgents :many
+SELECT cs.id FROM chat_session cs
+JOIN agent a ON a.id = cs.agent_id
+WHERE a.runtime_id = $1 AND a.kind = 'system'
+ORDER BY cs.id
+FOR UPDATE OF cs
+`
+
+func (q *Queries) LockChatSessionsBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, lockChatSessionsBySystemRuntimeAgents, runtimeID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const lockChatSessionsByWorkspace = `-- name: LockChatSessionsByWorkspace :many
+SELECT id FROM chat_session
+WHERE workspace_id = $1
+ORDER BY id
+FOR UPDATE
+`
+
+// ORDER BY id: a stable lock order keeps two concurrent deleters from
+// deadlocking against each other.
+func (q *Queries) LockChatSessionsByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, lockChatSessionsByWorkspace, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const markChatSessionRead = `-- name: MarkChatSessionRead :exec
UPDATE chat_session SET last_read_at = now()
WHERE id = $1
@@ -977,7 +1244,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE 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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -1028,6 +1295,7 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 487a07f6fc..0265ba98da 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -127,10 +127,11 @@ type AgentTaskQueue struct {
// Top-of-chain human originator for this run. For human-triggered tasks (comment by a member, chat, quick-create) equals that member. For agent-fanout tasks inherited from the parent task's originator_user_id via comment.source_task_id. NULL when no human is in the chain (autopilot, system-driven). Used by canInvokeAgent to judge A2A by the originator; the Composio overlay now follows invocation permission and uses the agent owner's connection, so this is audit/attribution + A2A gating, NOT a Composio owner==originator gate (MUL-3963).
OriginatorUserID pgtype.UUID `json:"originator_user_id"`
// Non-secret per-task connected app metadata corresponding to runtime_mcp_overlay, used by the daemon brief to tell agents which app capabilities are mounted. Cleared with runtime_mcp_overlay after task completion.
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
- CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
- DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
- ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
+ DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
+ ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
+ ChatFinalizeDeferredAt pgtype.Timestamptz `json:"chat_finalize_deferred_at"`
}
type AgentToLabel struct {
@@ -308,6 +309,15 @@ type ChannelUserBinding struct {
BoundAt pgtype.Timestamptz `json:"bound_at"`
}
+type ChatDraftRestore struct {
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Content string `json:"content"`
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type ChatMessage struct {
ID pgtype.UUID `json:"id"`
ChatSessionID pgtype.UUID `json:"chat_session_id"`
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 4f931c6826..74b61d818d 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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -86,6 +86,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
@@ -217,7 +218,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, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_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, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -271,6 +272,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index 91ba25ab39..a15cbcbe6a 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -78,6 +78,19 @@ cleared_outbound_cards AS (
DELETE FROM channel_outbound_card_message
WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
),
+cleared_draft_restores AS (
+ -- chat_draft_restore is keyed by chat_session_id with no FK (MUL-3515) and has
+ -- no reaper, while its chat_session rows cascade away with the workspace. Reach
+ -- them directly through chat_session (unlike the cards above, this is not
+ -- limited to channel-bound sessions) or every pending restore — each holding a
+ -- user's prompt text — would outlive the workspace permanently (#5219).
+ --
+ -- This sweep only sees restores committed before the statement's snapshot, so
+ -- the caller must already hold LockChatSessionsByWorkspace: that lock is what
+ -- keeps FinalizeDeferredCancelledChat from inserting one behind it.
+ DELETE FROM chat_draft_restore
+ WHERE chat_session_id IN (SELECT id FROM chat_session WHERE workspace_id = $1)
+),
cleared_inbound_dedup AS (
DELETE FROM channel_inbound_message_dedup WHERE installation_id IN (SELECT id FROM ws_installations)
),
@@ -274,6 +287,50 @@ func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Wor
return items, nil
}
+const lockWorkspaceForChatSessionCreate = `-- name: LockWorkspaceForChatSessionCreate :one
+SELECT id FROM workspace WHERE id = $1 FOR KEY SHARE
+`
+
+// The creator half of the workspace delete/create protocol (#5219). Every
+// production path that inserts a chat_session takes this FOR KEY SHARE lock on the
+// parent workspace row, inside its transaction, before CreateChatSession. It
+// conflicts with DeleteWorkspace's FOR UPDATE (so a create is blocked while a
+// delete is in progress, and vice versa) but not with other creators (FOR KEY
+// SHARE locks share), so concurrent session creation stays unserialized. This
+// makes the mutual exclusion explicit rather than leaning on the workspace FK's
+// implicit FOR KEY SHARE, which would vanish if that FK is dropped.
+func (q *Queries) LockWorkspaceForChatSessionCreate(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockWorkspaceForChatSessionCreate, id)
+ var id_2 pgtype.UUID
+ err := row.Scan(&id_2)
+ return id_2, err
+}
+
+const lockWorkspaceForDelete = `-- name: LockWorkspaceForDelete :one
+SELECT id FROM workspace WHERE id = $1 FOR UPDATE
+`
+
+// Taken first by DeleteWorkspace, before it enumerates the workspace's chat
+// sessions. LockChatSessionsByWorkspace only covers sessions that exist when it
+// runs; a CreateChatSession committing during the delete window would add one
+// the lock set never saw, and a finalizer could then insert a restore for it
+// after the sweep's snapshot — orphaning the prompt (#5219).
+//
+// The delete window is held closed against new sessions by an EXPLICIT protocol,
+// not the chat_session.workspace_id FK: every session creator takes
+// LockWorkspaceForChatSessionCreate (FOR KEY SHARE) on this row first, and this
+// FOR UPDATE conflicts with it. Keeping the bar in the app layer means it does
+// not silently break if that FK is ever dropped (the codebase is moving FK
+// relationships into the application layer, MUL-3515). Lock order is
+// workspace -> chat_session -> agent_task_queue; the finalizer never touches
+// workspace, so this cannot deadlock against it.
+func (q *Queries) LockWorkspaceForDelete(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockWorkspaceForDelete, id)
+ var id_2 pgtype.UUID
+ err := row.Scan(&id_2)
+ return id_2, err
+}
+
const updateWorkspace = `-- name: UpdateWorkspace :one
UPDATE workspace SET
name = COALESCE($2, name),
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index e4e141028a..cdd2ea1c7d 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -784,6 +784,32 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
+-- name: MarkChatFinalizeDeferred :one
+-- Arms the deferred chat-finalize marker for a cancelled chat task whose
+-- empty-transcript judgment must wait for the daemon's flush ack (#5219).
+UPDATE agent_task_queue
+SET chat_finalize_deferred_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: ClaimChatFinalizeDeferred :one
+-- Atomically claims the deferred marker so the daemon ack and the sweeper
+-- cannot both finalize the same task (double-"Stopped." guard).
+UPDATE agent_task_queue
+SET chat_finalize_deferred_at = NULL
+WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
+RETURNING *;
+
+-- name: ListChatFinalizeDeferredExpired :many
+-- Deferred chat finalizations whose grace period elapsed without a daemon
+-- ack (dead or partitioned daemon). Batch-capped like the other sweeper
+-- queries so one tick can't monopolise the DB.
+SELECT * FROM agent_task_queue
+WHERE chat_finalize_deferred_at IS NOT NULL
+ AND chat_finalize_deferred_at < now() - make_interval(secs => @grace_secs::double precision)
+ORDER BY chat_finalize_deferred_at
+LIMIT @max_per_tick::int;
+
-- name: CountRunningTasks :one
SELECT count(*) FROM agent_task_queue
WHERE agent_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory');
diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sql
index c352404f98..b92cebce42 100644
--- a/server/pkg/db/queries/attachment.sql
+++ b/server/pkg/db/queries/attachment.sql
@@ -140,3 +140,8 @@ WHERE workspace_id = $2
-- name: DeleteAttachment :exec
DELETE FROM attachment WHERE id = $1 AND workspace_id = $2;
+
+-- name: ListAttachmentsByIDs :many
+SELECT * FROM attachment
+WHERE id = ANY(sqlc.arg(attachment_ids)::uuid[]) AND workspace_id = sqlc.arg(workspace_id)
+ORDER BY created_at ASC;
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 56f2600c28..cdf09c7119 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -325,3 +325,107 @@ SELECT EXISTS (
SELECT 1 FROM chat_message
WHERE chat_session_id = $1 AND role = 'user'
) AS has_user_message;
+
+-- name: CreateChatDraftRestore :one
+-- Persists the deferred-cancellation draft restore (#5219) in the same tx
+-- that deletes the triggering user message: the chat:cancel_finalized
+-- broadcast is best-effort, so an offline client recovers the draft from
+-- this row instead. id is the deleted message's id.
+INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)
+VALUES ($1, $2, $3, $4, $5)
+RETURNING *;
+
+-- name: ListChatDraftRestoresBySession :many
+SELECT * FROM chat_draft_restore
+WHERE chat_session_id = $1
+ORDER BY created_at ASC;
+
+-- name: DeleteChatDraftRestore :execrows
+-- Idempotent consume: deleting an already-consumed restore matches no row.
+DELETE FROM chat_draft_restore
+WHERE id = $1 AND chat_session_id = $2;
+
+-- name: DeleteChatDraftRestoresBySession :exec
+-- chat_draft_restore carries no chat_session FK (MUL-3515), so DeleteChatSession
+-- prunes its pending restores in the same tx that deletes the session.
+DELETE FROM chat_draft_restore
+WHERE chat_session_id = $1;
+
+-- The chat_session row lock is the mutual-exclusion protocol between the
+-- draft-restore writer (FinalizeDeferredCancelledChat) and every deleter of a
+-- chat_session or one of its cascade parents. Without an FK, an INSERT into
+-- chat_draft_restore takes no lock on its session, so a prune-then-delete would
+-- otherwise miss a restore committed after its snapshot and strand it — with the
+-- user's prompt in it — forever (#5219).
+--
+-- The contract, held by all five paths below:
+-- deleter: lock the sessions FOR UPDATE -> prune restores -> delete the parent
+-- finalizer: lock the session FOR UPDATE -> insert the restore
+-- Whoever locks first wins: a finalizer that got there first commits its row
+-- before the deleter's prune statement takes its snapshot, so the prune sweeps
+-- it; a deleter that got there first leaves no session for the finalizer to
+-- lock, so it never inserts.
+--
+-- Lock order is chat_session -> agent_task_queue everywhere (the finalizer locks
+-- the session before claiming its task) so the deleters' cascade into
+-- agent_task_queue cannot deadlock against it.
+--
+-- The single-session delete path needs no new query: it already holds
+-- LockChatSessionForDelete (same FOR UPDATE row lock) across its prune.
+
+-- name: LockChatSessionForTask :one
+-- The finalizer's half of the protocol. No rows means the session is already
+-- gone (its cascade NULLs agent_task_queue.chat_session_id), so there is nothing
+-- to lock and nothing to restore into.
+SELECT cs.id
+FROM agent_task_queue t
+JOIN chat_session cs ON cs.id = t.chat_session_id
+WHERE t.id = $1
+FOR UPDATE OF cs;
+
+-- name: LockChatSessionsByWorkspace :many
+-- ORDER BY id: a stable lock order keeps two concurrent deleters from
+-- deadlocking against each other.
+SELECT id FROM chat_session
+WHERE workspace_id = $1
+ORDER BY id
+FOR UPDATE;
+
+-- name: LockChatSessionsByArchivedRuntimeAgents :many
+SELECT cs.id FROM chat_session cs
+JOIN agent a ON a.id = cs.agent_id
+WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
+ORDER BY cs.id
+FOR UPDATE OF cs;
+
+-- name: LockChatSessionsBySystemRuntimeAgents :many
+SELECT cs.id FROM chat_session cs
+JOIN agent a ON a.id = cs.agent_id
+WHERE a.runtime_id = $1 AND a.kind = 'system'
+ORDER BY cs.id
+FOR UPDATE OF cs;
+
+-- name: DeleteChatDraftRestoresByArchivedRuntimeAgents :exec
+-- chat_session cascades from agent, so hard-deleting a runtime's archived agents
+-- silently drops their sessions — and, without an FK, would strand the pending
+-- restores (which still hold the user's prompt text) forever. Prune them in the
+-- same tx, BEFORE the agent rows go: the join below needs them. Mirrors
+-- DeleteChannelInstallationsByArchivedRuntimeAgents.
+DELETE FROM chat_draft_restore
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs
+ JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.archived_at IS NOT NULL
+);
+
+-- name: DeleteChatDraftRestoresBySystemRuntimeAgents :exec
+-- Same cascade, for the system agents a runtime teardown also hard-deletes
+-- (DeleteSystemAgentsByRuntime). Split from the archived-agent prune because the
+-- runtime-profile teardown deletes only archived agents: pruning system-agent
+-- sessions there would destroy restores whose session survives.
+DELETE FROM chat_draft_restore
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs
+ JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.kind = 'system'
+);
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index c79ccab103..e04837730b 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -56,6 +56,34 @@ UPDATE workspace SET issue_counter = issue_counter + 1
WHERE id = $1
RETURNING issue_counter;
+-- name: LockWorkspaceForDelete :one
+-- Taken first by DeleteWorkspace, before it enumerates the workspace's chat
+-- sessions. LockChatSessionsByWorkspace only covers sessions that exist when it
+-- runs; a CreateChatSession committing during the delete window would add one
+-- the lock set never saw, and a finalizer could then insert a restore for it
+-- after the sweep's snapshot — orphaning the prompt (#5219).
+--
+-- The delete window is held closed against new sessions by an EXPLICIT protocol,
+-- not the chat_session.workspace_id FK: every session creator takes
+-- LockWorkspaceForChatSessionCreate (FOR KEY SHARE) on this row first, and this
+-- FOR UPDATE conflicts with it. Keeping the bar in the app layer means it does
+-- not silently break if that FK is ever dropped (the codebase is moving FK
+-- relationships into the application layer, MUL-3515). Lock order is
+-- workspace -> chat_session -> agent_task_queue; the finalizer never touches
+-- workspace, so this cannot deadlock against it.
+SELECT id FROM workspace WHERE id = $1 FOR UPDATE;
+
+-- name: LockWorkspaceForChatSessionCreate :one
+-- The creator half of the workspace delete/create protocol (#5219). Every
+-- production path that inserts a chat_session takes this FOR KEY SHARE lock on the
+-- parent workspace row, inside its transaction, before CreateChatSession. It
+-- conflicts with DeleteWorkspace's FOR UPDATE (so a create is blocked while a
+-- delete is in progress, and vice versa) but not with other creators (FOR KEY
+-- SHARE locks share), so concurrent session creation stays unserialized. This
+-- makes the mutual exclusion explicit rather than leaning on the workspace FK's
+-- implicit FOR KEY SHARE, which would vanish if that FK is dropped.
+SELECT id FROM workspace WHERE id = $1 FOR KEY SHARE;
+
-- name: DeleteWorkspace :exec
-- The channel_* tables (MUL-3515 §4) and resource-label junctions carry NO FK to
-- workspace, so — unlike the CASCADE-backed tables the DELETE below sweeps —
@@ -87,6 +115,19 @@ cleared_outbound_cards AS (
DELETE FROM channel_outbound_card_message
WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
),
+cleared_draft_restores AS (
+ -- chat_draft_restore is keyed by chat_session_id with no FK (MUL-3515) and has
+ -- no reaper, while its chat_session rows cascade away with the workspace. Reach
+ -- them directly through chat_session (unlike the cards above, this is not
+ -- limited to channel-bound sessions) or every pending restore — each holding a
+ -- user's prompt text — would outlive the workspace permanently (#5219).
+ --
+ -- This sweep only sees restores committed before the statement's snapshot, so
+ -- the caller must already hold LockChatSessionsByWorkspace: that lock is what
+ -- keeps FinalizeDeferredCancelledChat from inserting one behind it.
+ DELETE FROM chat_draft_restore
+ WHERE chat_session_id IN (SELECT id FROM chat_session WHERE workspace_id = $1)
+),
cleared_inbound_dedup AS (
DELETE FROM channel_inbound_message_dedup WHERE installation_id IN (SELECT id FROM ws_installations)
),
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index c5e7e82490..9cbf273c87 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -69,11 +69,17 @@ const (
EventSkillDeleted = "skill:deleted"
// Chat events
- EventChatMessage = "chat:message"
- EventChatDone = "chat:done"
- EventChatSessionRead = "chat:session_read"
- EventChatSessionDeleted = "chat:session_deleted"
- EventChatSessionUpdated = "chat:session_updated"
+ EventChatMessage = "chat:message"
+ EventChatDone = "chat:done"
+ // EventChatCancelFinalized carries the deferred outcome of a cancelled
+ // chat task once the daemon has flushed its transcript (or the sweeper
+ // grace period expired): either a late "Stopped." assistant message or a
+ // draft restore (#5219). Channel outbounds (Slack/Lark) deliberately do
+ // not subscribe to it — cancellation stays silent on external channels.
+ EventChatCancelFinalized = "chat:cancel_finalized"
+ EventChatSessionRead = "chat:session_read"
+ EventChatSessionDeleted = "chat:session_deleted"
+ EventChatSessionUpdated = "chat:session_updated"
// Project events
EventProjectCreated = "project:created"
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 228415e84d..e29b5c0735 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -10,6 +10,15 @@ const (
// Gated so only daemons+servers that both support it route claim over WS;
// everyone else keeps using the HTTP claim endpoint.
DaemonCapabilityRPCV1 = "rpc-v1"
+
+ // AppCapabilityChatDraftRestoreV1 is advertised (X-Client-Capabilities) by
+ // app clients that understand the durable draft-restore recovery path:
+ // chat:cancel_finalized as an invalidation hint plus the draft-restores
+ // endpoint. Cancelling a started-but-empty chat task defers the
+ // empty/non-empty judgment (#5219), so its cancel response carries no
+ // synchronous restore — a client without this capability would silently
+ // drop the user's prompt, and keeps the legacy synchronous restore instead.
+ AppCapabilityChatDraftRestoreV1 = "chat-draft-restore-v1"
)
// RPCRequestPayload is the generic daemon→server request envelope carried in a
@@ -161,6 +170,45 @@ type ChatDonePayload struct {
MessageKind string `json:"message_kind,omitempty"`
}
+// Outcome values carried by ChatCancelFinalizedPayload.
+const (
+ // ChatCancelOutcomeStopped: the transcript turned out non-empty, so a
+ // "Stopped." assistant message was persisted.
+ ChatCancelOutcomeStopped = "stopped"
+ // ChatCancelOutcomeRestored: the transcript stayed empty, so the
+ // triggering user message was deleted and its content should be
+ // restored into the composer as a draft.
+ ChatCancelOutcomeRestored = "restored"
+)
+
+// ChatCancelFinalizedPayload is broadcast when a cancelled chat task's
+// deferred finalization settles (#5219). The cancel HTTP response cannot
+// carry this outcome — it is only known after the daemon's transcript flush —
+// so clients react to this event instead: outcome "stopped" inserts the
+// assistant message (MessageID/Content/... describe the new row, shaped like
+// ChatDonePayload), outcome "restored" removes the deleted user message from
+// caches and prompts the initiator's client to fetch the durable draft
+// restore from the creator-authorized endpoint. The restored prompt's content
+// and attachments deliberately never ride this workspace-wide broadcast.
+type ChatCancelFinalizedPayload struct {
+ Outcome string `json:"outcome"`
+ ChatSessionID string `json:"chat_session_id"`
+ TaskID string `json:"task_id"`
+ // InitiatorUserID is the human who triggered the cancelled task. Only
+ // this user's client needs to fetch the draft restore (the endpoint is
+ // creator-authorized regardless); clients treat a missing value as
+ // "not me".
+ InitiatorUserID string `json:"initiator_user_id,omitempty"`
+ MessageID string `json:"message_id,omitempty"`
+ // Content/MessageKind/CreatedAt/ElapsedMs describe the persisted
+ // "Stopped." assistant row and are set only for outcome "stopped" —
+ // the same exposure surface as chat:done.
+ Content string `json:"content,omitempty"`
+ MessageKind string `json:"message_kind,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
+ ElapsedMs int64 `json:"elapsed_ms,omitempty"`
+}
+
// ChatSessionReadPayload is broadcast when the creator marks a session as read.
// Fires to other devices so their unread counts stay in sync.
type ChatSessionReadPayload struct {