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: cancel task
Gusb3fc5125a51a
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex beab3ed14..bb7e1ebfa 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -1549,10 +1549,15 @@ describe("daemon kill_task handling", () => {vi.clearAllMocks();mockProcessExit.mockImplementation((() => {}) as any);mockOpenSync.mockReturnValue(42);+ // Use short timeouts for KILL_TASK retry loop in tests+ process.env.ALOOK_KILL_TASK_MAX_WAIT_MS = "500";+ process.env.ALOOK_KILL_TASK_POLL_MS = "50";});afterEach(() => {for (const t of intervalTimers) realClearInterval(t);+ delete process.env.ALOOK_KILL_TASK_MAX_WAIT_MS;+ delete process.env.ALOOK_KILL_TASK_POLL_MS;});function makeKillTask(targetTaskId: string) {@@ -1609,7 +1614,7 @@ describe("daemon kill_task handling", () => {mockKill.mockRestore();});- it("reports 'target not found' when PID not in timeline", async () => {+ it("reports 'target not found' after retry timeout when PID never appears", async () => {setupKillTaskClaim("target_t1");mockFindRunningPidByTaskId.mockReturnValue(null);@@ -1620,10 +1625,13 @@ describe("daemon kill_task handling", () => {mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });await startDaemon();- await new Promise((r) => setTimeout(r, 50));+ // Wait longer than ALOOK_KILL_TASK_MAX_WAIT_MS (500ms) + overhead+ await new Promise((r) => setTimeout(r, 800));expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "target not found in timeline");expect(spawn).not.toHaveBeenCalled();+ // Should have retried multiple times+ expect(mockFindRunningPidByTaskId.mock.calls.length).toBeGreaterThan(1);});it("handles ESRCH when target process already exited", async () => {@@ -1649,7 +1657,8 @@ describe("daemon kill_task handling", () => {it("does not call startTask for kill_tasks", async () => {setupKillTaskClaim("target_t1");- mockFindRunningPidByTaskId.mockReturnValue(null);+ mockFindRunningPidByTaskId.mockReturnValue(99999);+ const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);vi.mocked(loadCLIConfigForProfile).mockReturnValue({server_url: "",@@ -1661,6 +1670,34 @@ describe("daemon kill_task handling", () => {await new Promise((r) => setTimeout(r, 50));expect(mockClientInstance.startTask).not.toHaveBeenCalled();++ mockKill.mockRestore();+ });++ it("finds PID after a few retries and sends SIGTERM", async () => {+ setupKillTaskClaim("target_t1");+ let callCount = 0;+ mockFindRunningPidByTaskId.mockImplementation(() => {+ callCount++;+ if (callCount >= 3) return 88888;+ return null;+ });+ const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 500));++ expect(mockKill).toHaveBeenCalledWith(88888, "SIGTERM");+ expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");+ expect(callCount).toBeGreaterThanOrEqual(3);++ mockKill.mockRestore();});});diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 6c4b38d1c..4b8ba69aa 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -646,7 +646,17 @@ async function handleTask(const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");const timelineDir = join(agentBaseDir, ".context_timeline");- const pid = findRunningPidByTaskId(timelineDir, targetTaskId);++ // Retry loop: session-runner may not have written its timeline entry yet+ const MAX_WAIT_MS = Number(process.env.ALOOK_KILL_TASK_MAX_WAIT_MS) || 15_000;+ const POLL_MS = Number(process.env.ALOOK_KILL_TASK_POLL_MS) || 200;+ const waitStart = Date.now();+ let pid: number | null = null;+ while (Date.now() - waitStart < MAX_WAIT_MS) {+ pid = findRunningPidByTaskId(timelineDir, targetTaskId);+ if (pid != null) break;+ await new Promise((r) => setTimeout(r, POLL_MS));+ }if (pid != null) {writeKillIntent(agentBaseDir, {diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.tsindex 634931012..6bd95643c 100644--- a/src/cli/daemon/session-runner.test.ts+++ b/src/cli/daemon/session-runner.test.ts@@ -7,6 +7,8 @@ const mockClientInstance = {failTask: vi.fn(async () => ({})),supersedeTask: vi.fn(async () => ({})),reportMessages: vi.fn(async () => ({})),+ getArtifactMeta: vi.fn(async () => ({ filename: "file.txt", content_type: "text/plain" })),+ downloadArtifact: vi.fn(async () => new ArrayBuffer(0)),};vi.mock("./client.js", () => {function MockDaemonClient() { return mockClientInstance; }@@ -239,7 +241,7 @@ describe("session-runner runSession", () => {);});- it("writes timeline init entry with session runner PID (process.pid)", async () => {+ it("writes timeline init entry with session runner PID (process.pid) and sessionId=undefined", async () => {setupBackend([], {status: "completed",output: "Done",@@ -254,7 +256,7 @@ describe("session-runner runSession", () => {"t1","do the thing","user_dm_message",- "sess-1",+ undefined,process.pid,"claude","c1",@@ -262,7 +264,50 @@ describe("session-runner runSession", () => {);expect(mockInitEntryAsync).toHaveBeenCalledWith("/tmp/ws/ws1/agent1/workdir/.context_timeline",- expect.objectContaining({ task_id: "t1", pid: process.pid }),+ expect.objectContaining({ task_id: "t1", pid: process.pid, session_id: null }),+ );+ });++ it("updates timeline entry with session_id after agent starts", async () => {+ setupBackend([], {+ status: "completed",+ output: "Done",+ error: "",+ durationMs: 100,+ sessionId: "sess-1",+ });++ await runSession(makeInput());++ // The first updateEntry call should set session_id+ const firstCall = mockUpdateEntry.mock.calls[0];+ expect(firstCall[0]).toBe("/tmp/ws/ws1/agent1/workdir/.context_timeline");+ expect(firstCall[1]).toBe("t1");+ const entry = { session_id: null as string | null };+ firstCall[2](entry);+ expect(entry.session_id).toBe("sess-1");+ });++ it("initEntryAsync is called with detailedLog from input.logFilePath", async () => {+ setupBackend([], {+ status: "completed",+ output: "Done",+ error: "",+ durationMs: 100,+ sessionId: "sess-1",+ });++ await runSession(makeInput({ logFilePath: "/tmp/logs/t1.log" }));++ expect(mockCreateTimelineEntry).toHaveBeenCalledWith(+ "t1",+ "do the thing",+ "user_dm_message",+ undefined,+ process.pid,+ "claude",+ "c1",+ "/tmp/logs/t1.log",);});@@ -492,6 +537,102 @@ describe("session-runner runSession", () => {expect(mockClientInstance.completeTask).not.toHaveBeenCalled();});+ it("updates timeline to failed when attachment download fails", async () => {+ mockClientInstance.getArtifactMeta.mockRejectedValueOnce(new Error("network error"));++ await runSession(makeInput({+ task: {+ id: "t1",+ agentId: "a1",+ runtimeId: "rt1",+ conversationId: "c1",+ workspaceId: "ws1",+ prompt: "do the thing",+ status: "dispatched",+ priority: 0,+ type: "user_dm_message",+ contextKey: "c1",+ createdAt: "2026-01-01T00:00:00Z",+ context: { attachment_ids: ["art-1"] },+ },+ }));++ // Timeline entry should have been written immediately+ expect(mockInitEntryAsync).toHaveBeenCalled();++ // Timeline should be updated to "failed" on attachment download error+ const failCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {+ const updater = call[2];+ const entry = { pid: 1, status: "running" as string, errmsg: null as string | null };+ updater(entry);+ return entry.status === "failed" && entry.errmsg?.includes("failed to download attachments");+ });+ expect(failCalls.length).toBe(1);++ // failTask should have been called+ expect(mockClientInstance.failTask).toHaveBeenCalledWith(+ "test_token",+ "t1",+ expect.stringContaining("failed to download attachments"),+ );++ // Agent should NOT have been started+ expect(mockBackendExecute).not.toHaveBeenCalled();+ });++ it("SIGTERM during setup phase (before agent starts) cleans up properly", async () => {+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);++ // Make downloadAttachments hang so SIGTERM fires during setup+ let resolveDownload: (() => void) | null = null;+ mockClientInstance.getArtifactMeta.mockImplementation(async () => {+ await new Promise<void>((resolve) => { resolveDownload = resolve; });+ return { filename: "file.txt", content_type: "text/plain" };+ });++ const sessionPromise = runSession(makeInput({+ task: {+ id: "t1",+ agentId: "a1",+ runtimeId: "rt1",+ conversationId: "c1",+ workspaceId: "ws1",+ prompt: "do the thing",+ status: "dispatched",+ priority: 0,+ type: "user_dm_message",+ contextKey: "c1",+ createdAt: "2026-01-01T00:00:00Z",+ context: { attachment_ids: ["art-1"] },+ },+ }));++ // Wait for initEntryAsync to complete and signal handler to be registered+ await new Promise((r) => setTimeout(r, 50));++ // Fire SIGTERM during attachment download (before agent starts)+ process.emit("SIGTERM", "SIGTERM");++ // Unblock the download so the promise can settle+ if (resolveDownload) resolveDownload();++ await new Promise((r) => setTimeout(r, 50));++ // Timeline should be updated (killed or cancelled depending on intent)+ const killCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {+ const updater = call[2];+ const entry = { pid: 1, status: "running" as string, errmsg: null as string | null };+ updater(entry);+ return entry.status === "killed";+ });+ expect(killCalls.length).toBe(1);++ // Should have called process.exit(1)+ expect(exitSpy).toHaveBeenCalledWith(1);++ exitSpy.mockRestore();+ });+it("gracefully cleans up on SIGTERM: kills agent, updates timeline to killed, calls failTask", async () => {// Mock process.kill to track callsconst killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);@@ -588,7 +729,7 @@ describe("session-runner runSession", () => {"t1","do the thing","user_dm_message",- "sess-1",+ undefined,process.pid,"codex","c1",@@ -848,6 +989,56 @@ describe("session-runner runSession", () => {expect.stringContaining("model=default"),);});++ it("truncates tool-result output longer than 500 chars in log", async () => {+ const longOutput = "x".repeat(1000);+ setupBackend(+ [+ { type: "tool-result", tool: "Read", callId: "c1", output: longOutput },+ ],+ {+ status: "completed",+ output: "Done",+ error: "",+ durationMs: 100,+ sessionId: "sess-1",+ },+ );++ await runSession(makeInput());++ const logCalls = (mockLog.info as any).mock.calls.map((c: any[]) => c[0] as string);+ const toolResultLog = logCalls.find((s: string) => s.includes('"type":"tool-result"'));+ expect(toolResultLog).toBeDefined();++ const parsed = JSON.parse(toolResultLog!);+ expect(parsed.output).toBe("x".repeat(500) + "... (1000 chars)");+ });++ it("does not truncate tool-result output under 500 chars in log", async () => {+ const shortOutput = "x".repeat(200);+ setupBackend(+ [+ { type: "tool-result", tool: "Read", callId: "c1", output: shortOutput },+ ],+ {+ status: "completed",+ output: "Done",+ error: "",+ durationMs: 100,+ sessionId: "sess-1",+ },+ );++ await runSession(makeInput());++ const logCalls = (mockLog.info as any).mock.calls.map((c: any[]) => c[0] as string);+ const toolResultLog = logCalls.find((s: string) => s.includes('"type":"tool-result"'));+ expect(toolResultLog).toBeDefined();++ const parsed = JSON.parse(toolResultLog!);+ expect(parsed.output).toBe(shortOutput);+ });});describe("kill-intent handling", () => {diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.tsindex 147749507..85395b9b5 100644--- a/src/cli/daemon/session-runner.ts+++ b/src/cli/daemon/session-runner.ts@@ -124,6 +124,66 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {task,);+ const agentBaseDir = path.dirname(timelineDir);++ // Timeline entry: write IMMEDIATELY so KILL_TASK can find our PID+ await initEntryAsync(+ timelineDir,+ createTimelineEntry(task.id, task.prompt, task.type, undefined, process.pid, provider, task.contextKey, input.logFilePath),+ );++ let killed = false;++ // Early signal handler (before agent starts — no agentPid/flushTimer yet)+ const earlyOnKill = async () => {+ if (killed) return;+ killed = true;+ log.info(`killed by signal (messages=0, tools=0)`);++ await cleanupAttachments(task.id);++ const intent = readKillIntent(agentBaseDir, task.id);+ clearKillIntent(agentBaseDir, task.id);++ if (intent?.reason === "superseded") {+ updateEntry(timelineDir, task.id, (entry) => {+ entry.pid = null;+ entry.status = "superseded";+ entry.successor_task_id = intent.successorTaskId ?? null;+ entry.supersede_reason = "superseded by newer task";+ });+ try {+ await client.supersedeTask(token, task.id);+ } catch { /* best-effort */ }+ } else if (intent?.reason === "cancelled") {+ updateEntry(timelineDir, task.id, (entry) => {+ entry.pid = null;+ entry.status = "cancelled";+ entry.errmsg = "cancelled by user";+ });+ await reportToServer(+ () => client.failTask(token, task.id, "cancelled by user"),+ { taskId: task.id, type: "fail", payload: { error: "cancelled by user" }, token, serverURL, createdAt: new Date().toISOString() },+ workspacesRoot,+ );+ } else {+ updateEntry(timelineDir, task.id, (entry) => {+ entry.pid = null;+ entry.status = "killed";+ entry.errmsg = "killed by signal";+ });+ await reportToServer(+ () => client.failTask(token, task.id, "killed by signal"),+ { taskId: task.id, type: "fail", payload: { error: "killed by signal" }, token, serverURL, createdAt: new Date().toISOString() },+ workspacesRoot,+ );+ }++ process.exit(1);+ };+ process.on("SIGTERM", earlyOnKill);+ process.on("SIGINT", earlyOnKill);+// Download attachments before building promptconst attachmentIds = (task.context?.attachment_ids as string[]) ?? [];let attachments: Attachment[] | undefined;@@ -136,7 +196,14 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {await cleanupAttachments(task.id);const errMsg = `failed to download attachments: ${e}`;log.error(errMsg);+ updateEntry(timelineDir, task.id, (entry) => {+ entry.pid = null;+ entry.status = "failed";+ entry.errmsg = errMsg;+ });await client.failTask(token, task.id, errMsg);+ process.removeListener("SIGTERM", earlyOnKill);+ process.removeListener("SIGINT", earlyOnKill);return;}}@@ -161,14 +228,13 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {// Capture agent PID for signal handlerconst agentPid = session.pid;- // Timeline init — use process.pid (session runner PID), not the inner agent PID+ // Update timeline entry with session_id once agent startsconst earlySessionId = await session.sessionId;log.info(`agent started (pid=${agentPid ?? "unknown"}, session=${earlySessionId})`);log.info(JSON.stringify({ role: "user", type: "text", content: prompt }));- await initEntryAsync(- timelineDir,- createTimelineEntry(task.id, task.prompt, task.type, earlySessionId, process.pid, provider, task.contextKey, input.logFilePath),- );+ updateEntry(timelineDir, task.id, (entry) => {+ entry.session_id = earlySessionId || null;+ });// Message batchingconst pendingMessages: {@@ -197,9 +263,10 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {const flushTimer = setInterval(flushMessages, FLUSH_INTERVAL_MS);- // --- Graceful shutdown on SIGTERM/SIGINT ---- let killed = false;- const agentBaseDir = path.dirname(timelineDir);+ // --- Replace early signal handler with full one ---+ process.removeListener("SIGTERM", earlyOnKill);+ process.removeListener("SIGINT", earlyOnKill);+const onKill = async () => {if (killed) return;killed = true;@@ -307,7 +374,11 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {});if (msg.type === "tool-use") toolCount++;- log.info(JSON.stringify({ role: "assistant", ...msg }));+ if (msg.type === "tool-result" && msg.output && msg.output.length > 500) {+ log.info(JSON.stringify({ role: "assistant", ...msg, output: msg.output.slice(0, 500) + `... (${msg.output.length} chars)` }));+ } else {+ log.info(JSON.stringify({ role: "assistant", ...msg }));+ }// Timeline — record assistant text messagesif (msg.type === "text" && msg.content) {