Skip to content

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

Go

MUL-5892 fix(chat): cancel queued tasks when a session is archived, and stop telling non-Slack sessions they have no channel (#6595)

Xichang(Seacen) Zhaocdf93e4914e9
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index a36ad83732..473f0ddd27 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -516,6 +516,15 @@ type SetChatSessionArchivedRequest struct {
// reviving this archived one. Unarchive deliberately does NOT recreate the
// binding: if later traffic already forked a new session, that session owns the
// channel now, and restoring the old binding would steal it back.
+//
+// Severing that binding is what makes archiving a bound session cancel its
+// in-flight tasks: the adapter still holds the chat id, so a turn that survives
+// the archive answers into a group room the session no longer belongs to. That
+// cancel is therefore scoped to sessions that HAD a binding. Archiving a
+// web-only chat leaves its tasks alone — it is the reversible organizing action
+// the UI presents (no confirmation, unarchive undoes it), and the destructive
+// counterpart is the Stop button, which cancels through CancelTaskByUser and
+// gives the user their typed prompt back.
func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
@@ -552,7 +561,58 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)
return
}
+ // Rows cancelled inside the tx, broadcast after it commits. nil when the
+ // request unarchives and nil for a web-only chat; BroadcastCancelledTasks
+ // is a no-op on an empty slice.
+ var cancelled []db.AgentTaskQueue
+
if req.Archived {
+ // Read the binding BEFORE the delete below, which is what erases the
+ // evidence: after it runs there is no way to tell a session that was
+ // on a channel from one that never was.
+ _, bindingErr := qtx.GetChannelChatSessionBindingBySessionAny(r.Context(), session.ID)
+ switch {
+ case bindingErr == nil:
+ // Bound, and the delete below is about to drop that binding.
+ // ClaimAgentTask does not read chat_session.status, so a task
+ // queued before the archive stays claimable after it: the daemon
+ // runs a turn on a conversation the user closed, spending runtime
+ // and quota and writing assistant messages into an archived chat.
+ // The binding is gone by then, so the brief describes the run as a
+ // private web chat — the misattribution the history note below
+ // exists to prevent — while the outbound senders, which resolve
+ // their destination through that same deleted row, have no route
+ // left to deliver on. Cancel in the same tx that drops the
+ // binding, as DeleteChatSession does.
+ //
+ // The query is not limited to never-started work: it also matches
+ // dispatched, running, waiting_local_directory and deferred, which
+ // is why the returned rows have to reach the post-commit broadcast
+ // below rather than being discarded.
+ cancelled, err = qtx.CancelAgentTasksByChatSession(r.Context(), session.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to cancel queued tasks for the archived session")
+ return
+ }
+ case errors.Is(bindingErr, pgx.ErrNoRows):
+ // A web-only chat has no room, no adapter and nowhere for a late
+ // answer to land, so there is nothing here to protect anyone from
+ // and archiving stays what the UI already says it is: the
+ // reversible "put it away" step that unarchive undoes, offered
+ // with no confirmation, with hard delete available only after it.
+ // Cancelling would also destroy the user's typed prompt — the Stop
+ // button cancels through CancelTaskByUser, which hands the prompt
+ // back (cancelled_chat_message.restore_to_input, or a durable
+ // chat_draft_restore row), and CancelAgentTasksByChatSession does
+ // neither.
+ default:
+ // We cannot tell whether this session was bound. Carrying on would
+ // silently skip the cancel and reopen the bug above, so fail the
+ // archive rather than guess; the caller can retry.
+ slog.Warn("read chat session channel binding failed", "session_id", sessionID, "error", bindingErr)
+ writeError(w, http.StatusInternalServerError, "failed to read chat session channel binding")
+ return
+ }
if err := qtx.DeleteChannelChatSessionBindingBySession(r.Context(), session.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to clear chat session channel binding")
return
@@ -565,6 +625,15 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)
return
}
+ // Post-commit broadcasts, same as DeleteChatSession: subscribers should
+ // never observe events for a tx that didn't actually persist. This is the
+ // call that captures the cancellation and revokes the tasks' mat_ tokens,
+ // reconciles each agent off 'working', emits task:cancelled so other
+ // clients drop the row instead of showing it queued until the next
+ // refresh, and wakes the runtime so a queued successor is claimed now
+ // rather than at the daemon's next poll.
+ h.TaskService.BroadcastCancelledTasks(r.Context(), cancelled)
+
resolvedSessionID := uuidToString(updated.ID)
status := updated.Status
h.publishChat(protocol.EventChatSessionUpdated, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionUpdatedPayload{
diff --git a/server/internal/handler/chat_archive_cancel_test.go b/server/internal/handler/chat_archive_cancel_test.go
new file mode 100644
index 0000000000..fdb790374a
--- /dev/null
+++ b/server/internal/handler/chat_archive_cancel_test.go
@@ -0,0 +1,552 @@
+package handler
+
+// chat_archive_cancel_test.go — archiving a chat session deletes its channel
+// binding but used to leave queued tasks claimable. ClaimAgentTask does not
+// read chat_session.status, so the daemon still ran the turn: runtime and
+// quota spent on a conversation the user closed, assistant messages written
+// into an archived chat, and the agent flipped back to 'working'. The binding
+// row is already gone by then, so the brief describes the run as a private web
+// chat, and the outbound senders — which resolve their destination through
+// that same row — have nowhere to deliver the answer.
+//
+// The cancel is therefore scoped to sessions that HAD a binding, which is what
+// the two tests below are: the same fixture archived twice, once bound and once
+// not. A web-only chat has no room and no late answer, and cancelling it would
+// destroy the user's typed prompt — CancelAgentTasksByChatSession is a bare
+// UPDATE with no restore, unlike the Stop button's CancelTaskByUser — so
+// archiving must leave it alone.
+//
+// For the bound case, cancelling the rows in the database is only half of it:
+// the cancellation has to reach the same post-commit lifecycle
+// DeleteChatSession runs, or the rows read 'cancelled' while agents stay
+// 'working', other clients keep showing the task, the tasks' API tokens stay
+// live, and the runtime waits for its next poll before claiming anything else.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/slack"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestArchivingAChannelBoundChatSessionCancelsItsQueuedTasks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ f := newArchiveCancelFixture(t, "Archive Cancels Queued")
+
+ // The binding is the reason this cancel exists at all: it is what makes the
+ // session a real conversation in a room, and the archive drops it a few
+ // lines after deciding. Bind before archiving, or the test is a web chat
+ // wearing the bug's failure message.
+ f.bindToChannel(t, "GROUP_ARCHIVE_CANCEL")
+
+ f.archive(t)
+
+ for _, tc := range []struct{ label, id string }{
+ {"queued", f.queuedTaskID},
+ {"running", f.runningTaskID},
+ } {
+ if status := f.taskStatus(t, tc.id); status != "cancelled" {
+ t.Fatalf("%s task status after archiving a channel-bound session = %q, want cancelled — the daemon will still run this turn on a closed conversation, spending runtime and quota and writing into an archived chat, and with the binding already gone it is briefed as a private web chat with no route left to answer on", tc.label, status)
+ }
+ }
+
+ // The binding read that gates the cancel happens before the delete; the
+ // delete still has to run, or the channel keeps resolving to this session.
+ if f.bindingExists(t) {
+ t.Errorf("archived session kept its channel_chat_session_binding — inbound traffic would revive a read-only conversation")
+ }
+
+ // Post-commit lifecycle. Each of these is something BroadcastCancelledTasks
+ // does and nothing else on this path does.
+
+ if agentStatus := f.agentStatus(t); agentStatus != "idle" {
+ t.Errorf("agent status after archiving its only conversation = %q, want idle — the agent keeps showing as working in the UI with no task left to finish it", agentStatus)
+ }
+
+ if seen := f.drainCancelledEvents(); len(seen) != 2 {
+ t.Errorf("task:cancelled emitted for %d of 2 tasks — every other client keeps the cancelled turn on screen until something else forces a refresh", len(seen))
+ }
+
+ if live := f.liveTaskTokens(t); live != 0 {
+ t.Errorf("cancelled task still has %d live task token(s) — the agent process can keep calling the API back for a turn that was cancelled", live)
+ }
+}
+
+// TestArchivingAWebOnlyChatSessionLeavesItsTasksRunning is the other direction:
+// the same fixture with no channel binding. Archive is the reversible
+// organizing action the UI presents — the row offers Stop OR Archive, never
+// both; Stop is `danger` behind a confirmation and Archive fires immediately
+// with none; unarchive undoes it and hard delete is offered only afterwards.
+// Cancelling here would make that immediate, unconfirmed click destructive, and
+// irreversibly so: the Stop button cancels through CancelTaskByUser, which
+// returns the prompt via cancelled_chat_message.restore_to_input or writes a
+// durable chat_draft_restore row, while CancelAgentTasksByChatSession does
+// neither and unarchive cannot undo a cancel.
+func TestArchivingAWebOnlyChatSessionLeavesItsTasksRunning(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ f := newArchiveCancelFixture(t, "Archive Leaves Web Chat")
+
+ // Deliberately no binding: this is a plain web chat.
+
+ f.archive(t)
+
+ for _, tc := range []struct{ label, id, want string }{
+ {"queued", f.queuedTaskID, "queued"},
+ {"running", f.runningTaskID, "running"},
+ } {
+ if status := f.taskStatus(t, tc.id); status != tc.want {
+ t.Fatalf("%s task status after archiving a web-only chat = %q, want %q — there is no room for a late answer to reach here, and cancelling destroys the user's typed prompt: this path writes no chat_draft_restore row and returns no restore_to_input, so the text is gone and unarchiving cannot bring it back", tc.label, status, tc.want)
+ }
+ }
+
+ if agentStatus := f.agentStatus(t); agentStatus != "working" {
+ t.Errorf("agent status after archiving a web-only chat = %q, want working — its turn is still running", agentStatus)
+ }
+
+ if seen := f.drainCancelledEvents(); len(seen) != 0 {
+ t.Errorf("archiving a web-only chat emitted task:cancelled for %d task(s) — every client drops a turn that is still running", len(seen))
+ }
+
+ if live := f.liveTaskTokens(t); live != 1 {
+ t.Errorf("running task has %d live task token(s) after archiving a web-only chat, want 1 — revoking it strands the agent process mid-turn", live)
+ }
+
+ // The archive itself must still happen; narrowing the cancel must not turn
+ // into skipping the status flip.
+ var status string
+ if err := testPool.QueryRow(ctx,
+ `SELECT status FROM chat_session WHERE id = $1`, f.sessionID).Scan(&status); err != nil {
+ t.Fatalf("reload chat session: %v", err)
+ }
+ if status != "archived" {
+ t.Fatalf("chat session status = %q, want archived", status)
+ }
+}
+
+// TestArchivingInsideTheDebounceWindowRefusesTheLateEnqueue covers the half of
+// the race the two tests above cannot reach: both of them start from a task
+// that already exists, so the archive always has something to cancel.
+//
+// A channel message has no task for up to DefaultChatRunBatchWindow. The
+// message row is persisted the moment it arrives; the task is created only
+// when the silence window expires and flushChatRun reloads the session and
+// calls EnqueueChatTask. Archive inside that window and the cancel finds
+// nothing to cancel, drops the binding and commits — and the flush then
+// arrives at a conversation that is already closed.
+//
+// The enqueue is the only place left that can refuse it. ClaimAgentTask does
+// not read chat_session.status either, so a row inserted here is claimed and
+// run.
+func TestArchivingInsideTheDebounceWindowRefusesTheLateEnqueue(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "Archive Inside Debounce Window")
+ bindChatSessionToChannel(t, agentID, sessionID, "GROUP_ARCHIVE_DEBOUNCE")
+
+ // The group message arrives: durable, unowned, and with no task of its own
+ // until the window expires. This is the window.
+ appendChannelUserMessage(t, ctx, sessionID, "还有一件事")
+
+ queued := subscribeChatTaskQueued(t, sessionID)
+
+ // The user archives while the timer is still running.
+ archiveChatSession(t, sessionID)
+
+ // Whatever the flush manages to create has to be cleaned up even when the
+ // assertions below fail.
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, sessionID)
+ })
+
+ // The window expires. flushChatRun reloads the session by id and hands it
+ // to EnqueueChatTask. The reload sees the archived row; the point is that
+ // nothing along the way used to look at its status.
+ sess, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+ _, enqueueErr := testHandler.TaskService.EnqueueChatTask(ctx, sess, parseUUID(testUserID), false)
+
+ var tasks int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, sessionID).Scan(&tasks); err != nil {
+ t.Fatalf("count tasks on the archived session: %v", err)
+ }
+ if tasks != 0 {
+ t.Fatalf("the debounced flush created %d task(s) on a session archived while its window was open — the daemon claims and runs that turn on a closed conversation: runtime and quota spent, assistant messages written into an archived chat, the agent flipped back to 'working', and with the binding already deleted the run is briefed as a private web chat", tasks)
+ }
+
+ select {
+ case taskID := <-queued:
+ t.Errorf("task:queued published for %s on an archived session — every client puts a running turn back on screen in a conversation the user closed", taskID)
+ default:
+ }
+
+ // The sentinel, not a bare failure: flushChatRun switches on the error, and
+ // this is the same refusal the send path already returns for the same race.
+ if !errors.Is(enqueueErr, service.ErrChatSessionArchived) {
+ t.Errorf("EnqueueChatTask on an archived session returned %v, want ErrChatSessionArchived", enqueueErr)
+ }
+}
+
+// TestEnqueueOnAnActiveSessionStillWorks is the other direction: the lock and
+// the status re-read added for the test above sit in front of every channel
+// turn, so an ordinary flush on a live session must still produce its task.
+func TestEnqueueOnAnActiveSessionStillWorks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "Enqueue On Active Session")
+ bindChatSessionToChannel(t, agentID, sessionID, "GROUP_ACTIVE_ENQUEUE")
+
+ messageID := appendChannelUserMessage(t, ctx, sessionID, "在吗")
+ task := flushChannelChatRun(t, ctx, sessionID)
+
+ if task.Status != "queued" {
+ t.Fatalf("task status on a live session = %q, want queued", task.Status)
+ }
+ var owner pgtype.UUID
+ if err := testPool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, messageID).Scan(&owner); err != nil {
+ t.Fatalf("load the message owner: %v", err)
+ }
+ if owner != task.ID {
+ t.Fatalf("the flushed message belongs to task %s, want the task just created (%s) — the refusal added for archived sessions must not touch the live path",
+ uuidToString(owner), uuidToString(task.ID))
+ }
+}
+
+// subscribeChatTaskQueued collects task:queued events for one session. Bus
+// handlers are never unsubscribed in this suite, so it filters on the session
+// id and never blocks a later publisher. events.Bus.Publish is synchronous, so
+// anything the enqueue was going to emit is already in the channel by the time
+// it returns.
+func subscribeChatTaskQueued(t *testing.T, sessionID string) <-chan string {
+ t.Helper()
+ seen := make(chan string, 4)
+ testHandler.Bus.Subscribe(protocol.EventTaskQueued, func(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ if id, _ := payload["chat_session_id"].(string); id != sessionID {
+ return
+ }
+ taskID, _ := payload["task_id"].(string)
+ select {
+ case seen <- taskID:
+ default:
+ }
+ })
+ return seen
+}
+
+// archiveCancelFixture is one agent marked 'working' with one chat session
+// carrying two in-flight turns — one queued, one already running — plus a live
+// task token for the running one and a filtered task:cancelled subscription.
+// CancelAgentTasksByChatSession matches both statuses, and the running one is
+// where dropping the post-commit broadcast shows up worst: the agent stays
+// 'working' with no task left.
+type archiveCancelFixture struct {
+ agentID string
+ sessionID string
+ queuedTaskID string
+ runningTaskID string
+ cancelled chan string
+}
+
+func newArchiveCancelFixture(t *testing.T, agentName string) *archiveCancelFixture {
+ t.Helper()
+ ctx := context.Background()
+
+ f := &archiveCancelFixture{}
+ f.agentID = createHandlerTestAgent(t, agentName, []byte("[]"))
+ f.sessionID = createHandlerTestChatSession(t, f.agentID)
+ f.queuedTaskID = queueArchiveTestTask(t, f.agentID, f.sessionID, "queued")
+ f.runningTaskID = queueArchiveTestTask(t, f.agentID, f.sessionID, "running")
+
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent SET status = 'working' WHERE id = $1`, f.agentID); err != nil {
+ t.Fatalf("mark agent working: %v", err)
+ }
+
+ // A live task token for the running task. captureTaskCancelled revokes it;
+ // on the bound leg, without the broadcast the token outlives the task it
+ // authenticates, and on the web-only leg it must survive untouched.
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)
+ VALUES ($1, $2, $3, $4, $5, now() + interval '24 hours')
+ `, "archive-cancel-test-"+f.runningTaskID, f.runningTaskID, f.agentID, testWorkspaceID, testUserID); err != nil {
+ t.Fatalf("mint task token: %v", err)
+ }
+
+ // Bus handlers are never unsubscribed in this suite, so filter to this
+ // fixture's own task ids and never block a later publisher.
+ f.cancelled = make(chan string, 4)
+ testHandler.Bus.Subscribe(protocol.EventTaskCancelled, func(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ id, _ := payload["task_id"].(string)
+ if id != f.queuedTaskID && id != f.runningTaskID {
+ return
+ }
+ select {
+ case f.cancelled <- id:
+ default:
+ }
+ })
+
+ return f
+}
+
+// bindToChannel gives the session a channel binding, the way an inbound message
+// from a group room would.
+func (f *archiveCancelFixture) bindToChannel(t *testing.T, channelChatID string) {
+ t.Helper()
+ bindChatSessionToChannel(t, f.agentID, f.sessionID, channelChatID)
+}
+
+// bindChatSessionToChannel installs a WeCom bot on the agent and binds the
+// session to one of its rooms, which is the state an inbound group message
+// leaves behind.
+func bindChatSessionToChannel(t *testing.T, agentID, sessionID, channelChatID string) {
+ t.Helper()
+ ctx := context.Background()
+
+ // channel_* rows have no FK to chat_session, so they outlive the session
+ // helper's cleanup; clear by deterministic key.
+ cleanup := func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID)
+ testPool.Exec(context.Background(),
+ `DELETE FROM channel_installation WHERE agent_id = $1`, agentID)
+ }
+ cleanup()
+ t.Cleanup(cleanup)
+
+ var instID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, status, installer_user_id)
+ VALUES ($1, $2, 'wecom', $3::jsonb, 'active', $4)
+ RETURNING id
+ `, testWorkspaceID, agentID, `{"app_id":"bot-`+channelChatID+`"}`, testUserID).Scan(&instID); err != nil {
+ t.Fatalf("create installation: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding
+ (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
+ VALUES ($1, $2, 'wecom', $3, 'group')
+ `, sessionID, instID, channelChatID); err != nil {
+ t.Fatalf("bind session: %v", err)
+ }
+}
+
+func (f *archiveCancelFixture) archive(t *testing.T) {
+ t.Helper()
+ archiveChatSession(t, f.sessionID)
+}
+
+// archiveChatSession archives through the real endpoint, so everything the
+// handler does on the way — the binding read, the cancel, the binding delete,
+// the post-commit broadcast — happens exactly as it does for a user clicking
+// Archive.
+func archiveChatSession(t *testing.T, sessionID string) {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPatch, "/api/chat/sessions/"+sessionID+"/archived",
+ bytes.NewReader([]byte(`{"archived":true}`)))
+ req.Header.Set("X-User-ID", testUserID)
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("sessionId", sessionID)
+ req = withChatTestWorkspaceCtx(t, req)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+
+ w := httptest.NewRecorder()
+ testHandler.SetChatSessionArchived(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("archive returned %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func (f *archiveCancelFixture) taskStatus(t *testing.T, taskID string) string {
+ t.Helper()
+ var status string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("reload task %s: %v", taskID, err)
+ }
+ return status
+}
+
+func (f *archiveCancelFixture) agentStatus(t *testing.T) string {
+ t.Helper()
+ var status string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status FROM agent WHERE id = $1`, f.agentID).Scan(&status); err != nil {
+ t.Fatalf("reload agent: %v", err)
+ }
+ return status
+}
+
+func (f *archiveCancelFixture) liveTaskTokens(t *testing.T) int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM task_token WHERE task_id = $1`, f.runningTaskID).Scan(&n); err != nil {
+ t.Fatalf("count task tokens: %v", err)
+ }
+ return n
+}
+
+func (f *archiveCancelFixture) bindingExists(t *testing.T) bool {
+ t.Helper()
+ var exists bool
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT EXISTS (SELECT 1 FROM channel_chat_session_binding WHERE chat_session_id = $1)`,
+ f.sessionID).Scan(&exists); err != nil {
+ t.Fatalf("query chat session binding: %v", err)
+ }
+ return exists
+}
+
+// drainCancelledEvents reads what the bus already delivered. events.Bus.Publish
+// is synchronous, so by the time the handler has returned every event this
+// archive was going to emit is already in the channel — an empty drain means
+// none were emitted, not that they are still in flight.
+func (f *archiveCancelFixture) drainCancelledEvents() map[string]bool {
+ seen := map[string]bool{}
+ for len(seen) < 2 {
+ select {
+ case id := <-f.cancelled:
+ seen[id] = true
+ default:
+ return seen
+ }
+ }
+ return seen
+}
+
+func queueArchiveTestTask(t *testing.T, agentID, sessionID, status string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (agent_id, chat_session_id, status, runtime_id)
+ VALUES ($1, $2, $3, (SELECT runtime_id FROM agent WHERE id = $1))
+ RETURNING id
+ `, agentID, sessionID, status).Scan(&taskID); err != nil {
+ t.Fatalf("queue a %s task: %v", status, err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM task_token WHERE task_id = $1`, taskID)
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return taskID
+}
+
+// TestNoHistoryNoteNamesTheActualChannel: the history reader is Slack-only, so
+// every other platform lands on the empty-read note. Telling a WeCom or Lark
+// session that it "is not connected to a chat channel" is false, and the
+// reader is an agent deciding who can see its answer. Both legs go through the
+// real response path and assert channel_type and note agree — they are derived
+// from one binding read, so they cannot contradict each other.
+func TestNoHistoryNoteNamesTheActualChannel(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID := createHandlerTestAgent(t, "History Note Channel", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ // Web-only session: the original wording is correct here.
+ body := readNoHistoryResponse(t, sessionID)
+ if body.ChannelType != "" {
+ t.Errorf("web-only session channel_type = %q, want empty", body.ChannelType)
+ }
+ if !strings.Contains(body.Note, "not connected to a chat channel") {
+ t.Errorf("web-only session note = %q", body.Note)
+ }
+
+ var instID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, status, installer_user_id)
+ VALUES ($1, $2, 'wecom', '{"app_id":"bot-history-note"}'::jsonb, 'active', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&instID); err != nil {
+ t.Fatalf("create installation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, instID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding
+ (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
+ VALUES ($1, $2, 'wecom', 'GROUP_1', 'group')
+ `, sessionID, instID); err != nil {
+ t.Fatalf("bind session: %v", err)
+ }
+
+ body = readNoHistoryResponse(t, sessionID)
+ if strings.Contains(body.Note, "not connected to a chat channel") {
+ t.Fatalf("a WeCom-bound session was told it is not on a channel: %q", body.Note)
+ }
+ if !strings.Contains(body.Note, "wecom") {
+ t.Errorf("note does not name the platform: %q", body.Note)
+ }
+ if body.ChannelType != "wecom" {
+ t.Errorf("channel_type = %q, want wecom", body.ChannelType)
+ }
+
+ // A binding read that fails for any reason other than "no such row" leaves
+ // us unable to tell which platform this session is on. Answering the
+ // web-only note there would hand this same WeCom session the wording the
+ // test above just rejected, on a 200, because a query failed. Report it
+ // instead, the way the archive path refuses to guess about the same read.
+ cancelledCtx, cancel := context.WithCancel(ctx)
+ cancel()
+ req := httptest.NewRequest(http.MethodGet, "/api/chat/sessions/"+sessionID+"/channel-history", nil)
+ req.Header.Set("X-User-ID", testUserID)
+ req = req.WithContext(cancelledCtx)
+ w := httptest.NewRecorder()
+ testHandler.respondChatHistory(w, req, parseUUID(sessionID), channel.HistoryPage{}, slack.ErrNoSlackSession)
+ if w.Code == http.StatusOK {
+ t.Fatalf("a failed binding read answered 200 %s — the agent is told it is in a web-only conversation because a query failed", strings.TrimSpace(w.Body.String()))
+ }
+}
+
+// readNoHistoryResponse drives the real response path rather than the note
+// helper — otherwise the test keeps passing when the handler stops calling it.
+func readNoHistoryResponse(t *testing.T, sessionID string) ChatChannelHistoryResponse {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodGet, "/api/chat/sessions/"+sessionID+"/channel-history", nil)
+ req.Header.Set("X-User-ID", testUserID)
+ w := httptest.NewRecorder()
+ testHandler.respondChatHistory(w, req, parseUUID(sessionID), channel.HistoryPage{}, slack.ErrNoSlackSession)
+
+ var body ChatChannelHistoryResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v (%s)", err, w.Body.String())
+ }
+ return body
+}
diff --git a/server/internal/handler/chat_history.go b/server/internal/handler/chat_history.go
index c575d12478..aea4adc4ad 100644
--- a/server/internal/handler/chat_history.go
+++ b/server/internal/handler/chat_history.go
@@ -7,6 +7,7 @@ import (
"net/http"
"strconv"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -124,9 +125,21 @@ func (h *Handler) chatHistorySession(w http.ResponseWriter, r *http.Request) (pg
func (h *Handler) respondChatHistory(w http.ResponseWriter, r *http.Request, sessionID pgtype.UUID, page channel.HistoryPage, err error) {
if err != nil {
if errors.Is(err, slack.ErrNoSlackSession) {
+ // One read of the binding, two derived fields. Reading it twice
+ // lets an archive land between them and produce a response whose
+ // channel_type names a platform while its note says there is no
+ // channel.
+ channelType, bindingErr := h.sessionChannelType(r.Context(), sessionID)
+ if bindingErr != nil {
+ slog.Error("chat session channel binding read failed", append(logger.RequestAttrs(r),
+ "error", bindingErr, "chat_session_id", uuidToString(sessionID))...)
+ writeError(w, http.StatusInternalServerError, "failed to read chat session channel binding")
+ return
+ }
writeJSON(w, http.StatusOK, ChatChannelHistoryResponse{
- Messages: []channel.HistoryMessage{},
- Note: "This conversation is not connected to a chat channel, so there is no channel history to read.",
+ ChannelType: channelType,
+ Messages: []channel.HistoryMessage{},
+ Note: noHistoryNote(channelType),
})
return
}
@@ -174,3 +187,45 @@ func parseHistoryLimit(raw string) int {
}
return n
}
+
+// noHistoryNote explains an empty read in terms the agent can act on. It is a
+// pure function of the channel type its caller already resolved, so the note
+// and the response's channel_type cannot disagree.
+//
+// The reader is Slack-only, so every other platform lands here — and the note
+// said "this conversation is not connected to a chat channel", which for a
+// WeCom, Lark or DingTalk session is simply false. An agent told it is in a
+// web-only conversation reasons differently about who can see its answer than
+// one told it is in a group whose backlog it cannot read, and that is a
+// difference worth not lying about.
+func noHistoryNote(channelType string) string {
+ if channelType == "" {
+ return "This conversation is not connected to a chat channel, so there is no channel history to read."
+ }
+ return "This conversation is on " + channelType + ", whose backlog this server cannot read. You can see the messages addressed to you in this session, but not the rest of the room."
+}
+
+// sessionChannelType names the platform behind a session, or "" when there is
+// none. Channel-agnostic on purpose: a per-platform lookup here would go blind
+// the next time a channel is added, which is exactly how the note above came
+// to be wrong.
+//
+// Only "no such row" means "no channel". Any other failure is us being unable
+// to tell, and answering "" there hands the agent the very note this change
+// removes — a WeCom or Lark session told it is web-only, on a 200, because a
+// connection blipped. The caller reports that rather than guessing, the same
+// way the archive path refuses to guess about the same read.
+func (h *Handler) sessionChannelType(ctx context.Context, sessionID pgtype.UUID) (string, error) {
+ if h.Queries == nil || !sessionID.Valid {
+ return "", nil
+ }
+ binding, err := h.Queries.GetChannelChatSessionBindingBySessionAny(ctx, sessionID)
+ switch {
+ case err == nil:
+ return binding.ChannelType, nil
+ case errors.Is(err, pgx.ErrNoRows):
+ return "", nil
+ default:
+ return "", err
+ }
+}
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index 4bef62d28b..cb659c6433 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -1112,6 +1112,42 @@ func TestRouter_FlushArchived_ClearsTyping(t *testing.T) {
}
}
+// TestRouter_FlushSessionArchived_ClearsTypingAndSaysNothing pins what the
+// flush does with the refusal EnqueueChatTask returns when the session was
+// archived while the debounce window was still open. Two things have to be
+// true, and the second is the one worth a test: the typing indicator must be
+// cleared here (no task will exist, so the bus-driven clear can never fire),
+// and nothing may be posted back — the archive deleted the channel binding
+// before this flush ran, so a notice would be addressed to a room that is no
+// longer bound to this conversation. The error is not one of the two the
+// switch names, so it falls to the default log branch and says nothing, which
+// is the behaviour this test holds in place.
+func TestRouter_FlushSessionArchived_ClearsTypingAndSaysNothing(t *testing.T) {
+ h := newHarness(t)
+ h.tasks.err = service.ErrChatSessionArchived
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !waitFor(time.Second, func() bool { return h.typing.settledCalls() == 1 }) {
+ t.Fatalf("an archived-session flush must clear the typing indicator, got %d OnSettled calls", h.typing.settledCalls())
+ }
+ // The ingest ACK is the only reply this message is entitled to; anything
+ // else came from the flush. Waiting the window out is the assertion —
+ // waitFor returns false only if it never happened.
+ spoke := func() (Result, bool) {
+ for _, r := range h.replier.calls() {
+ if r.Outcome != OutcomeIngested {
+ return r, true
+ }
+ }
+ return Result{}, false
+ }
+ if waitFor(200*time.Millisecond, func() bool { _, ok := spoke(); return ok }) {
+ reply, _ := spoke()
+ t.Fatalf("archived-session flush posted %q into a room the archive had already unbound", reply.Outcome)
+ }
+}
+
func TestRouter_FlushSuccess_DoesNotClearTyping(t *testing.T) {
h := newHarness(t)
if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 671d227ab5..a5e2934cd9 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1559,8 +1559,8 @@ var ErrChatQuickActionsStale = errors.New("chat quick actions: refresh target is
// quota-spending pass (MUL-5149).
var ErrChatQuickActionsBusy = errors.New("chat quick actions: session busy")
-// ErrChatSessionArchived signals that a direct-chat send lost a race with
-// archiving the session and therefore must not persist a new turn.
+// ErrChatSessionArchived signals that a send or a debounced channel flush lost
+// a race with archiving the session and therefore must not persist a new turn.
var ErrChatSessionArchived = errors.New("chat task: session archived")
// EnqueueChatTask creates a task-owned input batch for a chat session. Channel
@@ -1570,9 +1570,9 @@ var ErrChatSessionArchived = errors.New("chat task: session archived")
//
// Errors split into two layers:
//
-// - Productizable rejections (agent archived, no runtime) return
-// the sentinel errors above. Callers (e.g. the Lark dispatcher)
-// can errors.Is them to decide a user-visible outcome.
+// - Productizable rejections (agent archived, no runtime, session
+// archived) return the sentinel errors above. Callers (e.g. the Lark
+// dispatcher) can errors.Is them to decide a user-visible outcome.
//
// - Infrastructure failures (DB load / insert errors) are wrapped
// as ordinary errors. The caller should treat them as retryable
@@ -1625,6 +1625,35 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
}
defer tx.Rollback(ctx)
qtx := s.Queries.WithTx(tx)
+ // Refuse to enqueue onto a session that has been archived, the same guard
+ // the direct-send path takes. This is the one enqueue path with a delay in
+ // front of it: the channel run trigger is debounced by
+ // DefaultChatRunBatchWindow, so the message is persisted immediately and
+ // the task row is only created here, up to a window later. An archive
+ // committing inside that window cancels the tasks it can see — there are
+ // none yet — and drops the channel binding, and without this check the
+ // flush then inserts a fresh task on a conversation the user closed.
+ // ClaimAgentTask does not read chat_session.status either, so the daemon
+ // would run it: quota and runtime spent on a closed conversation, new
+ // assistant turns written into an archived chat, the agent flipped back to
+ // 'working', and the brief describing the run as a private web chat
+ // because the binding is already gone.
+ //
+ // The lock is what makes the check hold — the caller's copy of the session
+ // was loaded before the transaction opened and can already be stale, the
+ // same reason the send path re-reads the agent under its lock. It is
+ // deliberately FOR NO KEY UPDATE rather than the send path's FOR UPDATE;
+ // see LockChatSessionForEnqueue for why the channel path cannot afford to
+ // block the inbound appends FOR UPDATE would. Taken as the transaction's
+ // first statement, so the chat_session -> agent_task_queue order is
+ // unchanged and no new deadlock edge appears.
+ currentSession, err := qtx.LockChatSessionForEnqueue(ctx, chatSession.ID)
+ if err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("lock chat session: %w", err)
+ }
+ if currentSession.Status != "active" {
+ return db.AgentTaskQueue{}, ErrChatSessionArchived
+ }
mediaPendingUntil, err := qtx.GetChannelMediaPendingUntil(ctx, chatSession.ID)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
diff --git a/server/internal/service/task_channel_media_race_test.go b/server/internal/service/task_channel_media_race_test.go
index 78b1ebcf3d..8f832ae5ae 100644
--- a/server/internal/service/task_channel_media_race_test.go
+++ b/server/internal/service/task_channel_media_race_test.go
@@ -138,6 +138,105 @@ func TestEnqueueChatTaskDefersWhenMediaMessageCommitsDuringEnqueue(t *testing.T)
}
}
+// TestEnqueueChatTaskLocksOutAConcurrentArchiveButNotInboundMessages is the
+// other half of the archive guard, and it is about the lock MODE rather than
+// the status check.
+//
+// The handler-side test covers archive-then-flush: the archive has committed,
+// so the re-read under the lock sees 'archived' and the enqueue refuses. This
+// one covers the overlap — an archive arriving while an enqueue is mid-flight.
+// It must not be able to slip past: if it committed inside our transaction its
+// cancel would run against a task row that does not exist yet, and the enqueue
+// would go on to commit that row onto a closed conversation. So the archive has
+// to block on the lock, come through afterwards, and cancel what it then sees.
+//
+// The same transaction must NOT block the room's next message. Every inbound
+// message is an INSERT into chat_message, FK'd to this chat_session, so it takes
+// FOR KEY SHARE on the row we hold — and FOR UPDATE (what the send, delete and
+// draft paths take) conflicts with exactly that. Under FOR UPDATE a group's
+// next message would wait for the previous message's enqueue to finish. Both
+// halves are asserted from inside the enqueue transaction, which is the only
+// moment either is observable.
+func TestEnqueueChatTaskLocksOutAConcurrentArchiveButNotInboundMessages(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var chatSessionID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)
+ VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("seed chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ })
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)
+ VALUES ($1, 'user', 'first', TRUE)`, chatSessionID); err != nil {
+ t.Fatalf("seed inbound message: %v", err)
+ }
+
+ // Both probes run on their own connections, from inside the enqueue
+ // transaction, with a short lock_timeout: "blocked" and "not blocked" are
+ // then a returned error rather than a wall-clock guess.
+ var archiveErr, appendErr error
+ svc := &TaskService{
+ Queries: q,
+ TxStarter: &raceInjectTxStarter{pool: pool, inject: func() {
+ archiveErr = probeUnderLock(ctx, pool,
+ `UPDATE chat_session SET status = 'archived' WHERE id = $1`, chatSessionID)
+ appendErr = probeUnderLock(ctx, pool,
+ `INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)
+ VALUES ($1, 'user', 'second', TRUE)`, chatSessionID)
+ }},
+ Bus: events.New(),
+ }
+
+ task, err := svc.EnqueueChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID),
+ AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false)
+ if err != nil {
+ t.Fatalf("EnqueueChatTask: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)
+ })
+
+ if !isLockTimeout(archiveErr) {
+ t.Fatalf("an archive landing mid-enqueue got %v, want to be blocked on the chat_session lock — it would otherwise commit while this task row is still invisible, cancel nothing, and leave a queued turn on a closed conversation", archiveErr)
+ }
+ if appendErr != nil {
+ t.Fatalf("the room's next message could not be appended during an enqueue: %v — inbound ingestion must not wait behind the debounced flush of the message before it", appendErr)
+ }
+}
+
+// probeUnderLock runs one statement on its own connection with a short
+// lock_timeout, so a row lock held by the caller's transaction surfaces as
+// SQLSTATE 55P03 instead of hanging the test. The probe always rolls back: it
+// is asking whether it *could* proceed, not changing anything.
+func probeUnderLock(ctx context.Context, pool *pgxpool.Pool, sql, chatSessionID string) error {
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `SET LOCAL lock_timeout = '500ms'`); err != nil {
+ return err
+ }
+ _, err = tx.Exec(ctx, sql, chatSessionID)
+ return err
+}
+
+// isLockTimeout reports the "I was blocked" answer: SQLSTATE 55P03,
+// lock_not_available.
+func isLockTimeout(err error) bool {
+ var pgErr *pgconn.PgError
+ return errors.As(err, &pgErr) && pgErr.Code == "55P03"
+}
+
func TestDeferredChannelIssueTaskPromotesAfterMediaSettlement(t *testing.T) {
pool := newResolveOriginatorPool(t)
ctx := context.Background()
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 18d5121b9a..e3ae0bdefe 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -2154,6 +2154,72 @@ func (q *Queries) LockChatSessionForDraftWrite(ctx context.Context, id pgtype.UU
return i, err
}
+const lockChatSessionForEnqueue = `-- name: LockChatSessionForEnqueue :one
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
+WHERE id = $1
+FOR NO KEY UPDATE
+`
+
+// The chat-task enqueue's answer to archiving, and the one lock on this row
+// that a concurrent inbound message must NOT wait behind.
+//
+// The channel run trigger is debounced, so the message is persisted the moment
+// it arrives and the task row is created a window later. An archive committing
+// inside that window cancels the tasks it can see — there are none yet — and
+// deletes the channel binding, and the flush then enqueues onto a conversation
+// the user closed. ClaimAgentTask does not read chat_session.status, so the
+// daemon runs it. Taking this lock as the enqueue transaction's first
+// statement and re-reading status under it makes both interleavings safe:
+// enqueue-then-archive is caught by the archive's cancel, archive-then-enqueue
+// is refused here.
+//
+// FOR NO KEY UPDATE, not the FOR UPDATE the delete / runtime-bind / draft locks
+// take, and the difference is the point. Those three want to block concurrent
+// INSERTs that reference this row: FOR UPDATE conflicts with the FOR KEY SHARE
+// an FK insert takes on its parent, which is exactly how LockChatSessionForDelete
+// stops a send from slipping a task in between its cancel and its delete. This
+// lock wants the opposite. Every inbound channel message is an INSERT into
+// chat_message, FK'd to this same row, and the flush it eventually triggers
+// holds this lock for the whole enqueue — under FOR UPDATE the room's next
+// message would block behind the previous message's enqueue. FOR NO KEY UPDATE
+// does not conflict with FOR KEY SHARE, so appends keep flowing, while it still
+// conflicts with FOR UPDATE and with FOR NO KEY UPDATE — which is what
+// SetChatSessionArchived's UPDATE (status is not a key column) and the delete
+// path's lock take. So the archive and the delete still serialise against this
+// enqueue in both directions, which is all this guard needs.
+//
+// Returns the whole row, not just the id, for the same reason
+// LockChatSessionForDraftWrite does: the caller must re-check status INSIDE the
+// transaction, because an enqueue blocked here resumes holding the row it read
+// before blocking — and the archive is what it was blocked on.
+//
+// Same row and same position (first statement) as the other three, so the
+// repo-wide chat_session -> agent_task_queue order is unchanged and no new
+// deadlock edge is introduced.
+func (q *Queries) LockChatSessionForEnqueue(ctx context.Context, id pgtype.UUID) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, lockChatSessionForEnqueue, id)
+ var i ChatSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.CreatorID,
+ &i.Title,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.Status,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UnreadSince,
+ &i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.ProjectID,
+ )
+ return i, err
+}
+
const lockChatSessionForRuntimeBind = `-- name: LockChatSessionForRuntimeBind :one
SELECT id FROM chat_session
WHERE id = $1
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index d6940ba282..70d0fdc171 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -353,6 +353,47 @@ SELECT id FROM chat_session
WHERE id = $1
FOR UPDATE;
+-- name: LockChatSessionForEnqueue :one
+-- The chat-task enqueue's answer to archiving, and the one lock on this row
+-- that a concurrent inbound message must NOT wait behind.
+--
+-- The channel run trigger is debounced, so the message is persisted the moment
+-- it arrives and the task row is created a window later. An archive committing
+-- inside that window cancels the tasks it can see — there are none yet — and
+-- deletes the channel binding, and the flush then enqueues onto a conversation
+-- the user closed. ClaimAgentTask does not read chat_session.status, so the
+-- daemon runs it. Taking this lock as the enqueue transaction's first
+-- statement and re-reading status under it makes both interleavings safe:
+-- enqueue-then-archive is caught by the archive's cancel, archive-then-enqueue
+-- is refused here.
+--
+-- FOR NO KEY UPDATE, not the FOR UPDATE the delete / runtime-bind / draft locks
+-- take, and the difference is the point. Those three want to block concurrent
+-- INSERTs that reference this row: FOR UPDATE conflicts with the FOR KEY SHARE
+-- an FK insert takes on its parent, which is exactly how LockChatSessionForDelete
+-- stops a send from slipping a task in between its cancel and its delete. This
+-- lock wants the opposite. Every inbound channel message is an INSERT into
+-- chat_message, FK'd to this same row, and the flush it eventually triggers
+-- holds this lock for the whole enqueue — under FOR UPDATE the room's next
+-- message would block behind the previous message's enqueue. FOR NO KEY UPDATE
+-- does not conflict with FOR KEY SHARE, so appends keep flowing, while it still
+-- conflicts with FOR UPDATE and with FOR NO KEY UPDATE — which is what
+-- SetChatSessionArchived's UPDATE (status is not a key column) and the delete
+-- path's lock take. So the archive and the delete still serialise against this
+-- enqueue in both directions, which is all this guard needs.
+--
+-- Returns the whole row, not just the id, for the same reason
+-- LockChatSessionForDraftWrite does: the caller must re-check status INSIDE the
+-- transaction, because an enqueue blocked here resumes holding the row it read
+-- before blocking — and the archive is what it was blocked on.
+--
+-- Same row and same position (first statement) as the other three, so the
+-- repo-wide chat_session -> agent_task_queue order is unchanged and no new
+-- deadlock edge is introduced.
+SELECT * FROM chat_session
+WHERE id = $1
+FOR NO KEY UPDATE;
+
-- name: LockChatSessionForDraftWrite :one
-- The autosave half of the agent_builder_draft protocol, and the writer's
-- answer to LockChatSessionForDelete.