Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add cli email pull

Gus9228b0c24f43
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 76e2b838c..f517c37c8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -32,6 +32,9 @@ importers:
commander:
specifier: ^14.0.3
version: 14.0.3
+ postal-mime:
+ specifier: ^2.7.4
+ version: 2.7.4
devDependencies:
'@types/bun':
specifier: ^1.3.12
@@ -5057,6 +5060,9 @@ packages:
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-0WdnFQYUrPGGTFu1uOqD2s7omwua8xaeYGdO6rb88oD5yJ/4pPHDA4sdWqfD8wQVfCny563n/HQS7zTFft+f/g==}
+
resolution: {integrity: sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==}
engines: {node: '>=4'}
@@ -11561,6 +11567,8 @@ snapshots:
+
dependencies:
cssesc: 3.0.0
diff --git a/src/cli/commands/agent.ts b/src/cli/commands/agent.ts
index cb79203dd..c8bcadcbd 100644
--- a/src/cli/commands/agent.ts
+++ b/src/cli/commands/agent.ts
@@ -12,12 +12,16 @@ interface Agent {
created_at: string;
}
-function resolveClientOpts(command: Command) {
+function resolveClientOpts(command: Command, workspaceOpt?: string) {
const parentOpts = command.parent?.parent?.opts() || {};
const profile: string | undefined = parentOpts.profile;
const cfg = loadCLIConfigForProfile(profile);
const serverUrl = parentOpts.server || cfg.server_url;
- const token = cfg.token;
+
+ const ws = workspaceOpt
+ ? cfg.watched_workspaces?.find((w) => w.id === workspaceOpt)
+ : cfg.watched_workspaces?.[0];
+ const token = ws?.token;
if (!token) {
console.error(
@@ -26,7 +30,7 @@ function resolveClientOpts(command: Command) {
process.exit(1);
}
- return { serverUrl, token, cfg, profile };
+ return { serverUrl, token, cfg, profile, workspaceId: ws?.id };
}
export function agentCommand(): Command {
@@ -38,9 +42,7 @@ export function agentCommand(): Command {
.option("--workspace <id>", "Workspace ID")
.option("--json", "Output as JSON")
.action(async (opts, command) => {
- const { serverUrl, token, cfg } = resolveClientOpts(command);
- const workspaceId =
- opts.workspace || cfg.watched_workspaces?.[0]?.id;
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.workspace);
const client = new APIClient(serverUrl, token, workspaceId);
try {
@@ -80,9 +82,7 @@ export function agentCommand(): Command {
.requiredOption("--runtime <runtime>", "Agent runtime")
.option("--workspace <id>", "Workspace ID")
.action(async (opts, command) => {
- const { serverUrl, token, cfg } = resolveClientOpts(command);
- const workspaceId =
- opts.workspace || cfg.watched_workspaces?.[0]?.id;
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.workspace);
const client = new APIClient(serverUrl, token, workspaceId);
if (!opts.name) {
diff --git a/src/cli/commands/email.test.ts b/src/cli/commands/email.test.ts
new file mode 100644
index 000000000..a6a07836f
--- /dev/null
+++ b/src/cli/commands/email.test.ts
@@ -0,0 +1,229 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "fs";
+import { join } from "path";
+import PostalMime from "postal-mime";
+
+// Test the PostalMime parsing and file writing logic in isolation
+// (CLI commands themselves depend on network + config which we don't mock here)
+
+const TMP_DIR = "/tmp/alook-emails-test";
+
+describe("email pull output structure", () => {
+ beforeEach(() => {
+ mkdirSync(TMP_DIR, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(TMP_DIR, { recursive: true, force: true });
+ });
+
+ it("creates metadata.json with correct fields", () => {
+ const emailDir = join(TMP_DIR, "test-email-1");
+ mkdirSync(emailDir, { recursive: true });
+
+ const metadata = {
+ id: "test-email-1",
+ subject: "Test Subject",
+ date: "2024-01-01T00:00:00Z",
+ status: "unread",
+ };
+ writeFileSync(join(emailDir, "metadata.json"), JSON.stringify(metadata, null, 2));
+
+ const written = JSON.parse(readFileSync(join(emailDir, "metadata.json"), "utf-8"));
+ expect(written.id).toBe("test-email-1");
+ expect(written.from).toBe("[email protected]");
+ expect(written.to).toBe("[email protected]");
+ expect(written.subject).toBe("Test Subject");
+ expect(written.status).toBe("unread");
+ expect(written.date).toBe("2024-01-01T00:00:00Z");
+ });
+
+ it("writes body.txt from parsed MIME text body", async () => {
+ const rawMime = "From: [email protected]\r\nTo: [email protected]\r\nSubject: Hello\r\nContent-Type: text/plain\r\n\r\nHello world";
+ const parsed = await new PostalMime().parse(rawMime);
+
+ const emailDir = join(TMP_DIR, "test-email-2");
+ mkdirSync(emailDir, { recursive: true });
+
+ if (parsed.text) {
+ writeFileSync(join(emailDir, "body.txt"), parsed.text);
+ }
+
+ expect(existsSync(join(emailDir, "body.txt"))).toBe(true);
+ expect(readFileSync(join(emailDir, "body.txt"), "utf-8").trim()).toBe("Hello world");
+ });
+
+ it("writes body.html from parsed MIME HTML body", async () => {
+ const rawMime = [
+ "Subject: Hello",
+ "Content-Type: text/html; charset=utf-8",
+ "",
+ "<p>Hello world</p>",
+ ].join("\r\n");
+ const parsed = await new PostalMime().parse(rawMime);
+
+ const emailDir = join(TMP_DIR, "test-email-3");
+ mkdirSync(emailDir, { recursive: true });
+
+ if (parsed.html) {
+ writeFileSync(join(emailDir, "body.html"), parsed.html);
+ }
+
+ expect(existsSync(join(emailDir, "body.html"))).toBe(true);
+ expect(readFileSync(join(emailDir, "body.html"), "utf-8").trim()).toBe("<p>Hello world</p>");
+ });
+
+ it("extracts attachments with correct binary content", async () => {
+ const boundary = "----=_Part_001";
+ const rawMime = [
+ "Subject: With attachment",
+ `Content-Type: multipart/mixed; boundary="${boundary}"`,
+ "",
+ `--${boundary}`,
+ "Content-Type: text/plain",
+ "",
+ "Body text",
+ `--${boundary}`,
+ "Content-Type: application/octet-stream",
+ 'Content-Disposition: attachment; filename="report.bin"',
+ "Content-Transfer-Encoding: base64",
+ "",
+ Buffer.from("binary content").toString("base64"),
+ `--${boundary}--`,
+ ].join("\r\n");
+
+ const parsed = await new PostalMime().parse(rawMime);
+ expect(parsed.attachments.length).toBeGreaterThan(0);
+
+ const emailDir = join(TMP_DIR, "test-email-4");
+ const attDir = join(emailDir, "attachments");
+ mkdirSync(attDir, { recursive: true });
+
+ for (const att of parsed.attachments) {
+ const filename = att.filename || "attachment-0.bin";
+ const content = att.content;
+ let buf: Buffer;
+ if (typeof content === "string") {
+ buf = Buffer.from(content, "base64");
+ } else if (content instanceof ArrayBuffer) {
+ buf = Buffer.from(new Uint8Array(content));
+ } else {
+ buf = Buffer.from(content as Uint8Array);
+ }
+ writeFileSync(join(attDir, filename), buf);
+ }
+
+ const writtenFile = join(attDir, "report.bin");
+ expect(existsSync(writtenFile)).toBe(true);
+ expect(readFileSync(writtenFile).toString()).toBe("binary content");
+ });
+
+ it("handles attachments with missing filename", async () => {
+ const boundary = "----=_Part_002";
+ const rawMime = [
+ "Subject: No filename",
+ `Content-Type: multipart/mixed; boundary="${boundary}"`,
+ "",
+ `--${boundary}`,
+ "Content-Type: text/plain",
+ "",
+ "Body",
+ `--${boundary}`,
+ "Content-Type: application/octet-stream",
+ "Content-Transfer-Encoding: base64",
+ "",
+ Buffer.from("data").toString("base64"),
+ `--${boundary}--`,
+ ].join("\r\n");
+
+ const parsed = await new PostalMime().parse(rawMime);
+
+ const emailDir = join(TMP_DIR, "test-email-5");
+ const attDir = join(emailDir, "attachments");
+ mkdirSync(attDir, { recursive: true });
+
+ for (let i = 0; i < parsed.attachments.length; i++) {
+ const att = parsed.attachments[i];
+ const filename = att.filename || `attachment-${i}.bin`;
+ const content = att.content;
+ let buf: Buffer;
+ if (typeof content === "string") {
+ buf = Buffer.from(content, "base64");
+ } else if (content instanceof ArrayBuffer) {
+ buf = Buffer.from(new Uint8Array(content));
+ } else {
+ buf = Buffer.from(content as Uint8Array);
+ }
+ writeFileSync(join(attDir, filename), buf);
+ }
+
+ // Should use fallback filename
+ const files = require("fs").readdirSync(attDir);
+ expect(files.length).toBeGreaterThan(0);
+ expect(files.some((f: string) => f.startsWith("attachment-"))).toBe(true);
+ });
+
+ it("handles duplicate attachment filenames by prefixing with index", () => {
+ const emailDir = join(TMP_DIR, "test-email-6");
+ const attDir = join(emailDir, "attachments");
+ mkdirSync(attDir, { recursive: true });
+
+ const usedFilenames = new Set<string>();
+ const attachments = [
+ { filename: "report.pdf" },
+ { filename: "report.pdf" },
+ ];
+
+ for (let i = 0; i < attachments.length; i++) {
+ let filename = attachments[i].filename;
+ if (usedFilenames.has(filename)) {
+ filename = `${i}-${filename}`;
+ }
+ usedFilenames.add(filename);
+ writeFileSync(join(attDir, filename), "content");
+ }
+
+ expect(existsSync(join(attDir, "report.pdf"))).toBe(true);
+ expect(existsSync(join(attDir, "1-report.pdf"))).toBe(true);
+ });
+
+ it("does not clear existing email directories", () => {
+ // Pre-create some content
+ const existingDir = join(TMP_DIR, "existing-email");
+ mkdirSync(existingDir, { recursive: true });
+ writeFileSync(join(existingDir, "metadata.json"), "existing");
+
+ // Create a new email directory
+ const newDir = join(TMP_DIR, "new-email");
+ mkdirSync(newDir, { recursive: true });
+ writeFileSync(join(newDir, "metadata.json"), "new");
+
+ // Existing should still be there
+ expect(existsSync(join(existingDir, "metadata.json"))).toBe(true);
+ expect(readFileSync(join(existingDir, "metadata.json"), "utf-8")).toBe("existing");
+ });
+});
+
+describe("email status validation", () => {
+ const VALID_STATUSES = ["unread", "read", "archived"];
+
+ it("accepts valid status values", () => {
+ for (const s of VALID_STATUSES) {
+ expect(VALID_STATUSES.includes(s)).toBe(true);
+ }
+ });
+
+ it("rejects invalid status values", () => {
+ expect(VALID_STATUSES.includes("deleted")).toBe(false);
+ expect(VALID_STATUSES.includes("pending")).toBe(false);
+ expect(VALID_STATUSES.includes("")).toBe(false);
+ });
+});
diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.ts
new file mode 100644
index 000000000..d1f975e03
--- /dev/null
+++ b/src/cli/commands/email.ts
@@ -0,0 +1,213 @@
+import { Command } from "commander";
+import { writeFileSync, mkdirSync } from "fs";
+import { join } from "path";
+import PostalMime from "postal-mime";
+import { APIClient } from "../lib/client.js";
+import { loadCLIConfigForProfile } from "../lib/config.js";
+import { printJSON } from "../lib/output.js";
+import { cmdPrefix } from "../lib/env.js";
+
+interface EmailResponse {
+ id: string;
+ agent_id: string;
+ from_email: string;
+ to_email: string;
+ subject: string;
+ r2_key: string;
+ is_whitelisted: boolean;
+ forwarded: boolean;
+ html_body: string;
+ attachments: unknown[];
+ status: string;
+ created_at: string;
+}
+
+const VALID_STATUSES = ["unread", "read", "archived"];
+const EMAIL_DIR = "/tmp/alook-emails";
+
+function resolveClientOpts(command: Command, opts: { workspace?: string; agentId?: string }) {
+ const parentOpts = command.parent?.parent?.opts() || {};
+ const profile: string | undefined = parentOpts.profile;
+ const cfg = loadCLIConfigForProfile(profile);
+ const serverUrl = parentOpts.server || cfg.server_url;
+ const workspaces = cfg.watched_workspaces || [];
+
+ // Resolve workspace: explicit flag > lookup by agent_id > first workspace
+ let ws;
+ if (opts.workspace) {
+ ws = workspaces.find((w) => w.id === opts.workspace);
+ } else if (opts.agentId) {
+ ws = workspaces.find((w) => w.agent_ids?.includes(opts.agentId!));
+ }
+ if (!ws) ws = workspaces[0];
+
+ const token = ws?.token;
+
+ if (!token) {
+ console.error(
+ `Error: not registered. Run '${cmdPrefix()} register --token <token>' first.`,
+ );
+ process.exit(1);
+ }
+
+ return { serverUrl, token, cfg, profile, workspaceId: ws?.id };
+}
+
+export function emailCommand(): Command {
+ const cmd = new Command("email").description("Manage agent emails");
+
+ cmd
+ .command("pull")
+ .description("Download and parse emails to /tmp/alook-emails/")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .option("--status <status>", "Filter by status (unread, read, archived)")
+ .option("--workspace <id>", "Workspace ID")
+ .option("--json", "Output as JSON instead of files")
+ .action(async (opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { workspace: opts.workspace, agentId: opts.agent_id });
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ if (opts.status && !VALID_STATUSES.includes(opts.status)) {
+ console.error(
+ `Error: invalid status "${opts.status}", must be one of: ${VALID_STATUSES.join(", ")}`,
+ );
+ process.exit(1);
+ }
+
+ try {
+ let query = `/api/email?agentId=${opts.agent_id}`;
+ if (opts.status) query += `&status=${opts.status}`;
+
+ const emails = await client.getJSON<EmailResponse[]>(query);
+
+ if (!emails.length) {
+ console.log("No emails found.");
+ return;
+ }
+
+ if (opts.json) {
+ printJSON(emails);
+ return;
+ }
+
+ mkdirSync(EMAIL_DIR, { recursive: true });
+
+ const downloadedPaths: string[] = [];
+
+ for (const email of emails) {
+ const emailDir = join(EMAIL_DIR, email.id);
+ mkdirSync(emailDir, { recursive: true });
+
+ // Write metadata
+ const metadata = {
+ id: email.id,
+ from: email.from_email,
+ to: email.to_email,
+ subject: email.subject,
+ date: email.created_at,
+ status: email.status,
+ };
+ const metadataPath = join(emailDir, "metadata.json");
+ writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
+ downloadedPaths.push(metadataPath);
+
+ // Fetch and parse raw MIME
+ let rawMime: string;
+ try {
+ rawMime = await client.getText(`/api/email/${email.id}/raw`);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg.includes("404")) {
+ console.warn(
+ `Warning: email body not available for ${email.id}, skipping`,
+ );
+ continue;
+ }
+ throw err;
+ }
+
+ const parsed = await new PostalMime().parse(rawMime);
+
+ if (parsed.text) {
+ const bodyPath = join(emailDir, "body.txt");
+ writeFileSync(bodyPath, parsed.text);
+ downloadedPaths.push(bodyPath);
+ }
+
+ if (parsed.html) {
+ const htmlPath = join(emailDir, "body.html");
+ writeFileSync(htmlPath, parsed.html);
+ downloadedPaths.push(htmlPath);
+ }
+
+ if (parsed.attachments && parsed.attachments.length > 0) {
+ const attDir = join(emailDir, "attachments");
+ mkdirSync(attDir, { recursive: true });
+ const usedFilenames = new Set<string>();
+
+ for (let i = 0; i < parsed.attachments.length; i++) {
+ const att = parsed.attachments[i];
+ let filename = att.filename || `attachment-${i}.bin`;
+ if (usedFilenames.has(filename)) {
+ filename = `${i}-${filename}`;
+ }
+ usedFilenames.add(filename);
+ const attPath = join(attDir, filename);
+ const content = att.content;
+ let buf: Buffer;
+ if (typeof content === "string") {
+ buf = Buffer.from(content, "base64");
+ } else if (content instanceof ArrayBuffer) {
+ buf = Buffer.from(new Uint8Array(content));
+ } else {
+ buf = Buffer.from(content as Uint8Array);
+ }
+ writeFileSync(attPath, buf);
+ downloadedPaths.push(attPath);
+ }
+ }
+ }
+
+ console.log(
+ `Downloaded ${emails.length} email${emails.length === 1 ? "" : "s"} to ${EMAIL_DIR}/`,
+ );
+ for (const p of downloadedPaths) {
+ console.log(` ${p}`);
+ }
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ cmd
+ .command("set")
+ .description("Update email status")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--email_id <id>", "Email ID")
+ .requiredOption("--status <status>", "New status (unread, read, archived)")
+ .option("--workspace <id>", "Workspace ID")
+ .action(async (opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { workspace: opts.workspace, agentId: opts.agent_id });
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ if (!VALID_STATUSES.includes(opts.status)) {
+ console.error(
+ `Error: invalid status "${opts.status}", must be one of: ${VALID_STATUSES.join(", ")}`,
+ );
+ process.exit(1);
+ }
+
+ try {
+ await client.patchJSON(`/api/email/${opts.email_id}`, {
+ status: opts.status,
+ });
+ console.log(`Email ${opts.email_id} status set to ${opts.status}`);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ return cmd;
+}
diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.ts
index 406074460..e6623e066 100644
--- a/src/cli/commands/register.ts
+++ b/src/cli/commands/register.ts
@@ -15,6 +15,10 @@ interface Workspace {
name: string;
}
+interface AgentListItem {
+ id: string;
+}
+
interface ActivateResponse {
daemon_id: string;
runtimes: { id: string; provider: string }[];
@@ -141,18 +145,27 @@ export function registerCommand(): Command {
process.exit(1);
}
+ // Fetch agents for this workspace
+ const wsClient = new APIClient(serverUrl, token, ws.id);
+ let agentIds: string[] = [];
+ try {
+ const agents = await wsClient.getJSON<AgentListItem[]>(`/api/agents?workspace_id=${ws.id}`);
+ agentIds = agents.map((a) => a.id);
+ } catch {
+ // Non-fatal — agent_ids will be empty
+ }
+
// Load existing config to preserve other workspaces
const existing = loadCLIConfigForProfile(profile);
const watched = existing.watched_workspaces || [];
const idx = watched.findIndex((w) => w.id === ws.id);
if (idx >= 0) {
- watched[idx] = { id: ws.id, name: ws.name, token };
+ watched[idx] = { id: ws.id, name: ws.name, token, agent_ids: agentIds };
} else {
- watched.push({ id: ws.id, name: ws.name, token });
+ watched.push({ id: ws.id, name: ws.name, token, agent_ids: agentIds });
}
saveCLIConfigForProfile(profile, {
- token: "",
server_url: serverUrl,
watched_workspaces: watched,
});
diff --git a/src/cli/commands/status.ts b/src/cli/commands/status.ts
index 91b7444e1..7565560b9 100644
--- a/src/cli/commands/status.ts
+++ b/src/cli/commands/status.ts
@@ -9,7 +9,8 @@ export function statusCommand(): Command {
const profile: string | undefined = command.parent?.opts().profile;
const cfg = loadCLIConfigForProfile(profile);
- if (!cfg.token) {
+ const ws = cfg.watched_workspaces?.[0];
+ if (!ws?.token) {
console.log("Not registered");
console.log(
`Run '${cmdPrefix()} register --token <token>' to register.`,
@@ -19,10 +20,7 @@ export function statusCommand(): Command {
console.log("Status: Registered");
console.log(`Server: ${cfg.server_url}`);
- if (cfg.watched_workspaces.length > 0) {
- const ws = cfg.watched_workspaces[0];
- console.log(`Workspace: ${ws.name} (${ws.id})`);
- }
+ console.log(`Workspace: ${ws.name} (${ws.id})`);
});
return cmd;
diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.ts
index 280958545..67c83bb69 100644
--- a/src/cli/daemon/client.test.ts
+++ b/src/cli/daemon/client.test.ts
@@ -46,6 +46,58 @@ describe("PollResponseSchema validation", () => {
const raw = { tasks: [{ id: "t1" }] }; // missing required fields
expect(() => PollResponseSchema.parse(raw)).toThrow();
});
+
+ it("parses task with email_handle in agent data", () => {
+ const raw = {
+ tasks: [{
+ id: "t1",
+ agent_id: "a1",
+ runtime_id: "r1",
+ conversation_id: "c1",
+ workspace_id: "w1",
+ prompt: "do it",
+ status: "dispatched",
+ priority: 1,
+ dispatched_at: "2024-01-01T00:00:00Z",
+ started_at: null,
+ completed_at: null,
+ result: null,
+ error: null,
+ created_at: "2024-01-01T00:00:00Z",
+ type: "user_dm_message",
+ agent: { instructions: "help", name: "bot", runtime_config: {}, email_handle: "myagent" },
+ }],
+ };
+
+ const parsed = PollResponseSchema.parse(raw);
+ expect(parsed.tasks[0].agent?.email_handle).toBe("myagent");
+ });
+
+ it("parses task with null email_handle", () => {
+ const raw = {
+ tasks: [{
+ id: "t1",
+ agent_id: "a1",
+ runtime_id: "r1",
+ conversation_id: "c1",
+ workspace_id: "w1",
+ prompt: "do it",
+ status: "dispatched",
+ priority: 1,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ result: null,
+ error: null,
+ created_at: "2024-01-01T00:00:00Z",
+ type: "user_dm_message",
+ agent: { instructions: "help", name: "bot", runtime_config: {}, email_handle: null },
+ }],
+ };
+
+ const parsed = PollResponseSchema.parse(raw);
+ expect(parsed.tasks[0].agent?.email_handle).toBeNull();
+ });
});
// ---------------------------------------------------------------------------
@@ -312,4 +364,25 @@ describe("fromApiTask", () => {
expect(task.agent?.id).toBeUndefined();
expect(task.agent?.name).toBe("bot");
});
+
+ it("maps email_handle to emailHandle", () => {
+ const api = validApiTask();
+ api.agent = { instructions: "help", name: "bot", runtime_config: {}, email_handle: "myagent" };
+ 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 };
+ const task = fromApiTask(api);
+ expect(task.agent?.emailHandle).toBeUndefined();
+ });
+
+ it("maps missing email_handle to undefined", () => {
+ const api = validApiTask();
+ // No email_handle field at all
+ 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 1bff02979..693ebcccf 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -48,7 +48,6 @@ vi.mock("./agent/index.js", () => ({
vi.mock("../lib/config.js", () => ({
loadCLIConfigForProfile: vi.fn(() => ({
- token: "",
server_url: null,
watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
})),
@@ -365,7 +364,6 @@ describe("daemon with multi-workspace config", () => {
// Configure two workspaces
vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- token: "",
server_url: "",
watched_workspaces: [
{ id: "ws1", name: "Personal", token: "al_tok_ws1" },
@@ -516,7 +514,6 @@ describe("daemon shutdown", () => {
it("deregisters each workspace with correct token on shutdown", async () => {
// Configure two workspaces
vi.mocked(loadCLIConfigForProfile).mockReturnValue({
- token: "",
server_url: "",
watched_workspaces: [
{ id: "ws1", name: "Personal", token: "al_tok_ws1" },
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 5898a990a..0bf7fd526 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -167,7 +167,10 @@ export async function startDaemon(
const pollTimer = setInterval(pollCycle, config.pollInterval);
+ let shuttingDown = false;
const shutdown = async () => {
+ if (shuttingDown) return;
+ shuttingDown = true;
log.info("Shutting down...");
clearInterval(pollTimer);
const shutdownMs = Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000;
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
new file mode 100644
index 000000000..16785b02f
--- /dev/null
+++ b/src/cli/daemon/execenv/context.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect } from "vitest";
+import { buildInstructionContent } from "./context.js";
+import type { Task } from "../types.js";
+
+function makeTask(overrides: Partial<Task> = {}): Task {
+ return {
+ id: "t1",
+ agentId: "agent-123",
+ runtimeId: "r1",
+ conversationId: "c1",
+ workspaceId: "ws1",
+ prompt: "test",
+ status: "running",
+ priority: 0,
+ type: "user_dm_message",
+ createdAt: "2024-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("buildInstructionContent email tool injection", () => {
+ it("includes email tool section when agent has email handle", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("## Email Tools");
+ expect(content).toContain("alook email pull --agent_id agent-123 --status unread");
+ expect(content).toContain("alook email set --agent_id agent-123 --email_id <EMAIL_ID> --status read");
+ expect(content).toContain("/tmp/alook-emails/");
+ expect(content).toContain("metadata.json");
+ });
+
+ it("omits email tool section when agent has no email handle", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "do stuff" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).not.toContain("## Email Tools");
+ expect(content).not.toContain("email pull");
+ });
+
+ it("omits email tool section when emailHandle is null", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "do stuff", emailHandle: null },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).not.toContain("## Email Tools");
+ });
+
+ it("omits email tool section when emailHandle is empty string", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "do stuff", emailHandle: "" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).not.toContain("## Email Tools");
+ });
+
+ it("uses correct agent ID in email tool commands", () => {
+ const task = makeTask({
+ agentId: "specific-agent-id",
+ agent: { name: "test", instructions: "", emailHandle: "handle" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("--agent_id specific-agent-id");
+ });
+
+ it("still includes big boss instructions alongside email tools", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "Follow these rules", emailHandle: "myagent" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("## BIG BOSS Instructions");
+ expect(content).toContain("Follow these rules");
+ expect(content).toContain("## Email Tools");
+ });
+});
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 1a917226a..956d65e1d 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -71,6 +71,20 @@ ${task.agent.instructions}
`;
}
+ if (task.agent?.emailHandle) {
+ content += `\n## Email Tools
+Run \`alook email pull --agent_id ${task.agentId} --status unread\` to download unread emails to \`/tmp/alook-emails/\`.
+Each email is saved to \`/tmp/alook-emails/<emailId>/\` with:
+- \`metadata.json\` — sender, recipient, subject, date, status
+- \`body.txt\` — plain text body
+- \`body.html\` — HTML body (if available)
+- \`attachments/\` — extracted attachment files (if any)
+
+After processing an email, mark it as read:
+Run \`alook email set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read\`
+`;
+ }
+
return content;
}
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
index 36b208750..3eda59c6a 100644
--- a/src/cli/daemon/types.ts
+++ b/src/cli/daemon/types.ts
@@ -17,6 +17,7 @@ export interface TaskAgentData {
id?: string;
name: string;
instructions: string;
+ emailHandle?: string | null;
}
export interface RepoData {
@@ -87,7 +88,7 @@ export function fromApiTask(api: import("@alook/shared").TaskApi): Task {
priority: api.priority,
type: api.type,
agent: api.agent
- ? { name: api.agent.name, instructions: api.agent.instructions }
+ ? { name: api.agent.name, instructions: api.agent.instructions, emailHandle: api.agent.email_handle ?? undefined }
: undefined,
repos: undefined,
createdAt: api.created_at,
diff --git a/src/cli/lib/client.ts b/src/cli/lib/client.ts
index 705728861..0c9aa4948 100644
--- a/src/cli/lib/client.ts
+++ b/src/cli/lib/client.ts
@@ -41,6 +41,24 @@ export class APIClient {
return this.request("DELETE", path);
}
+ patchJSON<T>(path: string, body?: unknown): Promise<T> {
+ return this.request("PATCH", path, body);
+ }
+
+ async getText(path: string): Promise<string> {
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${this.token}`,
+ };
+ if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
+
+ const res = await fetch(this.baseURL + path, { method: "GET", headers });
+ if (!res.ok) {
+ const text = await res.text();
+ throw new Error(`HTTP ${res.status}: ${text}`);
+ }
+ return res.text();
+ }
+
async healthCheck(): Promise<boolean> {
try {
await this.getJSON("/health");
diff --git a/src/cli/lib/config.test.ts b/src/cli/lib/config.test.ts
index 1432ae1c0..0e5b03611 100644
--- a/src/cli/lib/config.test.ts
+++ b/src/cli/lib/config.test.ts
@@ -69,7 +69,7 @@ describe("loadCLIConfig", () => {
});
it("returns parsed JSON when file exists", () => {
- const cfg = { token: "abc", server_url: "http://example.com" };
+ const cfg = { server_url: "http://example.com", watched_workspaces: [] };
mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
expect(loadCLIConfig()).toEqual(cfg);
});
@@ -78,9 +78,8 @@ describe("loadCLIConfig", () => {
describe("loadCLIConfigForProfile", () => {
it("returns profile config when profile specified", () => {
const profileCfg = {
- token: "profile-token",
server_url: "http://profile.example.com",
- watched_workspaces: [{ id: "w1", name: "Workspace 1" }],
+ watched_workspaces: [{ id: "w1", name: "Workspace 1", token: "ws-token" }],
};
const cfg = { profiles: { staging: profileCfg } };
mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
@@ -90,7 +89,6 @@ describe("loadCLIConfigForProfile", () => {
it("uses default_profile when no profile specified", () => {
const profileCfg = {
- token: "default-token",
server_url: "http://default.example.com",
watched_workspaces: [],
};
@@ -102,16 +100,14 @@ describe("loadCLIConfigForProfile", () => {
it("falls back to root-level fields when profile not found", () => {
const cfg = {
- token: "root-token",
server_url: "http://root.example.com",
- watched_workspaces: [{ id: "w2", name: "Root WS" }],
+ watched_workspaces: [{ id: "w2", name: "Root WS", token: "ws-token" }],
};
mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));
expect(loadCLIConfigForProfile()).toEqual({
- token: "root-token",
server_url: "http://root.example.com",
- watched_workspaces: [{ id: "w2", name: "Root WS" }],
+ watched_workspaces: [{ id: "w2", name: "Root WS", token: "ws-token" }],
});
});
@@ -121,7 +117,6 @@ describe("loadCLIConfigForProfile", () => {
});
expect(loadCLIConfigForProfile()).toEqual({
- token: "",
server_url: "",
watched_workspaces: [],
});
@@ -130,7 +125,7 @@ describe("loadCLIConfigForProfile", () => {
describe("saveCLIConfig", () => {
it("writes valid JSON with mode 0600 to ~/.alook in production", () => {
- const cfg = { token: "abc", server_url: "http://example.com" };
+ const cfg = { server_url: "http://example.com", watched_workspaces: [] };
saveCLIConfig(cfg);
expect(mockedMkdirSync).toHaveBeenCalledWith(
@@ -148,7 +143,7 @@ describe("saveCLIConfig", () => {
process.env.ALOOK_SERVER_URL = "http://localhost:3000";
process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";
- const cfg = { token: "dev-token", server_url: "http://localhost:3000" };
+ const cfg = { server_url: "http://localhost:3000", watched_workspaces: [] };
saveCLIConfig(cfg);
expect(mockedMkdirSync).toHaveBeenCalledWith(
@@ -165,11 +160,10 @@ describe("saveCLIConfig", () => {
describe("saveCLIConfigForProfile", () => {
it("updates specific profile", () => {
- const existing = { token: "root", profiles: {} };
+ const existing = { profiles: {} };
mockedReadFileSync.mockReturnValue(JSON.stringify(existing));
const profileCfg = {
- token: "new-token",
server_url: "http://new.example.com",
watched_workspaces: [],
};
@@ -185,17 +179,15 @@ describe("saveCLIConfigForProfile", () => {
mockedReadFileSync.mockReturnValue(JSON.stringify({}));
const profileCfg = {
- token: "root-token",
server_url: "http://root.example.com",
- watched_workspaces: [{ id: "w1", name: "WS" }],
+ watched_workspaces: [{ id: "w1", name: "WS", token: "ws-token" }],
};
saveCLIConfigForProfile(undefined, profileCfg);
const written = JSON.parse(
mockedWriteFileSync.mock.calls[0][1] as string,
);
- expect(written.token).toBe("root-token");
expect(written.server_url).toBe("http://root.example.com");
- expect(written.watched_workspaces).toEqual([{ id: "w1", name: "WS" }]);
+ expect(written.watched_workspaces).toEqual([{ id: "w1", name: "WS", token: "ws-token" }]);
});
});
diff --git a/src/cli/lib/config.ts b/src/cli/lib/config.ts
index 9f95cfbca..d54d04efe 100644
--- a/src/cli/lib/config.ts
+++ b/src/cli/lib/config.ts
@@ -7,16 +7,15 @@ interface WatchedWorkspace {
id: string;
name: string;
token: string;
+ agent_ids?: string[];
}
interface ProfileConfig {
- token: string;
server_url: string;
watched_workspaces: WatchedWorkspace[];
}
interface CLIConfig {
- token?: string;
server_url?: string;
watched_workspaces?: WatchedWorkspace[];
default_profile?: string;
@@ -51,7 +50,6 @@ export function loadCLIConfigForProfile(profile?: string): ProfileConfig {
return cfg.profiles[profileName];
}
return {
- token: cfg.token || "",
server_url: cfg.server_url || "",
watched_workspaces: cfg.watched_workspaces || [],
};
@@ -71,7 +69,6 @@ export function saveCLIConfigForProfile(
if (!cfg.profiles) cfg.profiles = {};
cfg.profiles[profile] = profileConfig;
} else {
- cfg.token = profileConfig.token;
cfg.server_url = profileConfig.server_url;
cfg.watched_workspaces = profileConfig.watched_workspaces;
}
diff --git a/src/cli/package.json b/src/cli/package.json
index b3666fcd3..873a6b86a 100644
--- a/src/cli/package.json
+++ b/src/cli/package.json
@@ -12,7 +12,8 @@
"dependencies": {
"@alook/shared": "workspace:*",
"citty": "^0.2.2",
- "commander": "^14.0.3"
+ "commander": "^14.0.3",
+ "postal-mime": "^2.7.4"
},
"devDependencies": {
"@types/bun": "^1.3.12",
diff --git a/src/cli/src/index.ts b/src/cli/src/index.ts
index 77f314501..dbd9873ee 100644
--- a/src/cli/src/index.ts
+++ b/src/cli/src/index.ts
@@ -5,6 +5,7 @@ import { statusCommand } from "../commands/status.js";
import { agentCommand } from "../commands/agent.js";
import { daemonCommand } from "../commands/daemon.js";
import { configCommand } from "../commands/config.js";
+import { emailCommand } from "../commands/email.js";
import { versionCommand } from "../commands/version.js";
const program = new Command();
@@ -19,6 +20,7 @@ program.addCommand(registerCommand());
program.addCommand(statusCommand());
program.addCommand(agentCommand());
program.addCommand(daemonCommand());
+program.addCommand(emailCommand());
program.addCommand(configCommand());
program.addCommand(versionCommand());
diff --git a/src/shared/src/db/queries/email.ts b/src/shared/src/db/queries/email.ts
index c946c09f1..f3db111cd 100644
--- a/src/shared/src/db/queries/email.ts
+++ b/src/shared/src/db/queries/email.ts
@@ -15,26 +15,37 @@ export async function getEmailById(db: Database, id: string, workspaceId: string
return rows[0] ?? null;
}
-export async function getEmailsByAgent(db: Database, agentId: string, workspaceId: string) {
+export async function getEmailsByAgent(db: Database, agentId: string, workspaceId: string, status?: string) {
+ const conditions = [eq(emails.agentId, agentId), eq(emails.workspaceId, workspaceId)];
+ if (status) conditions.push(eq(emails.status, status));
return db
.select()
.from(emails)
- .where(and(eq(emails.agentId, agentId), eq(emails.workspaceId, workspaceId)))
+ .where(and(...conditions))
.orderBy(desc(emails.createdAt));
}
-export async function getInboxEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string) {
+export async function getInboxEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {
+ const conditions = [eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId)];
+ if (status) conditions.push(eq(emails.status, status));
return db.select().from(emails)
- .where(and(eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId)))
+ .where(and(...conditions))
.orderBy(desc(emails.createdAt));
}
-export async function getSentEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string) {
+export async function getSentEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {
+ const conditions = [eq(emails.agentId, agentId), eq(emails.fromEmail, agentEmail), eq(emails.workspaceId, workspaceId)];
+ if (status) conditions.push(eq(emails.status, status));
return db.select().from(emails)
- .where(and(eq(emails.agentId, agentId), eq(emails.fromEmail, agentEmail), eq(emails.workspaceId, workspaceId)))
+ .where(and(...conditions))
.orderBy(desc(emails.createdAt));
}
+export async function updateEmailStatus(db: Database, id: string, workspaceId: string, status: string) {
+ const rows = await db.update(emails).set({ status }).where(and(eq(emails.id, id), eq(emails.workspaceId, workspaceId))).returning();
+ return rows[0] ?? null;
+}
+
export async function deleteEmail(db: Database, id: string, workspaceId: string) {
return db.delete(emails).where(and(eq(emails.id, id), eq(emails.workspaceId, workspaceId)));
}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 2ca8a5b13..fcf2a72e7 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -282,6 +282,7 @@ export const emails = sqliteTable(
forwarded: integer("forwarded", { mode: "boolean" }).notNull().default(false),
htmlBody: text("html_body").notNull().default(""),
attachments: text("attachments").notNull().default("[]"),
+ status: text("status").notNull().default("unread"),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
},
(t) => [
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 025107ef3..187480743 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -46,6 +46,7 @@ export const TaskAgentDataApiSchema = z.object({
instructions: z.string(),
name: z.string(),
runtime_config: z.record(z.string(), z.unknown()).default({}),
+ email_handle: z.string().nullable().optional(),
});
export type TaskAgentDataApi = z.infer<typeof TaskAgentDataApiSchema>;
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 117f1ff18..c2abe32b5 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -109,6 +109,7 @@ export interface Email {
forwarded: boolean;
html_body: string;
attachments: EmailAttachment[];
+ status: string;
created_at: string;
}
diff --git a/src/shared/test/queries/email.test.ts b/src/shared/test/queries/email.test.ts
index 74e125c74..542b6cd40 100644
--- a/src/shared/test/queries/email.test.ts
+++ b/src/shared/test/queries/email.test.ts
@@ -25,4 +25,28 @@ describe("email query module exports", () => {
it("exports getEmailsByAgent", () => {
expect(typeof emailQueries.getEmailsByAgent).toBe("function");
});
+
+ it("exports updateEmailStatus", () => {
+ expect(typeof emailQueries.updateEmailStatus).toBe("function");
+ });
+});
+
+describe("email query function signatures", () => {
+ it("getEmailsByAgent accepts optional status parameter", () => {
+ // The function should accept 4 parameters (db, agentId, workspaceId, status?)
+ expect(emailQueries.getEmailsByAgent.length).toBeLessThanOrEqual(4);
+ });
+
+ it("getInboxEmails accepts optional status parameter", () => {
+ expect(emailQueries.getInboxEmails.length).toBeLessThanOrEqual(5);
+ });
+
+ it("getSentEmails accepts optional status parameter", () => {
+ expect(emailQueries.getSentEmails.length).toBeLessThanOrEqual(5);
+ });
+
+ it("updateEmailStatus has correct arity", () => {
+ // (db, id, workspaceId, status)
+ expect(emailQueries.updateEmailStatus.length).toBe(4);
+ });
});
diff --git a/src/web/migrations/0006_email_status.sql b/src/web/migrations/0006_email_status.sql
new file mode 100644
index 000000000..bb565bd2b
--- /dev/null
+++ b/src/web/migrations/0006_email_status.sql
@@ -0,0 +1 @@
+ALTER TABLE emails ADD COLUMN status TEXT NOT NULL DEFAULT 'unread';
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
index c61e632ff..44dbb5af4 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
@@ -19,7 +19,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { ArrowUp, Loader2 } from "lucide-react";
import { Streamdown } from "streamdown";
-const MESSAGE_LIMIT = 20;
+const MESSAGE_LIMIT = 10;
export default function AgentChatPage() {
const params = useParams();
@@ -59,7 +59,7 @@ export default function AgentChatPage() {
try {
const conv = await getOrCreateAgentConversation(agentId, workspaceId);
setConversation(conv);
- const msgs = await listMessages(conv.id, workspaceId);
+ const msgs = await listMessages(conv.id, workspaceId, { limit: MESSAGE_LIMIT });
setMessages(msgs);
setHasMore(msgs.length >= MESSAGE_LIMIT);
} catch {
@@ -71,25 +71,15 @@ export default function AgentChatPage() {
load();
}, [agentId, workspaceId]);
- // Scroll to bottom on initial load and when new messages arrive at the bottom
+ // Scroll to bottom on initial load
useEffect(() => {
if (!loading && messages.length > 0 && !initialScrollDone.current) {
initialScrollDone.current = true;
- // Use instant scroll for initial load
setTimeout(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
}, 50);
- return;
}
- // For new messages/task updates, smooth scroll only if near bottom
- const el = scrollRef.current;
- if (el) {
- const isNearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 150;
- if (isNearBottom) {
- scrollToBottom();
- }
- }
- }, [messages, taskMessages, loading, scrollToBottom]);
+ }, [loading, messages.length]);
const loadOlderMessages = useCallback(async () => {
if (!conversation || loadingMoreRef.current || !hasMore) return;
@@ -103,6 +93,7 @@ export default function AgentChatPage() {
try {
const older = await listMessages(conversation.id, workspaceId, {
+ limit: MESSAGE_LIMIT,
before: oldest.created_at,
beforeId: oldest.id,
});
@@ -111,7 +102,11 @@ export default function AgentChatPage() {
return;
}
setHasMore(older.length >= MESSAGE_LIMIT);
- setMessages((prev) => [...older, ...prev]);
+ setMessages((prev) => {
+ const existingIds = new Set(prev.map((m) => m.id));
+ const unique = older.filter((m) => !existingIds.has(m.id));
+ return [...unique, ...prev];
+ });
// Restore scroll position so content doesn't jump
requestAnimationFrame(() => {
@@ -175,6 +170,7 @@ export default function AgentChatPage() {
const newMsgs = latest.filter((m) => !existingIds.has(m.id));
return [...prev, ...newMsgs];
});
+ scrollToBottom();
} catch {
toast.error("Failed to refresh messages");
}
@@ -218,6 +214,7 @@ export default function AgentChatPage() {
created_at: new Date().toISOString(),
};
setMessages((prev) => [...prev, optimistic]);
+ scrollToBottom();
try {
const { message, task } = await sendMessage(conversation.id, content, workspaceId);
diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
index 8a02eca9a..6b6f4d93d 100644
--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
@@ -300,7 +300,7 @@ export default function RuntimesPage() {
return (
<Card key={daemonId} size="sm" className="group">
<CardHeader>
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 min-w-0">
<Monitor className="size-4 text-muted-foreground shrink-0" />
<CardTitle className="truncate">
{displayName}
@@ -336,29 +336,27 @@ export default function RuntimesPage() {
</CardAction>
</CardHeader>
<CardContent>
- <div className="space-y-2">
+ <div className="space-y-2.5">
<p className="text-xs text-muted-foreground tabular-nums">
{machine.lastSeenAt ? new Date(
machine.lastSeenAt
).toLocaleString() : "Never seen"}
</p>
- {machine.runtimes.map((runtime) => (
- <div
- key={runtime.id}
- className="flex items-center gap-2"
- >
- <div className="min-w-0">
- <p className="text-xs font-medium truncate">
- {runtime.provider}
- {runtime.metadata?.version ? (
- <span className="ml-1.5 font-normal text-muted-foreground">
- {String(runtime.metadata.version)}
- </span>
- ) : null}
- </p>
- </div>
- </div>
- ))}
+ <div className="flex flex-wrap gap-1.5">
+ {machine.runtimes.map((runtime) => (
+ <Badge
+ key={runtime.id}
+ variant="secondary"
+ >
+ {runtime.provider}
+ {runtime.metadata?.version ? (
+ <span className="text-muted-foreground font-normal">
+ {String(runtime.metadata.version)}
+ </span>
+ ) : null}
+ </Badge>
+ ))}
+ </div>
</div>
</CardContent>
</Card>
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
index 3d6406387..e09f827a0 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
@@ -135,6 +135,7 @@ describe("POST /api/daemon/tasks/poll", () => {
instructions: "be helpful",
name: "Bot",
runtime_config: { model: "gpt-4" },
+ email_handle: null,
});
});
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.ts
index 11b4a3207..008b959c6 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts
@@ -66,6 +66,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
instructions: agent.instructions,
name: agent.name,
runtime_config: agent.runtimeConfig || {},
+ email_handle: agent.emailHandle || null,
}
: null,
});
diff --git a/src/web/src/app/api/email/[id]/raw/route.test.ts b/src/web/src/app/api/email/[id]/raw/route.test.ts
new file mode 100644
index 000000000..a6f511a33
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/raw/route.test.ts
@@ -0,0 +1,87 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetEmailById = vi.fn();
+const mockR2Get = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: {
+ DB: {},
+ EMAIL_BUCKET: {
+ get: (...args: unknown[]) => mockR2Get(...args),
+ },
+ },
+ })),
+}));
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ email: {
+ getEmailById: (...args: unknown[]) => mockGetEmailById(...args),
+ },
+ },
+}));
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+import { GET } from "./route";
+
+describe("GET /api/email/[id]/raw", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns full raw MIME with content-type message/rfc822", async () => {
+ const rawMime = "From: [email protected]\r\nSubject: Hello\r\n\r\nBody content";
+ mockGetEmailById.mockResolvedValue({ id: "e1", r2Key: "emails/e1/raw" });
+ mockR2Get.mockResolvedValue({
+ body: new ReadableStream({
+ start(c) { c.enqueue(new TextEncoder().encode(rawMime)); c.close(); },
+ }),
+ });
+
+ const req = new NextRequest("http://localhost/api/email/e1/raw");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get("Content-Type")).toBe("message/rfc822");
+ const body = await res.text();
+ expect(body).toBe(rawMime);
+ });
+
+ it("returns 404 when R2 object missing", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", r2Key: "emails/e1/raw" });
+ mockR2Get.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/email/e1/raw");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 404 when email not in workspace", async () => {
+ mockGetEmailById.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/email/e1/raw");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/email/[id]/raw/route.ts b/src/web/src/app/api/email/[id]/raw/route.ts
new file mode 100644
index 000000000..511c8cf0a
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/raw/route.ts
@@ -0,0 +1,28 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { createDb, queries } from "@alook/shared";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeError } from "@/lib/middleware/helpers";
+
+export const GET = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = createDb((env as Env).DB);
+
+ const id = ctx.params?.id;
+ if (!id) return writeError("email id is required", 400);
+
+ const email = await queries.email.getEmailById(db, id, ws.workspaceId);
+ if (!email) return writeError("email not found", 404);
+
+ const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);
+ if (!object) {
+ return writeError("Email raw content not available", 404);
+ }
+
+ return new Response(object.body, {
+ headers: { "Content-Type": "message/rfc822" },
+ });
+});
diff --git a/src/web/src/app/api/email/[id]/route.test.ts b/src/web/src/app/api/email/[id]/route.test.ts
index 2b48f19cb..beaf513a3 100644
--- a/src/web/src/app/api/email/[id]/route.test.ts
+++ b/src/web/src/app/api/email/[id]/route.test.ts
@@ -3,6 +3,7 @@ import { NextRequest } from "next/server";
const mockGetEmailById = vi.fn();
const mockDeleteEmail = vi.fn();
+const mockUpdateEmailStatus = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({
@@ -16,6 +17,7 @@ vi.mock("@alook/shared", () => ({
email: {
getEmailById: (...args: unknown[]) => mockGetEmailById(...args),
deleteEmail: (...args: unknown[]) => mockDeleteEmail(...args),
+ updateEmailStatus: (...args: unknown[]) => mockUpdateEmailStatus(...args),
},
},
}));
@@ -40,10 +42,10 @@ vi.mock("@/lib/middleware/helpers", () => {
});
vi.mock("@/lib/api/responses", () => ({
- emailToResponse: (e: any) => ({ id: e.id }),
+ emailToResponse: (e: any) => ({ id: e.id, status: e.status }),
}));
-import { GET, DELETE } from "./route";
+import { GET, DELETE, PATCH } from "./route";
describe("GET /api/email/[id]", () => {
beforeEach(() => vi.clearAllMocks());
@@ -91,3 +93,80 @@ describe("DELETE /api/email/[id]", () => {
expect(res.status).toBe(404);
});
});
+
+describe("PATCH /api/email/[id]", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("updates status for valid email in workspace", async () => {
+ mockUpdateEmailStatus.mockResolvedValue({ id: "e1", status: "read" });
+
+ const req = new NextRequest("http://localhost/api/email/e1", {
+ method: "PATCH",
+ body: JSON.stringify({ status: "read" }),
+ });
+ const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toEqual({ id: "e1", status: "read" });
+ expect(mockUpdateEmailStatus).toHaveBeenCalledWith({}, "e1", "ws1", "read");
+ });
+
+ it("updates status to archived", async () => {
+ mockUpdateEmailStatus.mockResolvedValue({ id: "e1", status: "archived" });
+
+ const req = new NextRequest("http://localhost/api/email/e1", {
+ method: "PATCH",
+ body: JSON.stringify({ status: "archived" }),
+ });
+ const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(200);
+ expect(mockUpdateEmailStatus).toHaveBeenCalledWith({}, "e1", "ws1", "archived");
+ });
+
+ it("returns 404 when email not in workspace", async () => {
+ mockUpdateEmailStatus.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/email/e1", {
+ method: "PATCH",
+ body: JSON.stringify({ status: "read" }),
+ });
+ const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 400 for invalid status value", async () => {
+ const req = new NextRequest("http://localhost/api/email/e1", {
+ method: "PATCH",
+ body: JSON.stringify({ status: "deleted" }),
+ });
+ const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toBe("invalid status");
+ });
+
+ it("returns 400 for missing status", async () => {
+ const req = new NextRequest("http://localhost/api/email/e1", {
+ method: "PATCH",
+ body: JSON.stringify({}),
+ });
+ const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 400 for invalid JSON body", async () => {
+ const req = new NextRequest("http://localhost/api/email/e1", {
+ method: "PATCH",
+ body: "not json",
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/email/[id]/route.ts b/src/web/src/app/api/email/[id]/route.ts
index e63d33390..5d0a45e63 100644
--- a/src/web/src/app/api/email/[id]/route.ts
+++ b/src/web/src/app/api/email/[id]/route.ts
@@ -38,3 +38,32 @@ export const DELETE = withAuth(async (req, ctx) => {
return new Response(null, { status: 204 });
});
+
+const VALID_STATUSES = ["unread", "read", "archived"] as const;
+
+export const PATCH = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = createDb((env as Env).DB);
+
+ const id = ctx.params?.id;
+ if (!id) return writeError("email id is required", 400);
+
+ let body: { status?: string };
+ try {
+ body = await req.json();
+ } catch {
+ return writeError("invalid JSON body", 400);
+ }
+
+ if (!body.status || !VALID_STATUSES.includes(body.status as typeof VALID_STATUSES[number])) {
+ return writeError("invalid status", 400);
+ }
+
+ const updated = await queries.email.updateEmailStatus(db, id, ws.workspaceId, body.status);
+ if (!updated) return writeError("email not found", 404);
+
+ return writeJSON(emailToResponse(updated));
+});
diff --git a/src/web/src/app/api/email/route.test.ts b/src/web/src/app/api/email/route.test.ts
new file mode 100644
index 000000000..5193bee8d
--- /dev/null
+++ b/src/web/src/app/api/email/route.test.ts
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetAgent = vi.fn();
+const mockGetEmailsByAgent = vi.fn();
+const mockGetInboxEmails = vi.fn();
+const mockGetSentEmails = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
+ email: {
+ getEmailsByAgent: (...args: unknown[]) => mockGetEmailsByAgent(...args),
+ getInboxEmails: (...args: unknown[]) => mockGetInboxEmails(...args),
+ getSentEmails: (...args: unknown[]) => mockGetSentEmails(...args),
+ },
+ },
+}));
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+vi.mock("@/lib/api/responses", () => ({
+ emailToResponse: (e: any) => e,
+}));
+
+import { GET } from "./route";
+
+describe("GET /api/email", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns all emails for agent (no status filter)", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+ mockGetEmailsByAgent.mockResolvedValue([{ id: "e1" }, { id: "e2" }]);
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1");
+ const res = await GET(req, {} as any);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toHaveLength(2);
+ expect(mockGetEmailsByAgent).toHaveBeenCalledWith({}, "a1", "ws1", undefined);
+ });
+
+ it("filters by status=unread", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+ mockGetEmailsByAgent.mockResolvedValue([{ id: "e1", status: "unread" }]);
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&status=unread");
+ const res = await GET(req, {} as any);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toHaveLength(1);
+ expect(mockGetEmailsByAgent).toHaveBeenCalledWith({}, "a1", "ws1", "unread");
+ });
+
+ it("filters by status and folder=inbox", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+ mockGetInboxEmails.mockResolvedValue([{ id: "e1" }]);
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&folder=inbox&status=unread");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "unread");
+ });
+
+ it("filters by status and folder=sent", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+ mockGetSentEmails.mockResolvedValue([]);
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&folder=sent&status=read");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockGetSentEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "read");
+ });
+
+ it("returns 400 for invalid status value", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&status=invalid");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toBe("invalid status");
+ });
+});
diff --git a/src/web/src/app/api/email/route.ts b/src/web/src/app/api/email/route.ts
index e24152233..61c841ee8 100644
--- a/src/web/src/app/api/email/route.ts
+++ b/src/web/src/app/api/email/route.ts
@@ -6,6 +6,8 @@ import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON, writeError } from "@/lib/middleware/helpers";
import { emailToResponse } from "@/lib/api/responses";
+const VALID_STATUSES = ["unread", "read", "archived"];
+
export const GET = withAuth(async (req: NextRequest, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
if (ws instanceof Response) return ws;
@@ -19,16 +21,21 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId);
if (!agent) return writeError("agent not found in workspace", 404);
+ const status = req.nextUrl.searchParams.get("status") ?? undefined;
+ if (status && !VALID_STATUSES.includes(status)) {
+ return writeError("invalid status", 400);
+ }
+
const folder = req.nextUrl.searchParams.get("folder");
const agentEmail = agent.emailHandle ? `${agent.emailHandle}@alook.ai` : "";
let emailList;
if (folder === "inbox" && agentEmail) {
- emailList = await queries.email.getInboxEmails(db, agentId, agentEmail, ws.workspaceId);
+ emailList = await queries.email.getInboxEmails(db, agentId, agentEmail, ws.workspaceId, status);
} else if (folder === "sent" && agentEmail) {
- emailList = await queries.email.getSentEmails(db, agentId, agentEmail, ws.workspaceId);
+ emailList = await queries.email.getSentEmails(db, agentId, agentEmail, ws.workspaceId, status);
} else {
- emailList = await queries.email.getEmailsByAgent(db, agentId, ws.workspaceId);
+ emailList = await queries.email.getEmailsByAgent(db, agentId, ws.workspaceId, status);
}
return writeJSON(emailList.map(emailToResponse));
diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsx
index 769d9fb82..2c8f3c953 100644
--- a/src/web/src/components/app-sidebar.tsx
+++ b/src/web/src/components/app-sidebar.tsx
@@ -37,14 +37,7 @@ export function AppSidebar() {
<nav className="flex h-full w-14 flex-col items-center py-2 gap-0.5">
{/* Top — logo */}
<div className="pb-2 border-b border-border/50 mb-1">
- <div
- role="button"
- tabIndex={0}
- title="Home"
- onClick={() => router.push(`${prefix}/home`)}
- onKeyDown={(e) => { if (e.key === "Enter") router.push(`${prefix}/home`); }}
- className="flex shrink-0 items-center justify-center size-10 cursor-pointer transition-opacity hover:opacity-70"
- >
+ <div className="flex shrink-0 items-center justify-center size-10">
<Logo size="sm" iconOnly />
</div>
</div>
diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsx
index b07c27907..424a5780b 100644
--- a/src/web/src/components/task-stream.tsx
+++ b/src/web/src/components/task-stream.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useRef, useEffect } from "react";
+import { useMemo, useRef, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import type { TaskMessage } from "@alook/shared";
@@ -196,6 +196,75 @@ function ThinkingBlock({ item }: { item: ThinkingItem }) {
);
}
+/* ── AnimatedNumber (slot-style slide) ── */
+
+function AnimatedNumber({ value }: { value: number }) {
+ const prevRef = useRef(value);
+ const [display, setDisplay] = useState({ current: value, previous: null as number | null });
+ const [phase, setPhase] = useState<"idle" | "animating">("idle");
+
+ useEffect(() => {
+ if (value === prevRef.current) return;
+ const prev = prevRef.current;
+ prevRef.current = value;
+
+ // Start animation: show both old (will slide up) and new (will slide in from below)
+ setDisplay({ current: value, previous: prev });
+ // Force a frame so the initial position renders before transition kicks in
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ setPhase("animating");
+ });
+ });
+
+ const timer = setTimeout(() => {
+ setPhase("idle");
+ setDisplay((d) => ({ ...d, previous: null }));
+ }, 300);
+ return () => clearTimeout(timer);
+ }, [value]);
+
+ return (
+ <span
+ style={{
+ display: "inline-block",
+ position: "relative",
+ overflow: "hidden",
+ height: "1.2em",
+ lineHeight: "1.2em",
+ verticalAlign: "bottom",
+ }}
+ >
+ {/* Old number — starts at 0, slides to -100% */}
+ {display.previous !== null && (
+ <span
+ style={{
+ display: "block",
+ position: "absolute",
+ inset: "0",
+ transition: phase === "animating" ? "transform 250ms ease-out, opacity 250ms ease-out" : "none",
+ transform: phase === "animating" ? "translateY(-100%)" : "translateY(0)",
+ opacity: phase === "animating" ? 0 : 1,
+ }}
+ >
+ {display.previous}
+ </span>
+ )}
+ {/* New number — starts at +100%, slides to 0 */}
+ <span
+ style={{
+ display: "block",
+ transition: phase === "animating" ? "transform 250ms ease-out, opacity 250ms ease-out" : "none",
+ transform: display.previous !== null && phase !== "animating" ? "translateY(100%)" : "translateY(0)",
+ opacity: display.previous !== null && phase !== "animating" ? 0 : 1,
+ }}
+ >
+ {display.current}
+ </span>
+ </span>
+ );
+}
+
/* ── TaskStream ── */
export function TaskStream({
@@ -238,7 +307,7 @@ export function TaskStream({
{/* Tool stream zone — foldable, height-limited, scrollable */}
{toolItems.length > 0 && (
- <details open={isRunning || undefined} className="group/stream">
+ <details className="group/stream">
<summary
className={cn(
"flex items-center gap-2 py-1 cursor-pointer select-none",
@@ -248,7 +317,10 @@ export function TaskStream({
)}
>
<ChevronRight className="size-3 shrink-0 text-muted-foreground/60 transition-transform duration-150 group-open/stream:rotate-90" />
- <span>{toolItems.length} step{toolItems.length !== 1 ? "s" : ""}</span>
+ {isRunning && (
+ <span className="size-1.5 rounded-full bg-primary animate-pulse shrink-0" />
+ )}
+ <span><AnimatedNumber value={toolItems.length} /> {toolItems.length === 1 ? "step" : "steps"}</span>
</summary>
<div
ref={toolScrollRef}
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index 5ec15349a..a52e128f7 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -59,6 +59,7 @@ export function emailToResponse(e: any) {
forwarded: !!e.forwarded,
html_body: e.htmlBody ?? "",
attachments: JSON.parse(e.attachments || "[]"),
+ status: e.status ?? "unread",
created_at: formatTimestamp(e.createdAt),
};
}