Skip to content

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

Go

feat(chat): improve chat UI, fix streaming, add stop/fullscreen/agent permissions

yushen3ffebd097c01
diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/(dashboard)/layout.tsx
index 8b4a696458..ce07373762 100644
--- a/apps/web/app/(dashboard)/layout.tsx
+++ b/apps/web/app/(dashboard)/layout.tsx
@@ -44,28 +44,26 @@ export default function DashboardLayout({
if (!user) return null;
+ if (!workspace) {
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <MulticaIcon className="size-6 animate-pulse" />
+ </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">
- <MulticaIcon className="size-6 animate-pulse" />
- </div>
- )}
- </SidebarInset>
- {workspace && (
- <>
- <ChatWindow />
- <ChatFab />
- </>
- )}
- <SearchCommand />
- </SidebarProvider>
+ <WorkspaceIdProvider wsId={workspace.id}>
+ <SidebarProvider className="h-svh">
+ <AppSidebar />
+ <SidebarInset className="overflow-hidden">
+ {children}
+ <ModalRegistry />
+ </SidebarInset>
+ <ChatWindow />
+ <ChatFab />
+ <SearchCommand />
+ </SidebarProvider>
+ </WorkspaceIdProvider>
);
}
diff --git a/apps/web/features/chat/components/chat-input.tsx b/apps/web/features/chat/components/chat-input.tsx
index d964a508fe..77c858889d 100644
--- a/apps/web/features/chat/components/chat-input.tsx
+++ b/apps/web/features/chat/components/chat-input.tsx
@@ -1,27 +1,28 @@
"use client";
import { useState, useRef, useCallback } from "react";
-import { ArrowUp } from "lucide-react";
+import { ArrowUp, Square } from "lucide-react";
interface ChatInputProps {
onSend: (content: string) => void;
- disabled?: boolean;
+ onStop?: () => void;
+ isRunning?: boolean;
}
-export function ChatInput({ onSend, disabled }: ChatInputProps) {
+export function ChatInput({ onSend, onStop, isRunning }: ChatInputProps) {
const [value, setValue] = useState("");
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleSend = useCallback(() => {
const trimmed = value.trim();
- if (!trimmed || disabled) return;
+ if (!trimmed || isRunning) return;
onSend(trimmed);
setValue("");
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
}
textareaRef.current?.focus();
- }, [value, disabled, onSend]);
+ }, [value, isRunning, onSend]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -52,18 +53,27 @@ export function ChatInput({ onSend, disabled }: ChatInputProps) {
}}
onKeyDown={handleKeyDown}
placeholder="Ask Multica..."
- disabled={disabled}
+ disabled={isRunning}
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">
- <button
- onClick={handleSend}
- disabled={disabled || !value.trim()}
- 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>
+ {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()}
+ 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.tsx
index 91a67b0b69..42f95fd92a 100644
--- a/apps/web/features/chat/components/chat-message-list.tsx
+++ b/apps/web/features/chat/components/chat-message-list.tsx
@@ -1,44 +1,58 @@
"use client";
-import { useEffect, useRef } from "react";
+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 { Bot, Loader2 } from "lucide-react";
-import type { ChatMessage, Agent } from "@multica/core/types";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@multica/ui/components/ui/collapsible";
+import { Bot, Loader2, ChevronRight, ChevronDown, Brain, AlertCircle } from "lucide-react";
+import { api } from "@/platform/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;
- streamingContent: string;
+ timelineItems: ChatTimelineItem[];
isWaiting: boolean;
}
export function ChatMessageList({
messages,
agent,
- streamingContent,
+ timelineItems,
isWaiting,
}: ChatMessageListProps) {
const bottomRef = useRef<HTMLDivElement>(null);
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
- }, [messages, streamingContent]);
+ }, [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} />
))}
- {streamingContent && (
+ {/* Live streaming timeline */}
+ {hasTimeline && (
<div className="flex items-start gap-3">
<AgentAvatar agent={agent} />
- <div className="min-w-0 flex-1 text-sm leading-relaxed whitespace-pre-wrap">
- {streamingContent}
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <TimelineView items={timelineItems} />
</div>
</div>
)}
- {isWaiting && !streamingContent && (
+ {isWaiting && !hasTimeline && (
<div className="flex items-start gap-3">
<AgentAvatar agent={agent} />
<div className="flex items-center pt-1">
@@ -51,6 +65,8 @@ export function ChatMessageList({
);
}
+// ─── Message bubbles ─────────────────────────────────────────────────────
+
function MessageBubble({
message,
agent,
@@ -58,9 +74,7 @@ function MessageBubble({
message: ChatMessage;
agent: Agent | null;
}) {
- const isUser = message.role === "user";
-
- if (isUser) {
+ 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%]">
@@ -70,16 +84,278 @@ function MessageBubble({
);
}
+ 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 text-sm leading-relaxed whitespace-pre-wrap">
- {message.content}
+ <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">
diff --git a/apps/web/features/chat/components/chat-window.tsx b/apps/web/features/chat/components/chat-window.tsx
index a513f98ace..86c6e6fe68 100644
--- a/apps/web/features/chat/components/chat-window.tsx
+++ b/apps/web/features/chat/components/chat-window.tsx
@@ -1,8 +1,8 @@
"use client";
-import { useCallback, useEffect } from "react";
+import { useCallback, useEffect, useRef } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { X, Minus, Maximize2, Send, ChevronDown, Bot } from "lucide-react";
+import { Minus, Maximize2, Minimize2, Send, ChevronDown, Bot, Plus } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@multica/ui/components/ui/avatar";
import {
DropdownMenu,
@@ -11,8 +11,10 @@ import {
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { useWorkspaceId } from "@multica/core/hooks";
-import { agentListOptions } from "@multica/core/workspace/queries";
-import { chatMessagesOptions, chatKeys } from "@/core/chat/queries";
+import { useAuthStore } from "@multica/core/auth";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import { canAssignAgent } from "@multica/views/issues/components";
+import { chatSessionsOptions, chatMessagesOptions, chatKeys } from "@/core/chat/queries";
import {
useCreateChatSession,
useSendChatMessage,
@@ -26,27 +28,38 @@ import type { TaskMessagePayload, ChatDonePayload, Agent } from "@multica/core/t
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 streamingContent = useChatStore((s) => s.streamingContent);
+ 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 setActiveSession = useChatStore((s) => s.setActiveSession);
const setPendingTask = useChatStore((s) => s.setPendingTask);
- const appendStreaming = useChatStore((s) => s.appendStreamingContent);
- const clearStreaming = useChatStore((s) => s.clearStreamingContent);
+ const addTimelineItem = useChatStore((s) => s.addTimelineItem);
+ const clearTimeline = useChatStore((s) => s.clearTimeline);
const setSelectedAgentId = useChatStore((s) => s.setSelectedAgentId);
+ const user = useAuthStore((s) => s.user);
const { data: agents = [] } = useQuery(agentListOptions(wsId));
- const { data: messages = [] } = useQuery(
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { data: sessions = [] } = useQuery(chatSessionsOptions(wsId));
+ const { data: rawMessages } = useQuery(
chatMessagesOptions(activeSessionId ?? ""),
);
+ // When no active session, always show empty — don't use stale cache
+ const messages = activeSessionId ? rawMessages ?? [] : [];
const qc = useQueryClient();
const createSession = useCreateChatSession();
const sendMessage = useSendChatMessage(activeSessionId ?? "");
- const availableAgents = agents.filter((a) => !a.archived_at);
+ 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 =
@@ -54,49 +67,70 @@ export function ChatWindow() {
availableAgents[0] ??
null;
- // Subscribe to task:message for streaming.
+ // 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(() => {
- if (!pendingTaskId) return;
-
const unsubMessage = subscribe("task:message", (payload) => {
const p = payload as TaskMessagePayload;
- if (p.task_id !== pendingTaskId) return;
- if (p.type === "text" && p.content) {
- appendStreaming(p.content);
- }
+ 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 (p.task_id !== pendingTaskId) return;
- const content = useChatStore.getState().streamingContent;
- if (content && activeSessionId) {
+ if (!pendingTaskRef.current || p.task_id !== pendingTaskRef.current) return;
+ const activeSessionId = useChatStore.getState().activeSessionId;
+ if (activeSessionId) {
qc.invalidateQueries({
queryKey: chatKeys.messages(activeSessionId),
});
}
- clearStreaming();
+ clearTimeline();
setPendingTask(null);
});
const unsubCompleted = subscribe("task:completed", (payload) => {
const p = payload as { task_id: string };
- if (p.task_id !== pendingTaskId) return;
+ if (!pendingTaskRef.current || p.task_id !== pendingTaskRef.current) return;
+ const activeSessionId = useChatStore.getState().activeSessionId;
if (activeSessionId) {
qc.invalidateQueries({
queryKey: chatKeys.messages(activeSessionId),
});
}
- clearStreaming();
+ clearTimeline();
setPendingTask(null);
});
const unsubFailed = subscribe("task:failed", (payload) => {
const p = payload as { task_id: string };
- if (p.task_id !== pendingTaskId) return;
- clearStreaming();
+ if (!pendingTaskRef.current || p.task_id !== pendingTaskRef.current) return;
+ clearTimeline();
setPendingTask(null);
});
@@ -106,15 +140,8 @@ export function ChatWindow() {
unsubCompleted();
unsubFailed();
};
- }, [
- pendingTaskId,
- activeSessionId,
- subscribe,
- appendStreaming,
- clearStreaming,
- setPendingTask,
- qc,
- ]);
+ // 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) => {
@@ -137,7 +164,6 @@ export function ChatWindow() {
);
qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
setPendingTask(task_id);
- clearStreaming();
},
[
activeSessionId,
@@ -145,11 +171,24 @@ export function ChatWindow() {
createSession,
setActiveSession,
setPendingTask,
- clearStreaming,
qc,
],
);
+ const handleStop = useCallback(async () => {
+ if (!pendingTaskId) return;
+ try {
+ await (await import("@/platform/api")).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);
@@ -161,10 +200,14 @@ export function ChatWindow() {
if (!isOpen) return null;
- const hasMessages = messages.length > 0 || !!streamingContent;
+ 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="fixed bottom-4 right-4 z-50 flex flex-col w-[420px] h-[600px] rounded-xl border bg-background shadow-2xl overflow-hidden">
+ <div className={containerClass}>
{/* Header */}
<div className="flex items-center justify-between border-b px-4 py-2.5">
<AgentSelector
@@ -174,24 +217,29 @@ export function ChatWindow() {
/>
<div className="flex items-center gap-0.5">
<button
- onClick={() => setOpen(false)}
+ 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"
>
- <Minus className="size-3.5" />
+ <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"
>
- <Maximize2 className="size-3.5" />
+ {isFullscreen ? <Minimize2 className="size-3.5" /> : <Maximize2 className="size-3.5" />}
</button>
<button
- onClick={() => {
- setOpen(false);
- setActiveSession(null);
- }}
+ 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"
>
- <X className="size-3.5" />
+ <Minus className="size-3.5" />
</button>
</div>
</div>
@@ -201,7 +249,7 @@ export function ChatWindow() {
<ChatMessageList
messages={messages}
agent={activeAgent}
- streamingContent={streamingContent}
+ timelineItems={timelineItems}
isWaiting={!!pendingTaskId}
/>
) : (
@@ -209,7 +257,7 @@ export function ChatWindow() {
)}
{/* Input */}
- <ChatInput onSend={handleSend} disabled={!!pendingTaskId} />
+ <ChatInput onSend={handleSend} onStop={handleStop} isRunning={!!pendingTaskId} />
</div>
);
}
diff --git a/apps/web/features/chat/store.ts b/apps/web/features/chat/store.ts
index 3e45cb204e..ba2e5059da 100644
--- a/apps/web/features/chat/store.ts
+++ b/apps/web/features/chat/store.ts
@@ -1,37 +1,62 @@
import { create } from "zustand";
const AGENT_STORAGE_KEY = "multica:chat:selectedAgentId";
+const SESSION_STORAGE_KEY = "multica:chat:activeSessionId";
-function readStoredAgentId(): string | null {
+function readStored(key: string): string | null {
if (typeof window === "undefined") return null;
- return localStorage.getItem(AGENT_STORAGE_KEY);
+ 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;
streamingContent: string;
selectedAgentId: string | null;
+ timelineItems: ChatTimelineItem[];
setOpen: (open: boolean) => void;
toggle: () => void;
+ toggleFullscreen: () => void;
setActiveSession: (id: string | null) => void;
setPendingTask: (taskId: string | null) => void;
appendStreamingContent: (text: string) => void;
clearStreamingContent: () => void;
setSelectedAgentId: (id: string) => void;
+ addTimelineItem: (item: ChatTimelineItem) => void;
+ clearTimeline: () => void;
}
export const useChatStore = create<ChatState>((set) => ({
isOpen: false,
- activeSessionId: null,
+ isFullscreen: false,
+ activeSessionId: readStored(SESSION_STORAGE_KEY),
pendingTaskId: null,
streamingContent: "",
- selectedAgentId: readStoredAgentId(),
- setOpen: (open) => set({ isOpen: open }),
- toggle: () => set((s) => ({ isOpen: !s.isOpen })),
- setActiveSession: (id) => set({ activeSessionId: id }),
- setPendingTask: (taskId) => set({ pendingTaskId: taskId }),
+ selectedAgentId: readStored(AGENT_STORAGE_KEY),
+ 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: [] }),
appendStreamingContent: (text) =>
set((s) => ({ streamingContent: s.streamingContent + text })),
clearStreamingContent: () => set({ streamingContent: "" }),
@@ -39,4 +64,14 @@ export const useChatStore = create<ChatState>((set) => ({
localStorage.setItem(AGENT_STORAGE_KEY, id);
set({ selectedAgentId: id });
},
+ 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/api/client.ts b/packages/core/api/client.ts
index d04cf1d01a..48440843bb 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -634,6 +634,10 @@ export class ApiClient {
});
}
+ async cancelTaskById(taskId: string): Promise<void> {
+ await this.fetch(`/api/tasks/${taskId}/cancel`, { method: "POST" });
+ }
+
async listAttachments(issueId: string): Promise<Attachment[]> {
return this.fetch(`/api/issues/${issueId}/attachments`);
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 7c57e1086c..ff8a655f97 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -245,6 +245,9 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
})
// Chat
+ // Tasks (generic)
+ r.Post("/api/tasks/{taskId}/cancel", h.CancelTask)
+
r.Route("/api/chat/sessions", func(r chi.Router) {
r.Post("/", h.CreateChatSession)
r.Get("/", h.ListChatSessions)
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index e3b15dd612..145bcbd160 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -84,7 +84,17 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {
b.WriteString("### Workflow\n\n")
- if ctx.TriggerCommentID != "" {
+ if ctx.ChatSessionID != "" {
+ // Chat task: interactive assistant mode
+ b.WriteString("**You are in chat mode.** A user is messaging you directly in a chat window.\n\n")
+ b.WriteString("- Respond conversationally and helpfully to the user's message\n")
+ b.WriteString("- You have full access to the `multica` CLI to look up issues, workspace info, members, agents, etc.\n")
+ b.WriteString("- If asked about issues, use `multica issue list --output json` or `multica issue get <id> --output json`\n")
+ b.WriteString("- If asked about the workspace, use `multica workspace get --output json`\n")
+ b.WriteString("- If asked to perform actions (create issues, update status, etc.), use the appropriate CLI commands\n")
+ b.WriteString("- If the task requires code changes, use `multica repo checkout <url>` to get the code first\n")
+ b.WriteString("- Keep responses concise and direct\n\n")
+ } else if ctx.TriggerCommentID != "" {
// Comment-triggered: focus on reading and replying
b.WriteString("**This task was triggered by a comment.** Your primary job is to respond.\n\n")
fmt.Fprintf(&b, "1. Run `multica issue get %s --output json` to understand the issue context\n", ctx.IssueID)
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 97b3237b1f..74fc7850d8 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -517,8 +517,15 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
}
workspaceID := ""
- if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {
- workspaceID = uuidToString(issue.WorkspaceID)
+ if task.IssueID.Valid {
+ if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {
+ workspaceID = uuidToString(issue.WorkspaceID)
+ }
+ }
+ if workspaceID == "" && task.ChatSessionID.Valid {
+ if cs, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID); err == nil {
+ workspaceID = uuidToString(cs.WorkspaceID)
+ }
}
for _, msg := range req.Messages {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index ee66f88783..181f4e376a 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -281,9 +281,17 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}
}
- // For chat tasks, update the chat session with the latest session_id/work_dir
- // and broadcast a chat:done event.
+ // For chat tasks, save assistant reply, update session, and broadcast chat:done.
if task.ChatSessionID.Valid {
+ var payload protocol.TaskCompletedPayload
+ if err := json.Unmarshal(result, &payload); err == nil && payload.Output != "" {
+ s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ChatSessionID: task.ChatSessionID,
+ Role: "assistant",
+ Content: redact.Text(payload.Output),
+ TaskID: task.ID,
+ })
+ }
s.Queries.UpdateChatSessionSession(ctx, db.UpdateChatSessionSessionParams{
ID: task.ChatSessionID,
SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},