Skip to content

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

Go

feat(chat): support deleting chat sessions (#2115)

Bohan Jiang60b215f44f38
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 79d1aa44b3..f5e8e95184 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1009,7 +1009,7 @@ export class ApiClient {
});
}
- async archiveChatSession(id: string): Promise<void> {
+ async deleteChatSession(id: string): Promise<void> {
await this.fetch(`/api/chat/sessions/${id}`, { method: "DELETE" });
}
diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.ts
index 2c25212295..1cb7994f7e 100644
--- a/packages/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -70,14 +70,20 @@ export function useMarkChatSessionRead() {
});
}
-export function useArchiveChatSession() {
+/**
+ * Hard-deletes a chat session. Optimistically removes the row from both
+ * the active and all-sessions lists so the history panel updates instantly;
+ * rolls back on error. The matching `chat:session_deleted` WS event keeps
+ * other tabs/devices in sync — see use-realtime-sync.ts.
+ */
+export function useDeleteChatSession() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
return useMutation({
mutationFn: (sessionId: string) => {
- logger.info("archiveChatSession.start", { sessionId });
- return api.archiveChatSession(sessionId);
+ logger.info("deleteChatSession.start", { sessionId });
+ return api.deleteChatSession(sessionId);
},
onMutate: async (sessionId) => {
await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
@@ -86,26 +92,20 @@ export function useArchiveChatSession() {
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
const prevAll = qc.getQueryData<ChatSession[]>(chatKeys.allSessions(wsId));
- // Optimistic: remove from active, mark as archived in allSessions
- qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) =>
- old ? old.filter((s) => s.id !== sessionId) : old,
- );
- qc.setQueryData<ChatSession[]>(chatKeys.allSessions(wsId), (old) =>
- old?.map((s) =>
- s.id === sessionId ? { ...s, status: "archived" as const } : s,
- ),
- );
+ const drop = (old?: ChatSession[]) => old?.filter((s) => s.id !== sessionId);
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), drop);
+ qc.setQueryData<ChatSession[]>(chatKeys.allSessions(wsId), drop);
- logger.debug("archiveChatSession.optimistic", { sessionId });
+ logger.debug("deleteChatSession.optimistic", { sessionId });
return { prevSessions, prevAll };
},
onError: (err, sessionId, ctx) => {
- logger.error("archiveChatSession.error.rollback", { sessionId, err });
+ logger.error("deleteChatSession.error.rollback", { sessionId, err });
if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
if (ctx?.prevAll) qc.setQueryData(chatKeys.allSessions(wsId), ctx.prevAll);
},
onSettled: (_data, _err, sessionId) => {
- logger.debug("archiveChatSession.settled", { sessionId });
+ logger.debug("deleteChatSession.settled", { sessionId });
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
qc.invalidateQueries({ queryKey: chatKeys.allSessions(wsId) });
},
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 6735cc1436..1c5577bde7 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -30,6 +30,7 @@ import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueD
import { inboxKeys } from "../inbox/queries";
import { workspaceKeys, workspaceListOptions } from "../workspace/queries";
import { chatKeys } from "../chat/queries";
+import { useChatStore } from "../chat";
import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
MemberAddedPayload,
@@ -206,7 +207,7 @@ 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:message", "chat:done", "chat:session_read", "chat:session_deleted",
// 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
@@ -625,6 +626,31 @@ export function useRealtimeSync(
invalidateSessionLists();
});
+ // chat:session_deleted fires after a hard delete. The originating tab has
+ // already optimistically dropped the row via useDeleteChatSession; this
+ // handler keeps OTHER tabs/devices in sync and also clears the active
+ // session pointer so a deleted session doesn't keep the chat window
+ // pointed at vanished messages.
+ const unsubChatSessionDeleted = ws.on("chat:session_deleted", (p) => {
+ const payload = p as { chat_session_id: string };
+ chatWsLogger.info("chat:session_deleted (global)", payload);
+ const id = getCurrentWsId();
+ if (id) {
+ const drop = (old?: { id: string }[]) =>
+ old?.filter((s) => s.id !== payload.chat_session_id);
+ qc.setQueryData(chatKeys.sessions(id), drop);
+ qc.setQueryData(chatKeys.allSessions(id), drop);
+ }
+ qc.removeQueries({ queryKey: chatKeys.messages(payload.chat_session_id) });
+ qc.removeQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
+ invalidatePendingAggregate();
+
+ const chatState = useChatStore.getState?.();
+ if (chatState && chatState.activeSessionId === payload.chat_session_id) {
+ chatState.setActiveSession(null);
+ }
+ });
+
return () => {
unsubAny();
unsubIssueUpdated();
@@ -658,6 +684,7 @@ export function useRealtimeSync(
unsubTaskCompleted();
unsubTaskFailed();
unsubChatSessionRead();
+ unsubChatSessionDeleted();
timers.forEach(clearTimeout);
timers.clear();
};
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 93ed6664c5..db6554bf5d 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -51,6 +51,7 @@ export type WSEventType =
| "chat:message"
| "chat:done"
| "chat:session_read"
+ | "chat:session_deleted"
| "project:created"
| "project:updated"
| "project:deleted"
@@ -280,6 +281,10 @@ export interface ChatSessionReadPayload {
chat_session_id: string;
}
+export interface ChatSessionDeletedPayload {
+ chat_session_id: string;
+}
+
export interface ProjectCreatedPayload {
project: Project;
}
diff --git a/packages/views/chat/components/chat-session-history.tsx b/packages/views/chat/components/chat-session-history.tsx
index fe731785fc..5b021c51fe 100644
--- a/packages/views/chat/components/chat-session-history.tsx
+++ b/packages/views/chat/components/chat-session-history.tsx
@@ -1,15 +1,27 @@
"use client";
+import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import { ArrowLeft, MessageSquare, Bot } from "lucide-react";
+import { ArrowLeft, MessageSquare, Bot, Trash2 } from "lucide-react";
import { cn } from "@multica/ui/lib/utils";
import { Button } from "@multica/ui/components/ui/button";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
import { Avatar, AvatarFallback, AvatarImage } from "@multica/ui/components/ui/avatar";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
import { useWorkspaceId } from "@multica/core/hooks";
import { agentListOptions } from "@multica/core/workspace/queries";
import { allChatSessionsOptions } from "@multica/core/chat/queries";
import { useChatStore } from "@multica/core/chat";
+import { useDeleteChatSession } from "@multica/core/chat/mutations";
import { createLogger } from "@multica/core/logger";
import type { ChatSession, Agent } from "@multica/core/types";
@@ -24,6 +36,9 @@ export function ChatSessionHistory() {
const { data: sessions = [] } = useQuery(allChatSessionsOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const deleteSession = useDeleteChatSession();
+ const [pendingDelete, setPendingDelete] = useState<ChatSession | null>(null);
+
const agentMap = new Map(agents.map((a) => [a.id, a]));
const handleSelectSession = (session: ChatSession) => {
@@ -39,6 +54,21 @@ export function ChatSessionHistory() {
setShowHistory(false);
};
+ const handleConfirmDelete = () => {
+ if (!pendingDelete) return;
+ const sessionId = pendingDelete.id;
+ logger.info("deleteSession.confirm", { sessionId });
+ // Clear the active pointer locally so the chat window doesn't keep
+ // pointing at a session we're about to remove. Other tabs are handled
+ // by the chat:session_deleted WS handler.
+ if (activeSessionId === sessionId) {
+ setActiveSession(null);
+ }
+ deleteSession.mutate(sessionId, {
+ onSettled: () => setPendingDelete(null),
+ });
+ };
+
return (
<div className="flex flex-1 flex-col overflow-hidden">
{/* Header */}
@@ -77,11 +107,41 @@ export function ChatSessionHistory() {
agent={agentMap.get(session.agent_id) ?? null}
isActive={session.id === activeSessionId}
onSelect={() => handleSelectSession(session)}
+ onRequestDelete={() => setPendingDelete(session)}
/>
))}
</div>
)}
</div>
+
+ <AlertDialog
+ open={!!pendingDelete}
+ onOpenChange={(open) => {
+ if (!open && !deleteSession.isPending) setPendingDelete(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete chat session</AlertDialogTitle>
+ <AlertDialogDescription>
+ {pendingDelete?.title
+ ? `"${pendingDelete.title}" and its messages will be permanently removed.`
+ : "This chat session and its messages will be permanently removed."}
+ {" "}This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={deleteSession.isPending}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleConfirmDelete}
+ disabled={deleteSession.isPending}
+ className="bg-destructive text-white hover:bg-destructive/90"
+ >
+ {deleteSession.isPending ? "Deleting..." : "Delete"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
);
}
@@ -91,44 +151,70 @@ function SessionItem({
agent,
isActive,
onSelect,
+ onRequestDelete,
}: {
session: ChatSession;
agent: Agent | null;
isActive: boolean;
onSelect: () => void;
+ onRequestDelete: () => void;
}) {
const timeAgo = formatTimeAgo(session.updated_at);
return (
- <button
- onClick={onSelect}
+ <div
className={cn(
- "flex w-full items-start gap-3 px-4 py-2.5 text-left transition-colors hover:bg-accent/50",
+ "group relative flex w-full items-start gap-3 px-4 py-2.5 text-left transition-colors hover:bg-accent/50",
isActive && "bg-accent/30",
)}
>
- <Avatar className="size-6 shrink-0 mt-0.5">
- {agent?.avatar_url && <AvatarImage src={agent.avatar_url} />}
- <AvatarFallback className="bg-purple-100 text-purple-700">
- <Bot className="size-3" />
- </AvatarFallback>
- </Avatar>
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span className="truncate text-sm font-medium">
- {session.title || "Untitled"}
- </span>
- </div>
- <div className="flex items-center gap-1.5 mt-0.5">
- {agent && (
- <span className="text-xs text-muted-foreground truncate">
- {agent.name}
+ <button
+ type="button"
+ onClick={onSelect}
+ className="flex flex-1 items-start gap-3 min-w-0 text-left"
+ >
+ <Avatar className="size-6 shrink-0 mt-0.5">
+ {agent?.avatar_url && <AvatarImage src={agent.avatar_url} />}
+ <AvatarFallback className="bg-purple-100 text-purple-700">
+ <Bot className="size-3" />
+ </AvatarFallback>
+ </Avatar>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-sm font-medium">
+ {session.title || "Untitled"}
</span>
- )}
- <span className="text-xs text-muted-foreground/60">{timeAgo}</span>
+ </div>
+ <div className="flex items-center gap-1.5 mt-0.5">
+ {agent && (
+ <span className="text-xs text-muted-foreground truncate">
+ {agent.name}
+ </span>
+ )}
+ <span className="text-xs text-muted-foreground/60">{timeAgo}</span>
+ </div>
</div>
- </div>
- </button>
+ </button>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 hover:text-destructive"
+ onClick={(e) => {
+ e.stopPropagation();
+ onRequestDelete();
+ }}
+ aria-label="Delete chat session"
+ />
+ }
+ >
+ <Trash2 className="size-3.5" />
+ </TooltipTrigger>
+ <TooltipContent side="left">Delete</TooltipContent>
+ </Tooltip>
+ </div>
);
}
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 9ec45d3168..3e24f11cef 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -83,7 +83,10 @@ export function ChatWindow() {
);
const pendingTaskId = pendingTask?.task_id ?? null;
- // Check if current session is archived
+ // Legacy archived sessions (the old soft-archive feature was removed but
+ // pre-existing rows with status='archived' may still exist) render as
+ // read-only: history list keeps showing them, but ChatInput is disabled
+ // and the server still rejects POST /messages for them.
const currentSession = activeSessionId
? allSessions.find((s) => s.id === activeSessionId)
: null;
@@ -470,7 +473,7 @@ export function ChatWindow() {
<OfflineBanner agentName={activeAgent?.name} availability={availability} />
)}
- {/* Input — disabled for archived sessions; locked out entirely
+ {/* Input — disabled for legacy archived sessions; locked out entirely
* when there's no agent (the EmptyState above carries the CTA). */}
<ChatInput
onSend={handleSend}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index aeaf4176a5..28e7e506bc 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -478,7 +478,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.ListChatSessions)
r.Route("/{sessionId}", func(r chi.Router) {
r.Get("/", h.GetChatSession)
- r.Delete("/", h.ArchiveChatSession)
+ r.Delete("/", h.DeleteChatSession)
r.Post("/messages", h.SendChatMessage)
r.Get("/messages", h.ListChatMessages)
r.Get("/pending-task", h.GetPendingChatTask)
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index df9cf0c8d3..fb707f6c9b 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -2,10 +2,12 @@ package handler
import (
"encoding/json"
+ "errors"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -174,7 +176,12 @@ func (h *Handler) GetChatSession(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, chatSessionToResponse(session))
}
-func (h *Handler) ArchiveChatSession(w http.ResponseWriter, r *http.Request) {
+// DeleteChatSession hard-deletes a chat session owned by the caller. The
+// row lock + cancel + delete run inside a single tx so a concurrent
+// SendChatMessage cannot enqueue a task that would later be orphaned by
+// the FK ON DELETE SET NULL on agent_task_queue.chat_session_id. Cancel
+// failure aborts the delete; events fire only after commit.
+func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
@@ -187,11 +194,54 @@ func (h *Handler) ArchiveChatSession(w http.ResponseWriter, r *http.Request) {
return
}
- if err := h.Queries.ArchiveChatSession(r.Context(), session.ID); err != nil {
- writeError(w, http.StatusInternalServerError, "failed to archive chat session")
+ 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)
+
+ // FOR UPDATE on the chat_session row blocks any concurrent INSERT into
+ // agent_task_queue that references it (the FK validation needs a
+ // KEY SHARE lock). After we commit the delete, the blocked INSERT
+ // fails its FK check, so it can't land an orphaned task.
+ if _, err := qtx.LockChatSessionForDelete(r.Context(), session.ID); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Already gone — treat as idempotent success.
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to lock chat session")
return
}
+ cancelled, err := qtx.CancelAgentTasksByChatSession(r.Context(), session.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to cancel chat session tasks")
+ return
+ }
+
+ if err := qtx.DeleteChatSession(r.Context(), session.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete chat session")
+ return
+ }
+
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Warn("commit chat session delete failed", "session_id", sessionID, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to commit chat session delete")
+ return
+ }
+
+ // Post-commit broadcasts. Subscribers should never observe events for a
+ // tx that didn't actually persist.
+ h.TaskService.BroadcastCancelledTasks(r.Context(), cancelled)
+
+ resolvedSessionID := uuidToString(session.ID)
+ h.publishChat(protocol.EventChatSessionDeleted, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionDeletedPayload{
+ ChatSessionID: resolvedSessionID,
+ })
+
w.WriteHeader(http.StatusNoContent)
}
@@ -237,6 +287,10 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // New archive flow doesn't exist anymore, but legacy rows with
+ // status='archived' may still be in the DB from before the feature
+ // was removed. Refuse to enqueue new agent work for them — frontend
+ // surfaces these as read-only.
if session.Status != "active" {
writeError(w, http.StatusBadRequest, "chat session is archived")
return
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 3b7f2337b7..a331036b11 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -364,6 +364,17 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID
return nil
}
+// BroadcastCancelledTasks reconciles each affected agent's status and emits
+// task:cancelled for every row. Callers must invoke this AFTER committing the
+// cancellation so subscribers don't observe a "cancelled" event for a row
+// that the tx might still roll back.
+func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, cancelled []db.AgentTaskQueue) {
+ for _, t := range cancelled {
+ s.ReconcileAgentStatus(ctx, t.AgentID)
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ }
+}
+
// 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) {
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 3c390b485a..855647d2cb 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -149,6 +149,64 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
return items, nil
}
+const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now()
+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', '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, last_heartbeat_at, trigger_summary, force_fresh_session
+`
+
+// Cancels active tasks belonging to a chat session. Called from
+// DeleteChatSession so the daemon doesn't keep running work whose result
+// has nowhere to land. Must run BEFORE the chat_session row is deleted —
+// the FK ON DELETE SET NULL would otherwise nullify chat_session_id and we
+// could no longer reach those tasks.
+func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSessionID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelAgentTasksByChatSession, chatSessionID)
+ 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.LastHeartbeatAt,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
@@ -1450,7 +1508,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, last_heartbeat_at, trigger_summary 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, last_heartbeat_at, trigger_summary, force_fresh_session FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -1497,6 +1555,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.FailureReason,
&i.LastHeartbeatAt,
&i.TriggerSummary,
+ &i.ForceFreshSession,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index d1a67b149f..bcc62eed2c 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -11,16 +11,6 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
-const archiveChatSession = `-- name: ArchiveChatSession :exec
-UPDATE chat_session SET status = 'archived', updated_at = now()
-WHERE id = $1
-`
-
-func (q *Queries) ArchiveChatSession(ctx context.Context, id pgtype.UUID) error {
- _, err := q.db.Exec(ctx, archiveChatSession, id)
- return err
-}
-
const createChatMessage = `-- name: CreateChatMessage :one
INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms)
VALUES ($1, $2, $3, $4, $5, $6)
@@ -148,6 +138,22 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
return i, err
}
+const deleteChatSession = `-- name: DeleteChatSession :exec
+DELETE FROM chat_session WHERE id = $1
+`
+
+// Hard delete. chat_message rows cascade via FK ON DELETE CASCADE; the
+// chat_session_id on agent_task_queue is set NULL by FK so completed/failed
+// task history survives the session being removed. Callers MUST run inside
+// the same transaction that holds LockChatSessionForDelete and that has
+// already cancelled any in-flight tasks (see CancelAgentTasksByChatSession)
+// so the daemon does not keep running work whose result has nowhere to
+// land.
+func (q *Queries) DeleteChatSession(ctx context.Context, id pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChatSession, id)
+ return err
+}
+
const getChatMessage = `-- name: GetChatMessage :one
SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms FROM chat_message
WHERE id = $1
@@ -484,6 +490,25 @@ func (q *Queries) ListPendingChatTasksByCreator(ctx context.Context, arg ListPen
return items, nil
}
+const lockChatSessionForDelete = `-- name: LockChatSessionForDelete :one
+SELECT id FROM chat_session
+WHERE id = $1
+FOR UPDATE
+`
+
+// Acquires an exclusive (FOR UPDATE) row lock on chat_session(id). Used by
+// the delete path so that a concurrent SendChatMessage cannot enqueue a new
+// agent_task_queue row referencing this session between our cancel and
+// delete steps. The FK from agent_task_queue.chat_session_id takes a
+// KEY SHARE lock on the parent row during INSERT validation, which
+// conflicts with FOR UPDATE — concurrent inserts block here and then fail
+// their FK check after we commit the delete.
+func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockChatSessionForDelete, id)
+ err := row.Scan(&id)
+ return id, err
+}
+
const markChatSessionRead = `-- name: MarkChatSessionRead :exec
UPDATE chat_session SET unread_since = NULL
WHERE id = $1
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index f5fd947389..3045c07bb0 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -157,6 +157,17 @@ SET status = 'cancelled', completed_at = now()
WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running')
RETURNING *;
+-- name: CancelAgentTasksByChatSession :many
+-- Cancels active tasks belonging to a chat session. Called from
+-- DeleteChatSession so the daemon doesn't keep running work whose result
+-- has nowhere to land. Must run BEFORE the chat_session row is deleted —
+-- the FK ON DELETE SET NULL would otherwise nullify chat_session_id and we
+-- could no longer reach those tasks.
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now()
+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running')
+RETURNING *;
+
-- name: GetAgentTask :one
SELECT * FROM agent_task_queue
WHERE id = $1;
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 624f8448d7..c30c70ed4f 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -46,9 +46,27 @@ SET session_id = COALESCE(sqlc.narg('session_id'), session_id),
updated_at = now()
WHERE id = sqlc.arg('id');
--- name: ArchiveChatSession :exec
-UPDATE chat_session SET status = 'archived', updated_at = now()
-WHERE id = $1;
+-- name: LockChatSessionForDelete :one
+-- Acquires an exclusive (FOR UPDATE) row lock on chat_session(id). Used by
+-- the delete path so that a concurrent SendChatMessage cannot enqueue a new
+-- agent_task_queue row referencing this session between our cancel and
+-- delete steps. The FK from agent_task_queue.chat_session_id takes a
+-- KEY SHARE lock on the parent row during INSERT validation, which
+-- conflicts with FOR UPDATE — concurrent inserts block here and then fail
+-- their FK check after we commit the delete.
+SELECT id FROM chat_session
+WHERE id = $1
+FOR UPDATE;
+
+-- name: DeleteChatSession :exec
+-- Hard delete. chat_message rows cascade via FK ON DELETE CASCADE; the
+-- chat_session_id on agent_task_queue is set NULL by FK so completed/failed
+-- task history survives the session being removed. Callers MUST run inside
+-- the same transaction that holds LockChatSessionForDelete and that has
+-- already cancelled any in-flight tasks (see CancelAgentTasksByChatSession)
+-- so the daemon does not keep running work whose result has nowhere to
+-- land.
+DELETE FROM chat_session WHERE id = $1;
-- name: TouchChatSession :exec
UPDATE chat_session SET updated_at = now()
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 8977cf65cc..939b34b00d 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -64,9 +64,10 @@ const (
EventSkillDeleted = "skill:deleted"
// Chat events
- EventChatMessage = "chat:message"
- EventChatDone = "chat:done"
- EventChatSessionRead = "chat:session_read"
+ EventChatMessage = "chat:message"
+ EventChatDone = "chat:done"
+ EventChatSessionRead = "chat:session_read"
+ EventChatSessionDeleted = "chat:session_deleted"
// Project events
EventProjectCreated = "project:created"
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 4381aaadf6..0014243d75 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -87,6 +87,13 @@ type ChatSessionReadPayload struct {
ChatSessionID string `json:"chat_session_id"`
}
+// ChatSessionDeletedPayload is broadcast when a chat session is hard-deleted
+// so other tabs/devices drop it from their session lists and reset the active
+// pointer if it referenced the deleted session.
+type ChatSessionDeletedPayload struct {
+ ChatSessionID string `json:"chat_session_id"`
+}
+
// DaemonHeartbeatRequestPayload is sent from daemon to server over WebSocket
// to update last_seen_at and pull pending actions for a single runtime.
// Mirrors the body of POST /api/daemon/heartbeat so both transports share