Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: codex multi-turn continuation, status badge task list, chat race fix

Gus1bc1c2d539c2
diff --git a/src/cli/daemon/agent/__tests__/codex.test.ts b/src/cli/daemon/agent/__tests__/codex.test.ts
index 5965520ae..963c75de6 100644
--- a/src/cli/daemon/agent/__tests__/codex.test.ts
+++ b/src/cli/daemon/agent/__tests__/codex.test.ts
@@ -420,26 +420,41 @@ describe("CodexBackend", () => {
expect(messages).not.toContainEqual(expect.objectContaining({ type: "status" }));
});
- it("raw protocol — turn/completed (nested) with completed triggers turn done", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ it("raw protocol — turn/completed (nested) with completed signals continuation (not immediate kill)", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 2 });
const mock = getMock();
await completeHandshake();
sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ // Should NOT immediately kill — should send continuation turn/start
+ expect(mock.stdinEnd).not.toHaveBeenCalled();
+ await tick();
+ // Continuation turn/start sent (id=4, after init=1, thread/start=2, turn/start=3)
+ const continuationWrite = mock.stdinWrites.find((w) => w.includes('"continue"'));
+ expect(continuationWrite).toBeDefined();
+ sendResponse(4, {});
+ await tick();
+
+ // Now send final_answer to end
+ sendNotification("item/completed", {
+ item: { type: "agentMessage", text: "done", phase: "final_answer" },
+ });
expect(mock.stdinEnd).toHaveBeenCalled();
- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
mock.proc.emit("close", 0);
const result = await session.result;
expect(result.status).toBe("completed");
});
- it("raw protocol — turn/completed (flat params) backward compat", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ it("raw protocol — turn/completed (flat params) backward compat signals continuation", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 1 });
const mock = getMock();
await completeHandshake();
sendNotification("turn/completed", { turnId: "turn_1", status: "completed" });
+ await tick();
+ // maxTurns=1 so loop exits immediately after first turn, triggers turn done
+ expect(mock.stdinEnd).toHaveBeenCalled();
mock.proc.emit("close", 0);
const result = await session.result;
@@ -497,12 +512,14 @@ describe("CodexBackend", () => {
});
it("raw protocol — duplicate turn/completed for same turnId is deduplicated", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 1 });
const mock = getMock();
await completeHandshake();
sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ // Same turnId — deduplicated, so "failed" is ignored
sendNotification("turn/completed", { turn: { id: "turn_1", status: "failed" } });
+ await tick();
mock.proc.emit("close", 0);
const result = await session.result;
@@ -622,13 +639,15 @@ describe("CodexBackend", () => {
expect(messages).toContainEqual({ type: "text", content: "Here is the answer" });
});
- it("raw protocol — thread/status/changed (nested idle) triggers turn done when turnStarted", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ it("raw protocol — thread/status/changed (nested idle) signals continuation when turnStarted", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 1 });
const mock = getMock();
await completeHandshake();
sendNotification("turn/started", { turn: { id: "turn_1" } });
sendNotification("thread/status/changed", { status: { type: "idle" } });
+ await tick();
+ // maxTurns=1 so loop exits after first continuation signal
expect(mock.stdinEnd).toHaveBeenCalled();
mock.proc.emit("close", 0);
@@ -636,13 +655,15 @@ describe("CodexBackend", () => {
expect(result.status).toBe("completed");
});
- it("raw protocol — thread/status/changed (flat idle) backward compat", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ it("raw protocol — thread/status/changed (flat idle) backward compat signals continuation", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 1 });
const mock = getMock();
await completeHandshake();
sendNotification("turn/started", { turn: { id: "turn_1" } });
sendNotification("thread/status/changed", { status: "idle" });
+ await tick();
+ expect(mock.stdinEnd).toHaveBeenCalled();
mock.proc.emit("close", 0);
const result = await session.result;
@@ -670,15 +691,17 @@ describe("CodexBackend", () => {
const mock = getMock();
await completeHandshake();
- sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
- // First call: stdin.end + kill
+ // final_answer triggers triggerTurnDone
+ sendNotification("item/completed", {
+ item: { type: "agentMessage", text: "answer", phase: "final_answer" },
+ });
expect(mock.stdinEnd).toHaveBeenCalledTimes(1);
expect(mock.proc.kill).toHaveBeenCalledTimes(1);
- // Second completion signal (e.g. thread/status/changed also fires)
- sendNotification("turn/started", { turn: { id: "turn_1" } });
+ // Subsequent signals should not fire again
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ sendNotification("turn/started", { turn: { id: "turn_2" } });
sendNotification("thread/status/changed", { status: { type: "idle" } });
- // Should not call again
expect(mock.stdinEnd).toHaveBeenCalledTimes(1);
expect(mock.proc.kill).toHaveBeenCalledTimes(1);
@@ -707,10 +730,10 @@ describe("CodexBackend", () => {
expect(mock.stdinEnd).not.toHaveBeenCalled();
- // Main thread completes normally
- sendNotification("turn/completed", {
+ // Main thread completes via final_answer
+ sendNotification("item/completed", {
threadId: "thread_main",
- turn: { id: "main_turn", status: "completed" },
+ item: { type: "agentMessage", text: "main done", phase: "final_answer" },
});
expect(mock.stdinEnd).toHaveBeenCalled();
mock.proc.emit("close", 0);
@@ -754,12 +777,13 @@ describe("CodexBackend", () => {
});
it("error notification with willRetry=true does NOT set turnError", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 1 });
const mock = getMock();
await completeHandshake();
sendNotification("error", { error: { message: "reconnecting" }, willRetry: true });
sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ await tick();
mock.proc.emit("close", 0);
const result = await session.result;
@@ -804,7 +828,7 @@ describe("CodexBackend", () => {
});
// Full integration test
- it("full integration: handshake → deltas → turn/completed → result resolves", async () => {
+ it("full integration: handshake → deltas → final_answer → result resolves", async () => {
const session = backend.execute("hello world", { cwd: "/tmp" });
const mock = getMock();
@@ -817,15 +841,12 @@ describe("CodexBackend", () => {
sendNotification("item/agentMessage/delta", { threadId: "thread_xyz", itemId: "msg_1", delta: "Hi" });
sendNotification("item/agentMessage/delta", { threadId: "thread_xyz", itemId: "msg_1", delta: " there" });
- // Agent completes with full text
+ // Agent completes with full text and final_answer
sendNotification("item/completed", {
threadId: "thread_xyz",
- item: { type: "agentMessage", id: "msg_1", text: "Hi there" },
+ item: { type: "agentMessage", id: "msg_1", text: "Hi there", phase: "final_answer" },
});
- // Turn completes
- sendNotification("turn/completed", { threadId: "thread_xyz", turn: { id: "turn_1", status: "completed" } });
-
expect(mock.stdinEnd).toHaveBeenCalled();
mock.proc.emit("close", 0);
@@ -869,11 +890,12 @@ describe("CodexBackend", () => {
});
it("turn completed successfully + non-zero exit code → status completed (not failed)", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 1 });
const mock = getMock();
await completeHandshake();
sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ await tick();
mock.proc.emit("close", 1);
const result = await session.result;
@@ -912,12 +934,13 @@ describe("CodexBackend", () => {
});
it("turn completed successfully + non-zero exit + turnError → status failed with turnError", async () => {
- const session = backend.execute("hello", { cwd: "/tmp" });
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 1 });
const mock = getMock();
await completeHandshake();
sendNotification("error", { error: { message: "rate limit" }, willRetry: false });
sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ await tick();
mock.proc.emit("close", 1);
const result = await session.result;
@@ -977,4 +1000,190 @@ describe("CodexBackend", () => {
expect(result.status).toBe("timeout");
vi.useRealTimers();
});
+
+ // Multi-turn continuation tests
+ it("multi-turn: text response → continuation → tool calls → final_answer → done", async () => {
+ const session = backend.execute("write a plan", { cwd: "/tmp", maxTurns: 10 });
+ const mock = getMock();
+
+ await completeHandshake("thread_mt");
+
+ // Turn 1: agent says "I'll write the plan"
+ sendNotification("turn/started", { threadId: "thread_mt", turn: { id: "turn_1" } });
+ sendNotification("item/completed", {
+ threadId: "thread_mt",
+ item: { type: "agentMessage", id: "msg_1", text: "I'll write the plan now" },
+ });
+ sendNotification("turn/completed", { threadId: "thread_mt", turn: { id: "turn_1", status: "completed" } });
+
+ // Should send continuation turn/start (id=4)
+ await tick();
+ const cont1 = mock.stdinWrites.filter((w) => w.includes('"continue"'));
+ expect(cont1.length).toBe(1);
+ sendResponse(4, {});
+ await tick();
+
+ // Turn 2: agent uses a tool
+ sendNotification("turn/started", { threadId: "thread_mt", turn: { id: "turn_2" } });
+ sendNotification("item/started", {
+ threadId: "thread_mt",
+ item: { type: "commandExecution", id: "cmd_1", command: "echo plan" },
+ });
+ sendNotification("item/completed", {
+ threadId: "thread_mt",
+ item: { type: "commandExecution", id: "cmd_1", aggregatedOutput: "plan content" },
+ });
+ // Agent produces final answer
+ sendNotification("item/completed", {
+ threadId: "thread_mt",
+ item: { type: "agentMessage", id: "msg_2", text: "Here is the plan", phase: "final_answer" },
+ });
+
+ // Should kill now
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ expect(result.output).toBe("Here is the plan");
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "I'll write the plan now" });
+ expect(messages).toContainEqual(expect.objectContaining({ type: "tool-use", tool: "exec_command" }));
+ expect(messages).toContainEqual(expect.objectContaining({ type: "tool-result", callId: "cmd_1" }));
+ expect(messages).toContainEqual({ type: "text", content: "Here is the plan" });
+ });
+
+ it("multi-turn: maxTurns limit stops runaway continuation", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 3 });
+ const mock = getMock();
+
+ await completeHandshake("thread_max");
+
+ // Turn 1 completes
+ sendNotification("turn/started", { threadId: "thread_max", turn: { id: "turn_1" } });
+ sendNotification("turn/completed", { threadId: "thread_max", turn: { id: "turn_1", status: "completed" } });
+ await tick();
+ sendResponse(4, {}); // continuation turn/start response
+ await tick();
+
+ // Turn 2 completes
+ sendNotification("turn/started", { threadId: "thread_max", turn: { id: "turn_2" } });
+ sendNotification("turn/completed", { threadId: "thread_max", turn: { id: "turn_2", status: "completed" } });
+ await tick();
+ sendResponse(5, {}); // continuation turn/start response
+ await tick();
+
+ // Turn 3 completes — this is the last allowed turn (maxTurns=3)
+ sendNotification("turn/started", { threadId: "thread_max", turn: { id: "turn_3" } });
+ sendNotification("turn/completed", { threadId: "thread_max", turn: { id: "turn_3", status: "completed" } });
+ await tick();
+
+ // Should kill after maxTurns exceeded (no more continuation)
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ it("multi-turn: turn/completed with error/failed still triggers immediate turn done", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 10 });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "error", error: { message: "rate limit" } } });
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toBe("rate limit");
+ });
+
+ it("multi-turn: phase=final_answer triggers immediate turn done (no continuation)", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 10 });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/completed", {
+ item: { type: "agentMessage", text: "answer", phase: "final_answer" },
+ });
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ // No continuation turn/start should have been sent
+ const continuations = mock.stdinWrites.filter((w) => w.includes('"continue"'));
+ expect(continuations.length).toBe(0);
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ it("multi-turn: continuation turn/start RPC failure triggers turn done", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 10 });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ await tick();
+ // Fail the continuation turn/start RPC (id=4)
+ sendError(4, { code: -1, message: "connection lost" });
+ await tick();
+
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ mock.proc.emit("close", 1);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toBe("connection lost");
+ });
+
+ it("multi-turn: turn/completed + thread/status/changed on same turn only triggers one continuation", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 2 });
+ const mock = getMock();
+
+ await completeHandshake("thread_dup");
+
+ sendNotification("turn/started", { threadId: "thread_dup", turn: { id: "turn_1" } });
+ // Both signals fire for same turn
+ sendNotification("turn/completed", { threadId: "thread_dup", turn: { id: "turn_1", status: "completed" } });
+ sendNotification("thread/status/changed", { threadId: "thread_dup", status: { type: "idle" } });
+ await tick();
+
+ // Only one continuation turn/start should be sent
+ const continuations = mock.stdinWrites.filter((w) => w.includes('"continue"'));
+ expect(continuations.length).toBe(1);
+
+ sendResponse(4, {}); // continuation response
+ await tick();
+
+ // End with final_answer
+ sendNotification("item/completed", {
+ threadId: "thread_dup",
+ item: { type: "agentMessage", text: "done", phase: "final_answer" },
+ });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ it("multi-turn: process exit mid-continuation resolves result correctly", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp", maxTurns: 10 });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/started", { turn: { id: "turn_1" } });
+ sendNotification("item/completed", {
+ item: { type: "agentMessage", text: "working on it" },
+ });
+ // Process exits unexpectedly (e.g. OOM kill) while waiting for continuation
+ mock.proc.emit("close", 137);
+
+ const result = await session.result;
+ // Has output so treated as completed despite non-zero exit
+ expect(result.status).toBe("completed");
+ expect(result.output).toBe("working on it");
+ });
});
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
index a92e5eb79..f0db055fd 100644
--- a/src/cli/daemon/agent/codex.ts
+++ b/src/cli/daemon/agent/codex.ts
@@ -78,10 +78,14 @@ export class CodexBackend implements AgentBackend {
// Turn lifecycle state
let turnStarted = false;
let turnDoneTriggered = false;
- let turnCompletedSuccessfully = false;
+ let anyTurnCompletedSuccessfully = false;
let lastCompletedTurnId = "";
let turnError = "";
+ // Continuation state (multi-turn)
+ let continuationResolve: (() => void) | null = null;
+ let turnContinuationTriggered = false;
+
// Pending RPC callbacks
const pendingRequests = new Map<
number,
@@ -143,10 +147,25 @@ export class CodexBackend implements AgentBackend {
if (msg && !turnError) turnError = msg;
};
+ const signalContinuation = () => {
+ if (turnContinuationTriggered) return;
+ turnContinuationTriggered = true;
+ if (continuationResolve) {
+ const r = continuationResolve;
+ continuationResolve = null;
+ r();
+ }
+ };
+
const triggerTurnDone = (aborted: boolean) => {
if (turnDoneTriggered) return;
turnDoneTriggered = true;
resultStatus = aborted ? "aborted" : "completed";
+ if (continuationResolve) {
+ const r = continuationResolve;
+ continuationResolve = null;
+ r();
+ }
try { proc.stdin?.end(); } catch { /* already closed */ }
try { proc.kill("SIGTERM"); } catch { /* already dead */ }
};
@@ -211,8 +230,8 @@ export class CodexBackend implements AgentBackend {
const status = (turn?.status as string) || (params.status as string) || "";
if (status === "completed" || status === "finished") {
- turnCompletedSuccessfully = true;
- triggerTurnDone(false);
+ anyTurnCompletedSuccessfully = true;
+ signalContinuation();
} else if (status === "cancelled" || status === "aborted" || status === "interrupted") {
triggerTurnDone(true);
} else if (status === "error" || status === "failed") {
@@ -239,7 +258,7 @@ export class CodexBackend implements AgentBackend {
? (statusObj.type as string) || ""
: (statusObj as string) || "";
if (statusType === "idle" && turnStarted) {
- triggerTurnDone(false);
+ signalContinuation();
}
break;
}
@@ -483,7 +502,7 @@ export class CodexBackend implements AgentBackend {
resolveSessionId(sessionId);
- // 5. Send turn/start with the prompt
+ // 4. Send turn/start with the prompt
await sendRpc("turn/start", {
threadId: sessionId,
input: [{ type: "text", text: prompt }],
@@ -497,7 +516,41 @@ export class CodexBackend implements AgentBackend {
}
};
- startHandshake();
+ const runWithContinuation = async () => {
+ await startHandshake();
+ if (resultStatus === "failed") return;
+
+ const parsedEnvTurns = parseInt(process.env.ALOOK_CODEX_MAX_TURNS || "50", 10);
+ const maxTurns = options.maxTurns ?? (Number.isNaN(parsedEnvTurns) ? 50 : parsedEnvTurns);
+ let turnCount = 1;
+
+ while (turnCount < maxTurns && !turnDoneTriggered) {
+ await new Promise<void>(resolve => { continuationResolve = resolve; });
+ if (turnDoneTriggered) break;
+
+ turnCount++;
+ turnStarted = false;
+ turnContinuationTriggered = false;
+ lastCompletedTurnId = "";
+
+ try {
+ await sendRpc("turn/start", {
+ threadId: sessionId,
+ input: [{ type: "text", text: "continue" }],
+ });
+ } catch (err) {
+ setTurnError(err instanceof Error ? err.message : "continuation turn/start failed");
+ triggerTurnDone(false);
+ break;
+ }
+ }
+
+ if (!turnDoneTriggered) {
+ triggerTurnDone(false);
+ }
+ };
+
+ runWithContinuation();
proc.on("close", (code: number | null) => {
if (timeoutTimer) clearTimeout(timeoutTimer);
@@ -506,7 +559,7 @@ export class CodexBackend implements AgentBackend {
if (timedOut) {
resultStatus = "timeout";
- } else if (code !== 0 && resultStatus === "completed" && !turnCompletedSuccessfully) {
+ } else if (code !== 0 && resultStatus === "completed" && !anyTurnCompletedSuccessfully) {
// If agent already produced output, treat as completed despite non-zero exit
// (e.g. MCP transport errors can crash the process after a successful response)
if (!lastOutput) {
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 6764d8ca8..cdb6d43fc 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -110,8 +110,9 @@ ${task.agent.instructions}
content += `\n## Your Colleagues
Below are your direct colleagues. You can reach them via email.
-**Important:**
-- When communicating with a colleague on the previous topics, always reply to the existing email thread instead of composing a new email. This keeps the full conversation context visible to your colleague so they can pick up where you left off. For a new topic, you can just start a new email.
+**Important:**
+- When communicating with a colleague on the **same topic** as an existing email thread, reply to that thread (use --in-reply-to) to keep context together.
+- **When starting a NEW topic or task that is unrelated to any previous email thread, you MUST compose a brand new email (do NOT use --in-reply-to). Never hijack an unrelated thread just because you recently emailed that colleague.** Judge by topic/task relevance, not by recency of communication.
`;
for (let i = 0; i < task.agent.colleagues.length; i++) {
const c = task.agent.colleagues[i];
diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.ts
index d872a2e2c..fae3b44c0 100644
--- a/src/cli/daemon/prompt.test.ts
+++ b/src/cli/daemon/prompt.test.ts
@@ -20,16 +20,16 @@ function makeTask(prompt: string, type = "user_dm_message"): Task {
describe("buildPrompt", () => {
it("returns structured JSON with type and instruction", () => {
const task = makeTask("Fix the login bug");
- expect(buildPrompt(task)).toBe(
- JSON.stringify({ type: "user_dm_message", instruction: "Fix the login bug" }),
- );
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.type).toBe("user_dm_message");
+ expect(parsed.instruction).toBe("Fix the login bug");
});
it("handles empty prompt", () => {
const task = makeTask("");
- expect(buildPrompt(task)).toBe(
- JSON.stringify({ type: "user_dm_message", instruction: "" }),
- );
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.type).toBe("user_dm_message");
+ expect(parsed.instruction).toBe("");
});
it("includes the task type in output", () => {
@@ -87,9 +87,15 @@ describe("buildPrompt", () => {
expect(parsed.notice).toContain("no human in this session");
});
- it("does not add notice for non-email tasks", () => {
+ it("adds DM_RESPONSE_NOTICE for user_dm_message tasks", () => {
const task = makeTask("Fix the bug", "user_dm_message");
const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.notice).toContain("final text response is visible to the user");
+ });
+
+ it("does not add notice for non-email non-dm tasks", () => {
+ const task = makeTask("Check inbox", "calendar_event");
+ const parsed = JSON.parse(buildPrompt(task));
expect(parsed.notice).toBeUndefined();
});
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
index 0c7277316..824ca342b 100644
--- a/src/cli/daemon/prompt.ts
+++ b/src/cli/daemon/prompt.ts
@@ -1,5 +1,10 @@
import type { Task, Attachment } from "./types.js";
+const DM_RESPONSE_NOTICE =
+ "IMPORTANT: Only your final text response is visible to the user." +
+ " Tool calls, intermediate reasoning, and mid-process outputs are NOT displayed." +
+ " Put all key information, answers, and conclusions in your final response — that is the only thing the user will read.";
+
const EMAIL_NOTICE =
"This task was triggered automatically by an incoming email. There is no human in this session." +
" If you need to communicate with a human, you MUST send an email using the email sending tool." +
@@ -16,6 +21,9 @@ function buildDmNotice(name: string, email: string): string {
export function buildPrompt(task: Task, attachments?: Attachment[]): string {
const obj: Record<string, unknown> = { type: task.type, instruction: task.prompt };
+ if (task.type === "user_dm_message") {
+ obj.notice = DM_RESPONSE_NOTICE;
+ }
if (task.type === "email_notification") {
const ctx = task.context as Record<string, unknown> | undefined;
const dmUser = ctx?.dmUser as { name: string; email: string } | undefined;
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index 2782fb5ed..db02b10ba 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -242,7 +242,7 @@ export function AgentChatView() {
const searchParams = useSearchParams();
const { workspaceId } = useWorkspace();
const { agents, activeTaskCounts, subscribeWs } = useAgentContext();
- const { activeChannel } = useChannel();
+ const { activeChannel, loading: channelLoading } = useChannel();
const agentId = params.id as string;
const scrollToTaskId = searchParams.get("task");
const targetConvId = searchParams.get("conv");
@@ -344,10 +344,14 @@ export function AgentChatView() {
}, []);
useEffect(() => {
+ if (channelLoading) return;
+
if (pollRef.current) clearInterval(pollRef.current);
pollRef.current = null;
pollTaskIdRef.current = null;
+ let ignore = false;
queueMicrotask(() => {
+ if (ignore) return;
setLoading(true);
initialScrollDone.current = false;
setActiveTask(null);
@@ -371,6 +375,7 @@ export function AgentChatView() {
listArtifacts(targetConvId, workspaceId).catch(() => [] as Artifact[]),
listBufferedMessages(targetConvId, workspaceId).catch(() => [] as Message[]),
]);
+ if (ignore) return;
setConversation(conv);
setMessages(msgs);
setHasMore(msgs.length >= MESSAGE_LIMIT);
@@ -379,13 +384,15 @@ export function AgentChatView() {
const taskIds = [...new Set(msgs.filter((m) => m.role === "assistant" && m.task_id).map((m) => m.task_id!))];
if (taskIds.length > 0) {
getTaskStepCounts(taskIds, workspaceId)
- .then(setStepCounts)
+ .then((counts) => { if (!ignore) setStepCounts(counts); })
.catch(() => {});
}
const task = await getTask(scrollToTaskId, workspaceId).catch(() => null);
+ if (ignore) return;
if (task && !["completed", "failed", "cancelled", "superseded"].includes(task.status)) {
setActiveTask(task);
const tmsgs = await getTaskMessages(scrollToTaskId, workspaceId).catch(() => [] as TaskMessage[]);
+ if (ignore) return;
setTaskMessages(tmsgs);
if (tmsgs.length > 0) {
lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq));
@@ -394,6 +401,7 @@ export function AgentChatView() {
}
} catch {
const data = await chatInit(agentId, workspaceId, activeChannel);
+ if (ignore) return;
setConversation(data.conversation);
setMessages(data.messages);
setHasMore(data.has_more_messages);
@@ -403,6 +411,7 @@ export function AgentChatView() {
}
} else {
const data = await chatInit(agentId, workspaceId, activeChannel);
+ if (ignore) return;
setConversation(data.conversation);
setMessages(data.messages);
setHasMore(data.has_more_messages);
@@ -424,11 +433,12 @@ export function AgentChatView() {
} catch {
toast.error("Failed to load conversation");
} finally {
- setLoading(false);
+ if (!ignore) setLoading(false);
}
}
load();
- }, [agentId, workspaceId, targetConvId, scrollToTaskId, activeChannel]);
+ return () => { ignore = true; };
+ }, [agentId, workspaceId, targetConvId, scrollToTaskId, activeChannel, channelLoading]);
// Scroll to bottom on initial load (skip if scroll-to-task is active)
useEffect(() => {
diff --git a/src/web/src/components/agent-status-badge.tsx b/src/web/src/components/agent-status-badge.tsx
index 9803e2e91..04124e252 100644
--- a/src/web/src/components/agent-status-badge.tsx
+++ b/src/web/src/components/agent-status-badge.tsx
@@ -1,16 +1,15 @@
"use client";
-import { useState, useCallback, useMemo } from "react";
+import { useState, useCallback } from "react";
import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { CalendarDays, Mail, MessageSquare } from "lucide-react";
import { badgeVariants } from "@/components/ui/badge";
import { Badge } from "@/components/ui/badge";
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
-import { listAgentActiveTasks, type ActiveTask } from "@/lib/api";
+import { listWorkspaceActiveTasks, type WorkspaceActiveTask } from "@/lib/api";
import { useWorkspace } from "@/contexts/workspace-context";
+import { relativeTime } from "@/lib/time";
interface AgentStatusBadgeProps {
isOnline: boolean;
@@ -18,23 +17,6 @@ interface AgentStatusBadgeProps {
agentId: string;
}
-const TASK_TYPES = [
- { type: "user_dm_message", icon: MessageSquare, label: "Chat" },
- { type: "email_notification", icon: Mail, label: "Email" },
- { type: "calendar_event", icon: CalendarDays, label: "Calendar" },
-] as const;
-
-function getTaskRoute(slug: string, agentId: string, type: string) {
- switch (type) {
- case "email_notification":
- return `/w/${slug}/agents/${agentId}/email`;
- case "calendar_event":
- return `/w/${slug}/calendar?agents=${agentId}`;
- default:
- return `/w/${slug}/agents/${agentId}`;
- }
-}
-
function StatusDot({ online }: { online: boolean }) {
return (
<span
@@ -46,22 +28,40 @@ function StatusDot({ online }: { online: boolean }) {
);
}
-function groupByType(tasks: ActiveTask[]) {
- const map: Record<string, { total: number; running: number }> = {};
- for (const t of tasks) {
- const entry = map[t.type] ?? (map[t.type] = { total: 0, running: 0 });
- entry.total++;
- if (t.status === "running") entry.running++;
- }
- return map;
+function TaskRow({ task, slug, agentId }: { task: WorkspaceActiveTask; slug: string; agentId: string }) {
+ const isRunning = task.status === "running";
+ return (
+ <Link
+ href={`/w/${slug}/agents/${agentId}?task=${task.id}&conv=${task.conversation_id}`}
+ className="flex items-center gap-2 w-full py-1.5 px-2 hover:bg-muted rounded-md transition-colors cursor-pointer"
+ >
+ <span
+ className={cn(
+ "size-1.5 rounded-full shrink-0",
+ isRunning ? "bg-primary animate-pulse" : "bg-muted-foreground/40"
+ )}
+ />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="text-[10px] text-muted-foreground shrink-0">
+ #{task.channel ?? "default"}
+ </span>
+ </div>
+ <p className="text-xs truncate">{task.prompt}</p>
+ </div>
+ <span className="text-[10px] text-muted-foreground whitespace-nowrap shrink-0">
+ {relativeTime(task.created_at)}
+ </span>
+ </Link>
+ );
}
+const MAX_VISIBLE_TASKS = 6;
const badgeBase = "gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer";
export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBadgeProps) {
const { slug, workspaceId } = useWorkspace();
- const router = useRouter();
- const [tasks, setTasks] = useState<ActiveTask[] | null>(null);
+ const [tasks, setTasks] = useState<WorkspaceActiveTask[] | null>(null);
const [loadingTasks, setLoadingTasks] = useState(false);
const [error, setError] = useState(false);
@@ -70,8 +70,8 @@ export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBa
setLoadingTasks(true);
setError(false);
try {
- const res = await listAgentActiveTasks(agentId, workspaceId);
- setTasks(res.tasks);
+ const res = await listWorkspaceActiveTasks(workspaceId);
+ setTasks(res.tasks.filter((t) => t.agent_id === agentId));
} catch {
setError(true);
} finally {
@@ -79,8 +79,6 @@ export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBa
}
}, [agentId, workspaceId]);
- const grouped = useMemo(() => (tasks ? groupByType(tasks) : null), [tasks]);
-
if (!isOnline) {
return (
<Badge
@@ -115,15 +113,17 @@ export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBa
<span className="hidden sm:inline">Online</span>
)}
</PopoverTrigger>
- <PopoverContent className="w-52 p-0">
+ <PopoverContent className="w-72 p-0">
{loadingTasks ? (
<div className="p-2 space-y-1">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="flex items-center gap-2 py-1.5 px-2">
- <Skeleton className="size-3.5 rounded" />
- <Skeleton className="h-3 w-12" />
- <div className="flex-1" />
- <Skeleton className="h-3 w-6" />
+ <Skeleton className="size-1.5 rounded-full" />
+ <div className="flex-1 space-y-1">
+ <Skeleton className="h-2.5 w-10" />
+ <Skeleton className="h-3 w-full" />
+ </div>
+ <Skeleton className="h-2.5 w-8" />
</div>
))}
</div>
@@ -132,31 +132,18 @@ export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBa
) : !tasks || tasks.length === 0 ? (
<div className="p-3 text-xs text-muted-foreground">No active tasks</div>
) : (
- <div className="py-1">
- {TASK_TYPES.map(({ type, icon: Icon, label }) => {
- const entry = grouped?.[type];
- return (
- <button
- key={type}
- type="button"
- onClick={() => router.push(getTaskRoute(slug, agentId, type))}
- className="flex items-center gap-2 w-full py-1.5 px-2 text-left hover:bg-muted rounded-md transition-colors cursor-pointer"
- >
- <Icon className="size-3.5 text-muted-foreground shrink-0" />
- <span className="text-xs flex-1">{label}</span>
- {entry ? (
- <span className="inline-flex items-center gap-1 text-xs text-muted-foreground tabular-nums">
- {entry.running > 0 && (
- <span className="size-1.5 rounded-full bg-status-online animate-pulse" />
- )}
- {entry.running > 0 ? entry.running : entry.total}
- </span>
- ) : (
- <span className="text-xs text-muted-foreground/40">0</span>
- )}
- </button>
- );
- })}
+ <div className="py-1 max-h-[300px] overflow-y-auto">
+ {tasks.slice(0, MAX_VISIBLE_TASKS).map((task) => (
+ <TaskRow key={task.id} task={task} slug={slug} agentId={agentId} />
+ ))}
+ {tasks.length > MAX_VISIBLE_TASKS && (
+ <Link
+ href={`/w/${slug}/agents/${agentId}/activity?status=running`}
+ className="block text-xs text-muted-foreground hover:text-foreground text-center py-1.5 transition-colors"
+ >
+ View all {tasks.length} tasks
+ </Link>
+ )}
</div>
)}
</PopoverContent>
diff --git a/src/web/src/components/canvas/active-tasks-float.tsx b/src/web/src/components/canvas/active-tasks-float.tsx
index d6350a32f..6a0666d49 100644
--- a/src/web/src/components/canvas/active-tasks-float.tsx
+++ b/src/web/src/components/canvas/active-tasks-float.tsx
@@ -8,20 +8,7 @@ import { useWorkspace } from "@/contexts/workspace-context";
import { useIsMobile } from "@/hooks/use-mobile";
import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";
import type { WorkspaceActiveTask } from "@/lib/api";
-
-function relativeTime(dateStr: string): string {
- const date = new Date(dateStr);
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMin = Math.floor(diffMs / 60000);
- if (diffMin < 1) return "just now";
- if (diffMin < 60) return `${diffMin}m ago`;
- const diffHrs = Math.floor(diffMin / 60);
- if (diffHrs < 24) return `${diffHrs}h ago`;
- const diffDays = Math.floor(diffHrs / 24);
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
-}
+import { relativeTime } from "@/lib/time";
function AgentAvatar({ name, avatarUrl, size = 20 }: { name?: string; avatarUrl?: string | null; size?: number }) {
const config = parseAvatarUrl(avatarUrl);
diff --git a/src/web/src/lib/time.ts b/src/web/src/lib/time.ts
new file mode 100644
index 000000000..16853a0f4
--- /dev/null
+++ b/src/web/src/lib/time.ts
@@ -0,0 +1,14 @@
+export function relativeTime(dateStr: string): string {
+ const date = new Date(dateStr);
+ if (isNaN(date.getTime())) return "";
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffMin = Math.floor(diffMs / 60000);
+ if (diffMin < 1) return "just now";
+ if (diffMin < 60) return `${diffMin}m ago`;
+ const diffHrs = Math.floor(diffMin / 60);
+ if (diffHrs < 24) return `${diffHrs}h ago`;
+ const diffDays = Math.floor(diffHrs / 24);
+ if (diffDays < 7) return `${diffDays}d ago`;
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}