Skip to content

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

Go

feat(chat): Chat V2 — first-class IM-style Chat tab (MUL-4171) (#5076)

Jiayuan Zhanga51ab4d55158
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index a39b61769d..b711c471ad 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -13,7 +13,7 @@ import {
import { ModalRegistry } from "@multica/views/modals/registry";
import { AppSidebar } from "@multica/views/layout";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
-import { ChatFab, ChatWindow } from "@multica/views/chat";
+import { FloatingChat } from "@multica/views/chat";
import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";
import { useNavigation } from "@multica/views/navigation";
import { getCurrentSlug, subscribeToCurrentSlug } from "@multica/core/platform";
@@ -218,11 +218,9 @@ export function DesktopShell() {
{/* Right side: header + content container */}
<motion.div layout transition={toolbarMotion} className="flex flex-1 min-w-0 flex-col">
<MainTopBar />
- {/* Content area with inset styling — relative so ChatWindow/ChatFab are constrained here */}
<div className="relative flex flex-1 min-h-0 flex-col overflow-hidden mr-2 mb-2 ml-0.5 rounded-xl shadow-sm bg-background">
<TabContent />
- {slug && <ChatWindow />}
- {slug && <ChatFab />}
+ {slug && <FloatingChat />}
</div>
</motion.div>
</SidebarProvider>
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index c39b1648bd..9157630935 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -24,6 +24,7 @@ import { DesktopRuntimesPage } from "./components/desktop-runtimes-page";
import { DesktopAgentsPage } from "./components/desktop-agents-page";
import { SquadsPage, SquadDetailPage as SquadDetailPageView } from "@multica/views/squads/components";
import { InboxPage } from "@multica/views/inbox";
+import { ChatPage } from "@multica/views/chat";
import { SettingsPage } from "@multica/views/settings";
import { useT } from "@multica/views/i18n";
import { Download, Server } from "lucide-react";
@@ -186,6 +187,7 @@ export const appRoutes: RouteObject[] = [
handle: { title: "Squad" },
},
{ path: "inbox", element: <InboxPage />, handle: { title: "Inbox" } },
+ { path: "chat", element: <ChatPage />, handle: { title: "Chat" } },
{
path: "attachments/:id/preview",
element: <AttachmentPreviewRoute />,
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/chat/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/chat/page.tsx
new file mode 100644
index 0000000000..dfeb9b95c0
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/chat/page.tsx
@@ -0,0 +1 @@
+export { ChatPage as default } from "@multica/views/chat";
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
index e9891d12a6..b2f23eb88e 100644
--- a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
@@ -3,7 +3,7 @@
import { DashboardLayout } from "@multica/views/layout";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
-import { ChatFab, ChatWindow } from "@multica/views/chat";
+import { FloatingChat } from "@multica/views/chat";
import { WebNotificationBridge } from "@/components/web-notification-bridge";
export default function Layout({ children }: { children: React.ReactNode }) {
@@ -14,9 +14,8 @@ export default function Layout({ children }: { children: React.ReactNode }) {
extra={
<>
<SearchCommand />
- <ChatWindow />
- <ChatFab />
<WebNotificationBridge />
+ <FloatingChat />
</>
}
>
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 2566187b90..0189a64d33 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -67,6 +67,7 @@ import type {
TaskMessagePayload,
Attachment,
ChatSession,
+ ChatPinnedAgent,
ChatMessage,
ChatMessagesPage,
ChatPendingTask,
@@ -1786,6 +1787,36 @@ export class ApiClient {
});
}
+ async setChatSessionPinned(id: string, pinned: boolean): Promise<ChatSession> {
+ return this.fetch(`/api/chat/sessions/${id}/pin`, {
+ method: "PATCH",
+ body: JSON.stringify({ pinned }),
+ });
+ }
+
+ async setChatSessionArchived(id: string, archived: boolean): Promise<ChatSession> {
+ return this.fetch(`/api/chat/sessions/${id}/archive`, {
+ method: "PATCH",
+ body: JSON.stringify({ archived }),
+ });
+ }
+
+ // Quick-agent bar: per-user pinned agents.
+ async listChatPinnedAgents(): Promise<ChatPinnedAgent[]> {
+ return this.fetch("/api/chat/pinned-agents");
+ }
+
+ async pinChatAgent(agentId: string): Promise<ChatPinnedAgent> {
+ return this.fetch("/api/chat/pinned-agents", {
+ method: "POST",
+ body: JSON.stringify({ agent_id: agentId }),
+ });
+ }
+
+ async unpinChatAgent(agentId: string): Promise<void> {
+ await this.fetch(`/api/chat/pinned-agents/${agentId}`, { method: "DELETE" });
+ }
+
async listChatMessages(sessionId: string): Promise<ChatMessage[]> {
return this.fetch(`/api/chat/sessions/${sessionId}/messages`);
}
diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.ts
index c43663b869..3c70442491 100644
--- a/packages/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -1,12 +1,64 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../api";
import { useWorkspaceId } from "../hooks";
-import { chatKeys } from "./queries";
+import { chatKeys, sortChatSessions } from "./queries";
import { createLogger } from "../logger";
-import type { ChatSession } from "../types";
+import type { ChatSession, ChatPinnedAgent } from "../types";
const logger = createLogger("chat.mut");
+/** Pin an agent to the quick-agent bar (optimistic append). */
+export function usePinChatAgent() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+
+ return useMutation({
+ mutationFn: (agentId: string) => api.pinChatAgent(agentId),
+ onMutate: async (agentId) => {
+ await qc.cancelQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
+ const prev = qc.getQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId));
+ qc.setQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId), (old) => {
+ if (old?.some((p) => p.agent_id === agentId)) return old;
+ const maxPos = old?.reduce((m, p) => Math.max(m, p.position), 0) ?? 0;
+ return [...(old ?? []), { agent_id: agentId, position: maxPos + 1 }];
+ });
+ return { prev };
+ },
+ onError: (err, agentId, ctx) => {
+ logger.error("pinChatAgent.error.rollback", { agentId, err });
+ if (ctx?.prev) qc.setQueryData(chatKeys.pinnedAgents(wsId), ctx.prev);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
+ },
+ });
+}
+
+/** Unpin an agent from the quick-agent bar (optimistic removal). */
+export function useUnpinChatAgent() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+
+ return useMutation({
+ mutationFn: (agentId: string) => api.unpinChatAgent(agentId),
+ onMutate: async (agentId) => {
+ await qc.cancelQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
+ const prev = qc.getQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId));
+ qc.setQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId), (old) =>
+ old?.filter((p) => p.agent_id !== agentId),
+ );
+ return { prev };
+ },
+ onError: (err, agentId, ctx) => {
+ logger.error("unpinChatAgent.error.rollback", { agentId, err });
+ if (ctx?.prev) qc.setQueryData(chatKeys.pinnedAgents(wsId), ctx.prev);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
+ },
+ });
+}
+
export function useCreateChatSession() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
@@ -49,7 +101,7 @@ export function useMarkChatSessionRead() {
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
const clear = (old?: ChatSession[]) =>
- old?.map((s) => (s.id === sessionId ? { ...s, has_unread: false } : s));
+ old?.map((s) => (s.id === sessionId ? { ...s, has_unread: false, unread_count: 0 } : s));
qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), clear);
return { prevSessions };
@@ -103,6 +155,89 @@ export function useUpdateChatSession() {
});
}
+/**
+ * Pins or unpins a chat. Optimistically flips `pinned` and re-sorts the cached
+ * list (pinned first, then by activity) so the row jumps to / from the top
+ * instantly; rolls back on error. The matching `chat:session_updated` WS event
+ * carries the new pin state to other tabs/devices — see use-realtime-sync.ts.
+ */
+export function useSetChatSessionPinned() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+
+ return useMutation({
+ mutationFn: (data: { sessionId: string; pinned: boolean }) => {
+ logger.info("setChatSessionPinned.start", data);
+ return api.setChatSessionPinned(data.sessionId, data.pinned);
+ },
+ onMutate: async ({ sessionId, pinned }) => {
+ await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
+
+ const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
+
+ const patch = (old?: ChatSession[]) =>
+ old &&
+ sortChatSessions(old.map((s) => (s.id === sessionId ? { ...s, pinned } : s)));
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), patch);
+
+ return { prevSessions };
+ },
+ onError: (err, vars, ctx) => {
+ logger.error("setChatSessionPinned.error.rollback", { sessionId: vars.sessionId, err });
+ if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
+ },
+ });
+}
+
+/**
+ * Archives or unarchives a chat session. Optimistically flips `status` in the
+ * cached list so the row moves between the active list and the "Archived" view
+ * instantly (both filter on status locally); rolls back on error. Bumps
+ * `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.
+ */
+export function useSetChatSessionArchived() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+
+ return useMutation({
+ mutationFn: (data: { sessionId: string; archived: boolean }) => {
+ logger.info("setChatSessionArchived.start", data);
+ return api.setChatSessionArchived(data.sessionId, data.archived);
+ },
+ onMutate: async ({ sessionId, archived }) => {
+ await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
+
+ const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
+
+ const nowIso = new Date().toISOString();
+ const patch = (old?: ChatSession[]) =>
+ old &&
+ sortChatSessions(
+ old.map((s) =>
+ s.id === sessionId
+ ? { ...s, status: archived ? "archived" : "active", updated_at: nowIso }
+ : s,
+ ),
+ );
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), patch);
+
+ return { prevSessions };
+ },
+ onError: (err, vars, ctx) => {
+ logger.error("setChatSessionArchived.error.rollback", { sessionId: vars.sessionId, err });
+ if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
+ },
+ });
+}
+
/**
* Hard-deletes a chat session. Optimistically removes the row from the
* sessions list so the dropdown updates instantly; rolls back on error.
diff --git a/packages/core/chat/queries.test.ts b/packages/core/chat/queries.test.ts
index ceb4b23993..0db2dd179a 100644
--- a/packages/core/chat/queries.test.ts
+++ b/packages/core/chat/queries.test.ts
@@ -1,9 +1,11 @@
import { describe, expect, it } from "vitest";
import type { TaskMessagePayload } from "../types/events";
+import type { ChatSession } from "../types/chat";
import {
isTaskMessageTaskId,
mergeTaskMessagesBySeq,
+ sortChatSessions,
taskMessagesOptions,
} from "./queries";
@@ -59,3 +61,45 @@ describe("mergeTaskMessagesBySeq", () => {
expect(mergeTaskMessagesBySeq(existing, [msg(1), msg(2)])).toBe(existing);
});
});
+
+describe("sortChatSessions", () => {
+ 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("puts pinned sessions before unpinned ones regardless of activity", () => {
+ const pinnedOld = session({ id: "pinned-old", pinned: true, updated_at: "2026-01-01T00:00:00Z" });
+ const unpinnedNew = session({ id: "unpinned-new", pinned: false, updated_at: "2026-06-01T00:00:00Z" });
+
+ const sorted = sortChatSessions([unpinnedNew, pinnedOld]);
+ expect(sorted.map((s) => s.id)).toEqual(["pinned-old", "unpinned-new"]);
+ });
+
+ it("orders within each group by most-recent activity (last message wins over updated_at)", () => {
+ const a = session({
+ id: "a",
+ updated_at: "2026-01-01T00:00:00Z",
+ last_message: { content: "x", role: "assistant", created_at: "2026-06-02T00:00:00Z" },
+ });
+ const b = session({ id: "b", updated_at: "2026-06-01T00:00:00Z" });
+
+ const sorted = sortChatSessions([b, a]);
+ expect(sorted.map((s) => s.id)).toEqual(["a", "b"]);
+ });
+
+ it("does not mutate the input array", () => {
+ const input = [session({ id: "1" }), session({ id: "2", pinned: true })];
+ const snapshot = input.map((s) => s.id);
+ sortChatSessions(input);
+ expect(input.map((s) => s.id)).toEqual(snapshot);
+ });
+});
diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.ts
index 513d26ecd0..3b5a3df76f 100644
--- a/packages/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -1,6 +1,7 @@
import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";
import { api } from "../api";
import type { TaskMessagePayload } from "../types/events";
+import type { ChatSession } from "../types/chat";
// NOTE on workspace scoping:
// `wsId` is used only as part of queryKey for cache isolation per workspace.
@@ -22,6 +23,8 @@ export const chatKeys = {
pendingTask: (sessionId: string) => [...chatKeys.pendingTaskAll(), sessionId] as const,
/** Aggregate of in-flight chat tasks for the current user — FAB reads this. */
pendingTasks: (wsId: string) => [...chatKeys.all(wsId), "pending-tasks"] as const,
+ /** Per-user pinned agents for the quick-agent bar. */
+ pinnedAgents: (wsId: string) => [...chatKeys.all(wsId), "pinned-agents"] as const,
/**
* Boolean "does the user have any in-flight chat task" — the FAB's cheap
* running indicator. Separate cache from the detailed `pendingTasks` list so
@@ -48,6 +51,36 @@ export function chatSessionsOptions(wsId: string) {
});
}
+/** Last-activity timestamp used to rank the IM list (newest first). */
+function sessionActivityTime(s: ChatSession): number {
+ return new Date(s.last_message?.created_at ?? s.updated_at).getTime();
+}
+
+/**
+ * Orders the chat list the same way the server does: pinned chats first, then
+ * everyone else by most-recent activity. Used both to render the list and to
+ * re-sort the cache after an optimistic pin/unpin or a WS patch, so a mutated
+ * flat cache never renders out of order. Returns a new array; stable for equal
+ * keys (Array.prototype.sort is stable), so pinned rows keep their server
+ * order when pin timestamps aren't carried in the list payload.
+ */
+export function sortChatSessions(sessions: ChatSession[]): ChatSession[] {
+ return [...sessions].sort((a, b) => {
+ const ap = a.pinned ? 1 : 0;
+ const bp = b.pinned ? 1 : 0;
+ if (ap !== bp) return bp - ap;
+ return sessionActivityTime(b) - sessionActivityTime(a);
+ });
+}
+
+export function chatPinnedAgentsOptions(wsId: string) {
+ return queryOptions({
+ queryKey: chatKeys.pinnedAgents(wsId),
+ queryFn: () => api.listChatPinnedAgents(),
+ staleTime: Infinity,
+ });
+}
+
export function chatSessionOptions(wsId: string, id: string) {
return queryOptions({
queryKey: chatKeys.session(wsId, id),
diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.ts
index 8fb7bc8a4e..302d83b999 100644
--- a/packages/core/chat/store.test.ts
+++ b/packages/core/chat/store.test.ts
@@ -95,3 +95,39 @@ describe("chat store — draft attachments", () => {
expect(store.getState().inputDraftAttachments["draft-1"]).toBeUndefined();
});
});
+
+describe("chat store — floating window preference", () => {
+ it("defaults OFF when no preference is stored (opt-in)", () => {
+ const store = createChatStore({ storage: memStorage() });
+ expect(store.getState().floatingChatEnabled).toBe(false);
+ });
+
+ it("honours an explicit stored 'true' preference", () => {
+ const storage = memStorage();
+ storage.setItem("multica:chat:floatingChatEnabled", "true");
+ const store = createChatStore({ storage });
+ expect(store.getState().floatingChatEnabled).toBe(true);
+ });
+
+ it("persists an enable, then collapses an open overlay when disabled again", () => {
+ const storage = memStorage();
+ storage.setItem("multica:chat:floatingChatEnabled", "true");
+ storage.setItem("multica:chat:isOpen", "true");
+ const store = createChatStore({ storage });
+ expect(store.getState().floatingChatEnabled).toBe(true);
+ expect(store.getState().isOpen).toBe(true);
+
+ store.getState().setFloatingChatEnabled(false);
+ expect(store.getState().floatingChatEnabled).toBe(false);
+ expect(store.getState().isOpen).toBe(false);
+ expect(storage.getItem("multica:chat:floatingChatEnabled")).toBe("false");
+
+ // A fresh store rehydrates the persisted preference.
+ const reopened = createChatStore({ storage });
+ expect(reopened.getState().floatingChatEnabled).toBe(false);
+
+ store.getState().setFloatingChatEnabled(true);
+ expect(store.getState().floatingChatEnabled).toBe(true);
+ expect(storage.getItem("multica:chat:floatingChatEnabled")).toBe("true");
+ });
+});
diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.ts
index 36b44827a7..182e1d40df 100644
--- a/packages/core/chat/store.ts
+++ b/packages/core/chat/store.ts
@@ -36,6 +36,14 @@ const CHAT_EXPANDED_KEY = "multica:chat:expanded";
* every subsequent reload.
*/
const OPEN_KEY = "multica:chat:isOpen";
+/**
+ * Whether the floating chat window (FAB + overlay) is available at all,
+ * persisted globally like OPEN_KEY. This is the Settings → Chat preference:
+ * when off, the FAB/overlay never mount and Chat lives only in its tab.
+ * Missing key = default OFF — the floating window is opt-in, enabled from
+ * the Settings → Chat tab.
+ */
+const FLOATING_KEY = "multica:chat:floatingChatEnabled";
function readDrafts(storage: StorageAdapter, key: string): Record<string, string> {
const raw = storage.getItem(key);
@@ -126,6 +134,8 @@ export interface ChatTimelineItem {
export interface ChatState {
isOpen: boolean;
+ /** Settings preference: is the floating chat window available at all. */
+ floatingChatEnabled: boolean;
activeSessionId: string | null;
selectedAgentId: string | null;
/** Drafts per session: sessionId (or DRAFT_NEW_SESSION) → markdown text. */
@@ -138,6 +148,7 @@ export interface ChatState {
isExpanded: boolean;
setOpen: (open: boolean) => void;
toggle: () => void;
+ setFloatingChatEnabled: (enabled: boolean) => void;
setActiveSession: (id: string | null) => void;
setSelectedAgentId: (id: string) => void;
/** sessionId accepts a real session UUID or DRAFT_NEW_SESSION. */
@@ -168,8 +179,13 @@ export function createChatStore(options: ChatStoreOptions) {
const storedOpen = storage.getItem(OPEN_KEY);
const initialIsOpen = storedOpen === "true";
+ // Default OFF: the floating window is opt-in — only an explicit "true"
+ // (set from the Settings → Chat tab) enables it.
+ const initialFloatingEnabled = storage.getItem(FLOATING_KEY) === "true";
+
const store = create<ChatState>((set, get) => ({
isOpen: initialIsOpen,
+ floatingChatEnabled: initialFloatingEnabled,
activeSessionId: storage.getItem(wsKey(SESSION_STORAGE_KEY)),
selectedAgentId: storage.getItem(wsKey(AGENT_STORAGE_KEY)),
inputDrafts: readDrafts(storage, wsKey(DRAFTS_KEY)),
@@ -188,6 +204,14 @@ export function createChatStore(options: ChatStoreOptions) {
storage.setItem(OPEN_KEY, String(next));
set({ isOpen: next });
},
+ setFloatingChatEnabled: (enabled) => {
+ logger.info("setFloatingChatEnabled", { to: enabled });
+ storage.setItem(FLOATING_KEY, String(enabled));
+ // Turning the feature off should also collapse an open overlay so it
+ // does not linger until the next toggle.
+ set(enabled ? { floatingChatEnabled: true } : { floatingChatEnabled: false, isOpen: false });
+ if (!enabled) storage.setItem(OPEN_KEY, "false");
+ },
setActiveSession: (id) => {
logger.info("setActiveSession", { from: get().activeSessionId, to: id });
if (id) {
diff --git a/packages/core/paths/consistency.test.ts b/packages/core/paths/consistency.test.ts
index 422b47df50..c1618127a9 100644
--- a/packages/core/paths/consistency.test.ts
+++ b/packages/core/paths/consistency.test.ts
@@ -22,6 +22,7 @@ describe("paths.workspace() shape", () => {
"projects",
"autopilots",
"agents",
+ "chat",
"squads",
"inbox",
"myIssues",
@@ -43,6 +44,7 @@ describe("paths.workspace() shape", () => {
["projects", "projects"],
["autopilots", "autopilots"],
["agents", "agents"],
+ ["chat", "chat"],
["squads", "squads"],
["inbox", "inbox"],
["myIssues", "my-issues"],
diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.ts
index 8743c9e375..ad73dc4a49 100644
--- a/packages/core/paths/paths.ts
+++ b/packages/core/paths/paths.ts
@@ -31,6 +31,7 @@ function workspaceScoped(slug: string) {
squads: () => `${ws}/squads`,
squadDetail: (id: string) => `${ws}/squads/${encode(id)}`,
inbox: () => `${ws}/inbox`,
+ chat: () => `${ws}/chat`,
myIssues: () => `${ws}/my-issues`,
runtimes: () => `${ws}/runtimes`,
runtimeDetail: (id: string) => `${ws}/runtimes/${encode(id)}`,
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 3f6a3733f1..acd304dcdb 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -44,7 +44,7 @@ import {
type SystemNotificationPayload,
} from "../platform/system-notification";
import type { Workspace } from "../types/workspace";
-import { chatKeys, mergeTaskMessagesBySeq } from "../chat/queries";
+import { chatKeys, mergeTaskMessagesBySeq, sortChatSessions } from "../chat/queries";
import { useChatStore } from "../chat";
import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
@@ -84,6 +84,7 @@ import type {
ChatMessage,
ChatPendingTask,
ChatMessagesPage,
+ ChatSession,
InvitationCreatedPayload,
} from "../types";
@@ -1102,6 +1103,11 @@ export function useRealtimeSync(
invalidateChatMessageQueries(qc, payload.chat_session_id);
qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
+ // FailTask persisted a failure chat_message, so the thread list's
+ // last_message / unread_count / sort order changed too. Mirror the
+ // chat:done (success) path and refresh the sessions list — otherwise the
+ // left rail keeps a stale preview until the next full refetch.
+ invalidateSessionLists();
});
const unsubChatSessionRead = ws.on("chat:session_read", (p) => {
@@ -1117,24 +1123,35 @@ export function useRealtimeSync(
const payload = p as {
chat_session_id: string;
title?: string;
+ pinned?: boolean;
+ status?: "active" | "archived";
updated_at?: string;
};
chatWsLogger.info("chat:session_updated (global)", payload);
const id = getCurrentWsId();
if (!id) return;
- const patch = (
- old?: { id: string; title: string; updated_at: string }[],
- ) =>
- old?.map((s) =>
+ // `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,
);
- qc.setQueryData(chatKeys.sessions(id), patch);
+ return payload.pinned === undefined && payload.status === undefined
+ ? next
+ : sortChatSessions(next);
+ });
});
// chat:session_deleted fires after a hard delete. The originating tab has
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index 211d4c14c2..214590484e 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -1,5 +1,20 @@
import type { AgentTask } from "./agent";
+/** A user's pinned "quick agent" for the Chat list top bar. */
+export interface ChatPinnedAgent {
+ agent_id: string;
+ position: number;
+}
+
+/** Preview of a session's most recent message, for the IM-style list. */
+export interface ChatLastMessage {
+ content: string;
+ role: "user" | "assistant";
+ created_at: string;
+ /** Present when the last message is a failed assistant reply. */
+ failure_reason?: string | null;
+}
+
export interface ChatSession {
id: string;
workspace_id: string;
@@ -7,8 +22,17 @@ export interface ChatSession {
creator_id: string;
title: string;
status: "active" | "archived";
- /** True when the session has any unread assistant replies. List-only. */
+ /** True when the session has any unread assistant replies. List-only.
+ * Convenience for `unread_count > 0`. */
has_unread: boolean;
+ /** Number of unread assistant messages (after the read cursor). List-only;
+ * optional so older clients / non-list payloads stay valid. */
+ unread_count?: number;
+ /** Latest message in the session, or null when empty. List-only. */
+ last_message?: ChatLastMessage | null;
+ /** True when the user has pinned this chat to the top of the list.
+ * Optional so older clients / non-list payloads stay valid. */
+ pinned?: boolean;
created_at: string;
updated_at: string;
}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index ea56f8c08c..db89e9b7e1 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -79,6 +79,8 @@ export type { Attachment } from "./attachment";
export { attachmentDownloadPath, attachmentIdFromDownloadURL, contentReferencesAttachment } from "./attachment-url";
export type {
ChatSession,
+ ChatLastMessage,
+ ChatPinnedAgent,
ChatMessage,
ChatMessagesPage,
ChatPendingTask,
diff --git a/packages/ui/components/common/submit-button.tsx b/packages/ui/components/common/submit-button.tsx
index e5cd897df5..1ea02339b8 100644
--- a/packages/ui/components/common/submit-button.tsx
+++ b/packages/ui/components/common/submit-button.tsx
@@ -3,6 +3,7 @@
import type { ReactNode } from "react";
import { ArrowUp, Loader2, Square } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
import {
Tooltip,
TooltipContent,
@@ -15,6 +16,12 @@ interface SubmitButtonProps {
loading?: boolean;
running?: boolean;
onStop?: () => void;
+ /**
+ * Button silhouette. `"rounded"` (default) keeps the rounded-square used by
+ * issue comment composers; `"circle"` makes it a fully-round pill — the
+ * Chat V2 look. Opt-in so shared callers keep their existing shape.
+ */
+ shape?: "rounded" | "circle";
/**
* Tooltip shown over the send button when idle. Pass a string or a node
* (e.g. `Send · ⌘↵`). Omit to render no tooltip.
@@ -34,10 +41,12 @@ function SubmitButton({
onStop,
tooltip,
stopTooltip,
+ shape = "rounded",
}: SubmitButtonProps) {
+ const shapeClass = shape === "circle" ? "rounded-full" : undefined;
if (running) {
const stopButton = (
- <Button size="icon-sm" onClick={onStop}>
+ <Button size="icon-sm" className={cn(shapeClass)} onClick={onStop}>
<Square className="fill-current" />
</Button>
);
@@ -51,7 +60,12 @@ function SubmitButton({
}
const submitButton = (
- <Button size="icon-sm" disabled={disabled || loading} onClick={onClick}>
+ <Button
+ size="icon-sm"
+ className={cn(shapeClass)}
+ disabled={disabled || loading}
+ onClick={onClick}
+ >
{loading ? <Loader2 className="animate-spin" /> : <ArrowUp />}
</Button>
);
diff --git a/packages/ui/styles/tokens.css b/packages/ui/styles/tokens.css
index ab16eff53d..c78f9bfef7 100644
--- a/packages/ui/styles/tokens.css
+++ b/packages/ui/styles/tokens.css
@@ -66,7 +66,7 @@
--accent: oklch(0.967 0.001 286.375);
--accent-foreground: oklch(0.21 0.006 285.885);
--destructive: oklch(0.577 0.245 27.325);
- --border: oklch(0.92 0.004 286.32);
+ --border: oklch(0.945 0.003 286.32);
--input: oklch(0.92 0.004 286.32);
--ring: oklch(0.705 0.015 286.067);
/* Brand-derived blue gradient (h=255 = brand hue). chart-1 equals brand
@@ -120,7 +120,7 @@
--accent: oklch(0.274 0.006 286.033);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
- --border: oklch(1 0 0 / 10%);
+ --border: oklch(1 0 0 / 6%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.552 0.016 285.938);
/* Dark mode mirrors light mode's "primary → secondary" gradient on the
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
new file mode 100644
index 0000000000..4a06d3c653
--- /dev/null
+++ b/packages/views/chat/chat-page.tsx
@@ -0,0 +1,257 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useDefaultLayout } from "react-resizable-panels";
+import { ArrowLeft, MessageSquare } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ ResizablePanelGroup,
+ ResizablePanel,
+ ResizableHandle,
+} from "@multica/ui/components/ui/resizable";
+import { useIsMobile } from "@multica/ui/hooks/use-mobile";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { useChatStore } from "@multica/core/chat";
+import type { Agent, ChatSession } from "@multica/core/types";
+import { PageHeader } from "../layout/page-header";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+import { ChatMessageList, ChatMessageSkeleton } from "./components/chat-message-list";
+import { ChatInput } from "./components/chat-input";
+import { ChatThreadList } from "./components/chat-thread-list";
+import { ChatSessionHeader } from "./components/chat-session-header";
+import { EmptyState } from "./components/chat-empty-state";
+import { NewChatButton } from "./components/new-chat-button";
+import { useChatController } from "./components/use-chat-controller";
+import { OfflineBanner } from "./components/offline-banner";
+import { NoAgentBanner } from "./components/no-agent-banner";
+import { ArchivedAgentBanner } from "./components/archived-agent-banner";
+
+/**
+ * Chat tab — the first-class two-pane surface (thread list on the left,
+ * conversation on the right), mirroring the Inbox page layout. Shares all
+ * conversation logic with the floating FAB via `useChatController`; the
+ * left rail reuses `ChatThreadList`.
+ *
+ * Selection is URL-addressable via `?session=<id>` so a thread can be
+ * deep-linked, opened from a notification, and survive refresh. The chat
+ * store's `activeSessionId` stays the source of truth (both surfaces read
+ * it); the URL is kept in sync in both directions.
+ *
+ * Starting a chat is where the agent is chosen: the header ⊕ opens an agent
+ * picker (see NewChatButton), so the compose box no longer needs its own
+ * agent selector. Unlike the FAB, this page passes no `contextItems` to
+ * `ChatInput`, so its `@` mentions fall back to manual search (issue-comment
+ * style).
+ */
+export function ChatPage() {
+ const { t } = useT("chat");
+ const { searchParams, replace } = useNavigation();
+ const wsPaths = useWorkspacePaths();
+ const isMobile = useIsMobile();
+
+ const c = useChatController({ isActive: true });
+ const urlSession = searchParams.get("session") || null;
+
+ // "Composing a brand-new chat" — the user hit ⊕ but hasn't sent yet, so no
+ // session exists. On mobile this decides list-vs-conversation; on desktop the
+ // conversation pane is always mounted so it only needs to reset itself once a
+ // real session takes over.
+ const [composingNew, setComposingNew] = useState(false);
+ useEffect(() => {
+ if (c.activeSessionId) setComposingNew(false);
+ }, [c.activeSessionId]);
+
+ // Two-way sync between the URL (`?session=`) and the chat store's
+ // activeSessionId. Both effects read the LIVE store value via
+ // `useChatStore.getState()` rather than the render-captured `c.activeSessionId`.
+ // That is what keeps them from fighting on mount: a naive mirror effect fires
+ // with the stale (null) snapshot and "corrects" the URL by stripping the
+ // session before the URL→store effect has applied — breaking deep links and
+ // making selection / new-chat feel unresponsive. Reading getState() sees the
+ // value the sibling effect just wrote, so the reconciliation converges in one
+ // pass and is idempotent under StrictMode's double-invoke.
+
+ // URL → store: deep link, refresh, notification click, back/forward.
+ useEffect(() => {
+ if (urlSession !== useChatStore.getState().activeSessionId) {
+ c.setActiveSession(urlSession);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- react to URL only
+ }, [urlSession]);
+
+ // store → URL: thread selection, "new chat", and sessions created by sending.
+ useEffect(() => {
+ const live = useChatStore.getState().activeSessionId;
+ const current = searchParams.get("session") || null;
+ if (live !== current) {
+ const base = wsPaths.chat();
+ replace(live ? `${base}?session=${live}` : base);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- react to store only
+ }, [c.activeSessionId]);
+
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({
+ id: "multica_chat_layout",
+ });
+
+ const handleSelect = (session: ChatSession) => {
+ c.handleSelectSession(session);
+ setComposingNew(false);
+ };
+
+ const startNewChat = (agent: Agent | null) => {
+ if (agent) c.handleStartNewChat(agent);
+ else c.handleNewChat();
+ setComposingNew(true);
+ };
+
+ const newChatButton = (
+ <NewChatButton
+ agents={c.availableAgents}
+ userId={c.user?.id}
+ onStart={startNewChat}
+ side="bottom"
+ />
+ );
+
+ const listHeader = (
+ <PageHeader className="justify-between border-b-0">
+ <div className="flex items-center gap-2">
+ <h1 className="text-sm font-semibold">{t(($) => $.page.title)}</h1>
+ </div>
+ {newChatButton}
+ </PageHeader>
+ );
+
+ const listBody = (
+ <div className="p-1">
+ <ChatThreadList
+ sessions={c.sessions}
+ agents={c.agents}
+ activeSessionId={c.activeSessionId}
+ onSelectSession={handleSelect}
+ />
+ </div>
+ );
+
+ // The conversation pane: message list / skeleton / empty above a persistent
+ // banner + input. Identical composition to the floating window's body, so a
+ // brand-new chat (no active session) shows the agent-aware empty state + input.
+ // No compose-box agent selector — the agent is fixed when the chat starts.
+ const conversation = (
+ <div className="flex flex-1 flex-col min-h-0">
+ {c.currentSession && (
+ <ChatSessionHeader session={c.currentSession} agent={c.activeAgent} />
+ )}
+ {c.showSkeleton ? (
+ <ChatMessageSkeleton />
+ ) : c.hasMessages ? (
+ <ChatMessageList
+ key={c.activeSessionId}
+ messages={c.messages}
+ pendingTask={c.pendingTask}
+ availability={c.availability}
+ firstItemIndex={c.firstItemIndex}
+ hasOlderMessages={c.hasOlderMessages}
+ isFetchingOlderMessages={c.isFetchingOlderMessages}
+ onLoadOlderMessages={() => void c.fetchOlderMessages()}
+ />
+ ) : (
+ <EmptyState agent={c.activeAgent} />
+ )}
+
+ {c.noAgent ? (
+ <NoAgentBanner />
+ ) : c.isAgentArchived ? (
+ <ArchivedAgentBanner agentName={c.activeAgent?.name} />
+ ) : (
+ <OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />
+ )}
+
+ <ChatInput
+ onSend={c.handleSend}
+ restoreDraftRequest={c.restoreDraftRequest}
+ onRestoreDraftConsumed={c.handleRestoreDraftConsumed}
+ onUploadFile={c.handleUploadFile}
+ onStop={c.handleStop}
+ isRunning={!!c.pendingTaskId}
+ disabled={c.isSessionArchived || c.isAgentArchived}
+ noAgent={c.noAgent}
+ agentArchived={c.isAgentArchived}
+ agentName={c.activeAgent?.name}
+ />
+ </div>
+ );
+
+ // -- Mobile: list / conversation toggle -----------------------------------
+ if (isMobile) {
+ if (c.activeSessionId || composingNew) {
+ return (
+ <div className="flex flex-1 flex-col min-h-0">
+ <div className="flex h-12 shrink-0 items-center border-b px-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ c.setActiveSession(null);
+ setComposingNew(false);
+ }}
+ className="gap-1.5 text-muted-foreground"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ {t(($) => $.page.title)}
+ </Button>
+ </div>
+ {conversation}
+ </div>
+ );
+ }
+ return (
+ <div className="flex flex-1 flex-col min-h-0">
+ {listHeader}
+ <div className="flex-1 min-h-0 overflow-y-auto">{listBody}</div>
+ </div>
+ );
+ }
+
+ // -- Desktop: resizable two-panel. The conversation pane appears only once
+ // there is a chat target — an open thread or a new chat whose agent was just
+ // picked via ⊕. With nothing selected there is no agent, so we show a neutral
+ // prompt instead of an orphaned compose box. -------------------------------
+ const hasTarget = !!c.activeSessionId || composingNew;
+ return (
+ <ResizablePanelGroup
+ orientation="horizontal"
+ className="flex-1 min-h-0"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
+ >
+ <ResizablePanel
+ id="list"
+ defaultSize={320}
+ minSize={240}
+ maxSize={480}
+ groupResizeBehavior="preserve-pixel-size"
+ >
+ <div className="flex flex-col border-r h-full">
+ {listHeader}
+ <div className="flex-1 min-h-0 overflow-y-auto">{listBody}</div>
+ </div>
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel id="detail" minSize="40%">
+ <div className="flex flex-col min-h-0 h-full">
+ {hasTarget ? (
+ conversation
+ ) : (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
+ <MessageSquare className="h-10 w-10 text-muted-foreground/30" />
+ <p className="text-sm">{t(($) => $.page.select_prompt)}</p>
+ </div>
+ )}
+ </div>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+}
diff --git a/packages/views/chat/components/archived-agent-banner.tsx b/packages/views/chat/components/archived-agent-banner.tsx
new file mode 100644
index 0000000000..dafb1d981d
--- /dev/null
+++ b/packages/views/chat/components/archived-agent-banner.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { Archive } from "lucide-react";
+import { useT } from "../../i18n";
+
+// Sibling of OfflineBanner / NoAgentBanner, occupying the same banner slot
+// above the chat input. Shown when the open session's agent has been archived
+// (retired): the input above is disabled and this banner explains that the
+// conversation is read-only history — the agent can no longer reply.
+//
+// Layout (`px-5` outer, `mx-auto max-w-4xl` inner) mirrors its siblings so the
+// banner's edges line up with the input on every viewport size.
+export function ArchivedAgentBanner({ agentName }: { agentName?: string }) {
+ const { t } = useT("chat");
+ const name = agentName?.trim() || t(($) => $.offline_banner.fallback_name);
+ return (
+ <div className="px-5 mb-1.5">
+ <div className="mx-auto flex w-full max-w-4xl items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs bg-muted text-muted-foreground ring-1 ring-border">
+ <Archive className="size-3.5 shrink-0" />
+ <span className="truncate">
+ {t(($) => $.archived_agent_banner, { name })}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/chat-add-menu.tsx b/packages/views/chat/components/chat-add-menu.tsx
new file mode 100644
index 0000000000..064c6ce91e
--- /dev/null
+++ b/packages/views/chat/components/chat-add-menu.tsx
@@ -0,0 +1,72 @@
+"use client";
+
+import { useRef } from "react";
+import { Plus, Image as ImageIcon } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { useT } from "../../i18n";
+
+interface ChatAddMenuProps {
+ /** Called with each selected file — the caller routes it through the
+ * editor's upload extension, same path as paste / drag-drop. */
+ onSelectFile: (file: File) => void;
+ disabled?: boolean;
+}
+
+/**
+ * The "+" affordance at the bottom-left of the chat composer. Replaces the
+ * standalone paperclip button: file upload now lives here as a submenu entry,
+ * leaving room for future add-actions (agents, skills, tools) under one entry
+ * point without crowding the input bar.
+ */
+export function ChatAddMenu({ onSelectFile, disabled }: ChatAddMenuProps) {
+ const { t } = useT("chat");
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(e.target.files ?? []);
+ if (files.length === 0) return;
+ e.target.value = "";
+ for (const file of files) onSelectFile(file);
+ };
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ disabled={disabled}
+ aria-label={t(($) => $.input.add_tooltip)}
+ title={t(($) => $.input.add_tooltip)}
+ className="rounded-full text-muted-foreground"
+ >
+ <Plus />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="start" side="top" sideOffset={6}>
+ <DropdownMenuItem onClick={() => inputRef.current?.click()}>
+ <ImageIcon />
+ {t(($) => $.input.upload_file)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <input
+ ref={inputRef}
+ type="file"
+ multiple
+ className="hidden"
+ onChange={handleChange}
+ />
+ </>
+ );
+}
diff --git a/packages/views/chat/components/chat-empty-state.tsx b/packages/views/chat/components/chat-empty-state.tsx
new file mode 100644
index 0000000000..0a266d3d53
--- /dev/null
+++ b/packages/views/chat/components/chat-empty-state.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import type { Agent } from "@multica/core/types";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { useT } from "../../i18n";
+
+/**
+ * Empty compose placeholder shown when a chat has no messages yet. Agent-aware:
+ * it leads with the chosen agent's avatar + name + description so the user knows
+ * exactly who they're about to talk to. The composer below is the entry point —
+ * no starter prompts, they read as filler more than help.
+ */
+export function EmptyState({ agent }: { agent: Agent | null }) {
+ const { t } = useT("chat");
+ const description = agent?.description?.trim();
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center gap-4 px-6 py-8">
+ {agent && (
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size={56}
+ className="ring-1 ring-inset ring-border"
+ />
+ )}
+ <div className="max-w-sm space-y-1 text-center">
+ <h3 className="text-base font-semibold">
+ {agent
+ ? t(($) => $.empty_state.chat_with_named, { name: agent.name })
+ : t(($) => $.empty_state.first_time_title)}
+ </h3>
+ {description && (
+ <p className="text-sm text-muted-foreground">{description}</p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index 939f9024ea..10187bba7f 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -248,7 +248,8 @@ describe("ChatInput attachment wiring", () => {
// Wait for the submit button to become enabled (onUpdate has fired and
// React has re-rendered). SubmitButton has no aria-label, so we pick
- // the last action button on the bar (FileUploadButton, SubmitButton).
+ // the last action button on the bar (ChatAddMenu "+" is on the left,
+ // SubmitButton is last).
let sendButton: HTMLElement;
await waitFor(() => {
const buttons = screen.getAllByRole("button");
@@ -363,10 +364,10 @@ describe("ChatInput attachment wiring", () => {
it("does not render the file upload button when onUploadFile is omitted", () => {
renderInput({ onUploadFile: undefined });
- // FileUploadButton renders an icon button labelled by its tooltip — when
- // upload wiring is absent the chat input falls back to "submit + extras"
- // only. Probe by counting buttons: with no upload, only the submit
- // button is in the action row.
+ // The ChatAddMenu "+" (which hosts file upload) only mounts when upload
+ // wiring is present — without it the chat input falls back to "submit +
+ // extras" only. Probe by counting buttons: with no upload, only the
+ // submit button is in the action row.
const buttons = screen.getAllByRole("button");
// The agent picker may render zero buttons
// in this test (no leftAdornment passed). So a single button = submit.
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index 332b50e34b..1b8d8fa4b7 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -9,8 +9,8 @@ import {
useFileDropZone,
FileDropOverlay,
} from "../../editor";
-import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
+import { ChatAddMenu } from "./chat-add-menu";
import { useChatStore, newSessionDraftKey } from "@multica/core/chat";
import { createLogger } from "@multica/core/logger";
import { enterKey, formatShortcut, modKey } from "@multica/core/platform";
@@ -75,6 +75,10 @@ interface ChatInputProps {
* surfaces a distinct placeholder. Kept separate from `disabled` so
* archived-session copy stays untouched. */
noAgent?: boolean;
+ /** True when `disabled` is because the bound agent was archived (retired),
+ * as opposed to the session itself being archived — swaps the placeholder
+ * copy so the read-only reason reads accurately. */
+ agentArchived?: boolean;
/** Name of the currently selected agent, used in the placeholder. */
agentName?: string;
/** Rendered at the bottom-left of the input bar — typically the agent picker. */
@@ -92,6 +96,7 @@ export function ChatInput({
isRunning,
disabled,
noAgent,
+ agentArchived,
agentName,
leftAdornment,
contextItems,
@@ -320,7 +325,9 @@ export function ChatInput({
const placeholder = noAgent
? t(($) => $.input.placeholder_no_agent)
: disabled
- ? t(($) => $.input.placeholder_archived)
+ ? agentArchived
+ ? t(($) => $.input.placeholder_archived_agent)
+ : t(($) => $.input.placeholder_archived)
: agentName
? t(($) => $.input.placeholder_named, { name: agentName })
: t(($) => $.input.placeholder_default);
@@ -389,20 +396,19 @@ export function ChatInput({
// continues a bullet list, leaving users stuck after one item.
/>
</div>
- {leftAdornment && (
- <div className="absolute bottom-1.5 left-2 flex items-center">
+ {(uploadEnabled || leftAdornment) && (
+ <div className="absolute bottom-1.5 left-1.5 flex items-center gap-1">
+ {uploadEnabled && (
+ <ChatAddMenu
+ onSelectFile={(file) => editorRef.current?.uploadFile(file)}
+ />
+ )}
{leftAdornment}
</div>
)}
<div className="absolute bottom-1 right-1.5 flex items-center gap-1">
- {uploadEnabled && (
- <FileUploadButton
- size="sm"
- multiple
- onSelect={(file) => editorRef.current?.uploadFile(file)}
- />
- )}
<SubmitButton
+ shape="circle"
onClick={handleSend}
disabled={isEmpty || isSubmitting || !!disabled || !!noAgent || pendingUploads > 0}
loading={isSubmitting}
diff --git a/packages/views/chat/components/chat-window.agent-dropdown.test.tsx b/packages/views/chat/components/chat-new-chat-button.test.tsx
similarity index 71%
rename from packages/views/chat/components/chat-window.agent-dropdown.test.tsx
rename to packages/views/chat/components/chat-new-chat-button.test.tsx
index 30935b4d3c..965f33af13 100644
--- a/packages/views/chat/components/chat-window.agent-dropdown.test.tsx
+++ b/packages/views/chat/components/chat-new-chat-button.test.tsx
@@ -11,7 +11,7 @@ vi.mock("../../common/actor-avatar", () => ({
),
}));
-import { AgentDropdown } from "./chat-window";
+import { NewChatButton } from "./new-chat-button";
const TEST_RESOURCES = { en: { chat: enChat, issues: enIssues } };
@@ -50,31 +50,29 @@ const agents = [
makeAgent({ id: "other-gamma", name: "Gamma", owner_id: "user-2" }),
];
-function renderDropdown(onSelect = vi.fn()) {
+// The ⊕ button carries the localized "New chat" label as its accessible name.
+const NEW_CHAT_LABEL = enChat.window.new_chat_tooltip;
+
+function renderPicker(onStart = vi.fn()) {
render(
<I18nProvider locale="en" resources={TEST_RESOURCES}>
- <AgentDropdown
- agents={agents}
- activeAgent={agents[0]!}
- userId="user-1"
- onSelect={onSelect}
- />
+ <NewChatButton agents={agents} userId="user-1" onStart={onStart} />
</I18nProvider>,
);
- fireEvent.click(screen.getByText("Alpha"));
- return { onSelect };
+ fireEvent.click(screen.getByRole("button", { name: NEW_CHAT_LABEL }));
+ return { onStart };
}
-describe("AgentDropdown", () => {
- it("opens the shared picker upward from the chat input", async () => {
- renderDropdown();
+describe("NewChatButton", () => {
+ it("opens the agent picker below the ⊕ trigger", async () => {
+ renderPicker();
const dialog = await screen.findByRole("dialog");
- expect(dialog).toHaveAttribute("data-side", "top");
+ expect(dialog).toHaveAttribute("data-side", "bottom");
});
it("filters both My agents and Others by agent name", async () => {
- renderDropdown();
+ renderPicker();
const input = await screen.findByRole("textbox", { name: "Filter options" });
fireEvent.change(input, { target: { value: "ta" } });
@@ -88,7 +86,7 @@ describe("AgentDropdown", () => {
});
it("matches My agents by pinyin", async () => {
- renderDropdown();
+ renderPicker();
const input = await screen.findByRole("textbox", { name: "Filter options" });
fireEvent.change(input, { target: { value: "zhang" } });
@@ -101,7 +99,7 @@ describe("AgentDropdown", () => {
});
it("shows the shared empty state when no agents match", async () => {
- renderDropdown();
+ renderPicker();
const input = await screen.findByRole("textbox", { name: "Filter options" });
fireEvent.change(input, { target: { value: "missing" } });
@@ -111,31 +109,34 @@ describe("AgentDropdown", () => {
expect(screen.queryByText("Others")).not.toBeInTheDocument();
});
- it("left-aligns agent picker rows", async () => {
- renderDropdown();
-
- const dialog = await screen.findByRole("dialog");
- const alphaRow = Array.from(
- dialog.querySelectorAll<HTMLButtonElement>("button[data-picker-item]"),
- ).find((row) => row.textContent?.includes("Alpha"));
-
- expect(alphaRow).toBeDefined();
- expect(alphaRow).toHaveClass("text-left");
- });
-
- it("keeps the current agent marked and selects another agent", async () => {
- const { onSelect } = renderDropdown();
+ it("pre-checks no agent (a new chat has no current) and reports the chosen agent", async () => {
+ const { onStart } = renderPicker();
const dialog = screen.getByRole("dialog");
+ // No agent should carry a visible check mark for a fresh new chat.
const alphaRow = within(dialog).getByText("Alpha").closest("button");
expect(alphaRow).not.toBeNull();
- expect(alphaRow!.querySelector("svg:not(.invisible)")).not.toBeNull();
+ expect(alphaRow!.querySelector("svg:not(.invisible)")).toBeNull();
fireEvent.click(within(dialog).getByText("Beta"));
- expect(onSelect).toHaveBeenCalledWith(agents[2]);
+ expect(onStart).toHaveBeenCalledWith(agents[2]);
await waitFor(() => {
expect(screen.queryByRole("textbox", { name: "Filter options" })).not.toBeInTheDocument();
});
});
-});
\ No newline at end of file
+
+ it("starts immediately without a picker when only one agent exists", () => {
+ const onStart = vi.fn();
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <NewChatButton agents={[agents[0]!]} userId="user-1" onStart={onStart} />
+ </I18nProvider>,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: NEW_CHAT_LABEL }));
+
+ expect(onStart).toHaveBeenCalledWith(agents[0]);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/chat/components/chat-session-header.tsx b/packages/views/chat/components/chat-session-header.tsx
new file mode 100644
index 0000000000..842e99e630
--- /dev/null
+++ b/packages/views/chat/components/chat-session-header.tsx
@@ -0,0 +1,201 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { Archive, ArchiveRestore, MoreHorizontal, Pencil, Trash2, UserRound } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from "@multica/ui/components/ui/dropdown-menu";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { useWorkspacePaths } from "@multica/core/paths";
+import {
+ useUpdateChatSession,
+ useDeleteChatSession,
+ useSetChatSessionArchived,
+} from "@multica/core/chat/mutations";
+import { useChatStore } from "@multica/core/chat";
+import type { Agent, ChatSession } from "@multica/core/types";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+
+/**
+ * Per-session header for the conversation pane: agent avatar + editable chat
+ * title + agent subtitle, with a ⋯ menu (rename / view agent profile / delete).
+ * The avatar's hover card is the lightweight "view profile" affordance; the
+ * menu item navigates to the full agent page.
+ */
+export function ChatSessionHeader({
+ session,
+ agent,
+}: {
+ session: ChatSession;
+ agent: Agent | null;
+}) {
+ const { t } = useT("chat");
+ const wsPaths = useWorkspacePaths();
+ const { push } = useNavigation();
+ const updateSession = useUpdateChatSession();
+ const deleteSession = useDeleteChatSession();
+ const setArchived = useSetChatSessionArchived();
+ const setActiveSession = useChatStore((s) => s.setActiveSession);
+
+ const isArchived = session.status === "archived";
+
+ const [editing, setEditing] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [draft, setDraft] = useState(session.title ?? "");
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const title = session.title?.trim() || t(($) => $.window.untitled);
+
+ useEffect(() => {
+ if (editing) {
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ }
+ }, [editing]);
+
+ const startRename = () => {
+ setDraft(session.title ?? "");
+ setEditing(true);
+ };
+
+ const commitRename = () => {
+ setEditing(false);
+ const trimmed = draft.trim();
+ if (!trimmed || trimmed === session.title) return;
+ updateSession.mutate({ sessionId: session.id, title: trimmed });
+ };
+
+ const viewProfile = () => {
+ if (agent) push(wsPaths.agentDetail(agent.id));
+ };
+
+ const doDelete = () => {
+ setConfirmDelete(false);
+ setActiveSession(null);
+ deleteSession.mutate(session.id);
+ };
+
+ const doArchive = () => setArchived.mutate({ sessionId: session.id, archived: true });
+ const doUnarchive = () => setArchived.mutate({ sessionId: session.id, archived: false });
+
+ return (
+ <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">
+ {agent ? (
+ <ActorAvatar actorType="agent" actorId={agent.id} size={30} enableHoverCard showStatusDot />
+ ) : (
+ <span className="size-[30px] shrink-0" />
+ )}
+
+ <div className="min-w-0 flex-1">
+ {editing ? (
+ <input
+ ref={inputRef}
+ value={draft}
+ maxLength={200}
+ aria-label={t(($) => $.header.rename)}
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={commitRename}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ commitRename();
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ setEditing(false);
+ }
+ }}
+ className="w-full rounded-sm bg-background px-1 py-0.5 text-sm font-semibold outline-none ring-1 ring-border focus-visible:ring-brand"
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={startRename}
+ title={t(($) => $.header.rename)}
+ className="block max-w-full truncate text-left text-sm font-semibold text-foreground outline-none hover:text-foreground/80 focus-visible:text-foreground/80"
+ >
+ {title}
+ </button>
+ )}
+ {agent && (
+ <div className="truncate text-xs text-muted-foreground">
+ {agent.name}
+ {agent.description ? ` · ${agent.description}` : ""}
+ </div>
+ )}
+ </div>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<Button variant="ghost" size="icon-sm" className="text-muted-foreground" />}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-auto">
+ <DropdownMenuItem onClick={startRename}>
+ <Pencil className="h-4 w-4" />
+ {t(($) => $.header.rename)}
+ </DropdownMenuItem>
+ {agent && (
+ <DropdownMenuItem onClick={viewProfile}>
+ <UserRound className="h-4 w-4" />
+ {t(($) => $.header.view_profile)}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ {isArchived ? (
+ <>
+ <DropdownMenuItem onClick={doUnarchive}>
+ <ArchiveRestore className="h-4 w-4" />
+ {t(($) => $.header.unarchive)}
+ </DropdownMenuItem>
+ {/* Hard delete is offered only once a chat is archived. */}
+ <DropdownMenuItem variant="destructive" onClick={() => setConfirmDelete(true)}>
+ <Trash2 className="h-4 w-4" />
+ {t(($) => $.header.delete)}
+ </DropdownMenuItem>
+ </>
+ ) : (
+ <DropdownMenuItem onClick={doArchive}>
+ <Archive className="h-4 w-4" />
+ {t(($) => $.header.archive)}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.session_history.delete_dialog.title)}</AlertDialogTitle>
+ <AlertDialogDescription>{title}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.session_history.delete_dialog.cancel)}</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={doDelete}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {t(($) => $.session_history.delete_dialog.confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsx
new file mode 100644
index 0000000000..f5460d4000
--- /dev/null
+++ b/packages/views/chat/components/chat-thread-list.tsx
@@ -0,0 +1,519 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ Archive,
+ ArchiveRestore,
+ ChevronLeft,
+ ChevronRight,
+ Clock,
+ Loader2,
+ Pin,
+ PinOff,
+ Square,
+ Trash2,
+} from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePresenceMap } from "@multica/core/agents";
+import { api } from "@multica/core/api";
+import { pendingChatTasksOptions, chatKeys, sortChatSessions } from "@multica/core/chat/queries";
+import {
+ useDeleteChatSession,
+ useSetChatSessionArchived,
+ useSetChatSessionPinned,
+} from "@multica/core/chat/mutations";
+import { useChatStore } from "@multica/core/chat";
+import type { Agent, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { createLogger } from "@multica/core/logger";
+import { removeChatMessageFromCaches } from "./use-chat-controller";
+import { useT } from "../../i18n";
+
+const apiLogger = createLogger("chat.api");
+
+// IM-style timestamp: today → clock, this year → M/D, else full date.
+function formatChatTime(dateStr: string): string {
+ const d = new Date(dateStr);
+ const now = new Date();
+ if (d.toDateString() === now.toDateString()) {
+ return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
+ }
+ if (d.getFullYear() === now.getFullYear()) {
+ return d.toLocaleDateString([], { month: "numeric", day: "numeric" });
+ }
+ return d.toLocaleDateString();
+}
+
+// Collapse a (possibly markdown / multi-line) message into a one-line preview.
+function toPreview(content: string): string {
+ return content
+ .replace(/```[\s\S]*?```/g, " ")
+ .replace(/[#*`>~]/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+/**
+ * IM-style conversation list: each row is agent avatar + name + last-message
+ * preview + time, with a red unread *count* badge. An in-flight agent shows a
+ * "typing…" indicator; a failed last reply shows a destructive hint. Rows are
+ * rendered in the server's order (most-recent activity first). Renaming lives
+ * in the conversation header's ⋯ menu, not here.
+ *
+ * Two views, toggled locally: the default "history" view lists active chats and
+ * hovering a row reveals pin + archive (or stop, while running) — archiving is
+ * the reversible, one-click default so nothing is destroyed by accident. A
+ * footer entry ("Archived · N") switches to the "archived" view, which lists
+ * archived chats and is the ONLY place a chat can be hard-deleted (hover →
+ * unarchive + delete). Both views read the same flat sessions cache and split
+ * on `status` locally.
+ */
+export function ChatThreadList({
+ sessions,
+ agents,
+ activeSessionId,
+ onSelectSession,
+}: {
+ sessions: ChatSession[];
+ agents: Agent[];
+ activeSessionId: string | null;
+ onSelectSession: (session: ChatSession) => void;
+}) {
+ const { t } = useT("chat");
+ const wsId = useWorkspaceId();
+ const agentById = useMemo(() => new Map(agents.map((a) => [a.id, a])), [agents]);
+
+ // Split the flat cache locally: active chats fill the default history view,
+ // archived chats fill the "Archived" view. Both sorted pinned-first (then by
+ // activity) so the list stays ordered even after an optimistic pin/archive or
+ // a WS patch mutates the flat cache in place.
+ const historySessions = useMemo(
+ () => sortChatSessions(sessions.filter((s) => s.status !== "archived")),
+ [sessions],
+ );
+ const archivedSessions = useMemo(
+ () => sortChatSessions(sessions.filter((s) => s.status === "archived")),
+ [sessions],
+ );
+
+ // Which view is showing. Falls back to history when the archived list drains
+ // (last chat unarchived / deleted) so we never strand the user on an empty
+ // archive.
+ const [view, setView] = useState<"history" | "archived">("history");
+ useEffect(() => {
+ if (view === "archived" && archivedSessions.length === 0) setView("history");
+ }, [view, archivedSessions.length]);
+
+ const [confirmingDeleteId, setConfirmingDeleteId] = useState<string | null>(null);
+ const [confirmingStopId, setConfirmingStopId] = useState<string | null>(null);
+ const [stoppingTaskId, setStoppingTaskId] = useState<string | null>(null);
+ const deleteSession = useDeleteChatSession();
+ const setPinned = useSetChatSessionPinned();
+ const setArchived = useSetChatSessionArchived();
+ const setActiveSession = useChatStore((s) => s.setActiveSession);
+ const queryClient = useQueryClient();
+
+ const { data: pending } = useQuery(pendingChatTasksOptions(wsId));
+ const pendingTaskBySessionId = useMemo(
+ () => new Map((pending?.tasks ?? []).map((task) => [task.chat_session_id, task])),
+ [pending],
+ );
+
+ // Per-agent presence, so a pending task on an OFFLINE agent shows "waiting"
+ // rather than a misleading "typing…" (the task is queued until the agent is
+ // back). Same availability source the conversation pane's status pill uses,
+ // keeping the two surfaces consistent.
+ const presence = useWorkspacePresenceMap(wsId);
+
+ useEffect(() => {
+ if (!confirmingStopId || pendingTaskBySessionId.has(confirmingStopId)) return;
+ setConfirmingStopId(null);
+ }, [confirmingStopId, pendingTaskBySessionId]);
+
+ const handleConfirmDelete = (session: ChatSession) => {
+ const sessionId = session.id;
+ if (activeSessionId === sessionId) setActiveSession(null);
+ deleteSession.mutate(sessionId, {
+ onSettled: () => setConfirmingDeleteId(null),
+ });
+ };
+
+ const handleConfirmStop = (
+ session: ChatSession,
+ task: PendingChatTasksResponse["tasks"][number],
+ ) => {
+ setStoppingTaskId(task.task_id);
+ queryClient.setQueryData<PendingChatTasksResponse>(chatKeys.pendingTasks(wsId), (current) => {
+ if (!current) return current;
+ return {
+ ...current,
+ tasks: current.tasks.filter((item) => item.task_id !== task.task_id),
+ };
+ });
+ queryClient.setQueryData(chatKeys.pendingTask(session.id), {});
+ queryClient.invalidateQueries({ queryKey: chatKeys.messages(session.id) });
+ queryClient.invalidateQueries({ queryKey: chatKeys.messagesPage(session.id) });
+
+ api.cancelTaskById(task.task_id).then(
+ (result) => {
+ const restored = result.cancelled_chat_message;
+ if (restored?.restore_to_input) {
+ removeChatMessageFromCaches(queryClient, restored.chat_session_id, restored.message_id);
+ }
+ apiLogger.info("cancelTask.success (list row)", { taskId: task.task_id, sessionId: session.id });
+ },
+ (err) =>
+ apiLogger.warn("cancelTask.error (list row; task may have already finished)", {
+ taskId: task.task_id,
+ sessionId: session.id,
+ err,
+ }),
+ ).finally(() => {
+ queryClient.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });
+ queryClient.invalidateQueries({ queryKey: chatKeys.pendingTask(session.id) });
+ setStoppingTaskId(null);
+ setConfirmingStopId(null);
+ });
+ };
+
+ const renderRow = (session: ChatSession) => {
+ const isCurrent = session.id === activeSessionId;
+ const agent = agentById.get(session.agent_id) ?? null;
+ const pendingTask = pendingTaskBySessionId.get(session.id);
+ const isRunning = !!pendingTask;
+ // Only "offline" (definitively long-offline) downgrades typing → waiting.
+ // Unknown/loading presence keeps the optimistic "typing…" so we never
+ // suppress it just because presence data hasn't landed yet.
+ const agentOffline = agent
+ ? presence.byAgent.get(agent.id)?.availability === "offline"
+ : false;
+ const unread = isCurrent ? 0 : (session.unread_count ?? 0);
+ const isConfirmingDelete = confirmingDeleteId === session.id;
+ const isConfirmingStop = confirmingStopId === session.id && !!pendingTask;
+ const isConfirmingAction = isConfirmingDelete || isConfirmingStop;
+ const titleText = session.title?.trim() || t(($) => $.window.untitled);
+ const last = session.last_message ?? null;
+ const timeText = last ? formatChatTime(last.created_at) : formatChatTime(session.updated_at);
+
+ // The second line: typing/waiting → failed → preview.
+ let previewNode: React.ReactNode;
+ if (isRunning && agentOffline) {
+ // Task is queued but the agent is offline — it will run once the agent
+ // is back. Show a static "waiting", not an animated "typing".
+ previewNode = (
+ <span className="flex min-w-0 items-center gap-1.5 text-muted-foreground">
+ <Clock className="size-3 shrink-0" />
+ <span className="truncate">{t(($) => $.list.waiting)}</span>
+ </span>
+ );
+ } else if (isRunning) {
+ previewNode = (
+ <span className="flex min-w-0 items-center gap-1.5 text-emerald-500">
+ <Loader2 className="size-3 shrink-0 animate-spin" />
+ <span className="truncate">{t(($) => $.list.typing)}</span>
+ </span>
+ );
+ } else if (last?.failure_reason) {
+ previewNode = <span className="block truncate text-destructive">{t(($) => $.list.failed)}</span>;
+ } else if (last) {
+ previewNode = (
+ <span className={cn("block truncate", unread > 0 ? "text-foreground/80" : "text-muted-foreground")}>
+ {last.role === "user" ? t(($) => $.list.you_prefix) : ""}
+ {toPreview(last.content)}
+ </span>
+ );
+ } else {
+ previewNode = <span className="block truncate text-muted-foreground/60">{t(($) => $.list.no_messages)}</span>;
+ }
+
+ return (
+ <div
+ key={session.id}
+ aria-current={isCurrent ? "true" : undefined}
+ tabIndex={0}
+ onClick={() => {
+ if (isConfirmingAction) return;
+ onSelectSession(session);
+ }}
+ onKeyDown={(e) => {
+ if (isConfirmingAction) return;
+ if (e.key !== "Enter" && e.key !== " ") return;
+ e.preventDefault();
+ onSelectSession(session);
+ }}
+ className={cn(
+ // Fixed height so nothing (hover actions, confirm prompts) can change
+ // the row size and make the list jump. Content is vertically centered.
+ "group/row relative flex h-14 min-w-0 cursor-default items-center gap-3 rounded-md px-2 outline-none transition-colors focus-visible:ring-1 focus-visible:ring-ring",
+ isCurrent ? "bg-accent" : "hover:bg-accent/50",
+ isConfirmingAction && "bg-destructive/5 hover:bg-destructive/5",
+ )}
+ >
+ {/* Thin ring keeps photo + fallback avatars reading as the same circle
+ (the fallback's faint bg otherwise looks smaller). */}
+ {agent ? (
+ <ActorAvatar actorType="agent" actorId={agent.id} size={36} enableHoverCard className="ring-1 ring-inset ring-border" />
+ ) : (
+ <span className="size-9 shrink-0" />
+ )}
+
+ <div className="min-w-0 flex-1">
+ {/* Line 1: name + time (time stays put; hover actions overlay below) */}
+ <div className="flex items-center gap-1.5">
+ {session.pinned && (
+ <Pin
+ aria-label={t(($) => $.list.pinned)}
+ className="size-3 shrink-0 -rotate-45 fill-current text-muted-foreground"
+ />
+ )}
+ <span className={cn("min-w-0 flex-1 truncate text-sm", unread > 0 ? "font-semibold text-foreground" : "font-medium")}>
+ {titleText}
+ </span>
+ <span className="ml-auto shrink-0 text-[11px] text-muted-foreground">{timeText}</span>
+ </div>
+
+ {/* Line 2: preview + unread badge, or an inline confirm prompt */}
+ <div className="mt-0.5 flex items-center gap-2">
+ {isConfirmingDelete ? (
+ <ConfirmRow
+ label={t(($) => $.session_history.delete_dialog.title)}
+ cancelText={t(($) => $.session_history.delete_dialog.cancel)}
+ confirmText={
+ deleteSession.isPending
+ ? t(($) => $.session_history.delete_dialog.confirming)
+ : t(($) => $.session_history.delete_dialog.confirm)
+ }
+ pending={deleteSession.isPending}
+ onCancel={() => setConfirmingDeleteId(null)}
+ onConfirm={() => handleConfirmDelete(session)}
+ />
+ ) : isConfirmingStop && pendingTask ? (
+ <ConfirmRow
+ label={t(($) => $.session_history.stop_dialog.title)}
+ cancelText={t(($) => $.session_history.stop_dialog.cancel)}
+ confirmText={
+ stoppingTaskId === pendingTask.task_id
+ ? t(($) => $.session_history.stop_dialog.confirming)
+ : t(($) => $.session_history.stop_dialog.confirm)
+ }
+ pending={stoppingTaskId === pendingTask.task_id}
+ onCancel={() => setConfirmingStopId(null)}
+ onConfirm={() => handleConfirmStop(session, pendingTask)}
+ />
+ ) : (
+ <>
+ <div className="min-w-0 flex-1 overflow-hidden text-xs">{previewNode}</div>
+ {unread > 0 && (
+ <span
+ aria-label={t(($) => $.session_history.row_subtitle.new_reply)}
+ // Softer, warmer red than the vivid `destructive` token —
+ // an IM unread badge, not an error.
+ className="inline-flex h-[18px] min-w-[18px] shrink-0 items-center justify-center rounded-full bg-[oklch(0.62_0.14_18)] px-1 text-[10.5px] font-semibold text-white"
+ >
+ {unread > 99 ? "99+" : unread}
+ </span>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Hover actions — absolutely positioned so showing/hiding them never
+ changes the row height (which was making the list jump). The archived
+ view is the only place hard-delete lives; the history view offers the
+ reversible archive instead. */}
+ {!isConfirmingAction && (
+ <div className="absolute inset-y-0 right-1 hidden items-center gap-0.5 rounded-md bg-gradient-to-l from-accent from-40% to-transparent pl-10 pr-1 group-hover/row:flex">
+ {view === "archived" ? (
+ <>
+ <RowAction
+ icon={<ArchiveRestore className="size-3.5" />}
+ label={t(($) => $.list.unarchive)}
+ onClick={() => setArchived.mutate({ sessionId: session.id, archived: false })}
+ />
+ <RowAction
+ icon={<Trash2 className="size-3.5" />}
+ label={t(($) => $.session_history.row_delete_aria)}
+ danger
+ onClick={() => setConfirmingDeleteId(session.id)}
+ />
+ </>
+ ) : (
+ <>
+ <RowAction
+ icon={session.pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5 -rotate-45" />}
+ label={session.pinned ? t(($) => $.list.unpin) : t(($) => $.list.pin)}
+ onClick={() => setPinned.mutate({ sessionId: session.id, pinned: !session.pinned })}
+ />
+ {isRunning ? (
+ <RowAction
+ icon={<Square className="size-3 fill-current" />}
+ label={t(($) => $.session_history.row_stop_aria)}
+ danger
+ onClick={() => setConfirmingStopId(session.id)}
+ />
+ ) : (
+ <RowAction
+ icon={<Archive className="size-3.5" />}
+ label={t(($) => $.list.archive)}
+ onClick={() => setArchived.mutate({ sessionId: session.id, archived: true })}
+ />
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ // Archived view: a back header, then the archived rows. Delete lives only
+ // here (via each row's hover actions).
+ if (view === "archived") {
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setView("history")}
+ className="flex w-full items-center gap-1.5 rounded-md px-2 py-2 text-left text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <ChevronLeft className="size-4 shrink-0" />
+ <span className="truncate">{t(($) => $.list.archived_title)}</span>
+ <span className="ml-auto shrink-0 tabular-nums text-muted-foreground/70">
+ {archivedSessions.length}
+ </span>
+ </button>
+ {archivedSessions.map(renderRow)}
+ </>
+ );
+ }
+
+ // History (default) view: active rows + a footer entry into the archive.
+ const archivedEntry = archivedSessions.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setView("archived")}
+ className="mt-1 flex h-10 w-full items-center gap-2 rounded-md px-2 text-left text-xs text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <span className="flex size-9 shrink-0 items-center justify-center">
+ <Archive className="size-4" />
+ </span>
+ <span className="min-w-0 flex-1 truncate font-medium">{t(($) => $.list.archived_title)}</span>
+ <span className="shrink-0 tabular-nums text-muted-foreground/70">{archivedSessions.length}</span>
+ <ChevronRight className="size-4 shrink-0 text-muted-foreground/50" />
+ </button>
+ );
+
+ if (historySessions.length === 0) {
+ return (
+ <>
+ <div className="px-2 py-1.5 text-xs text-muted-foreground">
+ {t(($) => $.window.no_previous)}
+ </div>
+ {archivedEntry}
+ </>
+ );
+ }
+
+ return (
+ <>
+ {historySessions.map(renderRow)}
+ {archivedEntry}
+ </>
+ );
+}
+
+function RowAction({
+ icon,
+ label,
+ onClick,
+ danger,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ onClick: () => void;
+ danger?: boolean;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={label}
+ onPointerDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ onClick();
+ }}
+ className={cn(
+ "inline-flex size-7 items-center justify-center rounded text-muted-foreground transition-colors focus-visible:outline-none",
+ danger
+ ? "hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive"
+ : "hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground",
+ )}
+ >
+ {icon}
+ </button>
+ );
+}
+
+function ConfirmRow({
+ label,
+ cancelText,
+ confirmText,
+ pending,
+ onCancel,
+ onConfirm,
+}: {
+ label: string;
+ cancelText: string;
+ confirmText: string;
+ pending: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+}) {
+ return (
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <span className="min-w-0 flex-1 truncate text-xs font-medium text-destructive">{label}</span>
+ <div className="flex shrink-0 items-center gap-1">
+ <button
+ type="button"
+ onPointerDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ onCancel();
+ }}
+ disabled={pending}
+ className="inline-flex h-6 items-center rounded px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
+ >
+ {cancelText}
+ </button>
+ <button
+ type="button"
+ onPointerDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ onConfirm();
+ }}
+ disabled={pending}
+ className="inline-flex h-6 items-center rounded px-2 text-[11px] font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50"
+ >
+ {confirmText}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 058a24fd62..f8a2bc597f 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -3,7 +3,7 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useInfiniteQuery, useQuery, useQueryClient, type InfiniteData } from "@tanstack/react-query";
import { motion } from "motion/react";
-import { Minus, Maximize2, Minimize2, ChevronDown, Plus, Check, Trash2, Pencil, Loader2, Square } from "lucide-react";
+import { Minus, Maximize2, Minimize2, ChevronDown, Plus, Check, Archive, Pencil, Loader2, Square } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { cn } from "@multica/ui/lib/utils";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
@@ -30,6 +30,7 @@ import {
import { matchesPinyin } from "../../editor/extensions/pinyin-match";
import { OfflineBanner } from "./offline-banner";
import { NoAgentBanner } from "./no-agent-banner";
+import { ArchivedAgentBanner } from "./archived-agent-banner";
import {
chatSessionsOptions,
chatMessagesPageOptions,
@@ -40,8 +41,8 @@ import {
} from "@multica/core/chat/queries";
import {
useCreateChatSession,
- useDeleteChatSession,
useMarkChatSessionRead,
+ useSetChatSessionArchived,
useUpdateChatSession,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
@@ -50,6 +51,7 @@ import { ChatInput } from "./chat-input";
import { ChatResizeHandles } from "./chat-resize-handles";
import { useChatContextItems } from "./use-chat-context-items";
import { useChatResize } from "./use-chat-resize";
+import { hasOptimisticInFlight } from "./use-chat-controller";
import { createLogger } from "@multica/core/logger";
import type { Agent, Attachment, ChatMessage, ChatMessagesPage, ChatPendingTask, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
import { useT } from "../../i18n";
@@ -172,7 +174,9 @@ export function ChatWindow() {
const { data: members = [] } = useQuery(memberListOptions(wsId));
// Single sessions cache — eliminates the separate active/all queries
// that used to drift during the WS-invalidate window.
- const { data: sessions = [] } = useQuery(chatSessionsOptions(wsId));
+ const { data: sessions = [], isSuccess: sessionsLoaded } = useQuery(
+ chatSessionsOptions(wsId),
+ );
const {
data: rawMessagePages,
isLoading: messagesLoading,
@@ -236,8 +240,21 @@ export function ChatWindow() {
(a) => !a.archived_at && canAssignAgent(a, user?.id, memberRole),
);
- // Resolve selected agent: stored preference → first available
+ // The agent bound to the OPEN session, resolved from the full agent list
+ // (archived included). An archived agent is filtered out of availableAgents,
+ // so resolving only from that list would make an archived-agent session
+ // render some *other* available agent — wrong avatar/name and a send that
+ // targets the wrong agent. Binding to the session's real agent keeps it
+ // honest; the archived state then makes the conversation read-only.
+ const sessionAgent = currentSession
+ ? agents.find((a) => a.id === currentSession.agent_id) ?? null
+ : null;
+ const isAgentArchived = !!sessionAgent?.archived_at;
+
+ // Resolve selected agent: open session's agent → stored preference → first
+ // available. New chats have no session, so they fall through to the picker.
const activeAgent =
+ sessionAgent ??
availableAgents.find((a) => a.id === selectedAgentId) ??
availableAgents[0] ??
null;
@@ -277,11 +294,24 @@ export function ChatWindow() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per mount
}, []);
- // Open intent is fully driven by `activeSessionId` in storage — no mount
- // restore, no self-heal. Adding either reintroduces a "two signals
- // describing one fact" race (the previous self-heal mis-cleared the
- // freshly-created session because allSessions was still stale during the
- // post-create invalidate-refetch window).
+ // Self-heal a dangling `activeSessionId` (persisted / restored from storage)
+ // that points at a session which was deleted or lost access: once the
+ // sessions list has loaded and doesn't contain it — with no in-flight
+ // optimistic write exempting a just-created session — clear it so the
+ // floating window shows the new-chat state instead of an editable empty chat
+ // whose send would POST into a nonexistent session. Same fix the shared
+ // controller applies for the tab (kept in sync via `hasOptimisticInFlight`).
+ // The earlier "no self-heal" note was about a naive version keyed on stale
+ // `allSessions`; the optimistic-write signal here exempts the freshly-created
+ // session (handleSend seeds its optimistic message + pending task BEFORE
+ // setActiveSession), so it is never mistaken for stale.
+ useEffect(() => {
+ if (!activeSessionId || !sessionsLoaded) return;
+ if (sessions.some((s) => s.id === activeSessionId)) return;
+ if (hasOptimisticInFlight(qc, activeSessionId)) return;
+ uiLogger.info("clearing dangling activeSessionId (floating)", { sessionId: activeSessionId });
+ setActiveSession(null);
+ }, [activeSessionId, sessionsLoaded, sessions, qc, setActiveSession]);
// WS events are handled globally in useRealtimeSync — the query cache
// stays current even when this window is closed. See packages/core/realtime/.
@@ -330,7 +360,18 @@ export function ChatWindow() {
const sessionPromiseRef = useRef<Promise<string | null> | null>(null);
const ensureSession = useCallback(
async (titleSeed: string): Promise<string | null> => {
- if (activeSessionId) return activeSessionId;
+ // Trust the current id only when it's real: in the loaded list, or a
+ // just-created one still awaiting the refetch (has an optimistic write).
+ // A dangling id (deleted / no access) must not be treated as an existing
+ // session — fall through and create a fresh one instead of POSTing 404.
+ if (
+ activeSessionId &&
+ (!sessionsLoaded ||
+ sessions.some((s) => s.id === activeSessionId) ||
+ hasOptimisticInFlight(qc, activeSessionId))
+ ) {
+ return activeSessionId;
+ }
if (!activeAgent) return null;
if (sessionPromiseRef.current) return sessionPromiseRef.current;
@@ -348,7 +389,7 @@ export function ChatWindow() {
sessionPromiseRef.current = promise;
return promise;
},
- [activeSessionId, activeAgent, createSession],
+ [activeSessionId, activeAgent, createSession, sessions, sessionsLoaded, qc],
);
const handleUploadFile = useCallback(
@@ -423,6 +464,16 @@ export function ChatWindow() {
apiLogger.warn("sendChatMessage skipped: no active agent");
return false;
}
+ // Read-only conversation: the agent is retired and can no longer pick up
+ // work, so refuse to enqueue a task that would sit orphaned forever. The
+ // input is disabled in this state; this is the belt-and-braces guard.
+ if (isAgentArchived) {
+ apiLogger.warn("sendChatMessage skipped: agent is archived", {
+ sessionId: activeSessionId,
+ agentId: activeAgent.id,
+ });
+ return false;
+ }
const finalContent = content;
@@ -569,6 +620,7 @@ export function ChatWindow() {
activeSessionId,
selectedAgentId,
activeAgent,
+ isAgentArchived,
ensureSession,
cancelChatTask,
qc,
@@ -783,12 +835,15 @@ export function ChatWindow() {
* first agent-list response stays banner-free. */}
{noAgent ? (
<NoAgentBanner />
+ ) : isAgentArchived ? (
+ <ArchivedAgentBanner agentName={activeAgent?.name} />
) : (
<OfflineBanner agentName={activeAgent?.name} availability={availability} />
)}
- {/* Input — disabled for legacy archived sessions; locked out entirely
- * when there's no agent (the EmptyState above carries the CTA). */}
+ {/* Input — disabled for legacy archived sessions and for sessions whose
+ * agent has been archived (read-only); locked out entirely when there's
+ * no agent (the EmptyState above carries the CTA). */}
<ChatInput
onSend={handleSend}
restoreDraftRequest={restoreDraftRequest}
@@ -796,8 +851,9 @@ export function ChatWindow() {
onUploadFile={handleUploadFile}
onStop={handleStop}
isRunning={!!pendingTaskId}
- disabled={isSessionArchived}
+ disabled={isSessionArchived || isAgentArchived}
noAgent={noAgent}
+ agentArchived={isAgentArchived}
agentName={activeAgent?.name}
leftAdornment={
<AgentDropdown
@@ -982,7 +1038,6 @@ function SessionDropdown({
);
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
- const [confirmingDeleteId, setConfirmingDeleteId] = useState<string | null>(null);
const [confirmingStopId, setConfirmingStopId] = useState<string | null>(null);
const [stoppingTaskId, setStoppingTaskId] = useState<string | null>(null);
const [completedFlashIds, setCompletedFlashIds] = useState<Set<string>>(() => new Set());
@@ -992,7 +1047,7 @@ function SessionDropdown({
// session id (not the full session) so a stale closure can't overwrite a
// newer rename pulled in via WS.
const [renamingId, setRenamingId] = useState<string | null>(null);
- const deleteSession = useDeleteChatSession();
+ const setArchived = useSetChatSessionArchived();
const updateSession = useUpdateChatSession();
const setActiveSession = useChatStore((s) => s.setActiveSession);
const queryClient = useQueryClient();
@@ -1065,19 +1120,18 @@ function SessionDropdown({
(s) => s.id !== activeSessionId && s.has_unread,
).length;
- const handleConfirmDelete = (session: ChatSession) => {
- const sessionId = session.id;
- const isDeletingCurrent = activeSessionId === sessionId;
- // Eager local clear when the user is deleting the session they're
- // currently looking at — otherwise messages / pendingTask queries
- // keep rendering the now-deleted session until chat:session_deleted
- // arrives over WS (~50–200ms gap).
- if (isDeletingCurrent) {
+ // Archive (not hard-delete) is the reversible, one-click default here — the
+ // same safety model as ChatThreadList. The floating window offers NO
+ // hard-delete: unarchive / delete live only in the full Chat page's Archived
+ // view (reachable via the expand button), so a stale floating dropdown can't
+ // 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);
}
- deleteSession.mutate(sessionId, {
- onSettled: () => setConfirmingDeleteId(null),
- });
+ setArchived.mutate({ sessionId: session.id, archived: true });
};
const handleSubmitRename = (sessionId: string, raw: string) => {
@@ -1146,9 +1200,8 @@ function SessionDropdown({
const showCompleted = completedFlashIds.has(session.id) && !isCurrent;
const showUnread = session.has_unread && !isCurrent;
const isRenaming = renamingId === session.id;
- const isConfirmingDelete = confirmingDeleteId === session.id;
const isConfirmingStop = confirmingStopId === session.id && !!pendingTask;
- const isConfirmingAction = isConfirmingDelete || isConfirmingStop;
+ const isConfirmingAction = isConfirmingStop;
const titleText = session.title?.trim() || t(($) => $.window.untitled);
const trailingStatus = isRunning
? t(($) => $.session_history.row_subtitle.working)
@@ -1198,10 +1251,6 @@ function SessionDropdown({
onSubmit={(value) => handleSubmitRename(session.id, value)}
onCancel={() => setRenamingId(null)}
/>
- ) : isConfirmingDelete ? (
- <div className="truncate text-sm font-medium text-destructive">
- {t(($) => $.session_history.delete_dialog.title)}
- </div>
) : isConfirmingStop ? (
<div className="truncate text-sm font-medium text-destructive">
{t(($) => $.session_history.stop_dialog.title)}
@@ -1219,44 +1268,7 @@ function SessionDropdown({
)}
</div>
{!isRenaming && (
- isConfirmingDelete ? (
- <div className="flex shrink-0 items-center gap-1">
- <button
- type="button"
- onPointerDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- setConfirmingDeleteId(null);
- }}
- disabled={deleteSession.isPending}
- className="inline-flex h-7 items-center rounded px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
- >
- {t(($) => $.session_history.delete_dialog.cancel)}
- </button>
- <button
- type="button"
- onPointerDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- handleConfirmDelete(session);
- }}
- disabled={deleteSession.isPending}
- className="inline-flex h-7 items-center rounded px-2 text-[11px] font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50"
- >
- {deleteSession.isPending
- ? t(($) => $.session_history.delete_dialog.confirming)
- : t(($) => $.session_history.delete_dialog.confirm)}
- </button>
- </div>
- ) : isConfirmingStop && pendingTask ? (
+ isConfirmingStop && pendingTask ? (
<div className="flex shrink-0 items-center gap-1">
<button
type="button"
@@ -1356,13 +1368,13 @@ function SessionDropdown({
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
- setConfirmingDeleteId(session.id);
+ handleArchive(session);
}}
- className="inline-flex size-7 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive focus-visible:outline-none"
- aria-label={t(($) => $.session_history.row_delete_aria)}
- title={t(($) => $.session_history.row_delete_aria)}
+ className="inline-flex size-7 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:outline-none"
+ aria-label={t(($) => $.list.archive)}
+ title={t(($) => $.list.archive)}
>
- <Trash2 className="size-3.5" />
+ <Archive className="size-3.5" />
</button>
</>
)}
diff --git a/packages/views/chat/components/new-chat-button.tsx b/packages/views/chat/components/new-chat-button.tsx
new file mode 100644
index 0000000000..2e827ac950
--- /dev/null
+++ b/packages/views/chat/components/new-chat-button.tsx
@@ -0,0 +1,199 @@
+"use client";
+
+import React, { useMemo, useState } from "react";
+import { Plus } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
+import { ActorAvatar } from "../../common/actor-avatar";
+import {
+ PickerEmpty,
+ PickerItem,
+ PickerSection,
+ PropertyPicker,
+} from "../../issues/components/pickers/property-picker";
+import { matchesPinyin } from "../../editor/extensions/pinyin-match";
+import type { Agent } from "@multica/core/types";
+import { useT } from "../../i18n";
+
+/**
+ * Agent picker: a searchable, grouped (My agents / Others) list of agents in a
+ * PropertyPicker. The caller supplies the trigger. `currentAgentId` marks one
+ * agent with a check — omit it (as "new chat" does) when there is no current
+ * selection to highlight.
+ */
+export function AgentPicker({
+ agents,
+ userId,
+ currentAgentId,
+ onSelect,
+ trigger,
+ triggerRender,
+ side = "bottom",
+ align = "start",
+}: {
+ agents: Agent[];
+ userId: string | undefined;
+ currentAgentId?: string;
+ onSelect: (agent: Agent) => void;
+ trigger: React.ReactNode;
+ triggerRender: React.ReactElement;
+ side?: "top" | "bottom";
+ align?: "start" | "center" | "end";
+}) {
+ const { t } = useT("chat");
+ const [open, setOpen] = useState(false);
+ const [filter, setFilter] = useState("");
+ const { mine, others } = useMemo(() => {
+ const mine: Agent[] = [];
+ const others: Agent[] = [];
+ for (const a of agents) {
+ if (a.owner_id === userId) mine.push(a);
+ else others.push(a);
+ }
+ return { mine, others };
+ }, [agents, userId]);
+
+ const query = filter.trim().toLowerCase();
+ const matches = (name: string) =>
+ !query || name.toLowerCase().includes(query) || matchesPinyin(name, query);
+ const filteredMine = mine.filter((agent) => matches(agent.name));
+ const filteredOthers = others.filter((agent) => matches(agent.name));
+
+ const handlePick = (agent: Agent) => {
+ onSelect(agent);
+ setOpen(false);
+ };
+
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ width="w-64"
+ align={align}
+ side={side}
+ searchable
+ searchPlaceholder={t(($) => $.window.agent_filter_placeholder)}
+ onSearchChange={setFilter}
+ triggerRender={triggerRender}
+ trigger={trigger}
+ >
+ {filteredMine.length === 0 && filteredOthers.length === 0 ? (
+ <PickerEmpty />
+ ) : (
+ <>
+ {filteredMine.length > 0 && (
+ <PickerSection label={t(($) => $.window.my_agents)}>
+ {filteredMine.map((agent) => (
+ <AgentPickerItem
+ key={agent.id}
+ agent={agent}
+ isCurrent={agent.id === currentAgentId}
+ onSelect={handlePick}
+ />
+ ))}
+ </PickerSection>
+ )}
+ {filteredOthers.length > 0 && (
+ <PickerSection label={t(($) => $.window.others)}>
+ {filteredOthers.map((agent) => (
+ <AgentPickerItem
+ key={agent.id}
+ agent={agent}
+ isCurrent={agent.id === currentAgentId}
+ onSelect={handlePick}
+ />
+ ))}
+ </PickerSection>
+ )}
+ </>
+ )}
+ </PropertyPicker>
+ );
+}
+
+function AgentPickerItem({
+ agent,
+ isCurrent,
+ onSelect,
+}: {
+ agent: Agent;
+ isCurrent: boolean;
+ onSelect: (agent: Agent) => void;
+}) {
+ return (
+ <PickerItem selected={isCurrent} onClick={() => onSelect(agent)}>
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size={24}
+ enableHoverCard
+ showStatusDot
+ />
+ <span className="truncate flex-1">{agent.name}</span>
+ </PickerItem>
+ );
+}
+
+/**
+ * "New chat" ⊕ button. Per the Chat V2 design, starting a new chat is where the
+ * agent is chosen — so this opens an AgentPicker and reports the pick via
+ * `onStart`. No agent is pre-checked: a new chat has no "current" agent yet.
+ * Shortcuts: with a single available agent it starts immediately (no point
+ * showing a one-item menu); with none it still fires `onStart(null)` so the
+ * surface shows its no-agent empty state.
+ */
+export function NewChatButton({
+ agents,
+ userId,
+ onStart,
+ side = "bottom",
+}: {
+ agents: Agent[];
+ userId: string | undefined;
+ onStart: (agent: Agent | null) => void;
+ side?: "top" | "bottom";
+}) {
+ const { t } = useT("chat");
+ const label = t(($) => $.window.new_chat_tooltip);
+
+ if (agents.length <= 1) {
+ const only = agents[0] ?? null;
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="rounded-full text-muted-foreground"
+ aria-label={label}
+ onClick={() => onStart(only)}
+ />
+ }
+ >
+ <Plus />
+ </TooltipTrigger>
+ <TooltipContent side={side === "top" ? "top" : "bottom"}>{label}</TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return (
+ <AgentPicker
+ agents={agents}
+ userId={userId}
+ onSelect={(agent) => onStart(agent)}
+ side={side}
+ align="start"
+ triggerRender={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="rounded-full text-muted-foreground"
+ aria-label={label}
+ />
+ }
+ trigger={<Plus />}
+ />
+ );
+}
diff --git a/packages/views/chat/components/quick-agent-bar.tsx b/packages/views/chat/components/quick-agent-bar.tsx
new file mode 100644
index 0000000000..26e4c3b7b2
--- /dev/null
+++ b/packages/views/chat/components/quick-agent-bar.tsx
@@ -0,0 +1,115 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Plus } from "lucide-react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { chatPinnedAgentsOptions } from "@multica/core/chat/queries";
+import { usePinChatAgent, useUnpinChatAgent } from "@multica/core/chat/mutations";
+import type { Agent } from "@multica/core/types";
+import {
+ ContextMenu,
+ ContextMenuTrigger,
+ ContextMenuContent,
+ ContextMenuItem,
+} from "@multica/ui/components/ui/context-menu";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { AgentPicker } from "./new-chat-button";
+import { useT } from "../../i18n";
+
+// Consistent thin ring so photo avatars and (fainter) fallback avatars read as
+// the same-size circle in the chat list.
+const AVATAR_RING = "ring-1 ring-inset ring-border";
+
+// Keep the bar compact — capped at 5, matching the server limit.
+const MAX_PINNED = 5;
+
+/**
+ * Quick-agent bar — a compact, avatar-only strip of the user's pinned agents at
+ * the top of the Chat list (per user · workspace, server-side). Tapping an
+ * avatar starts a new chat; hovering shows the agent info card; right-clicking
+ * removes it; the "+" adds one (up to 5). No title, no names — space is tight.
+ */
+export function QuickAgentBar({
+ agents,
+ userId,
+ onStartNewChat,
+}: {
+ agents: Agent[];
+ userId: string | undefined;
+ onStartNewChat: (agent: Agent) => void;
+}) {
+ const { t } = useT("chat");
+ const wsId = useWorkspaceId();
+ const { data: pinned = [] } = useQuery(chatPinnedAgentsOptions(wsId));
+ const pin = usePinChatAgent();
+ const unpin = useUnpinChatAgent();
+
+ const agentById = useMemo(() => new Map(agents.map((a) => [a.id, a])), [agents]);
+ const pinnedAgents = useMemo(
+ () => pinned.map((p) => agentById.get(p.agent_id)).filter((a): a is Agent => !!a),
+ [pinned, agentById],
+ );
+ const pinnedIds = useMemo(() => new Set(pinned.map((p) => p.agent_id)), [pinned]);
+ const addable = useMemo(() => agents.filter((a) => !pinnedIds.has(a.id)), [agents, pinnedIds]);
+ const canAdd = addable.length > 0 && pinnedAgents.length < MAX_PINNED;
+
+ // Nothing to pin and nothing pinned → hide the bar.
+ if (agents.length === 0) return null;
+ if (pinnedAgents.length === 0 && !canAdd) return null;
+
+ return (
+ <div className="flex items-center gap-1.5 overflow-x-auto border-b px-2 py-1.5">
+ {pinnedAgents.map((agent) => (
+ <ContextMenu key={agent.id}>
+ <ContextMenuTrigger
+ render={
+ <button
+ type="button"
+ aria-label={agent.name}
+ onClick={() => onStartNewChat(agent)}
+ className="flex size-[34px] shrink-0 items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ >
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size={34}
+ showStatusDot
+ enableHoverCard
+ profileLink={false}
+ className={AVATAR_RING}
+ />
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem variant="destructive" onClick={() => unpin.mutate(agent.id)}>
+ {t(($) => $.list.unpin_agent)}
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ ))}
+
+ {canAdd && (
+ <AgentPicker
+ agents={addable}
+ userId={userId}
+ onSelect={(agent) => pin.mutate(agent.id)}
+ side="bottom"
+ align="start"
+ triggerRender={
+ <button
+ type="button"
+ aria-label={t(($) => $.list.add_agent)}
+ // Filled circle (not a dashed outline) so it reads as the exact
+ // same size as the filled agent avatars — an empty outline looks
+ // larger at the same pixel diameter. Same ring as the avatars.
+ className="flex size-[34px] shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground ring-1 ring-inset ring-border outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ trigger={<Plus className="size-4" />}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/use-chat-context-items.test.ts b/packages/views/chat/components/use-chat-context-items.test.ts
deleted file mode 100644
index 054224e230..0000000000
--- a/packages/views/chat/components/use-chat-context-items.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { parseCurrentContextRoute } from "./use-chat-context-items";
-
-describe("parseCurrentContextRoute", () => {
- it("detects issue detail pages", () => {
- expect(parseCurrentContextRoute("/acme/issues/issue-1", new URLSearchParams())).toEqual({
- type: "issue",
- id: "issue-1",
- });
- });
-
- it("detects project detail pages", () => {
- expect(parseCurrentContextRoute("/acme/projects/project-1", new URLSearchParams())).toEqual({
- type: "project",
- id: "project-1",
- });
- });
-
- it("uses the inbox issue query param as the current issue id", () => {
- expect(parseCurrentContextRoute("/acme/inbox", new URLSearchParams("issue=issue-42"))).toEqual({
- type: "issue",
- id: "issue-42",
- });
- });
-
- it("does not treat the bare inbox route as current issue context", () => {
- expect(parseCurrentContextRoute("/acme/inbox", new URLSearchParams())).toBeNull();
- });
-});
diff --git a/packages/views/chat/components/use-chat-controller.test.ts b/packages/views/chat/components/use-chat-controller.test.ts
new file mode 100644
index 0000000000..0874ce751c
--- /dev/null
+++ b/packages/views/chat/components/use-chat-controller.test.ts
@@ -0,0 +1,67 @@
+import { describe, it, expect } from "vitest";
+import { QueryClient, type InfiniteData } from "@tanstack/react-query";
+import { chatKeys } from "@multica/core/chat/queries";
+import type { ChatMessage, ChatMessagesPage, ChatPendingTask } from "@multica/core/types";
+import { hasOptimisticInFlight } from "./use-chat-controller";
+
+// hasOptimisticInFlight is the discriminator the stale-session self-heal uses
+// to EXEMPT a just-created session (awaiting the list refetch) from being
+// dropped as dangling. The critical property (MUL-4171 review): it must key
+// off OPTIMISTIC in-flight writes, NOT merely "has cached messages" — a session
+// deleted elsewhere can still hold real cached history and must remain eligible
+// for self-heal.
+const sid = "session-1";
+
+function msg(id: string): ChatMessage {
+ return {
+ id,
+ chat_session_id: sid,
+ role: "user",
+ content: "hi",
+ task_id: null,
+ created_at: "2026-07-08T00:00:00Z",
+ };
+}
+
+describe("hasOptimisticInFlight", () => {
+ it("is false with an empty cache", () => {
+ expect(hasOptimisticInFlight(new QueryClient(), sid)).toBe(false);
+ });
+
+ it("is false when only real (non-optimistic) cached history exists", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(sid), [msg("real-1"), msg("real-2")]);
+ qc.setQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sid), {
+ pages: [{ messages: [msg("real-1")], limit: 50, has_more: false, next_cursor: null }],
+ pageParams: [null],
+ });
+ // A completed session sets pendingTask to {} (no task_id).
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sid), {} as ChatPendingTask);
+ expect(hasOptimisticInFlight(qc, sid)).toBe(false);
+ });
+
+ it("is true while a pending task is in flight (task_id set)", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sid), {
+ task_id: "optimistic-abc",
+ status: "queued",
+ created_at: "2026-07-08T00:00:00Z",
+ });
+ expect(hasOptimisticInFlight(qc, sid)).toBe(true);
+ });
+
+ it("is true when an optimistic- message sits in the flat cache", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(sid), [msg("optimistic-123")]);
+ expect(hasOptimisticInFlight(qc, sid)).toBe(true);
+ });
+
+ it("is true when an optimistic- message sits in the paged cache", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sid), {
+ pages: [{ messages: [msg("optimistic-xyz")], limit: 50, has_more: false, next_cursor: null }],
+ pageParams: [null],
+ });
+ expect(hasOptimisticInFlight(qc, sid)).toBe(true);
+ });
+});
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
new file mode 100644
index 0000000000..ded5e2cf49
--- /dev/null
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -0,0 +1,653 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ useInfiniteQuery,
+ useQuery,
+ useQueryClient,
+ type InfiniteData,
+} from "@tanstack/react-query";
+import { toast } from "sonner";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useAuthStore } from "@multica/core/auth";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import { canAssignAgent } from "@multica/views/issues/components";
+import { api } from "@multica/core/api";
+import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
+import { useFileUpload } from "@multica/core/hooks/use-file-upload";
+import {
+ chatSessionsOptions,
+ chatMessagesPageOptions,
+ pendingChatTaskOptions,
+ chatKeys,
+ isTaskMessageTaskId,
+} from "@multica/core/chat/queries";
+import {
+ useCreateChatSession,
+ useMarkChatSessionRead,
+} from "@multica/core/chat/mutations";
+import { useChatStore } from "@multica/core/chat";
+import { createLogger } from "@multica/core/logger";
+import type {
+ Agent,
+ Attachment,
+ ChatMessage,
+ ChatMessagesPage,
+ ChatPendingTask,
+} from "@multica/core/types";
+import { useT } from "../../i18n";
+
+const uiLogger = createLogger("chat.ui");
+const apiLogger = createLogger("chat.api");
+
+// Derive a concise session title from the first user message: first line,
+// markdown stripped, whitespace collapsed, capped. A deterministic title
+// (no LLM) — the server has no summarization model, so this is the sensible
+// default until a runtime-generated title is wired up.
+const CHAT_TITLE_MAX = 30;
+export function deriveChatTitle(content: string): string {
+ const firstLine = (content.split("\n").find((l) => l.trim()) ?? content).trim();
+ const cleaned = firstLine
+ .replace(/```[\s\S]*?```/g, " ")
+ .replace(/[#*`>~_]/g, "")
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") // markdown links/images → their text
+ .replace(/\s+/g, " ")
+ .trim();
+ if (cleaned.length <= CHAT_TITLE_MAX) return cleaned;
+ return cleaned.slice(0, CHAT_TITLE_MAX - 1).trimEnd() + "…";
+}
+
+// True when a session has an in-flight optimistic write — an `optimistic-`
+// message or a pending task in the cache. That is the signal of a just-created
+// (or actively-sending) session still awaiting server confirmation, before the
+// sessions-list refetch includes it. Deliberately NOT "has cached messages": a
+// session deleted elsewhere can still have real cached history, which must not
+// exempt it from the stale-session self-heal.
+export function hasOptimisticInFlight(
+ qc: ReturnType<typeof useQueryClient>,
+ sessionId: string,
+): boolean {
+ const pending = qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId));
+ if (pending?.task_id) return true;
+ const flat = qc.getQueryData<ChatMessage[]>(chatKeys.messages(sessionId));
+ if (flat?.some((m) => m.id.startsWith("optimistic-"))) return true;
+ const paged = qc.getQueryData<InfiniteData<ChatMessagesPage>>(
+ chatKeys.messagesPage(sessionId),
+ );
+ return Boolean(
+ paged?.pages.some((page) =>
+ page.messages.some((m) => m.id.startsWith("optimistic-")),
+ ),
+ );
+}
+const CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX = 1_000_000;
+
+function appendChatMessageToLatestPageCache(
+ qc: ReturnType<typeof useQueryClient>,
+ sessionId: string,
+ message: ChatMessage,
+) {
+ qc.setQueryData<InfiniteData<ChatMessagesPage>>(
+ chatKeys.messagesPage(sessionId),
+ (old) => {
+ if (!old) {
+ return {
+ pages: [{
+ messages: [message],
+ limit: 50,
+ has_more: false,
+ next_cursor: null,
+ }],
+ pageParams: [null],
+ };
+ }
+ if (old.pages.some((page) => page.messages.some((m) => m.id === message.id))) {
+ return old;
+ }
+ return {
+ ...old,
+ pages: old.pages.map((page, index) =>
+ index === 0 ? { ...page, messages: [...page.messages, message] } : page,
+ ),
+ };
+ },
+ );
+}
+
+function removeChatMessageFromPageCache(
+ qc: ReturnType<typeof useQueryClient>,
+ sessionId: string,
+ messageId: string,
+) {
+ qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
+ chatKeys.messagesPage(sessionId),
+ (old) => {
+ if (!old) return old;
+ return {
+ ...old,
+ pages: old.pages.map((page) => ({
+ ...page,
+ messages: page.messages.filter((m) => m.id !== messageId),
+ })),
+ };
+ },
+ );
+}
+
+export function removeChatMessageFromCaches(
+ qc: ReturnType<typeof useQueryClient>,
+ sessionId: string,
+ messageId: string,
+) {
+ qc.setQueryData<ChatMessage[]>(
+ chatKeys.messages(sessionId),
+ (old) => old?.filter((m) => m.id !== messageId) ?? old,
+ );
+ removeChatMessageFromPageCache(qc, sessionId, messageId);
+}
+
+function replaceOptimisticChatMessageId(
+ qc: ReturnType<typeof useQueryClient>,
+ sessionId: string,
+ optimisticId: string,
+ messageId: string,
+ taskId: string,
+) {
+ const replace = (messages: ChatMessage[] | undefined) => {
+ if (!messages) return messages;
+ if (messages.some((m) => m.id === messageId)) {
+ return messages.filter((m) => m.id !== optimisticId);
+ }
+ return messages.map((m) =>
+ m.id === optimisticId ? { ...m, id: messageId, task_id: taskId } : m,
+ );
+ };
+
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), replace);
+ qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
+ chatKeys.messagesPage(sessionId),
+ (old) => {
+ if (!old) return old;
+ return {
+ ...old,
+ pages: old.pages.map((page) => ({
+ ...page,
+ messages: replace(page.messages) ?? page.messages,
+ })),
+ };
+ },
+ );
+}
+
+/**
+ * Layout-agnostic chat controller. Holds every piece of chat conversation
+ * state and behavior — agent resolution, session lookup, the optimistic
+ * send/stop/cancel burst, message pagination, and auto-mark-read — so that
+ * both surfaces render the same conversation logic:
+ *
+ * - ChatWindow: the floating FAB overlay (adds resize / expand / minimize).
+ * - ChatPage: the first-class Chat tab (two-pane thread list + conversation).
+ *
+ * The only thing the caller supplies is `isActive` — whether its surface is
+ * currently on screen — which gates auto-mark-read so a background overlay
+ * doesn't silently clear unread state the user hasn't actually seen.
+ */
+export function useChatController(opts?: { isActive?: boolean }) {
+ const isActive = opts?.isActive ?? true;
+ const { t } = useT("chat");
+ const wsId = useWorkspaceId();
+ const activeSessionId = useChatStore((s) => s.activeSessionId);
+ const selectedAgentId = useChatStore((s) => s.selectedAgentId);
+ const setActiveSession = useChatStore((s) => s.setActiveSession);
+ const setSelectedAgentId = useChatStore((s) => s.setSelectedAgentId);
+ const user = useAuthStore((s) => s.user);
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { data: sessions = [], isSuccess: sessionsLoaded } = useQuery(
+ chatSessionsOptions(wsId),
+ );
+ const {
+ data: rawMessagePages,
+ isLoading: messagesLoading,
+ fetchNextPage: fetchOlderMessages,
+ hasNextPage: hasOlderMessages,
+ isFetchingNextPage: isFetchingOlderMessages,
+ } = useInfiniteQuery(chatMessagesPageOptions(activeSessionId ?? ""));
+
+ const messagePages = activeSessionId ? rawMessagePages?.pages ?? [] : [];
+ const messages = [...messagePages].reverse().flatMap((page) => page.messages);
+ const olderMessageCount = messagePages
+ .slice(1)
+ .reduce((sum, page) => sum + page.messages.length, 0);
+ const firstItemIndex =
+ messages.length > 0
+ ? CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX - olderMessageCount
+ : 0;
+ const showSkeleton = !!activeSessionId && messagesLoading;
+
+ const { data: pendingTask } = useQuery(
+ pendingChatTaskOptions(activeSessionId ?? ""),
+ );
+ const pendingTaskId = pendingTask?.task_id ?? null;
+ const stopRequestedBeforeTaskRef = useRef(false);
+ const [restoreDraftRequest, setRestoreDraftRequest] = useState<{
+ id: string;
+ content: string;
+ attachments?: Attachment[];
+ sessionId?: string;
+ } | null>(null);
+ const handleRestoreDraftConsumed = useCallback(() => {
+ setRestoreDraftRequest(null);
+ }, []);
+
+ const currentSession = activeSessionId
+ ? sessions.find((s) => s.id === activeSessionId)
+ : null;
+ const isSessionArchived = currentSession?.status === "archived";
+
+ const qc = useQueryClient();
+ const createSession = useCreateChatSession();
+ const markRead = useMarkChatSessionRead();
+
+ const currentMember = members.find((m) => m.user_id === user?.id);
+ const memberRole = currentMember?.role;
+ const availableAgents = agents.filter(
+ (a) => !a.archived_at && canAssignAgent(a, user?.id, memberRole),
+ );
+
+ // The agent bound to the OPEN session, resolved from the full agent list
+ // (archived included, since agentListOptions passes include_archived). An
+ // archived agent is filtered out of `availableAgents`, so resolving the
+ // active agent only from that list would make an archived-agent session
+ // silently render some *other* available agent — wrong avatar/name/presence
+ // in the header, and a send that targets the wrong agent. Binding to the
+ // session's real agent keeps the conversation honest; the archived state
+ // then makes it read-only (see isAgentArchived).
+ const sessionAgent = currentSession
+ ? agents.find((a) => a.id === currentSession.agent_id) ?? null
+ : null;
+ const isAgentArchived = !!sessionAgent?.archived_at;
+
+ // Resolve selected agent: open session's agent → stored preference → first
+ // available. New chats have no session, so they fall through to the picker.
+ const activeAgent =
+ sessionAgent ??
+ availableAgents.find((a) => a.id === selectedAgentId) ??
+ availableAgents[0] ??
+ null;
+
+ const agentAvailability = useWorkspaceAgentAvailability();
+ const noAgent = agentAvailability === "none";
+
+ const presenceDetail = useAgentPresenceDetail(wsId, activeAgent?.id);
+ const availability =
+ presenceDetail === "loading" ? undefined : presenceDetail.availability;
+
+ // Auto mark-as-read whenever the user is actively looking at a session with
+ // unread state. `isActive` lets the caller say "my surface is on screen":
+ // the floating overlay passes `isOpen`, the tab passes `true`.
+ const currentHasUnread =
+ sessions.find((s) => s.id === activeSessionId)?.has_unread ?? false;
+ useEffect(() => {
+ if (!isActive || !activeSessionId) return;
+ if (!currentHasUnread) return;
+ uiLogger.info("auto markRead", { sessionId: activeSessionId });
+ markRead.mutate(activeSessionId);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable
+ }, [isActive, activeSessionId, currentHasUnread]);
+
+ const { uploadWithToast } = useFileUpload(api);
+
+ const sessionPromiseRef = useRef<Promise<string | null> | null>(null);
+ const ensureSession = useCallback(
+ async (titleSeed: string): Promise<string | null> => {
+ // Trust the current session id only when it's real: present in the
+ // loaded list, or a just-created one still awaiting the list refetch
+ // (has an optimistic write). A dangling id (deleted / no access) must not
+ // be treated as an existing session — fall through and create a fresh one
+ // so the message lands somewhere instead of POSTing into a 404.
+ if (
+ activeSessionId &&
+ (!sessionsLoaded ||
+ sessions.some((s) => s.id === activeSessionId) ||
+ hasOptimisticInFlight(qc, activeSessionId))
+ ) {
+ return activeSessionId;
+ }
+ if (!activeAgent) return null;
+ if (sessionPromiseRef.current) return sessionPromiseRef.current;
+
+ const promise = (async () => {
+ try {
+ const session = await createSession.mutateAsync({
+ agent_id: activeAgent.id,
+ title: deriveChatTitle(titleSeed),
+ });
+ return session.id;
+ } finally {
+ sessionPromiseRef.current = null;
+ }
+ })();
+ sessionPromiseRef.current = promise;
+ return promise;
+ },
+ [activeSessionId, activeAgent, createSession, sessions, sessionsLoaded, qc],
+ );
+
+ // Self-heal a dangling `activeSessionId`. Once the sessions list has loaded
+ // and it isn't in the list — with no in-flight optimistic write exempting a
+ // just-created session — the id was deleted, lost access, or never existed
+ // (a stale `?session=` deep link, or a persisted floating-window selection).
+ // Clearing it stops BOTH surfaces (the tab and the floating window) from
+ // rendering an editable empty chat whose send would POST into a nonexistent
+ // session. Lives in the shared controller so every surface self-heals.
+ useEffect(() => {
+ if (!activeSessionId || !sessionsLoaded) return;
+ if (sessions.some((s) => s.id === activeSessionId)) return;
+ if (hasOptimisticInFlight(qc, activeSessionId)) return;
+ uiLogger.info("clearing dangling activeSessionId", { sessionId: activeSessionId });
+ setActiveSession(null);
+ }, [activeSessionId, sessionsLoaded, sessions, qc, setActiveSession]);
+
+ const handleUploadFile = useCallback(
+ async (file: File) => {
+ if (!activeAgent) return null;
+ return uploadWithToast(file);
+ },
+ [activeAgent, uploadWithToast],
+ );
+
+ const cancelChatTask = useCallback(
+ async (
+ taskId: string,
+ sessionId: string,
+ options: { restoreDraftToInput: boolean; source: string },
+ ) => {
+ apiLogger.info("cancelTask.start", {
+ taskId,
+ sessionId,
+ source: options.source,
+ });
+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+
+ try {
+ const result = await api.cancelTaskById(taskId);
+ const restored = result.cancelled_chat_message;
+ if (restored?.restore_to_input) {
+ removeChatMessageFromCaches(qc, restored.chat_session_id, restored.message_id);
+ if (options.restoreDraftToInput && restored.chat_session_id === sessionId) {
+ setRestoreDraftRequest({
+ id: restored.message_id,
+ content: restored.content,
+ attachments: restored.attachments,
+ sessionId: restored.chat_session_id,
+ });
+ }
+ }
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
+ apiLogger.info("cancelTask.success", {
+ taskId,
+ sessionId,
+ restoredToInput: !!restored?.restore_to_input && options.restoreDraftToInput,
+ });
+ return result;
+ } catch (err) {
+ apiLogger.warn("cancelTask.error (task may have already finished)", {
+ taskId,
+ sessionId,
+ err,
+ });
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
+ return null;
+ }
+ },
+ [qc],
+ );
+
+ const handleSend = useCallback(
+ async (
+ content: string,
+ attachmentIds?: string[],
+ commitInput?: (options?: { extraDraftKeys?: string[]; clearEditor?: boolean }) => void,
+ draftAttachments: Attachment[] = [],
+ ): Promise<boolean> => {
+ if (!activeAgent) {
+ apiLogger.warn("sendChatMessage skipped: no active agent");
+ return false;
+ }
+ // Read-only conversation: the agent is retired and can no longer pick up
+ // work, so refuse to enqueue a task that would sit orphaned forever. The
+ // input is disabled in this state; this is the belt-and-braces guard.
+ if (isAgentArchived) {
+ apiLogger.warn("sendChatMessage skipped: agent is archived", {
+ sessionId: activeSessionId,
+ agentId: activeAgent.id,
+ });
+ return false;
+ }
+
+ const finalContent = content;
+ const isNewSession = !activeSessionId;
+
+ apiLogger.info("sendChatMessage.start", {
+ sessionId: activeSessionId,
+ isNewSession,
+ agentId: activeAgent.id,
+ contentLength: finalContent.length,
+ attachmentCount: attachmentIds?.length ?? 0,
+ });
+
+ let sessionId: string | null = null;
+ try {
+ sessionId = await ensureSession(finalContent);
+ } catch (err) {
+ apiLogger.error("sendChatMessage.ensureSession.error", err);
+ toast.error(t(($) => $.input.send_failed_toast));
+ return false;
+ }
+ if (!sessionId) {
+ apiLogger.warn("sendChatMessage aborted: ensureSession returned null");
+ return false;
+ }
+
+ const sentAt = new Date().toISOString();
+ const optimistic: ChatMessage = {
+ id: `optimistic-${Date.now()}`,
+ chat_session_id: sessionId,
+ role: "user",
+ content: finalContent,
+ task_id: null,
+ created_at: sentAt,
+ attachments: draftAttachments,
+ };
+ appendChatMessageToLatestPageCache(qc, sessionId, optimistic);
+ qc.setQueryData<ChatMessage[]>(
+ chatKeys.messages(sessionId),
+ (old) => (old ? [...old, optimistic] : [optimistic]),
+ );
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {
+ task_id: `optimistic-${optimistic.id}`,
+ status: "queued",
+ created_at: sentAt,
+ });
+ const live = useChatStore.getState();
+ const stillOnSourceSession =
+ live.activeSessionId === activeSessionId &&
+ (activeSessionId !== null || live.selectedAgentId === selectedAgentId);
+ if (stillOnSourceSession) {
+ setActiveSession(sessionId);
+ }
+ commitInput?.({ extraDraftKeys: [sessionId], clearEditor: stillOnSourceSession });
+ apiLogger.debug("sendChatMessage.optimistic", { sessionId, optimisticId: optimistic.id });
+
+ let result;
+ try {
+ result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);
+ } catch (err) {
+ apiLogger.error("sendChatMessage.error.rollback", { sessionId, optimisticId: optimistic.id, err });
+ stopRequestedBeforeTaskRef.current = false;
+ removeChatMessageFromCaches(qc, sessionId, optimistic.id);
+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ setRestoreDraftRequest({
+ id: `send-failed-${optimistic.id}`,
+ content: finalContent,
+ attachments: draftAttachments,
+ sessionId,
+ });
+ toast.error(t(($) => $.input.send_failed_toast));
+ return false;
+ }
+ apiLogger.info("sendChatMessage.success", {
+ sessionId,
+ messageId: result.message_id,
+ taskId: result.task_id,
+ });
+ replaceOptimisticChatMessageId(qc, sessionId, optimistic.id, result.message_id, result.task_id);
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {
+ task_id: result.task_id,
+ status: "queued",
+ created_at: result.created_at,
+ });
+ if (stopRequestedBeforeTaskRef.current) {
+ stopRequestedBeforeTaskRef.current = false;
+ await cancelChatTask(result.task_id, sessionId, {
+ restoreDraftToInput: true,
+ source: "deferred-send",
+ });
+ return false;
+ }
+ if (attachmentIds && attachmentIds.length > 0 && result.attachment_ids) {
+ const boundIds = new Set(result.attachment_ids);
+ const missing = attachmentIds.filter((id) => !boundIds.has(id));
+ if (missing.length > 0) {
+ apiLogger.warn("sendChatMessage.attachments missing after send", {
+ sessionId,
+ messageId: result.message_id,
+ missing,
+ });
+ toast.error(t(($) => $.input.attachment_bind_failed_toast));
+ }
+ }
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
+ return true;
+ },
+ [
+ activeSessionId,
+ selectedAgentId,
+ activeAgent,
+ isAgentArchived,
+ ensureSession,
+ cancelChatTask,
+ qc,
+ setActiveSession,
+ t,
+ ],
+ );
+
+ const handleStop = useCallback(() => {
+ if (!pendingTaskId || !activeSessionId) {
+ apiLogger.debug("cancelTask skipped: no pending task");
+ return;
+ }
+ if (!isTaskMessageTaskId(pendingTaskId)) {
+ stopRequestedBeforeTaskRef.current = true;
+ apiLogger.info("cancelTask.deferred until server task id", {
+ taskId: pendingTaskId,
+ sessionId: activeSessionId,
+ });
+ return;
+ }
+ void cancelChatTask(pendingTaskId, activeSessionId, {
+ restoreDraftToInput: true,
+ source: "active-input",
+ });
+ }, [pendingTaskId, activeSessionId, cancelChatTask]);
+
+ const handleNewChat = useCallback(() => {
+ uiLogger.info("newChat", {
+ previousSessionId: activeSessionId,
+ previousPendingTask: pendingTaskId,
+ });
+ setActiveSession(null);
+ }, [activeSessionId, pendingTaskId, setActiveSession]);
+
+ // Start a fresh chat bound to a chosen agent. Unlike handleSelectAgent this
+ // does not no-op when the agent is unchanged — "new chat" always clears the
+ // active session so the user lands on an empty compose for that agent. The
+ // session row is created lazily on the first send (see ensureSession).
+ const handleStartNewChat = useCallback(
+ (agent: Agent) => {
+ uiLogger.info("startNewChat", {
+ agentId: agent.id,
+ previousSessionId: activeSessionId,
+ });
+ setSelectedAgentId(agent.id);
+ setActiveSession(null);
+ },
+ [activeSessionId, setSelectedAgentId, setActiveSession],
+ );
+
+ const handleSelectSession = useCallback(
+ (session: { id: string; agent_id: string }) => {
+ // Sessions are bound 1:1 to an agent — picking a session from a
+ // different agent implicitly switches the agent too.
+ if (activeAgent && session.agent_id !== activeAgent.id) {
+ uiLogger.info("selectSession (cross-agent)", {
+ from: activeAgent.id,
+ toAgent: session.agent_id,
+ toSession: session.id,
+ });
+ setSelectedAgentId(session.agent_id);
+ }
+ setActiveSession(session.id);
+ },
+ [activeAgent, setSelectedAgentId, setActiveSession],
+ );
+
+ const hasMessages = messages.length > 0 || !!pendingTaskId;
+
+ return {
+ // identity / lists
+ wsId,
+ user,
+ agents,
+ availableAgents,
+ sessions,
+ activeSessionId,
+ selectedAgentId,
+ currentSession,
+ isSessionArchived,
+ isAgentArchived,
+ activeAgent,
+ noAgent,
+ availability,
+ // messages
+ messages,
+ pendingTask,
+ pendingTaskId,
+ showSkeleton,
+ hasMessages,
+ firstItemIndex,
+ hasOlderMessages: !!hasOlderMessages,
+ isFetchingOlderMessages,
+ fetchOlderMessages,
+ // draft restore
+ restoreDraftRequest,
+ handleRestoreDraftConsumed,
+ // actions
+ handleSend,
+ handleStop,
+ handleUploadFile,
+ handleNewChat,
+ handleStartNewChat,
+ handleSelectSession,
+ // store setters (for surfaces that sync selection to the URL, etc.)
+ setActiveSession,
+ setSelectedAgentId,
+ };
+}
+
+export type ChatController = ReturnType<typeof useChatController>;
diff --git a/packages/views/chat/floating-chat.tsx b/packages/views/chat/floating-chat.tsx
new file mode 100644
index 0000000000..4152ad6c15
--- /dev/null
+++ b/packages/views/chat/floating-chat.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { useChatStore } from "@multica/core/chat";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { useNavigation } from "../navigation";
+import { ChatFab } from "./components/chat-fab";
+import { ChatWindow } from "./components/chat-window";
+
+/**
+ * Mount point for the floating chat overlay (FAB + window). Rendered once in
+ * each app shell's dashboard layout; owns the two gates that decide whether the
+ * overlay exists at all:
+ *
+ * 1. The Settings → Chat preference (`floatingChatEnabled`). When a user turns
+ * the floating window off, Chat lives only in its dedicated tab.
+ * 2. The Chat tab route itself. On `/:slug/chat` the full-page surface already
+ * owns the conversation, so a floating copy of the same `activeSessionId`
+ * would be pure duplication — hide it there.
+ */
+export function FloatingChat() {
+ const enabled = useChatStore((s) => s.floatingChatEnabled);
+ const { pathname } = useNavigation();
+ const wsPaths = useWorkspacePaths();
+
+ if (!enabled) return null;
+ // Suppress on the Chat tab — it renders the same conversation full-page.
+ if (pathname === wsPaths.chat() || pathname.startsWith(`${wsPaths.chat()}/`)) {
+ return null;
+ }
+
+ return (
+ <>
+ <ChatWindow />
+ <ChatFab />
+ </>
+ );
+}
diff --git a/packages/views/chat/index.ts b/packages/views/chat/index.ts
index 04295ff1f8..b9a26479d8 100644
--- a/packages/views/chat/index.ts
+++ b/packages/views/chat/index.ts
@@ -1,2 +1,2 @@
-export { ChatFab } from "./components/chat-fab";
-export { ChatWindow } from "./components/chat-window";
+export { ChatPage } from "./chat-page";
+export { FloatingChat } from "./floating-chat";
diff --git a/packages/views/editor/utils/link-handler.ts b/packages/views/editor/utils/link-handler.ts
index 4f4e580283..743ab284dc 100644
--- a/packages/views/editor/utils/link-handler.ts
+++ b/packages/views/editor/utils/link-handler.ts
@@ -24,6 +24,7 @@ const WORKSPACE_ROUTE_SEGMENTS = new Set([
"projects",
"autopilots",
"agents",
+ "chat",
"inbox",
"my-issues",
"runtimes",
diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsx
index f331ddc2c8..ffdd48639c 100644
--- a/packages/views/inbox/components/inbox-list-item.tsx
+++ b/packages/views/inbox/components/inbox-list-item.tsx
@@ -44,7 +44,7 @@ export function InboxListItem({
<button
type="button"
onClick={onClick}
- className={`group flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${
+ className={`group flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-left transition-colors ${
isSelected ? "bg-accent" : "hover:bg-accent/50"
}`}
>
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 8d7aa5573d..a4a64aa538 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -223,7 +223,7 @@ export function InboxPage() {
// -- Shared sub-components --------------------------------------------------
const listHeader = (
- <PageHeader className="justify-between">
+ <PageHeader className="justify-between border-b-0">
<div className="flex items-center gap-2">
<h1 className="text-sm font-semibold">{t(($) => $.page.title)}</h1>
{unreadCount > 0 && (
@@ -273,7 +273,7 @@ export function InboxPage() {
<p className="text-sm">{t(($) => $.list.empty)}</p>
</div>
) : (
- <div>
+ <div className="p-1">
{items.map((item) => (
<InboxListItem
key={item.id}
diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsx
index 76836e2563..f7687f51a6 100644
--- a/packages/views/layout/app-sidebar.test.tsx
+++ b/packages/views/layout/app-sidebar.test.tsx
@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "@multica/core/api";
import { AppSidebar } from "./app-sidebar";
-const { detail, deletePin, navigation, pins, summary, workspaces } = vi.hoisted(() => ({
+const { chatSessions, detail, deletePin, navigation, pins, summary, workspaces } = vi.hoisted(() => ({
+ chatSessions: { current: [] as { unread_count?: number }[] },
detail: { current: { isPending: false, isError: false, data: null as unknown, error: null as unknown } },
deletePin: vi.fn(),
navigation: { current: { pathname: "/acme/issues" } },
@@ -102,6 +103,7 @@ vi.mock("@multica/core/paths", () => ({
useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme", slug: "acme" }),
useWorkspacePaths: () => ({
inbox: () => "/acme/inbox",
+ chat: () => "/acme/chat",
myIssues: () => "/acme/my-issues",
issues: () => "/acme/issues",
projects: () => "/acme/projects",
@@ -161,6 +163,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({
if (queryKey[0] === "issue") return detail.current;
if (queryKey[0] === "inbox" && queryKey[1] === "unread-summary") return { data: summary.current };
if (queryKey[0] === "workspaces") return { data: workspaces.current };
+ if (queryKey[0] === "chat" && queryKey[2] === "sessions") return { data: chatSessions.current };
return { data: [] };
},
useQueryClient: () => ({ fetchQuery: vi.fn(), invalidateQueries: vi.fn() }),
@@ -279,3 +282,32 @@ describe("workspace-switcher dropdown per-workspace dot", () => {
expect(rowDots(container)).toHaveLength(0);
});
});
+
+describe("personal nav — Chat", () => {
+ beforeEach(() => {
+ chatSessions.current = [];
+ navigation.current = { pathname: "/acme/issues" };
+ });
+
+ // The mocked SidebarMenuButton exposes the AppLink target as `data-href`
+ // and renders the label + badge as its children.
+ const chatNav = (container: HTMLElement) =>
+ container.querySelector<HTMLElement>('button[data-href="/acme/chat"]');
+
+ it("renders a Chat nav link to the workspace chat route", () => {
+ const { container } = render(<AppSidebar />);
+ expect(chatNav(container)).not.toBeNull();
+ });
+
+ it("badges the Chat nav with the summed unread_count of chat sessions", () => {
+ chatSessions.current = [{ unread_count: 3 }, { unread_count: 2 }, { unread_count: 0 }];
+ const { container } = render(<AppSidebar />);
+ expect(chatNav(container)?.textContent).toContain("5");
+ });
+
+ it("shows no Chat unread badge when every session is read", () => {
+ chatSessions.current = [{ unread_count: 0 }, {}];
+ const { container } = render(<AppSidebar />);
+ expect(chatNav(container)?.textContent ?? "").not.toMatch(/\d/);
+ });
+});
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index 6953a99d90..000135466b 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -18,6 +18,7 @@ import { SortableContext, verticalListSortingStrategy, useSortable, arrayMove }
import { CSS } from "@dnd-kit/utilities";
import {
Inbox,
+ MessageSquare,
ListTodo,
Bot,
Monitor,
@@ -71,6 +72,7 @@ import { workspaceListOptions, myInvitationListOptions, workspaceKeys } from "@m
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { inboxKeys, deduplicateInboxItems, inboxUnreadSummaryOptions, hasOtherWorkspaceUnread, unreadWorkspaceIds } from "@multica/core/inbox/queries";
+import { chatSessionsOptions } from "@multica/core/chat/queries";
import { api, ApiError } from "@multica/core/api";
import { useModalStore } from "@multica/core/modals";
import { useConfigStore } from "@multica/core/config";
@@ -108,6 +110,7 @@ const EMPTY_INBOX_SUMMARY: Awaited<ReturnType<typeof api.getInboxUnreadSummary>>
// Only parameterless paths are valid nav destinations.
type NavKey =
| "inbox"
+ | "chat"
| "myIssues"
| "issues"
| "projects"
@@ -122,6 +125,7 @@ type NavKey =
// Static schema (key + icon) — labels resolved at render via useT("layout").
type NavLabelKey =
| "inbox"
+ | "chat"
| "my_issues"
| "issues"
| "projects"
@@ -135,6 +139,7 @@ type NavLabelKey =
const personalNav: { key: NavKey; labelKey: NavLabelKey; icon: typeof Inbox }[] = [
{ key: "inbox", labelKey: "inbox", icon: Inbox },
+ { key: "chat", labelKey: "chat", icon: MessageSquare },
{ key: "myIssues", labelKey: "my_issues", icon: CircleUser },
];
@@ -365,6 +370,16 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
() => deduplicateInboxItems(inboxItems).filter((i) => !i.read).length,
[inboxItems],
);
+ // Chat tab unread badge: number of chat threads with a fresh reply.
+ const { data: chatSessions = [] } = useQuery({
+ ...chatSessionsOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ // IM-style: total unread *messages* across all chat threads (not thread count).
+ const chatUnreadCount = React.useMemo(
+ () => chatSessions.reduce((sum, s) => sum + (s.unread_count ?? 0), 0),
+ [chatSessions],
+ );
// Cross-workspace unread summary backs the workspace-switcher dot. One
// shared cache entry across workspaces; gated on an active workspace since
// the endpoint resolves through the workspace-member middleware.
@@ -669,6 +684,11 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
{unreadCount > 99 ? "99+" : unreadCount}
</span>
)}
+ {item.key === "chat" && chatUnreadCount > 0 && (
+ <span className="ml-auto text-xs">
+ {chatUnreadCount > 99 ? "99+" : chatUnreadCount}
+ </span>
+ )}
</SidebarMenuButton>
</SidebarMenuItem>
);
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index d6afaf1246..1f33e867be 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -1,4 +1,8 @@
{
+ "page": {
+ "title": "Chat",
+ "select_prompt": "Pick a conversation, or start a new one with +"
+ },
"fab": {
"running": "Multica is working...",
"unread_one": "{{count}} unread chat",
@@ -8,12 +12,15 @@
"input": {
"placeholder_no_agent": "Create an agent to start chatting",
"placeholder_archived": "This session is archived",
+ "placeholder_archived_agent": "This agent has been archived",
"placeholder_named": "Message {{name}}…",
"placeholder_default": "Start a message…",
"send_tooltip": "Send",
"stop_tooltip": "Stop",
"send_failed_toast": "Failed to send message",
- "attachment_bind_failed_toast": "Message sent, but files were not attached. Please try again in a moment."
+ "attachment_bind_failed_toast": "Message sent, but files were not attached. Please try again in a moment.",
+ "add_tooltip": "Add",
+ "upload_file": "Image or files"
},
"message_list": {
"show_details": "Show details",
@@ -98,7 +105,8 @@
"first_time_actions": "Ask for a summary, plan your day, or hand off a quick task.",
"returning_title_named": "Hi, I'm {{name}}",
"returning_title_default": "Welcome to Multica",
- "returning_subtitle": "Try asking"
+ "returning_subtitle": "Try asking",
+ "chat_with_named": "Chat with {{name}}"
},
"starter_prompts": {
"list_open": "List my open tasks by priority",
@@ -106,6 +114,7 @@
"plan_next": "Plan what to work on next"
},
"no_agent_banner": "You need an agent to start chatting.",
+ "archived_agent_banner": "{{name}} has been archived — this conversation is read-only.",
"offline_banner": {
"fallback_name": "the agent",
"unstable": "{{name}}'s connection is unstable — replies may be delayed.",
@@ -129,5 +138,29 @@
"searching_web": "Searching the web",
"fallback": "Working"
}
+ },
+ "list": {
+ "typing": "Typing…",
+ "failed": "Failed to send",
+ "you_prefix": "You: ",
+ "no_messages": "No messages yet",
+ "quick_agents": "Frequent agents",
+ "add": "Add",
+ "add_agent": "Add a frequent agent",
+ "unpin_agent": "Remove from frequent",
+ "waiting": "Waiting for reply",
+ "pin": "Pin",
+ "unpin": "Unpin",
+ "pinned": "Pinned",
+ "archive": "Archive",
+ "unarchive": "Unarchive",
+ "archived_title": "Archived"
+ },
+ "header": {
+ "view_profile": "View agent profile",
+ "rename": "Rename chat",
+ "archive": "Archive chat",
+ "unarchive": "Unarchive chat",
+ "delete": "Delete chat"
}
}
diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.json
index 52917c162e..b874fa9eea 100644
--- a/packages/views/locales/en/layout.json
+++ b/packages/views/locales/en/layout.json
@@ -1,6 +1,7 @@
{
"nav": {
"inbox": "Inbox",
+ "chat": "Chat",
"my_issues": "My Issues",
"issues": "Issues",
"projects": "Projects",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 1b18ba2a4f..44c5ea465f 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -21,6 +21,11 @@
"sync_failed": "Failed to save your timezone preference."
}
},
+ "chat": {
+ "floating_title": "Floating window",
+ "floating_label": "Floating chat window",
+ "floating_hint": "Show the floating chat button in the corner of every page. Off by default — turn it on to summon chat anywhere; when off, Chat lives only in this tab."
+ },
"page": {
"title": "Settings",
"my_account": "My Account",
@@ -28,6 +33,7 @@
"tabs": {
"profile": "Profile",
"preferences": "Preferences",
+ "chat": "Chat",
"notifications": "Notifications",
"tokens": "API Tokens",
"general": "General",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index c739925de7..2416100154 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -1,4 +1,8 @@
{
+ "page": {
+ "title": "チャット",
+ "select_prompt": "会話を選ぶか、+ で新規作成してください"
+ },
"fab": {
"running": "Multica が作業中です...",
"unread_other": "未読のチャット {{count}}件",
@@ -7,12 +11,15 @@
"input": {
"placeholder_no_agent": "チャットを始めるにはエージェントを作成してください",
"placeholder_archived": "このセッションはアーカイブされています",
+ "placeholder_archived_agent": "このエージェントはアーカイブされています",
"placeholder_named": "{{name}} にメッセージ…",
"placeholder_default": "メッセージを入力…",
"send_tooltip": "送信",
"stop_tooltip": "停止",
"send_failed_toast": "メッセージを送信できませんでした",
- "attachment_bind_failed_toast": "メッセージは送信されましたが、ファイルを添付できませんでした。しばらくしてからもう一度お試しください。"
+ "attachment_bind_failed_toast": "メッセージは送信されましたが、ファイルを添付できませんでした。しばらくしてからもう一度お試しください。",
+ "add_tooltip": "追加",
+ "upload_file": "画像・ファイル"
},
"message_list": {
"show_details": "詳細を表示",
@@ -95,7 +102,8 @@
"first_time_actions": "要約を頼んだり、今日の予定を立てたり、簡単なタスクを任せたりしてみましょう。",
"returning_title_named": "こんにちは、{{name}} です",
"returning_title_default": "Multica へようこそ",
- "returning_subtitle": "こう聞いてみましょう"
+ "returning_subtitle": "こう聞いてみましょう",
+ "chat_with_named": "{{name}} とチャット"
},
"starter_prompts": {
"list_open": "オープンなタスクを優先度順にまとめて",
@@ -103,6 +111,7 @@
"plan_next": "次に取り組むことを計画して"
},
"no_agent_banner": "チャットを始めるにはエージェントが必要です。",
+ "archived_agent_banner": "{{name}} はアーカイブされました。この会話は読み取り専用です。",
"offline_banner": {
"fallback_name": "エージェント",
"unstable": "{{name}} の接続が不安定です。返信が遅れる場合があります。",
@@ -126,5 +135,29 @@
"searching_web": "ウェブを検索中",
"fallback": "作業中"
}
+ },
+ "list": {
+ "typing": "入力中…",
+ "failed": "送信失敗",
+ "you_prefix": "あなた:",
+ "no_messages": "メッセージはまだありません",
+ "quick_agents": "よく使う Agent",
+ "add": "追加",
+ "add_agent": "よく使う Agent を追加",
+ "unpin_agent": "よく使うから外す",
+ "waiting": "返信待ち",
+ "pin": "ピン留め",
+ "unpin": "ピン留めを解除",
+ "pinned": "ピン留め済み",
+ "archive": "アーカイブ",
+ "unarchive": "アーカイブ解除",
+ "archived_title": "アーカイブ済み"
+ },
+ "header": {
+ "view_profile": "Agent のプロフィール",
+ "rename": "名前を変更",
+ "delete": "チャットを削除",
+ "archive": "チャットをアーカイブ",
+ "unarchive": "アーカイブを解除"
}
}
diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.json
index 76e85bc0fb..0a9ac5b775 100644
--- a/packages/views/locales/ja/layout.json
+++ b/packages/views/locales/ja/layout.json
@@ -1,6 +1,7 @@
{
"nav": {
"inbox": "インボックス",
+ "chat": "チャット",
"my_issues": "マイイシュー",
"issues": "イシュー",
"projects": "プロジェクト",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 12f7092aae..6cc843beec 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -21,6 +21,11 @@
"sync_failed": "タイムゾーン設定を保存できませんでした。"
}
},
+ "chat": {
+ "floating_title": "フローティングウィンドウ",
+ "floating_label": "フローティングチャット",
+ "floating_hint": "すべてのページの隅にフローティングチャットボタンを表示します。デフォルトはオフ——オンにするとどこからでもチャットを呼び出せます。オフのときは専用タブでのみ利用できます。"
+ },
"page": {
"title": "設定",
"my_account": "マイアカウント",
@@ -28,6 +33,7 @@
"tabs": {
"profile": "プロフィール",
"preferences": "環境設定",
+ "chat": "チャット",
"notifications": "通知",
"tokens": "API トークン",
"general": "一般",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index c6bd9cb881..e251e32948 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -1,4 +1,8 @@
{
+ "page": {
+ "title": "채팅",
+ "select_prompt": "대화를 선택하거나 +로 새로 시작하세요"
+ },
"fab": {
"running": "Multica가 작업 중입니다...",
"unread_other": "읽지 않은 채팅 {{count}}개",
@@ -7,12 +11,15 @@
"input": {
"placeholder_no_agent": "채팅을 시작하려면 에이전트를 만드세요",
"placeholder_archived": "보관된 세션입니다",
+ "placeholder_archived_agent": "보관된 에이전트입니다",
"placeholder_named": "{{name}}에게 메시지 보내기…",
"placeholder_default": "메시지 입력…",
"send_tooltip": "보내기",
"stop_tooltip": "중지",
"send_failed_toast": "메시지를 보내지 못했습니다",
- "attachment_bind_failed_toast": "메시지는 보냈지만 파일이 첨부되지 않았습니다. 잠시 후 다시 시도해 주세요."
+ "attachment_bind_failed_toast": "메시지는 보냈지만 파일이 첨부되지 않았습니다. 잠시 후 다시 시도해 주세요.",
+ "add_tooltip": "추가",
+ "upload_file": "이미지 또는 파일"
},
"message_list": {
"show_details": "세부 정보 보기",
@@ -95,7 +102,8 @@
"first_time_actions": "요약을 요청하거나, 오늘 할 일을 계획하거나, 간단한 작업을 맡겨보세요.",
"returning_title_named": "안녕하세요, 저는 {{name}}입니다",
"returning_title_default": "Multica에 오신 것을 환영합니다",
- "returning_subtitle": "이렇게 요청해 보세요"
+ "returning_subtitle": "이렇게 요청해 보세요",
+ "chat_with_named": "{{name}}와 채팅"
},
"starter_prompts": {
"list_open": "열린 작업을 우선순위별로 정리해 줘",
@@ -103,6 +111,7 @@
"plan_next": "다음에 할 일을 계획해 줘"
},
"no_agent_banner": "채팅을 시작하려면 에이전트가 필요합니다.",
+ "archived_agent_banner": "{{name}}은(는) 보관되었습니다. 이 대화는 읽기 전용입니다.",
"offline_banner": {
"fallback_name": "에이전트",
"unstable": "{{name}}의 연결이 불안정합니다. 답변이 지연될 수 있습니다.",
@@ -126,5 +135,29 @@
"searching_web": "웹 검색 중",
"fallback": "작업 중"
}
+ },
+ "list": {
+ "typing": "입력 중…",
+ "failed": "전송 실패",
+ "you_prefix": "나: ",
+ "no_messages": "아직 메시지가 없습니다",
+ "quick_agents": "자주 쓰는 Agent",
+ "add": "추가",
+ "add_agent": "자주 쓰는 Agent 추가",
+ "unpin_agent": "자주 쓰기에서 제거",
+ "waiting": "답장 대기 중",
+ "pin": "고정",
+ "unpin": "고정 해제",
+ "pinned": "고정됨",
+ "archive": "보관",
+ "unarchive": "보관 해제",
+ "archived_title": "보관됨"
+ },
+ "header": {
+ "view_profile": "Agent 프로필 보기",
+ "rename": "이름 변경",
+ "delete": "채팅 삭제",
+ "archive": "채팅 보관",
+ "unarchive": "채팅 보관 해제"
}
}
diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.json
index 83b5c66ab0..2557c9917b 100644
--- a/packages/views/locales/ko/layout.json
+++ b/packages/views/locales/ko/layout.json
@@ -1,6 +1,7 @@
{
"nav": {
"inbox": "인박스",
+ "chat": "채팅",
"my_issues": "내 이슈",
"issues": "이슈",
"projects": "프로젝트",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 596168e954..5716e500b7 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -21,6 +21,11 @@
"sync_failed": "시간대 설정을 저장하지 못했습니다."
}
},
+ "chat": {
+ "floating_title": "플로팅 창",
+ "floating_label": "플로팅 채팅 창",
+ "floating_hint": "모든 페이지 모서리에 플로팅 채팅 버튼을 표시합니다. 기본값은 꺼짐 — 켜면 어디서나 채팅을 불러올 수 있고, 꺼면 채팅은 이 탭에서만 사용할 수 있습니다."
+ },
"page": {
"title": "설정",
"my_account": "내 계정",
@@ -28,6 +33,7 @@
"tabs": {
"profile": "프로필",
"preferences": "환경설정",
+ "chat": "채팅",
"notifications": "알림",
"tokens": "API 토큰",
"general": "일반",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index a983049a67..df8fd47a95 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -1,4 +1,8 @@
{
+ "page": {
+ "title": "Chat",
+ "select_prompt": "选择一个对话,或点 + 新建"
+ },
"fab": {
"running": "Multica 正在工作...",
"unread_other": "{{count}} 条未读对话",
@@ -7,12 +11,15 @@
"input": {
"placeholder_no_agent": "创建一个智能体后才能开始对话",
"placeholder_archived": "此会话已归档",
+ "placeholder_archived_agent": "该智能体已归档",
"placeholder_named": "给 {{name}} 发消息…",
"placeholder_default": "输入消息…",
"send_tooltip": "发送",
"stop_tooltip": "停止",
"send_failed_toast": "发送消息失败",
- "attachment_bind_failed_toast": "消息已发送,但文件未能附加。请稍后重试。"
+ "attachment_bind_failed_toast": "消息已发送,但文件未能附加。请稍后重试。",
+ "add_tooltip": "添加",
+ "upload_file": "图片或文件"
},
"message_list": {
"show_details": "查看详情",
@@ -95,7 +102,8 @@
"first_time_actions": "让它做一份总结、规划你的一天,或交给它一个小任务。",
"returning_title_named": "你好,我是 {{name}}",
"returning_title_default": "欢迎使用 Multica",
- "returning_subtitle": "试试问"
+ "returning_subtitle": "试试问",
+ "chat_with_named": "与 {{name}} 对话"
},
"starter_prompts": {
"list_open": "按优先级列出我未完成的任务",
@@ -103,6 +111,7 @@
"plan_next": "规划接下来该做什么"
},
"no_agent_banner": "需要先有一个智能体才能开始对话。",
+ "archived_agent_banner": "{{name}} 已归档——此会话为只读。",
"offline_banner": {
"fallback_name": "智能体",
"unstable": "{{name}} 的连接不稳定——回复可能延迟。",
@@ -126,5 +135,29 @@
"searching_web": "搜索网页",
"fallback": "处理中"
}
+ },
+ "list": {
+ "typing": "正在输入…",
+ "failed": "发送失败",
+ "you_prefix": "你:",
+ "no_messages": "还没有消息",
+ "quick_agents": "常用 Agent",
+ "add": "添加",
+ "add_agent": "添加常用 Agent",
+ "unpin_agent": "移出常用",
+ "waiting": "等待回复",
+ "pin": "置顶",
+ "unpin": "取消置顶",
+ "pinned": "已置顶",
+ "archive": "归档",
+ "unarchive": "取消归档",
+ "archived_title": "已归档"
+ },
+ "header": {
+ "view_profile": "查看 Agent 资料",
+ "rename": "重命名会话",
+ "delete": "删除会话",
+ "archive": "归档会话",
+ "unarchive": "取消归档"
}
}
diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.json
index 1f41d69c86..547b7e040b 100644
--- a/packages/views/locales/zh-Hans/layout.json
+++ b/packages/views/locales/zh-Hans/layout.json
@@ -1,6 +1,7 @@
{
"nav": {
"inbox": "收件箱",
+ "chat": "Chat",
"my_issues": "我的 issue",
"issues": "Issues",
"projects": "项目",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index e9d8324f0c..5d18728f2b 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -21,6 +21,11 @@
"sync_failed": "保存时区偏好失败。"
}
},
+ "chat": {
+ "floating_title": "悬浮窗",
+ "floating_label": "悬浮聊天窗",
+ "floating_hint": "在每个页面右下角显示悬浮聊天按钮。默认关闭——打开后可随处召唤聊天;关闭时,聊天只在此标签页中可用。"
+ },
"page": {
"title": "设置",
"my_account": "我的账号",
@@ -28,6 +33,7 @@
"tabs": {
"profile": "个人资料",
"preferences": "偏好设置",
+ "chat": "聊天",
"notifications": "通知",
"tokens": "API Token",
"general": "通用",
diff --git a/packages/views/settings/components/chat-tab.tsx b/packages/views/settings/components/chat-tab.tsx
new file mode 100644
index 0000000000..803585d398
--- /dev/null
+++ b/packages/views/settings/components/chat-tab.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { Switch } from "@multica/ui/components/ui/switch";
+import { useChatStore } from "@multica/core/chat";
+import { useT } from "../../i18n";
+
+/**
+ * Chat settings — its own tab under "My Account". Currently just the
+ * floating-window toggle: when off (the default), the FAB / overlay never
+ * mount and Chat is reachable only from its dedicated tab. The preference is
+ * a persisted client setting (`floatingChatEnabled`), so it applies
+ * immediately without a round-trip.
+ */
+export function ChatTab() {
+ const { t } = useT("settings");
+ const enabled = useChatStore((s) => s.floatingChatEnabled);
+ const setEnabled = useChatStore((s) => s.setFloatingChatEnabled);
+
+ return (
+ <div className="space-y-8">
+ <section className="space-y-4">
+ <h2 className="text-sm font-semibold">{t(($) => $.chat.floating_title)}</h2>
+ <label className="flex items-center justify-between gap-4">
+ <div className="space-y-0.5 pr-4">
+ <p className="text-sm font-medium">{t(($) => $.chat.floating_label)}</p>
+ <p className="text-xs text-muted-foreground">
+ {t(($) => $.chat.floating_hint)}
+ </p>
+ </div>
+ <Switch checked={enabled} onCheckedChange={setEnabled} />
+ </label>
+ </section>
+ </div>
+ );
+}
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index 5dc317519f..413c3eb36d 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -11,6 +11,7 @@ import {
FlaskConical,
Bell,
Plug,
+ MessageCircle,
} from "lucide-react";
import { GitHubMark } from "./github-mark";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";
@@ -18,6 +19,7 @@ import { useCurrentWorkspace } from "@multica/core/paths";
import { useNavigation } from "../../navigation";
import { AccountTab } from "./account-tab";
import { PreferencesTab } from "./preferences-tab";
+import { ChatTab } from "./chat-tab";
import { TokensTab } from "./tokens-tab";
import { WorkspaceTab } from "./workspace-tab";
import { MembersTab } from "./members-tab";
@@ -28,10 +30,11 @@ import { LabsTab } from "./labs-tab";
import { NotificationsTab } from "./notifications-tab";
import { useT } from "../../i18n";
-const ACCOUNT_TAB_KEYS = ["profile", "preferences", "notifications", "tokens"] as const;
+const ACCOUNT_TAB_KEYS = ["profile", "preferences", "chat", "notifications", "tokens"] as const;
const ACCOUNT_TAB_ICONS = {
profile: User,
preferences: SlidersHorizontal,
+ chat: MessageCircle,
notifications: Bell,
tokens: Key,
} as const;
@@ -169,6 +172,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
<div className="w-full max-w-3xl mx-auto p-4 md:p-6">
<TabsContent value="profile"><AccountTab /></TabsContent>
<TabsContent value="preferences"><PreferencesTab /></TabsContent>
+ <TabsContent value="chat"><ChatTab /></TabsContent>
<TabsContent value="notifications"><NotificationsTab /></TabsContent>
<TabsContent value="tokens"><TokensTab /></TabsContent>
<TabsContent value="workspace"><WorkspaceTab /></TabsContent>
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 20a78292a6..7a45ba5354 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1244,6 +1244,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/{sessionId}", func(r chi.Router) {
r.Get("/", h.GetChatSession)
r.Patch("/", h.UpdateChatSession)
+ r.Patch("/pin", h.SetChatSessionPinned)
+ r.Patch("/archive", h.SetChatSessionArchived)
r.Delete("/", h.DeleteChatSession)
r.Post("/messages", h.SendChatMessage)
r.Get("/messages", h.ListChatMessages)
@@ -1255,6 +1257,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/api/chat/pending-tasks", h.ListPendingChatTasks)
r.Get("/api/chat/pending-tasks/has-any", h.HasPendingChatTasks)
+ // Quick-agent bar: per-user pinned agents for one-tap new chats.
+ r.Get("/api/chat/pinned-agents", h.ListChatPinnedAgents)
+ r.Post("/api/chat/pinned-agents", h.PinChatAgent)
+ r.Delete("/api/chat/pinned-agents/{agentId}", h.UnpinChatAgent)
+
// Agent-facing channel reads (MUL-3871). The caller's task-scoped token
// resolves to its own chat session; no session/channel id is passed, so
// an agent can only read its own conversation. `history` is the channel
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index ddca45e9f1..9d469cfba9 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -187,6 +187,17 @@ func buildCommentPrompt(task Task, provider string) string {
// buildChatPrompt constructs a prompt for interactive chat tasks.
func buildChatPrompt(task Task) string {
+ // Proactive self-introduction: the agent was just created and is opening the
+ // conversation. There is no user message to reply to — the agent sends the
+ // first message so the thread reads as the agent messaging its creator, not
+ // the creator prompting the agent (MUL-4230).
+ if task.ChatIntro {
+ var b strings.Builder
+ b.WriteString("You are running as a chat assistant for a Multica workspace.\n")
+ b.WriteString("You were just created, and this is the very first message in a direct chat with the person who created you. They have not written anything yet — you are opening the conversation. Send a short, warm, first-person introduction: who you are, what you're good at, and how they can work with you. Do NOT phrase it as an answer to a question or repeat any prompt back; just introduce yourself as if you reached out first.\n")
+ return b.String()
+ }
+
var b strings.Builder
b.WriteString("You are running as a chat assistant for a Multica workspace.\n")
b.WriteString("A user is chatting with you directly. Respond to their message.\n\n")
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index eca45cb298..8117821d39 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -309,6 +309,28 @@ func TestBuildChatPromptChannelAwareness(t *testing.T) {
})
}
+func TestBuildChatPromptAgentIntro(t *testing.T) {
+ // The proactive self-introduction chat (MUL-4230) has no user message: the
+ // prompt must tell the agent to open the conversation itself, and must NOT
+ // carry the generic "respond to their message" framing or an empty
+ // "User message:" section that would confuse the agent.
+ out := buildChatPrompt(Task{ChatSessionID: "sess-1", ChatIntro: true})
+ for _, want := range []string{
+ "You were just created",
+ "you are opening the conversation",
+ "introduce yourself",
+ } {
+ if !strings.Contains(out, want) {
+ t.Fatalf("intro prompt missing %q\n--- output ---\n%s", want, out)
+ }
+ }
+ for _, unwanted := range []string{"Respond to their message", "User message:"} {
+ if strings.Contains(out, unwanted) {
+ t.Fatalf("intro prompt should not contain %q\n--- output ---\n%s", unwanted, out)
+ }
+ }
+}
+
func TestBuildChatPromptSlashSkills(t *testing.T) {
t.Run("injects selected skills block", func(t *testing.T) {
task := Task{
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 718eb9b7f2..4168b6de2c 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -82,6 +82,7 @@ type Task struct {
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; selects which read command the prompt tells the agent to start with
ChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments linked to the chat message; agent uses these to `multica attachment download <id>`
+ ChatIntro bool `json:"chat_intro,omitempty"` // true for the agent's proactive self-introduction chat (no user message); selects the self-introduction prompt in buildChatPrompt
AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot run_only tasks
AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this run
AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 4df659e7ba..f0362de491 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -322,6 +322,7 @@ type AgentTaskResponse struct {
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`
ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry
+ ChatIntro bool `json:"chat_intro,omitempty"` // true for the agent's proactive self-introduction chat (is_agent_intro session, no user message); the daemon builds an intro prompt instead of a reply prompt
AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks
AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task
AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context
@@ -977,6 +978,10 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
actorType, actorID := h.resolveActor(r, ownerID, workspaceID)
h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})
+ // Kick off a "meet your new agent" chat so the agent introduces itself
+ // (LLM-generated via a real run, not a canned template). Best effort.
+ h.sendAgentWelcomeChat(r.Context(), created, ownerID, workspaceID)
+
obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(
ownerID,
workspaceID,
@@ -994,6 +999,36 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, resp)
}
+// sendAgentWelcomeChat creates a "meet your new agent" chat: a session owned by
+// the agent's creator, flagged is_agent_intro, then enqueues a real agent run so
+// the agent introduces itself — the intro is LLM-generated by the agent, not a
+// static template. No user message is persisted: the intro run is driven
+// server-side (the daemon builds a self-introduction prompt for is_agent_intro
+// sessions, see buildChatPrompt) so the thread reads as the agent proactively
+// messaging its creator, not the creator prompting the agent (MUL-4230). Best
+// effort: any failure is logged and never blocks the (already-committed) agent
+// creation.
+func (h *Handler) sendAgentWelcomeChat(ctx context.Context, agent db.Agent, creatorID, workspaceID string) {
+ if !agent.RuntimeID.Valid {
+ return // no runtime → the agent can't run; skip the welcome
+ }
+ session, err := h.Queries.CreateChatSession(ctx, db.CreateChatSessionParams{
+ WorkspaceID: parseUUID(workspaceID),
+ AgentID: agent.ID,
+ CreatorID: parseUUID(creatorID),
+ Title: "👋 " + agent.Name,
+ IsAgentIntro: true,
+ })
+ if err != nil {
+ slog.Warn("agent welcome: create session failed", "agent_id", uuidToString(agent.ID), "error", err)
+ return
+ }
+
+ if _, err := h.TaskService.EnqueueChatTask(ctx, session, parseUUID(creatorID), false); err != nil {
+ slog.Warn("agent welcome: enqueue task failed", "chat_session_id", uuidToString(session.ID), "error", err)
+ }
+}
+
type UpdateAgentRequest struct {
Name *string `json:"name"`
Description *string `json:"description"`
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index b53747a075..079049ce2a 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -144,7 +144,10 @@ func (h *Handler) ListChatSessions(w http.ResponseWriter, r *http.Request) {
CreatorID: uuidToString(s.CreatorID),
Title: s.Title,
Status: s.Status,
- HasUnread: s.HasUnread,
+ HasUnread: s.UnreadCount > 0,
+ UnreadCount: int(s.UnreadCount),
+ LastMessage: buildChatLastMessage(s.LastMessageAt, s.LastMessageContent, s.LastMessageRole, s.LastMessageFailureReason),
+ Pinned: s.PinnedAt.Valid,
CreatedAt: timestampToString(s.CreatedAt),
UpdatedAt: timestampToString(s.UpdatedAt),
})
@@ -170,7 +173,10 @@ func (h *Handler) ListChatSessions(w http.ResponseWriter, r *http.Request) {
CreatorID: uuidToString(s.CreatorID),
Title: s.Title,
Status: s.Status,
- HasUnread: s.HasUnread,
+ HasUnread: s.UnreadCount > 0,
+ UnreadCount: int(s.UnreadCount),
+ LastMessage: buildChatLastMessage(s.LastMessageAt, s.LastMessageContent, s.LastMessageRole, s.LastMessageFailureReason),
+ Pinned: s.PinnedAt.Valid,
CreatedAt: timestampToString(s.CreatedAt),
UpdatedAt: timestampToString(s.UpdatedAt),
})
@@ -248,8 +254,9 @@ type UpdateChatSessionRequest struct {
// UpdateChatSession updates user-editable fields on a chat session — today
// just `title`, surfaced by the inline rename affordance in the session
-// dropdown. Title is the only field accepted: `status` is legacy + read-only,
-// agent/creator/workspace are immutable, the resume pointers
+// dropdown. Title is the only field accepted here: `status` has its own
+// archive/unarchive endpoint (SetChatSessionArchived), `pinned` its own pin
+// endpoint, agent/creator/workspace are immutable, the resume pointers
// (session_id / work_dir / runtime_id) are daemon-owned.
func (h *Handler) UpdateChatSession(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
@@ -302,6 +309,103 @@ func (h *Handler) UpdateChatSession(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, chatSessionToResponse(updated))
}
+type SetChatSessionPinnedRequest struct {
+ Pinned bool `json:"pinned"`
+}
+
+// SetChatSessionPinned pins or unpins a chat so it sticks to the top of the
+// caller's conversation list. Pin state is per-session and, since sessions are
+// per-creator, inherently per-user. It never bumps updated_at (see the SQL) so
+// an unpinned chat does not jump the activity-sorted list.
+func (h *Handler) SetChatSessionPinned(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ sessionID := chi.URLParam(r, "sessionId")
+
+ var req SetChatSessionPinnedRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+
+ session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)
+ if !ok {
+ return
+ }
+
+ updated, err := h.Queries.SetChatSessionPinned(r.Context(), db.SetChatSessionPinnedParams{
+ ID: session.ID,
+ Pinned: req.Pinned,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update chat session")
+ return
+ }
+
+ resolvedSessionID := uuidToString(updated.ID)
+ pinned := updated.PinnedAt.Valid
+ h.publishChat(protocol.EventChatSessionUpdated, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionUpdatedPayload{
+ ChatSessionID: resolvedSessionID,
+ Title: updated.Title,
+ Pinned: &pinned,
+ UpdatedAt: timestampToString(updated.UpdatedAt),
+ })
+
+ writeJSON(w, http.StatusOK, chatSessionToResponse(updated))
+}
+
+type SetChatSessionArchivedRequest struct {
+ Archived bool `json:"archived"`
+}
+
+// SetChatSessionArchived archives or unarchives a chat session owned by the
+// caller. Archiving is the reversible sibling of delete: the row stays in the
+// 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.
+func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ sessionID := chi.URLParam(r, "sessionId")
+
+ var req SetChatSessionArchivedRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+
+ session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)
+ if !ok {
+ return
+ }
+
+ updated, err := h.Queries.SetChatSessionArchived(r.Context(), db.SetChatSessionArchivedParams{
+ ID: session.ID,
+ Archived: req.Archived,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update chat session")
+ return
+ }
+
+ resolvedSessionID := uuidToString(updated.ID)
+ status := updated.Status
+ h.publishChat(protocol.EventChatSessionUpdated, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionUpdatedPayload{
+ ChatSessionID: resolvedSessionID,
+ Title: updated.Title,
+ Status: &status,
+ UpdatedAt: timestampToString(updated.UpdatedAt),
+ })
+
+ writeJSON(w, http.StatusOK, chatSessionToResponse(updated))
+}
+
// DeleteChatSession hard-deletes a chat session owned by the caller. The
// row lock + cancel + delete run inside a single tx so a concurrent
// SendChatMessage cannot enqueue a task that would later be orphaned by
@@ -447,15 +551,35 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- // New archive flow doesn't exist anymore, but legacy rows with
- // status='archived' may still be in the DB from before the feature
- // was removed. Refuse to enqueue new agent work for them — frontend
- // surfaces these as read-only.
+ // Archived sessions are read-only: refuse to enqueue new agent work for
+ // them (see SetChatSessionArchived). The frontend disables the composer
+ // for status='archived' and only offers unarchive/delete there. Legacy
+ // soft-archived rows from before the feature are covered by the same check.
if session.Status != "active" {
writeError(w, http.StatusBadRequest, "chat session is archived")
return
}
+ // Preflight the agent's enqueue preconditions BEFORE persisting the user
+ // message. EnqueueChatTask (below) rejects an archived or runtime-less agent
+ // with an error; without this check a stale client (agent archived in
+ // another tab) would land the user message, then get a 500, leaving an
+ // orphan message with no task or reply. Fail fast with a 4xx and mutate
+ // nothing. See EnqueueChatTask's ErrChatTaskAgentArchived / NoRuntime.
+ agent, err := h.Queries.GetAgent(r.Context(), session.AgentID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load chat agent")
+ return
+ }
+ if agent.ArchivedAt.Valid {
+ writeError(w, http.StatusConflict, "chat agent is archived")
+ return
+ }
+ if !agent.RuntimeID.Valid {
+ writeError(w, http.StatusConflict, "chat agent has no runtime")
+ return
+ }
+
// Create the user message first so the daemon can always find it.
msg, err := h.Queries.CreateChatMessage(r.Context(), db.CreateChatMessageParams{
ChatSessionID: session.ID,
@@ -1023,12 +1147,42 @@ type ChatSessionResponse struct {
CreatorID string `json:"creator_id"`
Title string `json:"title"`
Status string `json:"status"`
- // Only populated by list endpoints — single-session fetches return false.
- HasUnread bool `json:"has_unread"`
+ // Only populated by list endpoints — single-session fetches return 0/false/nil.
+ // HasUnread is kept as a convenience (== UnreadCount > 0) for existing consumers.
+ HasUnread bool `json:"has_unread"`
+ UnreadCount int `json:"unread_count"`
+ LastMessage *ChatLastMessage `json:"last_message"`
+ // Pinned marks a chat the user has stuck to the top of the list. Populated
+ // by list endpoints and by the pin/unpin + single-session responses.
+ Pinned bool `json:"pinned"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
+// ChatLastMessage is a preview of a session's most recent message, used to
+// render the IM-style conversation list (name + snippet + time). nil when the
+// session has no messages yet.
+type ChatLastMessage struct {
+ Content string `json:"content"`
+ Role string `json:"role"`
+ CreatedAt string `json:"created_at"`
+ FailureReason *string `json:"failure_reason"`
+}
+
+// buildChatLastMessage assembles the preview from list-row columns; returns nil
+// when there is no last message (the LEFT JOIN produced a NULL timestamp).
+func buildChatLastMessage(at pgtype.Timestamptz, content, role string, failure pgtype.Text) *ChatLastMessage {
+ if !at.Valid {
+ return nil
+ }
+ return &ChatLastMessage{
+ Content: content,
+ Role: role,
+ CreatedAt: timestampToString(at),
+ FailureReason: textToPtr(failure),
+ }
+}
+
type ChatMessageResponse struct {
ID string `json:"id"`
ChatSessionID string `json:"chat_session_id"`
@@ -1058,6 +1212,7 @@ func chatSessionToResponse(s db.ChatSession) ChatSessionResponse {
CreatorID: uuidToString(s.CreatorID),
Title: s.Title,
Status: s.Status,
+ Pinned: s.PinnedAt.Valid,
CreatedAt: timestampToString(s.CreatedAt),
UpdatedAt: timestampToString(s.UpdatedAt),
}
diff --git a/server/internal/handler/chat_pinned_agent.go b/server/internal/handler/chat_pinned_agent.go
new file mode 100644
index 0000000000..e7a5ff9e90
--- /dev/null
+++ b/server/internal/handler/chat_pinned_agent.go
@@ -0,0 +1,169 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// maxChatPinnedAgents caps the quick-agent bar so it stays compact.
+const maxChatPinnedAgents = 5
+
+// ChatPinnedAgentResponse is one entry in a user's "quick agent" bar.
+type ChatPinnedAgentResponse struct {
+ AgentID string `json:"agent_id"`
+ Position float64 `json:"position"`
+}
+
+// resolveChatAgentAccess returns the set of agent ids the caller may use, or
+// writes an error and returns ok=false. Mirrors ListChatSessions so pins can't
+// surface or target agents the caller has lost access to.
+func (h *Handler) resolveChatAgentAccess(w http.ResponseWriter, r *http.Request, userID, workspaceID string) (map[string]struct{}, bool) {
+ member, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
+ return nil, false
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)
+ if !ok {
+ writeError(w, http.StatusInternalServerError, "failed to resolve agent access")
+ return nil, false
+ }
+ return allowed, true
+}
+
+// ListChatPinnedAgents returns the caller's pinned quick-chat agents, ordered.
+// Pins for agents the caller can no longer access (archived / permissions
+// changed) are dropped from the response.
+func (h *Handler) ListChatPinnedAgents(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ allowed, ok := h.resolveChatAgentAccess(w, r, userID, workspaceID)
+ if !ok {
+ return
+ }
+
+ rows, err := h.Queries.ListChatPinnedAgents(r.Context(), db.ListChatPinnedAgentsParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: parseUUID(userID),
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list pinned agents")
+ return
+ }
+
+ resp := make([]ChatPinnedAgentResponse, 0, len(rows))
+ for _, row := range rows {
+ agentID := uuidToString(row.AgentID)
+ if _, ok := allowed[agentID]; !ok {
+ continue
+ }
+ resp = append(resp, ChatPinnedAgentResponse{AgentID: agentID, Position: row.Position})
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// PinChatAgent adds an agent to the caller's quick-chat bar (append at end).
+// Idempotent — pinning an already-pinned agent returns 200.
+func (h *Handler) PinChatAgent(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+
+ var req struct {
+ AgentID string `json:"agent_id"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ agentUUID, ok := parseUUIDOrBadRequest(w, req.AgentID, "agent_id")
+ if !ok {
+ return
+ }
+
+ allowed, ok := h.resolveChatAgentAccess(w, r, userID, workspaceID)
+ if !ok {
+ return
+ }
+ if _, ok := allowed[req.AgentID]; !ok {
+ writeError(w, http.StatusNotFound, "agent not found")
+ return
+ }
+
+ // Cap the quick-agent bar at a small, curated set. Re-pinning an already
+ // pinned agent stays idempotent and is allowed even at the cap.
+ existing, err := h.Queries.ListChatPinnedAgents(r.Context(), db.ListChatPinnedAgentsParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: parseUUID(userID),
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list pinned agents")
+ return
+ }
+ alreadyPinned := false
+ for _, e := range existing {
+ if uuidToString(e.AgentID) == req.AgentID {
+ alreadyPinned = true
+ break
+ }
+ }
+ if !alreadyPinned && len(existing) >= maxChatPinnedAgents {
+ writeError(w, http.StatusBadRequest, "pinned agent limit reached")
+ return
+ }
+
+ maxPos, err := h.Queries.GetMaxChatPinnedAgentPosition(r.Context(), db.GetMaxChatPinnedAgentPositionParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: parseUUID(userID),
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to get position")
+ return
+ }
+
+ row, err := h.Queries.CreateChatPinnedAgent(r.Context(), db.CreateChatPinnedAgentParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: parseUUID(userID),
+ AgentID: agentUUID,
+ Position: maxPos + 1,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to pin agent")
+ return
+ }
+ writeJSON(w, http.StatusOK, ChatPinnedAgentResponse{
+ AgentID: uuidToString(row.AgentID),
+ Position: row.Position,
+ })
+}
+
+// UnpinChatAgent removes an agent from the caller's quick-chat bar.
+func (h *Handler) UnpinChatAgent(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ agentUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "agentId"), "agentId")
+ if !ok {
+ return
+ }
+
+ if err := h.Queries.DeleteChatPinnedAgent(r.Context(), db.DeleteChatPinnedAgentParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: parseUUID(userID),
+ AgentID: agentUUID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to unpin agent")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/server/internal/handler/chat_test.go b/server/internal/handler/chat_test.go
index cc0c557029..2d8688620e 100644
--- a/server/internal/handler/chat_test.go
+++ b/server/internal/handler/chat_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"net/url"
"testing"
+ "time"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/util"
@@ -123,6 +124,50 @@ func TestSendChatMessage_LinksAttachments(t *testing.T) {
}
}
+// TestSendChatMessage_ArchivedAgent verifies that sending to a session whose
+// agent was archived is rejected with 409 BEFORE any message is persisted.
+// EnqueueChatTask rejects an archived agent, but only after CreateChatMessage;
+// without the handler's preflight a stale client would leave an orphan user
+// message with no task or reply.
+func TestSendChatMessage_ArchivedAgent(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "ChatArchivedAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ // Archive the agent out from under the (stale) client.
+ if _, err := testPool.Exec(
+ context.Background(),
+ `UPDATE agent SET archived_at = now() WHERE id = $1`,
+ agentID,
+ ); err != nil {
+ t.Fatalf("archive agent: %v", err)
+ }
+
+ sendReq := newRequest("POST", "/api/chat-sessions/"+sessionID+"/messages", map[string]any{
+ "content": "still there?",
+ })
+ sendReq = withURLParam(sendReq, "sessionId", sessionID)
+ sendReq = withChatTestWorkspaceCtx(t, sendReq)
+ sendW := httptest.NewRecorder()
+ testHandler.SendChatMessage(sendW, sendReq)
+
+ if sendW.Code != http.StatusConflict {
+ t.Fatalf("SendChatMessage to archived agent: expected 409, got %d: %s", sendW.Code, sendW.Body.String())
+ }
+
+ // The rejected send must not have persisted an orphan user message.
+ var count int
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT count(*) FROM chat_message WHERE chat_session_id = $1`,
+ sessionID,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count chat messages: %v", err)
+ }
+ if count != 0 {
+ t.Fatalf("expected no chat_message rows after rejected send, got %d", count)
+ }
+}
+
// TestSendChatMessage_LinksUnattachedAttachments verifies the new compose
// path: upload creates a workspace-scoped unattached attachment, and chat send
// binds it to both the session and the user message.
@@ -236,6 +281,130 @@ func TestUpdateChatSession_RenamesTitle(t *testing.T) {
}
}
+// TestSetChatSessionPinned_TogglesPin confirms PATCH /pin stamps pinned_at on
+// pin and clears it on unpin, returns the new state, and does not bump
+// updated_at (pinning is a list-ordering preference, not activity).
+func TestSetChatSessionPinned_TogglesPin(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "ChatPinAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ var updatedBefore time.Time
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT updated_at FROM chat_session WHERE id = $1`,
+ sessionID,
+ ).Scan(&updatedBefore); err != nil {
+ t.Fatalf("query updated_at: %v", err)
+ }
+
+ pin := func(pinned bool) ChatSessionResponse {
+ req := newRequest("PATCH", "/api/chat/sessions/"+sessionID+"/pin", map[string]any{
+ "pinned": pinned,
+ })
+ req = withURLParam(req, "sessionId", sessionID)
+ req = withChatTestWorkspaceCtx(t, req)
+ w := httptest.NewRecorder()
+ testHandler.SetChatSessionPinned(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("SetChatSessionPinned(%v): expected 200, got %d: %s", pinned, w.Code, w.Body.String())
+ }
+ var resp ChatSessionResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode pin: %v", err)
+ }
+ return resp
+ }
+
+ // Pin.
+ if resp := pin(true); !resp.Pinned {
+ t.Fatalf("pin=true response Pinned: want true, got false")
+ }
+ var pinnedAt *time.Time
+ var updatedAfter time.Time
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT pinned_at, updated_at FROM chat_session WHERE id = $1`,
+ sessionID,
+ ).Scan(&pinnedAt, &updatedAfter); err != nil {
+ t.Fatalf("query pinned_at: %v", err)
+ }
+ if pinnedAt == nil {
+ t.Fatalf("pinned_at: want non-null after pin, got null")
+ }
+ if !updatedAfter.Equal(updatedBefore) {
+ t.Fatalf("updated_at must not change on pin: before %v, after %v", updatedBefore, updatedAfter)
+ }
+
+ // Unpin.
+ if resp := pin(false); resp.Pinned {
+ t.Fatalf("pin=false response Pinned: want false, got true")
+ }
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT pinned_at FROM chat_session WHERE id = $1`,
+ sessionID,
+ ).Scan(&pinnedAt); err != nil {
+ t.Fatalf("query pinned_at after unpin: %v", err)
+ }
+ if pinnedAt != nil {
+ t.Fatalf("pinned_at: want null after unpin, got %v", *pinnedAt)
+ }
+}
+
+// TestSetChatSessionArchived_TogglesStatus archives then unarchives a session,
+// asserting the response + DB status column flip and that updated_at is bumped
+// (so the row re-sorts in whichever list it lands).
+func TestSetChatSessionArchived_TogglesStatus(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "ChatArchiveAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ archive := func(archived bool) ChatSessionResponse {
+ 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())
+ }
+ var resp ChatSessionResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode archive: %v", err)
+ }
+ return resp
+ }
+
+ dbStatus := func() string {
+ var status string
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT status FROM chat_session WHERE id = $1`,
+ sessionID,
+ ).Scan(&status); err != nil {
+ t.Fatalf("query status: %v", err)
+ }
+ return status
+ }
+
+ // Archive.
+ if resp := archive(true); resp.Status != "archived" {
+ t.Fatalf("archive=true response Status: want archived, got %q", resp.Status)
+ }
+ if got := dbStatus(); got != "archived" {
+ t.Fatalf("db status after archive: want archived, got %q", got)
+ }
+
+ // Unarchive restores it to active.
+ if resp := archive(false); resp.Status != "active" {
+ t.Fatalf("archive=false response Status: want active, got %q", resp.Status)
+ }
+ if got := dbStatus(); got != "active" {
+ t.Fatalf("db status after unarchive: want active, got %q", got)
+ }
+}
+
// TestUpdateChatSession_RejectsBlank refuses an empty/whitespace title with 400.
// (Untitled is a render-side fallback, not a stored value.)
func TestUpdateChatSession_RejectsBlank(t *testing.T) {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 63483c15b9..63960e9014 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1710,6 +1710,22 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
resp.WorkspaceID = uuidToString(cs.WorkspaceID)
resp.ChatSessionID = uuidToString(cs.ID)
resp.ThreadName = cs.Title
+ // An is_agent_intro session carries no user message: the agent opens
+ // the conversation by introducing itself. Flag it so the daemon builds
+ // a self-introduction prompt rather than a "reply to their message"
+ // prompt (MUL-4230). The is_agent_intro column stays true for the
+ // session's whole life, so gate the intro prompt on the session still
+ // having zero human messages — otherwise every follow-up turn after the
+ // creator replies would re-run the "introduce yourself" prompt and the
+ // agent keeps repeating the same introduction (MUL-4259).
+ if cs.IsAgentIntro {
+ if hasUser, herr := h.Queries.ChatSessionHasUserMessage(r.Context(), cs.ID); herr != nil {
+ slog.Warn("chat intro gate: has-user-message check failed",
+ "chat_session_id", uuidToString(cs.ID), "error", herr)
+ } else {
+ resp.ChatIntro = !hasUser
+ }
+ }
// Flag a channel-backed session so the daemon makes the agent aware
// it is operating inside Slack — read this conversation's history
// from the channel via `multica chat history` / `multica chat thread`,
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index 5b8286f53f..1f665dca5a 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -227,6 +227,114 @@ func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {
return resp.Task, w.Body.String()
}
+// claimChatIntroForTest claims the next task for a runtime and returns the
+// claimed task id plus its chat_intro flag (false when the field is absent, as
+// it is omitempty).
+func claimChatIntroForTest(t *testing.T, runtimeID string) (string, bool, string) {
+ t.Helper()
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "chat-intro-review")
+ req = withURLParam(req, "runtimeId", runtimeID)
+
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp struct {
+ Task *struct {
+ ID string `json:"id"`
+ ChatIntro bool `json:"chat_intro"`
+ } `json:"task"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode claim response: %v", err)
+ }
+ if resp.Task == nil {
+ t.Fatalf("expected a claimable task, got none: %s", w.Body.String())
+ }
+ return resp.Task.ID, resp.Task.ChatIntro, w.Body.String()
+}
+
+// TestClaimTaskByRuntime_ChatIntroGateClearsAfterUserReplies pins the MUL-4259
+// fix: an is_agent_intro session drives the self-introduction prompt only on
+// its first, message-less turn. Once the creator has replied, later turns on
+// the same (still is_agent_intro) session must claim with chat_intro=false so
+// the agent answers instead of repeating its introduction.
+func TestClaimTaskByRuntime_ChatIntroGateClearsAfterUserReplies(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Chat intro gate runtime")
+ agentID, _ := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Chat intro gate agent")
+ // Allow more than one in-flight task so the second claim isn't blocked by
+ // the first (which stays 'dispatched') on the concurrency limit.
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET max_concurrent_tasks = 5 WHERE id = $1`, agentID); err != nil {
+ t.Fatalf("raise max_concurrent_tasks: %v", err)
+ }
+
+ var sessionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status, runtime_id, is_agent_intro)
+ VALUES ($1, $2, $3, '👋 intro', 'active', $4, true)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&sessionID); err != nil {
+ t.Fatalf("insert intro chat session: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID) })
+
+ seedQueuedChatTask := func() string {
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, chat_session_id)
+ VALUES ($1, $2, 'queued', 0, $3)
+ RETURNING id
+ `, agentID, runtimeID, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("seed queued chat task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+ return taskID
+ }
+
+ // First turn: no user message yet → the server-driven intro run.
+ introTaskID := seedQueuedChatTask()
+ claimedID, chatIntro, body := claimChatIntroForTest(t, runtimeID)
+ if claimedID != introTaskID {
+ t.Fatalf("claimed task id = %s, want intro task %s: %s", claimedID, introTaskID, body)
+ }
+ if !chatIntro {
+ t.Fatalf("expected chat_intro=true for the message-less intro turn: %s", body)
+ }
+
+ // The intro run finishes. Chat tasks serialize on chat_session_id, so the
+ // next turn only becomes claimable once this one leaves an in-flight state.
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`, introTaskID); err != nil {
+ t.Fatalf("complete intro task: %v", err)
+ }
+
+ // The creator replies: persist a user message on the same session.
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content)
+ VALUES ($1, 'user', 'thanks! can you help me with X?')
+ `, sessionID); err != nil {
+ t.Fatalf("insert user reply: %v", err)
+ }
+
+ // Second turn on the same is_agent_intro session must NOT re-introduce.
+ followupTaskID := seedQueuedChatTask()
+ claimedID, chatIntro, body = claimChatIntroForTest(t, runtimeID)
+ if claimedID != followupTaskID {
+ t.Fatalf("claimed task id = %s, want follow-up task %s: %s", claimedID, followupTaskID, body)
+ }
+ if chatIntro {
+ t.Fatalf("expected chat_intro=false once the creator has replied: %s", body)
+ }
+}
+
func TestClaimTaskByRuntime_ReclaimsStaleDispatchedTask(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index a7b7c440b9..5fd5ba0622 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1735,13 +1735,8 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
slog.Error("failed to save assistant chat message", "task_id", util.UUIDToString(task.ID), "error", err)
} else {
assistantMsg = &row
- // Event-driven unread: stamp unread_since on the first unread
- // assistant message. No-op if the session already has unread.
- // If the user is actively viewing the session, the frontend's
- // auto-mark-read effect will clear this within a tick.
- if err := s.Queries.SetUnreadSinceIfNull(ctx, task.ChatSessionID); err != nil {
- slog.Warn("failed to set unread_since", "chat_session_id", util.UUIDToString(task.ChatSessionID), "error", err)
- }
+ // Unread is derived from the read cursor (chat_session.last_read_at)
+ // vs the assistant messages after it — no per-reply stamping needed.
}
}
s.broadcastChatDone(ctx, task, assistantMsg)
@@ -1879,10 +1874,6 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
"task_id", util.UUIDToString(task.ID),
"chat_session_id", util.UUIDToString(task.ChatSessionID),
"error", err)
- } else if err := s.Queries.SetUnreadSinceIfNull(ctx, task.ChatSessionID); err != nil {
- slog.Warn("failed to set unread_since on failure",
- "chat_session_id", util.UUIDToString(task.ChatSessionID),
- "error", err)
}
}
diff --git a/server/migrations/145_chat_read_cursor.down.sql b/server/migrations/145_chat_read_cursor.down.sql
new file mode 100644
index 0000000000..db4df054f8
--- /dev/null
+++ b/server/migrations/145_chat_read_cursor.down.sql
@@ -0,0 +1,16 @@
+ALTER TABLE chat_session ADD COLUMN unread_since TIMESTAMPTZ;
+
+-- Best-effort restore of the boolean flag: any session with an assistant
+-- message after its read cursor is stamped unread at the earliest such message.
+UPDATE chat_session cs
+ SET unread_since = sub.first_unread
+ FROM (
+ SELECT m.chat_session_id, min(m.created_at) AS first_unread
+ FROM chat_message m
+ JOIN chat_session s ON s.id = m.chat_session_id
+ WHERE m.role = 'assistant' AND m.created_at > s.last_read_at
+ GROUP BY m.chat_session_id
+ ) sub
+ WHERE cs.id = sub.chat_session_id;
+
+ALTER TABLE chat_session DROP COLUMN last_read_at;
diff --git a/server/migrations/145_chat_read_cursor.up.sql b/server/migrations/145_chat_read_cursor.up.sql
new file mode 100644
index 0000000000..dc20889471
--- /dev/null
+++ b/server/migrations/145_chat_read_cursor.up.sql
@@ -0,0 +1,15 @@
+-- IM-style unread: replace the per-session `unread_since` boolean flag with a
+-- read cursor `last_read_at`. Unread is now derived as the *count* of assistant
+-- messages after the cursor, so the chat list can show a real number (like an
+-- IM conversation) instead of a single dot.
+ALTER TABLE chat_session ADD COLUMN last_read_at TIMESTAMPTZ NOT NULL DEFAULT now();
+
+-- Preserve existing unread state during the switch: a session currently flagged
+-- unread gets its cursor placed just before the first unread reply, so those
+-- messages still count. `unread_since` is the arrival time of the first unread
+-- assistant message.
+UPDATE chat_session
+ SET last_read_at = unread_since - interval '1 microsecond'
+ WHERE unread_since IS NOT NULL;
+
+ALTER TABLE chat_session DROP COLUMN unread_since;
diff --git a/server/migrations/146_chat_pinned_agent.down.sql b/server/migrations/146_chat_pinned_agent.down.sql
new file mode 100644
index 0000000000..15e6181204
--- /dev/null
+++ b/server/migrations/146_chat_pinned_agent.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS chat_pinned_agent;
diff --git a/server/migrations/146_chat_pinned_agent.up.sql b/server/migrations/146_chat_pinned_agent.up.sql
new file mode 100644
index 0000000000..11fd924ae5
--- /dev/null
+++ b/server/migrations/146_chat_pinned_agent.up.sql
@@ -0,0 +1,15 @@
+-- Per-user "quick agent" pins for the Chat list: a curated, ordered set of
+-- agents the user keeps at the top of the conversation list for one-tap new
+-- chats. Kept separate from the generic `pinned_item` table (issues/projects)
+-- so it doesn't leak into the sidebar's pinned section.
+CREATE TABLE chat_pinned_agent (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ user_id UUID NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
+ agent_id UUID NOT NULL REFERENCES agent(id) ON DELETE CASCADE,
+ position FLOAT NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (workspace_id, user_id, agent_id)
+);
+
+CREATE INDEX idx_chat_pinned_agent_user_ws ON chat_pinned_agent (workspace_id, user_id, position);
diff --git a/server/migrations/147_chat_agent_intro.down.sql b/server/migrations/147_chat_agent_intro.down.sql
new file mode 100644
index 0000000000..665c6e2b11
--- /dev/null
+++ b/server/migrations/147_chat_agent_intro.down.sql
@@ -0,0 +1 @@
+ALTER TABLE chat_session DROP COLUMN is_agent_intro;
diff --git a/server/migrations/147_chat_agent_intro.up.sql b/server/migrations/147_chat_agent_intro.up.sql
new file mode 100644
index 0000000000..cae6d34394
--- /dev/null
+++ b/server/migrations/147_chat_agent_intro.up.sql
@@ -0,0 +1,6 @@
+-- Flags a chat_session auto-created when its agent was created, so its first
+-- turn is a proactive self-introduction from the agent. Such a session carries
+-- NO visible user message: the intro run is driven server-side (see the chat
+-- prompt in server/internal/daemon/prompt.go) so the thread reads as the agent
+-- messaging its creator first, not the creator prompting the agent.
+ALTER TABLE chat_session ADD COLUMN is_agent_intro BOOLEAN NOT NULL DEFAULT FALSE;
diff --git a/server/migrations/148_chat_session_pinned.down.sql b/server/migrations/148_chat_session_pinned.down.sql
new file mode 100644
index 0000000000..b0871b32cf
--- /dev/null
+++ b/server/migrations/148_chat_session_pinned.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS idx_chat_session_pinned;
+ALTER TABLE chat_session DROP COLUMN IF EXISTS pinned_at;
diff --git a/server/migrations/148_chat_session_pinned.up.sql b/server/migrations/148_chat_session_pinned.up.sql
new file mode 100644
index 0000000000..820f610dd1
--- /dev/null
+++ b/server/migrations/148_chat_session_pinned.up.sql
@@ -0,0 +1,12 @@
+-- Per-conversation pin for the Chat list: a user can pin a chat so it stays
+-- at the top of their conversation list, above the activity-sorted rest.
+-- `pinned_at` doubles as the sort key within the pinned group (most-recently
+-- pinned first) and as the boolean flag (NULL = not pinned). Sessions are
+-- already per-creator, so no extra user dimension is needed.
+ALTER TABLE chat_session ADD COLUMN pinned_at TIMESTAMPTZ;
+
+-- Partial index over pinned rows only — the pinned group is small, and the
+-- list query orders by pinned_at within a single (workspace, creator) scan.
+CREATE INDEX idx_chat_session_pinned
+ ON chat_session (creator_id, workspace_id, pinned_at DESC)
+ WHERE pinned_at IS NOT NULL;
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index a616848d64..c877515e29 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -11,6 +11,26 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const chatSessionHasUserMessage = `-- name: ChatSessionHasUserMessage :one
+SELECT EXISTS (
+ SELECT 1 FROM chat_message
+ WHERE chat_session_id = $1 AND role = 'user'
+) AS has_user_message
+`
+
+// Reports whether a session has any human (role='user') message yet. Used to
+// scope the is_agent_intro self-introduction prompt to the very first,
+// server-driven turn: an intro session starts with zero user messages, so the
+// opening run gets the "introduce yourself" prompt. Once the creator replies,
+// later turns in the same session must fall back to the normal reply prompt
+// instead of repeating the introduction every turn (MUL-4259).
+func (q *Queries) ChatSessionHasUserMessage(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, chatSessionHasUserMessage, chatSessionID)
+ var has_user_message bool
+ err := row.Scan(&has_user_message)
+ return has_user_message, err
+}
+
const createChatMessage = `-- name: CreateChatMessage :one
INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms)
VALUES ($1, $2, $3, $4, $5, $6)
@@ -50,16 +70,17 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
}
const createChatSession = `-- name: CreateChatSession :one
-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id)
-VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2))
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id
+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro)
+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5)
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, runtime_id, last_read_at, is_agent_intro, pinned_at
`
type CreateChatSessionParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- AgentID pgtype.UUID `json:"agent_id"`
- CreatorID pgtype.UUID `json:"creator_id"`
- Title string `json:"title"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ Title string `json:"title"`
+ IsAgentIntro bool `json:"is_agent_intro"`
}
func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionParams) (ChatSession, error) {
@@ -68,6 +89,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
arg.AgentID,
arg.CreatorID,
arg.Title,
+ arg.IsAgentIntro,
)
var i ChatSession
err := row.Scan(
@@ -81,8 +103,10 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
- &i.UnreadSince,
&i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
)
return i, err
}
@@ -234,7 +258,7 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa
}
const getChatSession = `-- name: GetChatSession :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, runtime_id, last_read_at, is_agent_intro, pinned_at FROM chat_session
WHERE id = $1
`
@@ -252,14 +276,16 @@ func (q *Queries) GetChatSession(ctx context.Context, id pgtype.UUID) (ChatSessi
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
- &i.UnreadSince,
&i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
)
return i, err
}
const getChatSessionInWorkspace = `-- name: GetChatSessionInWorkspace :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, runtime_id, last_read_at, is_agent_intro, pinned_at FROM chat_session
WHERE id = $1 AND workspace_id = $2
`
@@ -282,8 +308,10 @@ func (q *Queries) GetChatSessionInWorkspace(ctx context.Context, arg GetChatSess
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
- &i.UnreadSince,
&i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
)
return i, err
}
@@ -429,11 +457,25 @@ 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.unread_since IS NOT NULL)::bool AS has_unread
+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.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,
+ COALESCE(lm.content, '') AS last_message_content,
+ COALESCE(lm.role, '') AS last_message_role,
+ lm.created_at AS last_message_at,
+ lm.failure_reason AS last_message_failure_reason
FROM chat_session cs
+LEFT JOIN LATERAL (
+ SELECT content, role, created_at, failure_reason
+ FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ ORDER BY m.created_at DESC
+ LIMIT 1
+) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2
-ORDER BY cs.updated_at DESC
+ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC
`
type ListAllChatSessionsByCreatorParams struct {
@@ -442,19 +484,25 @@ type ListAllChatSessionsByCreatorParams struct {
}
type ListAllChatSessionsByCreatorRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- AgentID pgtype.UUID `json:"agent_id"`
- CreatorID pgtype.UUID `json:"creator_id"`
- Title string `json:"title"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
- Status string `json:"status"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- UnreadSince pgtype.Timestamptz `json:"unread_since"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- HasUnread bool `json:"has_unread"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ Title string `json:"title"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ Status string `json:"status"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ LastReadAt pgtype.Timestamptz `json:"last_read_at"`
+ IsAgentIntro bool `json:"is_agent_intro"`
+ PinnedAt pgtype.Timestamptz `json:"pinned_at"`
+ UnreadCount int32 `json:"unread_count"`
+ LastMessageContent string `json:"last_message_content"`
+ LastMessageRole string `json:"last_message_role"`
+ LastMessageAt pgtype.Timestamptz `json:"last_message_at"`
+ LastMessageFailureReason pgtype.Text `json:"last_message_failure_reason"`
}
func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllChatSessionsByCreatorParams) ([]ListAllChatSessionsByCreatorRow, error) {
@@ -477,9 +525,15 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
- &i.UnreadSince,
&i.RuntimeID,
- &i.HasUnread,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.UnreadCount,
+ &i.LastMessageContent,
+ &i.LastMessageRole,
+ &i.LastMessageAt,
+ &i.LastMessageFailureReason,
); err != nil {
return nil, err
}
@@ -579,11 +633,25 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages
}
const listChatSessionsByCreator = `-- name: ListChatSessionsByCreator :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.unread_since IS NOT NULL)::bool AS has_unread
+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.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,
+ COALESCE(lm.content, '') AS last_message_content,
+ COALESCE(lm.role, '') AS last_message_role,
+ lm.created_at AS last_message_at,
+ lm.failure_reason AS last_message_failure_reason
FROM chat_session cs
+LEFT JOIN LATERAL (
+ SELECT content, role, created_at, failure_reason
+ FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ ORDER BY m.created_at DESC
+ LIMIT 1
+) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'
-ORDER BY cs.updated_at DESC
+ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC
`
type ListChatSessionsByCreatorParams struct {
@@ -592,24 +660,30 @@ type ListChatSessionsByCreatorParams struct {
}
type ListChatSessionsByCreatorRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- AgentID pgtype.UUID `json:"agent_id"`
- CreatorID pgtype.UUID `json:"creator_id"`
- Title string `json:"title"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
- Status string `json:"status"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- UnreadSince pgtype.Timestamptz `json:"unread_since"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- HasUnread bool `json:"has_unread"`
-}
-
-// Returns active sessions with a boolean unread flag. Unread is strictly
-// per-session: either the user has uncleared assistant replies in this
-// session or they don't. Counting messages would be misleading.
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ Title string `json:"title"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ Status string `json:"status"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ LastReadAt pgtype.Timestamptz `json:"last_read_at"`
+ IsAgentIntro bool `json:"is_agent_intro"`
+ PinnedAt pgtype.Timestamptz `json:"pinned_at"`
+ UnreadCount int32 `json:"unread_count"`
+ LastMessageContent string `json:"last_message_content"`
+ LastMessageRole string `json:"last_message_role"`
+ LastMessageAt pgtype.Timestamptz `json:"last_message_at"`
+ LastMessageFailureReason pgtype.Text `json:"last_message_failure_reason"`
+}
+
+// IM-style list: each active session with its unread *count* (assistant
+// messages after the read cursor), a preview of the latest message, and
+// ordered by most-recent activity so a new reply bumps a session to the top.
func (q *Queries) ListChatSessionsByCreator(ctx context.Context, arg ListChatSessionsByCreatorParams) ([]ListChatSessionsByCreatorRow, error) {
rows, err := q.db.Query(ctx, listChatSessionsByCreator, arg.WorkspaceID, arg.CreatorID)
if err != nil {
@@ -630,9 +704,15 @@ func (q *Queries) ListChatSessionsByCreator(ctx context.Context, arg ListChatSes
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
- &i.UnreadSince,
&i.RuntimeID,
- &i.HasUnread,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.UnreadCount,
+ &i.LastMessageContent,
+ &i.LastMessageRole,
+ &i.LastMessageAt,
+ &i.LastMessageFailureReason,
); err != nil {
return nil, err
}
@@ -724,27 +804,92 @@ func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID)
}
const markChatSessionRead = `-- name: MarkChatSessionRead :exec
-UPDATE chat_session SET unread_since = NULL
+UPDATE chat_session SET last_read_at = now()
WHERE id = $1
`
-// Clears unread_since, dropping the session's unread count to 0.
+// Advances the read cursor to now, dropping the session's unread_count to 0.
func (q *Queries) MarkChatSessionRead(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, markChatSessionRead, id)
return err
}
-const setUnreadSinceIfNull = `-- name: SetUnreadSinceIfNull :exec
-UPDATE chat_session SET unread_since = now()
-WHERE id = $1 AND unread_since IS NULL
+const setChatSessionArchived = `-- name: SetChatSessionArchived :one
+UPDATE chat_session
+SET status = CASE WHEN $2::bool THEN 'archived' ELSE 'active' END,
+ updated_at = now()
+WHERE id = $1
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, runtime_id, last_read_at, is_agent_intro, pinned_at
`
-// Atomically stamps the first unread assistant message's arrival time.
-// No-op if the session is already in "has unread" state — keeps the earliest
-// unread boundary stable across multiple incoming replies.
-func (q *Queries) SetUnreadSinceIfNull(ctx context.Context, id pgtype.UUID) error {
- _, err := q.db.Exec(ctx, setUnreadSinceIfNull, id)
- return err
+type SetChatSessionArchivedParams struct {
+ ID pgtype.UUID `json:"id"`
+ Archived bool `json:"archived"`
+}
+
+// Archive/unarchive a chat session by flipping status between 'active' and
+// 'archived'. Bumps updated_at so the row re-sorts on the receiving list. The
+// send-message path refuses archived sessions (see SendChatMessage), so the
+// conversation is effectively read-only until it is unarchived.
+func (q *Queries) SetChatSessionArchived(ctx context.Context, arg SetChatSessionArchivedParams) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, setChatSessionArchived, arg.ID, arg.Archived)
+ 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.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ )
+ return i, err
+}
+
+const setChatSessionPinned = `-- name: SetChatSessionPinned :one
+UPDATE chat_session
+SET pinned_at = CASE WHEN $2::bool THEN COALESCE(pinned_at, now()) ELSE NULL END
+WHERE id = $1
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, runtime_id, last_read_at, is_agent_intro, pinned_at
+`
+
+type SetChatSessionPinnedParams struct {
+ ID pgtype.UUID `json:"id"`
+ Pinned bool `json:"pinned"`
+}
+
+// Pin/unpin a chat. Deliberately does NOT touch updated_at: pinning is a
+// list-ordering preference, not activity, so it must not bump the session's
+// last-activity sort key (which would make an unpinned chat jump the list).
+// pinned = true stamps pinned_at only when it was NULL, so re-pinning keeps
+// the original pin order; pinned = false clears it.
+func (q *Queries) SetChatSessionPinned(ctx context.Context, arg SetChatSessionPinnedParams) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, setChatSessionPinned, arg.ID, arg.Pinned)
+ 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.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ )
+ return i, err
}
const touchChatSession = `-- name: TouchChatSession :exec
@@ -791,7 +936,7 @@ func (q *Queries) UpdateChatSessionSession(ctx context.Context, arg UpdateChatSe
const updateChatSessionTitle = `-- name: UpdateChatSessionTitle :one
UPDATE chat_session SET title = $2, updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, runtime_id, last_read_at, is_agent_intro, pinned_at
`
type UpdateChatSessionTitleParams struct {
@@ -813,8 +958,10 @@ func (q *Queries) UpdateChatSessionTitle(ctx context.Context, arg UpdateChatSess
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
- &i.UnreadSince,
&i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat_pinned_agent.sql.go b/server/pkg/db/generated/chat_pinned_agent.sql.go
new file mode 100644
index 0000000000..435c0e82d3
--- /dev/null
+++ b/server/pkg/db/generated/chat_pinned_agent.sql.go
@@ -0,0 +1,120 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: chat_pinned_agent.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const createChatPinnedAgent = `-- name: CreateChatPinnedAgent :one
+INSERT INTO chat_pinned_agent (workspace_id, user_id, agent_id, position)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (workspace_id, user_id, agent_id)
+DO UPDATE SET position = chat_pinned_agent.position
+RETURNING id, workspace_id, user_id, agent_id, position, created_at
+`
+
+type CreateChatPinnedAgentParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ Position float64 `json:"position"`
+}
+
+// Idempotent: pinning an already-pinned agent is a no-op that returns the
+// existing row (DO UPDATE keeps `:one` from hitting a no-rows error).
+func (q *Queries) CreateChatPinnedAgent(ctx context.Context, arg CreateChatPinnedAgentParams) (ChatPinnedAgent, error) {
+ row := q.db.QueryRow(ctx, createChatPinnedAgent,
+ arg.WorkspaceID,
+ arg.UserID,
+ arg.AgentID,
+ arg.Position,
+ )
+ var i ChatPinnedAgent
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.UserID,
+ &i.AgentID,
+ &i.Position,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const deleteChatPinnedAgent = `-- name: DeleteChatPinnedAgent :exec
+DELETE FROM chat_pinned_agent
+WHERE workspace_id = $1 AND user_id = $2 AND agent_id = $3
+`
+
+type DeleteChatPinnedAgentParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+func (q *Queries) DeleteChatPinnedAgent(ctx context.Context, arg DeleteChatPinnedAgentParams) error {
+ _, err := q.db.Exec(ctx, deleteChatPinnedAgent, arg.WorkspaceID, arg.UserID, arg.AgentID)
+ return err
+}
+
+const getMaxChatPinnedAgentPosition = `-- name: GetMaxChatPinnedAgentPosition :one
+SELECT COALESCE(MAX(position), 0)::float8 AS max_position
+FROM chat_pinned_agent
+WHERE workspace_id = $1 AND user_id = $2
+`
+
+type GetMaxChatPinnedAgentPositionParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+func (q *Queries) GetMaxChatPinnedAgentPosition(ctx context.Context, arg GetMaxChatPinnedAgentPositionParams) (float64, error) {
+ row := q.db.QueryRow(ctx, getMaxChatPinnedAgentPosition, arg.WorkspaceID, arg.UserID)
+ var max_position float64
+ err := row.Scan(&max_position)
+ return max_position, err
+}
+
+const listChatPinnedAgents = `-- name: ListChatPinnedAgents :many
+SELECT id, workspace_id, user_id, agent_id, position, created_at FROM chat_pinned_agent
+WHERE workspace_id = $1 AND user_id = $2
+ORDER BY position ASC, created_at ASC
+`
+
+type ListChatPinnedAgentsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+func (q *Queries) ListChatPinnedAgents(ctx context.Context, arg ListChatPinnedAgentsParams) ([]ChatPinnedAgent, error) {
+ rows, err := q.db.Query(ctx, listChatPinnedAgents, arg.WorkspaceID, arg.UserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChatPinnedAgent{}
+ for rows.Next() {
+ var i ChatPinnedAgent
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.UserID,
+ &i.AgentID,
+ &i.Position,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 5ff5a463ea..d7d3b543c3 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -305,19 +305,30 @@ type ChatMessage struct {
ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
}
-type ChatSession struct {
+type ChatPinnedAgent struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
AgentID pgtype.UUID `json:"agent_id"`
- CreatorID pgtype.UUID `json:"creator_id"`
- Title string `json:"title"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
- Status string `json:"status"`
+ Position float64 `json:"position"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- UnreadSince pgtype.Timestamptz `json:"unread_since"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
+}
+
+type ChatSession struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ Title string `json:"title"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ Status string `json:"status"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ LastReadAt pgtype.Timestamptz `json:"last_read_at"`
+ IsAgentIntro bool `json:"is_agent_intro"`
+ PinnedAt pgtype.Timestamptz `json:"pinned_at"`
}
type Comment struct {
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 0790887024..5168c8beac 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -1,6 +1,6 @@
-- name: CreateChatSession :one
-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id)
-VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2))
+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro)
+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5)
RETURNING *;
-- name: GetChatSession :one
@@ -12,27 +12,77 @@ SELECT * FROM chat_session
WHERE id = $1 AND workspace_id = $2;
-- name: ListChatSessionsByCreator :many
--- Returns active sessions with a boolean unread flag. Unread is strictly
--- per-session: either the user has uncleared assistant replies in this
--- session or they don't. Counting messages would be misleading.
+-- IM-style list: each active session with its unread *count* (assistant
+-- messages after the read cursor), a preview of the latest message, and
+-- ordered by most-recent activity so a new reply bumps a session to the top.
SELECT cs.*,
- (cs.unread_since IS NOT NULL)::bool AS has_unread
+ (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,
+ COALESCE(lm.content, '') AS last_message_content,
+ COALESCE(lm.role, '') AS last_message_role,
+ lm.created_at AS last_message_at,
+ lm.failure_reason AS last_message_failure_reason
FROM chat_session cs
+LEFT JOIN LATERAL (
+ SELECT content, role, created_at, failure_reason
+ FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ ORDER BY m.created_at DESC
+ LIMIT 1
+) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'
-ORDER BY cs.updated_at DESC;
+ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;
-- name: ListAllChatSessionsByCreator :many
SELECT cs.*,
- (cs.unread_since IS NOT NULL)::bool AS has_unread
+ (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,
+ COALESCE(lm.content, '') AS last_message_content,
+ COALESCE(lm.role, '') AS last_message_role,
+ lm.created_at AS last_message_at,
+ lm.failure_reason AS last_message_failure_reason
FROM chat_session cs
+LEFT JOIN LATERAL (
+ SELECT content, role, created_at, failure_reason
+ FROM chat_message m
+ WHERE m.chat_session_id = cs.id
+ ORDER BY m.created_at DESC
+ LIMIT 1
+) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2
-ORDER BY cs.updated_at DESC;
+ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;
-- name: UpdateChatSessionTitle :one
UPDATE chat_session SET title = $2, updated_at = now()
WHERE id = $1
RETURNING *;
+-- name: SetChatSessionPinned :one
+-- Pin/unpin a chat. Deliberately does NOT touch updated_at: pinning is a
+-- list-ordering preference, not activity, so it must not bump the session's
+-- last-activity sort key (which would make an unpinned chat jump the list).
+-- pinned = true stamps pinned_at only when it was NULL, so re-pinning keeps
+-- the original pin order; pinned = false clears it.
+UPDATE chat_session
+SET pinned_at = CASE WHEN @pinned::bool THEN COALESCE(pinned_at, now()) ELSE NULL END
+WHERE id = $1
+RETURNING *;
+
+-- name: SetChatSessionArchived :one
+-- Archive/unarchive a chat session by flipping status between 'active' and
+-- 'archived'. Bumps updated_at so the row re-sorts on the receiving list. The
+-- send-message path refuses archived sessions (see SendChatMessage), so the
+-- conversation is effectively read-only until it is unarchived.
+UPDATE chat_session
+SET status = CASE WHEN @archived::bool THEN 'archived' ELSE 'active' END,
+ updated_at = now()
+WHERE id = $1
+RETURNING *;
+
-- name: UpdateChatSessionSession :exec
-- Updates the resume pointer for a chat session. Empty/NULL inputs are
-- ignored via COALESCE so a task that completes without a session_id (e.g.
@@ -198,17 +248,10 @@ SELECT EXISTS (
) AS has_pending;
-- name: MarkChatSessionRead :exec
--- Clears unread_since, dropping the session's unread count to 0.
-UPDATE chat_session SET unread_since = NULL
+-- Advances the read cursor to now, dropping the session's unread_count to 0.
+UPDATE chat_session SET last_read_at = now()
WHERE id = $1;
--- name: SetUnreadSinceIfNull :exec
--- Atomically stamps the first unread assistant message's arrival time.
--- No-op if the session is already in "has unread" state — keeps the earliest
--- unread boundary stable across multiple incoming replies.
-UPDATE chat_session SET unread_since = now()
-WHERE id = $1 AND unread_since IS NULL;
-
-- name: GetMostRecentUserChatMessage :one
-- Returns the most recent role='user' message in a session. Used by the
-- Lark `/issue` command parser: when the user types `/issue` with no
@@ -219,3 +262,15 @@ SELECT * FROM chat_message
WHERE chat_session_id = $1 AND role = 'user'
ORDER BY created_at DESC
LIMIT 1;
+
+-- name: ChatSessionHasUserMessage :one
+-- Reports whether a session has any human (role='user') message yet. Used to
+-- scope the is_agent_intro self-introduction prompt to the very first,
+-- server-driven turn: an intro session starts with zero user messages, so the
+-- opening run gets the "introduce yourself" prompt. Once the creator replies,
+-- later turns in the same session must fall back to the normal reply prompt
+-- instead of repeating the introduction every turn (MUL-4259).
+SELECT EXISTS (
+ SELECT 1 FROM chat_message
+ WHERE chat_session_id = $1 AND role = 'user'
+) AS has_user_message;
diff --git a/server/pkg/db/queries/chat_pinned_agent.sql b/server/pkg/db/queries/chat_pinned_agent.sql
new file mode 100644
index 0000000000..60927a8f0f
--- /dev/null
+++ b/server/pkg/db/queries/chat_pinned_agent.sql
@@ -0,0 +1,22 @@
+-- name: ListChatPinnedAgents :many
+SELECT * FROM chat_pinned_agent
+WHERE workspace_id = $1 AND user_id = $2
+ORDER BY position ASC, created_at ASC;
+
+-- name: CreateChatPinnedAgent :one
+-- Idempotent: pinning an already-pinned agent is a no-op that returns the
+-- existing row (DO UPDATE keeps `:one` from hitting a no-rows error).
+INSERT INTO chat_pinned_agent (workspace_id, user_id, agent_id, position)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (workspace_id, user_id, agent_id)
+DO UPDATE SET position = chat_pinned_agent.position
+RETURNING *;
+
+-- name: DeleteChatPinnedAgent :exec
+DELETE FROM chat_pinned_agent
+WHERE workspace_id = $1 AND user_id = $2 AND agent_id = $3;
+
+-- name: GetMaxChatPinnedAgentPosition :one
+SELECT COALESCE(MAX(position), 0)::float8 AS max_position
+FROM chat_pinned_agent
+WHERE workspace_id = $1 AND user_id = $2;
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 91552bba7f..85c3ac56c9 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -122,7 +122,13 @@ type ChatSessionDeletedPayload struct {
type ChatSessionUpdatedPayload struct {
ChatSessionID string `json:"chat_session_id"`
Title string `json:"title"`
- UpdatedAt string `json:"updated_at"`
+ // Pinned is set only by the pin/unpin path; nil on a plain rename so a
+ // receiver leaves the existing pin state untouched.
+ Pinned *bool `json:"pinned,omitempty"`
+ // Status is set only by the archive/unarchive path ("active"/"archived");
+ // nil on rename/pin so a receiver leaves the existing status untouched.
+ Status *string `json:"status,omitempty"`
+ UpdatedAt string `json:"updated_at"`
}
// DaemonHeartbeatRequestPayload is sent from daemon to server over WebSocket