Skip to content

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

Go

refactor(chat): extract chat data layer to packages/core/chat

Naiyuan Qingaa6577c5b7ef
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 09bc65e119..9d9dab9b38 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -7,6 +7,7 @@ import { SidebarProvider } from "@multica/ui/components/ui/sidebar";
import { ModalRegistry } from "@multica/views/modals/registry";
import { AppSidebar, DashboardGuard } from "@multica/views/layout";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
+import { ChatFab, ChatWindow } from "@multica/views/chat";
import { DesktopNavigationProvider } from "@/platform/navigation";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { TabBar } from "./tab-bar";
@@ -93,6 +94,8 @@ export function DesktopShell() {
</div>
<ModalRegistry />
<SearchCommand />
+ <ChatWindow />
+ <ChatFab />
</DashboardGuard>
</DesktopNavigationProvider>
);
diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/(dashboard)/layout.tsx
index 72afaa149e..a2ecebf9e6 100644
--- a/apps/web/app/(dashboard)/layout.tsx
+++ b/apps/web/app/(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 "@/features/chat";
+import { ChatFab, ChatWindow } from "@multica/views/chat";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
diff --git a/apps/web/core/chat/ws-updaters.ts b/apps/web/core/chat/ws-updaters.ts
deleted file mode 100644
index e72d0525bd..0000000000
--- a/apps/web/core/chat/ws-updaters.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import type { QueryClient } from "@tanstack/react-query";
-import type { ChatMessage } from "@multica/core/types";
-import { chatKeys } from "./queries";
-
-export function onChatMessageCreated(
- qc: QueryClient,
- sessionId: string,
- message: ChatMessage,
-) {
- qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), (old) => {
- if (!old) return old;
- if (old.some((m) => m.id === message.id)) return old;
- return [...old, message];
- });
-}
-
-export function onChatDone(qc: QueryClient, sessionId: string) {
- qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
-}
diff --git a/apps/web/features/chat/store.ts b/apps/web/features/chat/store.ts
deleted file mode 100644
index fe4df559d5..0000000000
--- a/apps/web/features/chat/store.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { create } from "zustand";
-
-const AGENT_STORAGE_KEY = "multica:chat:selectedAgentId";
-const SESSION_STORAGE_KEY = "multica:chat:activeSessionId";
-
-function readStored(key: string): string | null {
- if (typeof window === "undefined") return null;
- return localStorage.getItem(key);
-}
-
-export interface ChatTimelineItem {
- seq: number;
- type: "tool_use" | "tool_result" | "thinking" | "text" | "error";
- tool?: string;
- content?: string;
- input?: Record<string, unknown>;
- output?: string;
-}
-
-interface ChatState {
- isOpen: boolean;
- isFullscreen: boolean;
- activeSessionId: string | null;
- pendingTaskId: string | null;
- selectedAgentId: string | null;
- showHistory: boolean;
- timelineItems: ChatTimelineItem[];
- setOpen: (open: boolean) => void;
- toggle: () => void;
- toggleFullscreen: () => void;
- setActiveSession: (id: string | null) => void;
- setPendingTask: (taskId: string | null) => void;
- setSelectedAgentId: (id: string) => void;
- setShowHistory: (show: boolean) => void;
- addTimelineItem: (item: ChatTimelineItem) => void;
- clearTimeline: () => void;
-}
-
-export const useChatStore = create<ChatState>((set) => ({
- isOpen: false,
- isFullscreen: false,
- activeSessionId: readStored(SESSION_STORAGE_KEY),
- pendingTaskId: null,
- selectedAgentId: readStored(AGENT_STORAGE_KEY),
- showHistory: false,
- timelineItems: [],
- setOpen: (open) => set({ isOpen: open, ...(open ? {} : { isFullscreen: false }) }),
- toggle: () => set((s) => ({ isOpen: !s.isOpen, ...(s.isOpen ? { isFullscreen: false } : {}) })),
- toggleFullscreen: () => set((s) => ({ isFullscreen: !s.isFullscreen })),
- setActiveSession: (id) => {
- if (id) {
- localStorage.setItem(SESSION_STORAGE_KEY, id);
- } else {
- localStorage.removeItem(SESSION_STORAGE_KEY);
- }
- set({ activeSessionId: id });
- },
- setPendingTask: (taskId) => set({ pendingTaskId: taskId, timelineItems: [] }),
- setSelectedAgentId: (id) => {
- localStorage.setItem(AGENT_STORAGE_KEY, id);
- set({ selectedAgentId: id });
- },
- setShowHistory: (show) => set({ showHistory: show }),
- addTimelineItem: (item) =>
- set((s) => {
- if (s.timelineItems.some((t) => t.seq === item.seq)) return s;
- return {
- timelineItems: [...s.timelineItems, item].sort(
- (a, b) => a.seq - b.seq,
- ),
- };
- }),
- clearTimeline: () => set({ timelineItems: [] }),
-}));
diff --git a/packages/core/chat/index.ts b/packages/core/chat/index.ts
new file mode 100644
index 0000000000..e5c6f068dc
--- /dev/null
+++ b/packages/core/chat/index.ts
@@ -0,0 +1,38 @@
+export { createChatStore } from "./store";
+export type { ChatStoreOptions, ChatState, ChatTimelineItem } from "./store";
+
+import type { createChatStore as CreateChatStoreFn } from "./store";
+
+type ChatStoreInstance = ReturnType<typeof CreateChatStoreFn>;
+
+/** Module-level singleton — set once at app boot via `registerChatStore()`. */
+let _store: ChatStoreInstance | null = null;
+
+/**
+ * Register the chat store instance created by the app.
+ * Must be called at boot before any component renders.
+ */
+export function registerChatStore(store: ChatStoreInstance) {
+ _store = store;
+}
+
+/**
+ * Singleton accessor — a Zustand hook backed by the registered instance.
+ * Supports `useChatStore(selector)` and `useChatStore.getState()`.
+ */
+export const useChatStore: ChatStoreInstance = new Proxy(
+ (() => {}) as unknown as ChatStoreInstance,
+ {
+ apply(_target, _thisArg, args) {
+ if (!_store)
+ throw new Error(
+ "Chat store not initialised — call registerChatStore() first",
+ );
+ return (_store as unknown as (...a: unknown[]) => unknown)(...args);
+ },
+ get(_target, prop) {
+ if (!_store) return undefined;
+ return Reflect.get(_store, prop);
+ },
+ },
+);
diff --git a/apps/web/core/chat/mutations.ts b/packages/core/chat/mutations.ts
similarity index 90%
rename from apps/web/core/chat/mutations.ts
rename to packages/core/chat/mutations.ts
index 3fba0b9b74..2a208919fc 100644
--- a/apps/web/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { api } from "@multica/core/api";
-import { useWorkspaceId } from "@multica/core/hooks";
+import { api } from "../api";
+import { useWorkspaceId } from "../hooks";
import { chatKeys } from "./queries";
export function useCreateChatSession() {
diff --git a/apps/web/core/chat/queries.ts b/packages/core/chat/queries.ts
similarity index 97%
rename from apps/web/core/chat/queries.ts
rename to packages/core/chat/queries.ts
index c9b590cf67..3571fab133 100644
--- a/apps/web/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -1,5 +1,5 @@
import { queryOptions } from "@tanstack/react-query";
-import { api } from "@multica/core/api";
+import { api } from "../api";
export const chatKeys = {
all: (wsId: string) => ["chat", wsId] as const,
diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.ts
new file mode 100644
index 0000000000..3e46ca5e89
--- /dev/null
+++ b/packages/core/chat/store.ts
@@ -0,0 +1,83 @@
+import { create } from "zustand";
+import type { StorageAdapter } from "../types";
+
+const AGENT_STORAGE_KEY = "multica:chat:selectedAgentId";
+const SESSION_STORAGE_KEY = "multica:chat:activeSessionId";
+
+export interface ChatTimelineItem {
+ seq: number;
+ type: "tool_use" | "tool_result" | "thinking" | "text" | "error";
+ tool?: string;
+ content?: string;
+ input?: Record<string, unknown>;
+ output?: string;
+}
+
+export interface ChatState {
+ isOpen: boolean;
+ isFullscreen: boolean;
+ activeSessionId: string | null;
+ pendingTaskId: string | null;
+ selectedAgentId: string | null;
+ showHistory: boolean;
+ timelineItems: ChatTimelineItem[];
+ setOpen: (open: boolean) => void;
+ toggle: () => void;
+ toggleFullscreen: () => void;
+ setActiveSession: (id: string | null) => void;
+ setPendingTask: (taskId: string | null) => void;
+ setSelectedAgentId: (id: string) => void;
+ setShowHistory: (show: boolean) => void;
+ addTimelineItem: (item: ChatTimelineItem) => void;
+ clearTimeline: () => void;
+}
+
+export interface ChatStoreOptions {
+ storage: StorageAdapter;
+}
+
+export function createChatStore(options: ChatStoreOptions) {
+ const { storage } = options;
+
+ return create<ChatState>((set) => ({
+ isOpen: false,
+ isFullscreen: false,
+ activeSessionId: storage.getItem(SESSION_STORAGE_KEY),
+ pendingTaskId: null,
+ selectedAgentId: storage.getItem(AGENT_STORAGE_KEY),
+ showHistory: false,
+ timelineItems: [],
+ setOpen: (open) =>
+ set({ isOpen: open, ...(open ? {} : { isFullscreen: false }) }),
+ toggle: () =>
+ set((s) => ({
+ isOpen: !s.isOpen,
+ ...(s.isOpen ? { isFullscreen: false } : {}),
+ })),
+ toggleFullscreen: () => set((s) => ({ isFullscreen: !s.isFullscreen })),
+ setActiveSession: (id) => {
+ if (id) {
+ storage.setItem(SESSION_STORAGE_KEY, id);
+ } else {
+ storage.removeItem(SESSION_STORAGE_KEY);
+ }
+ set({ activeSessionId: id });
+ },
+ setPendingTask: (taskId) => set({ pendingTaskId: taskId, timelineItems: [] }),
+ setSelectedAgentId: (id) => {
+ storage.setItem(AGENT_STORAGE_KEY, id);
+ set({ selectedAgentId: id });
+ },
+ setShowHistory: (show) => set({ showHistory: show }),
+ addTimelineItem: (item) =>
+ set((s) => {
+ if (s.timelineItems.some((t) => t.seq === item.seq)) return s;
+ return {
+ timelineItems: [...s.timelineItems, item].sort(
+ (a, b) => a.seq - b.seq,
+ ),
+ };
+ }),
+ clearTimeline: () => set({ timelineItems: [] }),
+ }));
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 4c8524a852..f0f4bfedaa 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -34,6 +34,10 @@
"./inbox/queries": "./inbox/queries.ts",
"./inbox/mutations": "./inbox/mutations.ts",
"./inbox/ws-updaters": "./inbox/ws-updaters.ts",
+ "./chat": "./chat/index.ts",
+ "./chat/queries": "./chat/queries.ts",
+ "./chat/mutations": "./chat/mutations.ts",
+ "./chat/store": "./chat/store.ts",
"./runtimes": "./runtimes/index.ts",
"./runtimes/queries": "./runtimes/queries.ts",
"./runtimes/mutations": "./runtimes/mutations.ts",
diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsx
index 6d0ca57942..2bba2d1eec 100644
--- a/packages/core/platform/core-provider.tsx
+++ b/packages/core/platform/core-provider.tsx
@@ -5,6 +5,7 @@ import { ApiClient } from "../api/client";
import { setApiInstance } from "../api";
import { createAuthStore, registerAuthStore } from "../auth";
import { createWorkspaceStore, registerWorkspaceStore } from "../workspace";
+import { createChatStore, registerChatStore } from "../chat";
import { WSProvider } from "../realtime";
import { QueryProvider } from "../provider";
import { createLogger } from "../logger";
@@ -47,6 +48,8 @@ function initCore(
workspaceStore = createWorkspaceStore(api, { storage });
registerWorkspaceStore(workspaceStore);
+ registerChatStore(createChatStore({ storage }));
+
initialized = true;
}
diff --git a/apps/web/features/chat/components/chat-fab.tsx b/packages/views/chat/components/chat-fab.tsx
similarity index 91%
rename from apps/web/features/chat/components/chat-fab.tsx
rename to packages/views/chat/components/chat-fab.tsx
index 4b90c85103..1aca107534 100644
--- a/apps/web/features/chat/components/chat-fab.tsx
+++ b/packages/views/chat/components/chat-fab.tsx
@@ -1,7 +1,7 @@
"use client";
import { Send } from "lucide-react";
-import { useChatStore } from "../store";
+import { useChatStore } from "@multica/core/chat";
export function ChatFab() {
const isOpen = useChatStore((s) => s.isOpen);
diff --git a/apps/web/features/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
similarity index 100%
rename from apps/web/features/chat/components/chat-input.tsx
rename to packages/views/chat/components/chat-input.tsx
diff --git a/apps/web/features/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
similarity index 99%
rename from apps/web/features/chat/components/chat-message-list.tsx
rename to packages/views/chat/components/chat-message-list.tsx
index 8fc88fc2f0..67268e9e96 100644
--- a/apps/web/features/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -13,7 +13,7 @@ import { Bot, Loader2, ChevronRight, ChevronDown, Brain, AlertCircle } from "luc
import { api } from "@multica/core/api";
import { Markdown } from "@multica/views/common/markdown";
import type { ChatMessage, Agent, TaskMessagePayload } from "@multica/core/types";
-import type { ChatTimelineItem } from "../store";
+import type { ChatTimelineItem } from "@multica/core/chat";
// ─── Public component ────────────────────────────────────────────────────
diff --git a/apps/web/features/chat/components/chat-session-history.tsx b/packages/views/chat/components/chat-session-history.tsx
similarity index 97%
rename from apps/web/features/chat/components/chat-session-history.tsx
rename to packages/views/chat/components/chat-session-history.tsx
index 00f5303f66..266f36a236 100644
--- a/apps/web/features/chat/components/chat-session-history.tsx
+++ b/packages/views/chat/components/chat-session-history.tsx
@@ -6,9 +6,9 @@ import { Avatar, AvatarFallback, AvatarImage } from "@multica/ui/components/ui/a
import { Bot } from "lucide-react";
import { useWorkspaceId } from "@multica/core/hooks";
import { agentListOptions } from "@multica/core/workspace/queries";
-import { allChatSessionsOptions } from "@/core/chat/queries";
-import { useArchiveChatSession } from "@/core/chat/mutations";
-import { useChatStore } from "../store";
+import { allChatSessionsOptions } from "@multica/core/chat/queries";
+import { useArchiveChatSession } from "@multica/core/chat/mutations";
+import { useChatStore } from "@multica/core/chat";
import type { ChatSession, Agent } from "@multica/core/types";
export function ChatSessionHistory() {
diff --git a/apps/web/features/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
similarity index 98%
rename from apps/web/features/chat/components/chat-window.tsx
rename to packages/views/chat/components/chat-window.tsx
index 4062ebf4e9..c17aa958cd 100644
--- a/apps/web/features/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -15,9 +15,14 @@ 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 { chatSessionsOptions, allChatSessionsOptions, chatMessagesOptions, chatKeys } from "@/core/chat/queries";
-import { useCreateChatSession } from "@/core/chat/mutations";
-import { useChatStore } from "../store";
+import {
+ chatSessionsOptions,
+ allChatSessionsOptions,
+ chatMessagesOptions,
+ chatKeys,
+} from "@multica/core/chat/queries";
+import { useCreateChatSession } from "@multica/core/chat/mutations";
+import { useChatStore } from "@multica/core/chat";
import { ChatMessageList } from "./chat-message-list";
import { ChatInput } from "./chat-input";
import { ChatSessionHistory } from "./chat-session-history";
@@ -147,7 +152,7 @@ export function ChatWindow() {
unsubCompleted();
unsubFailed();
};
-
+
}, [subscribe, addTimelineItem, clearTimeline, setPendingTask, qc]);
const handleSend = useCallback(
diff --git a/apps/web/features/chat/index.ts b/packages/views/chat/index.ts
similarity index 72%
rename from apps/web/features/chat/index.ts
rename to packages/views/chat/index.ts
index 4a8adad622..04295ff1f8 100644
--- a/apps/web/features/chat/index.ts
+++ b/packages/views/chat/index.ts
@@ -1,3 +1,2 @@
export { ChatFab } from "./components/chat-fab";
export { ChatWindow } from "./components/chat-window";
-export { useChatStore } from "./store";
diff --git a/packages/views/package.json b/packages/views/package.json
index e225ce79af..f962c5573f 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -31,6 +31,7 @@
"./layout": "./layout/index.ts",
"./auth": "./auth/index.ts",
"./search": "./search/index.ts",
+ "./chat": "./chat/index.ts",
"./settings": "./settings/index.ts"
},
"dependencies": {