Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix: pre-resolve merge conflicts with origin/main
Naiyuan Qing79b4c7530305
diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/(dashboard)/layout.tsxindex 6bb3c93cf1..c2c0e4b95d 100644--- a/apps/web/app/(dashboard)/layout.tsx+++ b/apps/web/app/(dashboard)/layout.tsx@@ -1,14 +1,33 @@"use client";+import { Search } from "lucide-react";+import { SidebarMenuButton } from "@multica/ui/components/ui/sidebar";import { DashboardLayout } from "@multica/views/layout";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";-import { SearchCommand } from "@/features/search";+import { SearchCommand, useSearchStore } from "@/features/search";+import { ChatFab, ChatWindow } from "@/features/chat";++function SearchTrigger() {+ return (+ <SidebarMenuButton+ className="text-muted-foreground"+ onClick={() => useSearchStore.getState().setOpen(true)}+ >+ <Search />+ <span>Search...</span>+ <kbd className="pointer-events-none ml-auto inline-flex h-5 select-none items-center gap-0.5 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground">+ <span className="text-xs">⌘</span>K+ </kbd>+ </SidebarMenuButton>+ );+}export default function Layout({ children }: { children: React.ReactNode }) {return (<DashboardLayoutloadingIndicator={<MulticaIcon className="size-6" />}- extra={<SearchCommand />}+ searchSlot={<SearchTrigger />}+ extra={<><SearchCommand /><ChatWindow /><ChatFab /></>}>{children}</DashboardLayout>diff --git a/apps/web/app/globals.css b/apps/web/app/globals.cssindex be5951d722..f184d463c1 100644--- a/apps/web/app/globals.css+++ b/apps/web/app/globals.css@@ -1,12 +1,12 @@@import "tailwindcss";@import "tw-animate-css";@import "shadcn/tailwind.css";-@import "@multica/ui/styles/tokens.css";-@import "@multica/ui/styles/base.css";+@import "../../../packages/ui/styles/tokens.css";+@import "../../../packages/ui/styles/base.css";@import "./custom.css";@custom-variant dark (&:is(.dark *));-@source "../../../packages/ui/**/*.tsx";+@source "../../../packages/ui/**/*.{ts,tsx}";@source "../../../packages/core/**/*.{ts,tsx}";@source "../../../packages/views/**/*.{ts,tsx}";diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsxindex 7c796a921b..090c12b16e 100644--- a/apps/web/app/layout.tsx+++ b/apps/web/app/layout.tsx@@ -38,6 +38,8 @@ export const metadata: Metadata = {},twitter: {card: "summary_large_image",+ site: "@multica_hq",+ creator: "@multica_hq",},alternates: {canonical: "/",diff --git a/apps/web/core/chat/mutations.ts b/apps/web/core/chat/mutations.tsnew file mode 100644index 0000000000..3fba0b9b74--- /dev/null+++ b/apps/web/core/chat/mutations.ts@@ -0,0 +1,31 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "@multica/core/api";+import { useWorkspaceId } from "@multica/core/hooks";+import { chatKeys } from "./queries";++export function useCreateChatSession() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();++ return useMutation({+ mutationFn: (data: { agent_id: string; title?: string }) =>+ api.createChatSession(data),+ onSettled: () => {+ qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });+ qc.invalidateQueries({ queryKey: chatKeys.allSessions(wsId) });+ },+ });+}++export function useArchiveChatSession() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();++ return useMutation({+ mutationFn: (sessionId: string) => api.archiveChatSession(sessionId),+ onSettled: () => {+ qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });+ qc.invalidateQueries({ queryKey: chatKeys.allSessions(wsId) });+ },+ });+}diff --git a/apps/web/core/chat/queries.ts b/apps/web/core/chat/queries.tsnew file mode 100644index 0000000000..c9b590cf67--- /dev/null+++ b/apps/web/core/chat/queries.ts@@ -0,0 +1,44 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "@multica/core/api";++export const chatKeys = {+ all: (wsId: string) => ["chat", wsId] as const,+ sessions: (wsId: string) => [...chatKeys.all(wsId), "sessions"] as const,+ allSessions: (wsId: string) => [...chatKeys.all(wsId), "sessions", "all"] as const,+ session: (wsId: string, id: string) => [...chatKeys.all(wsId), "session", id] as const,+ messages: (sessionId: string) => ["chat", "messages", sessionId] as const,+};++export function chatSessionsOptions(wsId: string) {+ return queryOptions({+ queryKey: chatKeys.sessions(wsId),+ queryFn: () => api.listChatSessions(),+ staleTime: Infinity,+ });+}++export function allChatSessionsOptions(wsId: string) {+ return queryOptions({+ queryKey: chatKeys.allSessions(wsId),+ queryFn: () => api.listChatSessions({ status: "all" }),+ staleTime: Infinity,+ });+}++export function chatSessionOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: chatKeys.session(wsId, id),+ queryFn: () => api.getChatSession(id),+ enabled: !!id,+ staleTime: Infinity,+ });+}++export function chatMessagesOptions(sessionId: string) {+ return queryOptions({+ queryKey: chatKeys.messages(sessionId),+ queryFn: () => api.listChatMessages(sessionId),+ enabled: !!sessionId,+ staleTime: Infinity,+ });+}diff --git a/apps/web/core/chat/ws-updaters.ts b/apps/web/core/chat/ws-updaters.tsnew file mode 100644index 0000000000..e72d0525bd--- /dev/null+++ b/apps/web/core/chat/ws-updaters.ts@@ -0,0 +1,19 @@+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/components/chat-fab.tsx b/apps/web/features/chat/components/chat-fab.tsxnew file mode 100644index 0000000000..4b90c85103--- /dev/null+++ b/apps/web/features/chat/components/chat-fab.tsx@@ -0,0 +1,21 @@+"use client";++import { Send } from "lucide-react";+import { useChatStore } from "../store";++export function ChatFab() {+ const isOpen = useChatStore((s) => s.isOpen);+ const toggle = useChatStore((s) => s.toggle);++ if (isOpen) return null;++ return (+ <button+ onClick={toggle}+ className="fixed bottom-4 right-4 z-50 flex items-center gap-2 rounded-full border bg-background px-4 py-2 text-sm font-medium text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ <Send className="size-3.5" />+ Ask Multica+ </button>+ );+}diff --git a/apps/web/features/chat/components/chat-input.tsx b/apps/web/features/chat/components/chat-input.tsxnew file mode 100644index 0000000000..60df43572b--- /dev/null+++ b/apps/web/features/chat/components/chat-input.tsx@@ -0,0 +1,82 @@+"use client";++import { useState, useRef, useCallback } from "react";+import { ArrowUp, Square } from "lucide-react";++interface ChatInputProps {+ onSend: (content: string) => void;+ onStop?: () => void;+ isRunning?: boolean;+ disabled?: boolean;+}++export function ChatInput({ onSend, onStop, isRunning, disabled }: ChatInputProps) {+ const [value, setValue] = useState("");+ const textareaRef = useRef<HTMLTextAreaElement>(null);++ const handleSend = useCallback(() => {+ const trimmed = value.trim();+ if (!trimmed || isRunning || disabled) return;+ onSend(trimmed);+ setValue("");+ if (textareaRef.current) {+ textareaRef.current.style.height = "auto";+ }+ textareaRef.current?.focus();+ }, [value, isRunning, disabled, onSend]);++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ handleSend();+ }+ },+ [handleSend],+ );++ const handleInput = useCallback(() => {+ const el = textareaRef.current;+ if (!el) return;+ el.style.height = "auto";+ el.style.height = Math.min(el.scrollHeight, 120) + "px";+ }, []);++ return (+ <div className="border-t bg-muted/30 p-3">+ <div className="rounded-lg border bg-background">+ <textarea+ ref={textareaRef}+ value={value}+ onChange={(e) => {+ setValue(e.target.value);+ handleInput();+ }}+ onKeyDown={handleKeyDown}+ placeholder={disabled ? "This session is archived" : "Ask Multica..."}+ disabled={isRunning || disabled}+ className="block w-full resize-none bg-transparent px-3 pt-3 pb-2 text-sm placeholder:text-muted-foreground focus:outline-none disabled:opacity-50"+ rows={1}+ />+ <div className="flex items-center justify-end px-2 pb-2">+ {isRunning ? (+ <button+ onClick={onStop}+ className="flex size-7 items-center justify-center rounded-full bg-foreground text-background transition-opacity hover:opacity-80"+ >+ <Square className="size-3 fill-current" />+ </button>+ ) : (+ <button+ onClick={handleSend}+ disabled={!value.trim() || disabled}+ className="flex size-7 items-center justify-center rounded-full bg-foreground text-background transition-opacity hover:opacity-80 disabled:opacity-30"+ >+ <ArrowUp className="size-4" />+ </button>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/features/chat/components/chat-message-list.tsx b/apps/web/features/chat/components/chat-message-list.tsxnew file mode 100644index 0000000000..8fc88fc2f0--- /dev/null+++ b/apps/web/features/chat/components/chat-message-list.tsx@@ -0,0 +1,368 @@+"use client";++import { useState, useEffect, useRef } from "react";+import { useQuery } from "@tanstack/react-query";+import { cn } from "@multica/ui/lib/utils";+import { Avatar, AvatarFallback, AvatarImage } from "@multica/ui/components/ui/avatar";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@multica/ui/components/ui/collapsible";+import { Bot, Loader2, ChevronRight, ChevronDown, Brain, AlertCircle } from "lucide-react";+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";++// ─── Public component ────────────────────────────────────────────────────++interface ChatMessageListProps {+ messages: ChatMessage[];+ agent: Agent | null;+ timelineItems: ChatTimelineItem[];+ isWaiting: boolean;+}++export function ChatMessageList({+ messages,+ agent,+ timelineItems,+ isWaiting,+}: ChatMessageListProps) {+ const bottomRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ bottomRef.current?.scrollIntoView({ behavior: "smooth" });+ }, [messages, timelineItems]);++ const hasTimeline = timelineItems.length > 0;++ return (+ <div className="flex-1 overflow-y-auto px-4 py-3 space-y-4">+ {messages.map((msg) => (+ <MessageBubble key={msg.id} message={msg} agent={agent} />+ ))}+ {/* Live streaming timeline */}+ {hasTimeline && (+ <div className="flex items-start gap-3">+ <AgentAvatar agent={agent} />+ <div className="min-w-0 flex-1 space-y-1.5">+ <TimelineView items={timelineItems} />+ </div>+ </div>+ )}+ {isWaiting && !hasTimeline && (+ <div className="flex items-start gap-3">+ <AgentAvatar agent={agent} />+ <div className="flex items-center pt-1">+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ </div>+ </div>+ )}+ <div ref={bottomRef} />+ </div>+ );+}++// ─── Message bubbles ─────────────────────────────────────────────────────++function MessageBubble({+ message,+ agent,+}: {+ message: ChatMessage;+ agent: Agent | null;+}) {+ if (message.role === "user") {+ return (+ <div className="flex justify-end">+ <div className="rounded-2xl bg-primary px-3.5 py-2 text-sm text-primary-foreground max-w-[85%]">+ {message.content}+ </div>+ </div>+ );+ }++ return <AssistantMessage message={message} agent={agent} />;+}++function AssistantMessage({+ message,+ agent,+}: {+ message: ChatMessage;+ agent: Agent | null;+}) {+ const taskId = message.task_id;++ // Always fetch task messages for assistant messages with a task_id+ const { data: taskMessages } = useQuery({+ queryKey: ["task-messages", taskId],+ queryFn: () => api.listTaskMessages(taskId!),+ enabled: !!taskId,+ staleTime: Infinity,+ });++ const timeline: ChatTimelineItem[] = (taskMessages ?? []).map(+ (m: TaskMessagePayload) => ({+ seq: m.seq,+ type: m.type,+ tool: m.tool,+ content: m.content,+ input: m.input,+ output: m.output,+ }),+ );++ return (+ <div className="flex items-start gap-3">+ <AgentAvatar agent={agent} />+ <div className="min-w-0 flex-1 space-y-1.5">+ {timeline.length > 0 ? (+ <TimelineView items={timeline} />+ ) : (+ <div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">+ <Markdown>{message.content}</Markdown>+ </div>+ )}+ </div>+ </div>+ );+}++// ─── Timeline: flat interleaved text + collapsible tool groups ───────────++interface TimelineSegment {+ kind: "text" | "tools";+ items: ChatTimelineItem[];+}++/** Split items into segments: consecutive non-text → "tools", consecutive text → merged "text". */+function segmentTimeline(items: ChatTimelineItem[]): TimelineSegment[] {+ const segments: TimelineSegment[] = [];+ let toolBuf: ChatTimelineItem[] = [];+ let textBuf: ChatTimelineItem[] = [];++ const flushTools = () => {+ if (toolBuf.length > 0) {+ segments.push({ kind: "tools", items: toolBuf });+ toolBuf = [];+ }+ };++ const flushText = () => {+ if (textBuf.length > 0) {+ segments.push({ kind: "text", items: textBuf });+ textBuf = [];+ }+ };++ for (const item of items) {+ if (item.type === "text") {+ flushTools();+ textBuf.push(item);+ } else {+ flushText();+ toolBuf.push(item);+ }+ }+ flushText();+ flushTools();+ return segments;+}++function TimelineView({ items }: { items: ChatTimelineItem[] }) {+ const segments = segmentTimeline(items);++ return (+ <>+ {segments.map((seg, i) =>+ seg.kind === "text" ? (+ <div key={seg.items[0]!.seq} className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">+ <Markdown>{seg.items.map((t) => t.content ?? "").join("")}</Markdown>+ </div>+ ) : (+ <ToolGroupCollapsible+ key={seg.items[0]!.seq}+ items={seg.items}+ defaultOpen={i === segments.length - 1}+ />+ ),+ )}+ </>+ );+}++function ToolGroupCollapsible({+ items,+ defaultOpen,+}: {+ items: ChatTimelineItem[];+ defaultOpen?: boolean;+}) {+ const [open, setOpen] = useState(defaultOpen ?? false);+ const toolCount = items.filter((i) => i.type === "tool_use").length;+ const label = `${toolCount} ${toolCount === 1 ? "tool" : "tools"}`;++ return (+ <Collapsible open={open} onOpenChange={setOpen}>+ <CollapsibleTrigger className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors">+ {open ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}+ <span>{label}</span>+ </CollapsibleTrigger>+ <CollapsibleContent>+ <div className="mt-1 rounded-lg border bg-muted/20 p-2 space-y-0.5">+ {items.map((item) => (+ <ItemRow key={item.seq} item={item} />+ ))}+ </div>+ </CollapsibleContent>+ </Collapsible>+ );+}++// ─── Individual item rows ────────────────────────────────────────────────++function ItemRow({ item }: { item: ChatTimelineItem }) {+ switch (item.type) {+ case "tool_use":+ return <ToolCallRow item={item} />;+ case "tool_result":+ return <ToolResultRow item={item} />;+ case "thinking":+ return <ThinkingRow item={item} />;+ case "error":+ return <ErrorRow item={item} />;+ default:+ return null;+ }+}++function shortenPath(p: string): string {+ const parts = p.split("/");+ if (parts.length <= 3) return p;+ return ".../" + parts.slice(-2).join("/");+}++function getToolSummary(item: ChatTimelineItem): string {+ if (!item.input) return "";+ const inp = item.input as Record<string, string>;+ if (inp.query) return inp.query;+ if (inp.file_path) return shortenPath(inp.file_path);+ if (inp.path) return shortenPath(inp.path);+ if (inp.pattern) return inp.pattern;+ if (inp.description) return String(inp.description);+ if (inp.command) {+ const cmd = String(inp.command);+ return cmd.length > 100 ? cmd.slice(0, 100) + "..." : cmd;+ }+ if (inp.prompt) {+ const p = String(inp.prompt);+ return p.length > 100 ? p.slice(0, 100) + "..." : p;+ }+ if (inp.skill) return String(inp.skill);+ for (const v of Object.values(inp)) {+ if (typeof v === "string" && v.length > 0 && v.length < 120) return v;+ }+ return "";+}++function ToolCallRow({ item }: { item: ChatTimelineItem }) {+ const [open, setOpen] = useState(false);+ const summary = getToolSummary(item);+ const hasInput = item.input && Object.keys(item.input).length > 0;++ return (+ <Collapsible open={open} onOpenChange={setOpen}>+ <CollapsibleTrigger className="flex w-full items-center gap-1.5 rounded px-1 -mx-1 py-0.5 text-xs hover:bg-accent/30 transition-colors">+ <ChevronRight+ className={cn(+ "h-3 w-3 shrink-0 text-muted-foreground transition-transform",+ open && "rotate-90",+ !hasInput && "invisible",+ )}+ />+ <span className="font-medium text-foreground shrink-0">{item.tool}</span>+ {summary && <span className="truncate text-muted-foreground">{summary}</span>}+ </CollapsibleTrigger>+ {hasInput && (+ <CollapsibleContent>+ <pre className="ml-[18px] mt-0.5 max-h-32 overflow-auto rounded bg-muted/50 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-all">+ {JSON.stringify(item.input, null, 2)}+ </pre>+ </CollapsibleContent>+ )}+ </Collapsible>+ );+}++function ToolResultRow({ item }: { item: ChatTimelineItem }) {+ const [open, setOpen] = useState(false);+ const output = item.output ?? "";+ if (!output) return null;++ const preview = output.length > 120 ? output.slice(0, 120) + "..." : output;++ return (+ <Collapsible open={open} onOpenChange={setOpen}>+ <CollapsibleTrigger className="flex w-full items-start gap-1.5 rounded px-1 -mx-1 py-0.5 text-xs hover:bg-accent/30 transition-colors">+ <ChevronRight+ className={cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform mt-0.5", open && "rotate-90")}+ />+ <span className="text-muted-foreground/70 truncate">+ {item.tool ? `${item.tool} result: ` : "result: "}{preview}+ </span>+ </CollapsibleTrigger>+ <CollapsibleContent>+ <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-muted/50 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-all">+ {output.length > 4000 ? output.slice(0, 4000) + "\n... (truncated)" : output}+ </pre>+ </CollapsibleContent>+ </Collapsible>+ );+}++function ThinkingRow({ item }: { item: ChatTimelineItem }) {+ const [open, setOpen] = useState(false);+ const text = item.content ?? "";+ if (!text) return null;++ const preview = text.length > 150 ? text.slice(0, 150) + "..." : text;++ return (+ <Collapsible open={open} onOpenChange={setOpen}>+ <CollapsibleTrigger className="flex w-full items-start gap-1.5 rounded px-1 -mx-1 py-0.5 text-xs hover:bg-accent/30 transition-colors">+ <Brain className="h-3 w-3 shrink-0 text-muted-foreground/60 mt-0.5" />+ <span className="text-muted-foreground italic truncate">{preview}</span>+ </CollapsibleTrigger>+ <CollapsibleContent>+ <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-muted/30 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-words">+ {text}+ </pre>+ </CollapsibleContent>+ </Collapsible>+ );+}++function ErrorRow({ item }: { item: ChatTimelineItem }) {+ return (+ <div className="flex items-start gap-1.5 px-1 -mx-1 py-0.5 text-xs">+ <AlertCircle className="h-3 w-3 shrink-0 text-destructive mt-0.5" />+ <span className="text-destructive">{item.content}</span>+ </div>+ );+}++// ─── Shared ──────────────────────────────────────────────────────────────++function AgentAvatar({ agent }: { agent: Agent | null }) {+ return (+ <Avatar className="size-6 shrink-0 mt-0.5">+ {agent?.avatar_url && <AvatarImage src={agent.avatar_url} />}+ <AvatarFallback className="bg-purple-100 text-purple-700">+ <Bot className="size-3" />+ </AvatarFallback>+ </Avatar>+ );+}diff --git a/apps/web/features/chat/components/chat-session-history.tsx b/apps/web/features/chat/components/chat-session-history.tsxnew file mode 100644index 0000000000..00f5303f66--- /dev/null+++ b/apps/web/features/chat/components/chat-session-history.tsx@@ -0,0 +1,202 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { ArrowLeft, MessageSquare, Archive, Trash2 } from "lucide-react";+import { Avatar, AvatarFallback, AvatarImage } from "@multica/ui/components/ui/avatar";+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 type { ChatSession, Agent } from "@multica/core/types";++export function ChatSessionHistory() {+ const wsId = useWorkspaceId();+ const setShowHistory = useChatStore((s) => s.setShowHistory);+ const setActiveSession = useChatStore((s) => s.setActiveSession);+ const clearTimeline = useChatStore((s) => s.clearTimeline);+ const setPendingTask = useChatStore((s) => s.setPendingTask);+ const activeSessionId = useChatStore((s) => s.activeSessionId);++ const { data: sessions = [] } = useQuery(allChatSessionsOptions(wsId));+ const { data: agents = [] } = useQuery(agentListOptions(wsId));+ const archiveSession = useArchiveChatSession();++ const agentMap = new Map(agents.map((a) => [a.id, a]));++ const handleSelectSession = (session: ChatSession) => {+ setActiveSession(session.id);+ clearTimeline();+ setPendingTask(null);+ setShowHistory(false);+ };++ const handleArchive = (e: React.MouseEvent, sessionId: string) => {+ e.stopPropagation();+ archiveSession.mutate(sessionId);+ if (activeSessionId === sessionId) {+ setActiveSession(null);+ }+ };++ const activeSessions = sessions.filter((s) => s.status === "active");+ const archivedSessions = sessions.filter((s) => s.status === "archived");++ return (+ <div className="flex flex-1 flex-col overflow-hidden">+ {/* Header */}+ <div className="flex items-center gap-2 border-b px-4 py-2.5">+ <button+ onClick={() => setShowHistory(false)}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ <ArrowLeft className="size-3.5" />+ </button>+ <span className="text-sm font-medium">Chat History</span>+ </div>++ {/* Session list */}+ <div className="flex-1 overflow-y-auto">+ {sessions.length === 0 ? (+ <div className="flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground">+ <MessageSquare className="size-6" />+ <span className="text-sm">No chat sessions yet</span>+ </div>+ ) : (+ <>+ {activeSessions.length > 0 && (+ <SessionGroup+ label="Active"+ sessions={activeSessions}+ agentMap={agentMap}+ activeSessionId={activeSessionId}+ onSelect={handleSelectSession}+ onArchive={handleArchive}+ />+ )}+ {archivedSessions.length > 0 && (+ <SessionGroup+ label="Archived"+ sessions={archivedSessions}+ agentMap={agentMap}+ activeSessionId={activeSessionId}+ onSelect={handleSelectSession}+ />+ )}+ </>+ )}+ </div>+ </div>+ );+}++function SessionGroup({+ label,+ sessions,+ agentMap,+ activeSessionId,+ onSelect,+ onArchive,+}: {+ label: string;+ sessions: ChatSession[];+ agentMap: Map<string, Agent>;+ activeSessionId: string | null;+ onSelect: (session: ChatSession) => void;+ onArchive?: (e: React.MouseEvent, sessionId: string) => void;+}) {+ return (+ <div>+ <div className="px-4 pt-3 pb-1">+ <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">+ {label}+ </span>+ </div>+ {sessions.map((session) => (+ <SessionItem+ key={session.id}+ session={session}+ agent={agentMap.get(session.agent_id) ?? null}+ isActive={session.id === activeSessionId}+ onSelect={() => onSelect(session)}+ onArchive={onArchive ? (e) => onArchive(e, session.id) : undefined}+ />+ ))}+ </div>+ );+}++function SessionItem({+ session,+ agent,+ isActive,+ onSelect,+ onArchive,+}: {+ session: ChatSession;+ agent: Agent | null;+ isActive: boolean;+ onSelect: () => void;+ onArchive?: (e: React.MouseEvent) => void;+}) {+ const timeAgo = formatTimeAgo(session.updated_at);++ return (+ <button+ onClick={onSelect}+ className={`group flex w-full items-start gap-3 px-4 py-2.5 text-left transition-colors hover:bg-accent/50 ${+ isActive ? "bg-accent/30" : ""+ }`}+ >+ <Avatar className="size-6 shrink-0 mt-0.5">+ {agent?.avatar_url && <AvatarImage src={agent.avatar_url} />}+ <AvatarFallback className="bg-purple-100 text-purple-700 text-[10px]">+ <Bot className="size-3" />+ </AvatarFallback>+ </Avatar>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-sm font-medium">+ {session.title || "Untitled"}+ </span>+ {session.status === "archived" && (+ <Archive className="size-3 shrink-0 text-muted-foreground" />+ )}+ </div>+ <div className="flex items-center gap-1.5 mt-0.5">+ {agent && (+ <span className="text-xs text-muted-foreground truncate">+ {agent.name}+ </span>+ )}+ <span className="text-xs text-muted-foreground/60">{timeAgo}</span>+ </div>+ </div>+ {onArchive && (+ <button+ onClick={onArchive}+ title="Archive"+ className="invisible group-hover:visible flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-destructive shrink-0 mt-0.5"+ >+ <Trash2 className="size-3" />+ </button>+ )}+ </button>+ );+}++function formatTimeAgo(dateStr: string): string {+ const date = new Date(dateStr);+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMins = Math.floor(diffMs / 60000);+ const diffHours = Math.floor(diffMs / 3600000);+ const diffDays = Math.floor(diffMs / 86400000);++ if (diffMins < 1) return "just now";+ if (diffMins < 60) return `${diffMins}m ago`;+ if (diffHours < 24) return `${diffHours}h ago`;+ if (diffDays < 7) return `${diffDays}d ago`;+ return date.toLocaleDateString();+}diff --git a/apps/web/features/chat/components/chat-window.tsx b/apps/web/features/chat/components/chat-window.tsxnew file mode 100644index 0000000000..3d972fc9fd--- /dev/null+++ b/apps/web/features/chat/components/chat-window.tsx@@ -0,0 +1,373 @@+"use client";++import { useCallback, useEffect, useRef } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { Minus, Maximize2, Minimize2, Send, ChevronDown, Bot, Plus, History } from "lucide-react";+import { Avatar, AvatarFallback, AvatarImage } from "@multica/ui/components/ui/avatar";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+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 { chatSessionsOptions, allChatSessionsOptions, chatMessagesOptions, chatKeys } from "@/core/chat/queries";+import { useCreateChatSession } from "@/core/chat/mutations";+import { useChatStore } from "../store";+import { ChatMessageList } from "./chat-message-list";+import { ChatInput } from "./chat-input";+import { ChatSessionHistory } from "./chat-session-history";+import { useWS } from "@multica/core/realtime";+import type { TaskMessagePayload, ChatDonePayload, Agent, ChatMessage } from "@multica/core/types";++export function ChatWindow() {+ const wsId = useWorkspaceId();+ const isOpen = useChatStore((s) => s.isOpen);+ const isFullscreen = useChatStore((s) => s.isFullscreen);+ const activeSessionId = useChatStore((s) => s.activeSessionId);+ const pendingTaskId = useChatStore((s) => s.pendingTaskId);+ const timelineItems = useChatStore((s) => s.timelineItems);+ const selectedAgentId = useChatStore((s) => s.selectedAgentId);+ const setOpen = useChatStore((s) => s.setOpen);+ const toggleFullscreen = useChatStore((s) => s.toggleFullscreen);+ const showHistory = useChatStore((s) => s.showHistory);+ const setActiveSession = useChatStore((s) => s.setActiveSession);+ const setPendingTask = useChatStore((s) => s.setPendingTask);+ const addTimelineItem = useChatStore((s) => s.addTimelineItem);+ const clearTimeline = useChatStore((s) => s.clearTimeline);+ const setSelectedAgentId = useChatStore((s) => s.setSelectedAgentId);+ const setShowHistory = useChatStore((s) => s.setShowHistory);++ const user = useAuthStore((s) => s.user);+ const { data: agents = [] } = useQuery(agentListOptions(wsId));+ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const { data: sessions = [] } = useQuery(chatSessionsOptions(wsId));+ const { data: allSessions = [] } = useQuery(allChatSessionsOptions(wsId));+ const { data: rawMessages } = useQuery(+ chatMessagesOptions(activeSessionId ?? ""),+ );+ // When no active session, always show empty — don't use stale cache+ const messages = activeSessionId ? rawMessages ?? [] : [];++ // Check if current session is archived+ const currentSession = activeSessionId+ ? allSessions.find((s) => s.id === activeSessionId)+ : null;+ const isSessionArchived = currentSession?.status === "archived";++ const qc = useQueryClient();+ const createSession = useCreateChatSession();++ 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),+ );++ // Resolve selected agent: stored preference → first available+ const activeAgent =+ availableAgents.find((a) => a.id === selectedAgentId) ??+ availableAgents[0] ??+ null;++ // Auto-restore most recent active session from server (only once on mount)+ const didRestoreRef = useRef(false);+ useEffect(() => {+ if (didRestoreRef.current) return;+ didRestoreRef.current = true;+ if (activeSessionId || sessions.length === 0) return;+ const latest = sessions.find((s) => s.status === "active");+ if (latest) {+ setActiveSession(latest.id);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps -- run once when sessions load+ }, [sessions]);++ // Use ref for pendingTaskId so WS handlers always see the latest value+ // without needing to re-subscribe on every change.+ const pendingTaskRef = useRef<string | null>(pendingTaskId);+ pendingTaskRef.current = pendingTaskId;++ const { subscribe } = useWS();++ useEffect(() => {+ const unsubMessage = subscribe("task:message", (payload) => {+ const p = payload as TaskMessagePayload;+ if (!pendingTaskRef.current || p.task_id !== pendingTaskRef.current) return;+ addTimelineItem({+ seq: p.seq,+ type: p.type,+ tool: p.tool,+ content: p.content,+ input: p.input,+ output: p.output,+ });+ });++ const unsubDone = subscribe("chat:done", (payload) => {+ const p = payload as ChatDonePayload;+ if (!pendingTaskRef.current || p.task_id !== pendingTaskRef.current) return;+ const activeSessionId = useChatStore.getState().activeSessionId;+ if (activeSessionId) {+ qc.invalidateQueries({+ queryKey: chatKeys.messages(activeSessionId),+ });+ }+ clearTimeline();+ setPendingTask(null);+ });++ const unsubCompleted = subscribe("task:completed", (payload) => {+ const p = payload as { task_id: string };+ if (!pendingTaskRef.current || p.task_id !== pendingTaskRef.current) return;+ const activeSessionId = useChatStore.getState().activeSessionId;+ if (activeSessionId) {+ qc.invalidateQueries({+ queryKey: chatKeys.messages(activeSessionId),+ });+ }+ clearTimeline();+ setPendingTask(null);+ });++ const unsubFailed = subscribe("task:failed", (payload) => {+ const p = payload as { task_id: string };+ if (!pendingTaskRef.current || p.task_id !== pendingTaskRef.current) return;+ clearTimeline();+ setPendingTask(null);+ });++ return () => {+ unsubMessage();+ unsubDone();+ unsubCompleted();+ unsubFailed();+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps -- refs + stable store actions, subscribe once+ }, [subscribe, addTimelineItem, clearTimeline, setPendingTask, qc]);++ const handleSend = useCallback(+ async (content: string) => {+ if (!activeAgent) return;++ let sessionId = activeSessionId;++ if (!sessionId) {+ const session = await createSession.mutateAsync({+ agent_id: activeAgent.id,+ title: content.slice(0, 50),+ });+ sessionId = session.id;+ setActiveSession(sessionId);+ }++ // Optimistic: show user message immediately.+ const optimistic: ChatMessage = {+ id: `optimistic-${Date.now()}`,+ chat_session_id: sessionId,+ role: "user",+ content,+ task_id: null,+ created_at: new Date().toISOString(),+ };+ qc.setQueryData<ChatMessage[]>(+ chatKeys.messages(sessionId),+ (old) => (old ? [...old, optimistic] : [optimistic]),+ );++ const result = await api.sendChatMessage(sessionId, content);+ setPendingTask(result.task_id);+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });+ },+ [+ activeSessionId,+ activeAgent,+ createSession,+ setActiveSession,+ setPendingTask,+ qc,+ ],+ );++ const handleStop = useCallback(async () => {+ if (!pendingTaskId) return;+ try {+ await api.cancelTaskById(pendingTaskId);+ } catch {+ // Task may already be completed+ }+ if (activeSessionId) {+ qc.invalidateQueries({ queryKey: chatKeys.messages(activeSessionId) });+ }+ clearTimeline();+ setPendingTask(null);+ }, [pendingTaskId, activeSessionId, clearTimeline, setPendingTask, qc]);++ const handleSelectAgent = useCallback(+ (agent: Agent) => {+ setSelectedAgentId(agent.id);+ // Reset session when switching agent+ setActiveSession(null);+ },+ [setSelectedAgentId, setActiveSession],+ );++ if (!isOpen) return null;++ const hasMessages = messages.length > 0 || timelineItems.length > 0;++ const containerClass = isFullscreen+ ? "fixed inset-y-0 right-0 z-50 flex flex-col w-[50%] border-l bg-background shadow-2xl"+ : "fixed bottom-4 right-4 z-50 flex flex-col w-[420px] h-[600px] rounded-xl border bg-background shadow-2xl overflow-hidden";++ return (+ <div className={containerClass}>+ {/* Header */}+ {!showHistory && (+ <div className="flex items-center justify-between border-b px-4 py-2.5">+ <AgentSelector+ agents={availableAgents}+ activeAgent={activeAgent}+ onSelect={handleSelectAgent}+ />+ <div className="flex items-center gap-0.5">+ <button+ onClick={() => setShowHistory(true)}+ title="Chat history"+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ <History className="size-3.5" />+ </button>+ <button+ onClick={() => {+ setActiveSession(null);+ clearTimeline();+ setPendingTask(null);+ }}+ title="New chat"+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ <Plus className="size-3.5" />+ </button>+ <button+ onClick={toggleFullscreen}+ title={isFullscreen ? "Exit fullscreen" : "Fullscreen"}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ {isFullscreen ? <Minimize2 className="size-3.5" /> : <Maximize2 className="size-3.5" />}+ </button>+ <button+ onClick={() => setOpen(false)}+ title="Minimize"+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"+ >+ <Minus className="size-3.5" />+ </button>+ </div>+ </div>+ )}++ {showHistory ? (+ <ChatSessionHistory />+ ) : (+ <>+ {/* Messages or Empty State */}+ {hasMessages ? (+ <ChatMessageList+ messages={messages}+ agent={activeAgent}+ timelineItems={timelineItems}+ isWaiting={!!pendingTaskId}+ />+ ) : (+ <EmptyState agentName={activeAgent?.name} />+ )}++ {/* Input — disabled for archived sessions */}+ <ChatInput+ onSend={handleSend}+ onStop={handleStop}+ isRunning={!!pendingTaskId}+ disabled={isSessionArchived}+ />+ </>+ )}+ </div>+ );+}++function AgentSelector({+ agents,+ activeAgent,+ onSelect,+}: {+ agents: Agent[];+ activeAgent: Agent | null;+ onSelect: (agent: Agent) => void;+}) {+ if (!activeAgent) {+ return <span className="text-sm text-muted-foreground">No agents</span>;+ }++ if (agents.length <= 1) {+ return (+ <div className="flex items-center gap-2">+ <AgentAvatarSmall agent={activeAgent} />+ <span className="text-sm font-medium">{activeAgent.name}</span>+ </div>+ );+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger className="flex items-center gap-2 rounded-md px-1.5 py-1 -ml-1.5 transition-colors hover:bg-accent">+ <AgentAvatarSmall agent={activeAgent} />+ <span className="text-sm font-medium">{activeAgent.name}</span>+ <ChevronDown className="size-3 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ {agents.map((agent) => (+ <DropdownMenuItem+ key={agent.id}+ onClick={() => onSelect(agent)}+ className="flex items-center gap-2"+ >+ <AgentAvatarSmall agent={agent} />+ <span>{agent.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function AgentAvatarSmall({ agent }: { agent: Agent }) {+ return (+ <Avatar className="size-5">+ {agent.avatar_url && <AvatarImage src={agent.avatar_url} />}+ <AvatarFallback className="bg-purple-100 text-purple-700 text-[10px]">+ <Bot className="size-3" />+ </AvatarFallback>+ </Avatar>+ );+}++function EmptyState({ agentName }: { agentName?: string }) {+ return (+ <div className="flex flex-1 flex-col items-center justify-center gap-4 px-8">+ <Send className="size-8 text-muted-foreground/50" />+ <div className="text-center">+ <h3 className="text-base font-semibold">Welcome to Multica</h3>+ <p className="mt-1 text-sm text-muted-foreground">+ {agentName+ ? `Chat with ${agentName} or ask anything`+ : "Ask anything or tell Multica what you need"}+ </p>+ </div>+ </div>+ );+}diff --git a/apps/web/features/chat/index.ts b/apps/web/features/chat/index.tsnew file mode 100644index 0000000000..4a8adad622--- /dev/null+++ b/apps/web/features/chat/index.ts@@ -0,0 +1,3 @@+export { ChatFab } from "./components/chat-fab";+export { ChatWindow } from "./components/chat-window";+export { useChatStore } from "./store";diff --git a/apps/web/features/chat/store.ts b/apps/web/features/chat/store.tsnew file mode 100644index 0000000000..fe4df559d5--- /dev/null+++ b/apps/web/features/chat/store.ts@@ -0,0 +1,74 @@+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/apps/web/features/landing/components/landing-footer.tsx b/apps/web/features/landing/components/landing-footer.tsxindex db9aa4c5dd..94649a90f4 100644--- a/apps/web/features/landing/components/landing-footer.tsx+++ b/apps/web/features/landing/components/landing-footer.tsx@@ -4,6 +4,7 @@ import Link from "next/link";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";import { cn } from "@multica/ui/lib/utils";import { useAuthStore } from "@multica/core/auth";+import { XMark, GitHubMark, githubUrl, twitterUrl } from "./shared";import { useLocale, locales, localeLabels } from "../i18n";export function LandingFooter() {@@ -27,6 +28,24 @@ export function LandingFooter() {<p className="mt-4 max-w-[300px] text-[14px] leading-[1.7] text-white/50 sm:text-[15px]">{t.footer.tagline}</p>+ <div className="mt-4 flex items-center gap-3">+ <Link+ href={twitterUrl}+ target="_blank"+ rel="noreferrer"+ className="text-white/40 transition-colors hover:text-white"+ >+ <XMark className="size-4" />+ </Link>+ <Link+ href={githubUrl}+ target="_blank"+ rel="noreferrer"+ className="text-white/40 transition-colors hover:text-white"+ >+ <GitHubMark className="size-4" />+ </Link>+ </div><div className="mt-6"><Linkhref={user ? "/issues" : "/login"}diff --git a/apps/web/features/landing/components/shared.tsx b/apps/web/features/landing/components/shared.tsxindex dd51102ea0..2e0903b3d0 100644--- a/apps/web/features/landing/components/shared.tsx+++ b/apps/web/features/landing/components/shared.tsx@@ -1,6 +1,7 @@import { cn } from "@multica/ui/lib/utils";export const githubUrl = "https://github.com/multica-ai/multica";+export const twitterUrl = "https://x.com/multica_hq";export function GitHubMark({ className }: { className?: string }) {return (@@ -15,6 +16,19 @@ export function GitHubMark({ className }: { className?: string }) {);}+export function XMark({ className }: { className?: string }) {+ return (+ <svg+ viewBox="0 0 24 24"+ aria-hidden="true"+ className={className}+ fill="currentColor"+ >+ <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />+ </svg>+ );+}+export function ImageIcon({ className }: { className?: string }) {return (<svg@@ -61,6 +75,81 @@ export function CodexLogo({ className }: { className?: string }) {);}+export function OpenClawLogo({ className }: { className?: string }) {+ return (+ <svg+ viewBox="0 0 16 16"+ aria-hidden="true"+ className={className}+ fill="none"+ >+ <g fill="#3a0a0d">+ <rect x="1" y="5" width="1" height="3" />+ <rect x="2" y="4" width="1" height="1" />+ <rect x="2" y="8" width="1" height="1" />+ <rect x="3" y="3" width="1" height="1" />+ <rect x="3" y="9" width="1" height="1" />+ <rect x="4" y="2" width="1" height="1" />+ <rect x="4" y="10" width="1" height="1" />+ <rect x="5" y="2" width="6" height="1" />+ <rect x="11" y="2" width="1" height="1" />+ <rect x="12" y="3" width="1" height="1" />+ <rect x="12" y="9" width="1" height="1" />+ <rect x="13" y="4" width="1" height="1" />+ <rect x="13" y="8" width="1" height="1" />+ <rect x="14" y="5" width="1" height="3" />+ <rect x="5" y="11" width="6" height="1" />+ <rect x="4" y="12" width="1" height="1" />+ <rect x="11" y="12" width="1" height="1" />+ <rect x="3" y="13" width="1" height="1" />+ <rect x="12" y="13" width="1" height="1" />+ <rect x="5" y="14" width="6" height="1" />+ </g>+ <g fill="#ff4f40">+ <rect x="5" y="3" width="6" height="1" />+ <rect x="4" y="4" width="8" height="1" />+ <rect x="3" y="5" width="10" height="1" />+ <rect x="3" y="6" width="10" height="1" />+ <rect x="3" y="7" width="10" height="1" />+ <rect x="4" y="8" width="8" height="1" />+ <rect x="5" y="9" width="6" height="1" />+ <rect x="5" y="12" width="6" height="1" />+ <rect x="6" y="13" width="4" height="1" />+ </g>+ <g fill="#ff775f">+ <rect x="1" y="6" width="2" height="1" />+ <rect x="2" y="5" width="1" height="1" />+ <rect x="2" y="7" width="1" height="1" />+ <rect x="13" y="6" width="2" height="1" />+ <rect x="13" y="5" width="1" height="1" />+ <rect x="13" y="7" width="1" height="1" />+ </g>+ <g fill="#081016">+ <rect x="6" y="5" width="1" height="1" />+ <rect x="9" y="5" width="1" height="1" />+ </g>+ <g fill="#f5fbff">+ <rect x="6" y="4" width="1" height="1" />+ <rect x="9" y="4" width="1" height="1" />+ </g>+ </svg>+ );+}++export function OpenCodeLogo({ className }: { className?: string }) {+ return (+ <svg+ viewBox="0 0 24 24"+ aria-hidden="true"+ className={className}+ fill="none"+ >+ <path d="M18 18H6V6H18V18Z" fill="#CFCECD" />+ <path d="M18 3H6V18H18V3ZM24 24H0V0H24V24Z" fill="#656363" />+ </svg>+ );+}+export function headerButtonClassName(tone: "ghost" | "solid",variant: "dark" | "light" = "dark",diff --git a/apps/web/features/search/index.ts b/apps/web/features/search/index.tsindex 6e3baea480..b6f719b680 100644--- a/apps/web/features/search/index.ts+++ b/apps/web/features/search/index.ts@@ -1 +1,2 @@export { SearchCommand } from "./components/search-command";+export { useSearchStore } from "./stores/search-store";diff --git a/apps/web/features/search/stores/search-store.ts b/apps/web/features/search/stores/search-store.tsnew file mode 100644index 0000000000..341fe01d7a--- /dev/null+++ b/apps/web/features/search/stores/search-store.ts@@ -0,0 +1,15 @@+"use client";++import { create } from "zustand";++interface SearchStore {+ open: boolean;+ setOpen: (open: boolean) => void;+ toggle: () => void;+}++export const useSearchStore = create<SearchStore>((set) => ({+ open: false,+ setOpen: (open) => set({ open }),+ toggle: () => set((s) => ({ open: !s.open })),+}));diff --git a/packages/core/package.json b/packages/core/package.jsonindex 9f78095cd5..ba7091a83b 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -35,6 +35,7 @@"./runtimes": "./runtimes/index.ts","./runtimes/queries": "./runtimes/queries.ts","./runtimes/mutations": "./runtimes/mutations.ts",+ "./runtimes/hooks": "./runtimes/hooks.ts","./realtime": "./realtime/index.ts","./navigation": "./navigation/index.ts","./modals": "./modals/index.ts",diff --git a/packages/core/provider.tsx b/packages/core/provider.tsxindex 41331d2e94..c3a6535152 100644--- a/packages/core/provider.tsx+++ b/packages/core/provider.tsx@@ -6,12 +6,12 @@ import { ReactQueryDevtools } from "@tanstack/react-query-devtools";import { createQueryClient } from "./query-client";import type { ReactNode } from "react";-export function QueryProvider({ children }: { children: ReactNode }) {+export function QueryProvider({ children, showDevtools = true }: { children: ReactNode; showDevtools?: boolean }) {const [queryClient] = useState(createQueryClient);return (<QueryClientProvider client={queryClient}>{children}- <ReactQueryDevtools initialIsOpen={false} />+ {showDevtools && <ReactQueryDevtools initialIsOpen={false} />}</QueryClientProvider>);}diff --git a/packages/core/runtimes/hooks.ts b/packages/core/runtimes/hooks.tsnew file mode 100644index 0000000000..efcfb0387a--- /dev/null+++ b/packages/core/runtimes/hooks.ts@@ -0,0 +1,73 @@+import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";+import { useAuthStore } from "../auth";+import { useWorkspaceId } from "../hooks";+import type { AgentRuntime } from "../types";+import { runtimeListOptions, latestCliVersionOptions } from "./queries";++function stripV(v: string): string {+ return v.replace(/^v/, "");+}++function isNewer(latest: string, current: string): boolean {+ const l = stripV(latest).split(".").map(Number);+ const c = stripV(current).split(".").map(Number);+ for (let i = 0; i < Math.max(l.length, c.length); i++) {+ const lv = l[i] ?? 0;+ const cv = c[i] ?? 0;+ if (lv > cv) return true;+ if (lv < cv) return false;+ }+ return false;+}++function runtimeNeedsUpdate(+ rt: AgentRuntime,+ latestVersion: string,+ userId: string,+): boolean {+ if (rt.runtime_mode !== "local") return false;+ // Only show to the user who owns this runtime.+ if (rt.owner_id !== userId) return false;+ const cliVersion =+ rt.metadata && typeof rt.metadata.cli_version === "string"+ ? rt.metadata.cli_version+ : null;+ if (!cliVersion) return false;+ return isNewer(latestVersion, cliVersion);+}++/**+ * Returns true if the current user has any local runtime with an outdated CLI version.+ */+export function useMyRuntimesNeedUpdate(): boolean {+ const wsId = useWorkspaceId();+ const userId = useAuthStore((s) => s.user?.id);+ const { data: runtimes } = useQuery(runtimeListOptions(wsId));+ const { data: latestVersion } = useQuery(latestCliVersionOptions());++ if (!runtimes || !latestVersion || !userId) return false;++ return runtimes.some((rt) => runtimeNeedsUpdate(rt, latestVersion, userId));+}++/**+ * Returns a Set of runtime IDs that belong to the current user and have updates available.+ */+export function useUpdatableRuntimeIds(): Set<string> {+ const wsId = useWorkspaceId();+ const userId = useAuthStore((s) => s.user?.id);+ const { data: runtimes } = useQuery(runtimeListOptions(wsId));+ const { data: latestVersion } = useQuery(latestCliVersionOptions());++ return useMemo(() => {+ if (!runtimes || !latestVersion || !userId) return new Set<string>();+ const ids = new Set<string>();+ for (const rt of runtimes) {+ if (runtimeNeedsUpdate(rt, latestVersion, userId)) {+ ids.add(rt.id);+ }+ }+ return ids;+ }, [runtimes, latestVersion, userId]);+}diff --git a/packages/core/runtimes/queries.ts b/packages/core/runtimes/queries.tsindex 153f0bcdd1..6c02e8c2b9 100644--- a/packages/core/runtimes/queries.ts+++ b/packages/core/runtimes/queries.ts@@ -5,6 +5,7 @@ export const runtimeKeys = {all: (wsId: string) => ["runtimes", wsId] as const,list: (wsId: string) => [...runtimeKeys.all(wsId), "list"] as const,listMine: (wsId: string) => [...runtimeKeys.all(wsId), "list", "mine"] as const,+ latestVersion: () => ["runtimes", "latestVersion"] as const,};export function runtimeListOptions(wsId: string, owner?: "me") {@@ -13,3 +14,25 @@ export function runtimeListOptions(wsId: string, owner?: "me") {queryFn: () => api.listRuntimes({ workspace_id: wsId, owner }),});}++const GITHUB_RELEASES_URL =+ "https://api.github.com/repos/multica-ai/multica/releases/latest";++export function latestCliVersionOptions() {+ return queryOptions({+ queryKey: runtimeKeys.latestVersion(),+ queryFn: async (): Promise<string | null> => {+ try {+ const resp = await fetch(GITHUB_RELEASES_URL, {+ headers: { Accept: "application/vnd.github+json" },+ });+ if (!resp.ok) return null;+ const data = await resp.json();+ return (data.tag_name as string) ?? null;+ } catch {+ return null;+ }+ },+ staleTime: 10 * 60 * 1000, // 10 minutes+ });+}diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex 0fbfa77f58..21bbbb1e3d 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -16,14 +16,18 @@ import {BookOpenText,SquarePen,CircleUser,+ FolderKanban,+ Ellipsis,} from "lucide-react";import { WorkspaceAvatar } from "../workspace/workspace-avatar";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";import {Sidebar,SidebarContent,SidebarGroup,SidebarGroupContent,+ SidebarGroupLabel,SidebarHeader,SidebarFooter,SidebarMenu,@@ -47,15 +51,20 @@ import { useQuery } from "@tanstack/react-query";import { inboxKeys, deduplicateInboxItems } from "@multica/core/inbox/queries";import { api } from "@multica/core/api";import { useModalStore } from "@multica/core/modals";+import { useMyRuntimesNeedUpdate } from "@multica/core/runtimes/hooks";-const primaryNav = [+const personalNav = [{ href: "/inbox", label: "Inbox", icon: Inbox },{ href: "/my-issues", label: "My Issues", icon: CircleUser },- { href: "/issues", label: "Issues", icon: ListTodo },];const workspaceNav = [+ { href: "/issues", label: "Issues", icon: ListTodo },+ { href: "/projects", label: "Projects", icon: FolderKanban },{ href: "/agents", label: "Agents", icon: Bot },+];++const configureNav = [{ href: "/runtimes", label: "Runtimes", icon: Monitor },{ href: "/skills", label: "Skills", icon: BookOpenText },{ href: "/settings", label: "Settings", icon: Settings },@@ -70,13 +79,15 @@ function DraftDot() {interface AppSidebarProps {/** Rendered above SidebarHeader (e.g. desktop traffic light spacer) */topSlot?: React.ReactNode;+ /** Rendered in the header between workspace switcher and new-issue button (e.g. search trigger) */+ searchSlot?: React.ReactNode;/** Extra className for SidebarHeader */headerClassName?: string;/** Extra style for SidebarHeader */headerStyle?: React.CSSProperties;}-export function AppSidebar({ topSlot, headerClassName, headerStyle }: AppSidebarProps = {}) {+export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }: AppSidebarProps = {}) {const { pathname, push } = useNavigation();const user = useAuthStore((s) => s.user);const authLogout = useAuthStore((s) => s.logout);@@ -94,6 +105,7 @@ export function AppSidebar({ topSlot, headerClassName, headerStyle }: AppSidebar() => deduplicateInboxItems(inboxItems).filter((i) => !i.read).length,[inboxItems],);+ const hasRuntimeUpdates = useMyRuntimesNeedUpdate();const logout = () => {push("/");@@ -106,21 +118,20 @@ export function AppSidebar({ topSlot, headerClassName, headerStyle }: AppSidebar{topSlot}{/* Workspace Switcher */}<SidebarHeader className={cn("py-3", headerClassName)} style={headerStyle}>- <div className="flex items-center gap-4">- <SidebarMenu className="min-w-0 flex-1">- <SidebarMenuItem>- <DropdownMenu>- <DropdownMenuTrigger- render={- <SidebarMenuButton>- <WorkspaceAvatar name={workspace?.name ?? "M"} size="sm" />- <span className="flex-1 truncate font-medium">- {workspace?.name ?? "Multica"}- </span>- <ChevronDown className="size-3 text-muted-foreground" />- </SidebarMenuButton>- }- />+ <SidebarMenu>+ <SidebarMenuItem>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <SidebarMenuButton>+ <WorkspaceAvatar name={workspace?.name ?? "M"} size="sm" />+ <span className="flex-1 truncate font-medium">+ {workspace?.name ?? "Multica"}+ </span>+ <ChevronDown className="size-3 text-muted-foreground" />+ </SidebarMenuButton>+ }+ /><DropdownMenuContentclassName="w-auto"align="start"@@ -174,20 +185,28 @@ export function AppSidebar({ topSlot, headerClassName, headerStyle }: AppSidebar</DropdownMenuItem></DropdownMenuGroup></DropdownMenuContent>- </DropdownMenu>+ </DropdownMenu>+ </SidebarMenuItem>+ </SidebarMenu>+ <SidebarMenu>+ {searchSlot && (+ <SidebarMenuItem>+ {searchSlot}</SidebarMenuItem>- </SidebarMenu>- <Tooltip>- <TooltipTrigger- className="relative flex h-7 w-7 items-center justify-center rounded-lg bg-background text-foreground shadow-sm hover:bg-accent"+ )}+ <SidebarMenuItem>+ <SidebarMenuButton+ className="text-muted-foreground"onClick={() => useModalStore.getState().open("create-issue")}>- <SquarePen className="size-3.5" />- <DraftDot />- </TooltipTrigger>- <TooltipContent side="bottom">New issue</TooltipContent>- </Tooltip>- </div>+ <span className="relative">+ <SquarePen />+ <DraftDot />+ </span>+ <span>New Issue</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ </SidebarMenu></SidebarHeader>{/* Navigation */}@@ -195,7 +214,7 @@ export function AppSidebar({ topSlot, headerClassName, headerStyle }: AppSidebar<SidebarGroup><SidebarGroupContent><SidebarMenu className="gap-0.5">- {primaryNav.map((item) => {+ {personalNav.map((item) => {const isActive = pathname === item.href;return (<SidebarMenuItem key={item.href}>@@ -220,6 +239,7 @@ export function AppSidebar({ topSlot, headerClassName, headerStyle }: AppSidebar</SidebarGroup><SidebarGroup>+ <SidebarGroupLabel>Workspace</SidebarGroupLabel><SidebarGroupContent><SidebarMenu className="gap-0.5">{workspaceNav.map((item) => {@@ -240,8 +260,65 @@ export function AppSidebar({ topSlot, headerClassName, headerStyle }: AppSidebar</SidebarMenu></SidebarGroupContent></SidebarGroup>++ <SidebarGroup>+ <SidebarGroupLabel>Configure</SidebarGroupLabel>+ <SidebarGroupContent>+ <SidebarMenu className="gap-0.5">+ {configureNav.map((item) => {+ const isActive = pathname === item.href;+ return (+ <SidebarMenuItem key={item.href}>+ <SidebarMenuButton+ isActive={isActive}+ render={<AppLink href={item.href} />}+ className="text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground"+ >+ <item.icon />+ <span>{item.label}</span>+ {item.label === "Runtimes" && hasRuntimeUpdates && (+ <span className="ml-auto size-1.5 rounded-full bg-destructive" />+ )}+ </SidebarMenuButton>+ </SidebarMenuItem>+ );+ })}+ </SidebarMenu>+ </SidebarGroupContent>+ </SidebarGroup></SidebarContent>- <SidebarFooter />++ <SidebarFooter className="p-2">+ <div className="border-t pt-2">+ <div className="flex items-center gap-2.5 rounded-md px-2 py-1.5">+ <ActorAvatar+ name={user?.name ?? ""}+ initials={(user?.name ?? "U").charAt(0).toUpperCase()}+ avatarUrl={user?.avatar_url}+ size={28}+ />+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium leading-tight">+ {user?.name}+ </p>+ <p className="truncate text-xs text-muted-foreground leading-tight">+ {user?.email}+ </p>+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors">+ <Ellipsis className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" side="top" sideOffset={4}>+ <DropdownMenuItem variant="destructive" onClick={logout}>+ <LogOut className="h-3.5 w-3.5" />+ Log out+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ </SidebarFooter><SidebarRail /></Sidebar>);diff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsxindex 24689915df..60fb94270d 100644--- a/packages/views/layout/dashboard-layout.tsx+++ b/packages/views/layout/dashboard-layout.tsx@@ -9,8 +9,10 @@ import { useDashboardGuard } from "./use-dashboard-guard";interface DashboardLayoutProps {children: ReactNode;- /** Sibling of SidebarInset (e.g. SearchCommand) */+ /** Sibling of SidebarInset (e.g. SearchCommand, ChatWindow) */extra?: ReactNode;+ /** Rendered inside sidebar header as a search trigger */+ searchSlot?: ReactNode;/** Loading indicator */loadingIndicator?: ReactNode;}@@ -18,6 +20,7 @@ interface DashboardLayoutProps {export function DashboardLayout({children,extra,+ searchSlot,loadingIndicator,}: DashboardLayoutProps) {const { user, isLoading, workspace } = useDashboardGuard("/");@@ -32,22 +35,24 @@ export function DashboardLayout({if (!user) return null;+ if (!workspace) {+ return (+ <div className="flex h-svh items-center justify-center">+ {loadingIndicator}+ </div>+ );+ }+return (- <SidebarProvider className="h-svh">- <AppSidebar />- <SidebarInset className="overflow-hidden">- {workspace ? (- <WorkspaceIdProvider wsId={workspace.id}>- {children}- <ModalRegistry />- </WorkspaceIdProvider>- ) : (- <div className="flex flex-1 items-center justify-center">- {loadingIndicator}- </div>- )}- </SidebarInset>- {extra}- </SidebarProvider>+ <WorkspaceIdProvider wsId={workspace.id}>+ <SidebarProvider className="h-svh">+ <AppSidebar searchSlot={searchSlot} />+ <SidebarInset className="overflow-hidden">+ {children}+ <ModalRegistry />+ </SidebarInset>+ {extra}+ </SidebarProvider>+ </WorkspaceIdProvider>);}