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
feat: slim TaskMessage response and position new agents relative to parent on canvas
Gus40eb1f15f953
diff --git a/src/shared/src/api-types.ts b/src/shared/src/api-types.tsindex 70060de15..40840e2ee 100644--- a/src/shared/src/api-types.ts+++ b/src/shared/src/api-types.ts@@ -5,7 +5,7 @@ import type {AgentRuntime,Conversation,Message,- TaskMessage,+ TaskMessageResponse,MachineToken,CalendarEvent,Issue,@@ -44,7 +44,7 @@ export type ListMessagesResponse = ApiListResponse<Message>;export type ListTasksResponse = ApiListResponse<TaskApi>;export type GetTaskResponse = ApiResponse<TaskApi>;-export type ListTaskMessagesResponse = ApiListResponse<TaskMessage>;+export type ListTaskMessagesResponse = ApiListResponse<TaskMessageResponse>;export type ListMachineTokensResponse = ApiListResponse<MachineToken>;diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex bd3222dc5..bb406a063 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -9,6 +9,7 @@ export type {Conversation,Message,TaskMessage,+ TaskMessageResponse,MachineToken,Email,EmailDirection,diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex b3b9780c6..b193df9c7 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -149,6 +149,14 @@ export interface TaskMessage {output: string;}+export interface TaskMessageResponse {+ id: string;+ seq: number;+ type: string;+ content: string;+ output: string;+}+export interface Machine {daemon_id: string;workspace_id: string;@@ -276,7 +284,7 @@ export type WsMessage =| { type: "runtime.deleted"; daemonId: string }| { type: "task.created"; conversationId: string; task: TaskApi }| { type: "task.updated"; taskId: string; agentId: string; status: string }- | { type: "task.messages"; taskId: string; messages: TaskMessage[] }+ | { type: "task.messages"; taskId: string; messages: TaskMessageResponse[] }| { type: "email.received"; agentId: string }| { type: "email.sent"; agentId: string }| { type: "artifact.uploaded"; conversationId: string; artifact: Artifact }@@ -285,6 +293,7 @@ export type WsMessage =| { type: "followup.deleted"; conversationId: string; messageId: string }| { type: "followup.dispatch_failed"; conversationId: string; messageId: string; error: string }| { type: "conversation.message"; conversationId: string; message: Message }+ | { type: "agent.created"; agentId: string; workspaceId: string; parentAgentId: string }| { type: "issue.comment"; issueId: string; comment: IssueComment }| { type: "workspace.files"; agentId: string; requestId: string; requestType: "tree" | "read"; result: WorkspaceFileResult }diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex 7af8a601a..307a59372 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -105,7 +105,7 @@ function savePositions(workspaceId: string, nodes: Node[]) {function AgentCanvas({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }) {const router = useRouter();- const { agents, runtimes, loading, activeTaskCounts, agentLinks } = useAgentContext();+ const { agents, runtimes, loading, activeTaskCounts, agentLinks, pendingNewAgent, clearPendingNewAgent } = useAgentContext();const { slug, workspaceId } = useWorkspace();const { zoomIn, zoomOut, fitView } = useReactFlow();const canvasRef = useRef<HTMLDivElement>(null);@@ -229,26 +229,62 @@ function AgentCanvas({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }initialLayoutDone.current = true;setTimeout(() => fitView({ padding: 0.4, duration: 400 }), 50);}+ if (pendingNewAgent) clearPendingNewAgent();}} else if (newAgentIds.length > 0 && linksLoaded) {- // Existing positions + some new agents — layout new nodes only- const fixedNodes = newNodes.filter((n) => validPositions[n.id]);- const floatingNodes = newNodes.filter((n) => !validPositions[n.id]);- const currentEdges: Edge[] = links.map((link) => ({- id: link.id,- source: link.source_agent_id,- target: link.target_agent_id,- }));- const allLaid = getAutoLayout([...fixedNodes, ...floatingNodes], currentEdges, layoutType);- newNodes = newNodes.map((n) => {+ // Existing positions + some new agents — position relative to parent+ newNodes = newNodes.map((n, _i) => {if (validPositions[n.id]) return n;- const laid = allLaid.find((l) => l.id === n.id);- return laid ? { ...n, position: laid.position } : n;++ // Find parent: use pendingNewAgent hint or scan links+ let parentId: string | undefined;+ if (pendingNewAgent && n.id === pendingNewAgent.agentId) {+ parentId = pendingNewAgent.parentAgentId;+ }+ if (!parentId) {+ const linkedEdge = links.find(+ (l) => (l.source_agent_id === n.id && validPositions[l.target_agent_id]) ||+ (l.target_agent_id === n.id && validPositions[l.source_agent_id])+ );+ if (linkedEdge) {+ parentId = linkedEdge.source_agent_id === n.id+ ? linkedEdge.target_agent_id+ : linkedEdge.source_agent_id;+ }+ }++ const siblingIndex = newAgentIds.indexOf(n.id);+ if (parentId && validPositions[parentId]) {+ const pp = validPositions[parentId];+ let pos: { x: number; y: number };+ switch (layoutType) {+ case "tree":+ pos = { x: pp.x + siblingIndex * 300, y: pp.y + 200 };+ break;+ case "flow":+ pos = { x: pp.x + 350, y: pp.y + siblingIndex * 150 };+ break;+ default: // star+ pos = { x: pp.x + 300, y: pp.y + 100 + siblingIndex * 150 };+ break;+ }+ return { ...n, position: pos };+ }++ // Fallback: centroid of all existing nodes + offset+ const positions = Object.values(validPositions);+ const cx = positions.reduce((s, p) => s + p.x, 0) / positions.length;+ const cy = positions.reduce((s, p) => s + p.y, 0) / positions.length;+ return { ...n, position: { x: cx + 350 + siblingIndex * 300, y: cy } };});++ savePositions(workspaceId, newNodes);+ setTimeout(() => fitView({ padding: 0.4, duration: 400, includeHiddenNodes: false }), 50);+ if (pendingNewAgent) clearPendingNewAgent();}setNodes(newNodes);- }, [agents, runtimes, activeTaskCounts, slug, loading, workspaceId, linksLoaded, links, fitView]);+ }, [agents, runtimes, activeTaskCounts, slug, loading, workspaceId, linksLoaded, links, fitView, layoutType, pendingNewAgent, clearPendingNewAgent]);const onNodesChange = useCallback((changes: NodeChange[]) => {setNodes((nds) => applyNodeChanges(changes, nds));diff --git a/src/web/src/app/api/agents/recruit/route.ts b/src/web/src/app/api/agents/recruit/route.tsindex 44182d9c4..cd755dd4f 100644--- a/src/web/src/app/api/agents/recruit/route.ts+++ b/src/web/src/app/api/agents/recruit/route.ts@@ -10,6 +10,7 @@ import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { agentToResponse, agentLinkToResponse } from "@/lib/api/responses";import { TaskService } from "@/lib/services/task";import { invalidate, cached, cacheKeys } from "@/lib/cache";+import { broadcastToUser } from "@/lib/broadcast";import { randomConfig, serializeAvatarConfig } from "@/components/avatar";function generateUniqueHandleFromSet(@@ -110,6 +111,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {invalidate(cacheKeys.agentLinks(ws.workspaceId)),]);+ broadcastToUser(ctx.userId, {+ type: "agent.created",+ agentId: newAgent.id,+ workspaceId: ws.workspaceId,+ parentAgentId: agentId,+ }).catch(() => {});+if (isOnline(runtime.machineLastSeenAt)) {try {const callerName = callingAgent.name;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 ee95eea33..698957996 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@@ -2,7 +2,7 @@ import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb, withD1Retry } from "@/lib/db";-import type { TaskMessage } from "@alook/shared"+import type { TaskMessageResponse } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { taskMessageToResponse } from "@/lib/api/responses";@@ -77,16 +77,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const succeeded = filtered.filter((_, i) => results[i].status === "fulfilled");const broadcastable = succeeded.filter((m) => m.type !== "tool-result" && m.type !== "tool-use" && m.type !== "thinking");if (broadcastable.length > 0) {- const wsMessages: TaskMessage[] = broadcastable.map((m) => ({+ const wsMessages: TaskMessageResponse[] = broadcastable.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(() => {});}diff --git a/src/web/src/app/api/tasks/[id]/messages/route.test.ts b/src/web/src/app/api/tasks/[id]/messages/route.test.tsindex fa860e249..476b9c751 100644--- a/src/web/src/app/api/tasks/[id]/messages/route.test.ts+++ b/src/web/src/app/api/tasks/[id]/messages/route.test.ts@@ -6,10 +6,10 @@ const mockListTaskMessages = vi.fn();const mockListTaskMessagesSince = vi.fn();const mockTaskMessageToResponse = vi.fn((m: any) => ({id: m.id,- task_id: m.taskId,seq: m.seq,type: m.type,content: m.content,+ output: m.output || "",}));vi.mock("@/lib/middleware/helpers", () => ({@@ -87,8 +87,8 @@ describe("GET /api/tasks/[id]/messages", () => {expect(res.status).toBe(200);expect(body).toEqual([- { id: "m1", task_id: "t1", seq: 1, type: "text", content: "hello" },- { id: "m2", task_id: "t1", seq: 2, type: "text", content: "world" },+ { id: "m1", seq: 1, type: "text", content: "hello", output: "" },+ { id: "m2", seq: 2, type: "text", content: "world", output: "" },]);expect(mockListTaskMessages).toHaveBeenCalledWith({}, "t1");});@@ -109,7 +109,7 @@ describe("GET /api/tasks/[id]/messages", () => {expect(res.status).toBe(200);expect(body).toEqual([- { id: "m3", task_id: "t1", seq: 6, type: "text", content: "new msg" },+ { id: "m3", seq: 6, type: "text", content: "new msg", output: "" },]);expect(mockListTaskMessagesSince).toHaveBeenCalledWith({}, "t1", 5);expect(mockListTaskMessages).not.toHaveBeenCalled();diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex abc94b1dc..a5455804c 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -35,7 +35,7 @@ import {} from "@/lib/api";import { appendCachedMessage, getCachedMessages, getCachedMessagesBefore, getCacheMeta, mergeCachedMessages } from "@/lib/chat-cache";import type { PreviousConversation, TraceTask } from "@/lib/api";-import type { Artifact, Conversation, Issue, IssueComment, Message, SkillEntry, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";+import type { Artifact, Conversation, Issue, IssueComment, Message, SkillEntry, TaskApi as Task, TaskMessageResponse, WsMessage } from "@alook/shared";import { useAgentContext } from "@/contexts/agent-context";import { useInboxCount } from "@/contexts/inbox-count-context";import { useFlagCount } from "@/contexts/flag-count-context";@@ -335,7 +335,7 @@ export function AgentChatView({const [sending, setSending] = useState(false);const [cancelling, setCancelling] = useState(false);const [activeTask, setActiveTask] = useState<Task | null>(null);- const [taskMessages, setTaskMessages] = useState<TaskMessage[]>([]);+ const [taskMessages, setTaskMessages] = useState<TaskMessageResponse[]>([]);const [messagesLoading, setMessagesLoading] = useState(true);const [connectionLost, setConnectionLost] = useState(false);const [hasMore, setHasMore] = useState(false);@@ -648,7 +648,7 @@ export function AgentChatView({if (ignore) return;if (task && !["completed", "failed", "cancelled", "superseded"].includes(task.status)) {setActiveTask(task);- const tmsgs = await getTaskMessages(scrollToTaskId, workspaceId).catch(() => [] as TaskMessage[]);+ const tmsgs = await getTaskMessages(scrollToTaskId, workspaceId).catch(() => [] as TaskMessageResponse[]);if (ignore) return;setTaskMessages(tmsgs);if (tmsgs.length > 0) {diff --git a/src/web/src/components/agent-chat/historical-task-thinking.tsx b/src/web/src/components/agent-chat/historical-task-thinking.tsxindex e8a0388a5..fad585571 100644--- a/src/web/src/components/agent-chat/historical-task-thinking.tsx+++ b/src/web/src/components/agent-chat/historical-task-thinking.tsx@@ -3,7 +3,7 @@import { useState, useCallback } from "react";import { TaskStream } from "@/components/task-stream";import { getTaskMessages } from "@/lib/api";-import type { TaskMessage, TaskApi } from "@alook/shared";+import type { TaskMessageResponse, TaskApi } from "@alook/shared";const COMPLETED_STUB: TaskApi = {id: "",@@ -32,7 +32,7 @@ export function HistoricalTaskThinking({thinkingCount: number;workspaceId: string;}) {- const [messages, setMessages] = useState<TaskMessage[]>([]);+ const [messages, setMessages] = useState<TaskMessageResponse[]>([]);const [loading, setLoading] = useState(false);const [fetched, setFetched] = useState(false);diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsxindex 36c9b0271..80715cac5 100644--- a/src/web/src/components/agent-chat/message-list.tsx+++ b/src/web/src/components/agent-chat/message-list.tsx@@ -1,5 +1,5 @@import React, { memo } from "react";-import type { Agent, Artifact, Message, TaskApi as Task, TaskMessage } from "@alook/shared";+import type { Agent, Artifact, Message, TaskApi as Task, TaskMessageResponse } from "@alook/shared";import { cn } from "@/lib/utils";import { Button } from "@/components/ui/button";@@ -22,7 +22,7 @@ export interface MessageItemProps {agents: Agent[];artifacts: Artifact[];activeTask: Task | null;- taskMessages: TaskMessage[];+ taskMessages: TaskMessageResponse[];connectionLost: boolean;isLastMessage: boolean;thinkingCount: number;diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsxindex c88880c45..5fdcedf05 100644--- a/src/web/src/components/task-stream.tsx+++ b/src/web/src/components/task-stream.tsx@@ -3,7 +3,7 @@import { useMemo, useRef, useEffect, useState } from "react";import { Badge } from "@/components/ui/badge";import { cn } from "@/lib/utils";-import type { TaskMessage } from "@alook/shared";+import type { TaskMessageResponse } from "@alook/shared";import type { TaskApi as Task } from "@alook/shared";import {ChevronRight,@@ -29,11 +29,11 @@ interface ErrorItem {type StreamItem = TextItem | ErrorItem;-function itemKey(msg: TaskMessage): string {+function itemKey(msg: TaskMessageResponse): string {return msg.id || `seq-${msg.seq}`;}-function groupMessages(messages: TaskMessage[]): StreamItem[] {+function groupMessages(messages: TaskMessageResponse[]): StreamItem[] {const items: StreamItem[] = [];for (const msg of messages) {@@ -129,7 +129,7 @@ export function TaskStream({thinkingLoading,}: {task: Task;- messages: TaskMessage[];+ messages: TaskMessageResponse[];connectionLost?: boolean;onRetry?: () => void;thinkingCountHint?: number;diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsxindex 8c421080d..54f8d3c0a 100644--- a/src/web/src/contexts/agent-context.tsx+++ b/src/web/src/contexts/agent-context.tsx@@ -48,6 +48,8 @@ interface AgentContextValue {runtimes: Runtime[];loading: boolean;activeTaskCounts: Record<string, number>;+ pendingNewAgent: { agentId: string; parentAgentId: string } | null;+ clearPendingNewAgent: () => void;activeTaskDetails: WorkspaceActiveTask[];pins: Map<string, { created_at: string; position: number }>;reload: () => Promise<void>;@@ -92,6 +94,8 @@ export function AgentProvider({const [activeTaskDetails, setActiveTaskDetails] = useState<WorkspaceActiveTask[]>([]);const hasActiveTasksRef = useRef(false);const [agentLinks, setAgentLinks] = useState<AgentLink[]>([]);+ const [pendingNewAgent, setPendingNewAgent] = useState<{ agentId: string; parentAgentId: string } | null>(null);+ const clearPendingNewAgent = useCallback(() => setPendingNewAgent(null), []);const [pins, setPins] = useState<Map<string, { created_at: string; position: number }>>(new Map());const [unpinnedOrder, setUnpinnedOrder] = useState<Map<string, number>>(new Map());const loadedRef = useRef(false);@@ -229,7 +233,6 @@ export function AgentProvider({// AgentProvider only reloads agents/runtimes for runtime eventsswitch (msg.type) {case "runtime.registered":- // Filter by workspaceId — ignore registrations in other workspacesif (msg.workspaceId !== workspaceId) break;reload();break;@@ -237,10 +240,14 @@ export function AgentProvider({reload();break;case "runtime.status":- // Filter by workspaceId — ignore messages from other workspacesif (msg.workspaceId !== workspaceId) break;reloadRuntimes();break;+ case "agent.created":+ if (msg.workspaceId !== workspaceId) break;+ setPendingNewAgent({ agentId: msg.agentId, parentAgentId: msg.parentAgentId });+ reload();+ break;case "task.updated":fetchTaskCounts();break;@@ -398,6 +405,8 @@ export function AgentProvider({loading,activeTaskCounts,activeTaskDetails,+ pendingNewAgent,+ clearPendingNewAgent,pins,reload,subscribeWs,diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 9d7d6d8d2..a3fec5da9 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -24,7 +24,7 @@ import type {MeetingSession,Message,TaskApi,- TaskMessage,+ TaskMessageResponse,UpdateIssueRequest,User,Workspace,@@ -262,7 +262,7 @@ export interface ChatInitResponse {artifacts: Artifact[];buffered_messages: Message[];active_task: TaskApi | null;- task_messages: TaskMessage[];+ task_messages: TaskMessageResponse[];has_more_messages: boolean;has_more_conversations: boolean;has_more_artifacts: boolean;@@ -298,7 +298,7 @@ export interface ConversationInitResponse {flagged_message_ids: string[];thinking_counts: Record<string, number>;active_task: TaskApi | null;- task_messages: TaskMessage[];+ task_messages: TaskMessageResponse[];cache_valid: boolean;message_count: number;}@@ -577,7 +577,7 @@ export const getTask = (id: string, workspaceId: string) =>apiFetch<TaskApi>(`/api/tasks/${id}${wsQuery(workspaceId)}`);export const getTaskMessages = (id: string, workspaceId: string, since?: number) =>- apiFetch<TaskMessage[]>(+ apiFetch<TaskMessageResponse[]>(`/api/tasks/${id}/messages${wsQuery(workspaceId, since ? { since: String(since) } : undefined)}`);diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex 882a8b596..028b7e5b8 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -158,18 +158,13 @@ export function messageToResponse(m: any) {}export function taskMessageToResponse(m: any) {- const resp: any = {+ return {id: m.id,- task_id: m.taskId,seq: m.seq,type: m.type,- tool: m.tool,- call_id: m.callId || "",content: m.content,output: m.output,};- if (m.input) resp.input = m.input;- return resp;}export function runtimeToResponse(rt: any) {