Skip to content

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

Go

fix(chat): advance selection to next chat when archiving the open session (#5110)

Jiayuan Zhang4a93f4ce41c2
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index 4a06d3c653..7e110612ff 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -100,6 +100,23 @@ export function ChatPage() {
setComposingNew(false);
};
+ // Single archive path for both entry points (thread-list row + conversation
+ // header). When the archived chat is the one in view, move the pane off it:
+ // on desktop advance to the next chat (Inbox-style); on mobile drop back to
+ // the list, which reads more naturally than being thrown into an unrelated
+ // conversation full-screen. Archiving any other chat leaves the view put.
+ const handleArchive = (session: ChatSession) => {
+ if (session.id === c.activeSessionId) {
+ if (isMobile) {
+ c.setActiveSession(null);
+ setComposingNew(false);
+ } else {
+ c.advanceSelectionAfterArchive(session);
+ }
+ }
+ c.archiveSession(session.id);
+ };
+
const startNewChat = (agent: Agent | null) => {
if (agent) c.handleStartNewChat(agent);
else c.handleNewChat();
@@ -131,6 +148,7 @@ export function ChatPage() {
agents={c.agents}
activeSessionId={c.activeSessionId}
onSelectSession={handleSelect}
+ onArchive={handleArchive}
/>
</div>
);
@@ -142,7 +160,11 @@ export function ChatPage() {
const conversation = (
<div className="flex flex-1 flex-col min-h-0">
{c.currentSession && (
- <ChatSessionHeader session={c.currentSession} agent={c.activeAgent} />
+ <ChatSessionHeader
+ session={c.currentSession}
+ agent={c.activeAgent}
+ onArchive={handleArchive}
+ />
)}
{c.showSkeleton ? (
<ChatMessageSkeleton />
diff --git a/packages/views/chat/components/chat-session-header.tsx b/packages/views/chat/components/chat-session-header.tsx
index 842e99e630..ff05b10628 100644
--- a/packages/views/chat/components/chat-session-header.tsx
+++ b/packages/views/chat/components/chat-session-header.tsx
@@ -41,9 +41,14 @@ import { useT } from "../../i18n";
export function ChatSessionHeader({
session,
agent,
+ onArchive,
}: {
session: ChatSession;
agent: Agent | null;
+ // Archiving the open conversation must move the pane off it (advance to the
+ // next chat on desktop, back to the list on mobile), so the parent owns it —
+ // see ChatPage.handleArchive. Falls back to a plain status flip if unwired.
+ onArchive?: (session: ChatSession) => void;
}) {
const { t } = useT("chat");
const wsPaths = useWorkspacePaths();
@@ -91,7 +96,10 @@ export function ChatSessionHeader({
deleteSession.mutate(session.id);
};
- const doArchive = () => setArchived.mutate({ sessionId: session.id, archived: true });
+ const doArchive = () =>
+ onArchive
+ ? onArchive(session)
+ : setArchived.mutate({ sessionId: session.id, archived: true });
const doUnarchive = () => setArchived.mutate({ sessionId: session.id, archived: false });
return (
diff --git a/packages/views/chat/components/chat-thread-list.test.tsx b/packages/views/chat/components/chat-thread-list.test.tsx
new file mode 100644
index 0000000000..96a56ae7bc
--- /dev/null
+++ b/packages/views/chat/components/chat-thread-list.test.tsx
@@ -0,0 +1,142 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { Agent, ChatSession } from "@multica/core/types";
+import enChat from "../../locales/en/chat.json";
+import enIssues from "../../locales/en/issues.json";
+
+// --- Mocks ------------------------------------------------------------------
+// The list no longer owns the archive-advance behavior — the parent (ChatPage)
+// does, so it stays layout-aware and routes through the shared controller. Here
+// we only assert the history-row Archive action delegates to the `onArchive`
+// prop and does NOT fire the archive mutation itself. The advance semantics
+// (next / previous / clear / cross-agent sync) are covered in the controller
+// test, and mobile-vs-desktop in the page. setActiveSession/archiveMutate are
+// kept as negative assertions: the list must not touch them for a history
+// archive anymore.
+
+const setActiveSession = vi.fn();
+const archiveMutate = vi.fn();
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => (
+ <span data-testid={`avatar-${actorId}`} />
+ ),
+}));
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+vi.mock("@multica/core/agents", () => ({
+ useWorkspacePresenceMap: () => ({ byAgent: new Map() }),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { cancelTaskById: vi.fn() },
+}));
+
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: (selector: (s: { setActiveSession: typeof setActiveSession }) => unknown) =>
+ selector({ setActiveSession }),
+}));
+
+vi.mock("@multica/core/chat/mutations", () => ({
+ useDeleteChatSession: () => ({ mutate: vi.fn(), isPending: false }),
+ useSetChatSessionPinned: () => ({ mutate: vi.fn(), isPending: false }),
+ useSetChatSessionArchived: () => ({ mutate: archiveMutate, isPending: false }),
+}));
+
+vi.mock("@tanstack/react-query", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@tanstack/react-query")>();
+ return {
+ ...actual,
+ useQuery: () => ({ data: { tasks: [] } }),
+ useQueryClient: () => ({ setQueryData: vi.fn(), invalidateQueries: vi.fn() }),
+ };
+});
+
+import { ChatThreadList } from "./chat-thread-list";
+
+const TEST_RESOURCES = { en: { chat: enChat, issues: enIssues } };
+
+function makeSession(overrides: Partial<ChatSession> & Pick<ChatSession, "id">): ChatSession {
+ return {
+ workspace_id: "ws-1",
+ agent_id: "agent-1",
+ creator_id: "user-1",
+ title: `Chat ${overrides.id}`,
+ status: "active",
+ has_unread: false,
+ unread_count: 0,
+ last_message: null,
+ pinned: false,
+ created_at: new Date(0).toISOString(),
+ updated_at: new Date(0).toISOString(),
+ ...overrides,
+ };
+}
+
+const agent = { id: "agent-1", name: "Alpha" } as unknown as Agent;
+
+// Sessions are sorted by most-recent activity (updated_at) first, pinned first.
+// Give them descending timestamps so the rendered order is s1, s2, s3.
+const sessions: ChatSession[] = [
+ makeSession({ id: "s1", updated_at: "2026-07-08T03:00:00Z" }),
+ makeSession({ id: "s2", updated_at: "2026-07-08T02:00:00Z" }),
+ makeSession({ id: "s3", updated_at: "2026-07-08T01:00:00Z" }),
+];
+
+function renderList(activeSessionId: string | null, onArchive = vi.fn()) {
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatThreadList
+ sessions={sessions}
+ agents={[agent]}
+ activeSessionId={activeSessionId}
+ onSelectSession={vi.fn()}
+ onArchive={onArchive}
+ />
+ </I18nProvider>,
+ );
+ return onArchive;
+}
+
+const ARCHIVE_LABEL = enChat.list.archive;
+
+describe("ChatThreadList archive delegation", () => {
+ beforeEach(() => {
+ setActiveSession.mockClear();
+ archiveMutate.mockClear();
+ });
+
+ it("delegates the history-row Archive action to onArchive with that session", () => {
+ const onArchive = renderList("s2");
+ // Rows render in order s1, s2, s3 → the second archive button is s2's.
+ const archiveButtons = screen.getAllByRole("button", { name: ARCHIVE_LABEL });
+ fireEvent.click(archiveButtons[1]!);
+
+ expect(onArchive).toHaveBeenCalledTimes(1);
+ expect(onArchive.mock.calls[0]![0]).toMatchObject({ id: "s2" });
+ });
+
+ it("passes the archived row's session even when it isn't the open one", () => {
+ const onArchive = renderList("s1");
+ const archiveButtons = screen.getAllByRole("button", { name: ARCHIVE_LABEL });
+ // Archive s3 while s1 is the open one — the parent decides what to do.
+ fireEvent.click(archiveButtons[2]!);
+
+ expect(onArchive).toHaveBeenCalledTimes(1);
+ expect(onArchive.mock.calls[0]![0]).toMatchObject({ id: "s3" });
+ });
+
+ it("does not flip archive status or move selection itself", () => {
+ renderList("s2");
+ const archiveButtons = screen.getAllByRole("button", { name: ARCHIVE_LABEL });
+ fireEvent.click(archiveButtons[1]!);
+
+ // Advance + mutation are the parent/controller's job now; the list stays out.
+ expect(setActiveSession).not.toHaveBeenCalled();
+ expect(archiveMutate).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsx
index f5460d4000..1b4780aa47 100644
--- a/packages/views/chat/components/chat-thread-list.tsx
+++ b/packages/views/chat/components/chat-thread-list.tsx
@@ -75,11 +75,16 @@ export function ChatThreadList({
agents,
activeSessionId,
onSelectSession,
+ onArchive,
}: {
sessions: ChatSession[];
agents: Agent[];
activeSessionId: string | null;
onSelectSession: (session: ChatSession) => void;
+ // Archiving is owned by the parent so the selection advance stays layout-
+ // aware (desktop advances to the next chat; mobile drops back to the list)
+ // and routes through the shared controller — see ChatPage.handleArchive.
+ onArchive: (session: ChatSession) => void;
}) {
const { t } = useT("chat");
const wsId = useWorkspaceId();
@@ -358,7 +363,7 @@ export function ChatThreadList({
<RowAction
icon={<Archive className="size-3.5" />}
label={t(($) => $.list.archive)}
- onClick={() => setArchived.mutate({ sessionId: session.id, archived: true })}
+ onClick={() => onArchive(session)}
/>
)}
</>
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index f8a2bc597f..75498a9bae 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -1127,9 +1127,15 @@ function SessionDropdown({
// bypass the "archive first, delete only from Archived" semantics.
const handleArchive = (session: ChatSession) => {
if (activeSessionId === session.id) {
- // Eager local clear when archiving the session in view, so the composer
- // doesn't keep pointing at a now read-only session until WS catches up.
- setActiveSession(null);
+ // Archiving the session in view: advance to the next chat (fall back to
+ // the previous, clear only when none remain) instead of stranding the
+ // composer on a now read-only session — mirrors the Chat tab and the
+ // Inbox list. Routing the non-null advance through onSelectSession keeps
+ // selectedAgentId in sync when the next chat belongs to another agent.
+ const idx = historySessions.findIndex((s) => s.id === session.id);
+ const next = historySessions[idx + 1] ?? historySessions[idx - 1] ?? null;
+ if (next) onSelectSession(next);
+ else setActiveSession(null);
}
setArchived.mutate({ sessionId: session.id, archived: true });
};
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
new file mode 100644
index 0000000000..6c2861552e
--- /dev/null
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -0,0 +1,195 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import type { Agent, ChatSession } from "@multica/core/types";
+
+// --- Shared mutable state (hoisted so vi.mock factories can reach it) --------
+const h = vi.hoisted(() => {
+ const store = {
+ activeSessionId: null as string | null,
+ selectedAgentId: null as string | null,
+ setActiveSession: vi.fn((id: string | null) => {
+ store.activeSessionId = id;
+ }),
+ setSelectedAgentId: vi.fn((id: string | null) => {
+ store.selectedAgentId = id;
+ }),
+ };
+ return {
+ store,
+ archivedMutate: vi.fn(),
+ // useQuery reads these so each test can vary the loaded data.
+ sessions: [] as ChatSession[],
+ agents: [] as Agent[],
+ };
+});
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (sel: (s: { user: { id: string } }) => unknown) =>
+ sel({ user: { id: "user-1" } }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ agentListOptions: () => ({ queryKey: ["agents"] }),
+ memberListOptions: () => ({ queryKey: ["members"] }),
+}));
+vi.mock("@multica/views/issues/components", () => ({ canAssignAgent: () => true }));
+vi.mock("@multica/core/api", () => ({
+ api: { sendChatMessage: vi.fn(), cancelTaskById: vi.fn() },
+}));
+vi.mock("@multica/core/agents", () => ({
+ useAgentPresenceDetail: () => ({ availability: "online" }),
+ useWorkspaceAgentAvailability: () => "available",
+}));
+vi.mock("@multica/core/hooks/use-file-upload", () => ({
+ useFileUpload: () => ({ uploadWithToast: vi.fn() }),
+}));
+vi.mock("@multica/core/chat/mutations", () => ({
+ useCreateChatSession: () => ({ mutateAsync: vi.fn() }),
+ useMarkChatSessionRead: () => ({ mutate: vi.fn() }),
+ useSetChatSessionArchived: () => ({ mutate: h.archivedMutate }),
+}));
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: Object.assign(
+ (sel: (s: typeof h.store) => unknown) => sel(h.store),
+ { getState: () => h.store },
+ ),
+}));
+vi.mock("@multica/core/logger", () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+}));
+vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "x" }) }));
+vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+
+vi.mock("@tanstack/react-query", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@tanstack/react-query")>();
+ return {
+ ...actual,
+ useQuery: (options: { queryKey?: unknown[] }) => {
+ const key = options.queryKey ?? [];
+ if (key.includes("agents")) return { data: h.agents };
+ if (key.includes("members")) {
+ return { data: [{ user_id: "user-1", role: "admin" }] };
+ }
+ if (key.includes("sessions")) return { data: h.sessions, isSuccess: true };
+ return { data: null };
+ },
+ useInfiniteQuery: () => ({
+ data: undefined,
+ isLoading: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ }),
+ useQueryClient: () => ({
+ getQueryData: vi.fn(),
+ setQueryData: vi.fn(),
+ invalidateQueries: vi.fn(),
+ }),
+ };
+});
+
+import { useChatController } from "./use-chat-controller";
+
+// --- Fixtures ---------------------------------------------------------------
+function makeSession(
+ overrides: Partial<ChatSession> & Pick<ChatSession, "id" | "agent_id">,
+): ChatSession {
+ return {
+ workspace_id: "ws-1",
+ creator_id: "user-1",
+ title: `Chat ${overrides.id}`,
+ status: "active",
+ has_unread: false,
+ unread_count: 0,
+ last_message: null,
+ pinned: false,
+ created_at: new Date(0).toISOString(),
+ updated_at: new Date(0).toISOString(),
+ ...overrides,
+ };
+}
+
+const agentA = { id: "agent-a", name: "Alpha" } as unknown as Agent;
+const agentB = { id: "agent-b", name: "Beta" } as unknown as Agent;
+
+// Descending updated_at → sortChatSessions renders them sA, sB, sC.
+const sA = makeSession({ id: "sA", agent_id: "agent-a", updated_at: "2026-07-08T03:00:00Z" });
+const sB = makeSession({ id: "sB", agent_id: "agent-b", updated_at: "2026-07-08T02:00:00Z" });
+const sC = makeSession({ id: "sC", agent_id: "agent-a", updated_at: "2026-07-08T01:00:00Z" });
+
+function setup(activeSessionId: string | null, sessions: ChatSession[], agents: Agent[]) {
+ h.store.activeSessionId = activeSessionId;
+ h.store.selectedAgentId = null;
+ h.sessions = sessions;
+ h.agents = agents;
+ const { result } = renderHook(() => useChatController());
+ // Ignore any render-time store writes (self-heal etc.); we assert only the
+ // effect of the call under test.
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedAgentId.mockClear();
+ h.archivedMutate.mockClear();
+ return result;
+}
+
+describe("useChatController.advanceSelectionAfterArchive", () => {
+ beforeEach(() => {
+ h.store.setActiveSession.mockClear();
+ h.store.setSelectedAgentId.mockClear();
+ h.archivedMutate.mockClear();
+ });
+
+ it("advances to the next chat and syncs the selected agent across agents", () => {
+ const result = setup("sA", [sA, sB, sC], [agentA, agentB]);
+ act(() => result.current.advanceSelectionAfterArchive(sA));
+
+ expect(h.store.setActiveSession).toHaveBeenCalledWith("sB");
+ // The next chat belongs to a different agent — selectedAgentId must follow
+ // so a subsequent "new chat" defaults to the right agent (the review bug).
+ expect(h.store.setSelectedAgentId).toHaveBeenCalledWith("agent-b");
+ });
+
+ it("does not touch the selected agent when the next chat is the same agent", () => {
+ // Both chats belong to agent-a; archiving the open one advances within the
+ // same agent, so there is no reason to rewrite selectedAgentId.
+ const a1 = makeSession({ id: "a1", agent_id: "agent-a", updated_at: "2026-07-08T03:00:00Z" });
+ const a2 = makeSession({ id: "a2", agent_id: "agent-a", updated_at: "2026-07-08T02:00:00Z" });
+ const result = setup("a1", [a1, a2], [agentA, agentB]);
+ act(() => result.current.advanceSelectionAfterArchive(a1));
+
+ expect(h.store.setActiveSession).toHaveBeenCalledWith("a2");
+ expect(h.store.setSelectedAgentId).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the previous chat when archiving the last open one", () => {
+ const result = setup("sC", [sA, sB, sC], [agentA, agentB]);
+ act(() => result.current.advanceSelectionAfterArchive(sC));
+
+ expect(h.store.setActiveSession).toHaveBeenCalledWith("sB");
+ });
+
+ it("clears the selection when archiving the only chat", () => {
+ const only = makeSession({ id: "only", agent_id: "agent-a" });
+ const result = setup("only", [only], [agentA]);
+ act(() => result.current.advanceSelectionAfterArchive(only));
+
+ expect(h.store.setActiveSession).toHaveBeenCalledWith(null);
+ expect(h.store.setSelectedAgentId).not.toHaveBeenCalled();
+ });
+
+ it("is a no-op when the archived chat is not the open one", () => {
+ const result = setup("sB", [sA, sB, sC], [agentA, agentB]);
+ act(() => result.current.advanceSelectionAfterArchive(sA));
+
+ expect(h.store.setActiveSession).not.toHaveBeenCalled();
+ expect(h.store.setSelectedAgentId).not.toHaveBeenCalled();
+ });
+});
+
+describe("useChatController.archiveSession", () => {
+ it("fires the archive mutation for the given session", () => {
+ const result = setup("sA", [sA, sB, sC], [agentA, agentB]);
+ act(() => result.current.archiveSession("sA"));
+
+ expect(h.archivedMutate).toHaveBeenCalledWith({ sessionId: "sA", archived: true });
+ });
+});
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index ded5e2cf49..20d23b7ff4 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -21,10 +21,12 @@ import {
pendingChatTaskOptions,
chatKeys,
isTaskMessageTaskId,
+ sortChatSessions,
} from "@multica/core/chat/queries";
import {
useCreateChatSession,
useMarkChatSessionRead,
+ useSetChatSessionArchived,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
import { createLogger } from "@multica/core/logger";
@@ -248,6 +250,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
const qc = useQueryClient();
const createSession = useCreateChatSession();
const markRead = useMarkChatSessionRead();
+ const setArchived = useSetChatSessionArchived();
const currentMember = members.find((m) => m.user_id === user?.id);
const memberRole = currentMember?.role;
@@ -607,6 +610,33 @@ export function useChatController(opts?: { isActive?: boolean }) {
[activeAgent, setSelectedAgentId, setActiveSession],
);
+ // Archiving the chat currently in view would otherwise strand the
+ // conversation pane on a now read-only, "dangling" session. Mirror the Inbox
+ // list: advance selection to the next chat in the (sorted, non-archived)
+ // history, fall back to the previous one, and clear only when nothing is
+ // left. Routing the non-null advance through handleSelectSession keeps
+ // selectedAgentId in sync, so a follow-up "new chat" still defaults to the
+ // right agent even when the next chat belongs to a different agent. A no-op
+ // when the archived session isn't the open one — that selection stays put.
+ const advanceSelectionAfterArchive = useCallback(
+ (session: { id: string; agent_id: string }) => {
+ if (activeSessionId !== session.id) return;
+ const history = sortChatSessions(
+ sessions.filter((s) => s.status !== "archived"),
+ );
+ const idx = history.findIndex((s) => s.id === session.id);
+ const next = history[idx + 1] ?? history[idx - 1] ?? null;
+ if (next) handleSelectSession(next);
+ else setActiveSession(null);
+ },
+ [activeSessionId, sessions, handleSelectSession, setActiveSession],
+ );
+
+ const archiveSession = useCallback(
+ (sessionId: string) => setArchived.mutate({ sessionId, archived: true }),
+ [setArchived],
+ );
+
const hasMessages = messages.length > 0 || !!pendingTaskId;
return {
@@ -644,6 +674,8 @@ export function useChatController(opts?: { isActive?: boolean }) {
handleNewChat,
handleStartNewChat,
handleSelectSession,
+ advanceSelectionAfterArchive,
+ archiveSession,
// store setters (for surfaces that sync selection to the URL, etc.)
setActiveSession,
setSelectedAgentId,