Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(chat): clear external channel binding on archive, drop archived from FAB unread (#5214)
Naiyuan Qing0b054b5c8b04
diff --git a/packages/core/chat/queries.test.ts b/packages/core/chat/queries.test.tsindex 0db2dd179a..68b08ef1ed 100644--- a/packages/core/chat/queries.test.ts+++ b/packages/core/chat/queries.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import type { TaskMessagePayload } from "../types/events";import type { ChatSession } from "../types/chat";import {+ countUnreadChatSessions,isTaskMessageTaskId,mergeTaskMessagesBySeq,sortChatSessions,@@ -103,3 +104,48 @@ describe("sortChatSessions", () => {expect(input.map((s) => s.id)).toEqual(snapshot);});});++describe("countUnreadChatSessions", () => {+ const session = (over: Partial<ChatSession>): ChatSession => ({+ id: "s",+ workspace_id: "w",+ agent_id: "a",+ creator_id: "c",+ title: "t",+ status: "active",+ has_unread: false,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...over,+ });++ it("counts only active sessions that have unread", () => {+ const sessions = [+ session({ id: "active-unread", status: "active", has_unread: true }),+ session({ id: "active-read", status: "active", has_unread: false }),+ ];++ expect(countUnreadChatSessions(sessions)).toBe(1);+ });++ it("excludes archived sessions even when they carry unread", () => {+ // The stuck-badge bug: an archived session keeps has_unread, but it is+ // hidden from the default list and read-only, so the badge must ignore it+ // (MUL-4372).+ const sessions = [+ session({ id: "archived-unread", status: "archived", has_unread: true }),+ session({ id: "active-unread", status: "active", has_unread: true }),+ ];++ expect(countUnreadChatSessions(sessions)).toBe(1);+ });++ it("returns 0 when the only unread sessions are archived", () => {+ const sessions = [+ session({ id: "archived-1", status: "archived", has_unread: true }),+ session({ id: "archived-2", status: "archived", has_unread: true }),+ ];++ expect(countUnreadChatSessions(sessions)).toBe(0);+ });+});diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.tsindex 3b5a3df76f..8793530efb 100644--- a/packages/core/chat/queries.ts+++ b/packages/core/chat/queries.ts@@ -73,6 +73,20 @@ export function sortChatSessions(sessions: ChatSession[]): ChatSession[] {});}+/**+ * Number of sessions that should light up the quick-chat FAB unread badge.+ * `chatSessionsOptions` fetches `status=all` (active + archived) so the thread+ * list can render an Archived view, but archived sessions must NOT contribute+ * to the badge: they are read-only and hidden from the default history list, so+ * a badge sourced from one is uncleared-able — the user can't open it to mark it+ * read. Archiving now also drops the external-channel binding server-side, so no+ * new unread should land on an archived session; this filter is the front-end+ * half of that guarantee (MUL-4372).+ */+export function countUnreadChatSessions(sessions: ChatSession[]): number {+ return sessions.filter((s) => s.has_unread && s.status !== "archived").length;+}+export function chatPinnedAgentsOptions(wsId: string) {return queryOptions({queryKey: chatKeys.pinnedAgents(wsId),diff --git a/packages/views/chat/components/chat-fab.tsx b/packages/views/chat/components/chat-fab.tsxindex 5354911230..15bd92c3f6 100644--- a/packages/views/chat/components/chat-fab.tsx+++ b/packages/views/chat/components/chat-fab.tsx@@ -4,7 +4,11 @@ import { MessageCircle } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { cn } from "@multica/ui/lib/utils";import { useChatStore } from "@multica/core/chat";-import { chatSessionsOptions, hasPendingChatTasksOptions } from "@multica/core/chat/queries";+import {+ chatSessionsOptions,+ countUnreadChatSessions,+ hasPendingChatTasksOptions,+} from "@multica/core/chat/queries";import { useWorkspaceId } from "@multica/core/hooks";import { createLogger } from "@multica/core/logger";import {@@ -33,7 +37,7 @@ export function ChatFab() {if (isOpen) return null;- const unreadSessionCount = sessions.filter((s) => s.has_unread).length;+ const unreadSessionCount = countUnreadChatSessions(sessions);const isRunning = hasPending?.has_pending ?? false;const handleClick = () => {diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 564d93e310..e105cd99b0 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -366,6 +366,17 @@ type SetChatSessionArchivedRequest struct {// user's history (behind the "Archived" entry) and the conversation becomes// read-only — SendChatMessage refuses status='archived'. Hard delete is only// offered from the archived list, so nothing is destroyed in one hover click.+//+// Archiving also severs any external-channel binding. The web send path already+// treats status='archived' as read-only, but the channel engine (Feishu/Slack)+// resolves inbound traffic through channel_chat_session_binding without checking+// session status, so a bound session kept accumulating agent replies — and a+// stuck unread badge — after the user archived it (MUL-4372). Dropping the+// binding in the same tx makes the next inbound message for that external chat+// create a fresh chat_session under a new binding (see EnsureSession) instead of+// 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.func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {@@ -385,7 +396,15 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)return}- updated, err := h.Queries.SetChatSessionArchived(r.Context(), db.SetChatSessionArchivedParams{+ 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)++ updated, err := qtx.SetChatSessionArchived(r.Context(), db.SetChatSessionArchivedParams{ID: session.ID,Archived: req.Archived,})@@ -394,6 +413,19 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)return}+ if req.Archived {+ if err := qtx.DeleteChannelChatSessionBindingBySession(r.Context(), session.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clear chat session channel binding")+ return+ }+ }++ if err := tx.Commit(r.Context()); err != nil {+ slog.Warn("commit chat session archive failed", "session_id", sessionID, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to commit chat session update")+ return+ }+resolvedSessionID := uuidToString(updated.ID)status := updated.Statush.publishChat(protocol.EventChatSessionUpdated, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionUpdatedPayload{diff --git a/server/internal/handler/chat_test.go b/server/internal/handler/chat_test.goindex 2fc50e1e67..63c3edf9c5 100644--- a/server/internal/handler/chat_test.go+++ b/server/internal/handler/chat_test.go@@ -695,3 +695,96 @@ VALUES ($1, 'feishu', $2, $3, 'final')t.Fatal("deleted chat session's channel_outbound_card_message was not pruned (no reaper would ever collect it)")}}++// TestSetChatSessionArchived_ClearsChannelBinding verifies the archive path+// severs the external-channel link (MUL-4372): the channel engine resolves+// inbound Feishu/Slack traffic through channel_chat_session_binding without+// checking session status, so an archived-but-still-bound session kept+// accumulating agent replies and a stuck, uncleared unread badge. Archiving must+// drop the binding so the next inbound message forks a fresh session; unarchive+// must NOT recreate it (a later session may already own the channel).+func TestSetChatSessionArchived_ClearsChannelBinding(t *testing.T) {+ agentID := createHandlerTestAgent(t, "ChatArchiveBindingAgent", []byte("[]"))+ sessionID := createHandlerTestChatSession(t, agentID)+ ctx := context.Background()++ const appID = "cli_chat_archive_binding"+ const channelChatID = "oc_chat_archive_binding"++ // channel_* rows have no FK to chat_session/workspace (MUL-3515 §4), so they+ // outlive the helper's chat_session cleanup; clear by deterministic key.+ cleanChannel := func() {+ _, _ = testPool.Exec(context.Background(),+ `DELETE FROM channel_chat_session_binding WHERE channel_chat_id = $1`, channelChatID)+ _, _ = testPool.Exec(context.Background(),+ `DELETE FROM channel_installation WHERE channel_type = 'feishu' AND config->>'app_id' = $1`, appID)+ }+ cleanChannel()+ t.Cleanup(cleanChannel)++ var installID string+ if err := testPool.QueryRow(ctx, `+INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, installer_user_id)+VALUES ($1, $2, 'feishu', jsonb_build_object('app_id', $3::text), $4)+RETURNING id+`, testWorkspaceID, agentID, appID, testUserID).Scan(&installID); err != nil {+ t.Fatalf("insert channel_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, 'feishu', $3, 'p2p')+`, sessionID, installID, channelChatID); err != nil {+ t.Fatalf("insert channel_chat_session_binding: %v", err)+ }++ archive := func(archived bool) {+ t.Helper()+ payload := `{"archived":false}`+ if archived {+ payload = `{"archived":true}`+ }+ req := httptest.NewRequest(http.MethodPost, "/api/chat/sessions/"+sessionID+"/archive", bytes.NewReader([]byte(payload)))+ req.Header.Set("X-User-ID", testUserID)+ req = withURLParam(req, "sessionId", sessionID)+ req = withChatTestWorkspaceCtx(t, req)+ w := httptest.NewRecorder()+ testHandler.SetChatSessionArchived(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("SetChatSessionArchived(%v): expected 200, got %d: %s", archived, w.Code, w.Body.String())+ }+ }++ bindingExists := func() bool {+ t.Helper()+ var exists bool+ if err := testPool.QueryRow(ctx,+ `SELECT EXISTS (SELECT 1 FROM channel_chat_session_binding WHERE channel_chat_id = $1)`, channelChatID).Scan(&exists); err != nil {+ t.Fatalf("query chat session binding: %v", err)+ }+ return exists+ }++ // Archive → binding must be gone so future channel traffic cannot revive+ // this now read-only session.+ archive(true)+ if bindingExists() {+ t.Fatal("archived chat session's channel_chat_session_binding was not cleared")+ }++ var status string+ if err := testPool.QueryRow(ctx,+ `SELECT status FROM chat_session WHERE id = $1`, sessionID).Scan(&status); err != nil {+ t.Fatalf("query chat session status: %v", err)+ }+ if status != "archived" {+ t.Fatalf("expected chat session status 'archived', got %q", status)+ }++ // Unarchive → must NOT recreate/steal the binding. A later inbound message+ // may already have forked a new session that owns the channel now.+ archive(false)+ if bindingExists() {+ t.Fatal("unarchive recreated the channel_chat_session_binding; it must not restore or steal the channel")+ }+}