Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: resolve auto-save data loss and improve chat/unread UX
Gus9b083c5b7520
diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex b9749cde8..e78c198ef 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -30,6 +30,7 @@ import type { Agent, AgentLink } from "@alook/shared";import { useAgentContext } from "@/contexts/agent-context";import { useWorkspace } from "@/contexts/workspace-context";import { useIsMobile } from "@/hooks/use-mobile";+import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";import { Button } from "@/components/ui/button";import { AgentPreviewCard } from "@/components/agent-preview-card";import {@@ -46,7 +47,6 @@ import { LinkSidecar } from "@/components/canvas/link-sidecar";import { ActiveTasksFloat } from "@/components/canvas/active-tasks-float";import { UpcomingEventsFloat } from "@/components/canvas/upcoming-events-float";import { getAutoLayout } from "@/components/canvas/auto-layout";-import { AgentChatSheet } from "@/components/canvas/agent-chat-sheet";const nodeTypes = { agent: AgentNode };const edgeTypes = { link: LinkEdge };@@ -510,13 +510,11 @@ export default function HomePage() {const { agents, loading } = useAgentContext();const { workspaceId } = useWorkspace();const isMobile = useIsMobile();- const [chatSheetAgent, setChatSheetAgent] = useState<Agent | null>(null);- const [chatSheetOpen, setChatSheetOpen] = useState(false);+ const { openAgentChat } = useAgentChatSheet();const handleAgentClick = useCallback((agent: Agent) => {- setChatSheetAgent(agent);- setChatSheetOpen(true);- }, []);+ openAgentChat(agent.id);+ }, [openAgentChat]);if (loading) {return (@@ -544,18 +542,12 @@ export default function HomePage() {}if (isMobile) {- return (- <>- <MobileAgentList onAgentClick={handleAgentClick} />- <AgentChatSheet open={chatSheetOpen} onOpenChange={setChatSheetOpen} agent={chatSheetAgent} />- </>- );+ return <MobileAgentList onAgentClick={handleAgentClick} />;}return (<ReactFlowProvider><AgentCanvas onAgentClick={handleAgentClick} />- <AgentChatSheet open={chatSheetOpen} onOpenChange={setChatSheetOpen} agent={chatSheetAgent} /></ReactFlowProvider>);}diff --git a/src/web/src/app/(app)/w/[slug]/issues/page.tsx b/src/web/src/app/(app)/w/[slug]/issues/page.tsxindex 087b9a0f3..49ece2717 100644--- a/src/web/src/app/(app)/w/[slug]/issues/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/issues/page.tsx@@ -393,6 +393,21 @@ export default function IssuesPage() {}}}+ if (msg.type === "conversation.message"+ && msg.message.role === "event"+ && msg.message.content.startsWith("Issue status changed:")+ && !pendingStatusUpdate.current+ && msg.conversationId !== detailConvIdRef.current) {+ const match = msg.message.content.match(/-> (\w+)/);+ if (match) {+ const newStatus = match[1] as Issue["status"];+ setIssues((prev) => prev.map((i) =>+ i.conversation_id === msg.conversationId+ ? { ...i, status: newStatus, updated_at: msg.message.created_at }+ : i+ ));+ }+ }if (msg.type === "issue.comment" && selectedIdRef.current === msg.issueId) {setDetail((prev) => {if (!prev) return prev;diff --git a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsxindex 0daddc63d..87532ddfa 100644--- a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx@@ -71,6 +71,8 @@ export function InstructionTab() {fetchInstruction();}, [fetchInstruction]);+ const scheduleSaveRef = useRef<() => void>(() => {});+const flushSave = useCallback(async () => {if (savingRef.current) return;const current = valueRef.current;@@ -83,6 +85,9 @@ export function InstructionTab() {toast.error(err instanceof Error ? err.message : "Failed to save");} finally {savingRef.current = false;+ if (valueRef.current !== savedValueRef.current) {+ scheduleSaveRef.current();+ }}}, [workspaceId]);@@ -91,6 +96,10 @@ export function InstructionTab() {debounceRef.current = setTimeout(flushSave, DEBOUNCE_MS);}, [flushSave]);+ useEffect(() => {+ scheduleSaveRef.current = scheduleSave;+ }, [scheduleSave]);+const handleChange = useCallback((next: string) => {setValue(next);@@ -120,10 +129,16 @@ export function InstructionTab() {return () => {if (debounceRef.current) clearTimeout(debounceRef.current);if (valueRef.current !== savedValueRef.current) {- void flushSave();+ const params = new URLSearchParams({ workspace_id: workspaceId });+ fetch(`/api/members/me?${params}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ global_instruction: valueRef.current }),+ keepalive: true,+ });}};- }, [flushSave]);+ }, [workspaceId]);const ratio = value.length / MAX_LENGTH;diff --git a/src/web/src/app/(app)/w/[slug]/unread/page.tsx b/src/web/src/app/(app)/w/[slug]/unread/page.tsxindex 71d397b2c..7b4595cd4 100644--- a/src/web/src/app/(app)/w/[slug]/unread/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/unread/page.tsx@@ -1,11 +1,11 @@"use client";import { useState, useEffect, useCallback, useRef } from "react";-import Link from "next/link";import { useWorkspace } from "@/contexts/workspace-context";import { useAgentContext } from "@/contexts/agent-context";import { listInboxItems, markAllInboxRead, type InboxItem } from "@/lib/api";import { useInboxCount } from "@/contexts/inbox-count-context";+import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";import { Skeleton } from "@/components/ui/skeleton";import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";import { Checkbox } from "@/components/ui/checkbox";@@ -50,11 +50,11 @@ function TypeBadge({ type }: { type: string | null }) {);}-function InboxRow({ item, slug, onClick }: { item: InboxItem; slug: string; onClick?: () => void }) {+function InboxRow({ item, slug, onClick }: { item: InboxItem; slug: string; onClick?: (e: React.MouseEvent) => void }) {const statusLabel = item.root_task_status === "failed" ? "Failed" : "Completed";return (- <Link+ <ahref={`/w/${slug}/agents/${item.agent_id}?conv=${item.id}`}onClick={onClick}className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"@@ -86,7 +86,7 @@ function InboxRow({ item, slug, onClick }: { item: InboxItem; slug: string; onCl</p></div></div>- </Link>+ </a>);}@@ -112,6 +112,7 @@ export default function InboxPage() {const { slug, workspaceId } = useWorkspace();const { subscribeWs } = useAgentContext();const { count, refresh: refreshInboxCount, decrement: decrementInboxCount } = useInboxCount();+ const { openAgentChat } = useAgentChatSheet();const [items, setItems] = useState<InboxItem[]>([]);const [loading, setLoading] = useState(true);@@ -302,7 +303,17 @@ export default function InboxPage() {) : (<>{items.map((item) => (- <InboxRow key={item.id} item={item} slug={slug} onClick={decrementInboxCount} />+ <InboxRow+ key={item.id}+ item={item}+ slug={slug}+ onClick={(e) => {+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;+ e.preventDefault();+ decrementInboxCount();+ openAgentChat(item.agent_id, { conversationId: item.id });+ }}+ />))}{loadingMore && <SkeletonRow promptWidth="50%" />}</>diff --git a/src/web/src/app/api/issues/[id]/route.test.ts b/src/web/src/app/api/issues/[id]/route.test.tsindex d40b86782..58d4aeb85 100644--- a/src/web/src/app/api/issues/[id]/route.test.ts+++ b/src/web/src/app/api/issues/[id]/route.test.ts@@ -65,6 +65,11 @@ vi.mock("@/lib/logger", () => ({log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },}));+const mockBroadcastToUser = vi.fn().mockResolvedValue(undefined);+vi.mock("@/lib/broadcast", () => ({+ broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),+}));+const mockCancelActiveTask = vi.fn();const mockCancelTrace = vi.fn();vi.mock("@/lib/services/task", () => ({@@ -100,6 +105,7 @@ describe("PATCH /api/issues/[id]", () => {it("updates status and records status transition", async () => {mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1" });mockUpdateIssue.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });+ mockCreateMessage.mockResolvedValue({ id: "m1", role: "event", content: "Issue status changed: todo -> in_progress" });const req = new NextRequest("http://localhost/api/issues/iss_1", {method: "PATCH",body: JSON.stringify({ status: "in_progress" }),@@ -108,6 +114,7 @@ describe("PATCH /api/issues/[id]", () => {expect(res.status).toBe(200);expect(mockUpdateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", { title: undefined, description: undefined, status: "in_progress" });expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({ role: "event", content: "Issue status changed: todo -> in_progress" }));+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({ type: "conversation.message", conversationId: "c1" }));});});diff --git a/src/web/src/app/api/issues/[id]/route.ts b/src/web/src/app/api/issues/[id]/route.tsindex a4eaaf343..b9556e993 100644--- a/src/web/src/app/api/issues/[id]/route.ts+++ b/src/web/src/app/api/issues/[id]/route.ts@@ -143,12 +143,17 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {if (!updated) return writeError("issue not found", 404);if (body.status && body.status !== existing.status && existing.conversationId) {- await queries.message.createMessage(db, {+ const eventMsg = await queries.message.createMessage(db, {conversationId: existing.conversationId,role: "event",content: `Issue status changed: ${existing.status} -> ${body.status}`,metadata: JSON.stringify({ issueId: existing.id }),});+ broadcastToUser(ctx.userId, {+ type: "conversation.message",+ conversationId: existing.conversationId,+ message: messageToResponse(eventMsg),+ }).catch(() => {});}return writeJSON(issueToResponse(updated));diff --git a/src/web/src/components/agent-edit-form.tsx b/src/web/src/components/agent-edit-form.tsxindex 733456534..8a94700f3 100644--- a/src/web/src/components/agent-edit-form.tsx+++ b/src/web/src/components/agent-edit-form.tsx@@ -107,6 +107,8 @@ export function AgentEditForm({const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);const savingInstructionsRef = useRef(false);+ const scheduleInstructionSaveRef = useRef<() => void>(() => {});+const flushInstructions = useCallback(async () => {if (savingInstructionsRef.current) return;const current = instructionsRef.current;@@ -119,6 +121,9 @@ export function AgentEditForm({toast.error(err instanceof Error ? err.message : "Failed to save instructions");} finally {savingInstructionsRef.current = false;+ if (instructionsRef.current !== savedInstructionsRef.current) {+ scheduleInstructionSaveRef.current();+ }}}, [agent.id, workspaceId]);@@ -127,6 +132,10 @@ export function AgentEditForm({debounceRef.current = setTimeout(flushInstructions, DEBOUNCE_MS);}, [flushInstructions]);+ useEffect(() => {+ scheduleInstructionSaveRef.current = scheduleInstructionSave;+ }, [scheduleInstructionSave]);+const handleInstructionChange = useCallback((next: string) => {setInstructions(next);@@ -156,10 +165,16 @@ export function AgentEditForm({return () => {if (debounceRef.current) clearTimeout(debounceRef.current);if (instructionsRef.current !== savedInstructionsRef.current) {- void flushInstructions();+ const params = new URLSearchParams({ workspace_id: workspaceId });+ fetch(`/api/agents/${agent.id}?${params}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ instructions: instructionsRef.current }),+ keepalive: true,+ });}};- }, [flushInstructions]);+ }, [agent.id, workspaceId]);const selectedRuntime = runtimes.find((r) => r.id === runtimeId);const providerModels =diff --git a/src/web/src/components/canvas/active-tasks-float.tsx b/src/web/src/components/canvas/active-tasks-float.tsxindex 45852f694..e97114e5c 100644--- a/src/web/src/components/canvas/active-tasks-float.tsx+++ b/src/web/src/components/canvas/active-tasks-float.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useRef, useEffect } from "react";+import { useState, useRef, useEffect, useCallback } from "react";import Link from "next/link";import { X } from "lucide-react";import { useAgentContext } from "@/contexts/agent-context";@@ -9,6 +9,7 @@ import { useIsMobile } from "@/hooks/use-mobile";import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";import type { WorkspaceActiveTask } from "@/lib/api";import { relativeTime } from "@/lib/time";+import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";function AgentAvatar({ name, avatarUrl, size = 20 }: { name?: string; avatarUrl?: string | null; size?: number }) {const config = parseAvatarUrl(avatarUrl);@@ -23,12 +24,31 @@ function AgentAvatar({ name, avatarUrl, size = 20 }: { name?: string; avatarUrl?);}-function TaskRow({ task, slug }: { task: WorkspaceActiveTask; slug: string }) {+function TaskRow({+ task,+ slug,+ onOpenChat,+}: {+ task: WorkspaceActiveTask;+ slug: string;+ onOpenChat: (agentId: string, opts: { conversationId?: string; taskId?: string }) => void;+}) {const isRunning = task.status === "running";+ const href = `/w/${slug}/agents/${task.agent_id}?task=${task.id}&conv=${task.conversation_id}`;++ const handleClick = useCallback((e: React.MouseEvent) => {+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;+ e.preventDefault();+ onOpenChat(task.agent_id, {+ conversationId: task.conversation_id,+ taskId: task.id,+ });+ }, [task.agent_id, task.conversation_id, task.id, onOpenChat]);return (- <Link- href={`/w/${slug}/agents/${task.agent_id}?task=${task.id}&conv=${task.conversation_id}`}+ <a+ href={href}+ onClick={handleClick}className="flex items-center gap-2.5 px-3 py-2 hover:bg-accent/50 transition-colors cursor-pointer rounded-md"><div className="relative shrink-0">@@ -55,7 +75,7 @@ function TaskRow({ task, slug }: { task: WorkspaceActiveTask; slug: string }) {<span className="text-xs text-muted-foreground whitespace-nowrap shrink-0">{relativeTime(task.created_at)}</span>- </Link>+ </a>);}@@ -63,6 +83,7 @@ export function ActiveTasksFloat() {const { activeTaskDetails } = useAgentContext();const { slug } = useWorkspace();const isMobile = useIsMobile();+ const { openAgentChat } = useAgentChatSheet();const [expanded, setExpanded] = useState(false);const prevTaskIdsRef = useRef<Set<string>>(new Set());@@ -122,7 +143,7 @@ export function ActiveTasksFloat() {<div className="max-h-75 overflow-y-auto thin-scrollbar py-1">{tasks.slice(0, 8).map((task) => (- <TaskRow key={task.id} task={task} slug={slug} />+ <TaskRow key={task.id} task={task} slug={slug} onOpenChat={openAgentChat} />))}{taskCount > 8 && (<Linkdiff --git a/src/web/src/components/canvas/agent-chat-sheet.tsx b/src/web/src/components/canvas/agent-chat-sheet.tsxindex 7616ab2b2..51f31ce96 100644--- a/src/web/src/components/canvas/agent-chat-sheet.tsx+++ b/src/web/src/components/canvas/agent-chat-sheet.tsx@@ -1,6 +1,7 @@"use client";import React, { useState, useRef, useCallback } from "react";+import { useRouter } from "next/navigation";import {Sheet,SheetContent,@@ -10,21 +11,27 @@ import {import type { Agent } from "@alook/shared";import { AnimatedAvatar, parseAvatarUrl } from "@/components/avatar";import { useAgentContext } from "@/contexts/agent-context";+import { useWorkspace } from "@/contexts/workspace-context";import { ChannelBar } from "@/components/channel-bar";import { AgentChatView } from "@/components/agent-chat/agent-chat-view";+import { ArrowUpRight } from "lucide-react";interface AgentChatSheetProps {open: boolean;onOpenChange: (open: boolean) => void;agent: Agent | null;+ targetConvId?: string | null;+ scrollToTaskId?: string | null;}const MIN_WIDTH = 320;const MAX_WIDTH_RATIO = 0.8;const DEFAULT_WIDTH = 480;-export function AgentChatSheet({ open, onOpenChange, agent }: AgentChatSheetProps) {+export function AgentChatSheet({ open, onOpenChange, agent, targetConvId, scrollToTaskId }: AgentChatSheetProps) {const { runtimes, activeTaskCounts } = useAgentContext();+ const { slug } = useWorkspace();+ const router = useRouter();const [width, setWidth] = useState(DEFAULT_WIDTH);const dragging = useRef(false);@@ -79,16 +86,45 @@ export function AgentChatSheet({ open, onOpenChange, agent }: AgentChatSheetProp<span className="text-xs text-muted-foreground truncate">{agent.email_handle}@alook.ai</span>)}</div>+ {agent && (() => {+ const params = new URLSearchParams();+ if (scrollToTaskId) params.set("task", scrollToTaskId);+ if (targetConvId) params.set("conv", targetConvId);+ const qs = params.toString();+ const fullPageUrl = `/w/${slug}/agents/${agent.id}${qs ? `?${qs}` : ""}`;+ return (+ <a+ href={fullPageUrl}+ onClick={(e) => {+ if (e.metaKey || e.ctrlKey || e.shiftKey) return;+ e.preventDefault();+ onOpenChange(false);+ router.push(fullPageUrl);+ }}+ className="shrink-0 flex items-center justify-center size-7 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"+ title="Open full page"+ >+ <ArrowUpRight className="size-4" />+ </a>+ );+ })()}</div></SheetHeader>- <div className="px-4 pb-2">- <ChannelBar />- </div>+ {!targetConvId && (+ <div className="px-4 pb-2">+ <ChannelBar />+ </div>+ )}{agent && (<div className="flex-1 overflow-hidden flex flex-col">- <AgentChatView agentId={agent.id} />+ <AgentChatView+ key={`${agent.id}-${targetConvId ?? ""}`}+ agentId={agent.id}+ targetConvId={targetConvId}+ scrollToTaskId={scrollToTaskId}+ /></div>)}</SheetContent>diff --git a/src/web/src/components/inbox-popover.tsx b/src/web/src/components/inbox-popover.tsxindex a6cbc3f9a..9386e3797 100644--- a/src/web/src/components/inbox-popover.tsx+++ b/src/web/src/components/inbox-popover.tsx@@ -1,17 +1,18 @@"use client";import { useState, useCallback } from "react";-import Link from "next/link";import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";import { Skeleton } from "@/components/ui/skeleton";import { cn } from "@/lib/utils";import { listInboxItems, type InboxItem } from "@/lib/api";import { useWorkspace } from "@/contexts/workspace-context";import { useInboxCount } from "@/contexts/inbox-count-context";+import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";import { AgentAvatar } from "@/components/avatar";import { relativeTime } from "@/lib/time";import { getInboxFilterTypes } from "@/lib/inbox-filter";import { Inbox, ArrowUpRight } from "lucide-react";+import Link from "next/link";function InboxPopoverRow({item,@@ -20,10 +21,10 @@ function InboxPopoverRow({}: {item: InboxItem;slug: string;- onClick: () => void;+ onClick: (e: React.MouseEvent) => void;}) {return (- <Link+ <ahref={`/w/${slug}/agents/${item.agent_id}?conv=${item.id}`}onClick={onClick}className="block w-full py-1.5 px-2 hover:bg-muted rounded-md transition-colors cursor-pointer"@@ -40,7 +41,7 @@ function InboxPopoverRow({<p className="text-xs text-muted-foreground truncate mt-0.5 pl-8">{item.root_prompt ?? item.title}</p>- </Link>+ </a>);}@@ -55,6 +56,7 @@ export function InboxPopover({}) {const { slug, workspaceId } = useWorkspace();const { count: inboxCount, decrement } = useInboxCount();+ const { openAgentChat } = useAgentChatSheet();const [items, setItems] = useState<InboxItem[] | null>(null);const [loading, setLoading] = useState(false);const [open, setOpen] = useState(false);@@ -75,11 +77,14 @@ export function InboxPopover({}}, [workspaceId]);- const handleRowClick = () => {+ const handleRowClick = useCallback((item: InboxItem, e: React.MouseEvent) => {+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;+ e.preventDefault();decrement();setOpen(false);onNavigate?.();- };+ openAgentChat(item.agent_id, { conversationId: item.id });+ }, [decrement, onNavigate, openAgentChat]);return (<Popover@@ -149,7 +154,7 @@ export function InboxPopover({key={item.id}item={item}slug={slug}- onClick={handleRowClick}+ onClick={(e) => handleRowClick(item, e)}/>))}</div>diff --git a/src/web/src/components/issues/issue-sheet.tsx b/src/web/src/components/issues/issue-sheet.tsxindex f5dc5f7b3..ffc5634d6 100644--- a/src/web/src/components/issues/issue-sheet.tsx+++ b/src/web/src/components/issues/issue-sheet.tsx@@ -263,6 +263,28 @@ export function IssueSheet({const autoSaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const onUpdateRef = useRef(onUpdate);useEffect(() => { onUpdateRef.current = onUpdate; }, [onUpdate]);+ const titleRef2 = useRef(title);+ useEffect(() => { titleRef2.current = title; }, [title]);+ const descriptionRef2 = useRef(description);+ useEffect(() => { descriptionRef2.current = description; }, [description]);+ const issueRef = useRef(issue);+ useEffect(() => { issueRef.current = issue; }, [issue]);++ const flushAutoSave = useCallback(() => {+ if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current);+ autoSaveTimer.current = null;+ const iss = issueRef.current;+ if (!iss) return;+ const titleChanged = titleRef2.current !== iss.title;+ const descChanged = descriptionRef2.current !== (iss.description ?? "");+ if (!titleChanged && !descChanged) return;+ if (!titleRef2.current.trim()) return;+ const patch: { title?: string; description?: string } = {};+ if (titleChanged) patch.title = titleRef2.current.trim();+ if (descChanged) patch.description = descriptionRef2.current.trim();+ onUpdateRef.current?.(iss.id, patch);+ }, []);+useEffect(() => {if (mode !== "detail" || !issue || !open) return;const titleChanged = title !== issue.title;@@ -271,15 +293,19 @@ export function IssueSheet({if (!title.trim()) return;if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current);- autoSaveTimer.current = setTimeout(() => {- const patch: { title?: string; description?: string } = {};- if (titleChanged) patch.title = title.trim();- if (descChanged) patch.description = description.trim();- onUpdateRef.current?.(issue.id, patch);- }, 500);+ autoSaveTimer.current = setTimeout(flushAutoSave, 500);return () => { if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current); };- }, [title, description, mode, issue, open]);+ }, [title, description, mode, issue, open, flushAutoSave]);++ // Flush pending auto-save when sheet closes+ const prevOpenRef = useRef(open);+ useEffect(() => {+ if (prevOpenRef.current && !open && mode === "detail") {+ flushAutoSave();+ }+ prevOpenRef.current = open;+ }, [open, mode, flushAutoSave]);// --- Title auto-resize ---const resizeTitle = useCallback((el?: HTMLTextAreaElement | null) => {diff --git a/src/web/src/components/workspace-shell.tsx b/src/web/src/components/workspace-shell.tsxindex 4e7a92697..3fe96b396 100644--- a/src/web/src/components/workspace-shell.tsx+++ b/src/web/src/components/workspace-shell.tsx@@ -10,6 +10,7 @@ import {SheetContent,} from "@/components/ui/sheet";import { RuntimeVersionGate } from "@/components/runtime-version-gate";+import { AgentChatSheetProvider } from "@/contexts/agent-chat-sheet-context";const SidebarTriggerContext = createContext<(() => void) | null>(null);@@ -24,35 +25,39 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {if (isMobile) {return (<SidebarTriggerContext.Provider value={() => setSidebarOpen(true)}>- <div className="flex flex-col h-dvh overflow-hidden relative">- <GradientBackground />- <div className="flex-1 min-h-0 px-2 pb-2 pt-2 flex flex-col">- <MobileTopBar />- <main className="flex-1 min-h-0 rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">- {children}- </main>+ <AgentChatSheetProvider>+ <div className="flex flex-col h-dvh overflow-hidden relative">+ <GradientBackground />+ <div className="flex-1 min-h-0 px-2 pb-2 pt-2 flex flex-col">+ <MobileTopBar />+ <main className="flex-1 min-h-0 rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">+ {children}+ </main>+ </div>+ <Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>+ <SheetContent side="left" showCloseButton={false} style={{ width: 56 }} className="p-0">+ <AppSidebar onNavigate={() => setSidebarOpen(false)} />+ </SheetContent>+ </Sheet>+ <RuntimeVersionGate /></div>- <Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>- <SheetContent side="left" showCloseButton={false} style={{ width: 56 }} className="p-0">- <AppSidebar onNavigate={() => setSidebarOpen(false)} />- </SheetContent>- </Sheet>- <RuntimeVersionGate />- </div>+ </AgentChatSheetProvider></SidebarTriggerContext.Provider>);}return (- <div className="flex h-dvh overflow-hidden relative">- <GradientBackground />- <AppSidebar />- <div className="flex-1 flex flex-col min-w-0 pt-2 pr-2 pb-2">- <main className="flex-1 min-h-0 rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">- {children}- </main>+ <AgentChatSheetProvider>+ <div className="flex h-dvh overflow-hidden relative">+ <GradientBackground />+ <AppSidebar />+ <div className="flex-1 flex flex-col min-w-0 pt-2 pr-2 pb-2">+ <main className="flex-1 min-h-0 rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">+ {children}+ </main>+ </div>+ <RuntimeVersionGate /></div>- <RuntimeVersionGate />- </div>+ </AgentChatSheetProvider>);}diff --git a/src/web/src/contexts/agent-chat-sheet-context.tsx b/src/web/src/contexts/agent-chat-sheet-context.tsxnew file mode 100644index 000000000..cdc009cff--- /dev/null+++ b/src/web/src/contexts/agent-chat-sheet-context.tsx@@ -0,0 +1,86 @@+"use client";++import {+ createContext,+ useContext,+ useState,+ useCallback,+ useRef,+ type ReactNode,+} from "react";+import { useRouter } from "next/navigation";+import { useAgentContext } from "@/contexts/agent-context";+import { useWorkspace } from "@/contexts/workspace-context";+import { AgentChatSheet } from "@/components/canvas/agent-chat-sheet";++interface AgentChatSheetContextValue {+ openAgentChat: (+ agentId: string,+ opts?: { conversationId?: string; taskId?: string },+ ) => void;+}++const AgentChatSheetContext = createContext<AgentChatSheetContextValue | null>(+ null,+);++export function useAgentChatSheet() {+ const ctx = useContext(AgentChatSheetContext);+ if (!ctx)+ throw new Error(+ "useAgentChatSheet must be used within AgentChatSheetProvider",+ );+ return ctx;+}++export function AgentChatSheetProvider({ children }: { children: ReactNode }) {+ const router = useRouter();+ const { agents } = useAgentContext();+ const { slug } = useWorkspace();++ const [open, setOpen] = useState(false);+ const [agentId, setAgentId] = useState<string | null>(null);+ const [targetConvId, setTargetConvId] = useState<string | null>(null);+ const [scrollToTaskId, setScrollToTaskId] = useState<string | null>(null);++ const agent = agentId ? agents.find((a) => a.id === agentId) ?? null : null;++ const agentsRef = useRef(agents);+ agentsRef.current = agents;++ const openAgentChat = useCallback(+ (id: string, opts?: { conversationId?: string; taskId?: string }) => {+ const found = agentsRef.current.find((a) => a.id === id);+ if (!found) {+ router.push(`/w/${slug}/agents/${id}`);+ return;+ }+ setAgentId(id);+ setTargetConvId(opts?.conversationId ?? null);+ setScrollToTaskId(opts?.taskId ?? null);+ setOpen(true);+ },+ [router, slug],+ );++ const handleOpenChange = useCallback((nextOpen: boolean) => {+ setOpen(nextOpen);+ if (!nextOpen) {+ setTargetConvId(null);+ setScrollToTaskId(null);+ }+ }, []);++ return (+ <AgentChatSheetContext.Provider value={{ openAgentChat }}>+ {children}+ <AgentChatSheet+ open={open}+ onOpenChange={handleOpenChange}+ agent={agent}+ targetConvId={targetConvId}+ scrollToTaskId={scrollToTaskId}+ />+ </AgentChatSheetContext.Provider>+ );+}diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.tsindex 1bd3ee24b..e6cb856f0 100644--- a/src/web/src/lib/services/task.test.ts+++ b/src/web/src/lib/services/task.test.ts@@ -486,6 +486,9 @@ describe("TaskService", () => {agentQ.updateAgentStatus.mockResolvedValue(undefined);issueQ.getIssueByConversation.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });issueQ.updateIssue.mockResolvedValue({ id: "iss_1", status: "failed", conversationId: "c1" });+ const eventMsg = { id: "m1", conversationId: "c1", role: "event", content: "Issue status changed: in_progress -> failed" };+ messageQ.createMessage.mockResolvedValueOnce(undefined).mockResolvedValueOnce(eventMsg);+ conversationQ.getConversation.mockResolvedValue({ id: "c1", userId: "u1", workspaceId: "w1" });await service.failTask("t1", "w1", "something went wrong");@@ -503,6 +506,11 @@ describe("TaskService", () => {taskId: "t1",metadata: JSON.stringify({ issueId: "iss_1" }),});+ expect(broadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({+ type: "conversation.message",+ conversationId: "c1",+ message: eventMsg,+ }));});});diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.tsindex 840630dbe..99957e95c 100644--- a/src/web/src/lib/services/task.ts+++ b/src/web/src/lib/services/task.ts@@ -196,13 +196,26 @@ export class TaskService {const updated = await issueQueries.updateIssue(this.db, issue.id, task.workspaceId, { status });if (!updated) return;- await messageQueries.createMessage(this.db, {+ const eventMsg = await messageQueries.createMessage(this.db, {conversationId: task.conversationId,role: "event",content: `Issue status changed: ${issue.status} -> ${status}`,taskId: task.id,metadata: JSON.stringify({ issueId: issue.id }),});++ try {+ const conversation = await conversationQueries.getConversation(this.db, task.conversationId, task.workspaceId);+ if (conversation) {+ broadcastToUser(conversation.userId, {+ type: "conversation.message",+ conversationId: task.conversationId,+ message: messageToResponse(eventMsg),+ }).catch(() => {});+ }+ } catch {+ // non-critical: don't let broadcast failure block task lifecycle+ }}async supersedeTask(taskId: string, workspaceId: string) {