Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: improve mobile and agent backend

Gusb87898031289
diff --git a/src/cli/daemon/agent/__tests__/codex.test.ts b/src/cli/daemon/agent/__tests__/codex.test.ts
index 2ebb6bdf2..c9d95f5b0 100644
--- a/src/cli/daemon/agent/__tests__/codex.test.ts
+++ b/src/cli/daemon/agent/__tests__/codex.test.ts
@@ -9,6 +9,7 @@ function createMockProc() {
const stdinWrites: string[] = [];
const stdout = new Readable({ read() {} });
const stderr = new Readable({ read() {} });
+ const stdinEnd = vi.fn();
const proc = Object.assign(new EventEmitter(), {
stdout,
stderr,
@@ -17,11 +18,12 @@ function createMockProc() {
stdinWrites.push(data);
return true;
},
+ end: stdinEnd,
},
kill: vi.fn(),
pid: 12345,
});
- return { proc, stdout, stderr, stdinWrites };
+ return { proc, stdout, stderr, stdinWrites, stdinEnd };
}
vi.mock("child_process", () => ({
@@ -394,19 +396,33 @@ describe("CodexBackend", () => {
});
// Raw protocol tests
- it("raw protocol — turn/started sets status and captures turnId", async () => {
+ it("raw protocol — turn/started sets turnStarted flag", async () => {
const session = backend.execute("hello", { cwd: "/tmp" });
const mock = getMock();
await completeHandshake();
- sendNotification("turn/started", { turnId: "turn_1" });
+ sendNotification("turn/started", { turn: { id: "turn_1" } });
mock.proc.emit("close", 0);
const messages = await collectMessages(session.messages);
expect(messages).not.toContainEqual(expect.objectContaining({ type: "status" }));
});
- it("raw protocol — turn/completed with completed triggers turn done", async () => {
+ it("raw protocol — turn/completed (nested) with completed triggers turn done", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ 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" });
const mock = getMock();
@@ -423,20 +439,58 @@ describe("CodexBackend", () => {
const mock = getMock();
await completeHandshake();
- sendNotification("turn/completed", { turnId: "turn_1", status: "cancelled" });
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "cancelled" } });
mock.proc.emit("close", 0);
const result = await session.result;
expect(result.status).toBe("aborted");
});
+ it("raw protocol — turn/completed with interrupted triggers aborted", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turn: { id: "turn_2", status: "interrupted" } });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("aborted");
+ });
+
+ it("raw protocol — turn/completed with failed captures error message", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turn: { id: "turn_f", status: "failed", error: { message: "rate limit exceeded" } } });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toBe("rate limit exceeded");
+ });
+
+ it("raw protocol — turn/completed with failed uses fallback message when no error.message", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turn: { id: "turn_f2", status: "failed" } });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toBe("codex turn failed");
+ });
+
it("raw protocol — duplicate turn/completed for same turnId is deduplicated", async () => {
const session = backend.execute("hello", { cwd: "/tmp" });
const mock = getMock();
await completeHandshake();
- sendNotification("turn/completed", { turnId: "turn_1", status: "completed" });
- sendNotification("turn/completed", { turnId: "turn_1", status: "failed", output: "should not override" });
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "failed" } });
mock.proc.emit("close", 0);
const result = await session.result;
@@ -503,7 +557,41 @@ describe("CodexBackend", () => {
);
});
- it("raw protocol — item/completed (agentMessage, phase=final_answer) emits text + turn done", async () => {
+ it("raw protocol — item/completed (agentMessage) reads item.text (flat)", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/completed", {
+ item: {
+ type: "agentMessage",
+ text: "Flat text answer",
+ },
+ });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "Flat text answer" });
+ });
+
+ it("raw protocol — item/completed (agentMessage) falls back to item.content[] when item.text absent", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/completed", {
+ item: {
+ type: "agentMessage",
+ content: [{ type: "text", text: "Content array answer" }],
+ },
+ });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "Content array answer" });
+ });
+
+ it("raw protocol — item/completed (agentMessage, phase=final_answer) triggers turn done", async () => {
const session = backend.execute("hello", { cwd: "/tmp" });
const mock = getMock();
@@ -512,21 +600,36 @@ describe("CodexBackend", () => {
item: {
type: "agentMessage",
phase: "final_answer",
- content: [{ type: "text", text: "Here is the answer" }],
+ text: "Here is the answer",
},
});
+ expect(mock.stdinEnd).toHaveBeenCalled();
mock.proc.emit("close", 0);
const messages = await collectMessages(session.messages);
expect(messages).toContainEqual({ type: "text", content: "Here is the answer" });
});
- it("raw protocol — thread/status/changed (idle) triggers turn done", async () => {
+ it("raw protocol — thread/status/changed (nested idle) triggers turn done when turnStarted", async () => {
const session = backend.execute("hello", { cwd: "/tmp" });
const mock = getMock();
await completeHandshake();
- sendNotification("turn/started", { turnId: "turn_1" });
+ sendNotification("turn/started", { turn: { id: "turn_1" } });
+ sendNotification("thread/status/changed", { status: { type: "idle" } });
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ it("raw protocol — thread/status/changed (flat idle) backward compat", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/started", { turn: { id: "turn_1" } });
sendNotification("thread/status/changed", { status: "idle" });
mock.proc.emit("close", 0);
@@ -534,6 +637,195 @@ describe("CodexBackend", () => {
expect(result.status).toBe("completed");
});
+ it("raw protocol — thread/status/changed (idle) does NOT trigger turn done if turnStarted is false", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ // No turn/started sent — turnStarted remains false
+ sendNotification("thread/status/changed", { status: { type: "idle" } });
+ expect(mock.stdinEnd).not.toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ // Process exits with code 0 but turnDone was never triggered, status stays "completed" (default)
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ // triggerTurnDone idempotency
+ it("triggerTurnDone is idempotent — second call does not double-kill", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ // First call: stdin.end + kill
+ 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" } });
+ sendNotification("thread/status/changed", { status: { type: "idle" } });
+ // Should not call again
+ expect(mock.stdinEnd).toHaveBeenCalledTimes(1);
+ expect(mock.proc.kill).toHaveBeenCalledTimes(1);
+
+ mock.proc.emit("close", 0);
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ // Subagent thread filtering
+ it("subagent thread notifications are ignored — no text, no turn completion", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake("thread_main");
+
+ // Subagent sends agentMessage from different thread
+ sendNotification("item/completed", {
+ threadId: "thread_subagent",
+ item: { type: "agentMessage", text: "subagent leak" },
+ });
+ // Subagent sends turn/completed from different thread
+ sendNotification("turn/completed", {
+ threadId: "thread_subagent",
+ turn: { id: "sub_turn", status: "completed" },
+ });
+
+ expect(mock.stdinEnd).not.toHaveBeenCalled();
+
+ // Main thread completes normally
+ sendNotification("turn/completed", {
+ threadId: "thread_main",
+ turn: { id: "main_turn", status: "completed" },
+ });
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).not.toContainEqual(expect.objectContaining({ content: "subagent leak" }));
+ });
+
+ it("subagent item/completed with phase=final_answer from different thread is ignored", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake("thread_main");
+
+ sendNotification("item/completed", {
+ threadId: "thread_subagent",
+ item: { type: "agentMessage", text: "subagent final", phase: "final_answer" },
+ });
+
+ expect(mock.stdinEnd).not.toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).not.toContainEqual(expect.objectContaining({ content: "subagent final" }));
+ });
+
+ // Error notifications
+ it("error notification with willRetry=false captures turnError", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("error", { error: { message: "server crashed" }, willRetry: false });
+ // error does NOT trigger turnDone — the process may still send turn/completed
+ expect(mock.stdinEnd).not.toHaveBeenCalled();
+ mock.proc.emit("close", 1);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toBe("server crashed");
+ });
+
+ it("error notification with willRetry=true does NOT set turnError", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("error", { error: { message: "reconnecting" }, willRetry: true });
+ sendNotification("turn/completed", { turn: { id: "turn_1", status: "completed" } });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ expect(result.error).toBe("");
+ });
+
+ // turnError first-write-wins
+ it("turnError has first-write-wins semantics", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ // First error
+ sendNotification("error", { error: { message: "first error" }, willRetry: false });
+ // Second error — should be ignored
+ sendNotification("error", { error: { message: "second error" }, willRetry: false });
+ mock.proc.emit("close", 1);
+
+ const result = await session.result;
+ expect(result.error).toBe("first error");
+ });
+
+ // item/agentMessage/delta protocol detection
+ it("item/agentMessage/delta triggers raw protocol detection", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/agentMessage/delta", {
+ itemId: "msg_1",
+ delta: "Hello",
+ });
+ // Should be logged as debug (default case) since no specific handler
+ // But protocol should now be locked to raw
+ sendNotification("codex/event", { type: "agent_message", text: "should be ignored" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ // The legacy event should NOT produce a text message since protocol is locked to raw
+ expect(messages).not.toContainEqual({ type: "text", content: "should be ignored" });
+ });
+
+ // Full integration test
+ it("full integration: handshake → deltas → turn/completed → result resolves", async () => {
+ const session = backend.execute("hello world", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake("thread_xyz");
+
+ // Agent starts turn
+ sendNotification("turn/started", { threadId: "thread_xyz", turn: { id: "turn_1" } });
+
+ // Agent sends deltas (logged as debug, not accumulated)
+ 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
+ sendNotification("item/completed", {
+ threadId: "thread_xyz",
+ item: { type: "agentMessage", id: "msg_1", text: "Hi there" },
+ });
+
+ // Turn completes
+ sendNotification("turn/completed", { threadId: "thread_xyz", turn: { id: "turn_1", status: "completed" } });
+
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ expect(result.output).toBe("Hi there");
+ expect(result.sessionId).toBe("thread_xyz");
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "Hi there" });
+ });
+
// Protocol detection / locking
it("first legacy event locks protocol to legacy", async () => {
const session = backend.execute("hello", { cwd: "/tmp" });
diff --git a/src/cli/daemon/agent/__tests__/opencode.test.ts b/src/cli/daemon/agent/__tests__/opencode.test.ts
index 241d1903a..799228981 100644
--- a/src/cli/daemon/agent/__tests__/opencode.test.ts
+++ b/src/cli/daemon/agent/__tests__/opencode.test.ts
@@ -10,6 +10,7 @@ function createMockProc() {
const stdinWrites: string[] = [];
const stdout = new Readable({ read() {} });
const stderr = new Readable({ read() {} });
+ const stdinEnd = vi.fn();
const proc = Object.assign(new EventEmitter(), {
stdout,
stderr,
@@ -18,11 +19,12 @@ function createMockProc() {
stdinWrites.push(data);
return true;
},
+ end: stdinEnd,
},
kill: vi.fn(),
pid: 12345,
});
- return { proc, stdout, stderr, stdinWrites };
+ return { proc, stdout, stderr, stdinWrites, stdinEnd };
}
vi.mock("child_process", () => ({
@@ -275,4 +277,95 @@ describe("OpenCodeBackend", () => {
expect(result.output).toBe("final output");
expect(result.sessionId).toBe("sess_done");
});
+
+ // --- Turn completion: process lifecycle ---
+
+ it("done event closes stdin and kills the process", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "done", output: "all done" }) + "\n");
+ await tick();
+
+ 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("all done");
+ });
+
+ it("complete event closes stdin and kills the process", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "complete", output: "finished" }) + "\n");
+ await tick();
+
+ 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("error event closes stdin and kills the process", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "error", message: "fatal error" }) + "\n");
+ await tick();
+
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
+
+ mock.proc.emit("close", 1);
+ const result = await session.result;
+ expect(result.error).toBe("fatal error");
+ });
+
+ it("turnDone is idempotent — done after error does not double-kill", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "error", message: "boom" }) + "\n");
+ await tick();
+ mock.stdout.push(JSON.stringify({ type: "done", output: "done anyway" }) + "\n");
+ await tick();
+
+ expect(mock.stdinEnd).toHaveBeenCalledTimes(1);
+ expect(mock.proc.kill).toHaveBeenCalledTimes(1);
+
+ mock.proc.emit("close", 1);
+ await session.result;
+ });
+
+ it("full flow: message → tool_call → tool_result → done → result resolves", async () => {
+ const session = backend.execute("fix the bug", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "session", session_id: "sess_123" }) + "\n");
+ mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "Let me check" }) + "\n");
+ mock.stdout.push(JSON.stringify({ type: "tool_call", name: "read_file", call_id: "c1", input: { path: "/bug.ts" } }) + "\n");
+ mock.stdout.push(JSON.stringify({ type: "tool_result", call_id: "c1", output: "buggy code" }) + "\n");
+ mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "Found the bug" }) + "\n");
+ mock.stdout.push(JSON.stringify({ type: "done", output: "Found the bug", session_id: "sess_123" }) + "\n");
+ await tick();
+
+ expect(mock.stdinEnd).toHaveBeenCalled();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ expect(result.output).toBe("Found the bug");
+ expect(result.sessionId).toBe("sess_123");
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "Let me check" });
+ expect(messages).toContainEqual({ type: "text", content: "Found the bug" });
+ expect(messages).toContainEqual(expect.objectContaining({ type: "tool-use", tool: "read_file", callId: "c1" }));
+ expect(messages).toContainEqual(expect.objectContaining({ type: "tool-result", callId: "c1", output: "buggy code" }));
+ });
});
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
index 5bfca1a23..45b6dfa49 100644
--- a/src/cli/daemon/agent/codex.ts
+++ b/src/cli/daemon/agent/codex.ts
@@ -20,6 +20,7 @@ const RAW_DETECTION_METHODS = new Set([
"thread/started",
"item/started",
"item/completed",
+ "item/agentMessage/delta",
]);
/** Extract thread ID from a thread/start response. */
@@ -74,8 +75,11 @@ export class CodexBackend implements AgentBackend {
// Protocol detection state
let notificationProtocol: NotificationProtocol = "unknown";
- // Turn deduplication
+ // Turn lifecycle state
+ let turnStarted = false;
+ let turnDoneTriggered = false;
let lastCompletedTurnId = "";
+ let turnError = "";
// Pending RPC callbacks
const pendingRequests = new Map<
@@ -134,12 +138,16 @@ export class CodexBackend implements AgentBackend {
pendingRequests.clear();
};
+ const setTurnError = (msg: string) => {
+ if (msg && !turnError) turnError = msg;
+ };
+
const triggerTurnDone = (aborted: boolean) => {
- if (aborted) {
- resultStatus = "aborted";
- } else {
- resultStatus = "completed";
- }
+ if (turnDoneTriggered) return;
+ turnDoneTriggered = true;
+ resultStatus = aborted ? "aborted" : "completed";
+ try { proc.stdin?.end(); } catch { /* already closed */ }
+ try { proc.kill("SIGTERM"); } catch { /* already dead */ }
};
const handleServerRequest = (msg: JsonRpcMessage) => {
@@ -177,36 +185,58 @@ export class CodexBackend implements AgentBackend {
notificationProtocol = "raw";
}
- // thread/status/changed is raw-only but NOT a detection trigger
- if (method === "thread/status/changed" && notificationProtocol === "legacy") {
+ // thread/status/changed and error are raw-only but NOT detection triggers
+ if ((method === "thread/status/changed" || method === "error") && notificationProtocol === "legacy") {
+ return;
+ }
+
+ // Subagent thread filtering: ignore notifications from threads other than ours
+ const notifThreadId = params.threadId as string | undefined;
+ if (sessionId && notifThreadId && notifThreadId !== sessionId) {
return;
}
switch (method) {
case "turn/started": {
+ turnStarted = true;
break;
}
case "turn/completed": {
- const turnId = params.turnId as string | undefined;
- if (turnId && turnId === lastCompletedTurnId) return; // deduplicate
+ const turn = params.turn as Record<string, unknown> | undefined;
+ const turnId = (turn?.id as string) || (params.turnId as string) || "";
+ if (turnId && turnId === lastCompletedTurnId) return;
if (turnId) lastCompletedTurnId = turnId;
- const status = params.status as string | undefined;
+ const status = (turn?.status as string) || (params.status as string) || "";
if (status === "completed" || status === "finished") {
triggerTurnDone(false);
- } else if (status === "cancelled" || status === "aborted") {
+ } else if (status === "cancelled" || status === "aborted" || status === "interrupted") {
triggerTurnDone(true);
} else if (status === "error" || status === "failed") {
- resultStatus = "failed";
- lastError = (params.output as string) || "turn failed";
+ const turnErr = turn?.error as Record<string, unknown> | undefined;
+ setTurnError((turnErr?.message as string) || "codex turn failed");
+ triggerTurnDone(false);
+ }
+ break;
+ }
+
+ case "error": {
+ const errObj = params.error as Record<string, unknown> | undefined;
+ const errMsg = (errObj?.message as string) || (params.message as string) || "";
+ const willRetry = params.willRetry === true;
+ if (errMsg && !willRetry) {
+ setTurnError(errMsg);
}
break;
}
case "thread/status/changed": {
- const status = params.status as string | undefined;
- if (status === "idle") {
+ const statusObj = params.status as Record<string, unknown> | string | undefined;
+ const statusType = typeof statusObj === "object" && statusObj !== null
+ ? (statusObj.type as string) || ""
+ : (statusObj as string) || "";
+ if (statusType === "idle" && turnStarted) {
triggerTurnDone(false);
}
break;
@@ -254,15 +284,21 @@ export class CodexBackend implements AgentBackend {
output: "",
});
} else if (itemType === "agentMessage") {
- const content = item.content as
- | { type: string; text?: string }[]
- | undefined;
- if (Array.isArray(content)) {
- for (const block of content) {
- if (block.type === "output_text" || block.type === "text") {
- if (block.text) {
- pushMessage({ type: "text", content: block.text });
- lastOutput = block.text;
+ const flatText = item.text as string | undefined;
+ if (flatText) {
+ pushMessage({ type: "text", content: flatText });
+ lastOutput = flatText;
+ } else {
+ const content = item.content as
+ | { type: string; text?: string }[]
+ | undefined;
+ if (Array.isArray(content)) {
+ for (const block of content) {
+ if (block.type === "output_text" || block.type === "text") {
+ if (block.text) {
+ pushMessage({ type: "text", content: block.text });
+ lastOutput = block.text;
+ }
}
}
}
@@ -477,6 +513,11 @@ export class CodexBackend implements AgentBackend {
lastError = stderr;
}
+ if (turnError) {
+ resultStatus = "failed";
+ lastError = turnError;
+ }
+
// Resolve sessionId promise (fallback if handshake never completed)
resolveSessionId(sessionId);
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
index 36dd3e6f4..2bc179aa1 100644
--- a/src/cli/daemon/agent/opencode.ts
+++ b/src/cli/daemon/agent/opencode.ts
@@ -46,6 +46,14 @@ export class OpenCodeBackend implements AgentBackend {
resolveSessionId = resolve;
});
+ let turnDoneTriggered = false;
+ const turnDone = () => {
+ if (turnDoneTriggered) return;
+ turnDoneTriggered = true;
+ try { proc.stdin?.end(); } catch { /* already closed */ }
+ try { proc.kill("SIGTERM"); } catch { /* already dead */ }
+ };
+
const messageQueue: AgentMessage[] = [];
let messageResolve: (() => void) | null = null;
let messageDone = false;
@@ -130,6 +138,7 @@ export class OpenCodeBackend implements AgentBackend {
const content = (event.message as string) || (event.content as string) || "";
lastError = content;
pushMessage({ type: "error", content });
+ turnDone();
break;
}
@@ -146,6 +155,7 @@ export class OpenCodeBackend implements AgentBackend {
resultStatus = "failed";
if (!lastError) lastError = output || "task failed";
}
+ turnDone();
break;
}
diff --git a/src/web/src/components/calendar/calendar-agenda.tsx b/src/web/src/components/calendar/calendar-agenda.tsx
index fe3fad372..d1936c282 100644
--- a/src/web/src/components/calendar/calendar-agenda.tsx
+++ b/src/web/src/components/calendar/calendar-agenda.tsx
@@ -4,6 +4,7 @@ import { cn } from "@/lib/utils";
import type { CalendarEvent, Agent } from "@alook/shared";
import { Skeleton } from "@/components/ui/skeleton";
import { agentColor, dateKey } from "./calendar-month-grid";
+import { formatRepeatDisplay } from "./repeat-interval-utils";
export interface CalendarAgendaProps {
events: CalendarEvent[];
@@ -137,7 +138,7 @@ export function CalendarAgenda({
<span className="flex-1 truncate text-sm">{ev.title}</span>
{ev.repeat_interval && (
<span className="shrink-0 text-[10px] text-muted-foreground">
- every {ev.repeat_interval}
+ {formatRepeatDisplay(ev.repeat_interval!)}
</span>
)}
</button>
diff --git a/src/web/src/components/calendar/calendar-event-sheet.tsx b/src/web/src/components/calendar/calendar-event-sheet.tsx
index d8f597f9e..264ae68f6 100644
--- a/src/web/src/components/calendar/calendar-event-sheet.tsx
+++ b/src/web/src/components/calendar/calendar-event-sheet.tsx
@@ -25,6 +25,7 @@ import {
Clock,
Repeat as RepeatIcon,
User,
+ X,
} from "lucide-react";
import { cn } from "@/lib/utils";
import type {
@@ -34,14 +35,15 @@ import type {
} from "@alook/shared";
import { CalendarDatePicker } from "./calendar-date-picker";
import { CalendarTimePicker } from "./calendar-time-picker";
-
-const REPEAT_OPTIONS = [
- { value: "", label: "Does not repeat" },
- { value: "1hour", label: "Every hour" },
- { value: "1day", label: "Every day" },
- { value: "1week", label: "Every week" },
- { value: "1month", label: "Every month" },
-];
+import {
+ type RepeatUnit,
+ parseRepeatInterval,
+ formatRepeatInterval,
+ unitLabel,
+ isValidUnit,
+ REPEAT_UNITS,
+ PRESET_INTERVALS,
+} from "./repeat-interval-utils";
export interface CreateFormValues {
agent_id: string;
@@ -248,7 +250,16 @@ export function CalendarEventSheet({
const [description, setDescription] = useState("");
const [dateValue, setDateValue] = useState<Date>(new Date());
const [timeValue, setTimeValue] = useState<string>("09:00");
- const [repeat, setRepeat] = useState("");
+ const [repeatEnabled, setRepeatEnabled] = useState(false);
+ const [repeatCount, setRepeatCount] = useState("1");
+ const [repeatUnit, setRepeatUnit] = useState<RepeatUnit>("day");
+
+ const repeat = useMemo(() => {
+ if (!repeatEnabled) return "";
+ const n = parseInt(repeatCount, 10);
+ if (!n || n < 1) return "";
+ return formatRepeatInterval(n, repeatUnit);
+ }, [repeatEnabled, repeatCount, repeatUnit]);
const [stopDate, setStopDate] = useState<Date | null>(null);
const [scopeOpen, setScopeOpen] = useState(false);
const [deleteScopeOpen, setDeleteScopeOpen] = useState(false);
@@ -273,7 +284,16 @@ export function CalendarEventSheet({
setDescription(event.description ?? "");
setDateValue(scheduled);
setTimeValue(parseTime(scheduled));
- setRepeat(event.repeat_interval ?? "");
+ const parsed = parseRepeatInterval(event.repeat_interval ?? "");
+ if (parsed) {
+ setRepeatEnabled(true);
+ setRepeatCount(String(parsed.count));
+ setRepeatUnit(parsed.unit);
+ } else {
+ setRepeatEnabled(false);
+ setRepeatCount("1");
+ setRepeatUnit("day");
+ }
setStopDate(
event.repeat_stop_at ? new Date(event.repeat_stop_at) : null
);
@@ -283,7 +303,9 @@ export function CalendarEventSheet({
setDescription("");
setDateValue(defaultDate ?? new Date());
setTimeValue(nextSlotTime(new Date()));
- setRepeat("");
+ setRepeatEnabled(false);
+ setRepeatCount("1");
+ setRepeatUnit("day");
setStopDate(null);
}
// Seed only on open transition / event id change.
@@ -314,6 +336,10 @@ export function CalendarEventSheet({
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(timeValue)) {
return "Time must be HH:MM in 24-hour format";
}
+ if (repeatEnabled) {
+ const n = parseInt(repeatCount, 10);
+ if (!n || n < 1) return "Repeat count must be a positive number";
+ }
if (stopDate && !repeat) {
return "Stop date requires a repeat interval";
}
@@ -560,25 +586,84 @@ export function CalendarEventSheet({
</PropertyRow>
<PropertyRow icon={<RepeatIcon className="size-3.5" />}>
- <select
- aria-label="Repeat"
- value={repeat}
- onChange={(e) => {
- const next = e.target.value;
- setRepeat(next);
- // Stop date only makes sense with a repeat interval. Clearing
- // the interval hides the row but must also drop the underlying
- // state so validation / patch-building don't see stale values.
- if (!next) setStopDate(null);
- }}
- className={GHOST_SELECT}
- >
- {REPEAT_OPTIONS.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
+ {!repeatEnabled ? (
+ <select
+ aria-label="Repeat"
+ value=""
+ onChange={(e) => {
+ const v = e.target.value;
+ if (!v) return;
+ if (v === "__custom__") {
+ setRepeatEnabled(true);
+ setRepeatCount("1");
+ setRepeatUnit("day");
+ } else {
+ const parsed = parseRepeatInterval(v);
+ if (parsed) {
+ setRepeatEnabled(true);
+ setRepeatCount(String(parsed.count));
+ setRepeatUnit(parsed.unit);
+ }
+ }
+ }}
+ className={GHOST_SELECT}
+ >
+ <option value="">Does not repeat</option>
+ {PRESET_INTERVALS.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ <option value="__custom__">Custom…</option>
+ </select>
+ ) : (
+ <div className="-ml-1.5 flex items-center gap-0.5">
+ <span className="px-1 text-sm text-foreground">Every</span>
+ <input
+ type="text"
+ inputMode="numeric"
+ aria-label="Repeat count"
+ value={repeatCount}
+ onChange={(e) => {
+ setRepeatCount(e.target.value.replace(/[^\d]/g, ""));
+ }}
+ onBlur={() => {
+ const n = parseInt(repeatCount, 10);
+ if (!n || n < 1) setRepeatCount("1");
+ }}
+ maxLength={4}
+ style={{ width: `${Math.max(1, repeatCount.length) + 1.5}ch` }}
+ className="h-7 shrink-0 border-0 bg-transparent px-0 text-center text-sm tabular-nums text-foreground rounded-md outline-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0 transition-colors"
+ />
+ <select
+ aria-label="Repeat unit"
+ value={repeatUnit}
+ onChange={(e) => {
+ if (isValidUnit(e.target.value)) setRepeatUnit(e.target.value);
+ }}
+ className="h-7 border-0 bg-transparent px-1 text-center text-sm text-foreground rounded-md outline-none appearance-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0 transition-colors"
+ >
+ {REPEAT_UNITS.map((u) => (
+ <option key={u} value={u}>
+ {unitLabel(u, parseInt(repeatCount, 10) || 1)}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ aria-label="Remove repeat"
+ onClick={() => {
+ setRepeatEnabled(false);
+ setRepeatCount("1");
+ setRepeatUnit("day");
+ setStopDate(null);
+ }}
+ className="inline-flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ )}
</PropertyRow>
{repeat && (
diff --git a/src/web/src/components/calendar/repeat-interval-utils.test.ts b/src/web/src/components/calendar/repeat-interval-utils.test.ts
new file mode 100644
index 000000000..62ae4d082
--- /dev/null
+++ b/src/web/src/components/calendar/repeat-interval-utils.test.ts
@@ -0,0 +1,97 @@
+import { describe, it, expect } from "vitest";
+import {
+ parseRepeatInterval,
+ formatRepeatInterval,
+ unitLabel,
+ formatRepeatDisplay,
+ isValidUnit,
+} from "./repeat-interval-utils";
+
+describe("parseRepeatInterval", () => {
+ it("parses valid intervals", () => {
+ expect(parseRepeatInterval("1day")).toEqual({ count: 1, unit: "day" });
+ expect(parseRepeatInterval("30min")).toEqual({ count: 30, unit: "min" });
+ expect(parseRepeatInterval("2week")).toEqual({ count: 2, unit: "week" });
+ expect(parseRepeatInterval("12month")).toEqual({ count: 12, unit: "month" });
+ expect(parseRepeatInterval("24hour")).toEqual({ count: 24, unit: "hour" });
+ });
+
+ it("returns null for invalid inputs", () => {
+ expect(parseRepeatInterval("")).toBeNull();
+ expect(parseRepeatInterval("weekly")).toBeNull();
+ expect(parseRepeatInterval("1year")).toBeNull();
+ expect(parseRepeatInterval("0day")).toBeNull();
+ expect(parseRepeatInterval("day")).toBeNull();
+ expect(parseRepeatInterval("1 day")).toBeNull();
+ });
+});
+
+describe("formatRepeatInterval", () => {
+ it("composes count and unit", () => {
+ expect(formatRepeatInterval(1, "day")).toBe("1day");
+ expect(formatRepeatInterval(30, "min")).toBe("30min");
+ expect(formatRepeatInterval(12, "month")).toBe("12month");
+ });
+
+ it("round-trips with parse", () => {
+ for (const raw of ["1day", "2week", "30min", "12month", "24hour"]) {
+ const parsed = parseRepeatInterval(raw)!;
+ expect(formatRepeatInterval(parsed.count, parsed.unit)).toBe(raw);
+ }
+ });
+});
+
+describe("unitLabel", () => {
+ it("returns singular for count=1", () => {
+ expect(unitLabel("day", 1)).toBe("day");
+ expect(unitLabel("min", 1)).toBe("minute");
+ expect(unitLabel("hour", 1)).toBe("hour");
+ expect(unitLabel("week", 1)).toBe("week");
+ expect(unitLabel("month", 1)).toBe("month");
+ });
+
+ it("returns plural for count>1", () => {
+ expect(unitLabel("day", 3)).toBe("days");
+ expect(unitLabel("min", 30)).toBe("minutes");
+ expect(unitLabel("hour", 24)).toBe("hours");
+ expect(unitLabel("week", 2)).toBe("weeks");
+ expect(unitLabel("month", 12)).toBe("months");
+ });
+});
+
+describe("formatRepeatDisplay", () => {
+ it("formats count=1 without number", () => {
+ expect(formatRepeatDisplay("1day")).toBe("Every day");
+ expect(formatRepeatDisplay("1hour")).toBe("Every hour");
+ expect(formatRepeatDisplay("1week")).toBe("Every week");
+ expect(formatRepeatDisplay("1month")).toBe("Every month");
+ expect(formatRepeatDisplay("1min")).toBe("Every minute");
+ });
+
+ it("formats count>1 with number and plural", () => {
+ expect(formatRepeatDisplay("2week")).toBe("Every 2 weeks");
+ expect(formatRepeatDisplay("30min")).toBe("Every 30 minutes");
+ expect(formatRepeatDisplay("12month")).toBe("Every 12 months");
+ });
+
+ it("returns raw string for unparseable input", () => {
+ expect(formatRepeatDisplay("weekly")).toBe("weekly");
+ expect(formatRepeatDisplay("")).toBe("");
+ });
+});
+
+describe("isValidUnit", () => {
+ it("accepts valid units", () => {
+ expect(isValidUnit("min")).toBe(true);
+ expect(isValidUnit("hour")).toBe(true);
+ expect(isValidUnit("day")).toBe(true);
+ expect(isValidUnit("week")).toBe(true);
+ expect(isValidUnit("month")).toBe(true);
+ });
+
+ it("rejects invalid units", () => {
+ expect(isValidUnit("year")).toBe(false);
+ expect(isValidUnit("")).toBe(false);
+ expect(isValidUnit("days")).toBe(false);
+ });
+});
diff --git a/src/web/src/components/calendar/repeat-interval-utils.ts b/src/web/src/components/calendar/repeat-interval-utils.ts
new file mode 100644
index 000000000..07dc3e703
--- /dev/null
+++ b/src/web/src/components/calendar/repeat-interval-utils.ts
@@ -0,0 +1,67 @@
+export type RepeatUnit = "min" | "hour" | "day" | "week" | "month";
+
+export interface ParsedInterval {
+ count: number;
+ unit: RepeatUnit;
+}
+
+const INTERVAL_RE = /^(\d+)(min|hour|day|week|month)$/;
+
+export function parseRepeatInterval(raw: string): ParsedInterval | null {
+ const m = INTERVAL_RE.exec(raw);
+ if (!m) return null;
+ const count = parseInt(m[1]!, 10);
+ if (count < 1) return null;
+ return { count, unit: m[2]! as RepeatUnit };
+}
+
+export function formatRepeatInterval(count: number, unit: RepeatUnit): string {
+ return `${count}${unit}`;
+}
+
+const UNIT_LABELS: Record<RepeatUnit, [string, string]> = {
+ min: ["minute", "minutes"],
+ hour: ["hour", "hours"],
+ day: ["day", "days"],
+ week: ["week", "weeks"],
+ month: ["month", "months"],
+};
+
+export function unitLabel(unit: RepeatUnit, count: number): string {
+ return count === 1 ? UNIT_LABELS[unit][0] : UNIT_LABELS[unit][1];
+}
+
+export function formatRepeatDisplay(raw: string): string {
+ const parsed = parseRepeatInterval(raw);
+ if (!parsed) return raw;
+ const { count, unit } = parsed;
+ if (count === 1) return `Every ${UNIT_LABELS[unit][0]}`;
+ return `Every ${count} ${UNIT_LABELS[unit][1]}`;
+}
+
+const VALID_UNITS: Set<string> = new Set([
+ "min",
+ "hour",
+ "day",
+ "week",
+ "month",
+]);
+
+export function isValidUnit(s: string): s is RepeatUnit {
+ return VALID_UNITS.has(s);
+}
+
+export const REPEAT_UNITS: RepeatUnit[] = [
+ "min",
+ "hour",
+ "day",
+ "week",
+ "month",
+];
+
+export const PRESET_INTERVALS = [
+ { value: "1hour", label: "Every hour" },
+ { value: "1day", label: "Every day" },
+ { value: "1week", label: "Every week" },
+ { value: "1month", label: "Every month" },
+] as const;
diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsx
index 1c23db560..00b307c76 100644
--- a/src/web/src/components/home/hero-section.tsx
+++ b/src/web/src/components/home/hero-section.tsx
@@ -112,7 +112,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {
</h1>
<p
ref={sublineRef}
- className="max-w-lg text-center leading-relaxed px-2"
+ className="hidden sm:block max-w-lg text-center leading-relaxed px-2"
style={{
fontFamily: "var(--font-crt)",
color: "var(--landing-text-muted)",
@@ -173,7 +173,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {
{isLoggedIn ? (
<a
href="/workspaces?auto"
- className="inline-flex items-center gap-2 px-6 py-2.5 text-sm transition-all duration-200 hover:opacity-80"
+ className="hidden sm:inline-flex items-center gap-2 px-6 py-2.5 text-sm transition-all duration-200 hover:opacity-80"
style={{
fontFamily: "var(--font-mono)",
color: "var(--landing-text)",
@@ -191,7 +191,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {
) : (
<a
href="/sign-in"
- className="inline-flex items-center gap-2 px-6 py-2.5 text-sm transition-all duration-200 hover:opacity-80"
+ className="hidden sm:inline-flex items-center gap-2 px-6 py-2.5 text-sm transition-all duration-200 hover:opacity-80"
style={{
fontFamily: "var(--font-mono)",
color: "var(--landing-text)",
@@ -208,6 +208,15 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {
</a>
)}
</div>
+ <p
+ className="mt-4 sm:hidden text-center text-xs"
+ style={{
+ fontFamily: "var(--font-mono)",
+ color: "var(--landing-text-muted)",
+ }}
+ >
+ For the full experience, open on a desktop browser.
+ </p>
</div>
</section>
);