Skip to content

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

Go

fix(chat): reland archived-session unread + mount-race auto-read (MUL-4360) (#5333)

Naiyuan Qing47f9c5813f3e
diff --git a/packages/core/chat/mutations.test.tsx b/packages/core/chat/mutations.test.tsx
new file mode 100644
index 0000000000..088250665b
--- /dev/null
+++ b/packages/core/chat/mutations.test.tsx
@@ -0,0 +1,127 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import { useSetChatSessionArchived } from "./mutations";
+import { chatKeys } from "./queries";
+import type { ChatSession } from "../types";
+
+vi.mock("../hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+const WS_ID = "ws-1";
+
+function makeSession(overrides: Partial<ChatSession> = {}): ChatSession {
+ return {
+ id: "s1",
+ workspace_id: WS_ID,
+ agent_id: "agent-1",
+ creator_id: "user-1",
+ title: "Session 1",
+ status: "active",
+ has_unread: true,
+ unread_count: 2,
+ created_at: "2026-07-10T00:00:00Z",
+ updated_at: "2026-07-10T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function createWrapper(qc: QueryClient) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ };
+}
+
+describe("useSetChatSessionArchived", () => {
+ let qc: QueryClient;
+ let setChatSessionArchived: ReturnType<
+ typeof vi.fn<(id: string, archived: boolean) => Promise<ChatSession>>
+ >;
+
+ beforeEach(() => {
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ setChatSessionArchived = vi.fn();
+ setApiInstance({ setChatSessionArchived } as unknown as ApiClient);
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ // MUL-4360: archiving must zero the row's unread locally so no badge (FAB,
+ // sidebar Chat tab, chat-window header) keeps counting a just-archived
+ // session in the frame before the refetch lands. Mirrors the backend, which
+ // forces unread to 0 for archived rows in ListAllChatSessionsByCreator.
+ it("optimistically zeroes unread when archiving", async () => {
+ setChatSessionArchived.mockResolvedValue(
+ makeSession({ status: "archived" }),
+ );
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [makeSession()]);
+
+ const { result } = renderHook(() => useSetChatSessionArchived(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ sessionId: "s1", archived: true });
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.status).toBe("archived");
+ expect(row.unread_count).toBe(0);
+ expect(row.has_unread).toBe(false);
+ });
+
+ // Unarchive must NOT fabricate an unread count — the true state comes back
+ // from the server refetch (last_read_at is untouched), so the optimistic
+ // patch leaves the row's unread fields as-is.
+ it("does not resurrect unread when unarchiving", async () => {
+ setChatSessionArchived.mockResolvedValue(makeSession({ status: "active" }));
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ status: "archived", has_unread: false, unread_count: 0 }),
+ ]);
+
+ const { result } = renderHook(() => useSetChatSessionArchived(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ sessionId: "s1", archived: false });
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.status).toBe("active");
+ expect(row.unread_count).toBe(0);
+ expect(row.has_unread).toBe(false);
+ });
+
+ // On failure the optimistic patch (status + zeroed unread) rolls back whole.
+ it("rolls back the unread patch when the request fails", async () => {
+ setChatSessionArchived.mockRejectedValue(new Error("boom"));
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [makeSession()]);
+
+ const { result } = renderHook(() => useSetChatSessionArchived(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await expect(
+ result.current.mutateAsync({ sessionId: "s1", archived: true }),
+ ).rejects.toThrow("boom");
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.status).toBe("active");
+ expect(row.unread_count).toBe(2);
+ expect(row.has_unread).toBe(true);
+ });
+});
diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.ts
index 3c70442491..cdb8f9a5e6 100644
--- a/packages/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -199,6 +199,14 @@ export function useSetChatSessionPinned() {
* `updated_at` so the row re-sorts by activity in whichever view it lands.
* The matching `chat:session_updated` WS event carries the new status to other
* tabs/devices — see use-realtime-sync.ts.
+ *
+ * Archiving also zeroes the row's unread locally so every badge (FAB, sidebar
+ * Chat tab, chat-window header) drops it in the same frame the row moves to the
+ * Archived view. The backend already forces unread to 0 for archived rows (see
+ * ListAllChatSessionsByCreator / MUL-4360); this is the optimistic half so there
+ * is no window where the header/sidebar still count a just-archived session
+ * before the refetch lands. Unarchive does NOT restore a count here — the true
+ * unread state comes back from the server refetch (last_read_at is untouched).
*/
export function useSetChatSessionArchived() {
const qc = useQueryClient();
@@ -220,7 +228,12 @@ export function useSetChatSessionArchived() {
sortChatSessions(
old.map((s) =>
s.id === sessionId
- ? { ...s, status: archived ? "archived" : "active", updated_at: nowIso }
+ ? {
+ ...s,
+ status: archived ? "archived" : "active",
+ updated_at: nowIso,
+ ...(archived ? { unread_count: 0, has_unread: false } : {}),
+ }
: s,
),
);
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index a3e3869309..4eb6bbed5b 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -12,11 +12,13 @@ import type {
ChatMessage,
ChatPendingTask,
ChatMessagesPage,
+ ChatSession,
InboxItem,
Workspace,
} from "../types";
import {
applyChatDoneToCache,
+ applyChatSessionUpdatedToCache,
applyWorkspaceUpdatedToCache,
handleInboxNew,
invalidateChatMessageQueries,
@@ -153,6 +155,87 @@ describe("applyChatDoneToCache", () => {
});
});
+describe("applyChatSessionUpdatedToCache", () => {
+ const WS_ID = "ws-1";
+
+ function makeSession(overrides: Partial<ChatSession> = {}): ChatSession {
+ return {
+ id: "s1",
+ workspace_id: WS_ID,
+ agent_id: "agent-1",
+ creator_id: "user-1",
+ title: "Session 1",
+ status: "active",
+ has_unread: true,
+ unread_count: 2,
+ created_at: "2026-07-10T00:00:00Z",
+ updated_at: "2026-07-10T00:00:00Z",
+ ...overrides,
+ };
+ }
+
+ // MUL-4360 cross-tab: chatSessionsOptions is staleTime: Infinity, so a stale
+ // cache in another tab never self-heals. When an archive event lands there,
+ // the row's unread must be forced to 0 to match the archive mutation and the
+ // backend, or the sidebar/header keep counting an archived session no one can
+ // open — the same stuck badge, one surface over.
+ it("zeroes unread when a session_updated event archives a cached unread row", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [makeSession()]);
+
+ applyChatSessionUpdatedToCache(qc, WS_ID, {
+ chat_session_id: "s1",
+ status: "archived",
+ updated_at: "2026-07-10T01:00:00Z",
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.status).toBe("archived");
+ expect(row.unread_count).toBe(0);
+ expect(row.has_unread).toBe(false);
+ });
+
+ // Unarchive must NOT fabricate unread — the true state comes back from the
+ // server refetch (last_read_at is untouched). An `active` status event leaves
+ // the row's unread fields exactly as cached, so a previously-zeroed archived
+ // row stays at 0 rather than being resurrected out of thin air.
+ it("does not resurrect unread when a session_updated event reactivates a row", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ status: "archived", has_unread: false, unread_count: 0 }),
+ ]);
+
+ applyChatSessionUpdatedToCache(qc, WS_ID, {
+ chat_session_id: "s1",
+ status: "active",
+ updated_at: "2026-07-10T02:00:00Z",
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.status).toBe("active");
+ expect(row.unread_count).toBe(0);
+ expect(row.has_unread).toBe(false);
+ });
+
+ // A plain rename carries neither status nor pinned; it must not touch unread
+ // (a live active session keeps its real unread count) or re-sort.
+ it("leaves unread untouched on a rename-only event", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [makeSession()]);
+
+ applyChatSessionUpdatedToCache(qc, WS_ID, {
+ chat_session_id: "s1",
+ title: "Renamed",
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.title).toBe("Renamed");
+ expect(row.status).toBe("active");
+ expect(row.unread_count).toBe(2);
+ expect(row.has_unread).toBe(true);
+ });
+});
+
describe("invalidateChatMessageQueries", () => {
it("invalidates both legacy and paged chat message caches", () => {
const qc = createQueryClient();
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index dc4b6943da..3586b65003 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -184,6 +184,58 @@ function patchLatestChatMessagePage(
};
}
+type ChatSessionUpdatedPayload = {
+ chat_session_id: string;
+ title?: string;
+ pinned?: boolean;
+ status?: "active" | "archived";
+ updated_at?: string;
+};
+
+/**
+ * Patch the cached sessions row for a `chat:session_updated` event (rename,
+ * pin/unpin, archive/unarchive from any tab/device) instead of refetching the
+ * whole list. `pinned` is present only on pin/unpin events and `status` only on
+ * archive/unarchive; a plain rename omits both, so absent fields leave existing
+ * state untouched. When either changes we re-sort so the row lands in the right
+ * place (pin → top; archive → the other list) like the server order.
+ *
+ * Archiving MUST also zero the row's unread here: the server payload carries
+ * only status/updated_at, and chatSessionsOptions is `staleTime: Infinity`, so a
+ * stale cache in another tab/device would otherwise keep an archived session's
+ * unread badge lit forever — the same MUL-4360 stuck-badge bug, one surface over.
+ * This mirrors the archive mutation's optimistic patch and the backend deriving
+ * unread_count=0 for archived rows. Unarchive does NOT fabricate a count — the
+ * true unread state comes back from the server refetch (last_read_at is
+ * untouched), so we leave the row's unread fields as-is for `active`.
+ */
+export function applyChatSessionUpdatedToCache(
+ qc: QueryClient,
+ wsId: string,
+ payload: ChatSessionUpdatedPayload,
+): void {
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) => {
+ if (!old) return old;
+ const next = old.map((s) =>
+ s.id === payload.chat_session_id
+ ? {
+ ...s,
+ title: payload.title ?? s.title,
+ pinned: payload.pinned ?? s.pinned,
+ status: payload.status ?? s.status,
+ updated_at: payload.updated_at ?? s.updated_at,
+ ...(payload.status === "archived"
+ ? { unread_count: 0, has_unread: false }
+ : {}),
+ }
+ : s,
+ );
+ return payload.pinned === undefined && payload.status === undefined
+ ? next
+ : sortChatSessions(next);
+ });
+}
+
/**
* Apply a workspace:updated event to the cache. Always refreshes the
* workspace list. If the incoming `issue_prefix` differs from what's
@@ -1123,42 +1175,16 @@ export function useRealtimeSync(
invalidateSessionLists();
});
- // chat:session_updated fires after the creator renames a session in
- // any tab/device. Patch the cached row inline so the dropdown reflects
- // the new title without a full sessions-list refetch.
+ // chat:session_updated fires after the creator renames, pins, or archives
+ // a session in any tab/device. Patch the cached row inline so the dropdown
+ // and badges reflect the change without a full sessions-list refetch — see
+ // applyChatSessionUpdatedToCache for why archive must also zero unread.
const unsubChatSessionUpdated = ws.on("chat:session_updated", (p) => {
- const payload = p as {
- chat_session_id: string;
- title?: string;
- pinned?: boolean;
- status?: "active" | "archived";
- updated_at?: string;
- };
+ const payload = p as ChatSessionUpdatedPayload;
chatWsLogger.info("chat:session_updated (global)", payload);
const id = getCurrentWsId();
if (!id) return;
- // `pinned` is present only on pin/unpin events and `status` only on
- // archive/unarchive; a plain rename omits both, so leave the existing
- // state untouched then. When either changes we re-sort so the row lands
- // in the right place (pin → top; archive → the other list) like the
- // server order.
- qc.setQueryData<ChatSession[]>(chatKeys.sessions(id), (old) => {
- if (!old) return old;
- const next = old.map((s) =>
- s.id === payload.chat_session_id
- ? {
- ...s,
- title: payload.title ?? s.title,
- pinned: payload.pinned ?? s.pinned,
- status: payload.status ?? s.status,
- updated_at: payload.updated_at ?? s.updated_at,
- }
- : s,
- );
- return payload.pinned === undefined && payload.status === undefined
- ? next
- : sortChatSessions(next);
- });
+ applyChatSessionUpdatedToCache(qc, id, payload);
});
// chat:session_deleted fires after a hard delete. The originating tab has
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index 3285c15d44..27e39dc84e 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, vi } from "vitest";
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
import type { Agent, ChatSession } from "@multica/core/types";
@@ -200,14 +200,76 @@ describe("useChatController.archiveSession", () => {
});
});
+// MUL-4360 mount race: `activeSessionId` is persisted, so on a bare `/chat`
+// navigation the page restores the last session as active for one frame before
+// its URL→store effect clears it back to null. The auto-mark-read must NOT fire
+// for that transiently-active session — otherwise the badge vanishes though the
+// user never opened it (the exact "no active session yet the red dot cleared"
+// report). The read is deferred a tick and cancelled when activeSessionId moves.
+describe("useChatController auto mark-read", () => {
+ const unread = makeSession({
+ id: "sA",
+ agent_id: "agent-a",
+ has_unread: true,
+ unread_count: 2,
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ h.store.activeSessionId = null;
+ h.store.selectedAgentId = null;
+ h.markReadMutate.mockClear();
+ h.appForeground.value = true;
+ h.sessions = [unread];
+ h.agents = [agentA];
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("marks read a session that stays active past the tick", () => {
+ h.store.activeSessionId = "sA";
+ renderHook(() => useChatController());
+
+ // Deferred, not synchronous — nothing fires on the mount frame.
+ expect(h.markReadMutate).not.toHaveBeenCalled();
+
+ act(() => vi.advanceTimersByTime(1));
+ expect(h.markReadMutate).toHaveBeenCalledWith("sA");
+ });
+
+ it("does NOT mark read a session that was only momentarily active on mount", () => {
+ // Mount restores sA as active (persisted, unread)...
+ h.store.activeSessionId = "sA";
+ const { rerender } = renderHook(() => useChatController());
+
+ // ...then the page's URL→store effect clears it before the tick elapses.
+ h.store.activeSessionId = null;
+ rerender();
+
+ act(() => vi.advanceTimersByTime(1));
+ expect(h.markReadMutate).not.toHaveBeenCalled();
+ });
+});
+
+// Foreground gating (MUL-4485): a reply that lands while the app is backgrounded
+// must stay unread and clear once the user returns. This composes with the
+// MUL-4360 mount-race defer above — the read is scheduled a tick after the
+// effect runs — so each assertion advances fake timers to let it (or not) fire.
describe("useChatController auto mark-read — foreground gating (MUL-4485)", () => {
const unreadActive = makeSession({ id: "sU", agent_id: "agent-a", has_unread: true });
beforeEach(() => {
+ vi.useFakeTimers();
h.markReadMutate.mockClear();
h.appForeground.value = true;
});
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
function renderController(activeSessionId: string | null, sessions: ChatSession[]) {
h.store.activeSessionId = activeSessionId;
h.store.selectedAgentId = null;
@@ -218,24 +280,28 @@ describe("useChatController auto mark-read — foreground gating (MUL-4485)", ()
it("marks the active unread session read while the app is in the foreground", () => {
renderController("sU", [unreadActive]);
+ act(() => vi.advanceTimersByTime(1));
expect(h.markReadMutate).toHaveBeenCalledWith("sU");
});
it("does NOT mark read while the app is backgrounded, so the reply stays unread", () => {
h.appForeground.value = false;
renderController("sU", [unreadActive]);
+ act(() => vi.advanceTimersByTime(1));
expect(h.markReadMutate).not.toHaveBeenCalled();
});
it("marks read once the user returns to the foreground", () => {
h.appForeground.value = false;
const { rerender } = renderController("sU", [unreadActive]);
+ act(() => vi.advanceTimersByTime(1));
expect(h.markReadMutate).not.toHaveBeenCalled();
act(() => {
h.appForeground.value = true;
rerender();
});
+ act(() => vi.advanceTimersByTime(1));
expect(h.markReadMutate).toHaveBeenCalledWith("sU");
});
});
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 5457a168d2..e605b05af2 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -312,14 +312,32 @@ export function useChatController(opts?: { isActive?: boolean }) {
// additionally requires the window to be visible and focused: a reply landing
// while the app is backgrounded must stay unread so the sidebar badges it
// (MUL-4485); it clears the moment the user returns and this effect re-runs.
+ //
+ // The read is deferred by a tick and cancelled on cleanup, so a session that
+ // is only *momentarily* active never gets marked read. This is the fix for
+ // MUL-4360's mount race: `activeSessionId` is persisted, so on a bare `/chat`
+ // navigation the page restores the last session for one frame before its
+ // URL→store effect (which runs AFTER this hook's effects, since the hook is
+ // called first) clears it back to null. Without the defer, that restored-but-
+ // never-opened session was marked read in that gap — its badge vanished
+ // though the user never opened it (right pane still shows "select a chat").
+ // Deferring lets the subsequent activeSessionId change cancel the pending
+ // 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(() => {
if (!isActive || !appForeground || !activeSessionId) return;
if (!currentHasUnread) return;
- uiLogger.info("auto markRead", { sessionId: activeSessionId });
- markRead.mutate(activeSessionId);
+ const sessionId = activeSessionId;
+ const timer = setTimeout(() => {
+ if (useChatStore.getState().activeSessionId !== sessionId) return;
+ uiLogger.info("auto markRead", { sessionId });
+ markRead.mutate(sessionId);
+ }, 0);
+ return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable
}, [isActive, appForeground, activeSessionId, currentHasUnread]);
diff --git a/server/internal/handler/chat_test.go b/server/internal/handler/chat_test.go
index 63c3edf9c5..877fc2e343 100644
--- a/server/internal/handler/chat_test.go
+++ b/server/internal/handler/chat_test.go
@@ -788,3 +788,80 @@ VALUES ($1, $2, 'feishu', $3, 'p2p')
t.Fatal("unarchive recreated the channel_chat_session_binding; it must not restore or steal the channel")
}
}
+
+// TestListChatSessions_ArchivedSessionReportsZeroUnread pins the MUL-4360 fix:
+// ListAllChatSessionsByCreator forces unread_count/has_unread to 0 for archived
+// rows even when assistant messages sit past the read cursor, so a stuck unread
+// badge cannot survive on any surface (FAB, sidebar Chat tab, chat-window
+// header). Because archiving deliberately does NOT advance last_read_at,
+// unarchiving must restore the session's true unread count.
+func TestListChatSessions_ArchivedSessionReportsZeroUnread(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "ChatArchivedUnreadAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ ctx := context.Background()
+
+ // An assistant reply the user never read.
+ if _, err := testPool.Exec(ctx,
+ `INSERT INTO chat_message (chat_session_id, role, content) VALUES ($1, 'assistant', 'unread reply')`,
+ sessionID); err != nil {
+ t.Fatalf("insert assistant message: %v", err)
+ }
+ // Pin the read cursor firmly before that message so it counts as unread
+ // regardless of insert-time clock skew (last_read_at defaults to now()).
+ if _, err := testPool.Exec(ctx,
+ `UPDATE chat_session SET last_read_at = 'epoch' WHERE id = $1`, sessionID); err != nil {
+ t.Fatalf("reset last_read_at: %v", err)
+ }
+
+ unreadOf := func() (int, bool) {
+ t.Helper()
+ req := newRequest("GET", "/api/chat/sessions?status=all", nil)
+ req = withChatTestWorkspaceCtx(t, req)
+ w := httptest.NewRecorder()
+ testHandler.ListChatSessions(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListChatSessions: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp []ChatSessionResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode list: %v", err)
+ }
+ for _, s := range resp {
+ if s.ID == sessionID {
+ return s.UnreadCount, s.HasUnread
+ }
+ }
+ t.Fatalf("session %s not found in list of %d", sessionID, len(resp))
+ return 0, false
+ }
+
+ archive := func(archived bool) {
+ t.Helper()
+ req := newRequest("PATCH", "/api/chat/sessions/"+sessionID+"/archive", map[string]any{"archived": archived})
+ 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())
+ }
+ }
+
+ // Active baseline: the unread reply counts (guards against a regression that
+ // would zero unread for live sessions too).
+ if n, has := unreadOf(); n != 1 || !has {
+ t.Fatalf("active session unread: want count=1 has=true, got count=%d has=%v", n, has)
+ }
+
+ // Archived: unread forced to 0 even though the message still sits past the cursor.
+ archive(true)
+ if n, has := unreadOf(); n != 0 || has {
+ t.Fatalf("archived session unread: want count=0 has=false, got count=%d has=%v", n, has)
+ }
+
+ // Unarchive restores the true unread state (last_read_at was never touched).
+ archive(false)
+ if n, has := unreadOf(); n != 1 || !has {
+ t.Fatalf("unarchived session unread: want count=1 has=true, got count=%d has=%v", n, has)
+ }
+}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 95b68d871e..249b1edc41 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -473,10 +473,12 @@ func (q *Queries) LinkChatMessageToTask(ctx context.Context, arg LinkChatMessage
const listAllChatSessionsByCreator = `-- name: ListAllChatSessionsByCreator :many
SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at,
- (SELECT count(*) FROM chat_message m
- WHERE m.chat_session_id = cs.id
- AND m.role = 'assistant'
- AND m.created_at > cs.last_read_at)::int AS unread_count,
+ CASE WHEN cs.status = 'archived' THEN 0
+ ELSE (SELECT count(*) FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ AND m.role = 'assistant'
+ AND m.created_at > cs.last_read_at)
+ END::int AS unread_count,
COALESCE(lm.content, '') AS last_message_content,
COALESCE(lm.role, '') AS last_message_role,
lm.created_at AS last_message_at,
@@ -523,6 +525,13 @@ type ListAllChatSessionsByCreatorRow struct {
LastMessageKind string `json:"last_message_kind"`
}
+// Unlike ListChatSessionsByCreator this returns archived sessions too (for the
+// "Archived" view), so unread must be forced to 0 for archived rows: archiving
+// deliberately does NOT advance last_read_at (so unarchive can restore the true
+// unread state), but an archived session is read-only and hidden from history,
+// so any residual unread is uncleanable and must not light up any badge. Gating
+// on status here is the single source of truth for all unread surfaces (FAB,
+// sidebar Chat tab, chat-window header) — see MUL-4360.
func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllChatSessionsByCreatorParams) ([]ListAllChatSessionsByCreatorRow, error) {
rows, err := q.db.Query(ctx, listAllChatSessionsByCreator, arg.WorkspaceID, arg.CreatorID)
if err != nil {
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 63f97b6a82..56f2600c28 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -37,11 +37,20 @@ WHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'
ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;
-- name: ListAllChatSessionsByCreator :many
+-- Unlike ListChatSessionsByCreator this returns archived sessions too (for the
+-- "Archived" view), so unread must be forced to 0 for archived rows: archiving
+-- deliberately does NOT advance last_read_at (so unarchive can restore the true
+-- unread state), but an archived session is read-only and hidden from history,
+-- so any residual unread is uncleanable and must not light up any badge. Gating
+-- on status here is the single source of truth for all unread surfaces (FAB,
+-- sidebar Chat tab, chat-window header) — see MUL-4360.
SELECT cs.*,
- (SELECT count(*) FROM chat_message m
- WHERE m.chat_session_id = cs.id
- AND m.role = 'assistant'
- AND m.created_at > cs.last_read_at)::int AS unread_count,
+ CASE WHEN cs.status = 'archived' THEN 0
+ ELSE (SELECT count(*) FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ AND m.role = 'assistant'
+ AND m.created_at > cs.last_read_at)
+ END::int AS unread_count,
COALESCE(lm.content, '') AS last_message_content,
COALESCE(lm.role, '') AS last_message_role,
lm.created_at AS last_message_at,