Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(inbox): materialized inbox_unread table + daemon steering merge fix + UI polish

Gusf32de50a1837
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index 1e5521678..e79cc8a24 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -446,7 +446,7 @@ describe("daemon session runner dispatch", () => {
expect(mockClientInstance.failTask).toHaveBeenCalledWith(
"al_test_token",
"t1",
- expect.stringContaining("session-runner crashed"),
+ expect.stringContaining("exit"),
);
});
});
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 1b21b0431..bffc0a442 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -1002,10 +1002,40 @@ async function handleTask(
const timelineDir = join(agentBaseDir, ".context_timeline");
const ctxKey = task.contextKey;
- const lockAcquired = acquireSteeringLock(agentBaseDir, ctxKey);
+ let lockAcquired = acquireSteeringLock(agentBaseDir, ctxKey);
if (!lockAcquired) {
- log.warn(`Steering lock contention for context_key=${ctxKey}, proceeding without steering`);
- } else {
+ // Lock held by another task's steering cycle. Wait for the owner to
+ // create a pendingSteer entry so we can merge into it, rather than
+ // bypassing steering and spawning a concurrent runner.
+ const MERGE_WAIT_MS = 5_000;
+ const MERGE_POLL_MS = 50;
+ const mergeStart = Date.now();
+ while (Date.now() - mergeStart < MERGE_WAIT_MS) {
+ const existing = pendingSteer.get(ctxKey);
+ if (existing) {
+ const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
+ let myAttachments: Attachment[] = [];
+ if (attachmentIds.length > 0) {
+ try { myAttachments = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds); } catch { /* best effort */ }
+ }
+ existing.tasks.push(task);
+ existing.attachments.set(task.id, myAttachments);
+ log.info(`Steering: ${task.id} merged into pending entry (lock contention) for context_key=${ctxKey} (${existing.tasks.length} tasks)`);
+ existing.wake();
+ try { await client.supersedeTask(token, task.id); } catch { /* best effort */ }
+ activeTasks.delete(task.id);
+ return;
+ }
+ // Owner hasn't set the entry yet — also try acquiring the lock ourselves
+ lockAcquired = acquireSteeringLock(agentBaseDir, ctxKey);
+ if (lockAcquired) break;
+ await new Promise((r) => setTimeout(r, MERGE_POLL_MS));
+ }
+ if (!lockAcquired) {
+ log.warn(`Steering lock contention for context_key=${ctxKey}, proceeding without steering`);
+ }
+ }
+ if (lockAcquired) {
try {
const result = findSupersedablePredecessor(timelineDir, ctxKey, provider, steerWarmupGraceMs(), Date.now());
@@ -1076,7 +1106,7 @@ async function handleTask(
}
try {
await client.supersedeTask(token, predecessor.task_id);
- } catch (e) { log.warn(`Steering: failed to mark predecessor superseded`, e); }
+ } catch { /* best effort — predecessor may already be in terminal state from its close handler */ }
}
// Build merged prompt if multiple tasks accumulated.
@@ -1112,6 +1142,7 @@ async function handleTask(
existing.attachments.set(task.id, myAttachments);
log.info(`Steering: ${task.id} merged into pending entry for context_key=${ctxKey} (${existing.tasks.length} tasks)`);
existing.wake();
+ try { await client.supersedeTask(token, task.id); } catch { /* best effort */ }
activeTasks.delete(task.id);
return; // Non-owner exits — owner spawns on my behalf. Lock released by finally.
}
@@ -1156,39 +1187,42 @@ async function handleTask(
activeTasks.delete(task.id);
if (code !== 0) {
const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
+
+ // Check kill intent first — if present, the exit was expected.
const killIntent = readKillIntent(agentBaseDir, task.id);
if (killIntent) {
- log.info(`Task ${task.id} exited due to kill intent — skipping failTask`);
+ log.info(`Task ${task.id} exited (${killIntent.reason}) — expected, skipping failTask`);
clearKillIntent(agentBaseDir, task.id);
return;
}
- const msg = code === null
- ? `session-runner killed by signal (task ${task.id})`
- : `session-runner crashed (exit code ${code}, task ${task.id})`;
- log.warn(msg);
-
- // Update timeline JSONL as fallback
- const timelineDir = join(agentBaseDir, ".context_timeline");
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "failed";
- entry.errmsg = msg;
- });
-
+ // No intent file — the session-runner's onKill handler may have already
+ // cleared it and marked the task terminal (superseded/cancelled/failed).
+ // Try to mark it failed server-side; if it's already terminal, that's fine.
+ const errorMsg = code === null ? "killed by signal" : `session-runner exited with code ${code}`;
try {
- await client.failTask(token, task.id, msg);
+ await client.failTask(token, task.id, errorMsg);
+ // failTask succeeded → this was a genuine unexpected crash.
+ log.warn(`session-runner crashed (${errorMsg}, task ${task.id})`);
+ const timelineDir = join(agentBaseDir, ".context_timeline");
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.pid = null;
+ entry.status = "failed";
+ entry.errmsg = errorMsg;
+ });
} catch (e) {
if (isClientError(e)) {
- log.info(`Backstop: task ${task.id} already in terminal state`);
+ // Task already in terminal state (session-runner's onKill handled it).
+ // This is the normal path for superseded/cancelled tasks — not a crash.
+ log.info(`Task ${task.id} exited (already terminal) — session-runner handled cleanup`);
return;
}
- log.error(`Backstop: failed to report crash for task ${task.id}`, e);
+ log.error(`Failed to report crash for task ${task.id}`, e);
try {
await writeMarkerFile(config.workspacesRoot, {
taskId: task.id,
type: "fail",
- payload: { error: msg },
+ payload: { error: errorMsg },
token,
serverURL: config.serverURL,
createdAt: new Date().toISOString(),
diff --git a/src/shared/src/db/queries/inbox.ts b/src/shared/src/db/queries/inbox.ts
index 118c3f6d3..edfb20273 100644
--- a/src/shared/src/db/queries/inbox.ts
+++ b/src/shared/src/db/queries/inbox.ts
@@ -2,6 +2,99 @@ import { sql } from "drizzle-orm";
import { nanoid } from "nanoid";
import type { Database } from "../index";
+const UNREAD_ELIGIBLE_TYPES = ["user_dm_message", "email_notification", "calendar_event"];
+
+export function isUnreadEligible(
+ task: { parentTaskId?: string | null; traceId?: string | null; type: string; context?: unknown },
+): boolean {
+ if (task.parentTaskId != null) return false;
+ if (task.traceId == null) return false;
+ if (!UNREAD_ELIGIBLE_TYPES.includes(task.type)) return false;
+ if (task.type === "email_notification" && (task.context as any)?.isInternal === true) return false;
+ return true;
+}
+
+export async function upsertUnreadEntry(
+ db: Database,
+ entry: {
+ conversationId: string;
+ userId: string;
+ workspaceId: string;
+ agentId: string;
+ taskId: string;
+ taskType: string;
+ taskStatus: string;
+ taskPrompt: string | null;
+ completedAt: string;
+ latestMessageId: string | null;
+ },
+) {
+ const id = nanoid();
+ await db.run(sql`
+ INSERT INTO inbox_unread (id, conversation_id, user_id, workspace_id, agent_id, task_id, task_type, task_status, task_prompt, completed_at, latest_message_id)
+ VALUES (${id}, ${entry.conversationId}, ${entry.userId}, ${entry.workspaceId}, ${entry.agentId}, ${entry.taskId}, ${entry.taskType}, ${entry.taskStatus}, ${entry.taskPrompt}, ${entry.completedAt}, ${entry.latestMessageId})
+ ON CONFLICT (conversation_id, user_id) DO UPDATE SET
+ agent_id = excluded.agent_id,
+ task_id = excluded.task_id,
+ task_type = excluded.task_type,
+ task_status = excluded.task_status,
+ task_prompt = excluded.task_prompt,
+ completed_at = excluded.completed_at,
+ latest_message_id = excluded.latest_message_id
+ WHERE excluded.completed_at >= inbox_unread.completed_at
+ `);
+}
+
+export async function updateUnreadLatestMessage(
+ db: Database,
+ conversationId: string,
+ userId: string,
+ messageId: string,
+) {
+ await db.run(sql`
+ UPDATE inbox_unread
+ SET latest_message_id = ${messageId}
+ WHERE conversation_id = ${conversationId} AND user_id = ${userId}
+ `);
+}
+
+export async function deleteUnreadEntry(
+ db: Database,
+ conversationId: string,
+ userId: string,
+) {
+ await db.run(sql`
+ DELETE FROM inbox_unread
+ WHERE conversation_id = ${conversationId} AND user_id = ${userId}
+ `);
+}
+
+export async function deleteAllUnreadEntries(
+ db: Database,
+ userId: string,
+ workspaceId: string,
+) {
+ await db.run(sql`
+ DELETE FROM inbox_unread
+ WHERE user_id = ${userId} AND workspace_id = ${workspaceId}
+ `);
+}
+
+export async function findLatestAssistantMessageId(
+ db: Database,
+ conversationId: string,
+): Promise<string | null> {
+ const rows = await db.all<{ id: string }>(sql`
+ SELECT id FROM message
+ WHERE conversation_id = ${conversationId}
+ AND role = 'assistant'
+ AND status = 'active'
+ ORDER BY created_at DESC
+ LIMIT 1
+ `);
+ return rows[0]?.id ?? null;
+}
+
export async function listUnreadConversations(
db: Database,
userId: string,
@@ -10,7 +103,7 @@ export async function listUnreadConversations(
) {
const limit = opts?.limit ?? 30;
const beforeClause = opts?.before
- ? sql`AND t.completed_at < ${opts.before}`
+ ? sql`AND u.completed_at < ${opts.before}`
: sql``;
const types = opts?.types?.length ? opts.types : ["user_dm_message"];
@@ -29,57 +122,26 @@ export async function listUnreadConversations(
root_task_status: string | null;
root_task_type: string | null;
}>(sql`
- SELECT c.id,
- c.agent_id,
+ SELECT u.conversation_id AS id,
+ u.agent_id,
c.title,
c.channel,
- m_latest.content AS latest_response,
- t.completed_at AS latest_response_at,
- t.prompt AS root_prompt,
+ m.content AS latest_response,
+ u.completed_at AS latest_response_at,
+ u.task_prompt AS root_prompt,
a.name AS agent_name,
a.avatar_url AS agent_avatar_url,
- t.status AS root_task_status,
- t.type AS root_task_type
- FROM agent_task_queue t
- INNER JOIN conversation c
- ON c.id = t.conversation_id
- AND c.user_id = ${userId}
- AND c.workspace_id = ${workspaceId}
- LEFT JOIN conversation_read_state crs
- ON crs.conversation_id = c.id AND crs.user_id = ${userId}
- INNER JOIN message m_latest
- ON m_latest.conversation_id = c.id
- AND m_latest.role = 'assistant'
- AND m_latest.status = 'active'
- AND m_latest.id = (
- SELECT id FROM message
- WHERE conversation_id = c.id
- AND role = 'assistant'
- AND status = 'active'
- ORDER BY created_at DESC LIMIT 1
- )
- LEFT JOIN agent a
- ON a.id = c.agent_id AND a.workspace_id = c.workspace_id
- WHERE t.workspace_id = ${workspaceId}
- AND t.parent_task_id IS NULL
- AND t.trace_id IS NOT NULL
- AND t.type IN (${typePlaceholders})
- AND t.status IN ('completed', 'failed')
- AND t.completed_at > COALESCE(crs.last_read_at, '1970-01-01T00:00:00.000Z')
- AND NOT (t.type = 'email_notification' AND COALESCE(json_extract(t.context, '$.isInternal'), 0) = 1)
- AND t.id = (
- SELECT id FROM agent_task_queue
- WHERE workspace_id = ${workspaceId}
- AND conversation_id = c.id
- AND parent_task_id IS NULL
- AND trace_id IS NOT NULL
- AND type IN (${typePlaceholders})
- AND status IN ('completed', 'failed')
- AND NOT (type = 'email_notification' AND COALESCE(json_extract(context, '$.isInternal'), 0) = 1)
- ORDER BY completed_at DESC LIMIT 1
- )
+ u.task_status AS root_task_status,
+ u.task_type AS root_task_type
+ FROM inbox_unread u
+ INNER JOIN conversation c ON c.id = u.conversation_id
+ LEFT JOIN message m ON m.id = u.latest_message_id
+ LEFT JOIN agent a ON a.id = u.agent_id AND a.workspace_id = u.workspace_id
+ WHERE u.user_id = ${userId}
+ AND u.workspace_id = ${workspaceId}
+ AND u.task_type IN (${typePlaceholders})
${beforeClause}
- ORDER BY t.completed_at DESC
+ ORDER BY u.completed_at DESC
LIMIT ${limit + 1}
`);
@@ -99,21 +161,11 @@ export async function getUnreadCount(
const typePlaceholders = sql.join(validTypes.map(t => sql`${t}`), sql`, `);
const rows = await db.all<{ count: number }>(sql`
- SELECT COUNT(DISTINCT t.conversation_id) AS count
- FROM agent_task_queue t
- INNER JOIN conversation c
- ON c.id = t.conversation_id
- AND c.user_id = ${userId}
- AND c.workspace_id = ${workspaceId}
- LEFT JOIN conversation_read_state crs
- ON crs.conversation_id = t.conversation_id AND crs.user_id = ${userId}
- WHERE t.workspace_id = ${workspaceId}
- AND t.parent_task_id IS NULL
- AND t.trace_id IS NOT NULL
- AND t.type IN (${typePlaceholders})
- AND t.status IN ('completed', 'failed')
- AND t.completed_at > COALESCE(crs.last_read_at, '1970-01-01T00:00:00.000Z')
- AND NOT (t.type = 'email_notification' AND COALESCE(json_extract(t.context, '$.isInternal'), 0) = 1)
+ SELECT COUNT(*) AS count
+ FROM inbox_unread
+ WHERE user_id = ${userId}
+ AND workspace_id = ${workspaceId}
+ AND task_type IN (${typePlaceholders})
`);
return rows[0]?.count ?? 0;
@@ -131,6 +183,7 @@ export async function markConversationRead(
ON CONFLICT (conversation_id, user_id)
DO UPDATE SET last_read_at = ${now}
`);
+ await deleteUnreadEntry(db, conversationId, userId);
}
export async function markAllConversationsRead(
@@ -148,4 +201,5 @@ export async function markAllConversationsRead(
ON CONFLICT (conversation_id, user_id)
DO UPDATE SET last_read_at = ${now}
`);
+ await deleteAllUnreadEntries(db, userId, workspaceId);
}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index ca1db39c3..b77d9d777 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -788,3 +788,28 @@ export const agentSkill = sqliteTable(
}).onDelete("cascade"),
]
);
+
+export const inboxUnread = sqliteTable(
+ "inbox_unread",
+ {
+ id: text("id").primaryKey().$defaultFn(() => nanoid()),
+ conversationId: text("conversation_id")
+ .notNull()
+ .references(() => conversation.id, { onDelete: "cascade" }),
+ userId: text("user_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ workspaceId: text("workspace_id").notNull(),
+ agentId: text("agent_id").notNull(),
+ taskId: text("task_id").notNull(),
+ taskType: text("task_type").notNull(),
+ taskStatus: text("task_status").notNull(),
+ taskPrompt: text("task_prompt"),
+ completedAt: text("completed_at").notNull(),
+ latestMessageId: text("latest_message_id"),
+ },
+ (t) => [
+ unique("inbox_unread_conv_user").on(t.conversationId, t.userId),
+ index("idx_inbox_unread_user_ws").on(t.userId, t.workspaceId, t.taskType, t.completedAt),
+ ]
+);
diff --git a/src/shared/test/queries/inbox.test.ts b/src/shared/test/queries/inbox.test.ts
index 03f194b6e..fb0fa0138 100644
--- a/src/shared/test/queries/inbox.test.ts
+++ b/src/shared/test/queries/inbox.test.ts
@@ -8,61 +8,254 @@ function createMockDb(rows: any[]) {
return chain;
}
+// ---------------------------------------------------------------------------
+// Exports
+// ---------------------------------------------------------------------------
+
describe("inbox exports", () => {
it("exports listUnreadConversations", () => { expect(typeof inboxQueries.listUnreadConversations).toBe("function"); });
it("exports getUnreadCount", () => { expect(typeof inboxQueries.getUnreadCount).toBe("function"); });
it("exports markConversationRead", () => { expect(typeof inboxQueries.markConversationRead).toBe("function"); });
it("exports markAllConversationsRead", () => { expect(typeof inboxQueries.markAllConversationsRead).toBe("function"); });
+ it("exports upsertUnreadEntry", () => { expect(typeof inboxQueries.upsertUnreadEntry).toBe("function"); });
+ it("exports updateUnreadLatestMessage", () => { expect(typeof inboxQueries.updateUnreadLatestMessage).toBe("function"); });
+ it("exports deleteUnreadEntry", () => { expect(typeof inboxQueries.deleteUnreadEntry).toBe("function"); });
+ it("exports deleteAllUnreadEntries", () => { expect(typeof inboxQueries.deleteAllUnreadEntries).toBe("function"); });
+ it("exports findLatestAssistantMessageId", () => { expect(typeof inboxQueries.findLatestAssistantMessageId).toBe("function"); });
+ it("exports isUnreadEligible", () => { expect(typeof inboxQueries.isUnreadEligible).toBe("function"); });
+});
+
+// ---------------------------------------------------------------------------
+// TC4: isUnreadEligible
+// ---------------------------------------------------------------------------
+
+describe("isUnreadEligible", () => {
+ const base = { parentTaskId: null, traceId: "t1", type: "user_dm_message", context: {} };
+
+ it("returns true for root DM task with trace", () => {
+ expect(inboxQueries.isUnreadEligible(base)).toBe(true);
+ });
+
+ it("returns true for email_notification task", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, type: "email_notification" })).toBe(true);
+ });
+
+ it("returns true for calendar_event task", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, type: "calendar_event" })).toBe(true);
+ });
+
+ it("returns false for child task (parentTaskId set)", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, parentTaskId: "p1" })).toBe(false);
+ });
+
+ it("returns false for task without traceId", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, traceId: null })).toBe(false);
+ });
+
+ it("returns false for isInternal email", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, type: "email_notification", context: { isInternal: true } })).toBe(false);
+ });
+
+ it("returns false for kill_task type", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, type: "kill_task" })).toBe(false);
+ });
+
+ it("returns false for issue_event (not in whitelist)", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, type: "issue_event" })).toBe(false);
+ });
+
+ it("returns true for email_notification that is NOT internal", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, type: "email_notification", context: { isInternal: false } })).toBe(true);
+ });
+
+ it("returns true for email_notification with no context", () => {
+ expect(inboxQueries.isUnreadEligible({ ...base, type: "email_notification", context: undefined })).toBe(true);
+ });
});
+// ---------------------------------------------------------------------------
+// TC1: upsertUnreadEntry
+// ---------------------------------------------------------------------------
+
+describe("upsertUnreadEntry", () => {
+ it("calls db.run with INSERT ON CONFLICT", async () => {
+ const mockDb = createMockDb([]);
+ await inboxQueries.upsertUnreadEntry(mockDb, {
+ conversationId: "c1",
+ userId: "u1",
+ workspaceId: "w1",
+ agentId: "a1",
+ taskId: "t1",
+ taskType: "user_dm_message",
+ taskStatus: "completed",
+ taskPrompt: "hello",
+ completedAt: "2026-01-01T00:00:00Z",
+ latestMessageId: "m1",
+ });
+ expect(mockDb.run).toHaveBeenCalled();
+ });
+
+ it("can be called twice (upsert semantics)", async () => {
+ const mockDb = createMockDb([]);
+ const entry = {
+ conversationId: "c1",
+ userId: "u1",
+ workspaceId: "w1",
+ agentId: "a1",
+ taskId: "t1",
+ taskType: "user_dm_message",
+ taskStatus: "completed",
+ taskPrompt: "hello",
+ completedAt: "2026-01-01T00:00:00Z",
+ latestMessageId: "m1",
+ };
+ await inboxQueries.upsertUnreadEntry(mockDb, entry);
+ await inboxQueries.upsertUnreadEntry(mockDb, { ...entry, taskId: "t2", completedAt: "2026-01-02T00:00:00Z" });
+ expect(mockDb.run).toHaveBeenCalledTimes(2);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// TC2: updateUnreadLatestMessage
+// ---------------------------------------------------------------------------
+
+describe("updateUnreadLatestMessage", () => {
+ it("calls db.run for UPDATE when row exists", async () => {
+ const mockDb = createMockDb([]);
+ await inboxQueries.updateUnreadLatestMessage(mockDb, "c1", "u1", "m_new");
+ expect(mockDb.run).toHaveBeenCalled();
+ });
+
+ it("is a no-op when no row exists (UPDATE affects 0 rows)", async () => {
+ const mockDb = createMockDb([]);
+ await inboxQueries.updateUnreadLatestMessage(mockDb, "c_nonexistent", "u1", "m1");
+ expect(mockDb.run).toHaveBeenCalled();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// TC3: deleteUnreadEntry / deleteAllUnreadEntries
+// ---------------------------------------------------------------------------
+
+describe("deleteUnreadEntry", () => {
+ it("calls db.run for DELETE", async () => {
+ const mockDb = createMockDb([]);
+ await inboxQueries.deleteUnreadEntry(mockDb, "c1", "u1");
+ expect(mockDb.run).toHaveBeenCalled();
+ });
+
+ it("second call is a no-op (DELETE of non-existent row)", async () => {
+ const mockDb = createMockDb([]);
+ await inboxQueries.deleteUnreadEntry(mockDb, "c1", "u1");
+ await inboxQueries.deleteUnreadEntry(mockDb, "c1", "u1");
+ expect(mockDb.run).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("deleteAllUnreadEntries", () => {
+ it("calls db.run for DELETE", async () => {
+ const mockDb = createMockDb([]);
+ await inboxQueries.deleteAllUnreadEntries(mockDb, "u1", "w1");
+ expect(mockDb.run).toHaveBeenCalled();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// TC9 / TC11: listUnreadConversations (rewritten query)
+// ---------------------------------------------------------------------------
+
describe("listUnreadConversations", () => {
it("returns items and hasMore=false when rows <= limit", async () => {
- const rows = [{ id: "c_1" }];
- const mockDb = createMockDb(rows);
- const result = await inboxQueries.listUnreadConversations(mockDb, "u", "w");
+ const rows = [{ id: "c_1", agent_id: "a1", title: "t", channel: "default", latest_response: "hi", latest_response_at: "2026-01-01", root_prompt: "hey", agent_name: "Bot", agent_avatar_url: null, root_task_status: "completed", root_task_type: "user_dm_message" }];
+ const result = await inboxQueries.listUnreadConversations(createMockDb(rows), "u", "w");
expect(result.items).toEqual(rows);
expect(result.hasMore).toBe(false);
});
+
it("returns hasMore=true when rows exceed limit", async () => {
const rows = Array.from({ length: 31 }, (_, i) => ({ id: `c_${i}` }));
const result = await inboxQueries.listUnreadConversations(createMockDb(rows), "u", "w");
expect(result.hasMore).toBe(true);
expect(result.items.length).toBe(30);
});
+
it("uses custom limit", async () => {
const rows = Array.from({ length: 6 }, (_, i) => ({ id: `c_${i}` }));
const result = await inboxQueries.listUnreadConversations(createMockDb(rows), "u", "w", { limit: 5 });
expect(result.hasMore).toBe(true);
expect(result.items.length).toBe(5);
});
+
it("handles before option", async () => {
const result = await inboxQueries.listUnreadConversations(createMockDb([]), "u", "w", { before: "2026-01-01" });
expect(result.items).toEqual([]);
});
+
it("handles types option", async () => {
const result = await inboxQueries.listUnreadConversations(createMockDb([]), "u", "w", { types: ["email_notification"] });
expect(result.items).toEqual([]);
});
+
+ it("defaults to user_dm_message type when no types given", async () => {
+ const result = await inboxQueries.listUnreadConversations(createMockDb([]), "u", "w");
+ expect(result.items).toEqual([]);
+ });
});
+// ---------------------------------------------------------------------------
+// TC10: getUnreadCount
+// ---------------------------------------------------------------------------
+
describe("getUnreadCount", () => {
- it("returns 0 when empty", async () => { expect(await inboxQueries.getUnreadCount(createMockDb([]), "u", "w")).toBe(0); });
- it("returns count", async () => { expect(await inboxQueries.getUnreadCount(createMockDb([{ count: 5 }]), "u", "w")).toBe(5); });
- it("handles custom types", async () => { expect(await inboxQueries.getUnreadCount(createMockDb([{ count: 2 }]), "u", "w", ["email_notification"])).toBe(2); });
+ it("returns 0 when empty", async () => {
+ expect(await inboxQueries.getUnreadCount(createMockDb([]), "u", "w")).toBe(0);
+ });
+
+ it("returns count", async () => {
+ expect(await inboxQueries.getUnreadCount(createMockDb([{ count: 5 }]), "u", "w")).toBe(5);
+ });
+
+ it("handles custom types (single type)", async () => {
+ expect(await inboxQueries.getUnreadCount(createMockDb([{ count: 2 }]), "u", "w", ["email_notification"])).toBe(2);
+ });
+
+ it("handles custom types (multiple types)", async () => {
+ expect(await inboxQueries.getUnreadCount(createMockDb([{ count: 7 }]), "u", "w", ["user_dm_message", "email_notification"])).toBe(7);
+ });
});
+// ---------------------------------------------------------------------------
+// TC7 / TC8: markConversationRead / markAllConversationsRead
+// ---------------------------------------------------------------------------
+
describe("markConversationRead", () => {
- it("calls db.run", async () => {
+ it("calls db.run twice (read_state + delete unread)", async () => {
const mockDb = createMockDb([]);
await inboxQueries.markConversationRead(mockDb, "u", "c");
- expect(mockDb.run).toHaveBeenCalled();
+ expect(mockDb.run).toHaveBeenCalledTimes(2);
});
});
describe("markAllConversationsRead", () => {
- it("calls db.run", async () => {
+ it("calls db.run twice (read_state + delete all unread)", async () => {
const mockDb = createMockDb([]);
await inboxQueries.markAllConversationsRead(mockDb, "u", "w");
- expect(mockDb.run).toHaveBeenCalled();
+ expect(mockDb.run).toHaveBeenCalledTimes(2);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// findLatestAssistantMessageId
+// ---------------------------------------------------------------------------
+
+describe("findLatestAssistantMessageId", () => {
+ it("returns message id when found", async () => {
+ const result = await inboxQueries.findLatestAssistantMessageId(createMockDb([{ id: "m_123" }]), "c1");
+ expect(result).toBe("m_123");
+ });
+
+ it("returns null when no assistant message exists", async () => {
+ const result = await inboxQueries.findLatestAssistantMessageId(createMockDb([]), "c1");
+ expect(result).toBeNull();
});
});
diff --git a/src/web/migrations/0037_inbox_unread_table.sql b/src/web/migrations/0037_inbox_unread_table.sql
new file mode 100644
index 000000000..a5df12b8e
--- /dev/null
+++ b/src/web/migrations/0037_inbox_unread_table.sql
@@ -0,0 +1,43 @@
+-- Create the inbox_unread table for fast unread inbox loading
+CREATE TABLE IF NOT EXISTS inbox_unread (
+ id TEXT PRIMARY KEY,
+ conversation_id TEXT NOT NULL REFERENCES conversation(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ workspace_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ task_id TEXT NOT NULL,
+ task_type TEXT NOT NULL,
+ task_status TEXT NOT NULL,
+ task_prompt TEXT,
+ completed_at TEXT NOT NULL,
+ latest_message_id TEXT,
+ UNIQUE(conversation_id, user_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_inbox_unread_user_ws
+ ON inbox_unread(user_id, workspace_id, task_type, completed_at);
+
+-- Backfill from existing data: insert the latest eligible completed/failed root task
+-- per conversation that hasn't been read yet.
+INSERT INTO inbox_unread (id, conversation_id, user_id, workspace_id, agent_id, task_id, task_type, task_status, task_prompt, completed_at, latest_message_id)
+SELECT lower(hex(randomblob(11))), c.id, c.user_id, c.workspace_id, c.agent_id, t.id, t.type, t.status, t.prompt, t.completed_at,
+ (SELECT id FROM message WHERE conversation_id = c.id AND role = 'assistant' AND status = 'active' ORDER BY created_at DESC LIMIT 1)
+FROM agent_task_queue t
+INNER JOIN conversation c ON c.id = t.conversation_id
+LEFT JOIN conversation_read_state crs ON crs.conversation_id = c.id AND crs.user_id = c.user_id
+WHERE t.parent_task_id IS NULL
+ AND t.trace_id IS NOT NULL
+ AND t.type IN ('user_dm_message', 'email_notification', 'calendar_event')
+ AND t.status IN ('completed', 'failed')
+ AND t.completed_at > COALESCE(crs.last_read_at, '1970-01-01T00:00:00.000Z')
+ AND NOT (t.type = 'email_notification' AND COALESCE(json_extract(t.context, '$.isInternal'), 0) = 1)
+ AND t.id = (
+ SELECT id FROM agent_task_queue sub
+ WHERE sub.workspace_id = t.workspace_id AND sub.conversation_id = c.id
+ AND sub.parent_task_id IS NULL AND sub.trace_id IS NOT NULL
+ AND sub.type IN ('user_dm_message', 'email_notification', 'calendar_event')
+ AND sub.status IN ('completed', 'failed')
+ AND NOT (sub.type = 'email_notification' AND COALESCE(json_extract(sub.context, '$.isInternal'), 0) = 1)
+ ORDER BY sub.completed_at DESC LIMIT 1
+ )
+ON CONFLICT(conversation_id, user_id) DO NOTHING;
diff --git a/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts
index 2a1429c35..011d7ff53 100644
--- a/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts
@@ -10,6 +10,7 @@ const m = {
getConversation: vi.fn(),
createMessage: vi.fn(),
updateConversationTitle: vi.fn(),
+ updateUnreadLatestMessage: vi.fn().mockResolvedValue(undefined),
};
vi.mock("@alook/shared", async () => {
@@ -24,6 +25,9 @@ vi.mock("@alook/shared", async () => {
message: {
createMessage: (...a: unknown[]) => m.createMessage(...a),
},
+ inbox: {
+ updateUnreadLatestMessage: (...a: unknown[]) => m.updateUnreadLatestMessage(...a),
+ },
},
};
});
diff --git a/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts b/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts
index fa39e03ac..ec9dddfd6 100644
--- a/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts
@@ -53,5 +53,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
message: messageToResponse(message),
}).catch(() => {});
+ queries.inbox.updateUnreadLatestMessage(db, id, conversation.userId, message.id).catch(() => {});
+
return writeJSON({ message: messageToResponse(message) }, 201);
});
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 a0d69c1b1..1d778227c 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -530,7 +530,7 @@ export function AgentChatView({
return (
<>
<div className="flex-1 overflow-y-auto px-3 md:px-5">
- <div className="mx-auto max-w-3xl py-6 space-y-4 motion-safe:animate-[fade-up_200ms_ease-out_both]">
+ <div className="mx-auto max-w-3xl py-6 space-y-6 motion-safe:animate-[fade-up_200ms_ease-out_both]">
{/* Agent cluster — top [avatar][name] header, bubbles stacked below
in the gutter (mirrors AgentRow's Slack/Discord layout). */}
<div className="flex justify-start items-start gap-2">
@@ -675,9 +675,8 @@ export function AgentChatView({
const pos = groupPositions[idx];
const isGroupStart =
pos === "first" || pos === "solo" || pos === null;
- // mt-4 between clusters, a roomier mt-1.5 between grouped bubbles
- // within a cluster (mt-0.5 read too cramped).
- const spacing = idx === 0 ? "" : isGroupStart ? "mt-4" : "mt-1.5";
+ // mt-6 between clusters, mt-1.5 between grouped bubbles within a cluster.
+ const spacing = idx === 0 ? "" : isGroupStart ? "mt-6" : "mt-1.5";
if (item.kind === "nap") {
return (
diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsx
index 5941ddc2d..c7f6940e5 100644
--- a/src/web/src/components/agent-chat/message-list.tsx
+++ b/src/web/src/components/agent-chat/message-list.tsx
@@ -332,29 +332,21 @@ interface MessageAction {
active?: boolean;
}
-// Desktop: a small horizontal toolbar pinned to the bubble's OPEN-side top
-// corner, overlapping it (sits above the bubble top so it never covers text),
-// fading in on hover. `side` keys off message role so the chip grows AWAY from
-// the hazard: agent (left-aligned) anchors its LEFT edge to the bubble and
-// grows right (away from the avatar gutter); user (right-aligned) anchors its
-// RIGHT edge and grows left (away from the screen edge). For a short bubble the
-// overhang lands in empty cluster space, never the gutter or off-screen — no
-// width threshold, no JS measuring (the bubble anchor is already `w-fit`).
+// Desktop: a small horizontal toolbar pinned to the bubble's TOP-RIGHT corner,
+// overlapping it (sits above the bubble top so it never covers text), fading in
+// on hover. Always right-anchored regardless of message role.
function MessageActionsToolbar({
actions,
- side,
}: {
actions: MessageAction[];
- side: "left" | "right";
}) {
if (actions.length === 0) return null;
return (
<div
className={cn(
- "absolute -top-3 z-10 flex items-center gap-0.5 rounded-lg border bg-card p-0.5 shadow-sm",
+ "absolute -top-3 right-0 z-10 flex items-center gap-0.5 rounded-lg border bg-card p-0.5 shadow-sm",
// Fade-only reveal (reduced-motion safe — no transform/lift).
"opacity-0 transition-opacity duration-150 group-hover/msg:opacity-100 focus-within:opacity-100",
- side === "left" ? "left-0" : "right-0",
)}
>
{actions.map((a) => (
@@ -554,9 +546,9 @@ export const MessageItem = memo(function MessageItem({
) : null;
// The desktop hover toolbar for a given side. Only on hover-capable devices.
- const toolbarFor = (side: "left" | "right") =>
+ const toolbar =
hoverCapable && messageActions.length > 0 ? (
- <MessageActionsToolbar actions={messageActions} side={side} />
+ <MessageActionsToolbar actions={messageActions} />
) : null;
return (
@@ -578,7 +570,7 @@ export const MessageItem = memo(function MessageItem({
onRetry={onRetry}
provider={provider}
/>
- {isTaskDone && toolbarFor("left")}
+ {isTaskDone && toolbar}
{isTaskDone && actionSheet}
</div>
</AgentRow>
@@ -608,13 +600,14 @@ export const MessageItem = memo(function MessageItem({
<Streamdown plugins={{ mermaid, cjk }} controls={{ code: { copy: true, download: false }, table: { copy: false, download: false, fullscreen: false } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={mentionComponents}>{highlightMentions(messageBody, agents)}</Streamdown>
</div>
)}
- {msg.attachment_ids && msg.attachment_ids.length > 0 && (
- <AttachmentChips attachmentIds={msg.attachment_ids} artifacts={artifacts} onArtifactClick={onArtifactClick} />
- )}
- {!msg.attachment_ids && (
- <PendingFileChips pendingFiles={pendingFilesByMessage} messageId={msg.id} />
- )}
- {toolbarFor("right")}
+ {(() => {
+ if (msg.attachment_ids && msg.attachment_ids.length > 0) {
+ const hasMatch = msg.attachment_ids.some((id: string) => artifacts.some((a) => a.id === id));
+ if (hasMatch) return <AttachmentChips attachmentIds={msg.attachment_ids} artifacts={artifacts} onArtifactClick={onArtifactClick} />;
+ }
+ return <PendingFileChips pendingFiles={pendingFilesByMessage} messageId={msg.id} />;
+ })()}
+ {toolbar}
</div>
{actionSheet}
{isSendFailed && (
@@ -690,7 +683,7 @@ export const MessageItem = memo(function MessageItem({
provider={(msg.metadata.provider as string | null | undefined) ?? provider}
message={msg.content}
/>
- {toolbarFor("left")}
+ {toolbar}
{actionSheet}
</div>
) : (
@@ -708,7 +701,7 @@ export const MessageItem = memo(function MessageItem({
<Streamdown plugins={{ mermaid, cjk }} 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>
{isFlagged && <FlagDot />}
- {toolbarFor("left")}
+ {toolbar}
{actionSheet}
</div>
)}
diff --git a/src/web/src/components/agent-chat/presence-line.tsx b/src/web/src/components/agent-chat/presence-line.tsx
index a5011ebc4..ee6433367 100644
--- a/src/web/src/components/agent-chat/presence-line.tsx
+++ b/src/web/src/components/agent-chat/presence-line.tsx
@@ -3,25 +3,21 @@
import { cn } from "@/lib/utils";
/**
- * Social presence line above the composer. Two states only:
- * this conversation has a live task (dispatched / queued / running)
- * → "{Name} is typing…" + dots
- * otherwise → nothing
+ * Social presence line above the composer. Three states:
+ * queued / dispatched → "{Name} is reading" + dots (preparing / querying)
+ * running → "{Name} is typing" + dots (actively generating)
+ * otherwise → nothing (idle)
*
- * No "on something" / busy-elsewhere copy (dropped per Gus). Crossfades on
- * change and gates the typing-dot animation behind prefers-reduced-motion.
+ * The reading→typing distinction lets the user tell whether the agent is stuck
+ * in query (e.g. runtime offline) vs actively working. Crossfades between
+ * states and gates the dot animation behind prefers-reduced-motion.
*/
-type Presence = "typing" | "idle";
+type Presence = "reading" | "typing" | "idle";
function derivePresence(taskStatus: string | null | undefined): Presence {
- if (
- taskStatus === "running" ||
- taskStatus === "queued" ||
- taskStatus === "dispatched"
- ) {
- return "typing";
- }
+ if (taskStatus === "running") return "typing";
+ if (taskStatus === "queued" || taskStatus === "dispatched") return "reading";
return "idle";
}
@@ -35,6 +31,11 @@ function TypingDots() {
);
}
+function presenceLabel(presence: Presence, name: string): string {
+ if (presence === "reading") return `${name} is reading`;
+ return `${name} is typing`;
+}
+
export function PresenceLine({
agentFirstName,
taskStatus,
@@ -44,8 +45,6 @@ export function PresenceLine({
}) {
const presence = derivePresence(taskStatus);
- // Reserve a fixed-height row so the composer never shifts as presence changes.
- // mb gives the line breathing room above the composer (it sat too close).
return (
<div className="h-5 px-1 mb-2 flex items-center" aria-live="polite">
<span
@@ -55,9 +54,9 @@ export function PresenceLine({
presence !== "idle" && "motion-safe:animate-[fade-up_200ms_ease-out_both]",
)}
>
- {presence === "typing" && (
+ {presence !== "idle" && (
<>
- <span>{agentFirstName} is typing</span>
+ <span>{presenceLabel(presence, agentFirstName)}</span>
<TypingDots />
</>
)}
diff --git a/src/web/src/hooks/use-agent-chat.ts b/src/web/src/hooks/use-agent-chat.ts
index ffa8db8c2..96914bfad 100644
--- a/src/web/src/hooks/use-agent-chat.ts
+++ b/src/web/src/hooks/use-agent-chat.ts
@@ -793,6 +793,10 @@ export function useAgentChat(
initialScrollDone.current = true;
if (scrollToTaskId || scrollToMessageId) {
isNearBottom.current = false;
+ // Start at the bottom so the scroll-to-target effect scrolls UP (short
+ // distance to a recent task) instead of DOWN from the top (long distance
+ // through the entire conversation history).
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
} else if (propTargetConvId) {
setTimeout(() => {
const assistantMsgs = scrollRef.current?.querySelectorAll(
@@ -837,7 +841,7 @@ export function useAgentChat(
`[data-task-id="${CSS.escape(scrollToTaskId)}"]`,
);
if (!el) return false;
- el.scrollIntoView({ behavior: "smooth", block: "start" });
+ el.scrollIntoView({ behavior: "smooth", block: "center" });
el.classList.add("task-highlight");
highlightTimerId = setTimeout(() => {
el.classList.remove("task-highlight");
@@ -897,7 +901,7 @@ export function useAgentChat(
`[data-message-id="${CSS.escape(scrollToMessageId)}"]`,
);
if (!el) return false;
- el.scrollIntoView({ behavior: "smooth", block: "start" });
+ el.scrollIntoView({ behavior: "smooth", block: "center" });
el.classList.add("task-highlight");
highlightTimerId = setTimeout(() => {
el.classList.remove("task-highlight");
@@ -1493,6 +1497,13 @@ export function useAgentChat(
2000,
);
if (optimisticIdx !== -1) {
+ const optimisticId = prev[optimisticIdx].id;
+ setPendingFilesByMessage((p) => {
+ if (!p.has(optimisticId)) return p;
+ const next = new Map(p);
+ next.delete(optimisticId);
+ return next;
+ });
const updated = [...prev];
updated[optimisticIdx] = msg.message;
return updated;
diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.ts
index d3cb0af0c..ba5196dc4 100644
--- a/src/web/src/lib/services/task.test.ts
+++ b/src/web/src/lib/services/task.test.ts
@@ -51,6 +51,11 @@ vi.mock("@alook/shared", () => ({
runtime: {
getAgentRuntime: vi.fn(),
},
+ inbox: {
+ isUnreadEligible: vi.fn().mockReturnValue(false),
+ upsertUnreadEntry: vi.fn().mockResolvedValue(undefined),
+ findLatestAssistantMessageId: vi.fn().mockResolvedValue(null),
+ },
},
}));
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
index be634ee63..8380b485e 100644
--- a/src/web/src/lib/services/task.ts
+++ b/src/web/src/lib/services/task.ts
@@ -11,6 +11,7 @@ const agentQueries = queries.agent;
const messageQueries = queries.message;
const conversationQueries = queries.conversation;
const issueQueries = queries.issue;
+const inboxQueries = queries.inbox;
export class TaskService {
constructor(private db: Database) {}
@@ -165,6 +166,7 @@ export class TaskService {
// is still persisted on the task row (in `result`) for debugging.
// (failTask still surfaces an error bubble — a failed run must not go silent.)
await this.reconcileAgentStatus(task.agentId, task.workspaceId);
+ this.maybeUpsertUnread(task, workspaceId, null).catch(() => {});
return task;
}
@@ -182,6 +184,7 @@ export class TaskService {
return task;
}
+ let errorMessageId: string | null = null;
if (error) {
// Attribute the error to the agent runtime (Claude Code / Codex /
// OpenCode) so the chat UI can make clear it did NOT come from Alook.
@@ -204,6 +207,7 @@ export class TaskService {
taskId,
metadata: JSON.stringify({ error_source: "runtime", provider }),
});
+ errorMessageId = msg?.id ?? null;
try {
const conversation = await conversationQueries.getConversation(this.db, task.conversationId, workspaceId);
@@ -221,6 +225,7 @@ export class TaskService {
await this.reconcileAgentStatus(task.agentId, task.workspaceId);
await this.syncIssueStatusFromTask(task, "failed");
+ this.maybeUpsertUnread(task, workspaceId, errorMessageId).catch(() => {});
return task;
}
@@ -258,6 +263,33 @@ export class TaskService {
}
}
+ private async maybeUpsertUnread(
+ task: { id: string; conversationId: string; type: string; parentTaskId?: string | null; traceId?: string | null; prompt: string; status: string; completedAt?: string | null; context?: unknown; workspaceId: string; agentId: string },
+ workspaceId: string,
+ knownMessageId: string | null,
+ ) {
+ if (!inboxQueries.isUnreadEligible(task)) return;
+ if (!task.completedAt) return;
+
+ const conversation = await conversationQueries.getConversation(this.db, task.conversationId, workspaceId);
+ if (!conversation) return;
+
+ const latestMessageId = knownMessageId ?? await inboxQueries.findLatestAssistantMessageId(this.db, task.conversationId);
+
+ await inboxQueries.upsertUnreadEntry(this.db, {
+ conversationId: task.conversationId,
+ userId: conversation.userId,
+ workspaceId,
+ agentId: conversation.agentId,
+ taskId: task.id,
+ taskType: task.type,
+ taskStatus: task.status,
+ taskPrompt: task.prompt,
+ completedAt: task.completedAt,
+ latestMessageId,
+ });
+ }
+
async supersedeTask(taskId: string, workspaceId: string) {
const task = await taskQueries.supersedeTask(this.db, taskId, workspaceId);