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: multi-workspace polling and status
Gus86f4142db0af
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 083b00154..3ab87b05f 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -97,6 +97,7 @@ export async function startDaemon(version: p.version,}));+ log.info(`Registering workspace ${ws.id} (${ws.name ?? "unnamed"}) with ${runtimes.length} runtime(s)...`);let resp;try {resp = await client.register(ws.token, {@@ -110,6 +111,7 @@ export async function startDaemon(log.error(`Failed to register workspace ${ws.id}, skipping`, e);continue;}+ log.info(`Workspace ${ws.id} registered — ${resp.runtimes.length} runtime(s)`);const runtimeIds = resp.runtimes.map((r: { id: string }) => r.id);workspaceStates.push({ workspaceId: ws.id, token: ws.token, runtimeIds });@@ -131,7 +133,7 @@ export async function startDaemon(const allRuntimeIds = workspaceStates.flatMap((ws) => ws.runtimeIds);health.setRuntimeCount(allRuntimeIds.length);log.info(- `Daemon started — ${allRuntimeIds.length} runtime(s) across ${workspaces.length} workspace(s)`,+ `Daemon started — ${allRuntimeIds.length} runtime(s) across ${workspaceStates.length} workspace(s)`,);const activeTasks = new Set<string>();diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.tsindex 343e3abb0..a5c62d43c 100644--- a/src/cli/daemon/execenv/context.test.ts+++ b/src/cli/daemon/execenv/context.test.ts@@ -19,16 +19,37 @@ function makeTask(overrides: Partial<Task> = {}): Task {}describe("buildInstructionContent email tool injection", () => {- it("includes email tool section when agent has email handle", () => {+ it("includes email tool section with full email address when agent has email handle", () => {const task = makeTask({agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },});const content = buildInstructionContent(task);- expect(content).toContain("alook email pull --agent_id agent-123 --status unread");- expect(content).toContain("alook email set --agent_id agent-123 --email_id <EMAIL_ID> --status read");+ expect(content).toContain("npx @alook/cli pull --agent_id agent-123 --status unread");+ expect(content).toContain("npx @alook/cli set --agent_id agent-123 --email_id <EMAIL_ID> --status read");expect(content).toContain("/tmp/alook-emails/");expect(content).toContain("metadata.json");+ expect(content).toContain("Your email address is '[email protected]'");+ });++ it("includes owner email when user email is provided", () => {+ const task = makeTask({+ agent: { name: "test", instructions: "do stuff", emailHandle: "myagent", userEmail: "[email protected]" },+ });+ const content = buildInstructionContent(task);++ expect(content).toContain("Your email address is '[email protected]'");+ expect(content).toContain("Your owner's email address is '[email protected]'");+ });++ it("omits owner email line when user email is not provided", () => {+ const task = makeTask({+ agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },+ });+ const content = buildInstructionContent(task);++ expect(content).toContain("Your email address is '[email protected]'");+ expect(content).not.toContain("owner's email");});it("omits email tool section when agent has no email handle", () => {diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex df19278ed..909ddbcc1 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -1,4 +1,5 @@import { createHash } from "crypto";+import { toAlookAddress } from "@alook/shared";import {writeFileSync,readFileSync,@@ -14,7 +15,8 @@ import type { Task } from "../types.js";export const CANONICAL_FILE = "AGENTS.md";export const SYMLINK_ALIASES = ["CLAUDE.md"];-const SYSTEM_PROMPT = `## Memory Management+const SYSTEM_PROMPT = `You're Alook Agent.+## Memory Management- Your memory directory is ./, don't write ANY EXTERNAL memory file.- Write ESSENTIAL yet SHORT memory to ./memory.md- For SPECIFIC yet LONG rules or pattern, write to experiences/[NAME].md, and add index to ./memory.md for later recall.@@ -75,10 +77,12 @@ ${task.agent.instructions}content += `\n## Alook CLI ToolsYou can communicate with the world through Alook CLI.Your alook agent id is '${task.agentId}'. remember this, most of alook cli will requires you input your agent id.+Your email address is '${toAlookAddress(task.agent.emailHandle)}'.+${task.agent.userEmail ? `Your owner's email address is '${task.agent.userEmail}'.` : ""}### Emails----Run 'alook email pull --agent_id ${task.agentId} --status unread' to download unread emails to '/tmp/alook-emails/'.+Run 'npx @alook/cli pull --agent_id ${task.agentId} --status unread' to download unread emails to '/tmp/alook-emails/'.Each email is saved to '/tmp/alook-emails/<emailId>/' with:- 'metadata.json' — sender, recipient, subject, date, status- 'body.txt' — plain text body@@ -86,7 +90,7 @@ Each email is saved to '/tmp/alook-emails/<emailId>/' with:- 'attachments/' — extracted attachment files (if any)---Before starting to process an email, mark it as read:-- Run 'alook email set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'+- Run 'npx @alook/cli set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'---`;}diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.tsindex 56beb9913..b39270e02 100644--- a/src/cli/daemon/types.ts+++ b/src/cli/daemon/types.ts@@ -18,6 +18,7 @@ export interface TaskAgentData {name: string;instructions: string;emailHandle?: string | null;+ userEmail?: string | null;}export interface RepoData {@@ -100,7 +101,7 @@ export function fromApiTask(api: import("@alook/shared").TaskApi): Task {priority: api.priority,type: api.type,agent: api.agent- ? { name: api.agent.name, instructions: api.agent.instructions, emailHandle: api.agent.email_handle ?? undefined }+ ? { name: api.agent.name, instructions: api.agent.instructions, emailHandle: api.agent.email_handle ?? undefined, userEmail: api.agent.user_email ?? undefined }: undefined,repos: undefined,createdAt: api.created_at,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 187480743..57f937d5f 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -47,6 +47,7 @@ export const TaskAgentDataApiSchema = z.object({name: z.string(),runtime_config: z.record(z.string(), z.unknown()).default({}),email_handle: z.string().nullable().optional(),+ user_email: z.string().nullable().optional(),});export type TaskAgentDataApi = z.infer<typeof TaskAgentDataApiSchema>;diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsxindex 9c509715a..fbb625a76 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx@@ -357,7 +357,7 @@ export default function AgentChatPage() {) : !hasTaskStream ? (<div className="flex justify-start"><div className="markdown max-w-full px-1 py-1 text-base text-foreground">- <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }}>{msg.content}</Streamdown>+ <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{msg.content}</Streamdown></div></div>) : null}diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsindex e09f827a0..8b3ac36ce 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";import { NextRequest } from "next/server";const mockGetRuntimeIdsByDaemon = vi.fn();-const mockUpdateMachineLastSeen = vi.fn();+const mockUpsertMachine = vi.fn();const mockGetAgent = vi.fn();const mockClaimTasksForRuntimes = vi.fn();const mockSweepStaleState = vi.fn();@@ -22,7 +22,7 @@ vi.mock("@alook/shared", async () => {getRuntimeIdsByDaemon: (...args: unknown[]) => mockGetRuntimeIdsByDaemon(...args),},machine: {- updateMachineLastSeen: (...args: unknown[]) => mockUpdateMachineLastSeen(...args),+ upsertMachine: (...args: unknown[]) => mockUpsertMachine(...args),},agent: {getAgent: (...args: unknown[]) => mockGetAgent(...args),@@ -84,21 +84,27 @@ function postReq(body: unknown) {describe("POST /api/daemon/tasks/poll", () => {beforeEach(() => vi.clearAllMocks());- it("returns empty tasks array when daemon has no runtimes", async () => {+ it("returns empty tasks array when daemon has no runtimes but still updates liveness", async () => {+ mockUpsertMachine.mockResolvedValue({});mockGetRuntimeIdsByDaemon.mockResolvedValue([]);+ mockBroadcastToUser.mockResolvedValue(undefined);const res = await POST(postReq({ daemon_id: "d1" }));const body = await res.json();expect(res.status).toBe(200);expect(body.tasks).toEqual([]);- expect(mockUpdateMachineLastSeen).not.toHaveBeenCalled();- expect(mockBroadcastToUser).not.toHaveBeenCalled();+ expect(mockUpsertMachine).toHaveBeenCalledWith({}, {+ daemonId: "d1",+ workspaceId: "w1",+ deviceInfo: "d1",+ });+ expect(mockBroadcastToUser).toHaveBeenCalled();});- it("resolves runtime IDs from daemon_id and updates machine last_seen_at", async () => {+ it("resolves runtime IDs from daemon_id and upserts machine liveness", async () => {+ mockUpsertMachine.mockResolvedValue({});mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2"]);- mockUpdateMachineLastSeen.mockResolvedValue(undefined);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);@@ -106,14 +112,17 @@ describe("POST /api/daemon/tasks/poll", () => {await POST(postReq({ daemon_id: "d1" }));expect(mockGetRuntimeIdsByDaemon).toHaveBeenCalledWith({}, "d1", "w1");- // 1 machine write instead of N runtime writes- expect(mockUpdateMachineLastSeen).toHaveBeenCalledTimes(1);- expect(mockUpdateMachineLastSeen).toHaveBeenCalledWith({}, "d1", "w1");+ expect(mockUpsertMachine).toHaveBeenCalledTimes(1);+ expect(mockUpsertMachine).toHaveBeenCalledWith({}, {+ daemonId: "d1",+ workspaceId: "w1",+ deviceInfo: "d1",+ });});it("returns tasks with agent data for claimed tasks", async () => {+ mockUpsertMachine.mockResolvedValue({});mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2"]);- mockUpdateMachineLastSeen.mockResolvedValue(undefined);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([@@ -136,12 +145,13 @@ describe("POST /api/daemon/tasks/poll", () => {name: "Bot",runtime_config: { model: "gpt-4" },email_handle: null,+ user_email: "[email protected]",});});it("broadcasts single runtime.status with daemonId and workspaceId", async () => {+ mockUpsertMachine.mockResolvedValue({});mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2", "r3"]);- mockUpdateMachineLastSeen.mockResolvedValue(undefined);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);@@ -159,8 +169,8 @@ describe("POST /api/daemon/tasks/poll", () => {});it("calls sweepStaleState", async () => {+ mockUpsertMachine.mockResolvedValue({});mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockUpdateMachineLastSeen.mockResolvedValue(undefined);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);@@ -171,8 +181,8 @@ describe("POST /api/daemon/tasks/poll", () => {});it("respects max_tasks parameter", async () => {+ mockUpsertMachine.mockResolvedValue({});mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockUpdateMachineLastSeen.mockResolvedValue(undefined);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);@@ -183,8 +193,8 @@ describe("POST /api/daemon/tasks/poll", () => {});it("defaults max_tasks to 1", async () => {+ mockUpsertMachine.mockResolvedValue({});mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockUpdateMachineLastSeen.mockResolvedValue(undefined);mockSweepStaleState.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);mockClaimTasksForRuntimes.mockResolvedValue([]);diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex 008b959c6..8552aa61f 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -19,7 +19,21 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- // 1. Resolve runtime IDs from daemon_id + workspaceId+ // 1. Liveness: upsert machine row (creates if missing, updates lastSeenAt if exists)+ await queries.machine.upsertMachine(db, {+ daemonId: body.daemon_id,+ workspaceId: ctx.workspaceId,+ deviceInfo: body.daemon_id,+ });++ broadcastToUser(ctx.userId, {+ type: "runtime.status",+ daemonId: body.daemon_id,+ workspaceId: ctx.workspaceId,+ status: "online",+ }).catch(() => {});++ // 2. Resolve runtime IDs from daemon_id + workspaceIdconst runtimeIds = await queries.runtime.getRuntimeIdsByDaemon(db,body.daemon_id,@@ -30,21 +44,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ tasks: [] });}- // 2. Liveness: update machine last_seen_at (1 row write instead of N)- await queries.machine.updateMachineLastSeen(- db,- body.daemon_id,- ctx.workspaceId,- );-- // Single broadcast at daemon level- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId: body.daemon_id,- workspaceId: ctx.workspaceId,- status: "online",- }).catch(() => {});-// 3. Housekeeping: sweep stale stateawait sweepStaleState(db, ctx.workspaceId);@@ -67,6 +66,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {name: agent.name,runtime_config: agent.runtimeConfig || {},email_handle: agent.emailHandle || null,+ user_email: ctx.email || null,}: null,});diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex 23b262893..b0a9a7be8 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -812,10 +812,6 @@.markdown a {text-decoration: underline;text-underline-offset: 2px;- text-decoration-color: var(--border);- transition: text-decoration-color 200ms;-}-.markdown a:hover {text-decoration-color: currentColor;}.markdown hr {diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsxindex 424a5780b..5057fc0cd 100644--- a/src/web/src/components/task-stream.tsx+++ b/src/web/src/components/task-stream.tsx@@ -360,7 +360,7 @@ export function TaskStream({key={item.id}className="markdown max-w-full px-1 py-1 text-base text-foreground">- <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }}>{item.content}</Streamdown>+ <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{item.content}</Streamdown></div>))}</div>