Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: simplify task stream to text-only, add agent recruit CLI, mock network dev tool, pet position persistence

Gus2f4e9c7d0617
diff --git a/.env.example b/.env.example
index 397857e26..13197b136 100644
--- a/.env.example
+++ b/.env.example
@@ -118,6 +118,13 @@
# App URL used by auth client (defaults to http://localhost:3000)
# NEXT_PUBLIC_APP_URL=http://localhost:3000
+# Mock network mode — adds artificial delay to all API requests (dev only)
+# Useful for testing loading states, skeletons, and race conditions.
+# NEXT_PUBLIC_MOCK_NETWORK=true
+
+# Delay in milliseconds applied to each API request when mock network is enabled (default: 300)
+# NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS=300
+
# WebSocket Durable Object port (dev only, must match src/ws-do/wrangler.toml)
# NEXT_PUBLIC_WS_DO_PORT=8789
diff --git a/src/cli/commands/agent.ts b/src/cli/commands/agent.ts
new file mode 100644
index 000000000..f56799cdc
--- /dev/null
+++ b/src/cli/commands/agent.ts
@@ -0,0 +1,77 @@
+import { Command } from "commander";
+import { readFileSync } from "fs";
+import { APIClient } from "../lib/client.js";
+import { printJSON } from "../lib/output.js";
+import { resolveAgentId } from "../lib/flags.js";
+import { resolveClientOpts } from "../lib/resolve-client.js";
+
+function readField(opts: { inline?: string; file?: string }, inlineName: string, fileName: string): string | null {
+ if (opts.inline && opts.file) {
+ console.error(`Error: --${inlineName} and --${fileName} are mutually exclusive`);
+ process.exit(1);
+ }
+ if (opts.file) return readFileSync(opts.file, "utf-8");
+ return opts.inline ?? null;
+}
+
+export function agentCommand(): Command {
+ const cmd = new Command("agent").description("Manage agents");
+
+ cmd
+ .command("recruit")
+ .description("Recruit a new colleague agent")
+ .option("--agent_id <id>", "Agent ID (or set ALOOK_AGENT_ID env var)")
+ .option("--instructions <text>", "Instructions for the new agent (system prompt)")
+ .option("--instructions-file <path>", "Read instructions from a file")
+ .option("--relationship <text>", "Relationship/delegation instruction for the link")
+ .option("--relationship-file <path>", "Read relationship from a file")
+ .option("--name <name>", "Preferred name for the new agent (auto-generated if omitted)")
+ .option("--description <text>", "Agent description")
+ .option("--model <model>", "Model override")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ const instructions = readField(
+ { inline: opts.instructions, file: opts.instructionsFile },
+ "instructions",
+ "instructions-file",
+ );
+ if (!instructions) {
+ console.error("Error: --instructions or --instructions-file is required");
+ process.exit(1);
+ }
+
+ const relationship = readField(
+ { inline: opts.relationship, file: opts.relationshipFile },
+ "relationship",
+ "relationship-file",
+ );
+ if (!relationship) {
+ console.error("Error: --relationship or --relationship-file is required");
+ process.exit(1);
+ }
+
+ const agentId = resolveAgentId(opts);
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ const body: Record<string, string> = { instructions, relationship };
+ if (opts.name) body.name = opts.name;
+ if (opts.description) body.description = opts.description;
+ if (opts.model) body.model = opts.model;
+
+ try {
+ const res = await client.postJSON<{
+ agent: { id: string; name: string; email: string };
+ link: { id: string; instruction: string };
+ }>(`/api/agents/recruit?agentId=${encodeURIComponent(agentId)}`, body);
+
+ if (opts.json) return printJSON(res);
+ console.log(`Recruited ${res.agent.name} (${res.agent.email}) — ${res.agent.id}`);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ return cmd;
+}
diff --git a/src/cli/commands/register.test.ts b/src/cli/commands/register.test.ts
index 06fd316a0..663d86f7c 100644
--- a/src/cli/commands/register.test.ts
+++ b/src/cli/commands/register.test.ts
@@ -61,11 +61,11 @@ describe("alook register", () => {
ok: resp.status >= 200 && resp.status < 300,
status: resp.status,
json: async () => resp.body,
- text: async () => JSON.stringify(resp.body),
+ text: async (): Promise<string> => JSON.stringify(resp.body),
};
}
}
- return { ok: false, status: 404, text: async () => "not found" };
+ return { ok: false, status: 404, text: async (): Promise<string> => "not found" };
}));
}
diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.ts
index 7257b8ac8..47984cdda 100644
--- a/src/cli/commands/update.test.ts
+++ b/src/cli/commands/update.test.ts
@@ -86,7 +86,7 @@ describe("alook update", () => {
mockGetCurrentVersion.mockReturnValue("0.5.0");
mockFetchLatestVersion.mockResolvedValue("1.0.0");
mockRunNpmUpdate.mockResolvedValue({ success: true, output: "" });
- (globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({ ok: true });
+ (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({ ok: true });
const cmd = updateCommand();
await cmd.parseAsync(["node", "update"]);
diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.ts
index 4f0e37500..7331d9ac9 100644
--- a/src/cli/daemon/client.test.ts
+++ b/src/cli/daemon/client.test.ts
@@ -148,7 +148,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ tasks: [] }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await client.poll("tok", "d1", 3);
@@ -167,7 +167,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ tasks: [] }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await client.poll("my_token_123", "d1", 1);
@@ -187,7 +187,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve(validPollResponse()),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const result = await client.poll("tok", "d1", 1);
@@ -201,7 +201,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ tasks: [] }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const result = await client.poll("tok", "d1", 1);
@@ -214,7 +214,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ tasks: [], pending_rescan: true }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const result = await client.poll("tok", "d1", 1);
@@ -227,7 +227,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ tasks: [] }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const result = await client.poll("tok", "d1", 1);
@@ -239,7 +239,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ tasks: [], evicted: true }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const result = await client.poll("tok", "d1", 1);
@@ -252,7 +252,7 @@ describe("DaemonClient.poll() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ unexpected: "data" }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await expect(client.poll("tok", "d1", 1)).rejects.toThrow();
@@ -275,7 +275,7 @@ describe("DaemonClient.register() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ runtimes: [{ id: "rt1" }] }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const resp = await client.register("tok", {
@@ -294,7 +294,7 @@ describe("DaemonClient.register() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ runtimes: [{ id: "rt1" }] }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await client.register("my_ws_token", {
@@ -332,7 +332,7 @@ describe("DaemonClient.deregister() with mocked fetch", () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 204,
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await client.deregister("tok", "d1");
@@ -367,7 +367,7 @@ describe("DaemonClient retries on TypeError (network failure)", () => {
status: 200,
json: () => Promise.resolve({ tasks: [] }),
});
- globalThis.fetch = fetchMock;
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const result = await client.poll("tok", "d1", 1);
@@ -378,7 +378,7 @@ describe("DaemonClient retries on TypeError (network failure)", () => {
it("throws TypeError after exhausting all retries", async () => {
const fetchMock = vi.fn().mockRejectedValue(new TypeError("fetch failed"));
- globalThis.fetch = fetchMock;
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await expect(client.poll("tok", "d1", 1)).rejects.toThrow(TypeError);
@@ -392,7 +392,7 @@ describe("DaemonClient retries on TypeError (network failure)", () => {
status: 500,
text: () => Promise.resolve("Internal Server Error"),
});
- globalThis.fetch = fetchMock;
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await expect(client.completeTask("tok", "t1", { output: "done" })).rejects.toThrow("HTTP 500");
@@ -407,7 +407,7 @@ describe("DaemonClient retries on TypeError (network failure)", () => {
ok: true,
arrayBuffer: () => Promise.resolve(new ArrayBuffer(4)),
});
- globalThis.fetch = fetchMock;
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
const buf = await client.downloadArtifact("tok", "art1", "ws1");
@@ -433,7 +433,7 @@ describe("DaemonClient.heartbeat() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ ok: true }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await client.heartbeat("tok", "d1");
@@ -464,7 +464,7 @@ describe("DaemonClient.sweep() with mocked fetch", () => {
ok: true,
status: 200,
json: () => Promise.resolve({ ok: true }),
- });
+ }) as unknown as typeof fetch;
const client = new DaemonClient("http://localhost:8080");
await client.sweep("tok", "d1");
@@ -511,7 +511,7 @@ function validApiTask(): TaskApi {
error: null,
created_at: "2024-01-01T00:00:00Z",
type: "user_dm_message",
- agent: { instructions: "help", name: "bot", runtime_config: {} },
+ agent: { instructions: "help", name: "bot", runtime_config: {}, email_addresses: [], colleagues: [] },
};
}
@@ -546,14 +546,14 @@ describe("fromApiTask", () => {
it("maps email_handle to emailHandle", () => {
const api = validApiTask();
- api.agent = { instructions: "help", name: "bot", runtime_config: {}, email_handle: "myagent" };
+ api.agent = { instructions: "help", name: "bot", runtime_config: {}, email_handle: "myagent", email_addresses: [], colleagues: [] };
const task = fromApiTask(api);
expect(task.agent?.emailHandle).toBe("myagent");
});
it("maps null email_handle to undefined", () => {
const api = validApiTask();
- api.agent = { instructions: "help", name: "bot", runtime_config: {}, email_handle: null };
+ api.agent = { instructions: "help", name: "bot", runtime_config: {}, email_handle: null, email_addresses: [], colleagues: [] };
const task = fromApiTask(api);
expect(task.agent?.emailHandle).toBeUndefined();
});
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index b04270aed..71a16fea0 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -91,8 +91,8 @@ vi.mock("./update-handler.js", () => ({
const mockFindRunningPidByTaskId = vi.fn();
const mockFindRunningEntryByContextKey = vi.fn(() => null);
vi.mock("./execenv/timeline.js", () => ({
- findRunningPidByTaskId: (...args: any[]) => mockFindRunningPidByTaskId(...args),
- findRunningEntryByContextKey: (...args: any[]) => mockFindRunningEntryByContextKey(...args),
+ findRunningPidByTaskId: (...args: any[]) => mockFindRunningPidByTaskId(...(args as any[])),
+ findRunningEntryByContextKey: (...args: any[]) => mockFindRunningEntryByContextKey(...(args as any[])),
}));
const mockWriteKillIntent = vi.fn();
@@ -101,11 +101,11 @@ const mockAcquireSteeringLock = vi.fn(() => true);
const mockReleaseSteeringLock = vi.fn();
const mockCleanupStaleIntents = vi.fn();
vi.mock("./execenv/steering.js", () => ({
- writeKillIntent: (...args: any[]) => mockWriteKillIntent(...args),
- clearKillIntent: (...args: any[]) => mockClearKillIntent(...args),
- acquireSteeringLock: (...args: any[]) => mockAcquireSteeringLock(...args),
- releaseSteeringLock: (...args: any[]) => mockReleaseSteeringLock(...args),
- cleanupStaleIntents: (...args: any[]) => mockCleanupStaleIntents(...args),
+ writeKillIntent: (...args: any[]) => mockWriteKillIntent(...(args as any[])),
+ clearKillIntent: (...args: any[]) => mockClearKillIntent(...(args as any[])),
+ acquireSteeringLock: (...args: any[]) => mockAcquireSteeringLock(...(args as any[])),
+ releaseSteeringLock: (...args: any[]) => mockReleaseSteeringLock(...(args as any[])),
+ cleanupStaleIntents: (...args: any[]) => mockCleanupStaleIntents(...(args as any[])),
}));
// Track spawned children
@@ -142,13 +142,13 @@ const mockUnlinkSync = vi.fn();
vi.mock("fs", () => ({
existsSync: vi.fn((p: string) => p.endsWith("session-runner.js")),
- openSync: (...args: any[]) => mockOpenSync(...args),
- closeSync: (...args: any[]) => mockCloseSync(...args),
- renameSync: (...args: any[]) => mockRenameSync(...args),
- mkdirSync: (...args: any[]) => mockMkdirSync(...args),
- readdirSync: (...args: any[]) => mockReaddirSync(...args),
- statSync: (...args: any[]) => mockStatSync(...args),
- unlinkSync: (...args: any[]) => mockUnlinkSync(...args),
+ openSync: (...args: any[]) => mockOpenSync(...(args as any[])),
+ closeSync: (...args: any[]) => mockCloseSync(...(args as any[])),
+ renameSync: (...args: any[]) => mockRenameSync(...(args as any[])),
+ mkdirSync: (...args: any[]) => mockMkdirSync(...(args as any[])),
+ readdirSync: (...args: any[]) => mockReaddirSync(...(args as any[])),
+ statSync: (...args: any[]) => mockStatSync(...(args as any[])),
+ unlinkSync: (...args: any[]) => mockUnlinkSync(...(args as any[])),
realpathSync: vi.fn((p: string) => p),
readFileSync: vi.fn(() => ""),
writeFileSync: vi.fn(),
@@ -159,10 +159,10 @@ const mockReadFile = vi.fn(async () => "");
const mockUnlink = vi.fn(async () => undefined);
const mockFsStat = vi.fn(async () => ({ mtimeMs: Date.now() }));
vi.mock("fs/promises", () => ({
- readdir: (...args: any[]) => mockReaddir(...args),
- readFile: (...args: any[]) => mockReadFile(...args),
- unlink: (...args: any[]) => mockUnlink(...args),
- stat: (...args: any[]) => mockFsStat(...args),
+ readdir: (...args: any[]) => mockReaddir(...(args as any[])),
+ readFile: (...args: any[]) => mockReadFile(...(args as any[])),
+ unlink: (...args: any[]) => mockUnlink(...(args as any[])),
+ stat: (...args: any[]) => mockFsStat(...(args as any[])),
}));
vi.mock("url", () => ({
@@ -273,13 +273,13 @@ describe("daemon session runner dispatch", () => {
};
let claimed = false;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
if (!claimed) {
claimed = true;
return { tasks: [fakeTask], evicted: false };
}
return { tasks: [], evicted: false };
- });
+ }) as any);
return fakeTask;
}
@@ -336,13 +336,13 @@ describe("daemon session runner dispatch", () => {
};
let claimed = false;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
if (!claimed) {
claimed = true;
return { tasks: [fakeTask], evicted: false };
}
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -506,11 +506,11 @@ describe("daemon with multi-workspace config", () => {
// W1 returns 3 tasks, W2 should get remaining (20 - 3 = 17)
let pollCall = 0;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
pollCall++;
if (pollCall === 1) return { tasks: [fakeTask, { ...fakeTask, id: "t2" }, { ...fakeTask, id: "t3" }], evicted: false };
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -548,12 +548,12 @@ describe("daemon with multi-workspace config", () => {
};
let pollCall = 0;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
pollCall++;
if (pollCall === 1) return { tasks: [fakeTaskWs1], evicted: false };
if (pollCall === 2) return { tasks: [fakeTaskWs2], evicted: false };
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -661,13 +661,13 @@ describe("daemon shutdown", () => {
};
let claimed = false;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
if (!claimed) {
claimed = true;
return { tasks: [fakeTask], evicted: false };
}
return { tasks: [], evicted: false };
- });
+ }) as any);
mockClientInstance.startTask.mockResolvedValue({});
await startDaemon();
@@ -733,10 +733,10 @@ describe("daemon agent_ids lazy sync", () => {
});
let claimed = false;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
if (!claimed) { claimed = true; return { tasks: [makeFakeTask()], evicted: false }; }
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -754,10 +754,10 @@ describe("daemon agent_ids lazy sync", () => {
});
let claimed = false;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
if (!claimed) { claimed = true; return { tasks: [makeFakeTask()], evicted: false }; }
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -772,13 +772,13 @@ describe("daemon agent_ids lazy sync", () => {
});
let claimed = false;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
if (!claimed) {
claimed = true;
return { tasks: [makeFakeTask({ id: "t1" }), makeFakeTask({ id: "t2" })], evicted: false };
}
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -1010,11 +1010,11 @@ describe("pruneSessionRunnerLogs", () => {
it("deletes oldest files when over limit, keeping newest 500", () => {
const files = Array.from({ length: 505 }, (_, i) => `${i}.log`);
mockReaddirSync.mockReturnValue(files);
- mockStatSync.mockImplementation((p: string) => {
+ mockStatSync.mockImplementation(((p: string) => {
const name = path.basename(p);
const idx = parseInt(name);
return { mtimeMs: idx * 1000 };
- });
+ }) as any);
pruneSessionRunnerLogs();
@@ -1137,12 +1137,12 @@ describe("daemon workspace eviction", () => {
});
const pollTokens: string[] = [];
- mockClientInstance.poll.mockImplementation(async (token: string) => {
+ mockClientInstance.poll.mockImplementation((async (token: string) => {
pollTokens.push(token);
// Evict ws2 (middle workspace)
if (token === "al_tok_ws2") return { tasks: [], evicted: true };
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -1184,10 +1184,10 @@ describe("daemon workspace eviction", () => {
return { runtimes: [{ id: `rt${registerCall}` }] };
});
- mockClientInstance.poll.mockImplementation(async (token: string) => {
+ mockClientInstance.poll.mockImplementation((async (token: string) => {
if (token === "al_tok_ws2") return { tasks: [], evicted: true };
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -1218,10 +1218,10 @@ describe("daemon workspace eviction", () => {
throw new Error("disk full");
});
- mockClientInstance.poll.mockImplementation(async (token: string) => {
+ mockClientInstance.poll.mockImplementation((async (token: string) => {
if (token === "al_tok_ws2") return { tasks: [], evicted: true };
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -1260,10 +1260,10 @@ describe("daemon 401 handling (no config removal)", () => {
],
});
- mockClientInstance.register.mockImplementation(async (token: string) => {
+ mockClientInstance.register.mockImplementation((async (token: string) => {
if (token === "al_tok_ws2") throw new Error("HTTP 401 Unauthorized");
return { runtimes: [{ id: "rt1" }] };
- });
+ }) as any);
mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
await startDaemon();
@@ -1290,10 +1290,10 @@ describe("daemon 401 handling (no config removal)", () => {
return { runtimes: [{ id: `rt${registerCall}` }] };
});
- mockClientInstance.poll.mockImplementation(async (token: string) => {
+ mockClientInstance.poll.mockImplementation((async (token: string) => {
if (token === "al_tok_ws2") throw new Error("HTTP 401 Unauthorized");
return { tasks: [], evicted: false };
- });
+ }) as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 50));
@@ -1320,7 +1320,7 @@ describe("daemon restart via update", () => {
tasks: [],
evicted: false,
pending_update: { version: "2.0.0" },
- });
+ } as any);
await startDaemon();
@@ -1342,7 +1342,7 @@ describe("daemon restart via update", () => {
tasks: [],
evicted: false,
pending_update: { version: "0.1.0" },
- });
+ } as any);
await startDaemon();
@@ -1364,7 +1364,7 @@ describe("daemon restart via update", () => {
tasks: [],
evicted: false,
pending_update: { version: "2.0.0" },
- });
+ } as any);
await startDaemon();
@@ -1445,7 +1445,7 @@ describe("daemon rescan via poll", () => {
tasks: [],
evicted: false,
pending_rescan: true,
- });
+ } as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 200));
@@ -1514,15 +1514,15 @@ describe("daemon restart spawn", () => {
});
// Make handleCliUpdate immediately invoke the restart callback
- vi.mocked(handleCliUpdate).mockImplementation((_version: string, onSuccess: () => void) => {
+ vi.mocked(handleCliUpdate).mockImplementation(((_version: string, onSuccess: () => void) => {
onSuccess();
- });
+ }) as any);
mockClientInstance.poll.mockResolvedValue({
tasks: [],
evicted: false,
pending_update: { version: "2.0.0" },
- });
+ } as any);
await startDaemon();
await new Promise((r) => setTimeout(r, 200));
@@ -1600,13 +1600,13 @@ describe("daemon kill_task handling", () => {
function setupKillTaskClaim(targetTaskId: string) {
let claimed = false;
- mockClientInstance.poll.mockImplementation(async () => {
+ mockClientInstance.poll.mockImplementation((async () => {
if (!claimed) {
claimed = true;
return { tasks: [makeKillTask(targetTaskId)], evicted: false };
}
return { tasks: [], evicted: false };
- });
+ }) as any);
}
it("sends SIGTERM when target PID is found in timeline", async () => {
diff --git a/src/cli/daemon/execenv/__tests__/context.test.ts b/src/cli/daemon/execenv/__tests__/context.test.ts
index 774d90649..cdc825d51 100644
--- a/src/cli/daemon/execenv/__tests__/context.test.ts
+++ b/src/cli/daemon/execenv/__tests__/context.test.ts
@@ -39,7 +39,11 @@ function makeTask(overrides: Partial<Task> = {}): Task {
prompt: "do something",
status: "running",
priority: 0,
+ type: "user_dm_message",
createdAt: "2026-01-01T00:00:00Z",
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
agent: { name: "test-agent", instructions: "Be helpful and concise." },
...overrides,
};
diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.ts
index ee87af249..824b92651 100644
--- a/src/cli/daemon/execenv/__tests__/timeline.test.ts
+++ b/src/cli/daemon/execenv/__tests__/timeline.test.ts
@@ -359,6 +359,7 @@ describe("timeline", () => {
agent_responses: [],
errmsg: null,
provider: "claude",
+ detailed_log: null,
...overrides,
};
}
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
index 69cefb49f..52704e8a9 100644
--- a/src/cli/daemon/execenv/context.test.ts
+++ b/src/cli/daemon/execenv/context.test.ts
@@ -15,6 +15,9 @@ function makeTask(overrides: Partial<Task> = {}): Task {
priority: 0,
type: "user_dm_message",
createdAt: "2024-01-01T00:00:00Z",
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
...overrides,
};
}
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index e22f73681..dd69b540a 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -215,6 +215,23 @@ Upload files for your owner to review in the app.
When your task includes attachments, their local paths are listed in the prompt JSON under "attachments".
Use your Read tool to open them. Images and PDFs are read visually.
---
+`;
+
+ content += `\n### Agent Management
+Recruit new colleague agents directly from the CLI. The server auto-generates a name and email handle.
+- Run '${cmdPrefix()} agent recruit --instructions "<SYSTEM_PROMPT>" --relationship "<DELEGATION_CRITERIA>"'
+ - '--instructions' — the new agent's system prompt (what it does, how it behaves)
+ - '--relationship' — delegation criteria shown in both agents' COLLEAGUES section
+ - '--name <name>' (optional) — preferred name; server generates one if omitted
+ - '--description <text>' (optional) — agent description
+ - '--model <model>' (optional) — model override
+ - '--instructions-file <path>' — alternative: read instructions from a file (mutually exclusive with --instructions)
+ - '--relationship-file <path>' — alternative: read relationship from a file (mutually exclusive with --relationship)
+ - '--json' — output full JSON response
+- Example: '${cmdPrefix()} agent recruit --instructions "You are a QA engineer..." --relationship "DELEGATE when: code is ready for review"'
+- Output: 'Recruited Felix ([email protected]) — ag_xK9mPq2z'
+- The new agent shares your runtime, is automatically linked as your colleague, and receives a welcome task.
+---
`;
content += `\n### Calendar
diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.ts
index 1ce693d28..1e72049e0 100644
--- a/src/cli/daemon/prompt.test.ts
+++ b/src/cli/daemon/prompt.test.ts
@@ -14,6 +14,9 @@ function makeTask(prompt: string, type = "user_dm_message"): Task {
status: "pending",
priority: 1,
createdAt: new Date().toISOString(),
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
};
}
diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.ts
index 5ec2c6a35..5b888cf95 100644
--- a/src/cli/daemon/session-runner.test.ts
+++ b/src/cli/daemon/session-runner.test.ts
@@ -28,7 +28,7 @@ const mockPrepare = vi.fn(() => ({
},
}));
vi.mock("./execenv/index.js", () => ({
- prepare: (...args: any[]) => mockPrepare(...args),
+ prepare: (...args: any[]) => (mockPrepare as any)(...args),
}));
const mockInitEntryAsync = vi.fn(async () => {});
@@ -58,19 +58,19 @@ const mockCreateTimelineEntry = vi.fn(
detailed_log: detailedLog ?? null,
}),
);
-const mockFindResumableSessionByContextKey = vi.fn(() => null);
+const mockFindResumableSessionByContextKey = vi.fn((): string | null => null);
vi.mock("./execenv/timeline.js", () => ({
- initEntryAsync: (...args: any[]) => mockInitEntryAsync(...args),
- updateEntry: (...args: any[]) => mockUpdateEntry(...args),
- createTimelineEntry: (...args: any[]) => mockCreateTimelineEntry(...args),
- findResumableSessionByContextKey: (...args: any[]) => mockFindResumableSessionByContextKey(...args),
+ initEntryAsync: (...args: any[]) => (mockInitEntryAsync as any)(...args),
+ updateEntry: (...args: any[]) => (mockUpdateEntry as any)(...args),
+ createTimelineEntry: (...args: any[]) => (mockCreateTimelineEntry as any)(...args),
+ findResumableSessionByContextKey: (...args: any[]) => (mockFindResumableSessionByContextKey as any)(...args),
}));
-const mockReadKillIntent = vi.fn(() => null);
+const mockReadKillIntent = vi.fn((): any => null);
const mockClearKillIntent = vi.fn();
vi.mock("./execenv/steering.js", () => ({
- readKillIntent: (...args: any[]) => mockReadKillIntent(...args),
- clearKillIntent: (...args: any[]) => mockClearKillIntent(...args),
+ readKillIntent: (...args: any[]) => (mockReadKillIntent as any)(...args),
+ clearKillIntent: (...args: any[]) => (mockClearKillIntent as any)(...args),
}));
vi.mock("./prompt.js", () => ({
@@ -95,10 +95,10 @@ const mockWriteFile = vi.fn(async () => undefined);
const mockRename = vi.fn(async () => undefined);
const mockRm = vi.fn(async () => undefined);
vi.mock("fs/promises", () => ({
- mkdir: (...args: any[]) => mockMkdir(...args),
- writeFile: (...args: any[]) => mockWriteFile(...args),
- rename: (...args: any[]) => mockRename(...args),
- rm: (...args: any[]) => mockRm(...args),
+ mkdir: (...args: any[]) => (mockMkdir as any)(...args),
+ writeFile: (...args: any[]) => (mockWriteFile as any)(...args),
+ rename: (...args: any[]) => (mockRename as any)(...args),
+ rm: (...args: any[]) => (mockRm as any)(...args),
readdir: vi.fn(async () => []),
readFile: vi.fn(async () => ""),
unlink: vi.fn(async () => undefined),
@@ -125,6 +125,9 @@ function makeInput(overrides?: Partial<SessionRunnerInput>): SessionRunnerInput
type: "user_dm_message",
contextKey: "c1",
createdAt: "2026-01-01T00:00:00Z",
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
},
provider: "claude",
cliPath: "claude",
@@ -462,6 +465,9 @@ describe("session-runner runSession", () => {
priority: 0,
type: "calendar_event",
createdAt: "2026-04-17T09:00:00Z",
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
},
}),
);
@@ -495,6 +501,9 @@ describe("session-runner runSession", () => {
priority: 0,
type: "calendar_event",
createdAt: "2026-04-17T09:00:00Z",
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
},
}),
);
@@ -517,7 +526,7 @@ describe("session-runner runSession", () => {
await runSession(makeInput());
// completeTask should be called — branchName is not in the body since it's undefined
- const callBody = mockClientInstance.completeTask.mock.calls[0][2];
+ const callBody = (mockClientInstance.completeTask.mock.calls as any)[0][2];
expect(callBody.output).toBe("Done");
expect(callBody.session_id).toBe("sess-1");
// branch_name key should not be present (undefined values aren't serialized)
@@ -555,6 +564,9 @@ describe("session-runner runSession", () => {
type: "user_dm_message",
contextKey: "c1",
createdAt: "2026-01-01T00:00:00Z",
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
context: { attachment_ids: ["art-1"] },
},
}));
@@ -605,6 +617,9 @@ describe("session-runner runSession", () => {
type: "user_dm_message",
contextKey: "c1",
createdAt: "2026-01-01T00:00:00Z",
+ traceId: null,
+ parentTaskId: null,
+ channel: null,
context: { attachment_ids: ["art-1"] },
},
}));
@@ -616,7 +631,7 @@ describe("session-runner runSession", () => {
process.emit("SIGTERM", "SIGTERM");
// Unblock the download so the promise can settle
- if (resolveDownload) resolveDownload();
+ if (resolveDownload) (resolveDownload as () => void)();
await new Promise((r) => setTimeout(r, 50));
@@ -667,7 +682,7 @@ describe("session-runner runSession", () => {
process.emit("SIGTERM", "SIGTERM");
// Unblock the message iterator so runSession can finish
- if (resolveMessage) resolveMessage();
+ if (resolveMessage) (resolveMessage as () => void)();
// Wait for cleanup to finish
await new Promise((r) => setTimeout(r, 50));
@@ -965,7 +980,7 @@ describe("session-runner runSession", () => {
await new Promise((r) => setTimeout(r, 50));
process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) resolveMessage();
+ if (resolveMessage) (resolveMessage as () => void)();
await new Promise((r) => setTimeout(r, 50));
expect(mockLog.info).toHaveBeenCalledWith(
@@ -1070,7 +1085,7 @@ describe("session-runner runSession", () => {
await new Promise((r) => setTimeout(r, 50));
process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) resolveMessage();
+ if (resolveMessage) (resolveMessage as () => void)();
await new Promise((r) => setTimeout(r, 50));
// Timeline should be updated to "superseded"
@@ -1118,7 +1133,7 @@ describe("session-runner runSession", () => {
await new Promise((r) => setTimeout(r, 50));
process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) resolveMessage();
+ if (resolveMessage) (resolveMessage as () => void)();
await new Promise((r) => setTimeout(r, 50));
// Timeline should be updated to "cancelled" (not "killed")
@@ -1159,7 +1174,7 @@ describe("session-runner runSession", () => {
await new Promise((r) => setTimeout(r, 50));
process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) resolveMessage();
+ if (resolveMessage) (resolveMessage as () => void)();
await new Promise((r) => setTimeout(r, 50));
// Timeline should be updated to "killed" (original behavior)
@@ -1224,8 +1239,8 @@ describe("writeMarkerFile", () => {
it("atomic write: uses .tmp then renames to .json", async () => {
await writeMarkerFile("/tmp/ws", marker);
- const writeCall = mockWriteFile.mock.calls[0][0];
- const renameArgs = mockRename.mock.calls[0];
+ const writeCall = (mockWriteFile.mock.calls as any)[0][0];
+ const renameArgs = (mockRename.mock.calls as any)[0];
expect(writeCall).toContain(".tmp");
expect(renameArgs[0]).toContain(".tmp");
expect(renameArgs[1]).toContain(".json");
@@ -1266,7 +1281,7 @@ describe("reportToServer", () => {
await vi.runAllTimersAsync();
await promise;
expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
+ const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
expect(written.taskId).toBe("t1");
expect(written.type).toBe("complete");
});
@@ -1328,7 +1343,7 @@ describe("session-runner marker integration", () => {
await promise;
expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
+ const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
expect(written.type).toBe("complete");
expect(written.taskId).toBe("t1");
expect(written.payload.output).toBe("Done!");
@@ -1350,7 +1365,7 @@ describe("session-runner marker integration", () => {
await promise;
expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
+ const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
expect(written.type).toBe("fail");
expect(written.taskId).toBe("t1");
expect(written.payload.error).toBe("something broke");
@@ -1377,11 +1392,11 @@ describe("session-runner marker integration", () => {
const sessionPromise = runSession(makeInput());
await vi.advanceTimersByTimeAsync(50);
process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) resolveMessage();
+ if (resolveMessage) (resolveMessage as () => void)();
await vi.runAllTimersAsync();
expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
+ const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
expect(written.type).toBe("fail");
expect(written.payload.error).toBe("cancelled by user");
@@ -1410,11 +1425,11 @@ describe("session-runner marker integration", () => {
const sessionPromise = runSession(makeInput());
await vi.advanceTimersByTimeAsync(50);
process.emit("SIGTERM", "SIGTERM");
- if (resolveMessage) resolveMessage();
+ if (resolveMessage) (resolveMessage as () => void)();
await vi.runAllTimersAsync();
expect(mockWriteFile).toHaveBeenCalled();
- const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
+ const written = JSON.parse((mockWriteFile.mock.calls as any)[0][1] as string);
expect(written.type).toBe("fail");
expect(written.payload.error).toBe("killed by signal");
diff --git a/src/cli/daemon/types.test.ts b/src/cli/daemon/types.test.ts
index 4e36ab780..9e618ee15 100644
--- a/src/cli/daemon/types.test.ts
+++ b/src/cli/daemon/types.test.ts
@@ -29,6 +29,8 @@ describe("fromApiTask", () => {
name: "Agent 1",
instructions: "be helpful",
runtime_config: { model: "custom-model" },
+ email_addresses: [],
+ colleagues: [],
},
};
@@ -43,6 +45,8 @@ describe("fromApiTask", () => {
name: "Agent 1",
instructions: "be helpful",
runtime_config: {},
+ email_addresses: [],
+ colleagues: [],
},
};
@@ -100,6 +104,8 @@ describe("fromApiTask", () => {
name: "Agent 1",
instructions: "be helpful",
runtime_config: {},
+ email_addresses: [],
+ colleagues: [],
},
};
const result = fromApiTask(task);
diff --git a/src/cli/lib/output.test.ts b/src/cli/lib/output.test.ts
index ffbc1d740..4fe6f46b5 100644
--- a/src/cli/lib/output.test.ts
+++ b/src/cli/lib/output.test.ts
@@ -26,7 +26,7 @@ describe("printTable", () => {
printTable(headers, rows);
- const calls = logSpy.mock.calls.map((c) => c[0]);
+ const calls = logSpy.mock.calls.map((c: any) => c[0]);
expect(calls[0]).toBe("ID NAME STATUS ");
expect(calls[1]).toBe("-- --------- --------");
diff --git a/src/cli/lib/update.test.ts b/src/cli/lib/update.test.ts
index 9bdfed14a..69e4e0b0f 100644
--- a/src/cli/lib/update.test.ts
+++ b/src/cli/lib/update.test.ts
@@ -26,7 +26,7 @@ describe("fetchLatestVersion", () => {
});
it("parses npm registry response correctly", async () => {
- (globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
+ (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: true,
json: async () => ({ version: "1.2.3" }),
});
@@ -35,7 +35,7 @@ describe("fetchLatestVersion", () => {
});
it("returns null on network error", async () => {
- (globalThis.fetch as ReturnType<typeof vi.fn>).mockRejectedValue(
+ (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockRejectedValue(
new Error("network error"),
);
const v = await fetchLatestVersion();
@@ -43,7 +43,7 @@ describe("fetchLatestVersion", () => {
});
it("returns null on non-ok response", async () => {
- (globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
+ (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: false,
});
const v = await fetchLatestVersion();
diff --git a/src/cli/src/index.ts b/src/cli/src/index.ts
index eb8d90c55..5110c63b0 100644
--- a/src/cli/src/index.ts
+++ b/src/cli/src/index.ts
@@ -7,6 +7,7 @@ import { configCommand } from "../commands/config.js";
import { emailCommand } from "../commands/email.js";
import { calendarCommand } from "../commands/calendar.js";
import { issueCommand } from "../commands/issue.js";
+import { agentCommand } from "../commands/agent.js";
import { versionCommand } from "../commands/version.js";
import { updateCommand } from "../commands/update.js";
import { syncCommand } from "../commands/sync.js";
@@ -25,6 +26,7 @@ program.addCommand(daemonCommand());
program.addCommand(emailCommand());
program.addCommand(calendarCommand());
program.addCommand(issueCommand());
+program.addCommand(agentCommand());
program.addCommand(configCommand());
program.addCommand(versionCommand());
program.addCommand(updateCommand());
diff --git a/src/shared/src/db/queries/task-message.ts b/src/shared/src/db/queries/task-message.ts
index d782896b6..d2b77bde6 100644
--- a/src/shared/src/db/queries/task-message.ts
+++ b/src/shared/src/db/queries/task-message.ts
@@ -48,13 +48,13 @@ export async function listTaskMessages(db: Database, taskId: string, workspaceId
})
.from(taskMessage)
.innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))
- .where(and(eq(taskMessage.taskId, taskId), eq(agentTaskQueue.workspaceId, workspaceId), notInArray(taskMessage.type, ["tool-result"])))
+ .where(and(eq(taskMessage.taskId, taskId), eq(agentTaskQueue.workspaceId, workspaceId), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))
.orderBy(asc(taskMessage.seq));
}
return db
.select()
.from(taskMessage)
- .where(and(eq(taskMessage.taskId, taskId), notInArray(taskMessage.type, ["tool-result"])))
+ .where(and(eq(taskMessage.taskId, taskId), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))
.orderBy(asc(taskMessage.seq));
}
@@ -66,7 +66,7 @@ export async function listTaskMessagesSince(
return db
.select()
.from(taskMessage)
- .where(and(eq(taskMessage.taskId, taskId), gt(taskMessage.seq, afterSeq), notInArray(taskMessage.type, ["tool-result"])))
+ .where(and(eq(taskMessage.taskId, taskId), gt(taskMessage.seq, afterSeq), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))
.orderBy(asc(taskMessage.seq));
}
@@ -74,11 +74,10 @@ export async function deleteTaskMessages(db: Database, taskId: string) {
await db.delete(taskMessage).where(eq(taskMessage.taskId, taskId));
}
-const HIDDEN_STEP_TYPES = ["status", "log", "tool-result", "text"];
const SQLITE_MAX_PARAMS = 999;
-const FIXED_PARAMS = 1 + HIDDEN_STEP_TYPES.length; // workspaceId + notInArray values
+const FIXED_PARAMS = 2; // workspaceId + type filter value ("text")
-export async function countTaskMessagesByTaskIds(
+export async function countTextMessagesByTaskIds(
db: Database,
taskIds: string[],
workspaceId: string
@@ -99,7 +98,7 @@ export async function countTaskMessagesByTaskIds(
and(
inArray(taskMessage.taskId, taskIds),
eq(agentTaskQueue.workspaceId, workspaceId),
- notInArray(taskMessage.type, HIDDEN_STEP_TYPES)
+ eq(taskMessage.type, "text")
)
)
.groupBy(taskMessage.taskId);
@@ -120,7 +119,7 @@ export async function countTaskMessagesByTaskIds(
and(
inArray(taskMessage.taskId, chunk),
eq(agentTaskQueue.workspaceId, workspaceId),
- notInArray(taskMessage.type, HIDDEN_STEP_TYPES)
+ eq(taskMessage.type, "text")
)
)
.groupBy(taskMessage.taskId);
@@ -129,3 +128,4 @@ export async function countTaskMessagesByTaskIds(
return results;
}
+
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index c5cdfe31e..bd3222dc5 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -163,6 +163,7 @@ export {
SkillEntrySchema,
SkillSyncRequestSchema,
CreateStudioRequestSchema,
+ RecruitAgentRequestSchema,
DaemonPushMessageSchema,
} from "./schemas";
@@ -210,6 +211,7 @@ export type {
SkillEntry,
SkillSyncRequest,
CreateStudioRequest,
+ RecruitAgentRequest,
DaemonPushMessageType,
} from "./schemas";
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index a83ed20ed..7020754cf 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -774,3 +774,16 @@ export const CreateStudioRequestSchema = z.object({
{ message: "at least one member must have the leader role" },
);
export type CreateStudioRequest = z.infer<typeof CreateStudioRequestSchema>;
+
+// ---------------------------------------------------------------------------
+// Agent recruit schema
+// ---------------------------------------------------------------------------
+
+export const RecruitAgentRequestSchema = z.object({
+ instructions: z.string().min(1, "instructions is required"),
+ relationship: z.string().min(1, "relationship is required"),
+ name: z.string().optional(),
+ description: z.string().optional().default(""),
+ model: z.string().max(100).optional(),
+});
+export type RecruitAgentRequest = z.infer<typeof RecruitAgentRequestSchema>;
diff --git a/src/shared/test/queries/task-message.test.ts b/src/shared/test/queries/task-message.test.ts
index f4a1001c7..94282fa8d 100644
--- a/src/shared/test/queries/task-message.test.ts
+++ b/src/shared/test/queries/task-message.test.ts
@@ -17,10 +17,6 @@ describe("task-message query module exports", () => {
it("exports deleteTaskMessages", () => {
expect(typeof taskMessageQueries.deleteTaskMessages).toBe("function");
});
-
- it("exports countTaskMessagesByTaskIds", () => {
- expect(typeof taskMessageQueries.countTaskMessagesByTaskIds).toBe("function");
- });
});
describe("listTaskMessages", () => {
@@ -35,14 +31,3 @@ describe("listTaskMessagesSince", () => {
});
});
-describe("countTaskMessagesByTaskIds", () => {
- it("accepts (db, taskIds, workspaceId)", () => {
- expect(taskMessageQueries.countTaskMessagesByTaskIds.length).toBe(3);
- });
-
- it("returns empty array for empty taskIds input", async () => {
- const mockDb = {} as Parameters<typeof taskMessageQueries.countTaskMessagesByTaskIds>[0];
- const result = await taskMessageQueries.countTaskMessagesByTaskIds(mockDb, [], "ws-1");
- expect(result).toEqual([]);
- });
-});
diff --git a/src/web/src/app/api/agents/recruit/route.ts b/src/web/src/app/api/agents/recruit/route.ts
new file mode 100644
index 000000000..44182d9c4
--- /dev/null
+++ b/src/web/src/app/api/agents/recruit/route.ts
@@ -0,0 +1,143 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries, RecruitAgentRequestSchema, isValidHandle, isOnline, TASK_TYPES } from "@alook/shared";
+import { nanoid } from "nanoid";
+import { uniqueNamesGenerator, names } from "unique-names-generator";
+import { getDb } from "@/lib/db";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
+import { agentToResponse, agentLinkToResponse } from "@/lib/api/responses";
+import { TaskService } from "@/lib/services/task";
+import { invalidate, cached, cacheKeys } from "@/lib/cache";
+import { randomConfig, serializeAvatarConfig } from "@/components/avatar";
+
+function generateUniqueHandleFromSet(
+ handleSet: Set<string>,
+ baseName: string,
+): string {
+ const base = baseName.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 30);
+ if (isValidHandle(base) && !handleSet.has(base)) {
+ handleSet.add(base);
+ return base;
+ }
+ for (let i = 0; i < 5; i++) {
+ const suffix = uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "lowerCase" });
+ const candidate = `${base}-${suffix}`.slice(0, 30);
+ if (!isValidHandle(candidate)) continue;
+ if (!handleSet.has(candidate)) {
+ handleSet.add(candidate);
+ return candidate;
+ }
+ }
+ const fallback = `${base}-${nanoid(6)}`;
+ handleSet.add(fallback);
+ return fallback;
+}
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const agentId = req.nextUrl.searchParams.get("agentId");
+ if (!agentId) {
+ return writeError("agentId query param is required", 400);
+ }
+
+ const [body, valErr] = await parseBody(req, RecruitAgentRequestSchema);
+ if (valErr) return valErr;
+
+ const callingAgent = await queries.agent.getAgent(db, agentId, ws.workspaceId);
+ if (!callingAgent) {
+ return writeError("calling agent not found in workspace", 404);
+ }
+
+ const runtime = callingAgent.runtimeId
+ ? await queries.runtime.getAgentRuntimeForWorkspace(db, callingAgent.runtimeId, ws.workspaceId)
+ : null;
+ if (!runtime) {
+ return writeError("calling agent has no runtime", 400);
+ }
+
+ const agentName = body.name?.trim() || uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" });
+
+ const allHandles = await cached(cacheKeys.allHandles(ws.workspaceId), 120, () =>
+ queries.agent.getAllHandlesForWorkspace(db, ws.workspaceId),
+ );
+ const handleSet = new Set(allHandles.map((h) => h.emailHandle).filter(Boolean) as string[]);
+ const handle = generateUniqueHandleFromSet(handleSet, agentName);
+
+ const sanitizedRc: Record<string, unknown> | null = body.model ? { model: body.model } : null;
+
+ const newAgent = await queries.agent.createAgent(db, {
+ workspaceId: ws.workspaceId,
+ name: agentName,
+ description: body.description || "",
+ instructions: body.instructions,
+ runtimeId: callingAgent.runtimeId,
+ runtimeMode: runtime.runtimeMode,
+ runtimeConfig: sanitizedRc,
+ visibility: "private",
+ maxConcurrentTasks: 6,
+ ownerId: ctx.userId,
+ emailHandle: handle,
+ avatarUrl: serializeAvatarConfig(randomConfig()),
+ });
+
+ const link = await queries.agentLink.create(db, {
+ workspaceId: ws.workspaceId,
+ sourceAgentId: agentId,
+ targetAgentId: newAgent.id,
+ instruction: body.relationship,
+ });
+
+ if (callingAgent.emailHandle) {
+ const callerEmail = `${callingAgent.emailHandle}@alook.ai`;
+ await queries.whitelist.addWhitelist(db, newAgent.id, ws.workspaceId, callerEmail);
+ }
+ if (ctx.email) {
+ await queries.whitelist.addWhitelist(db, newAgent.id, ws.workspaceId, ctx.email.toLowerCase());
+ }
+
+ await Promise.all([
+ invalidate(cacheKeys.allAgents(ws.workspaceId)),
+ invalidate(cacheKeys.allHandles(ws.workspaceId)),
+ invalidate(cacheKeys.allAgentAccess(ws.workspaceId)),
+ invalidate(cacheKeys.allColleagues(ws.workspaceId)),
+ invalidate(cacheKeys.agentLinks(ws.workspaceId)),
+ ]);
+
+ if (isOnline(runtime.machineLastSeenAt)) {
+ try {
+ const callerName = callingAgent.name;
+ const callerEmail = callingAgent.emailHandle ? `${callingAgent.emailHandle}@alook.ai` : "your recruiter";
+ const welcomePrompt = `You have just been recruited by your colleague ${callerName} (${callerEmail}). Your instructions are already set. Please send them a short email introducing yourself — your name, your email address, and confirming you're ready to work. Be warm and concise.`;
+
+ const conv = await queries.conversation.createConversation(db, {
+ workspaceId: ws.workspaceId,
+ agentId: newAgent.id,
+ userId: ctx.userId,
+ title: `Welcome from ${callerName}`.slice(0, 50),
+ type: TASK_TYPES.EMAIL_NOTIFICATION,
+ });
+ const taskService = new TaskService(db);
+ await taskService.enqueueTask(
+ newAgent.id,
+ conv.id,
+ ws.workspaceId,
+ welcomePrompt,
+ TASK_TYPES.EMAIL_NOTIFICATION,
+ );
+ } catch {
+ // Best-effort
+ }
+ }
+
+ return writeJSON({
+ agent: { ...agentToResponse(newAgent), email: `${handle}@alook.ai` },
+ link: agentLinkToResponse(link),
+ }, 201);
+});
diff --git a/src/web/src/app/api/conversations/[id]/init/route.ts b/src/web/src/app/api/conversations/[id]/init/route.ts
index aabfa91c9..08538ea67 100644
--- a/src/web/src/app/api/conversations/[id]/init/route.ts
+++ b/src/web/src/app/api/conversations/[id]/init/route.ts
@@ -90,7 +90,7 @@ export const GET = withAuth(async (req, ctx) => {
}
}
- const stepCounts: Record<string, number> = {};
+ const thinkingCounts: Record<string, number> = {};
if (messages.length > 0) {
const taskIds = [
...new Set(
@@ -101,13 +101,13 @@ export const GET = withAuth(async (req, ctx) => {
];
if (taskIds.length > 0) {
try {
- const rows = await queries.taskMessage.countTaskMessagesByTaskIds(
+ const rows = await queries.taskMessage.countTextMessagesByTaskIds(
db,
taskIds,
ws.workspaceId
);
for (const row of rows) {
- stepCounts[row.taskId] = row.count;
+ thinkingCounts[row.taskId] = row.count;
}
} catch {
// non-critical
@@ -124,7 +124,7 @@ export const GET = withAuth(async (req, ctx) => {
artifacts: artifacts.map(queries.artifact.artifactToResponse),
buffered_messages: resolvedBuffered.map(messageToResponse),
flagged_message_ids: flaggedMessageIds,
- step_counts: stepCounts,
+ thinking_counts: thinkingCounts,
active_task: resolvedActiveTask ? taskToResponse(resolvedActiveTask) : null,
task_messages: taskMessages,
cache_valid: cacheValid,
diff --git a/src/web/src/app/api/daemon/routes.test.ts b/src/web/src/app/api/daemon/routes.test.ts
index fc03fe36b..476f74702 100644
--- a/src/web/src/app/api/daemon/routes.test.ts
+++ b/src/web/src/app/api/daemon/routes.test.ts
@@ -593,10 +593,9 @@ describe("daemon route body validation", () => {
expect.objectContaining({
type: "task.messages",
taskId: "t1",
- messages: expect.arrayContaining([
+ messages: [
expect.objectContaining({ seq: 1, type: "text", content: "hello" }),
- expect.objectContaining({ seq: 2, type: "tool-use", tool: "Read" }),
- ]),
+ ],
})
);
});
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts
index f72e916f8..b682af081 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts
@@ -163,7 +163,7 @@ describe("POST /api/daemon/tasks/[taskId]/messages", () => {
expect(mockCreateTaskMessage).not.toHaveBeenCalled();
});
- it("excludes tool-result messages from WebSocket broadcast", async () => {
+ it("only broadcasts text and error messages via WebSocket", async () => {
mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1" });
mockCreateTaskMessage.mockResolvedValue({ id: "m1" });
@@ -188,10 +188,36 @@ describe("POST /api/daemon/tasks/[taskId]/messages", () => {
expect(mockCreateTaskMessage).toHaveBeenCalledTimes(3);
expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);
const broadcastPayload = mockBroadcastToUser.mock.calls[0][1];
- expect(broadcastPayload.messages).toHaveLength(2);
- expect(broadcastPayload.messages.every((m: any) => m.type !== "tool-result")).toBe(true);
+ expect(broadcastPayload.messages).toHaveLength(1);
+ expect(broadcastPayload.messages[0].type).toBe("text");
+ });
+
+ it("stores thinking messages but does not broadcast them", async () => {
+ mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1" });
+ mockCreateTaskMessage.mockResolvedValue({ id: "m1" });
+
+ const res = await POST(
+ new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: [
+ { seq: 1, type: "text", content: "hello" },
+ { seq: 2, type: "thinking", content: "hmm" },
+ ],
+ }),
+ }),
+ withParams("t1")
+ );
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.status).toBe("ok");
+ expect(mockCreateTaskMessage).toHaveBeenCalledTimes(2);
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);
+ const broadcastPayload = mockBroadcastToUser.mock.calls[0][1];
+ expect(broadcastPayload.messages).toHaveLength(1);
expect(broadcastPayload.messages[0].type).toBe("text");
- expect(broadcastPayload.messages[1].type).toBe("tool-use");
});
it("does not broadcast when all messages are tool-result", async () => {
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
index f4f04341e..ee95eea33 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
@@ -75,7 +75,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
});
const succeeded = filtered.filter((_, i) => results[i].status === "fulfilled");
- const broadcastable = succeeded.filter((m) => m.type !== "tool-result");
+ const broadcastable = succeeded.filter((m) => m.type !== "tool-result" && m.type !== "tool-use" && m.type !== "thinking");
if (broadcastable.length > 0) {
const wsMessages: TaskMessage[] = broadcastable.map((m) => ({
id: "",
diff --git a/src/web/src/app/api/tasks/[id]/messages/route.test.ts b/src/web/src/app/api/tasks/[id]/messages/route.test.ts
index 57ecf2449..fa860e249 100644
--- a/src/web/src/app/api/tasks/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/tasks/[id]/messages/route.test.ts
@@ -142,11 +142,10 @@ describe("GET /api/tasks/[id]/messages", () => {
expect(body.error).toBe("task not found");
});
- it("does not return tool-result messages (filtered at query level)", async () => {
+ it("only returns text and error messages (tool-result, tool-use, thinking filtered at query level)", async () => {
const task = { id: "t1", workspaceId: "w1" };
const messages = [
{ id: "m1", taskId: "t1", seq: 1, type: "text", content: "hello" },
- { id: "m2", taskId: "t1", seq: 3, type: "tool-use", content: "search" },
];
mockGetTask.mockResolvedValue(task);
mockListTaskMessages.mockResolvedValue(messages);
@@ -158,14 +157,14 @@ describe("GET /api/tasks/[id]/messages", () => {
const body = await res.json();
expect(res.status).toBe(200);
- expect(body).toHaveLength(2);
- expect(body.every((m: any) => m.type !== "tool-result")).toBe(true);
+ expect(body).toHaveLength(1);
+ expect(body[0].type).toBe("text");
});
- it("does not return tool-result messages with since parameter (filtered at query level)", async () => {
+ it("only returns text and error messages with since parameter (filtered at query level)", async () => {
const task = { id: "t1", workspaceId: "w1" };
const messages = [
- { id: "m4", taskId: "t1", seq: 7, type: "thinking", content: "hmm" },
+ { id: "m4", taskId: "t1", seq: 7, type: "text", content: "new update" },
];
mockGetTask.mockResolvedValue(task);
mockListTaskMessagesSince.mockResolvedValue(messages);
@@ -178,6 +177,6 @@ describe("GET /api/tasks/[id]/messages", () => {
expect(res.status).toBe(200);
expect(body).toHaveLength(1);
- expect(body.every((m: any) => m.type !== "tool-result")).toBe(true);
+ expect(body[0].type).toBe("text");
});
});
diff --git a/src/web/src/app/api/tasks/step-counts/route.test.ts b/src/web/src/app/api/tasks/step-counts/route.test.ts
deleted file mode 100644
index 9a2cdf079..000000000
--- a/src/web/src/app/api/tasks/step-counts/route.test.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
-
-const mockCountTaskMessagesByTaskIds = vi.fn();
-
-vi.mock("@/lib/middleware/helpers", () => ({
- writeJSON: (data: any, status = 200) =>
- new Response(JSON.stringify(data), {
- status,
- headers: { "content-type": "application/json" },
- }),
- writeError: (message: string, status: number) =>
- new Response(JSON.stringify({ error: message }), {
- status,
- headers: { "content-type": "application/json" },
- }),
-}));
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
-}));
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
-
-vi.mock("@alook/shared", () => ({
- createDb: vi.fn(() => ({})),
- queries: {
- taskMessage: {
- countTaskMessagesByTaskIds: (...args: any[]) =>
- mockCountTaskMessagesByTaskIds(...args),
- },
- },
-}));
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any) => {
- return handler(req, { userId: "u1", email: "[email protected]" });
- }),
-}));
-vi.mock("@/lib/middleware/workspace", () => ({
- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
-}));
-
-import { POST } from "./route";
-
-function makeReq(body: unknown, qs = "workspace_id=w1") {
- return new NextRequest(`http://localhost/api/tasks/step-counts?${qs}`, {
- method: "POST",
- body: JSON.stringify(body),
- headers: { "content-type": "application/json" },
- });
-}
-
-describe("POST /api/tasks/step-counts", () => {
- beforeEach(() => vi.clearAllMocks());
-
- it("returns counts keyed by task ID", async () => {
- mockCountTaskMessagesByTaskIds.mockResolvedValue([
- { taskId: "t1", count: 5 },
- { taskId: "t2", count: 12 },
- ]);
-
- const res = await POST(makeReq({ task_ids: ["t1", "t2"] }));
- const body = await res.json();
-
- expect(res.status).toBe(200);
- expect(body).toEqual({ t1: 5, t2: 12 });
- expect(mockCountTaskMessagesByTaskIds).toHaveBeenCalledWith(
- {},
- ["t1", "t2"],
- "w1"
- );
- });
-
- it("returns empty object when no task_ids provided", async () => {
- const res = await POST(makeReq({ task_ids: [] }));
- const body = await res.json();
-
- expect(res.status).toBe(200);
- expect(body).toEqual({});
- expect(mockCountTaskMessagesByTaskIds).not.toHaveBeenCalled();
- });
-
- it("returns 400 when task_ids is missing", async () => {
- const res = await POST(makeReq({}));
- const body = await res.json();
-
- expect(res.status).toBe(400);
- expect(body.error).toBe("task_ids is required");
- });
-
- it("returns 400 when task_ids is not an array", async () => {
- const res = await POST(makeReq({ task_ids: "not-array" }));
- const body = await res.json();
-
- expect(res.status).toBe(400);
- expect(body.error).toBe("task_ids must be an array of strings");
- });
-
- it("returns 400 when task_ids contains non-strings", async () => {
- const res = await POST(makeReq({ task_ids: [1, 2] }));
- const body = await res.json();
-
- expect(res.status).toBe(400);
- expect(body.error).toBe("task_ids must be an array of strings");
- });
-
- it("rejects arrays exceeding 100 entries", async () => {
- const bigArray = Array.from({ length: 101 }, (_, i) => `t${i}`);
- const res = await POST(makeReq({ task_ids: bigArray }));
- const body = await res.json();
-
- expect(res.status).toBe(400);
- expect(body.error).toBe("task_ids exceeds maximum of 100 entries");
- });
-
- it("returns 400 for invalid JSON body", async () => {
- const req = new NextRequest(
- "http://localhost/api/tasks/step-counts?workspace_id=w1",
- {
- method: "POST",
- body: "not json",
- headers: { "content-type": "application/json" },
- }
- );
- const res = await POST(req);
- const body = await res.json();
-
- expect(res.status).toBe(400);
- expect(body.error).toBe("invalid request body");
- });
-});
diff --git a/src/web/src/app/api/tasks/step-counts/route.ts b/src/web/src/app/api/tasks/step-counts/route.ts
deleted file mode 100644
index cd09970ec..000000000
--- a/src/web/src/app/api/tasks/step-counts/route.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { getCloudflareContext } from "@opennextjs/cloudflare";
-import { queries } from "@alook/shared";
-import { getDb } from "@/lib/db";
-import { withAuth } from "@/lib/middleware/auth";
-import { withWorkspaceMember } from "@/lib/middleware/workspace";
-import { writeJSON, writeError } from "@/lib/middleware/helpers";
-
-export const POST = withAuth(async (req, ctx) => {
- const ws = await withWorkspaceMember(req, ctx);
- if (ws instanceof Response) return ws;
-
- let body: unknown;
- try {
- body = await req.json();
- } catch {
- return writeError("invalid request body", 400);
- }
-
- if (!body || typeof body !== "object" || !("task_ids" in body)) {
- return writeError("task_ids is required", 400);
- }
-
- const { task_ids } = body as { task_ids: unknown };
- if (!Array.isArray(task_ids) || !task_ids.every((id) => typeof id === "string")) {
- return writeError("task_ids must be an array of strings", 400);
- }
-
- if (task_ids.length > 100) {
- return writeError("task_ids exceeds maximum of 100 entries", 400);
- }
-
- if (task_ids.length === 0) {
- return writeJSON({});
- }
-
- const { env } = getCloudflareContext();
- const db = getDb((env as Env).DB);
-
- const rows = await queries.taskMessage.countTaskMessagesByTaskIds(
- db,
- task_ids,
- ws.workspaceId
- );
-
- const result: Record<string, number> = {};
- for (const row of rows) {
- result[row.taskId] = row.count;
- }
-
- return writeJSON(result);
-});
diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsx
index 2d4990f18..a8589077e 100644
--- a/src/web/src/app/layout.tsx
+++ b/src/web/src/app/layout.tsx
@@ -10,6 +10,7 @@ import { GoogleTagManager } from "@next/third-parties/google";
import { ThemeProvider } from "@/components/theme-provider";
import { ToasterProvider } from "@/components/toaster-provider";
import { TooltipProvider } from "@/components/ui/tooltip";
+import { MockNetworkBanner } from "@/components/mock-network-banner";
import "./globals.css";
const dmSans = DM_Sans({
@@ -124,7 +125,10 @@ export default function RootLayout({
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
</head>
<GoogleTagManager gtmId="GTM-56VHCCQZ" />
- <body className="min-h-full flex flex-col">
+ <body
+ className="min-h-full flex flex-col"
+ >
+ <MockNetworkBanner />
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
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 1d72c241f..81f65088a 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -366,7 +366,7 @@ export function AgentChatView({
const [previousConversations, setPreviousConversations] = useState<PreviousConversation[]>([]);
const [hasMoreConversations, setHasMoreConversations] = useState(false);
const [napMarkers, setNapMarkers] = useState<NapMarker[]>([]);
- const [stepCounts, setStepCounts] = useState<Record<string, number>>({});
+ const [thinkingCounts, setThinkingCounts] = useState<Record<string, number>>({});
const [renderNow] = useState(() => Date.now());
const [pendingFilesByMessage, setPendingFilesByMessage] = useState<Map<string, File[]>>(() => new Map());
@@ -550,7 +550,7 @@ export function AgentChatView({
setBufferedMessages([]);
setPendingFilesByMessage(new Map());
setNapMarkers([]);
- setStepCounts({});
+ setThinkingCounts({});
setPreviousConversations([]);
setHasMoreConversations(false);
oldestConversationCursorRef.current = null;
@@ -629,7 +629,7 @@ export function AgentChatView({
} else if (cacheMeta) {
setHasMore(cacheMeta.hasMore);
}
- setStepCounts(data.step_counts);
+ setThinkingCounts(data.thinking_counts);
setArtifacts(data.artifacts);
setBufferedMessages(data.buffered_messages);
setFlaggedIds(new Set(data.flagged_message_ids));
@@ -1872,7 +1872,7 @@ export function AgentChatView({
taskMessages={taskMessages}
connectionLost={connectionLost}
isLastMessage={messages.length > 0 && messages[messages.length - 1].id === msg.id}
- stepCount={msg.task_id ? (stepCounts[msg.task_id] ?? 0) : 0}
+ thinkingCount={msg.task_id ? (thinkingCounts[msg.task_id] ?? 0) : 0}
targetConvId={targetConvId}
workspaceId={workspaceId}
conversationType={conversation?.type}
diff --git a/src/web/src/components/agent-chat/historical-task-steps.tsx b/src/web/src/components/agent-chat/historical-task-thinking.tsx
similarity index 86%
rename from src/web/src/components/agent-chat/historical-task-steps.tsx
rename to src/web/src/components/agent-chat/historical-task-thinking.tsx
index 0556dff45..e8a0388a5 100644
--- a/src/web/src/components/agent-chat/historical-task-steps.tsx
+++ b/src/web/src/components/agent-chat/historical-task-thinking.tsx
@@ -23,13 +23,13 @@ const COMPLETED_STUB: TaskApi = {
type: "",
};
-export function HistoricalTaskSteps({
+export function HistoricalTaskThinking({
taskId,
- stepCount,
+ thinkingCount,
workspaceId,
}: {
taskId: string;
- stepCount: number;
+ thinkingCount: number;
workspaceId: string;
}) {
const [messages, setMessages] = useState<TaskMessage[]>([]);
@@ -54,9 +54,9 @@ export function HistoricalTaskSteps({
<TaskStream
task={COMPLETED_STUB}
messages={messages}
- stepCountHint={stepCount}
- onExpandSteps={fetchMessages}
- stepsLoading={loading}
+ thinkingCountHint={thinkingCount}
+ onExpandThinking={fetchMessages}
+ thinkingLoading={loading}
/>
);
}
diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsx
index 844763076..6d07afdf4 100644
--- a/src/web/src/components/agent-chat/message-list.tsx
+++ b/src/web/src/components/agent-chat/message-list.tsx
@@ -7,7 +7,7 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip
import { Streamdown } from "streamdown";
import { highlightMentions } from "@/lib/highlight-mentions";
import { TaskStream } from "@/components/task-stream";
-import { HistoricalTaskSteps } from "@/components/agent-chat/historical-task-steps";
+import { HistoricalTaskThinking } from "@/components/agent-chat/historical-task-thinking";
import { FileText, Calendar, CircleDot, Mail, Flag, Copy, Check } from "lucide-react";
import { getEventIconType } from "@/components/agent-chat/agent-chat-view";
@@ -24,7 +24,7 @@ export interface MessageItemProps {
taskMessages: TaskMessage[];
connectionLost: boolean;
isLastMessage: boolean;
- stepCount: number;
+ thinkingCount: number;
targetConvId: string | null;
workspaceId: string;
conversationType?: string | null;
@@ -113,7 +113,7 @@ export const MessageItem = memo(function MessageItem({
taskMessages,
connectionLost,
isLastMessage,
- stepCount,
+ thinkingCount,
targetConvId,
workspaceId,
conversationType,
@@ -136,15 +136,6 @@ export const MessageItem = memo(function MessageItem({
msg.conversation_id === activeTask.conversation_id &&
taskMessages.length > 0;
- const historicalStepCount =
- !hasTaskStream &&
- targetConvId &&
- msg.role === "assistant" &&
- msg.task_id &&
- stepCount > 0
- ? stepCount
- : 0;
-
const isTaskDone = hasTaskStream && activeTask && ["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
const actionButtons = msg.role === "assistant" ? (
@@ -221,13 +212,6 @@ export const MessageItem = memo(function MessageItem({
{isTaskDone && actionButtons}
</div>
)}
- {historicalStepCount > 0 && msg.task_id && (
- <HistoricalTaskSteps
- taskId={msg.task_id}
- stepCount={historicalStepCount}
- workspaceId={workspaceId}
- />
- )}
{msg.role === "user" ? (() => {
const awaitingRun = isLastMessage && !!activeTask && activeTask.status !== "running" && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
const slashMatch = msg.content.match(/^\/(\S+)\s?([\s\S]*)$/);
@@ -284,6 +268,9 @@ export const MessageItem = memo(function MessageItem({
"group/msg flex flex-col justify-start min-w-0 overflow-hidden",
isFlagged && "bg-muted/30 rounded-lg px-2 -mx-2"
)} data-message-id={msg.id} data-quote-source {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
+ {targetConvId && msg.role === "assistant" && msg.task_id && thinkingCount > 1 && (
+ <HistoricalTaskThinking taskId={msg.task_id} thinkingCount={thinkingCount - 1} workspaceId={workspaceId} />
+ )}
<div className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground">
<Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={mentionComponents}>{highlightMentions(msg.content, agents)}</Streamdown>
</div>
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet-activity.ts b/src/web/src/components/home-pet/cloud-code-monster-pet-activity.ts
index 093183130..143d2ebe2 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet-activity.ts
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet-activity.ts
@@ -12,6 +12,7 @@ import {
CLOUD_CODE_MONSTER_FAINT_MIN_EVENTS,
CLOUD_CODE_MONSTER_FAINT_MIN_SPAN_MS,
CLOUD_CODE_MONSTER_FAINT_REVERSAL_MIN_SPEED,
+ CLOUD_CODE_MONSTER_POSITION_STORAGE_KEY,
CLOUD_CODE_MONSTER_SIZE,
CLOUD_CODE_MONSTER_STORAGE_KEY,
CLOUD_CODE_MONSTER_VIOLENT_DRAG_MAX_ELAPSED_MS,
@@ -428,6 +429,34 @@ export function writeStoredActivity(activityState: StoredCloudCodeMonsterActivit
} catch {}
}
+export function readStoredPosition(): PetPoint | null {
+ try {
+ const raw = localStorage.getItem(CLOUD_CODE_MONSTER_POSITION_STORAGE_KEY);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw) as { x?: unknown; y?: unknown };
+ if (
+ typeof parsed.x === "number" &&
+ typeof parsed.y === "number" &&
+ Number.isFinite(parsed.x) &&
+ Number.isFinite(parsed.y)
+ ) {
+ return { x: parsed.x, y: parsed.y };
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+export function writeStoredPosition(position: PetPoint) {
+ try {
+ localStorage.setItem(
+ CLOUD_CODE_MONSTER_POSITION_STORAGE_KEY,
+ JSON.stringify({ x: position.x, y: position.y })
+ );
+ } catch {}
+}
+
export function createWalkToTargetVelocity(
from: PetPoint,
to: PetPoint,
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet-constants.ts b/src/web/src/components/home-pet/cloud-code-monster-pet-constants.ts
index c582d0c7a..ffbf5961d 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet-constants.ts
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet-constants.ts
@@ -1,5 +1,7 @@
export const CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS = 3 * 60 * 1000;
export const CLOUD_CODE_MONSTER_STORAGE_KEY = "alook-cloud-code-monster-pet-activity-v1";
+export const CLOUD_CODE_MONSTER_POSITION_STORAGE_KEY =
+ "alook-cloud-code-monster-pet-position-v1";
export const CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY =
"alook-cloud-code-monster-pet-preset-v1";
export const CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT =
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet-drag.ts b/src/web/src/components/home-pet/cloud-code-monster-pet-drag.ts
index 028ee2c0c..0ab65a9b1 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet-drag.ts
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet-drag.ts
@@ -19,6 +19,7 @@ import {
isMonsterFaintShakeEvent,
isViolentMonsterDrag,
shouldFaintFromMonsterShake,
+ writeStoredPosition,
} from "./cloud-code-monster-pet-activity";
import {
CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS,
@@ -293,6 +294,10 @@ export function usePetDrag({
lastPointerRef.current = null;
lastDragDeltaRef.current = null;
+ if (position) {
+ writeStoredPosition(position);
+ }
+
setPetTimer("walkSettle", () => {
setWalkIntensity(1);
}, 180);
@@ -303,6 +308,7 @@ export function usePetDrag({
},
[
isDragging,
+ position,
setIsDragging,
setPetTimer,
setWalkIntensity,
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
index 3ae26dde4..0033c66ee 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
@@ -23,6 +23,7 @@ import {
getBounds,
getMonsterFootstepIntervalMs,
readStoredActivity,
+ readStoredPosition,
reflectCloudCodeMonsterWalk,
resolveCloudCodeMonsterPeekPosition,
resolveCloudCodeMonsterPreviewComebackState,
@@ -289,7 +290,7 @@ export function CloudCodeMonsterPet({
currentPosition
? clampPetPosition(currentPosition, bounds, CLOUD_CODE_MONSTER_SIZE)
: clampPetPosition(
- initialPosition ?? {
+ initialPosition ?? readStoredPosition() ?? {
x: bounds.width - CLOUD_CODE_MONSTER_SIZE.width - 112,
y: Math.min(
bounds.height * 0.48,
diff --git a/src/web/src/components/mock-network-banner.tsx b/src/web/src/components/mock-network-banner.tsx
new file mode 100644
index 000000000..440dfbc88
--- /dev/null
+++ b/src/web/src/components/mock-network-banner.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { useState, useRef, useEffect, useCallback } from "react";
+
+export function MockNetworkBanner() {
+ const enabled =
+ process.env.NODE_ENV === "development" &&
+ process.env.NEXT_PUBLIC_MOCK_NETWORK === "true";
+ const delayMs = process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS || "300";
+
+ const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
+ const [mounted, setMounted] = useState(false);
+
+ const dragging = useRef(false);
+ const offset = useRef({ x: 0, y: 0 });
+ const pillRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ setPosition({ x: window.innerWidth - 220, y: window.innerHeight - 56 });
+ setMounted(true);
+ }, []);
+
+ const onPointerDown = useCallback((e: React.PointerEvent) => {
+ dragging.current = true;
+ offset.current = {
+ x: e.clientX - (position?.x ?? 0),
+ y: e.clientY - (position?.y ?? 0),
+ };
+ pillRef.current?.setPointerCapture(e.pointerId);
+ }, [position]);
+
+ const onPointerMove = useCallback((e: React.PointerEvent) => {
+ if (!dragging.current) return;
+ const newX = Math.max(0, Math.min(e.clientX - offset.current.x, window.innerWidth - 40));
+ const newY = Math.max(0, Math.min(e.clientY - offset.current.y, window.innerHeight - 40));
+ setPosition({ x: newX, y: newY });
+ }, []);
+
+ const onPointerUp = useCallback(() => {
+ dragging.current = false;
+ }, []);
+
+ if (!enabled || !mounted) return null;
+
+ return (
+ <div
+ ref={pillRef}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ style={{
+ position: "fixed",
+ left: position?.x ?? 0,
+ top: position?.y ?? 0,
+ zIndex: 9999,
+ height: "32px",
+ borderRadius: "16px",
+ backgroundColor: "#ef4444",
+ color: "#ffffff",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ padding: "0 12px",
+ fontSize: "12px",
+ fontWeight: 600,
+ cursor: "grab",
+ userSelect: "none",
+ touchAction: "none",
+ boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
+ whiteSpace: "nowrap",
+ }}
+ >
+ Mock Network — {delayMs}ms delay
+ </div>
+ );
+}
diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsx
index c37385203..c88880c45 100644
--- a/src/web/src/components/task-stream.tsx
+++ b/src/web/src/components/task-stream.tsx
@@ -6,55 +6,28 @@ import { cn } from "@/lib/utils";
import type { TaskMessage } from "@alook/shared";
import type { TaskApi as Task } from "@alook/shared";
import {
- Check,
ChevronRight,
- Brain,
AlertCircle,
RotateCw,
Loader2,
} from "lucide-react";
import { Streamdown } from "streamdown";
-/* ── Helpers ── */
-
-function formatToolName(tool: string): string {
- return tool
- .replace(/_/g, " ")
- .replace(/\b\w/g, (c) => c.toUpperCase());
-}
-
/* ── Grouped stream items ── */
-interface ToolCallGroup {
- kind: "tool-call";
- id: string;
- tool: string;
- input?: Record<string, unknown>;
-}
-
interface TextItem {
kind: "text";
id: string;
content: string;
}
-interface ThinkingItem {
- kind: "thinking";
+interface ErrorItem {
+ kind: "error";
id: string;
content: string;
}
-interface StatusItem {
- kind: "status";
- id: string;
- content: string;
- type: string;
-}
-
-type StreamItem = ToolCallGroup | TextItem | ThinkingItem | StatusItem;
-
-/** Types that are agent-internal lifecycle events, never user-facing. */
-const HIDDEN_TYPES = new Set(["status", "log"]);
+type StreamItem = TextItem | ErrorItem;
function itemKey(msg: TaskMessage): string {
return msg.id || `seq-${msg.seq}`;
@@ -62,152 +35,19 @@ function itemKey(msg: TaskMessage): string {
function groupMessages(messages: TaskMessage[]): StreamItem[] {
const items: StreamItem[] = [];
- const toolCalls = new Map<string, ToolCallGroup>();
for (const msg of messages) {
- if (HIDDEN_TYPES.has(msg.type)) continue;
const key = itemKey(msg);
- switch (msg.type) {
- case "tool-use": {
- const callId = msg.call_id;
- const group: ToolCallGroup = {
- kind: "tool-call",
- id: key,
- tool: msg.tool,
- input: msg.input,
- };
- if (callId) toolCalls.set(callId, group);
- items.push(group);
- break;
- }
- case "tool-result":
- break;
- case "text":
- items.push({ kind: "text", id: key, content: msg.content });
- break;
- case "thinking":
- items.push({ kind: "thinking", id: key, content: msg.content });
- break;
- case "error":
- items.push({
- kind: "status",
- id: key,
- content: msg.content || msg.output,
- type: "error",
- });
- break;
- default:
- break;
+ if (msg.type === "text") {
+ items.push({ kind: "text", id: key, content: msg.content });
+ } else if (msg.type === "error") {
+ items.push({ kind: "error", id: key, content: msg.content || msg.output });
}
}
return items;
}
-/* ── ToolCallBlock ── */
-
-function ToolCallBlock({ item, isRunning, isLast }: { item: ToolCallGroup; isRunning: boolean; isLast: boolean }) {
- const inputStr = useMemo(() => {
- if (!item.input) return null;
- try {
- return JSON.stringify(item.input, null, 2);
- } catch {
- return String(item.input);
- }
- }, [item.input]);
-
- if (!inputStr) {
- return (
- <div
- className={cn(
- "flex items-center gap-2 py-1 px-2 -mx-2 rounded-md",
- "text-sm text-muted-foreground"
- )}
- >
- <span className="font-medium text-foreground/80">
- {formatToolName(item.tool)}
- </span>
- {isRunning && isLast && (
- <span className="ml-auto size-1.5 rounded-full bg-primary/60 animate-pulse" />
- )}
- {isRunning && !isLast && (
- <Check className="ml-auto size-3 text-emerald-500" />
- )}
- </div>
- );
- }
-
- return (
- <details className="group/tool">
- <summary
- className={cn(
- "flex items-center gap-2 py-1 px-2 -mx-2 rounded-md cursor-pointer select-none",
- "text-sm text-muted-foreground transition-colors duration-150",
- "hover:bg-muted/60 hover:text-foreground",
- "[&::-webkit-details-marker]:hidden [&::marker]:hidden"
- )}
- >
- <ChevronRight className="size-3 shrink-0 text-muted-foreground/60 transition-transform duration-150 group-open/tool:rotate-90" />
- <span className="font-medium text-foreground/80">
- {formatToolName(item.tool)}
- </span>
- {isRunning && isLast && (
- <span className="ml-auto size-1.5 rounded-full bg-primary/60 animate-pulse" />
- )}
- {isRunning && !isLast && (
- <Check className="ml-auto size-3 text-emerald-500" />
- )}
- </summary>
-
- <div className="mt-1 mb-2 ml-5">
- <pre className="task-stream-pre overflow-x-auto rounded-md bg-muted/40 p-2.5 font-mono text-xs leading-relaxed text-muted-foreground max-h-48 max-w-full min-w-0 overflow-y-auto">
- {inputStr}
- </pre>
- </div>
- </details>
- );
-}
-
-/* ── ThinkingBlock ── */
-
-function ThinkingBlock({ item }: { item: ThinkingItem }) {
- if (!item.content) {
- return (
- <div
- className={cn(
- "flex items-center gap-2 py-1 px-2 -mx-2 rounded-md",
- "text-sm text-muted-foreground/60 italic"
- )}
- >
- <Brain className="size-3 shrink-0" />
- <span>Thinking...</span>
- </div>
- );
- }
-
- return (
- <details className="group/think">
- <summary
- className={cn(
- "flex items-center gap-2 py-1 px-2 -mx-2 rounded-md cursor-pointer select-none",
- "text-sm text-muted-foreground/60 italic transition-colors duration-150",
- "hover:bg-muted/60 hover:text-muted-foreground",
- "[&::-webkit-details-marker]:hidden [&::marker]:hidden"
- )}
- >
- <ChevronRight className="size-3 shrink-0 text-muted-foreground/40 transition-transform duration-150 group-open/think:rotate-90" />
- <Brain className="size-3 shrink-0" />
- <span>Thinking...</span>
- </summary>
- <div className="mt-1 mb-2 ml-5">
- <p className="text-sm italic text-muted-foreground/60 whitespace-pre-wrap">
- {item.content}
- </p>
- </div>
- </details>
- );
-}
-
/* ── AnimatedNumber (slot-style slide) ── */
function AnimatedNumber({ value }: { value: number }) {
@@ -284,39 +124,29 @@ export function TaskStream({
messages,
connectionLost,
onRetry,
- stepCountHint,
- onExpandSteps,
- stepsLoading,
+ thinkingCountHint,
+ onExpandThinking,
+ thinkingLoading,
}: {
task: Task;
messages: TaskMessage[];
connectionLost?: boolean;
onRetry?: () => void;
- stepCountHint?: number;
- onExpandSteps?: () => void;
- stepsLoading?: boolean;
+ thinkingCountHint?: number;
+ onExpandThinking?: () => void;
+ thinkingLoading?: boolean;
}) {
const [retrying, setRetrying] = useState(false);
const allItems = useMemo(() => groupMessages(messages), [messages]);
const isRunning = task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled" && task.status !== "superseded";
- const toolItems = allItems.filter((i) => i.kind !== "text");
const textItems = allItems.filter((i): i is TextItem => i.kind === "text");
-
+ const errorItems = allItems.filter((i): i is ErrorItem => i.kind === "error");
const finalTextItem = textItems.length > 0 ? textItems[textItems.length - 1] : null;
- const toolScrollRef = useRef<HTMLDivElement>(null);
const textScrollRef = useRef<HTMLDivElement>(null);
const expandedRef = useRef(false);
- // Auto-scroll tool area to bottom while running
- useEffect(() => {
- if (isRunning && toolScrollRef.current) {
- toolScrollRef.current.scrollTop = toolScrollRef.current.scrollHeight;
- }
- }, [toolItems.length, isRunning]);
-
- // Auto-scroll text area to bottom while running
useEffect(() => {
if (isRunning && textScrollRef.current) {
textScrollRef.current.scrollTop = textScrollRef.current.scrollHeight;
@@ -325,49 +155,51 @@ export function TaskStream({
const intermediateTextItems = isRunning ? textItems : textItems.slice(0, -1);
const hasFinalText = !isRunning && finalTextItem !== null;
- const displayStepCount = toolItems.length > 0 ? toolItems.length : stepCountHint ?? 0;
- const showStepsSection = toolItems.length > 0 || (stepCountHint && stepCountHint > 0);
+ const showThinkingSection = intermediateTextItems.length > 0 || (thinkingCountHint && thinkingCountHint > 0);
+ const displayThinkingCount = intermediateTextItems.length > 0 ? intermediateTextItems.length : thinkingCountHint ?? 0;
- const handleStepsToggle = (e: React.SyntheticEvent<HTMLDetailsElement>) => {
- if ((e.currentTarget as HTMLDetailsElement).open && !expandedRef.current && onExpandSteps) {
+ const handleThinkingToggle = (e: React.SyntheticEvent<HTMLDetailsElement>) => {
+ if ((e.currentTarget as HTMLDetailsElement).open && !expandedRef.current && onExpandThinking) {
expandedRef.current = true;
- onExpandSteps();
+ onExpandThinking();
}
};
return (
<div className="space-y-3 min-w-0 max-w-full">
- {/* Status badge */}
- <div className="flex items-center gap-2">
- {task.status === "running" ? (
- <Badge variant="secondary" className="gap-1.5 relative overflow-hidden">
- <span className="size-1.5 rounded-full bg-primary animate-pulse" />
- Working
- <div
- className="pointer-events-none absolute inset-0 -translate-x-full animate-[shimmer_2s_ease-in-out_infinite]"
- style={{
- background: "linear-gradient(90deg, transparent 0%, var(--shimmer) 40%, var(--shimmer-peak) 50%, var(--shimmer) 60%, transparent 100%)",
- }}
- />
- </Badge>
- ) : isRunning ? (
- <Badge variant="secondary" className="relative overflow-hidden">
- {task.status}
- <div
- className="pointer-events-none absolute inset-0 -translate-x-full animate-[shimmer_2s_ease-in-out_infinite]"
- style={{
- background: "linear-gradient(90deg, transparent 0%, var(--shimmer) 40%, var(--shimmer-peak) 50%, var(--shimmer) 60%, transparent 100%)",
- }}
- />
- </Badge>
- ) : (
- <Badge variant="secondary">{task.status}</Badge>
- )}
- </div>
+ {/* Status badge — only for live tasks, not historical */}
+ {!onExpandThinking && (
+ <div className="flex items-center gap-2">
+ {task.status === "running" ? (
+ <Badge variant="secondary" className="gap-1.5 relative overflow-hidden">
+ <span className="size-1.5 rounded-full bg-primary animate-pulse" />
+ Working
+ <div
+ className="pointer-events-none absolute inset-0 -translate-x-full animate-[shimmer_2s_ease-in-out_infinite]"
+ style={{
+ background: "linear-gradient(90deg, transparent 0%, var(--shimmer) 40%, var(--shimmer-peak) 50%, var(--shimmer) 60%, transparent 100%)",
+ }}
+ />
+ </Badge>
+ ) : isRunning ? (
+ <Badge variant="secondary" className="relative overflow-hidden">
+ {task.status}
+ <div
+ className="pointer-events-none absolute inset-0 -translate-x-full animate-[shimmer_2s_ease-in-out_infinite]"
+ style={{
+ background: "linear-gradient(90deg, transparent 0%, var(--shimmer) 40%, var(--shimmer-peak) 50%, var(--shimmer) 60%, transparent 100%)",
+ }}
+ />
+ </Badge>
+ ) : (
+ <Badge variant="secondary">{task.status}</Badge>
+ )}
+ </div>
+ )}
- {/* Tool stream zone — foldable, height-limited, scrollable */}
- {showStepsSection && (
- <details className="group/stream pl-1" onToggle={handleStepsToggle}>
+ {/* Thinking section — intermediate text, open while running or when no final text */}
+ {showThinkingSection && (
+ <details className="group/midtext pl-1" open={!hasFinalText && !onExpandThinking || undefined} onToggle={handleThinkingToggle}>
<summary
className={cn(
"flex items-center gap-1.5 py-1 cursor-pointer select-none",
@@ -376,62 +208,18 @@ export function TaskStream({
"[&::-webkit-details-marker]:hidden [&::marker]:hidden"
)}
>
- <ChevronRight className={cn("size-3 shrink-0 text-muted-foreground/60 transition-transform duration-150 group-open/stream:rotate-90", isRunning && "animate-pulse text-primary")} />
- <span><AnimatedNumber value={displayStepCount} /> {displayStepCount === 1 ? "step" : "steps"}</span>
+ <ChevronRight className="size-3 shrink-0 text-muted-foreground/60 transition-transform duration-150 group-open/midtext:rotate-90" />
+ <span><AnimatedNumber value={displayThinkingCount} /> thinking</span>
</summary>
- <div
- ref={toolScrollRef}
- className="mt-1 max-h-80 overflow-y-auto overflow-x-hidden thin-scrollbar space-y-0.5 pl-1"
- >
- {stepsLoading && toolItems.length === 0 && (
+ <div ref={textScrollRef} className="mt-1 pl-1">
+ {thinkingLoading && intermediateTextItems.length === 0 && (
<div className="flex items-center gap-2 py-2 text-xs text-muted-foreground">
<Loader2 className="size-3 animate-spin" />
- <span>Loading steps...</span>
+ <span>Loading...</span>
</div>
)}
- {toolItems.map((item, idx) => {
- switch (item.kind) {
- case "tool-call":
- return <ToolCallBlock key={item.id} item={item} isRunning={isRunning} isLast={idx === toolItems.length - 1} />;
- case "thinking":
- return <ThinkingBlock key={item.id} item={item as ThinkingItem} />;
- case "status":
- return (
- <p
- key={item.id}
- className="text-xs text-muted-foreground px-1 wrap-anywhere"
- >
- {item.type === "error" && (
- <AlertCircle className="inline size-3 mr-1 -mt-0.5 text-destructive" />
- )}
- {(item as StatusItem).content}
- </p>
- );
- default:
- return null;
- }
- })}
- </div>
- </details>
- )}
-
- {/* Thinking section — intermediate text, open while running or when no final text */}
- {intermediateTextItems.length > 0 && (
- <details className="group/midtext pl-1" open={!hasFinalText || undefined}>
- <summary
- className={cn(
- "flex items-center gap-1.5 py-1 cursor-pointer select-none",
- "text-xs text-muted-foreground transition-colors duration-150",
- "hover:text-foreground",
- "[&::-webkit-details-marker]:hidden [&::marker]:hidden"
- )}
- >
- <ChevronRight className="size-3 shrink-0 text-muted-foreground/60 transition-transform duration-150 group-open/midtext:rotate-90" />
- <span><AnimatedNumber value={intermediateTextItems.length} /> thinking</span>
- </summary>
- <div ref={textScrollRef} className="mt-1 space-y-2 pl-1">
{intermediateTextItems.map((item) => (
- <div key={item.id} className="markdown max-w-full min-w-0 px-1 py-0.5 text-sm text-muted-foreground">
+ <div key={item.id} className="markdown max-w-full min-w-0 px-1 text-sm text-muted-foreground">
<Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{item.content}</Streamdown>
</div>
))}
@@ -439,13 +227,25 @@ export function TaskStream({
</details>
)}
{/* Final text — shown after completion (not for historical tasks which render it as a message) */}
- {hasFinalText && !onExpandSteps && (
+ {hasFinalText && !onExpandThinking && (
<div className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground">
<Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{finalTextItem.content}</Streamdown>
</div>
)}
- {/* Error display */}
+ {/* Stream error messages */}
+ {errorItems.length > 0 && (
+ <div className="space-y-1 mt-1">
+ {errorItems.map((item) => (
+ <p key={item.id} className="text-sm text-destructive flex items-start gap-1.5 min-w-0">
+ <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
+ <span className="wrap-anywhere">{item.content}</span>
+ </p>
+ ))}
+ </div>
+ )}
+
+ {/* Task-level error display */}
{task.status === "failed" && task.error && (
<div className="flex items-start gap-2 mt-2 max-w-full overflow-hidden">
<p className="text-sm text-destructive flex items-start gap-1.5 min-w-0">
diff --git a/src/web/src/lib/api.test.ts b/src/web/src/lib/api.test.ts
index 3586d3d4e..57d683b17 100644
--- a/src/web/src/lib/api.test.ts
+++ b/src/web/src/lib/api.test.ts
@@ -219,41 +219,88 @@ describe("apiFetch", () => {
});
});
-describe("getTaskStepCounts", () => {
- it("sends POST with task_ids and workspace_id", async () => {
- const counts = { "t1": 5, "t2": 12 };
- mockFetch.mockResolvedValueOnce({
+describe("apiFetch — mock network delay", () => {
+ afterEach(() => {
+ process.env.NODE_ENV = "test";
+ delete process.env.NEXT_PUBLIC_MOCK_NETWORK;
+ delete process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS;
+ vi.useRealTimers();
+ vi.stubGlobal("fetch", mockFetch);
+ });
+
+ it("delays fetch by default 300ms when NEXT_PUBLIC_MOCK_NETWORK is true", async () => {
+ vi.useFakeTimers();
+ process.env.NODE_ENV = "development";
+ process.env.NEXT_PUBLIC_MOCK_NETWORK = "true";
+ vi.resetModules();
+
+ const localMockFetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
- json: async () => counts,
+ json: async () => [{ id: "a1" }],
});
+ vi.stubGlobal("fetch", localMockFetch);
+
+ const { listAgents } = await import("./api");
+ const promise = listAgents("w1");
+
+ expect(localMockFetch).not.toHaveBeenCalled();
- const { getTaskStepCounts } = await getApiFetch();
- const result = await getTaskStepCounts(["t1", "t2"], "ws-1");
- expect(result).toEqual(counts);
-
- expect(mockFetch).toHaveBeenCalledWith(
- expect.stringContaining("/api/tasks/step-counts"),
- expect.objectContaining({
- method: "POST",
- headers: expect.objectContaining({ "Content-Type": "application/json" }),
- body: JSON.stringify({ task_ids: ["t1", "t2"] }),
- })
- );
-
- const calledUrl = mockFetch.mock.calls[0][0] as string;
- expect(calledUrl).toContain("workspace_id=ws-1");
+ await vi.advanceTimersByTimeAsync(300);
+
+ const result = await promise;
+ expect(localMockFetch).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([{ id: "a1" }]);
});
- it("returns empty object for empty task_ids", async () => {
- mockFetch.mockResolvedValueOnce({
+ it("calls fetch immediately when mock network is disabled", async () => {
+ vi.useFakeTimers();
+ vi.resetModules();
+
+ const localMockFetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
- json: async () => ({}),
+ json: async () => [{ id: "a1" }],
});
+ vi.stubGlobal("fetch", localMockFetch);
- const { getTaskStepCounts } = await getApiFetch();
- const result = await getTaskStepCounts([], "ws-1");
- expect(result).toEqual({});
+ const { listAgents } = await import("./api");
+ const promise = listAgents("w1");
+
+ await vi.advanceTimersByTimeAsync(0);
+
+ const result = await promise;
+ expect(localMockFetch).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([{ id: "a1" }]);
+ });
+
+ it("uses custom delay from NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS", async () => {
+ vi.useFakeTimers();
+ process.env.NODE_ENV = "development";
+ process.env.NEXT_PUBLIC_MOCK_NETWORK = "true";
+ process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS = "500";
+ vi.resetModules();
+
+ const localMockFetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => [{ id: "a1" }],
+ });
+ vi.stubGlobal("fetch", localMockFetch);
+
+ const { listAgents } = await import("./api");
+ const promise = listAgents("w1");
+
+ expect(localMockFetch).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(499);
+ expect(localMockFetch).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1);
+
+ const result = await promise;
+ expect(localMockFetch).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([{ id: "a1" }]);
});
});
+
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index f18661fe9..bca996c1a 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -33,6 +33,10 @@ import { ApiError } from "@/lib/errors";
const API_BASE = "";
+const MOCK_NETWORK_ENABLED = process.env.NODE_ENV === "development" && process.env.NEXT_PUBLIC_MOCK_NETWORK === "true";
+const MOCK_NETWORK_DELAY_MS = parseInt(process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS || "300", 10) || 300;
+let mockNetworkLogged = false;
+
function humanizeValidationDetail(detail: string): string {
const [rawField, ...rest] = detail.split(":");
const rawMessage = rest.join(":").trim();
@@ -62,6 +66,14 @@ function getReadableErrorMessage(error: string | undefined, details: string[] |
}
async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
+ if (MOCK_NETWORK_ENABLED) {
+ if (!mockNetworkLogged) {
+ console.info(`[Mock Network] Enabled — ${MOCK_NETWORK_DELAY_MS}ms delay on all API requests`);
+ mockNetworkLogged = true;
+ }
+ await new Promise((r) => setTimeout(r, MOCK_NETWORK_DELAY_MS));
+ }
+
let res: Response;
try {
res = await fetch(API_BASE + path, {
@@ -284,7 +296,7 @@ export interface ConversationInitResponse {
artifacts: Artifact[];
buffered_messages: Message[];
flagged_message_ids: string[];
- step_counts: Record<string, number>;
+ thinking_counts: Record<string, number>;
active_task: TaskApi | null;
task_messages: TaskMessage[];
cache_valid: boolean;
@@ -571,15 +583,6 @@ export const retryTask = (id: string, workspaceId: string) =>
method: "POST",
});
-export const getTaskStepCounts = (taskIds: string[], workspaceId: string) =>
- apiFetch<Record<string, number>>(
- `/api/tasks/step-counts${wsQuery(workspaceId)}`,
- {
- method: "POST",
- body: JSON.stringify({ task_ids: taskIds }),
- }
- );
-
// Emails
export const listEmails = (agentId: string, workspaceId: string, folder?: string, address?: string) =>
apiFetch<Email[]>(`/api/email${wsQuery(workspaceId, { agentId, ...(folder ? { folder } : {}), ...(address ? { address } : {}) })}`);