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: task streaming loss when refresh
Gusefcc6b9f1ab2
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex 4a5433c33..05d93144d 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -59,6 +59,7 @@ those json are sorted by datetime in asc order.- When you start a new task, read the last ~10 lines of today's timeline to understand what has been asked and done recently.- if you don't know the current datetime, obtain the current datetime first.- When user ask you something you don't have in your current context, try to read the timeline jsonl files for answer (today or previous days).+- When access other local projects, make sure you read the CLAUDE.md/AGENTS.md file under the project root dir to understand the requirements.`;export function buildInstructionContent(task: Task): string {@@ -116,6 +117,7 @@ You have your own calendar to setup daily routines and reminders.Schedule future tasks for yourself. At the scheduled time, a new task is dispatched to you with the event as the prompt (task type 'calendar_event').!USE Calendar when you think the tasks are recurring or it should be conducted in the future.+!When scheduling calendar events relative to a weekday (e.g. "every Monday"), always run date '+%A' first to confirm today's weekday before calculating the target date---Keep the event title informative and concise, less than 20 words.Place the event details in description.diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.tsindex 777d69f1c..5ddbc5138 100644--- a/src/shared/src/db/queries/task.ts+++ b/src/shared/src/db/queries/task.ts@@ -249,3 +249,23 @@ export async function countRunningTasks(db: Database, agentId: string, workspace);return Number(rows[0]?.value ?? 0);}++export async function getActiveTaskByConversation(+ db: Database,+ conversationId: string,+ workspaceId: string+) {+ const rows = await db+ .select()+ .from(agentTaskQueue)+ .where(+ and(+ eq(agentTaskQueue.conversationId, conversationId),+ eq(agentTaskQueue.workspaceId, workspaceId),+ inArray(agentTaskQueue.status, ["queued", "dispatched", "running"])+ )+ )+ .orderBy(desc(agentTaskQueue.createdAt))+ .limit(1);+ return rows[0] ?? null;+}diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex 7fcdc0a9f..876bd6f91 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -159,4 +159,5 @@ export type WsMessage =| { type: "runtime.status"; daemonId: string; workspaceId: string; status: string }| { type: "runtime.deleted"; daemonId: string }| { type: "task.updated"; taskId: string; status: string }+ | { type: "task.messages"; taskId: string; messages: TaskMessage[] }| { type: "email.received"; agentId: string }diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts b/src/web/src/app/api/conversations/[id]/active-task/route.test.tsnew file mode 100644index 000000000..8642964de--- /dev/null+++ b/src/web/src/app/api/conversations/[id]/active-task/route.test.ts@@ -0,0 +1,81 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetConversation = vi.fn();+const mockGetActiveTaskByConversation = vi.fn();+const mockTaskToResponse = vi.fn((t: any) => ({ id: t.id, status: t.status }));++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ conversation: {+ getConversation: (...args: any[]) => mockGetConversation(...args),+ },+ task: {+ getActiveTaskByConversation: (...args: any[]) => mockGetActiveTaskByConversation(...args),+ },+ },+}));+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;+ return handler(req, { userId: "u1", email: "[email protected]", params });+ }),+}));+vi.mock("@/lib/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));+vi.mock("@/lib/api/responses", () => ({+ taskToResponse: (...args: any[]) => mockTaskToResponse(...args),+}));++import { GET } from "./route";++const withParams = (id: string) => ({ params: Promise.resolve({ id }) });++describe("GET /api/conversations/[id]/active-task", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns active task when one exists", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });+ mockGetActiveTaskByConversation.mockResolvedValue({ id: "t1", status: "running" });++ const res = await GET(+ new NextRequest("http://localhost/api/conversations/c1/active-task"),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ id: "t1", status: "running" });+ expect(mockGetActiveTaskByConversation).toHaveBeenCalledWith({}, "c1", "w1");+ });++ it("returns 204 when no active task", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });+ mockGetActiveTaskByConversation.mockResolvedValue(null);++ const res = await GET(+ new NextRequest("http://localhost/api/conversations/c1/active-task"),+ withParams("c1")+ );++ expect(res.status).toBe(204);+ });++ it("returns 404 when conversation not found", async () => {+ mockGetConversation.mockResolvedValue(null);++ const res = await GET(+ new NextRequest("http://localhost/api/conversations/c1/active-task"),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("conversation not found");+ });+});diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.ts b/src/web/src/app/api/conversations/[id]/active-task/route.tsnew file mode 100644index 000000000..1f554a139--- /dev/null+++ b/src/web/src/app/api/conversations/[id]/active-task/route.ts@@ -0,0 +1,31 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { createDb, queries } from "@alook/shared"+import { withAuth } from "@/lib/middleware/auth";+import { withWorkspaceMember } from "@/lib/middleware/workspace";+import { writeJSON, writeError } from "@/lib/middleware/helpers";+import { taskToResponse } from "@/lib/api/responses";++export const GET = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ const { env } = getCloudflareContext()+ const db = createDb((env as Env).DB)++ const id = ctx.params?.id;+ if (!id) {+ return writeError("conversation id is required", 400);+ }++ const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);+ if (!conversation) {+ return writeError("conversation not found", 404);+ }++ const task = await queries.task.getActiveTaskByConversation(db, id, ws.workspaceId);+ if (!task) {+ return new Response(null, { status: 204 });+ }++ return writeJSON(taskToResponse(task));+});diff --git a/src/web/src/app/api/daemon/routes.test.ts b/src/web/src/app/api/daemon/routes.test.tsindex 0a6a5685e..839c896d1 100644--- a/src/web/src/app/api/daemon/routes.test.ts+++ b/src/web/src/app/api/daemon/routes.test.ts@@ -521,6 +521,9 @@ describe("daemon route body validation", () => {vi.doMock("@/lib/api/responses", () => ({taskMessageToResponse: (m: any) => m,}));+ vi.doMock("@/lib/broadcast", () => ({+ broadcastToUser: vi.fn().mockResolvedValue(undefined),+ }));return (await import("./tasks/[taskId]/messages/route")).POST;}@@ -536,5 +539,93 @@ describe("daemon route body validation", () => {expect(res.status).toBe(400);});++ it("broadcasts task.messages via WebSocket after writing to DB", async () => {+ vi.resetModules();+ applyBase();++ const createMock = vi.fn().mockResolvedValue(undefined);+ const broadcastMock = vi.fn().mockResolvedValue(undefined);++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ taskMessage: { createTaskMessage: createMock },+ },+ };+ });+ vi.doMock("@/lib/api/responses", () => ({+ taskMessageToResponse: (m: any) => m,+ }));+ vi.doMock("@/lib/broadcast", () => ({+ broadcastToUser: broadcastMock,+ }));++ const POST = (await import("./tasks/[taskId]/messages/route")).POST;+ const res = await POST(+ postReq("http://localhost/api/daemon/tasks/t1/messages", {+ messages: [+ { seq: 1, type: "text", content: "hello" },+ { seq: 2, type: "tool-use", tool: "Read", content: "" },+ ],+ }),+ { params: Promise.resolve({ taskId: "t1" }) }+ );++ expect(res.status).toBe(200);+ expect(broadcastMock).toHaveBeenCalledWith(+ daemonAuth.userId,+ expect.objectContaining({+ type: "task.messages",+ taskId: "t1",+ messages: expect.arrayContaining([+ expect.objectContaining({ seq: 1, type: "text", content: "hello" }),+ expect.objectContaining({ seq: 2, type: "tool-use", tool: "Read" }),+ ]),+ })+ );+ });++ it("does not broadcast when messages array is empty", async () => {+ vi.resetModules();+ applyBase();++ const broadcastMock = vi.fn().mockResolvedValue(undefined);++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ taskMessage: { createTaskMessage: vi.fn().mockResolvedValue(undefined) },+ },+ };+ });+ vi.doMock("@/lib/api/responses", () => ({+ taskMessageToResponse: (m: any) => m,+ }));+ vi.doMock("@/lib/broadcast", () => ({+ broadcastToUser: broadcastMock,+ }));++ const POST = (await import("./tasks/[taskId]/messages/route")).POST;+ const res = await POST(+ postReq("http://localhost/api/daemon/tasks/t1/messages", {+ messages: [],+ }),+ { params: Promise.resolve({ taskId: "t1" }) }+ );++ expect(res.status).toBe(200);+ expect(broadcastMock).not.toHaveBeenCalled();+ });});});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.tsindex b928feadf..eae21f853 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts@@ -1,10 +1,12 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare"import { createDb, queries } from "@alook/shared"+import type { TaskMessage } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { taskMessageToResponse } from "@/lib/api/responses";import { ReportMessagesRequestSchema } from "@alook/shared";+import { broadcastToUser } from "@/lib/broadcast";import { log } from "@/lib/logger";export const GET = withAuth(async (_req, ctx) => {@@ -36,7 +38,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ status: "ok" });}- await Promise.all(+ const results = await Promise.allSettled(body.messages.map((m) =>queries.taskMessage.createTaskMessage(db, {taskId,@@ -47,11 +49,31 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {content: m.content || "",input: m.input,output: m.output || "",- }).catch((e) => {- log.warn("Failed to create task message", { taskId, err: e });})));+ results.forEach((r, i) => {+ if (r.status === "rejected") {+ log.warn("Failed to create task message", { taskId, err: r.reason });+ }+ });++ const succeeded = body.messages.filter((_, i) => results[i].status === "fulfilled");+ if (succeeded.length > 0) {+ const wsMessages: TaskMessage[] = succeeded.map((m) => ({+ id: "",+ task_id: taskId,+ seq: m.seq,+ type: m.type,+ tool: m.tool || "",+ call_id: m.call_id || "",+ content: m.content || "",+ output: m.output || "",+ ...(m.input ? { input: m.input } : {}),+ }));+ broadcastToUser(ctx.userId, { type: "task.messages", taskId, messages: wsMessages }).catch(() => {});+ }+return writeJSON({ status: "ok" });});diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex defb894a3..30296b4d8 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -809,9 +809,17 @@margin-bottom: 0.75em;border-radius: 0.5em;overflow-x: auto;+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;font-size: 0.85em;line-height: 1.6;- width: 100%;+ max-width: 100%;+ min-width: 0;+}+.markdown pre code {+ overflow-x: auto;+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ font-size: inherit;+ line-height: inherit;}.markdown pre:not(:has(> code)) {padding: 0.75em 1em;@@ -836,10 +844,13 @@}.markdown table {width: 100%;+ max-width: 100%;margin-top: 0.75em;margin-bottom: 0.75em;border-collapse: collapse;font-size: 0.9em;+ table-layout: fixed;+ overflow-wrap: break-word;}.markdown th,.markdown td {@@ -950,14 +961,20 @@padding: 0.5rem 0.75rem !important;border-radius: 0 !important;border: none !important;+ max-width: 100% !important;+ overflow-x: auto !important;--sdm-bg: #24292e !important;--sdm-fg: #e1e4e8 !important;background-color: #24292e !important;color: #e1e4e8 !important;+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important;}-[data-streamdown="code-block-body"] pre {+[data-streamdown="code-block-body"] pre,+[data-streamdown="code-block-body"] pre code,+[data-streamdown="code-block-body"] pre code span {background-color: #24292e !important;color: #e1e4e8 !important;+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important;}/* Actions wrapper: anchor inside top-right of code body */@@ -1038,8 +1055,8 @@[data-streamdown="table-cell"] {padding: 0.4em 0.75em !important;text-align: left !important;- white-space: nowrap;border-bottom: 1px solid var(--border) !important;+ overflow-wrap: break-word;}[data-streamdown="table-header-cell"] {diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex 3d08bb21c..77981ac1b 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -11,8 +11,10 @@ import {sendMessage,getTask,getTaskMessages,+ getActiveTask,} from "@/lib/api";-import type { Conversation, Message, TaskApi as Task, TaskMessage } from "@alook/shared";+import type { Conversation, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";+import { useAgentContext } from "@/contexts/agent-context";import { toast } from "sonner";import { cn } from "@/lib/utils";import { Skeleton } from "@/components/ui/skeleton";@@ -41,6 +43,7 @@ export function mergeMessages(existing: Message[], incoming: Message[]): Messageexport function AgentChatView() {const params = useParams();const { workspaceId } = useWorkspace();+ const { subscribeWs } = useAgentContext();const agentId = params.id as string;const [conversation, setConversation] = useState<Conversation | null>(null);@@ -61,6 +64,7 @@ export function AgentChatView() {const initialScrollDone = useRef(false);const loadingMoreRef = useRef(false);const isNearBottom = useRef(true);+ const startPollingRef = useRef<(taskId: string, conversationId: string, initialSeq?: number) => void>(null!);const scrollToBottom = useCallback(() => {isNearBottom.current = true;@@ -72,7 +76,7 @@ export function AgentChatView() {}, 50);}, []);- // Resolve conversation (get or create) then load messages+ // Resolve conversation (get or create) then load messages + recover active taskuseEffect(() => {async function load() {try {@@ -81,6 +85,20 @@ export function AgentChatView() {const msgs = await listMessages(conv.id, workspaceId, { limit: MESSAGE_LIMIT });setMessages(msgs);setHasMore(msgs.length >= MESSAGE_LIMIT);++ // Recover active task (e.g. after page refresh)+ const task = await getActiveTask(conv.id, workspaceId);+ if (task) {+ setActiveTask(task);+ const tmsgs = await getTaskMessages(task.id, workspaceId);+ if (tmsgs.length > 0) {+ setTaskMessages(tmsgs);+ lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq));+ }+ if (task.status !== "completed" && task.status !== "failed") {+ startPollingRef.current(task.id, conv.id, lastSeqRef.current);+ }+ }} catch {toast.error("Failed to load conversation");} finally {@@ -175,9 +193,9 @@ export function AgentChatView() {}, [loadOlderMessages, loadingMore, hasMore]);const startPolling = useCallback(- (taskId: string, conversationId: string) => {+ (taskId: string, conversationId: string, initialSeq?: number) => {if (pollRef.current) clearInterval(pollRef.current);- lastSeqRef.current = 0;+ lastSeqRef.current = initialSeq ?? 0;pollFailures.current = 0;setConnectionLost(false);@@ -193,7 +211,11 @@ export function AgentChatView() {setActiveTask(task);if (tmsgs.length > 0) {- setTaskMessages((prev) => [...prev, ...tmsgs]);+ setTaskMessages((prev) => {+ const existingSeqs = new Set(prev.map((m) => m.seq));+ const unique = tmsgs.filter((m) => !existingSeqs.has(m.seq));+ return unique.length > 0 ? [...prev, ...unique] : prev;+ });lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq),lastSeqRef.current@@ -226,10 +248,11 @@ export function AgentChatView() {toast.error("Lost connection to agent");}}- }, 1000);+ }, 3000);},[workspaceId, scrollToBottom]);+ startPollingRef.current = startPolling;useEffect(() => {return () => {@@ -237,6 +260,28 @@ export function AgentChatView() {};}, []);+ const activeTaskIdRef = useRef<string | null>(null);++ useEffect(() => {+ activeTaskIdRef.current = activeTask?.id ?? null;+ }, [activeTask]);++ useEffect(() => {+ return subscribeWs((msg: WsMessage) => {+ if (msg.type === "task.messages" && msg.taskId === activeTaskIdRef.current) {+ const incoming = msg.messages.filter((m) => m.seq > lastSeqRef.current);+ if (incoming.length > 0) {+ setTaskMessages((prev) => {+ const existingSeqs = new Set(prev.map((m) => m.seq));+ const unique = incoming.filter((m) => !existingSeqs.has(m.seq));+ return unique.length > 0 ? [...prev, ...unique] : prev;+ });+ lastSeqRef.current = Math.max(...incoming.map((m) => m.seq), lastSeqRef.current);+ }+ }+ });+ }, [subscribeWs]);+const handleSend = async () => {const content = input.trim();if (!content || sending || !conversation) return;@@ -332,7 +377,7 @@ export function AgentChatView() {<>{/* Messages */}<div- className="flex-1 overflow-y-auto px-5 thin-scrollbar"+ className="flex-1 overflow-y-auto overflow-x-hidden px-5 thin-scrollbar"ref={scrollRef}onScroll={handleScroll}onClick={(e) => {@@ -381,7 +426,7 @@ export function AgentChatView() {</div>) : !hasTaskStream ? (<div className="flex justify-start">- <div className="markdown max-w-full px-1 py-1 text-base text-foreground">+ <div className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground"><Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{msg.content}</Streamdown></div></div>diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsxindex 5057fc0cd..87fa5d14a 100644--- a/src/web/src/components/task-stream.tsx+++ b/src/web/src/components/task-stream.tsx@@ -54,18 +54,23 @@ type StreamItem = ToolCallGroup | TextItem | ThinkingItem | StatusItem;/** Types that are agent-internal lifecycle events, never user-facing. */const HIDDEN_TYPES = new Set(["status", "log"]);+function itemKey(msg: TaskMessage): string {+ return msg.id || `seq-${msg.seq}`;+}+function groupMessages(messages: TaskMessage[]): StreamItem[] {const items: StreamItem[] = [];const toolCalls = new Map<string, ToolCallGroup>();for (const msg of messages) {if (HIDDEN_TYPES.has(msg.type)) continue;+ const key = itemKey(msg);switch (msg.type) {case "tool-use": {const callId = msg.call_id;const group: ToolCallGroup = {kind: "tool-call",- id: msg.id,+ id: key,tool: msg.tool,input: msg.input,};@@ -87,7 +92,7 @@ function groupMessages(messages: TaskMessage[]): StreamItem[] {} else {items.push({kind: "status",- id: msg.id,+ id: key,content: msg.output || msg.content,type: "tool-result",});@@ -96,15 +101,15 @@ function groupMessages(messages: TaskMessage[]): StreamItem[] {break;}case "text":- items.push({ kind: "text", id: msg.id, content: msg.content });+ items.push({ kind: "text", id: key, content: msg.content });break;case "thinking":- items.push({ kind: "thinking", id: msg.id, content: msg.content });+ items.push({ kind: "thinking", id: key, content: msg.content });break;case "error":items.push({kind: "status",- id: msg.id,+ id: key,content: msg.content || msg.output,type: "error",});@@ -155,12 +160,12 @@ function ToolCallBlock({ item, isRunning }: { item: ToolCallGroup; isRunning: bo{hasDetails && (<div className="mt-1 mb-2 ml-5 space-y-2">{inputStr && (- <pre className="task-stream-pre overflow-x-auto rounded-md bg-muted/40 p-2.5 font-mono text-xs leading-relaxed text-muted-foreground max-h-48 overflow-y-auto">+ <pre className="task-stream-pre overflow-x-auto rounded-md bg-muted/40 p-2.5 font-mono text-xs leading-relaxed text-muted-foreground max-h-48 max-w-full min-w-0 overflow-y-auto">{inputStr}</pre>)}{item.output && (- <pre className="task-stream-pre overflow-x-auto rounded-md bg-muted/30 border border-border/50 p-2.5 font-mono text-xs leading-relaxed text-foreground/70 max-h-48 overflow-y-auto">+ <pre className="task-stream-pre overflow-x-auto rounded-md bg-muted/30 border border-border/50 p-2.5 font-mono text-xs leading-relaxed text-foreground/70 max-h-48 max-w-full min-w-0 overflow-y-auto">{item.output}</pre>)}@@ -358,7 +363,7 @@ export function TaskStream({{textItems.map((item) => (<divkey={item.id}- className="markdown max-w-full px-1 py-1 text-base text-foreground"+ className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground"><Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{item.content}</Streamdown></div>diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 38cc5b4dc..527064d3f 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -186,6 +186,10 @@ export const sendMessage = (conversationId: string, content: string, workspaceId});+// Active task for conversation (recovery on page refresh)+export const getActiveTask = (conversationId: string, workspaceId: string) =>+ apiFetch<TaskApi | undefined>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`);+// Machine tokensexport const createMachineToken = (name?: string, workspaceId?: string) =>apiFetch<{ token: string; id: string; name: string; created_at: string }>(