Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(chat): IM-chat rework — drop follow-up buffer, add agent-link up… (#267)

Gustavo Yead0adf585136
diff --git a/PRODUCT.md b/PRODUCT.md
new file mode 100644
index 000000000..dfea7a626
--- /dev/null
+++ b/PRODUCT.md
@@ -0,0 +1 @@
+read @DESIGN.md
\ No newline at end of file
diff --git a/src/cli/commands/agent.ts b/src/cli/commands/agent.ts
index c949ce85e..d00e8a023 100644
--- a/src/cli/commands/agent.ts
+++ b/src/cli/commands/agent.ts
@@ -76,5 +76,86 @@ export function agentCommand(): Command {
}
});
+ cmd
+ .command("link")
+ .description("Set (create-or-replace) the relationship with an existing colleague agent")
+ .option("--agent_id <id>", "Calling agent ID (or set ALOOK_AGENT_ID env var)")
+ .option("--to <handleOrId>", "Target agent: email handle (coder / [email protected]) or agent id (ag_...)")
+ .option("--relationship <text>", "Relationship/delegation instruction for the link")
+ .option("--relationship-file <path>", "Read relationship from a file")
+ .option("--json", "Output as JSON")
+ .action(async (opts, command) => {
+ const relationship = readField(
+ { inline: opts.relationship, file: opts.relationshipFile },
+ "relationship",
+ "relationship-file",
+ );
+ if (!relationship) {
+ console.error("Error: --relationship or --relationship-file is required");
+ process.exit(1);
+ }
+
+ const to = opts.to as string | undefined;
+ if (!to) {
+ console.error("Error: --to <handleOrId> is required");
+ process.exit(1);
+ }
+
+ const agentId = resolveAgentId(opts);
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ type AgentInfo = { id: string; name: string; email_handle: string | null };
+
+ try {
+ // Resolve target to an agent id. ag_-prefixed values are ids; anything
+ // else is treated as an email handle (domain stripped) and resolved via
+ // GET /api/agents, which returns id + email_handle for each agent.
+ let targetAgentId: string;
+ let agents: AgentInfo[] | null = null;
+ if (to.startsWith("ag_")) {
+ targetAgentId = to;
+ } else {
+ const handle = to.split("@")[0].toLowerCase();
+ agents = await client.getJSON<AgentInfo[]>("/api/agents");
+ const match = agents.find((a) => (a.email_handle || "").toLowerCase() === handle);
+ if (!match) {
+ console.error(`Error: no agent with handle '${handle}' in this workspace`);
+ process.exit(1);
+ }
+ targetAgentId = match.id;
+ }
+
+ const res = await client.putJSON<{
+ id: string;
+ source_agent_id: string;
+ target_agent_id: string;
+ instruction: string;
+ created: boolean;
+ }>(`/api/agent-links?agentId=${encodeURIComponent(agentId)}`, {
+ target_agent_id: targetAgentId,
+ instruction: relationship,
+ });
+
+ if (opts.json) return printJSON(res);
+
+ // Best-effort friendly labels; fall back to ids if names aren't handy.
+ if (!agents) {
+ try {
+ agents = await client.getJSON<AgentInfo[]>("/api/agents");
+ } catch {
+ agents = [];
+ }
+ }
+ const label = (id: string) => agents!.find((a) => a.id === id)?.name || id;
+ const meLabel = label(agentId);
+ const targetLabel = label(targetAgentId);
+ console.log(`Linked ${meLabel} <-> ${targetLabel} (${res.created ? "created" : "updated"})`);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
return cmd;
}
diff --git a/src/cli/commands/sync.test.ts b/src/cli/commands/sync.test.ts
new file mode 100644
index 000000000..f5e8783a0
--- /dev/null
+++ b/src/cli/commands/sync.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it, vi, afterEach } from "vitest";
+import { syncCommand } from "./sync";
+
+describe("syncCommand", () => {
+ const cmd = syncCommand();
+
+ it("registers sync subcommands (upload-artifact + send-dm)", () => {
+ const names = cmd.commands.map((c) => c.name());
+ expect(names).toContain("upload-artifact");
+ expect(names).toContain("send-dm");
+ });
+
+ it("send-dm: --agent_id and --conversation_id are optional (env fallback)", () => {
+ const sub = cmd.commands.find((c) => c.name() === "send-dm")!;
+ const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
+ const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
+ expect(mandatory).toEqual([]); // nothing required at the flag level
+ const longs = opts.map((o) => o.long);
+ expect(longs).toContain("--message");
+ expect(longs).toContain("--message-file");
+ expect(longs).toContain("--conversation_id");
+ expect(longs).toContain("--agent_id");
+ });
+
+ describe("send-dm behavior", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete process.env.ALOOK_CONVERSATION_ID;
+ });
+
+ function runSendDm(args: string[]) {
+ // Throw on exit so we can assert it was hit without actually exiting.
+ const exit = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
+ throw new Error(`exit:${code}`);
+ }) as never);
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ let thrown: Error | null = null;
+ try {
+ // parseAsync runs the action; commander dispatches to the subcommand.
+ return { promise: syncCommand().parseAsync(["node", "alook", "send-dm", ...args]), exit, errSpy };
+ } catch (e) {
+ thrown = e as Error;
+ return { thrown, exit, errSpy };
+ }
+ }
+
+ it("TC2: --message and --message-file together → error, exit 1", async () => {
+ const { promise, errSpy } = runSendDm([
+ "--message", "hi",
+ "--message-file", "/tmp/does-not-matter",
+ ]);
+ await expect(promise).rejects.toThrow("exit:1");
+ expect(errSpy).toHaveBeenCalledWith(
+ expect.stringContaining("mutually exclusive"),
+ );
+ });
+
+ it("TC3: no conversation id (no env, no flag) → error, exit 1", async () => {
+ delete process.env.ALOOK_CONVERSATION_ID;
+ const { promise, errSpy } = runSendDm(["--message", "hello"]);
+ await expect(promise).rejects.toThrow("exit:1");
+ expect(errSpy).toHaveBeenCalledWith(
+ expect.stringContaining("no conversation id"),
+ );
+ });
+
+ it("empty --message → error, exit 1", async () => {
+ process.env.ALOOK_CONVERSATION_ID = "c1";
+ const { promise, errSpy } = runSendDm(["--message", " "]);
+ await expect(promise).rejects.toThrow("exit:1");
+ expect(errSpy).toHaveBeenCalledWith(
+ expect.stringContaining("must not be empty"),
+ );
+ });
+ });
+});
diff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.ts
index 8f6db100a..b5709d7a6 100644
--- a/src/cli/commands/sync.ts
+++ b/src/cli/commands/sync.ts
@@ -8,7 +8,7 @@ import { resolveClientOpts } from "../lib/resolve-client.js";
import { guessContentType } from "../lib/file-utils.js";
export function syncCommand(): Command {
- const cmd = new Command("sync").description("File sync utilities");
+ const cmd = new Command("sync").description("Sync info with the user (files, messages)");
cmd
.command("upload-artifact")
@@ -53,5 +53,56 @@ export function syncCommand(): Command {
}
});
+ cmd
+ .command("send-dm")
+ .description("Send a message to the user in the current conversation (the agent's voice)")
+ .option("--agent_id <id>", "Agent ID")
+ .option("--conversation_id <id>", "Conversation ID (defaults to $ALOOK_CONVERSATION_ID)")
+ .option("--message <text>", "Message body")
+ .option("--message-file <path>", "Read message body from a file")
+ .action(async (opts, command) => {
+ if (opts.message && opts.messageFile) {
+ console.error("Error: --message and --message-file are mutually exclusive");
+ process.exit(1);
+ }
+
+ let content: string;
+ if (opts.messageFile) {
+ try {
+ content = readFileSync(opts.messageFile, "utf-8");
+ } catch (err) {
+ console.error(`Error: cannot read file "${opts.messageFile}": ${(err as Error).message}`);
+ process.exit(1);
+ }
+ } else {
+ content = opts.message ?? "";
+ }
+ if (!content.trim()) {
+ console.error("Error: --message or --message-file is required (and must not be empty)");
+ process.exit(1);
+ }
+
+ const conversationId = opts.conversation_id || process.env.ALOOK_CONVERSATION_ID;
+ if (!conversationId) {
+ console.error("Error: no conversation id (set --conversation_id or $ALOOK_CONVERSATION_ID)");
+ process.exit(1);
+ }
+
+ const agentId = resolveAgentId(opts);
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, { agentId });
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ try {
+ const result = await client.postJSON<Record<string, unknown>>(
+ `/api/daemon/conversations/${encodeURIComponent(conversationId)}/messages`,
+ { content, task_id: process.env.ALOOK_TASK_ID || undefined }
+ );
+ printJSON(result);
+ } catch (err) {
+ console.error(`Error sending message: ${(err as Error).message}`);
+ process.exit(1);
+ }
+ });
+
return cmd;
}
diff --git a/src/cli/daemon/agent/__tests__/opencode.test.ts b/src/cli/daemon/agent/__tests__/opencode.test.ts
index e0b1716df..7892c2ae1 100644
--- a/src/cli/daemon/agent/__tests__/opencode.test.ts
+++ b/src/cli/daemon/agent/__tests__/opencode.test.ts
@@ -142,6 +142,22 @@ describe("OpenCodeBackend", () => {
expect(messages).toContainEqual({ type: "error", content: "something broke" });
});
+ it("marks the run failed on an error event (so failTask persists the error)", async () => {
+ // Regression guard: an `error` event must set result.status="failed" — the
+ // same as codex and opencode's done/spawn-error branches. Otherwise the run
+ // ends "completed", failTask never runs, and the error is lost on reload.
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "error", message: "boom on run" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 1);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toBe("boom on run");
+ });
+
it("error event with content fallback works", async () => {
const session = backend.execute("hello", { cwd: "/tmp" });
const mock = getMock();
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
index 33068771a..a041a2f7f 100644
--- a/src/cli/daemon/agent/opencode.ts
+++ b/src/cli/daemon/agent/opencode.ts
@@ -169,6 +169,11 @@ export class OpenCodeBackend implements AgentBackend {
case "error": {
const content = (event.message as string) || (event.content as string) || (part?.error as string) || "";
lastError = content;
+ // Mark the run failed (matches codex.ts + the done/spawn-error branches
+ // below). Without this the run ends "completed", failTask never runs,
+ // no assistant error message is persisted, and the error is lost on
+ // reload — it only ever showed via the live task.messages broadcast.
+ resultStatus = "failed";
pushMessage({ type: "error", content });
turnDone();
break;
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index b49f32ca3..1e5521678 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -93,14 +93,31 @@ vi.mock("./update-handler.js", () => ({
}));
const mockFindRunningPidByTaskId = vi.fn();
-const mockFindRunningEntryByContextKey = vi.fn(() => null);
+const mockFindSupersedablePredecessor = vi.fn<(...args: any[]) => any>(() => null);
const mockUpdateEntry = vi.fn();
vi.mock("./execenv/timeline.js", () => ({
findRunningPidByTaskId: (...args: any[]) => mockFindRunningPidByTaskId(...(args as any[])),
- findRunningEntryByContextKey: (...args: any[]) => mockFindRunningEntryByContextKey(...(args as any[])),
+ findSupersedablePredecessor: (...args: any[]) => mockFindSupersedablePredecessor(...(args as any[])),
+ steerWarmupGraceMs: () => 30_000,
updateEntry: (...args: any[]) => mockUpdateEntry(...(args as any[])),
}));
+const mockDownloadAttachments = vi.fn<(...args: any[]) => any>(async () => []);
+const mockCleanupAttachments = vi.fn(async () => {});
+vi.mock("./session-runner.js", () => ({
+ writeMarkerFile: vi.fn(),
+ runSession: vi.fn(),
+ downloadAttachments: (...args: any[]) => mockDownloadAttachments(...(args as any[])),
+ cleanupAttachments: (...args: any[]) => mockCleanupAttachments(...(args as any[])),
+}));
+
+const mockBuildPrompt = vi.fn((..._args: any[]) => '{"type":"user_dm_message","instruction":"test"}');
+const mockBuildMergedPrompt = vi.fn((..._args: any[]) => '{"type":"merge_tasks","tasks":[]}');
+vi.mock("./prompt.js", () => ({
+ buildPrompt: (...args: any[]) => mockBuildPrompt(...(args as any[])),
+ buildMergedPrompt: (...args: any[]) => mockBuildMergedPrompt(...(args as any[])),
+}));
+
const mockWriteKillIntent = vi.fn();
const mockReadKillIntent = vi.fn(() => null);
const mockClearKillIntent = vi.fn();
@@ -470,6 +487,249 @@ describe("daemon session runner dispatch", () => {
});
});
+describe("daemon steering with pendingSteer merge", () => {
+ beforeEach(() => {
+ signalHandlers.clear();
+ intervalTimers.length = 0;
+ clearedTimers.length = 0;
+ spawnedChildren.length = 0;
+ nextPid = 50000;
+ vi.clearAllMocks();
+ mockProcessExit.mockImplementation((() => {}) as any);
+ mockOpenSync.mockReturnValue(42);
+ mockFindSupersedablePredecessor.mockReturnValue(null);
+ });
+
+ afterEach(() => {
+ for (const t of intervalTimers) realClearInterval(t);
+ });
+
+ function claimTaskWithContextKey() {
+ const fakeTask = {
+ id: "t_new",
+ agent_id: "a1",
+ runtime_id: "rt1",
+ conversation_id: "c1",
+ workspace_id: "ws1",
+ prompt: "newcomer",
+ status: "dispatched",
+ priority: 0,
+ context_key: "conv_thread",
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ type: "user_dm_message",
+ result: null,
+ error: null,
+ agent: { name: "Agent 1", instructions: "be helpful" },
+ };
+ let claimed = false;
+ mockClientInstance.poll.mockImplementation((async () => {
+ if (!claimed) {
+ claimed = true;
+ return { tasks: [fakeTask], evicted: false };
+ }
+ return { tasks: [], evicted: false };
+ }) as any);
+ return fakeTask;
+ }
+
+ // TC7 — the bug: predecessor pending (not started) → newcomer waits, then
+ // predecessor starts (agent_started flips) → newcomer supersedes + spawns.
+ it("waits for a warming-up predecessor, then supersedes once it starts", async () => {
+ claimTaskWithContextKey();
+ const pending = { pending: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" } };
+ const started = { entry: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" }, reason: "agent-started" };
+ // First call (initial classification) → pending; second call (re-classify in loop) → started.
+ mockFindSupersedablePredecessor
+ .mockReturnValueOnce(pending)
+ .mockReturnValueOnce(started);
+ mockFindRunningPidByTaskId.mockReturnValue(null);
+
+ await startDaemon();
+ // Wait for poll + wait loop + supersede + spawn.
+ await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 2000 });
+
+ expect(mockWriteKillIntent).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ reason: "superseded", targetTaskId: "t_warmup", successorTaskId: "t_new" }),
+ );
+ expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_warmup");
+ });
+
+ // TC8 — normal supersede unchanged: agent-started predecessor → kill + supersede immediately, spawn.
+ it("supersedes a genuinely-running predecessor immediately (no wait)", async () => {
+ claimTaskWithContextKey();
+ mockFindSupersedablePredecessor.mockReturnValue({
+ entry: { task_id: "t_live", pid: 40001, context_key: "conv_thread" },
+ reason: "agent-started",
+ });
+ mockFindRunningPidByTaskId.mockReturnValue(null);
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(mockWriteKillIntent).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ reason: "superseded", targetTaskId: "t_live", successorTaskId: "t_new" }),
+ );
+ expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_live");
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ // TC9 — stale fallback: predecessor not started but stale → supersede immediately, spawn.
+ it("supersedes a stale (crashed-warmup) predecessor immediately", async () => {
+ claimTaskWithContextKey();
+ mockFindSupersedablePredecessor.mockReturnValue({
+ entry: { task_id: "t_stale", pid: 40002, context_key: "conv_thread" },
+ reason: "stale",
+ });
+ mockFindRunningPidByTaskId.mockReturnValue(null);
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_stale");
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ // TC10 — predecessor vanishes during wait → newcomer spawns, no kill intent.
+ it("spawns without kill intent when predecessor vanishes during the wait", async () => {
+ claimTaskWithContextKey();
+ const pending = { pending: { task_id: "t_vanish", pid: 40003, context_key: "conv_thread" } };
+ // First call → pending; second call (re-classify) → null (predecessor gone).
+ mockFindSupersedablePredecessor
+ .mockReturnValueOnce(pending)
+ .mockReturnValueOnce(null);
+
+ await startDaemon();
+ await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 2000 });
+
+ expect(mockWriteKillIntent).not.toHaveBeenCalled();
+ expect(mockClientInstance.supersedeTask).not.toHaveBeenCalled();
+ });
+
+ // TC12 — no contextKey → never enters the steering/wait path.
+ it("does not enter the steering path for a task without a context_key", async () => {
+ const fakeTask = {
+ id: "t_noctx",
+ agent_id: "a1",
+ runtime_id: "rt1",
+ conversation_id: "c1",
+ workspace_id: "ws1",
+ prompt: "no ctx",
+ status: "dispatched",
+ priority: 0,
+ context_key: null,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ type: "user_dm_message",
+ result: null,
+ error: null,
+ agent: { name: "Agent 1", instructions: "be helpful" },
+ };
+ let claimed = false;
+ mockClientInstance.poll.mockImplementation((async () => {
+ if (!claimed) { claimed = true; return { tasks: [fakeTask], evicted: false }; }
+ return { tasks: [], evicted: false };
+ }) as any);
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(mockFindSupersedablePredecessor).not.toHaveBeenCalled();
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ // TC15 — lock is released between wait ticks (not held across sleep).
+ it("releases the steering lock between wait ticks so concurrent tasks are not bypassed", async () => {
+ claimTaskWithContextKey();
+ const pending = { pending: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" } };
+ const started = { entry: { task_id: "t_warmup", pid: 40000, context_key: "conv_thread" }, reason: "agent-started" };
+ mockFindSupersedablePredecessor
+ .mockReturnValueOnce(pending)
+ .mockReturnValueOnce(started);
+ mockFindRunningPidByTaskId.mockReturnValue(null);
+
+ await startDaemon();
+ await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 2000 });
+
+ // The lock was released at least once INSIDE the wait loop (before the sleep),
+ // then re-acquired for the next classification. The initial acquire + loop
+ // release + loop re-acquire means release was called MORE than just the
+ // outer finally. Verify release was called at least twice (once inside loop,
+ // once in finally).
+ expect(mockReleaseSteeringLock.mock.calls.length).toBeGreaterThanOrEqual(2);
+ // And re-acquire was called inside the loop (beyond the initial acquire).
+ expect(mockAcquireSteeringLock.mock.calls.length).toBeGreaterThanOrEqual(2);
+ });
+
+ // TC11 — MERGE: B (owner) waits, C merges into entry, A starts → 1 spawn with merged prompt.
+ // Assert: both spawn, C (newest) spawns LAST, supersede order is A then B.
+ it("merges a second task and spawns once with merged prompt", async () => {
+ const fakeB = {
+ id: "t_B", agent_id: "a1", runtime_id: "rt1", conversation_id: "c1",
+ workspace_id: "ws1", prompt: "B", status: "dispatched", priority: 0,
+ context_key: "conv_thread", dispatched_at: null, started_at: null,
+ completed_at: null, created_at: "2026-01-01T00:00:01Z",
+ type: "user_dm_message", result: null, error: null,
+ agent: { name: "Agent 1", instructions: "be helpful" },
+ };
+ const fakeC = {
+ id: "t_C", agent_id: "a1", runtime_id: "rt1", conversation_id: "c1",
+ workspace_id: "ws1", prompt: "C", status: "dispatched", priority: 0,
+ context_key: "conv_thread", dispatched_at: null, started_at: null,
+ completed_at: null, created_at: "2026-01-01T00:00:02Z",
+ type: "user_dm_message", result: null, error: null,
+ agent: { name: "Agent 1", instructions: "be helpful" },
+ };
+ let claimed = false;
+ mockClientInstance.poll.mockImplementation((async () => {
+ if (!claimed) { claimed = true; return { tasks: [fakeB, fakeC], evicted: false }; }
+ return { tasks: [], evicted: false };
+ }) as any);
+
+ // B initial → pending A (becomes owner). C initial → pending A (sees entry, merges, returns).
+ // B loop → A started → supersede A + spawn with merged prompt [B,C].
+ const pendingA = { pending: { task_id: "t_A", pid: 39000, context_key: "conv_thread" } };
+ const startedA = { entry: { task_id: "t_A", pid: 39000, context_key: "conv_thread" }, reason: "agent-started" };
+ mockFindSupersedablePredecessor
+ .mockReturnValueOnce(pendingA) // B initial
+ .mockReturnValueOnce(pendingA) // C initial
+ .mockReturnValueOnce(startedA); // B loop re-classify → supersede A
+ mockFindRunningPidByTaskId.mockReturnValue(null);
+
+ await startDaemon();
+ await vi.waitFor(() => { expect(spawn).toHaveBeenCalledTimes(1); }, { timeout: 3000 });
+
+ // Only 1 spawn (owner B spawns for both B and C).
+ expect(spawn).toHaveBeenCalledTimes(1);
+ // buildMergedPrompt called (multi-task entry).
+ expect(mockBuildMergedPrompt).toHaveBeenCalled();
+ // Predecessor A was superseded.
+ expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("al_test_token", "t_A");
+ });
+
+ // TC16 — Map cleanup: after owner spawns, pendingSteer key is deleted.
+ it("cleans up the pendingSteer Map after the owner spawns", async () => {
+ claimTaskWithContextKey();
+ mockFindSupersedablePredecessor.mockReturnValue({
+ entry: { task_id: "t_live", pid: 40001, context_key: "conv_thread" },
+ reason: "agent-started",
+ });
+ mockFindRunningPidByTaskId.mockReturnValue(null);
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(spawn).toHaveBeenCalledTimes(1);
+ // Map cleanup is internal; verified by no errors + successful spawn.
+ });
+});
+
describe("daemon with multi-workspace config", () => {
beforeEach(() => {
signalHandlers.clear();
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index d9d342d5b..1b21b0431 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -2,8 +2,9 @@ import { DaemonClient } from "./client.js";
import { type DaemonConfig, loadDaemonConfig, sessionRunnerLogDir, daemonLogFilePath } from "./config.js";
import { createHealthServer } from "./health.js";
import { detectVersion } from "./agent/index.js";
-import { type Task, type SessionRunnerInput, fromApiTask } from "./types.js";
-import { type MarkerData, writeMarkerFile } from "./session-runner.js";
+import { type Task, type Attachment, type SessionRunnerInput, fromApiTask } from "./types.js";
+import { type MarkerData, writeMarkerFile, downloadAttachments } from "./session-runner.js";
+import { buildPrompt, buildMergedPrompt } from "./prompt.js";
import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
import { createLogger } from "../lib/logger.js";
import { DaemonWsClient } from "./ws-client.js";
@@ -13,7 +14,7 @@ const log = createLogger({ module: "daemon" });
import { cmdPrefix } from "../lib/env.js";
import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";
import { handleCliUpdate, isUpdating, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";
-import { findRunningPidByTaskId, findRunningEntryByContextKey, updateEntry } from "./execenv/timeline.js";
+import { findRunningPidByTaskId, findSupersedablePredecessor, steerWarmupGraceMs, updateEntry, type ContextTimelineEntry } from "./execenv/timeline.js";
import { isAlive, killGraceMs } from "./kill-tree.js";
import {
writeKillIntent,
@@ -53,6 +54,13 @@ interface RuntimeData {
provider: string;
}
+interface PendingEntry {
+ tasks: Task[];
+ attachments: Map<string, Attachment[]>;
+ ownerTaskId: string;
+ wake: () => void;
+}
+
function isCommandAvailable(cmd: string): boolean {
try {
const check = process.platform === "win32" ? `where ${cmd}` : `which ${cmd}`;
@@ -343,6 +351,7 @@ export async function startDaemon(
);
const activeTasks = new Set<string>();
+ const pendingSteer = new Map<string, PendingEntry>();
// Seed known agent IDs from config so we only write on genuinely new ones
const knownAgentIds = new Set<string>(
@@ -441,7 +450,7 @@ export async function startDaemon(
syncAgentId(task.agentId, ws.workspaceId);
activeTasks.add(task.id);
remaining--;
- handleTask(client, config, runtimeIndex, task, ws.token, activeTasks)
+ handleTask(client, config, runtimeIndex, task, ws.token, activeTasks, pendingSteer)
.catch((e) => {
log.error("Task error", e);
activeTasks.delete(task.id);
@@ -530,7 +539,7 @@ export async function startDaemon(
if (!ws) continue;
syncAgentId(task.agentId, ws.workspaceId);
activeTasks.add(task.id);
- handleTask(client, config, runtimeIndex, task, ws.token, activeTasks)
+ handleTask(client, config, runtimeIndex, task, ws.token, activeTasks, pendingSteer)
.catch((e) => { log.error("WS task error", e); activeTasks.delete(task.id); });
}
break;
@@ -607,7 +616,7 @@ export async function startDaemon(
sender: null,
});
activeTasks.add(killTask.id);
- handleTask(client, config, runtimeIndex, killTask, ws.token, activeTasks)
+ handleTask(client, config, runtimeIndex, killTask, ws.token, activeTasks, pendingSteer)
.catch((e) => { log.error("WS kill task error", e); activeTasks.delete(killTask.id); });
}
break;
@@ -914,6 +923,7 @@ async function handleTask(
task: Task,
token: string,
activeTasks: Set<string>,
+ pendingSteer: Map<string, PendingEntry>,
): Promise<void> {
log.info(`Task ${task.id} claimed agent=${task.agentId}`);
@@ -985,61 +995,130 @@ async function handleTask(
const provider = runtimeData.provider;
// --- Steering: supersede predecessor if same context_key + provider ---
+ let promptOverride: string | undefined;
if (task.contextKey) {
const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
cleanupStaleIntents(agentBaseDir);
const timelineDir = join(agentBaseDir, ".context_timeline");
+ const ctxKey = task.contextKey;
- const lockAcquired = acquireSteeringLock(agentBaseDir, task.contextKey);
+ const lockAcquired = acquireSteeringLock(agentBaseDir, ctxKey);
if (!lockAcquired) {
- log.warn(`Steering lock contention for context_key=${task.contextKey}, proceeding without steering`);
+ log.warn(`Steering lock contention for context_key=${ctxKey}, proceeding without steering`);
} else {
try {
- const predecessor = findRunningEntryByContextKey(timelineDir, task.contextKey, provider);
- if (predecessor && predecessor.task_id !== task.id) {
- log.info(`Steering: task ${task.id} supersedes predecessor ${predecessor.task_id} (context_key=${task.contextKey})`);
-
- if (predecessor.pid != null) {
- writeKillIntent(agentBaseDir, {
- reason: "superseded",
- targetTaskId: predecessor.task_id,
- expectedPid: predecessor.pid,
- successorTaskId: task.id,
- });
- try {
- const delivered = await killAndVerify(predecessor.pid);
- log.info(
- delivered
- ? `Steering: terminated predecessor pid=${predecessor.pid}`
- : `Steering: predecessor pid=${predecessor.pid} already exited`,
- );
- } catch (e: unknown) {
- log.warn(`Steering: kill failed for pid=${predecessor.pid}`, e);
+ const result = findSupersedablePredecessor(timelineDir, ctxKey, provider, steerWarmupGraceMs(), Date.now());
+
+ if (result) {
+ // CASE 2: predecessor exists (pending or supersedable) — go through the pendingSteer Map.
+ const existing = pendingSteer.get(ctxKey);
+
+ if (!existing) {
+ // I am the owner (first waiter). Download my attachments, create the entry, run the wait loop.
+ 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 (e) {
+ log.warn(`Steering: failed to download attachments for ${task.id}`, e);
+ }
}
- // Wait for predecessor to stop (poll timeline for up to 15 seconds)
- const waitStart = Date.now();
- const MAX_WAIT_MS = 15_000;
- const POLL_MS = 200;
- while (Date.now() - waitStart < MAX_WAIT_MS) {
- const stillRunning = findRunningPidByTaskId(timelineDir, predecessor.task_id);
- if (stillRunning == null) break;
- await new Promise((r) => setTimeout(r, POLL_MS));
+
+ let ownerWake!: () => void;
+ const ownerSignal = new Promise<void>((resolve) => { ownerWake = resolve; });
+ const entry: PendingEntry = {
+ tasks: [task],
+ attachments: new Map([[task.id, myAttachments]]),
+ ownerTaskId: task.id,
+ wake: ownerWake,
+ };
+ pendingSteer.set(ctxKey, entry);
+
+ // Owner's wait loop: poll predecessor until started/stale/gone.
+ let predecessor = "entry" in result ? result.entry : null;
+ if (!predecessor) {
+ log.info(`Steering: predecessor ${(result as { pending: ContextTimelineEntry }).pending.task_id} warming up; ${task.id} waiting`);
+ const POLL_MS = 200;
+ const MAX_WAIT_MS = steerWarmupGraceMs();
+ const waitStart = Date.now();
+ while (Date.now() - waitStart < MAX_WAIT_MS) {
+ releaseSteeringLock(agentBaseDir, ctxKey);
+ await Promise.race([new Promise((r) => setTimeout(r, POLL_MS)), ownerSignal]);
+ if (!acquireSteeringLock(agentBaseDir, ctxKey)) continue;
+ const r = findSupersedablePredecessor(timelineDir, ctxKey, provider, steerWarmupGraceMs(), Date.now());
+ if (!r) { log.info(`Steering: predecessor vanished; ${task.id} proceeding`); break; }
+ if ("entry" in r) { predecessor = r.entry; break; }
+ }
+ if (!predecessor && Date.now() - waitStart >= MAX_WAIT_MS) {
+ releaseSteeringLock(agentBaseDir, ctxKey);
+ if (acquireSteeringLock(agentBaseDir, ctxKey)) {
+ const finalCheck = findSupersedablePredecessor(timelineDir, ctxKey, provider, 0, Date.now());
+ if (finalCheck && "entry" in finalCheck) predecessor = finalCheck.entry;
+ }
+ }
}
- if (findRunningPidByTaskId(timelineDir, predecessor.task_id) != null) {
- log.warn(`Steering: predecessor pid=${predecessor.pid} did not exit within ${MAX_WAIT_MS}ms, proceeding anyway`);
+
+ // Supersede predecessor if found.
+ if (predecessor && predecessor.task_id !== task.id) {
+ log.info(`Steering: task ${task.id} supersedes predecessor ${predecessor.task_id} (context_key=${ctxKey})`);
+ if (predecessor.pid != null) {
+ writeKillIntent(agentBaseDir, { reason: "superseded", targetTaskId: predecessor.task_id, expectedPid: predecessor.pid, successorTaskId: task.id });
+ try {
+ const delivered = await killAndVerify(predecessor.pid);
+ log.info(delivered ? `Steering: terminated predecessor pid=${predecessor.pid}` : `Steering: predecessor pid=${predecessor.pid} already exited`);
+ } catch (e: unknown) { log.warn(`Steering: kill failed for pid=${predecessor.pid}`, e); }
+ const killWaitStart = Date.now();
+ while (Date.now() - killWaitStart < 15_000) {
+ if (findRunningPidByTaskId(timelineDir, predecessor.task_id) == null) break;
+ await new Promise((r) => setTimeout(r, 200));
+ }
+ }
+ try {
+ await client.supersedeTask(token, predecessor.task_id);
+ } catch (e) { log.warn(`Steering: failed to mark predecessor superseded`, e); }
+ }
+
+ // Build merged prompt if multiple tasks accumulated.
+ const finalEntry = pendingSteer.get(ctxKey);
+ if (finalEntry && finalEntry.tasks.length > 1) {
+ promptOverride = buildMergedPrompt(finalEntry.tasks, finalEntry.attachments);
+ log.info(`Steering: merged ${finalEntry.tasks.length} tasks for context_key=${ctxKey}`);
+ } else if (finalEntry && finalEntry.tasks.length === 1) {
+ const att = finalEntry.attachments.get(task.id);
+ if (att && att.length > 0) {
+ promptOverride = buildPrompt(task, att);
+ }
+ }
+ pendingSteer.delete(ctxKey);
+ } else {
+ // I am NOT the owner — merge my content into the existing entry and exit.
+ 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 (e) { log.warn(`Steering: failed to download attachments for ${task.id}`, e); }
+ }
+
+ // Mark all previous tasks in the entry as superseded server-side (content kept in tasks array).
+ for (const prev of existing.tasks) {
+ if (prev.id !== existing.ownerTaskId) {
+ try { await client.supersedeTask(token, prev.id); } catch { /* best effort */ }
+ }
}
- }
- // Mark predecessor superseded server-side regardless of PID state
- try {
- await client.supersedeTask(token, predecessor.task_id);
- log.info(`Steering: predecessor ${predecessor.task_id} marked superseded`);
- } catch (e) {
- log.warn(`Steering: failed to mark predecessor superseded server-side`, e);
+ existing.tasks.push(task);
+ 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();
+ activeTasks.delete(task.id);
+ return; // Non-owner exits — owner spawns on my behalf. Lock released by finally.
}
}
+ // CASE 1 (null result) falls through: no predecessor → spawn immediately.
} finally {
- releaseSteeringLock(agentBaseDir, task.contextKey);
+ releaseSteeringLock(agentBaseDir, ctxKey);
}
}
}
@@ -1069,6 +1148,7 @@ async function handleTask(
workspacesRoot: config.workspacesRoot,
agentTimeout: config.agentTimeout,
messageInactivityTimeout: config.messageInactivityTimeout,
+ ...(promptOverride && { promptOverride }),
};
const child = spawnSessionRunner(input);
diff --git a/src/cli/daemon/execenv/__tests__/context.test.ts b/src/cli/daemon/execenv/__tests__/context.test.ts
index d9d4cedf2..5c778d6c3 100644
--- a/src/cli/daemon/execenv/__tests__/context.test.ts
+++ b/src/cli/daemon/execenv/__tests__/context.test.ts
@@ -154,6 +154,15 @@ describe("buildInstructionContent memory & format", () => {
expect(content).toContain("### Email command quick reference");
expect(content).toContain("email pull --email_id <EMAIL_ID>");
});
+
+ it("renders the Talking to the user block instructing send-dm", () => {
+ const content = buildInstructionContent(
+ makeTask({ agent: { name: "test", instructions: "", emailHandle: "myagent" } }),
+ );
+ expect(content).toContain("### Talking to the user");
+ expect(content).toContain("texting a colleague");
+ expect(content).toContain("sync send-dm");
+ });
});
describe("contentHash", () => {
diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.ts
index 2e4556531..72e3188c9 100644
--- a/src/cli/daemon/execenv/__tests__/timeline.test.ts
+++ b/src/cli/daemon/execenv/__tests__/timeline.test.ts
@@ -16,7 +16,8 @@ import {
createTimelineEntry,
findResumableSessionByContextKey,
findRunningPidByTaskId,
- findRunningEntryByContextKey,
+ findSupersedablePredecessor,
+ steerWarmupGraceMs,
_todayFilename,
_localISOString,
_filenameForDate,
@@ -536,7 +537,33 @@ describe("timeline", () => {
});
});
- describe("findRunningEntryByContextKey", () => {
+ // TC1 — agent_started round-trips through createTimelineEntry → updateEntry → re-read.
+ describe("agent_started marker round-trip", () => {
+ it("is falsy on a freshly-created entry and true after updateEntry sets it", () => {
+ const entry = createTimelineEntry("t_marker", "do something", TASK_TYPES.USER_DM_MESSAGE);
+ initEntry(dir, entry);
+
+ // Fresh row: marker absent → reads falsy.
+ expect(readEntries()[0].agent_started).toBeFalsy();
+
+ updateEntry(dir, "t_marker", (e) => {
+ e.agent_started = true;
+ });
+
+ // JSONL serialize/parse preserves the new field.
+ expect(readEntries()[0].agent_started).toBe(true);
+ });
+
+ it("a row written without the field reads as falsy", () => {
+ const entry = createTimelineEntry("t_legacy", "legacy row", TASK_TYPES.USER_DM_MESSAGE);
+ // Strip the field entirely to emulate an older/legacy row.
+ delete (entry as Partial<ContextTimelineEntry>).agent_started;
+ initEntry(dir, entry);
+ expect(readEntries()[0].agent_started).toBeFalsy();
+ });
+ });
+
+ describe("findSupersedablePredecessor", () => {
function writeEntry(filename: string, entry: ContextTimelineEntry) {
const filePath = join(dir, filename);
let existing = "";
@@ -544,14 +571,18 @@ describe("timeline", () => {
writeFileSync(filePath, existing + JSON.stringify(entry) + "\n");
}
+ // Fixed reference "now" so datetime math is deterministic.
+ const NOW = Date.parse("2026-06-03T12:00:00.000Z");
+ const GRACE = 30_000;
+
function makeEntry(overrides: Partial<ContextTimelineEntry>): ContextTimelineEntry {
return {
task_id: "t_1",
- context_key: null,
+ context_key: "conv_thread",
session_id: null,
- pid: null,
+ pid: 1000,
status: "running",
- datetime: new Date().toISOString(),
+ datetime: new Date(NOW).toISOString(),
type: "user_dm_message",
prompt: "test",
agent_responses: [],
@@ -562,111 +593,104 @@ describe("timeline", () => {
};
}
- it("returns running entry for same context_key and provider", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_running",
- status: "running",
- pid: 12345,
- context_key: "conv_thread",
- provider: "claude",
- }));
-
- const entry = findRunningEntryByContextKey(dir, "conv_thread", "claude");
- expect(entry).not.toBeNull();
- expect(entry!.task_id).toBe("t_running");
- expect(entry!.pid).toBe(12345);
+ // TC2 — fresh, not-started predecessor → pending.
+ it("returns pending for a fresh not-started running row", () => {
+ writeEntry(_todayFilename(), makeEntry({ task_id: "t_warmup" }));
+ const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
+ expect(result).not.toBeNull();
+ expect(result && "pending" in result && result.pending.task_id).toBe("t_warmup");
});
- it("returns null when no running entries exist", () => {
- expect(findRunningEntryByContextKey(dir, "conv_thread", "claude")).toBeNull();
+ // TC3 — agent_started === true → supersedable (agent-started).
+ it("returns supersedable/agent-started when agent_started is true", () => {
+ writeEntry(_todayFilename(), makeEntry({ task_id: "t_live", agent_started: true }));
+ const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
+ expect(result && "reason" in result && result.reason).toBe("agent-started");
+ expect(result && "entry" in result && result.entry.task_id).toBe("t_live");
});
- it("ignores non-running entries", () => {
+ // TC4 — not started but older than grace → supersedable (stale).
+ it("returns supersedable/stale when not started but older than the grace window", () => {
writeEntry(_todayFilename(), makeEntry({
- task_id: "t_done",
- status: "completed",
- context_key: "conv_thread",
- provider: "claude",
+ task_id: "t_stale",
+ datetime: new Date(NOW - GRACE - 1).toISOString(),
}));
-
- expect(findRunningEntryByContextKey(dir, "conv_thread", "claude")).toBeNull();
+ const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
+ expect(result && "reason" in result && result.reason).toBe("stale");
+ expect(result && "entry" in result && result.entry.task_id).toBe("t_stale");
});
- it("ignores different provider", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_codex",
- status: "running",
- pid: 22222,
- context_key: "conv_thread",
- provider: "codex",
- }));
-
- expect(findRunningEntryByContextKey(dir, "conv_thread", "claude")).toBeNull();
+ // TC5 — no matching running row; ignores wrong provider / context_key / status.
+ it("returns null when no running row matches ctxKey/provider", () => {
+ expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
});
- it("ignores different context_key", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_other",
- status: "running",
- pid: 33333,
- context_key: "conv_other",
- provider: "claude",
- }));
+ it("ignores a different provider", () => {
+ writeEntry(_todayFilename(), makeEntry({ task_id: "t_codex", provider: "codex" }));
+ expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
+ });
- expect(findRunningEntryByContextKey(dir, "conv_thread", "claude")).toBeNull();
+ it("ignores a different context_key", () => {
+ writeEntry(_todayFilename(), makeEntry({ task_id: "t_other", context_key: "conv_other" }));
+ expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
});
- it("returns the newest running entry for same context_key", () => {
- const twoMinAgo = new Date(Date.now() - 2 * 60 * 1000);
- const oneMinAgo = new Date(Date.now() - 1 * 60 * 1000);
+ it("ignores non-running rows", () => {
+ writeEntry(_todayFilename(), makeEntry({ task_id: "t_done", status: "completed" }));
+ expect(findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW)).toBeNull();
+ });
+ // TC6 — newest matching running row wins (reverse iteration).
+ it("picks the newest matching running row", () => {
writeEntry(_todayFilename(), makeEntry({
task_id: "t_older",
- status: "running",
- pid: 11111,
- context_key: "conv_thread",
- provider: "claude",
- datetime: twoMinAgo.toISOString(),
+ agent_started: true,
+ datetime: new Date(NOW - 120_000).toISOString(),
}));
writeEntry(_todayFilename(), makeEntry({
task_id: "t_newer",
- status: "running",
- pid: 22222,
- context_key: "conv_thread",
- provider: "claude",
- datetime: oneMinAgo.toISOString(),
+ datetime: new Date(NOW - 1_000).toISOString(),
}));
-
- const entry = findRunningEntryByContextKey(dir, "conv_thread", "claude");
- expect(entry!.task_id).toBe("t_newer");
+ // Newest is fresh + not started → pending (older agent-started row is shadowed).
+ const result = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW);
+ expect(result && "pending" in result && result.pending.task_id).toBe("t_newer");
+ });
+
+ // TC14 (helper-level) — pending → stale transition as `now` crosses the grace window,
+ // proving the local wait is bounded.
+ it("transitions pending → stale once the row crosses the grace window", () => {
+ writeEntry(_todayFilename(), makeEntry({ task_id: "t_wedge" }));
+ // Just inside the window → still pending (newcomer would wait).
+ const before = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW + GRACE);
+ expect(before && "pending" in before).toBe(true);
+ // Past the window → stale (newcomer supersedes, spin ends).
+ const after = findSupersedablePredecessor(dir, "conv_thread", "claude", GRACE, NOW + GRACE + 1);
+ expect(after && "reason" in after && after.reason).toBe("stale");
});
+ });
- it("scans up to 7 days for running entries", () => {
- const threeDaysAgo = new Date();
- threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
- writeEntry(_filenameForDate(threeDaysAgo), makeEntry({
- task_id: "t_old_running",
- status: "running",
- pid: 44444,
- context_key: "conv_thread",
- provider: "claude",
- datetime: threeDaysAgo.toISOString(),
- }));
+ describe("steerWarmupGraceMs", () => {
+ const KEY = "ALOOK_STEER_WARMUP_GRACE_MS";
+ let saved: string | undefined;
+ beforeEach(() => { saved = process.env[KEY]; });
+ afterEach(() => {
+ if (saved === undefined) delete process.env[KEY];
+ else process.env[KEY] = saved;
+ });
- const entry = findRunningEntryByContextKey(dir, "conv_thread", "claude");
- expect(entry!.task_id).toBe("t_old_running");
+ it("defaults to 30000 when unset", () => {
+ delete process.env[KEY];
+ expect(steerWarmupGraceMs()).toBe(30_000);
});
- it("null context_key tasks are never matched", () => {
- writeEntry(_todayFilename(), makeEntry({
- task_id: "t_null_ctx",
- status: "running",
- pid: 55555,
- context_key: null,
- provider: "claude",
- }));
+ it("reads a valid override from the env", () => {
+ process.env[KEY] = "5000";
+ expect(steerWarmupGraceMs()).toBe(5_000);
+ });
- expect(findRunningEntryByContextKey(dir, "conv_1", "claude")).toBeNull();
+ it("falls back to the default on a non-numeric override", () => {
+ process.env[KEY] = "not-a-number";
+ expect(steerWarmupGraceMs()).toBe(30_000);
});
});
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
index f61f7ceeb..12df3f599 100644
--- a/src/cli/daemon/execenv/context.test.ts
+++ b/src/cli/daemon/execenv/context.test.ts
@@ -126,6 +126,18 @@ describe("buildInstructionContent email tool injection", () => {
expect(content).toContain("The CLI auto-detects your identity from the environment");
});
+ it("includes the Talking to the user (send-dm) guidance block", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "", emailHandle: "handle" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("### Talking to the user");
+ expect(content).toContain("texting a colleague");
+ expect(content).toContain("npx @alook/cli sync send-dm");
+ expect(content).not.toContain("sync send-dm --agent_id");
+ });
+
it("still includes big boss instructions alongside email tools", () => {
const task = makeTask({
agent: { name: "test", instructions: "Follow these rules", emailHandle: "myagent" },
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index dc7f19d96..82e68aff2 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -222,6 +222,15 @@ Upload files for your owner to review in the app.
- You response will be rendered in remote server, so don't output link format with local path in your response (cause user can click it and jump to nowheres)
- If you think user may need to know any file detail, use upload-artifact tool to send the file to user.
+### Talking to the user
+You're texting a colleague, not filing a report. The only thing the user sees is what you send with \`${cmdPrefix()} sync send-dm\` — your task output, reasoning, and tool calls are all off-screen. If you finish without sending, they got silence.
+
+Message at milestones, the way a person would: acknowledge when you pick something up, share a real step forward or a fork in the road, and deliver the result. A quick task is often one message; a long one is a few well-spaced check-ins. Trust your read of the moment — don't narrate every small step, and don't go dark for a long stretch on something they're waiting on.
+
+Say what a colleague would say, not a transcript — the answer in your own voice. (Email- and calendar-triggered tasks have no one watching the chat; use email there.)
+
+\`${cmdPrefix()} sync send-dm --message "…"\` (or \`--message-file <path>\` for long/markdown). The conversation is in $ALOOK_CONVERSATION_ID, so you usually need no flags. You can send several times in one task.
+
### Attachments
When your task includes attachments, their local paths are listed in the prompt JSON under "attachments".
Use your Read tool to open them. Images and PDFs are read visually.
@@ -241,6 +250,15 @@ Recruit new colleague agents directly from the CLI. The server auto-generates a
- Example: '${cmdPrefix()} agent recruit --instructions "You are a QA engineer..." --relationship "DELEGATE when: code is ready for review"'
- Output: 'Recruited Felix ([email protected]) — ag_xK9mPq2z'
- The new agent shares your runtime, is automatically linked as your colleague, and receives a welcome task.
+
+Set or update the relationship with an EXISTING colleague (create-or-replace):
+- Run '${cmdPrefix()} agent link --to <handleOrId> --relationship "<DELEGATION_CRITERIA>"'
+ - '--to <handleOrId>' — target agent by email handle ('coder' or '[email protected]') or agent id ('ag_...')
+ - '--relationship <text>' — the delegation criteria both of you see (replaces it if a link already exists)
+ - '--relationship-file <path>' — alternative: read relationship from a file (mutually exclusive with --relationship)
+ - '--json' — output the link object incl. a 'created' boolean
+- Example: '${cmdPrefix()} agent link --to coder --relationship "DELEGATE when implementation is needed"'
+- Output: 'Linked Felix <-> coder (created)' (or '(updated)' when an existing link was replaced).
`;
content += `\n### Calendar
diff --git a/src/cli/daemon/execenv/timeline.ts b/src/cli/daemon/execenv/timeline.ts
index bc515c144..cb5bf64a1 100644
--- a/src/cli/daemon/execenv/timeline.ts
+++ b/src/cli/daemon/execenv/timeline.ts
@@ -28,6 +28,10 @@ export interface ContextTimelineEntry {
session_id: string | null;
pid: number | null;
status: "running" | "completed" | "failed" | "killed" | "superseded" | "cancelled";
+ // True once the agent CLI has genuinely started executing (session id resolved).
+ // Absent/false during the launch+warm-up window. Steering only supersedes a
+ // predecessor whose agent has actually started — a not-yet-started row is left alone.
+ agent_started?: boolean;
successor_task_id?: string | null;
supersede_reason?: string | null;
datetime: string;
@@ -262,11 +266,41 @@ export function findRunningPidByTaskId(
return null;
}
-export function findRunningEntryByContextKey(
+
+/**
+ * Steering warm-up grace window (ms). A predecessor row that is still "running"
+ * but whose agent never marked itself started becomes supersedable once it is
+ * older than this window — the crash-during-warm-up fallback so a conversation
+ * can never wedge if a session-runner dies before the agent-started marker lands.
+ */
+export function steerWarmupGraceMs(): number {
+ const raw = process.env.ALOOK_STEER_WARMUP_GRACE_MS;
+ const parsed = raw != null ? Number(raw) : NaN;
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 30_000;
+}
+
+export type SupersedablePredecessor =
+ | { entry: ContextTimelineEntry; reason: "agent-started" | "stale" }
+ | { pending: ContextTimelineEntry }
+ | null;
+
+/**
+ * Find the newest "running" timeline row for this context_key+provider and decide
+ * whether the newcomer may supersede it:
+ * - agent_started === true → supersedable (reason "agent-started")
+ * - not started but row older than grace → supersedable (reason "stale", crash fallback)
+ * - not started and fresh → pending (newcomer must wait its turn)
+ * - no matching running row → null (no predecessor)
+ *
+ * `now` is injected for deterministic tests; do NOT call Date.now() internally.
+ */
+export function findSupersedablePredecessor(
timelineDir: string,
contextKey: string,
provider: string,
-): ContextTimelineEntry | null {
+ warmupGraceMs: number,
+ now: number,
+): SupersedablePredecessor {
for (const filename of recentFilenames(7)) {
const dayEntries = readJsonl(join(timelineDir, filename));
for (let i = dayEntries.length - 1; i >= 0; i--) {
@@ -276,7 +310,13 @@ export function findRunningEntryByContextKey(
entry.context_key === contextKey &&
entry.provider === provider
) {
- return entry;
+ if (entry.agent_started === true) {
+ return { entry, reason: "agent-started" };
+ }
+ if (now - Date.parse(entry.datetime) > warmupGraceMs) {
+ return { entry, reason: "stale" };
+ }
+ return { pending: entry };
}
}
}
diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.ts
index f37bb21ee..095bae9da 100644
--- a/src/cli/daemon/prompt.test.ts
+++ b/src/cli/daemon/prompt.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { buildPrompt } from "./prompt.js";
+import { buildPrompt, buildTaskObject, buildMergedPrompt } from "./prompt.js";
import { localISOString } from "./execenv/timeline.js";
import type { Task } from "./types.js";
@@ -143,7 +143,9 @@ describe("buildPrompt", () => {
it("adds DM_RESPONSE_NOTICE for user_dm_message tasks", () => {
const task = makeTask("Fix the bug", "user_dm_message");
const parsed = JSON.parse(buildPrompt(task));
- expect(parsed.notice).toContain("final text response is visible to the user");
+ expect(parsed.notice).toContain("sync send-dm");
+ expect(parsed.notice).toContain("at milestones");
+ expect(parsed.notice).not.toContain("final text response is visible to the user");
});
it("adds CALENDAR_NOTICE for calendar_event tasks with no context", () => {
@@ -333,3 +335,55 @@ describe("buildPrompt", () => {
expect(parsed.sender).toBeUndefined();
});
});
+
+describe("buildTaskObject", () => {
+ it("returns the same object that buildPrompt would JSON.stringify", () => {
+ const task = makeTask("Fix bug");
+ const obj = buildTaskObject(task);
+ expect(JSON.stringify(obj)).toBe(buildPrompt(task));
+ });
+
+ it("includes attachments when provided", () => {
+ const task = makeTask("Fix bug");
+ const att = [{ path: "/tmp/a.txt", content_type: "text/plain", filename: "a.txt" }];
+ const obj = buildTaskObject(task, att);
+ expect(obj.attachments).toEqual([{ path: "/tmp/a.txt", content_type: "text/plain", filename: "a.txt" }]);
+ });
+});
+
+describe("buildMergedPrompt", () => {
+ it("wraps multiple sub-tasks in a merge_tasks envelope sorted by received_at", () => {
+ const taskA: Task = { ...makeTask("DM message", "user_dm_message"), id: "tA", createdAt: "2026-06-03T12:00:02.000Z" };
+ const taskB: Task = {
+ ...makeTask("New email from X: subject", "email_notification"),
+ id: "tB",
+ createdAt: "2026-06-03T12:00:01.000Z",
+ context: { emailId: "em_abc" },
+ };
+ const taskC: Task = { ...makeTask("Another DM", "user_dm_message"), id: "tC", createdAt: "2026-06-03T12:00:03.000Z" };
+
+ const attMap = new Map<string, any[]>();
+ attMap.set("tA", [{ path: "/tmp/a.txt", content_type: "text/plain", filename: "a.txt" }]);
+
+ const result = JSON.parse(buildMergedPrompt([taskA, taskB, taskC], attMap));
+
+ expect(result.type).toBe("merge_tasks");
+ expect(result.notice).toContain("simultaneously");
+ expect(result.tasks).toHaveLength(3);
+ // Sorted by received_at ascending (B=12:00:01, A=12:00:02, C=12:00:03).
+ expect(result.tasks[0].instruction).toBe("New email from X: subject");
+ expect(result.tasks[0].email_id).toBe("em_abc");
+ expect(result.tasks[1].instruction).toBe("DM message");
+ expect(result.tasks[1].attachments).toHaveLength(1);
+ expect(result.tasks[2].instruction).toBe("Another DM");
+ });
+
+ it("produces valid JSON with self-contained sub-tasks", () => {
+ const task = makeTask("Single task", "user_dm_message");
+ const result = JSON.parse(buildMergedPrompt([task], new Map()));
+ expect(result.type).toBe("merge_tasks");
+ expect(result.tasks).toHaveLength(1);
+ expect(result.tasks[0].type).toBe("user_dm_message");
+ expect(result.tasks[0].instruction).toBe("Single task");
+ });
+});
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
index 9361b4628..928f7512f 100644
--- a/src/cli/daemon/prompt.ts
+++ b/src/cli/daemon/prompt.ts
@@ -2,9 +2,9 @@ import type { Task, Attachment } from "./types.js";
import { localISOString } from "./execenv/timeline.js";
const DM_RESPONSE_NOTICE =
- "IMPORTANT: Only your final text response is visible to the user." +
- " Tool calls, intermediate reasoning, and mid-process outputs are NOT displayed." +
- " Put all key information, answers, and conclusions in your final response — that is the only thing the user will read.";
+ "Reply with `alook sync send-dm` — that's the only thing the user sees;" +
+ " your task output and reasoning are not shown." +
+ " Talk to them at milestones like a colleague would, and don't end your turn without sending what they need.";
const EMAIL_NOTICE =
"This task was triggered automatically by an incoming email. There is no human in this session." +
@@ -38,9 +38,7 @@ function buildDmNotice(name: string, email: string): string {
);
}
-export function buildPrompt(task: Task, attachments?: Attachment[]): string {
- // The arrival time of this info (when the message/task was created server-side).
- // Lets a resumed agent reason about elapsed wall-clock time between turns.
+export function buildTaskObject(task: Task, attachments?: Attachment[]): Record<string, unknown> {
const createdAt = new Date(task.createdAt);
const receivedAt = Number.isNaN(createdAt.getTime())
? localISOString()
@@ -108,5 +106,20 @@ export function buildPrompt(task: Task, attachments?: Attachment[]): string {
filename: a.filename,
}));
}
- return JSON.stringify(obj);
+ return obj;
+}
+
+export function buildPrompt(task: Task, attachments?: Attachment[]): string {
+ return JSON.stringify(buildTaskObject(task, attachments));
+}
+
+export function buildMergedPrompt(tasks: Task[], attachmentsMap: Map<string, Attachment[]>): string {
+ const subTasks = tasks
+ .map((t) => buildTaskObject(t, attachmentsMap.get(t.id)))
+ .sort((a, b) => String(a.received_at).localeCompare(String(b.received_at)));
+ return JSON.stringify({
+ type: "merge_tasks",
+ notice: "These messages arrived simultaneously. Process each one completely.",
+ tasks: subTasks,
+ });
}
diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.ts
index cbb5dd437..727428227 100644
--- a/src/cli/daemon/session-runner.test.ts
+++ b/src/cli/daemon/session-runner.test.ts
@@ -295,13 +295,34 @@ describe("session-runner runSession", () => {
await runSession(makeInput());
- // The first updateEntry call should set session_id
+ // The first updateEntry call should set session_id and mark the agent started.
const firstCall = mockUpdateEntry.mock.calls[0];
expect(firstCall[0]).toBe("/tmp/ws/ws1/a1/workdir/.context_timeline");
expect(firstCall[1]).toBe("t1");
- const entry = { session_id: null as string | null };
+ const entry = { session_id: null as string | null, agent_started: undefined as boolean | undefined };
firstCall[2](entry);
expect(entry.session_id).toBe("sess-1");
+ expect(entry.agent_started).toBe(true);
+ });
+
+ // TC13 — codex handshake failure: sessionId resolves to "" → agent_started NOT set.
+ // The row then falls through to the staleness path rather than looking like a live agent.
+ it("does not mark agent_started when sessionId resolves to an empty string", async () => {
+ setupBackend([], {
+ status: "completed",
+ output: "Done",
+ error: "",
+ durationMs: 100,
+ sessionId: "",
+ }, "");
+
+ await runSession(makeInput());
+
+ const firstCall = mockUpdateEntry.mock.calls[0];
+ const entry = { session_id: "stale" as string | null, agent_started: undefined as boolean | undefined };
+ firstCall[2](entry);
+ expect(entry.session_id).toBeNull();
+ expect(entry.agent_started).toBeUndefined();
});
it("initEntryAsync is called with detailedLog from input.logFilePath", async () => {
diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.ts
index f3e62e01a..cf524bb25 100644
--- a/src/cli/daemon/session-runner.ts
+++ b/src/cli/daemon/session-runner.ts
@@ -121,7 +121,7 @@ function sanitizeFilename(name: string): string {
return path.basename(name).replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
}
-async function cleanupAttachments(taskId: string): Promise<void> {
+export async function cleanupAttachments(taskId: string): Promise<void> {
try {
await rm(path.join(ATTACHMENTS_BASE, taskId), { recursive: true, force: true });
} catch {
@@ -129,7 +129,7 @@ async function cleanupAttachments(taskId: string): Promise<void> {
}
}
-async function downloadAttachments(
+export async function downloadAttachments(
client: DaemonClient,
token: string,
workspaceId: string,
@@ -182,8 +182,12 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
// --- State shared by the kill handler, hoisted so the SINGLE handler below
// can see it whether the kill lands before or after the agent spawns. ---
let killed = false;
- let agentPid: number | undefined = undefined;
- let flushTimer: ReturnType<typeof setInterval> | undefined = undefined;
+ // Assigned once after the agent spawns (below) but READ earlier inside onKill;
+ // prefer-const can't see the closure read, so it must stay `let`.
+ // eslint-disable-next-line prefer-const
+ let agentPid: number | undefined;
+ // eslint-disable-next-line prefer-const
+ let flushTimer: ReturnType<typeof setInterval> | undefined;
// Message batching
const pendingMessages: {
@@ -312,7 +316,7 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
// and called process.exit — but if exit hasn't flushed yet, don't spawn).
if (killed) return;
- const prompt = buildPrompt(task, attachments);
+ const prompt = input.promptOverride ?? buildPrompt(task, attachments);
const resumeSessionId = task.contextKey
? findResumableSessionByContextKey(timelineDir, task.contextKey, provider) ?? undefined
@@ -351,6 +355,11 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
log.info(JSON.stringify({ role: "user", type: "text", content: prompt }));
updateEntry(timelineDir, task.id, (entry) => {
entry.session_id = earlySessionId || null;
+ // Mark the agent as genuinely started so steering may supersede this run.
+ // Gate on a non-empty session id: codex resolves sessionId to "" if its
+ // thread/start handshake fails before completing — that is NOT a started
+ // agent, so leave the marker falsy and let the staleness path reap it.
+ if (earlySessionId) entry.agent_started = true;
});
flushTimer = setInterval(flushMessages, FLUSH_INTERVAL_MS);
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
index 500beddb5..04bb157cb 100644
--- a/src/cli/daemon/types.ts
+++ b/src/cli/daemon/types.ts
@@ -102,6 +102,7 @@ export interface SessionRunnerInput {
agentTimeout: number;
messageInactivityTimeout: number;
logFilePath?: string;
+ promptOverride?: string;
}
/** Convert a validated TaskApi (snake_case wire format) to the internal Task type. */
diff --git a/src/cli/lib/client.ts b/src/cli/lib/client.ts
index 9d746f016..efa9e1684 100644
--- a/src/cli/lib/client.ts
+++ b/src/cli/lib/client.ts
@@ -45,6 +45,10 @@ export class APIClient {
return this.request("PATCH", path, body);
}
+ putJSON<T>(path: string, body?: unknown): Promise<T> {
+ return this.request("PUT", path, body);
+ }
+
async postMultipart<T>(path: string, form: FormData): Promise<T> {
const headers: Record<string, string> = {
Authorization: `Bearer ${this.token}`,
diff --git a/src/email-worker/src/index.test.ts b/src/email-worker/src/index.test.ts
index afecf5b9b..28d962978 100644
--- a/src/email-worker/src/index.test.ts
+++ b/src/email-worker/src/index.test.ts
@@ -31,6 +31,13 @@ vi.mock("nanoid", () => ({
nanoid: () => `mock-id-${++nanoidCounter}`,
}))
+// Mock cloudflare:email — capture the raw MIME passed to the CF SEND_EMAIL binding.
+vi.mock("cloudflare:email", () => ({
+ EmailMessage: class {
+ constructor(public from: string, public to: string, public raw: string) {}
+ },
+}))
+
// Mock @alook/shared at module level — the handler never touches Drizzle
const mockGetAgentByHandle = vi.fn<(db: unknown, handle: unknown) => unknown>()
const mockGetAgent = vi.fn<(db: unknown, id: unknown, workspaceId: unknown) => unknown>()
@@ -525,23 +532,29 @@ describe("POST /send/agent", () => {
)
expect(res.status).toBe(200)
- const json = await res.json() as { ok: boolean; r2Key: string }
+ const json = await res.json() as { ok: boolean; r2Key: string; messageId: string }
expect(json.ok).toBe(true)
expect(json.r2Key).toMatch(/^emails\/mock-id-\d+\/raw$/)
- // Verify SEND_EMAIL.send was called with builder
+ // Verify SEND_EMAIL.send was called with a raw-MIME EmailMessage
expect(send).toHaveBeenCalledOnce()
- const sendArg = send.mock.calls[0][0]
+ const sendArg = send.mock.calls[0][0] as { from: string; to: string; raw: string }
expect(sendArg.from).toBe("[email protected]")
expect(sendArg.to).toBe("[email protected]")
- expect(sendArg.subject).toBe("Hello")
- expect(sendArg.html).toBe("<p>Hi there</p>")
+ expect(sendArg.raw).toContain("From: [email protected]")
+ expect(sendArg.raw).toContain("To: [email protected]")
+ expect(sendArg.raw).toContain("Subject: Hello")
+ expect(sendArg.raw).toContain("<p>Hi there</p>")
+
+ // TC2/TC6: the Message-ID on the wire == the returned id == the archived id
+ expect(sendArg.raw).toContain("Message-ID: " + json.messageId)
- // Verify R2 archive
+ // Verify R2 archive (same MIME as the wire message)
expect(put).toHaveBeenCalledOnce()
const [key, body, opts] = put.mock.calls[0]
expect(key).toMatch(/^emails\/mock-id-\d+\/raw$/)
expect(opts).toEqual({ httpMetadata: { contentType: "message/rfc822" } })
+ expect(body).toBe(sendArg.raw)
expect(body).toContain("From: [email protected]")
expect(body).toContain("To: [email protected]")
expect(body).toContain("Subject: Hello")
@@ -573,18 +586,17 @@ describe("POST /send/agent", () => {
expect(res.status).toBe(200)
- // Verify SEND_EMAIL.send includes attachments with raw ArrayBuffer content
- const sendArg = send.mock.calls[0][0]
- expect(sendArg.attachments).toHaveLength(1)
- expect(sendArg.attachments[0].filename).toBe("doc.txt")
- expect(sendArg.attachments[0].type).toBe("text/plain")
- expect(sendArg.attachments[0].disposition).toBe("attachment")
- expect(sendArg.attachments[0].content).toBeInstanceOf(ArrayBuffer)
- const decoded = new TextDecoder().decode(sendArg.attachments[0].content)
- expect(decoded).toBe("file content")
-
- // Verify R2 MIME archive contains attachment
+ // Verify the raw-MIME wire message carries the attachment (base64-encoded)
+ const sendArg = send.mock.calls[0][0] as { raw: string }
+ expect(sendArg.raw).toContain("multipart/mixed")
+ expect(sendArg.raw).toContain('Content-Disposition: attachment; filename="doc.txt"')
+ expect(sendArg.raw).toContain("Content-Transfer-Encoding: base64")
+ // TC2: attachment base64 round-trips intact in the rendered MIME
+ expect(sendArg.raw).toContain(btoa("file content"))
+
+ // Verify R2 MIME archive is the same MIME that went on the wire
const storedMime = put.mock.calls[0][1] as string
+ expect(storedMime).toBe(sendArg.raw)
expect(storedMime).toContain("multipart/mixed")
expect(storedMime).toContain('Content-Disposition: attachment; filename="doc.txt"')
expect(storedMime).toContain("Content-Transfer-Encoding: base64")
@@ -628,11 +640,11 @@ describe("POST /send/agent", () => {
expect(fetchOrder).toContain("emails/drafts/x/missing.txt")
expect(fetchOrder).toContain("emails/drafts/x/b.txt")
- // Only non-null attachments included
- const sendArg = send.mock.calls[0][0]
- expect(sendArg.attachments).toHaveLength(2)
- expect(sendArg.attachments[0].filename).toBe("a.txt")
- expect(sendArg.attachments[1].filename).toBe("b.txt")
+ // Only non-null attachments included in the raw MIME (missing.txt skipped)
+ const sendArg = send.mock.calls[0][0] as { raw: string }
+ expect(sendArg.raw).toContain('filename="a.txt"')
+ expect(sendArg.raw).toContain('filename="b.txt"')
+ expect(sendArg.raw).not.toContain('filename="missing.txt"')
})
it("returns 404 when agent not found in workspace", async () => {
@@ -684,7 +696,7 @@ describe("POST /send/agent", () => {
it("includes threading headers in outgoing MIME when inReplyTo/references provided", async () => {
mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })
- const { env, put } = agentSendEnv()
+ const { env, send, put } = agentSendEnv()
const res = await handler.fetch(
makeAgentSendRequest({
@@ -703,6 +715,12 @@ describe("POST /send/agent", () => {
const json = await res.json() as { ok: boolean; messageId: string }
expect(json.messageId).toMatch(/@alook\.ai>$/)
+ // Threading headers now ride the WIRE message (raw MIME), not just the archive.
+ const sendArg = send.mock.calls[0][0] as { raw: string }
+ expect(sendArg.raw).toContain("Message-ID: " + json.messageId)
+ expect(sendArg.raw).toContain("In-Reply-To: <[email protected]>")
+ expect(sendArg.raw).toContain("References: <[email protected]> <[email protected]>")
+
const storedMime = put.mock.calls[0][1] as string
expect(storedMime).toContain("Message-ID: " + json.messageId)
expect(storedMime).toContain("In-Reply-To: <[email protected]>")
@@ -773,7 +791,7 @@ describe("POST /send/agent with custom SMTP", () => {
it("sends via worker-mailer when customAccountId is provided", async () => {
mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })
mockGetEmailAccount.mockResolvedValue(CUSTOM_ACCOUNT)
- const { env, send } = customSmtpEnv()
+ const { env, send, put } = customSmtpEnv()
const res = await handler.fetch(
makeRequest({
@@ -800,6 +818,14 @@ describe("POST /send/agent with custom SMTP", () => {
expect(emailOpts.from).toEqual({ name: "Custom User", email: "[email protected]" })
expect(emailOpts.to).toBe("[email protected]")
expect(emailOpts.subject).toBe("Custom SMTP test")
+
+ // TC3: wire Message-ID is controlled, uses the from-account domain, and equals
+ // the returned/archived id (so a human reply threads back).
+ const json = await res.json() as { messageId: string }
+ expect(emailOpts.headers["Message-ID"]).toBe(json.messageId)
+ expect(json.messageId).toMatch(/@gmail\.com>$/)
+ const storedMime = put.mock.calls[0][1] as string
+ expect(storedMime).toContain("Message-ID: " + json.messageId)
})
it("falls back to CF SendEmail when no customAccountId", async () => {
diff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.ts
index 60da5142e..c15a57e98 100644
--- a/src/email-worker/src/index.ts
+++ b/src/email-worker/src/index.ts
@@ -3,6 +3,7 @@ import PostalMime from "postal-mime"
import { createDb, queries, parseEmailHandle, toAlookAddress, DEV_WEB_URL, createLogger, buildMimeMessage, extractAttachmentMeta } from "@alook/shared"
import { decrypt } from "@alook/shared/crypto"
import { WorkerMailer, type AuthType } from "worker-mailer"
+import { EmailMessage } from "cloudflare:email"
const SMTP_AUTH_TYPES: AuthType[] = ["plain", "login", "cram-md5"]
import type { EmailEnv } from "./types"
@@ -151,6 +152,31 @@ export default {
})
)).filter((a): a is NonNullable<typeof a> => a !== null)
+ // Generate the outbound Message-ID ONCE, before sending. This same id is placed
+ // on the wire, returned to the caller (for conversation-map registration), and
+ // stored in the R2 archive — so a human's reply (In-Reply-To = this id) threads
+ // back into the originating conversation. The id's domain must match the sending
+ // domain: @alook.ai for the CF path, the custom-account domain for the SMTP path.
+ const fromDomain = useCustomSmtp && customAccount
+ ? customAccount.emailAddress.split("@").pop()
+ : "alook.ai"
+ const outMessageId = `<${nanoid()}@${fromDomain}>`
+
+ // Build the raw MIME once — used both as the wire message (CF path) and as the
+ // R2 archive (both paths). buildMimeMessage emits From + Message-ID + threading
+ // headers, so the archived copy always matches what was transmitted.
+ const rawMime = buildMimeMessage({
+ from: fromAddress,
+ to: body.to,
+ subject: body.subject,
+ messageId: outMessageId,
+ inReplyTo: body.inReplyTo,
+ references: body.references,
+ body: htmlBody,
+ bodyType: "text/html",
+ attachments: attachments.map(a => ({ filename: a.filename, contentType: a.type, base64: a.base64 })),
+ })
+
if (useCustomSmtp && customAccount) {
const secret = env.ENCRYPTION_KEY
if (!secret) {
@@ -161,7 +187,9 @@ export default {
const smtpPassword = decrypt(customAccount.smtpPassword, secret)
const smtpTls = customAccount.smtpTls as number
- const threadingHeaders: Record<string, string> = {}
+ // Control the wire Message-ID so it equals the registered/archived id.
+ // WorkerMailer respects a provided Message-ID and only auto-generates if absent.
+ const threadingHeaders: Record<string, string> = { "Message-ID": outMessageId }
if (body.inReplyTo) threadingHeaders["In-Reply-To"] = body.inReplyTo
if (body.references) threadingHeaders["References"] = body.references
@@ -195,38 +223,13 @@ export default {
return Response.json({ error: `SMTP send failed: ${msg}` }, { status: 500 })
}
} else {
- const sendPayload: Record<string, unknown> = {
- from: fromAddress,
- to: body.to,
- subject: body.subject,
- html: htmlBody,
- }
- if (attachments.length > 0) {
- sendPayload.attachments = attachments.map(a => ({
- disposition: a.disposition,
- filename: a.filename,
- type: a.type,
- content: a.raw,
- }))
- }
- await env.SEND_EMAIL.send(sendPayload as any)
+ // Send the raw MIME so the wire Message-ID (and threading headers) are the ones
+ // we control. The CF structured builder has no reliable Message-ID field — its
+ // MTA assigns its own — so we use the raw-MIME overload instead.
+ await env.SEND_EMAIL.send(new EmailMessage(fromAddress, body.to, rawMime))
}
- // Build raw MIME for R2 archival
- const outMessageId = `<${nanoid()}@alook.ai>`
- const rawMime = buildMimeMessage({
- from: fromAddress,
- to: body.to,
- subject: body.subject,
- messageId: outMessageId,
- inReplyTo: body.inReplyTo,
- references: body.references,
- body: htmlBody,
- bodyType: "text/html",
- attachments: attachments.map(a => ({ filename: a.filename, contentType: a.type, base64: a.base64 })),
- })
-
- // Store MIME archive in R2
+ // Store the SAME MIME archive in R2 (wire id == archived id).
const r2Id = nanoid()
const r2Key = `emails/${r2Id}/raw`
await env.EMAIL_BUCKET.put(r2Key, rawMime, {
diff --git a/src/shared/src/db/queries/agent-link.ts b/src/shared/src/db/queries/agent-link.ts
index c6477b734..2e5117db2 100644
--- a/src/shared/src/db/queries/agent-link.ts
+++ b/src/shared/src/db/queries/agent-link.ts
@@ -57,6 +57,52 @@ export async function create(
return rows[0]!;
}
+export async function getByPair(
+ db: Database,
+ workspaceId: string,
+ a: string,
+ b: string,
+) {
+ const [sourceAgentId, targetAgentId] = a > b ? [b, a] : [a, b];
+ const rows = await db
+ .select()
+ .from(agentLink)
+ .where(
+ and(
+ eq(agentLink.workspaceId, workspaceId),
+ eq(agentLink.sourceAgentId, sourceAgentId),
+ eq(agentLink.targetAgentId, targetAgentId),
+ ),
+ );
+ return rows[0] ?? null;
+}
+
+export async function upsertByPair(
+ db: Database,
+ data: {
+ workspaceId: string;
+ sourceAgentId: string;
+ targetAgentId: string;
+ instruction: string;
+ },
+) {
+ const existing = await getByPair(
+ db,
+ data.workspaceId,
+ data.sourceAgentId,
+ data.targetAgentId,
+ );
+ if (existing) {
+ const updated = await update(db, existing.id, data.workspaceId, {
+ instruction: data.instruction,
+ });
+ if (!updated) return { row: existing, created: false };
+ return { row: updated, created: false };
+ }
+ const created = await create(db, data);
+ return { row: created, created: true };
+}
+
export async function update(
db: Database,
id: string,
diff --git a/src/shared/src/db/queries/message.ts b/src/shared/src/db/queries/message.ts
index 072f6f083..d4d7be173 100644
--- a/src/shared/src/db/queries/message.ts
+++ b/src/shared/src/db/queries/message.ts
@@ -110,108 +110,6 @@ export async function getMessage(db: Database, id: string) {
return rows[0] ?? null;
}
-export async function createBufferedMessage(
- db: Database,
- data: {
- conversationId: string;
- content: string;
- attachmentIds?: string | null;
- }
-) {
- const rows = await db
- .insert(message)
- .values({
- conversationId: data.conversationId,
- role: "user",
- content: data.content,
- status: "buffered",
- attachmentIds: data.attachmentIds ?? null,
- })
- .returning();
- return rows[0]!;
-}
-
-export async function listBufferedMessages(db: Database, conversationId: string) {
- return db
- .select()
- .from(message)
- .where(
- and(
- eq(message.conversationId, conversationId),
- eq(message.status, "buffered")
- )
- )
- .orderBy(asc(message.createdAt), asc(message.id));
-}
-
-export async function activateNextBufferedMessage(db: Database, conversationId: string) {
- const candidates = await db
- .select()
- .from(message)
- .where(
- and(
- eq(message.conversationId, conversationId),
- eq(message.status, "buffered")
- )
- )
- .orderBy(asc(message.createdAt), asc(message.id))
- .limit(1);
-
- if (candidates.length === 0) return null;
-
- const target = candidates[0]!;
- const updated = await db
- .update(message)
- .set({ status: "active", createdAt: new Date(Date.now() + 1000).toISOString() })
- .where(and(eq(message.id, target.id), eq(message.status, "buffered")))
- .returning();
-
- return updated[0] ?? null;
-}
-
-export async function revertToBuffered(db: Database, id: string) {
- const rows = await db
- .update(message)
- .set({ status: "buffered" })
- .where(and(eq(message.id, id), eq(message.status, "active")))
- .returning();
- return rows[0] ?? null;
-}
-
-export async function deleteBufferedMessage(db: Database, id: string) {
- const rows = await db
- .delete(message)
- .where(and(eq(message.id, id), eq(message.status, "buffered")))
- .returning();
- return rows[0] ?? null;
-}
-
-export async function deleteAllBufferedMessages(db: Database, conversationId: string) {
- const rows = await db
- .delete(message)
- .where(
- and(
- eq(message.conversationId, conversationId),
- eq(message.status, "buffered")
- )
- )
- .returning();
- return rows;
-}
-
-export async function countBufferedMessages(db: Database, conversationId: string) {
- const rows = await db
- .select({ count: count(message.id) })
- .from(message)
- .where(
- and(
- eq(message.conversationId, conversationId),
- eq(message.status, "buffered")
- )
- );
- return rows[0]?.count ?? 0;
-}
-
export async function updateMessageTaskId(db: Database, messageId: string, taskId: string) {
await db.update(message).set({ taskId }).where(eq(message.id, messageId));
}
diff --git a/src/shared/src/db/queries/task-message.ts b/src/shared/src/db/queries/task-message.ts
index d2b77bde6..1f24f04b6 100644
--- a/src/shared/src/db/queries/task-message.ts
+++ b/src/shared/src/db/queries/task-message.ts
@@ -1,4 +1,4 @@
-import { eq, and, gt, asc, count, inArray, notInArray } from "drizzle-orm";
+import { eq, and, gt, asc, notInArray } from "drizzle-orm";
import { taskMessage, agentTaskQueue } from "../schema";
import type { Database } from "../index";
@@ -48,16 +48,56 @@ export async function listTaskMessages(db: Database, taskId: string, workspaceId
})
.from(taskMessage)
.innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))
+ // Exclude tool-result/tool-use/thinking from the READ side only: the UI
+ // doesn't render them. They ARE still written (see daemon messages route)
+ // and retained for future data analysis — do NOT take this filter as a
+ // sign the rows are dead and stop persisting them.
.where(and(eq(taskMessage.taskId, taskId), eq(agentTaskQueue.workspaceId, workspaceId), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))
.orderBy(asc(taskMessage.seq));
}
return db
.select()
.from(taskMessage)
+ // Read-side UI exclusion only; rows are still stored for analysis (see above).
.where(and(eq(taskMessage.taskId, taskId), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))
.orderBy(asc(taskMessage.seq));
}
+// Errors-only, workspace-scoped: the chat init routes preload only `type:"error"`
+// rows so a persisted error survives a reload (the rest of a run's messages arrive
+// live via the task.messages WS broadcast / send-dm). Filtering in SQL keeps the
+// route's hot path lean and the workspace join enforces scoping. Kept separate
+// from listTaskMessages (which is the UI-exclusion read) on purpose.
+export async function listTaskErrorMessages(
+ db: Database,
+ taskId: string,
+ workspaceId: string
+) {
+ return db
+ .select({
+ id: taskMessage.id,
+ taskId: taskMessage.taskId,
+ seq: taskMessage.seq,
+ type: taskMessage.type,
+ tool: taskMessage.tool,
+ content: taskMessage.content,
+ callId: taskMessage.callId,
+ input: taskMessage.input,
+ output: taskMessage.output,
+ createdAt: taskMessage.createdAt,
+ })
+ .from(taskMessage)
+ .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))
+ .where(
+ and(
+ eq(taskMessage.taskId, taskId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ eq(taskMessage.type, "error")
+ )
+ )
+ .orderBy(asc(taskMessage.seq));
+}
+
export async function listTaskMessagesSince(
db: Database,
taskId: string,
@@ -66,6 +106,7 @@ export async function listTaskMessagesSince(
return db
.select()
.from(taskMessage)
+ // Read-side UI exclusion only; rows are still stored for analysis (see listTaskMessages).
.where(and(eq(taskMessage.taskId, taskId), gt(taskMessage.seq, afterSeq), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))
.orderBy(asc(taskMessage.seq));
}
@@ -73,59 +114,3 @@ export async function listTaskMessagesSince(
export async function deleteTaskMessages(db: Database, taskId: string) {
await db.delete(taskMessage).where(eq(taskMessage.taskId, taskId));
}
-
-const SQLITE_MAX_PARAMS = 999;
-const FIXED_PARAMS = 2; // workspaceId + type filter value ("text")
-
-export async function countTextMessagesByTaskIds(
- db: Database,
- taskIds: string[],
- workspaceId: string
-): Promise<Array<{ taskId: string; count: number }>> {
- if (taskIds.length === 0) return [];
-
- const chunkSize = SQLITE_MAX_PARAMS - FIXED_PARAMS;
-
- if (taskIds.length <= chunkSize) {
- const rows = await db
- .select({
- taskId: taskMessage.taskId,
- count: count(taskMessage.id),
- })
- .from(taskMessage)
- .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))
- .where(
- and(
- inArray(taskMessage.taskId, taskIds),
- eq(agentTaskQueue.workspaceId, workspaceId),
- eq(taskMessage.type, "text")
- )
- )
- .groupBy(taskMessage.taskId);
- return rows.map((r) => ({ taskId: r.taskId, count: r.count }));
- }
-
- const results: Array<{ taskId: string; count: number }> = [];
- for (let i = 0; i < taskIds.length; i += chunkSize) {
- const chunk = taskIds.slice(i, i + chunkSize);
- const rows = await db
- .select({
- taskId: taskMessage.taskId,
- count: count(taskMessage.id),
- })
- .from(taskMessage)
- .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))
- .where(
- and(
- inArray(taskMessage.taskId, chunk),
- eq(agentTaskQueue.workspaceId, workspaceId),
- eq(taskMessage.type, "text")
- )
- )
- .groupBy(taskMessage.taskId);
- results.push(...rows.map((r) => ({ taskId: r.taskId, count: r.count })));
- }
-
- return results;
-}
-
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 4fb5adf36..8d65b588e 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -139,12 +139,13 @@ export {
IssueApiSchema,
CreateAgentLinkRequestSchema,
UpdateAgentLinkRequestSchema,
+ UpsertAgentLinkRequestSchema,
AddWhitelistRequestSchema,
CreateAgentRequestSchema,
UpdateAgentRequestSchema,
CreateConversationRequestSchema,
CreateMessageRequestSchema,
- CreateBufferedMessageRequestSchema,
+ AgentDmRequestSchema,
EmailAttachmentSchema,
SendEmailRequestSchema,
UpdateEmailStatusRequestSchema,
@@ -186,6 +187,7 @@ export type {
DeregisterRequest,
CompleteTaskRequest,
FailTaskRequest,
+ AgentDmRequest,
MessageItem,
ReportMessagesRequest,
CreateCalendarEventRequestInput,
@@ -200,6 +202,7 @@ export type {
IssueApi,
CreateAgentLinkRequestInput,
UpdateAgentLinkRequestInput,
+ UpsertAgentLinkRequestInput,
AddWhitelistRequest,
CreateEmailAccountRequest,
UpdateMemberRequest,
@@ -248,6 +251,7 @@ export { isValidToken, isValidEmail } from "./utils/validation";
export { isOnline, formatStatus } from "./utils/status";
export { isUniqueConstraintError } from "./utils/db-errors";
export { generateWorkspaceSlug } from "./utils/slug";
+export { truncateTitle } from "./utils/title";
export { semverGte } from "./semver";
export { resolveMode, cliCommand, daemonCommand, getBaseUrl } from "./mode";
export type { AlookMode, ModeSignals, BaseUrlSignals } from "./mode";
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index a8b4f8e1b..b098cc0be 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -462,6 +462,12 @@ export const UpdateAgentLinkRequestSchema = z.object({
});
export type UpdateAgentLinkRequestInput = z.infer<typeof UpdateAgentLinkRequestSchema>;
+export const UpsertAgentLinkRequestSchema = z.object({
+ target_agent_id: z.string().min(1, "target_agent_id is required"),
+ instruction: z.string(),
+});
+export type UpsertAgentLinkRequestInput = z.infer<typeof UpsertAgentLinkRequestSchema>;
+
// ---------------------------------------------------------------------------
// Whitelist request schema
// ---------------------------------------------------------------------------
@@ -536,10 +542,14 @@ export const CreateMessageRequestSchema = z.object({
});
export type CreateMessageRequest = z.infer<typeof CreateMessageRequestSchema>;
-export const CreateBufferedMessageRequestSchema = z.object({
+// Agent-authored DM: the agent's own `role:"assistant"` reply, posted via the
+// machine-token daemon route (`alook sync send-dm`). Unlike CreateMessageRequest
+// (a user send) this does NOT enqueue a task — it only delivers the message.
+export const AgentDmRequestSchema = z.object({
content: z.string().min(1, "content is required"),
+ task_id: z.string().min(1).optional(),
});
-export type CreateBufferedMessageRequest = z.infer<typeof CreateBufferedMessageRequestSchema>;
+export type AgentDmRequest = z.infer<typeof AgentDmRequestSchema>;
// ---------------------------------------------------------------------------
// Email request schemas
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index b193df9c7..02d6255a2 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -133,7 +133,7 @@ export interface Message {
task_id: string | null;
attachment_ids: string[] | null;
metadata?: Record<string, unknown> | null;
- status?: "active" | "buffered";
+ status?: "active";
created_at: string;
}
@@ -288,10 +288,6 @@ export type WsMessage =
| { type: "email.received"; agentId: string }
| { type: "email.sent"; agentId: string }
| { type: "artifact.uploaded"; conversationId: string; artifact: Artifact }
- | { type: "followup.dispatched"; conversationId: string; message: Message; task: TaskApi }
- | { type: "followup.created"; conversationId: string; message: Message }
- | { type: "followup.deleted"; conversationId: string; messageId: string }
- | { type: "followup.dispatch_failed"; conversationId: string; messageId: string; error: string }
| { type: "conversation.message"; conversationId: string; message: Message }
| { type: "agent.created"; agentId: string; workspaceId: string; parentAgentId: string }
| { type: "issue.comment"; issueId: string; comment: IssueComment }
diff --git a/src/shared/src/utils/title.ts b/src/shared/src/utils/title.ts
new file mode 100644
index 000000000..a612a9d7f
--- /dev/null
+++ b/src/shared/src/utils/title.ts
@@ -0,0 +1,15 @@
+/**
+ * Derive a conversation title from the first message body: collapse whitespace,
+ * trim, and cap length at a word boundary when possible.
+ *
+ * Lifted from the user-send route so the agent-DM route can reuse the exact
+ * same auto-title behaviour (both set a conversation's title on first message).
+ */
+export function truncateTitle(text: string, maxLen = 50): string {
+ const trimmed = text.replace(/\s+/g, " ").trim();
+ if (trimmed.length <= maxLen) return trimmed;
+ const cut = trimmed.slice(0, maxLen);
+ const lastSpace = cut.lastIndexOf(" ");
+ const title = lastSpace > 20 ? cut.slice(0, lastSpace) : cut;
+ return title + "...";
+}
diff --git a/src/shared/test/queries/agent-link.test.ts b/src/shared/test/queries/agent-link.test.ts
index bbfd03b4b..41a244735 100644
--- a/src/shared/test/queries/agent-link.test.ts
+++ b/src/shared/test/queries/agent-link.test.ts
@@ -10,6 +10,102 @@ describe("agent-link query module exports", () => {
it("exports getColleaguesForAgent", () => { expect(typeof agentLinkQueries.getColleaguesForAgent).toBe("function"); });
it("exports getColleaguesForAgents", () => { expect(typeof agentLinkQueries.getColleaguesForAgents).toBe("function"); });
it("exports getAllColleaguesForWorkspace", () => { expect(typeof agentLinkQueries.getAllColleaguesForWorkspace).toBe("function"); });
+ it("exports getByPair", () => { expect(typeof agentLinkQueries.getByPair).toBe("function"); });
+ it("exports upsertByPair", () => { expect(typeof agentLinkQueries.upsertByPair).toBe("function"); });
+});
+
+// Helper: a select().from().where() chain that resolves to `rows`.
+function selectChain(rows: unknown[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ return chain;
+}
+
+describe("getByPair", () => {
+ // TC4: returns the row for either input order; null when absent.
+ it("queries canonical order (a < b) and returns the row", async () => {
+ const link = { id: "link_1", sourceAgentId: "ag_a", targetAgentId: "ag_z" };
+ const chain = selectChain([link]);
+ const result = await agentLinkQueries.getByPair(chain, "ws_1", "ag_a", "ag_z");
+ expect(result).toEqual(link);
+ });
+
+ it("returns the same row when input order is reversed (b, a)", async () => {
+ const link = { id: "link_1", sourceAgentId: "ag_a", targetAgentId: "ag_z" };
+ const chain = selectChain([link]);
+ const result = await agentLinkQueries.getByPair(chain, "ws_1", "ag_z", "ag_a");
+ expect(result).toEqual(link);
+ });
+
+ it("returns null when no row exists", async () => {
+ const chain = selectChain([]);
+ expect(await agentLinkQueries.getByPair(chain, "ws_1", "ag_a", "ag_z")).toBeNull();
+ });
+});
+
+describe("upsertByPair", () => {
+ // TC1: non-existent pair -> inserts 1 row, created:true, canonical order.
+ it("creates a new row (created:true) when the pair does not exist", async () => {
+ const created = { id: "link_new", sourceAgentId: "ag_a", targetAgentId: "ag_z" };
+ const chain: any = {};
+ // getByPair -> select().from().where() resolves empty
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([]));
+ // create() -> insert().values().returning()
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([created]));
+
+ const res = await agentLinkQueries.upsertByPair(chain, {
+ workspaceId: "ws_1",
+ sourceAgentId: "ag_z",
+ targetAgentId: "ag_a",
+ instruction: "hello",
+ });
+ expect(res).toEqual({ row: created, created: true });
+ // create() canonicalizes ag_z/ag_a -> ag_a/ag_z
+ expect(chain.values).toHaveBeenCalledWith(
+ expect.objectContaining({ sourceAgentId: "ag_a", targetAgentId: "ag_z", instruction: "hello" }),
+ );
+ });
+
+ // TC2/TC3: existing pair (either input order) -> updates the SAME row,
+ // created:false, no duplicate insert.
+ it("updates the existing row (created:false) and does not insert", async () => {
+ const existing = { id: "link_1", sourceAgentId: "ag_a", targetAgentId: "ag_z" };
+ const updated = { ...existing, instruction: "new text" };
+ // getByPair terminates on .where() (resolves rows); update() uses a longer
+ // .update().set().where().returning() chain. Track each independently.
+ const chain: any = {};
+ let whereCall = 0;
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([updated]));
+ chain.where = vi.fn(() => {
+ whereCall++;
+ // 1st where = getByPair lookup (returns existing); later wheres = update chain
+ return whereCall === 1 ? Promise.resolve([existing]) : chain;
+ });
+
+ // reversed input order (ag_z, ag_a) still hits the same canonical row
+ const res = await agentLinkQueries.upsertByPair(chain, {
+ workspaceId: "ws_1",
+ sourceAgentId: "ag_z",
+ targetAgentId: "ag_a",
+ instruction: "new text",
+ });
+ expect(res).toEqual({ row: updated, created: false });
+ expect(chain.update).toHaveBeenCalled();
+ expect(chain.insert).not.toHaveBeenCalled();
+ expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ instruction: "new text" }));
+ });
});
describe("create", () => {
diff --git a/src/shared/test/queries/message.test.ts b/src/shared/test/queries/message.test.ts
index 44d4faa14..62cb3d259 100644
--- a/src/shared/test/queries/message.test.ts
+++ b/src/shared/test/queries/message.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from "vitest";
import * as messageQueries from "../../src/db/queries/message";
+import { message } from "../../src/db/schema";
function createMockDb(rows: any[]) {
const chain: any = {};
@@ -38,34 +39,6 @@ describe("message query module exports", () => {
expect(typeof messageQueries.getMessage).toBe("function");
});
- it("exports createBufferedMessage", () => {
- expect(typeof messageQueries.createBufferedMessage).toBe("function");
- });
-
- it("exports listBufferedMessages", () => {
- expect(typeof messageQueries.listBufferedMessages).toBe("function");
- });
-
- it("exports activateNextBufferedMessage", () => {
- expect(typeof messageQueries.activateNextBufferedMessage).toBe("function");
- });
-
- it("exports revertToBuffered", () => {
- expect(typeof messageQueries.revertToBuffered).toBe("function");
- });
-
- it("exports deleteBufferedMessage", () => {
- expect(typeof messageQueries.deleteBufferedMessage).toBe("function");
- });
-
- it("exports deleteAllBufferedMessages", () => {
- expect(typeof messageQueries.deleteAllBufferedMessages).toBe("function");
- });
-
- it("exports countBufferedMessages", () => {
- expect(typeof messageQueries.countBufferedMessages).toBe("function");
- });
-
it("exports updateMessageTaskId", () => {
expect(typeof messageQueries.updateMessageTaskId).toBe("function");
});
@@ -126,22 +99,14 @@ describe("getMessage", () => {
});
});
-describe("countBufferedMessages", () => {
- it("returns count value", async () => {
- const chain: any = {};
- chain.select = vi.fn(() => chain);
- chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve([{ count: 5 }]));
- const result = await messageQueries.countBufferedMessages(chain, "conv_1");
- expect(result).toBe(5);
- });
- it("returns 0 when no results", async () => {
- const chain: any = {};
- chain.select = vi.fn(() => chain);
- chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve([]));
- const result = await messageQueries.countBufferedMessages(chain, "conv_1");
- expect(result).toBe(0);
+// TC9 — the message.status column (default "active") and the
+// idx_message_conversation_status index survive the buffer teardown.
+describe("message schema (TC9)", () => {
+ it("keeps the status column with default 'active'", () => {
+ expect(message.status).toBeDefined();
+ expect(message.status.name).toBe("status");
+ expect(message.status.notNull).toBe(true);
+ expect(message.status.default).toBe("active");
});
});
diff --git a/src/shared/test/queries/task-message.test.ts b/src/shared/test/queries/task-message.test.ts
index 94282fa8d..4b51cb7c0 100644
--- a/src/shared/test/queries/task-message.test.ts
+++ b/src/shared/test/queries/task-message.test.ts
@@ -1,6 +1,28 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
+import { drizzle } from "drizzle-orm/d1";
+import { eq, and, asc } from "drizzle-orm";
+import { taskMessage, agentTaskQueue } from "../../src/db/schema";
import * as taskMessageQueries from "../../src/db/queries/task-message";
+const fakeDb = drizzle({} as never);
+
+// Chainable mock that captures the .where() argument so we can exercise the REAL
+// query fn (it's async + awaits its builder internally, so we can't .toSQL() the
+// fn's return value directly — the runtime would auto-await a dead connection).
+function createCapturingDb(rows: unknown[]) {
+ const calls: { where?: unknown } = {};
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.innerJoin = vi.fn(() => chain);
+ chain.where = vi.fn((cond: unknown) => {
+ calls.where = cond;
+ return chain;
+ });
+ chain.orderBy = vi.fn(() => Promise.resolve(rows));
+ return { chain, calls };
+}
+
describe("task-message query module exports", () => {
it("exports createTaskMessage", () => {
expect(typeof taskMessageQueries.createTaskMessage).toBe("function");
@@ -10,6 +32,10 @@ describe("task-message query module exports", () => {
expect(typeof taskMessageQueries.listTaskMessages).toBe("function");
});
+ it("exports listTaskErrorMessages", () => {
+ expect(typeof taskMessageQueries.listTaskErrorMessages).toBe("function");
+ });
+
it("exports listTaskMessagesSince", () => {
expect(typeof taskMessageQueries.listTaskMessagesSince).toBe("function");
});
@@ -25,6 +51,53 @@ describe("listTaskMessages", () => {
});
});
+describe("listTaskErrorMessages", () => {
+ it("accepts (db, taskId, workspaceId)", () => {
+ expect(taskMessageQueries.listTaskErrorMessages.length).toBe(3);
+ });
+
+ it("runs the real query: joins, builds a WHERE, and returns the rows", async () => {
+ const rows = [{ id: "tm1", type: "error" }];
+ const { chain, calls } = createCapturingDb(rows);
+ const result = await taskMessageQueries.listTaskErrorMessages(
+ chain,
+ "task-1",
+ "ws-1",
+ );
+ // Exercises the actual fn (not a mirror): it joins, filters, and returns rows.
+ expect(chain.innerJoin).toHaveBeenCalled();
+ expect(chain.where).toHaveBeenCalledTimes(1);
+ expect(calls.where).toBeDefined();
+ expect(result).toEqual(rows);
+ });
+
+ it("compiles the expected WHERE clause (type='error', task + workspace scope)", () => {
+ // Reference SQL for the query above. This documents the intended shape and
+ // catches a regression in the column/filter set; it is a sibling check to
+ // the real-fn test above, not a stand-in for it.
+ const { sql, params } = fakeDb
+ .select()
+ .from(taskMessage)
+ .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))
+ .where(
+ and(
+ eq(taskMessage.taskId, "task-1"),
+ eq(agentTaskQueue.workspaceId, "ws-1"),
+ eq(taskMessage.type, "error"),
+ ),
+ )
+ .orderBy(asc(taskMessage.seq))
+ .toSQL();
+
+ expect(sql).toContain('inner join "agent_task_queue"');
+ expect(sql).toContain('"task_message"."task_id" = ?');
+ expect(sql).toContain('"agent_task_queue"."workspace_id" = ?');
+ expect(sql).toContain('"task_message"."type" = ?');
+ expect(sql).toContain('order by "task_message"."seq" asc');
+ expect(params).toEqual(["task-1", "ws-1", "error"]);
+ });
+});
+
describe("listTaskMessagesSince", () => {
it("accepts (db, taskId, afterSeq)", () => {
expect(taskMessageQueries.listTaskMessagesSince.length).toBe(3);
diff --git a/src/shared/test/schemas/agent-link.test.ts b/src/shared/test/schemas/agent-link.test.ts
new file mode 100644
index 000000000..0938921b9
--- /dev/null
+++ b/src/shared/test/schemas/agent-link.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from "vitest";
+import { UpsertAgentLinkRequestSchema } from "../../src/schemas";
+
+// TC11
+describe("UpsertAgentLinkRequestSchema", () => {
+ it("accepts a valid target_agent_id + instruction", () => {
+ const result = UpsertAgentLinkRequestSchema.parse({
+ target_agent_id: "ag_b",
+ instruction: "DELEGATE when needed",
+ });
+ expect(result.target_agent_id).toBe("ag_b");
+ expect(result.instruction).toBe("DELEGATE when needed");
+ });
+
+ it("accepts an empty instruction string", () => {
+ const result = UpsertAgentLinkRequestSchema.parse({
+ target_agent_id: "ag_b",
+ instruction: "",
+ });
+ expect(result.instruction).toBe("");
+ });
+
+ it("rejects missing target_agent_id", () => {
+ expect(() => UpsertAgentLinkRequestSchema.parse({ instruction: "x" })).toThrow();
+ });
+
+ it("rejects empty target_agent_id", () => {
+ expect(() =>
+ UpsertAgentLinkRequestSchema.parse({ target_agent_id: "", instruction: "x" }),
+ ).toThrow();
+ });
+
+ it("rejects non-string instruction", () => {
+ expect(() =>
+ UpsertAgentLinkRequestSchema.parse({ target_agent_id: "ag_b", instruction: 123 }),
+ ).toThrow();
+ });
+
+ it("rejects missing instruction", () => {
+ expect(() =>
+ UpsertAgentLinkRequestSchema.parse({ target_agent_id: "ag_b" }),
+ ).toThrow();
+ });
+});
diff --git a/src/shared/test/utils/title.test.ts b/src/shared/test/utils/title.test.ts
new file mode 100644
index 000000000..4a11a1b28
--- /dev/null
+++ b/src/shared/test/utils/title.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from "vitest";
+import { truncateTitle } from "../../src/utils/title";
+
+describe("truncateTitle", () => {
+ it("collapses runs of whitespace into single spaces", () => {
+ expect(truncateTitle("hello \n\t world")).toBe("hello world");
+ });
+
+ it("trims leading and trailing whitespace", () => {
+ expect(truncateTitle(" padded title ")).toBe("padded title");
+ });
+
+ it("returns the text unchanged when at or under the cap", () => {
+ const exact = "a".repeat(50);
+ expect(truncateTitle(exact)).toBe(exact);
+ expect(truncateTitle("short")).toBe("short");
+ });
+
+ it("caps at a word boundary and appends an ellipsis", () => {
+ // 60-char input, last space before the 50-char cut is after "boundary".
+ const text =
+ "the quick brown fox jumps over the lazy dog near a boundary marker";
+ const out = truncateTitle(text);
+ expect(out.endsWith("...")).toBe(true);
+ expect(out).not.toContain(" ");
+ // Cut on a space, never mid-word.
+ expect(out.slice(0, -3).endsWith(" ")).toBe(false);
+ expect(out.length).toBeLessThanOrEqual(53); // <=50 word-boundary cut + "..."
+ });
+
+ it("hard-cuts mid-word when there's no late-enough space (lastSpace <= 20)", () => {
+ // One long token (no spaces) — lastSpace is -1, so it slices at maxLen.
+ const text = "x".repeat(80);
+ const out = truncateTitle(text);
+ expect(out).toBe("x".repeat(50) + "...");
+ });
+
+ it("respects a custom maxLen", () => {
+ expect(truncateTitle("hello world", 5)).toBe("hello...");
+ });
+});
diff --git a/src/web/src/app/api/agent-links/route.test.ts b/src/web/src/app/api/agent-links/route.test.ts
index 4eb6777c4..2ae63598d 100644
--- a/src/web/src/app/api/agent-links/route.test.ts
+++ b/src/web/src/app/api/agent-links/route.test.ts
@@ -4,6 +4,10 @@ import { NextRequest } from "next/server";
const mockGetAgent = vi.fn();
const mockListByWorkspace = vi.fn();
const mockCreate = vi.fn();
+const mockUpsertByPair = vi.fn();
+const mockGetByPair = vi.fn();
+const mockUpdate = vi.fn();
+const mockInvalidate = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -20,11 +24,23 @@ vi.mock("@alook/shared", async () => {
agentLink: {
listByWorkspace: (...a: unknown[]) => mockListByWorkspace(...a),
create: (...a: unknown[]) => mockCreate(...a),
+ upsertByPair: (...a: unknown[]) => mockUpsertByPair(...a),
+ getByPair: (...a: unknown[]) => mockGetByPair(...a),
+ update: (...a: unknown[]) => mockUpdate(...a),
},
},
};
});
+vi.mock("@/lib/cache", () => ({
+ invalidate: (...a: unknown[]) => mockInvalidate(...a),
+ cached: (_k: string, _t: number, fn: () => unknown) => fn(),
+ cacheKeys: {
+ agentLinks: (ws: string) => `agentLinks:${ws}`,
+ allColleagues: (ws: string) => `allColleagues:${ws}`,
+ },
+}));
+
vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
@@ -48,7 +64,7 @@ vi.mock("@/lib/api/responses", () => ({
}),
}));
-import { GET, POST } from "./route";
+import { GET, POST, PUT } from "./route";
describe("GET /api/agent-links", () => {
beforeEach(() => vi.clearAllMocks());
@@ -145,3 +161,114 @@ describe("POST /api/agent-links", () => {
expect(res.status).toBe(409);
});
});
+
+describe("PUT /api/agent-links (upsert)", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ function put(body: unknown, query = "?agentId=ag_a") {
+ const req = new NextRequest(`http://localhost/api/agent-links${query}`, {
+ method: "PUT",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ });
+ return PUT(req, {} as any);
+ }
+
+ // TC5
+ it("returns 400 when agentId query param is missing", async () => {
+ const res = await put({ target_agent_id: "ag_b", instruction: "x" }, "");
+ expect(res.status).toBe(400);
+ });
+
+ // TC6
+ it("returns 400 for self-link", async () => {
+ const res = await put({ target_agent_id: "ag_a", instruction: "x" });
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toContain("itself");
+ });
+
+ // TC7 — caller not in workspace
+ it("returns 404 when calling agent not found", async () => {
+ mockGetAgent.mockResolvedValueOnce(null).mockResolvedValueOnce({ id: "ag_b" });
+ const res = await put({ target_agent_id: "ag_b", instruction: "x" });
+ expect(res.status).toBe(404);
+ });
+
+ // TC7 — target not in workspace
+ it("returns 404 when target agent not found", async () => {
+ mockGetAgent.mockResolvedValueOnce({ id: "ag_a" }).mockResolvedValueOnce(null);
+ const res = await put({ target_agent_id: "ag_nope", instruction: "x" });
+ expect(res.status).toBe(404);
+ });
+
+ // TC8
+ it("creates a new pair -> 201, created:true, invalidates caches", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_x" });
+ mockUpsertByPair.mockResolvedValue({
+ row: {
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "delegate",
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T00:00:00.000Z",
+ },
+ created: true,
+ });
+ const res = await put({ target_agent_id: "ag_b", instruction: "delegate" });
+ expect(res.status).toBe(201);
+ const body = await res.json();
+ expect(body.created).toBe(true);
+ expect(body.instruction).toBe("delegate");
+ expect(mockInvalidate).toHaveBeenCalledWith("allColleagues:ws1");
+ expect(mockInvalidate).toHaveBeenCalledWith("agentLinks:ws1");
+ });
+
+ // TC9
+ it("updates an existing pair -> 200, created:false, replaced instruction", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_x" });
+ mockUpsertByPair.mockResolvedValue({
+ row: {
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "new instruction",
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T01:00:00.000Z",
+ },
+ created: false,
+ });
+ const res = await put({ target_agent_id: "ag_b", instruction: "new instruction" });
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.created).toBe(false);
+ expect(body.instruction).toBe("new instruction");
+ });
+
+ // TC10
+ it("falls back to update on a concurrent-create unique race (no throw)", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_x" });
+ const uniqueErr = new Error("UNIQUE constraint failed");
+ (uniqueErr as any).code = "SQLITE_CONSTRAINT_UNIQUE";
+ mockUpsertByPair.mockRejectedValue(uniqueErr);
+ mockGetByPair.mockResolvedValue({ id: "al_1", workspaceId: "ws1" });
+ mockUpdate.mockResolvedValue({
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "raced",
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T02:00:00.000Z",
+ });
+ const res = await put({ target_agent_id: "ag_b", instruction: "raced" });
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.created).toBe(false);
+ expect(body.instruction).toBe("raced");
+ expect(mockUpdate).toHaveBeenCalled();
+ });
+});
diff --git a/src/web/src/app/api/agent-links/route.ts b/src/web/src/app/api/agent-links/route.ts
index 997788d54..fe7f1a4cb 100644
--- a/src/web/src/app/api/agent-links/route.ts
+++ b/src/web/src/app/api/agent-links/route.ts
@@ -3,6 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare";
import {
queries,
CreateAgentLinkRequestSchema,
+ UpsertAgentLinkRequestSchema,
isUniqueConstraintError,
} from "@alook/shared";
import { getDb } from "@/lib/db";
@@ -75,3 +76,64 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
throw e;
}
});
+
+// PUT /api/agent-links?agentId=<caller> — upsert (create-or-replace) the
+// relationship between the calling agent and a target agent. Idempotent: a new
+// pair is created (201), an existing pair has its instruction replaced (200).
+export const PUT = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const agentId = new URL(req.url).searchParams.get("agentId");
+ if (!agentId) {
+ return writeError("agentId query param is required", 400);
+ }
+
+ const [body, err] = await parseBody(req, UpsertAgentLinkRequestSchema);
+ if (err) return err;
+
+ if (agentId === body.target_agent_id) {
+ return writeError("cannot link an agent to itself", 400);
+ }
+
+ const [callerAgent, targetAgent] = await Promise.all([
+ queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId),
+ queries.agent.getAgent(db, body.target_agent_id, ws.workspaceId, ctx.userId),
+ ]);
+ if (!callerAgent) return writeError("calling agent not found in workspace", 404);
+ if (!targetAgent) return writeError("target agent not found in workspace", 404);
+
+ let row, created;
+ try {
+ ({ row, created } = await queries.agentLink.upsertByPair(db, {
+ workspaceId: ws.workspaceId,
+ sourceAgentId: agentId,
+ targetAgentId: body.target_agent_id,
+ instruction: body.instruction,
+ }));
+ } catch (e) {
+ if (!isUniqueConstraintError(e)) throw e;
+ // Lost a concurrent create race — the row now exists; fall back to update.
+ const existing = await queries.agentLink.getByPair(
+ db,
+ ws.workspaceId,
+ agentId,
+ body.target_agent_id,
+ );
+ if (!existing) throw e;
+ row = await queries.agentLink.update(db, existing.id, ws.workspaceId, {
+ instruction: body.instruction,
+ });
+ created = false;
+ }
+
+ await Promise.all([
+ invalidate(cacheKeys.allColleagues(ws.workspaceId)),
+ invalidate(cacheKeys.agentLinks(ws.workspaceId)),
+ ]);
+
+ return writeJSON({ ...agentLinkToResponse(row), created }, created ? 201 : 200);
+});
diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.test.ts b/src/web/src/app/api/agents/[id]/chat-init/route.test.ts
index 93ad3fcdf..77cbc5bcf 100644
--- a/src/web/src/app/api/agents/[id]/chat-init/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/chat-init/route.test.ts
@@ -9,9 +9,8 @@ const mockGetOrCreateAgentConversation = vi.fn();
const mockHasPreviousConversations = vi.fn();
const mockListMessages = vi.fn();
const mockListArtifactsByConversation = vi.fn();
-const mockListBufferedMessages = vi.fn();
const mockGetActiveTaskByConversation = vi.fn();
-const mockListTaskMessages = vi.fn();
+const mockListTaskErrorMessages = vi.fn();
const mockArtifactToResponse = vi.fn((r: any) => ({
id: r.id,
conversation_id: r.conversationId,
@@ -39,8 +38,6 @@ vi.mock("@alook/shared", () => ({
},
message: {
listMessages: (...args: unknown[]) => mockListMessages(...args),
- listBufferedMessages: (...args: unknown[]) =>
- mockListBufferedMessages(...args),
},
artifact: {
listArtifactsByConversation: (...args: unknown[]) =>
@@ -53,8 +50,8 @@ vi.mock("@alook/shared", () => ({
mockGetActiveTaskByConversation(...args),
},
taskMessage: {
- listTaskMessages: (...args: unknown[]) =>
- mockListTaskMessages(...args),
+ listTaskErrorMessages: (...args: unknown[]) =>
+ mockListTaskErrorMessages(...args),
},
},
}));
@@ -71,13 +68,6 @@ vi.mock("@/lib/middleware/workspace", () => ({
withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
}));
-const mockDispatchNextBufferedMessage = vi.fn().mockResolvedValue(null);
-vi.mock("@/lib/services/task", () => ({
- TaskService: vi.fn(() => ({
- dispatchNextBufferedMessage: mockDispatchNextBufferedMessage,
- })),
-}));
-
vi.mock("@/lib/api/responses", () => ({
conversationToResponse: vi.fn((c: any) => ({
id: c.id,
@@ -132,7 +122,6 @@ function setupDefaults() {
mockHasPreviousConversations.mockResolvedValue(false);
mockListMessages.mockResolvedValue({ messages: [], has_more: false });
mockListArtifactsByConversation.mockResolvedValue([]);
- mockListBufferedMessages.mockResolvedValue([]);
mockGetActiveTaskByConversation.mockResolvedValue(null);
}
@@ -162,7 +151,6 @@ describe("POST /api/agents/[id]/chat-init", () => {
mockHasPreviousConversations.mockResolvedValue(false);
mockListMessages.mockResolvedValue({ messages: [msg], has_more: false });
mockListArtifactsByConversation.mockResolvedValue([artifact]);
- mockListBufferedMessages.mockResolvedValue([]);
mockGetActiveTaskByConversation.mockResolvedValue(null);
const res = await POST(makeReq(), makeCtx());
@@ -174,7 +162,6 @@ describe("POST /api/agents/[id]/chat-init", () => {
expect(body.messages[0].id).toBe("m1");
expect(body.artifacts).toHaveLength(1);
expect(body.artifacts[0].id).toBe("art1");
- expect(body.buffered_messages).toEqual([]);
expect(body.active_task).toBeNull();
expect(body.task_messages).toEqual([]);
expect(body.has_more_messages).toBe(false);
@@ -192,7 +179,7 @@ describe("POST /api/agents/[id]/chat-init", () => {
expect(body.error).toBe("agent not found");
});
- it("includes active task and task messages when task is running", async () => {
+ it("preloads error task messages (workspace-scoped) for a running task", async () => {
const task = {
id: "t1",
agentId: "a1",
@@ -207,17 +194,12 @@ describe("POST /api/agents/[id]/chat-init", () => {
completedAt: null,
createdAt: "2024-01-01T00:00:00.000Z",
};
- const tmsg = {
- id: "tm1",
- taskId: "t1",
- seq: 1,
- type: "text",
- content: "working...",
- };
+ // The query filters to type:"error" in SQL; the route maps what it returns.
+ const errMsg = { id: "tm2", taskId: "t1", seq: 2, type: "error", content: "boom" };
setupDefaults();
mockGetActiveTaskByConversation.mockResolvedValue(task);
- mockListTaskMessages.mockResolvedValue([tmsg]);
+ mockListTaskErrorMessages.mockResolvedValue([errMsg]);
const res = await POST(makeReq(), makeCtx());
const body = await res.json();
@@ -225,34 +207,28 @@ describe("POST /api/agents/[id]/chat-init", () => {
expect(body.active_task).not.toBeNull();
expect(body.active_task.id).toBe("t1");
expect(body.task_messages).toHaveLength(1);
- expect(body.task_messages[0].seq).toBe(1);
+ expect(body.task_messages[0].seq).toBe(2);
+ expect(body.task_messages[0].type).toBe("error");
+ // Scoped to the active task and the authed workspace.
+ expect(mockListTaskErrorMessages).toHaveBeenCalledWith(
+ expect.anything(),
+ "t1",
+ "w1",
+ );
});
- it("skips task messages for completed tasks", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- runtimeId: "r1",
- conversationId: "c1",
- workspaceId: "w1",
- prompt: "do stuff",
- status: "completed",
- priority: 0,
- dispatchedAt: null,
- startedAt: null,
- completedAt: "2024-01-01T00:01:00.000Z",
- createdAt: "2024-01-01T00:00:00.000Z",
- };
-
+ it("does not query task errors when there is no active task", async () => {
+ // A run that ended in error is settled to status:"failed" and re-surfaces via
+ // its persisted assistant error message (not through this preload).
setupDefaults();
- mockGetActiveTaskByConversation.mockResolvedValue(task);
+ mockGetActiveTaskByConversation.mockResolvedValue(null);
const res = await POST(makeReq(), makeCtx());
const body = await res.json();
- expect(body.active_task.id).toBe("t1");
+ expect(body.active_task).toBeNull();
expect(body.task_messages).toEqual([]);
- expect(mockListTaskMessages).not.toHaveBeenCalled();
+ expect(mockListTaskErrorMessages).not.toHaveBeenCalled();
});
it("sets has_more_messages true when messages reach limit", async () => {
@@ -316,7 +292,6 @@ describe("POST /api/agents/[id]/chat-init", () => {
expect(res.status).toBe(200);
expect(body.messages).toEqual([]);
expect(body.artifacts).toEqual([]);
- expect(body.buffered_messages).toEqual([]);
expect(body.active_task).toBeNull();
expect(body.has_more_messages).toBe(false);
});
diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.ts b/src/web/src/app/api/agents/[id]/chat-init/route.ts
index b9409ab61..53fee17ca 100644
--- a/src/web/src/app/api/agents/[id]/chat-init/route.ts
+++ b/src/web/src/app/api/agents/[id]/chat-init/route.ts
@@ -10,7 +10,6 @@ import {
taskToResponse,
taskMessageToResponse,
} from "@/lib/api/responses";
-import { TaskService } from "@/lib/services/task";
const MESSAGE_LIMIT = 20;
const ARTIFACT_LIMIT = 50;
@@ -50,13 +49,12 @@ export const POST = withAuth(async (req, ctx) => {
const convId = conversation.id;
- const [messagesResult, artifactsResult, bufferedResult, activeTaskResult, hasMoreConvsResult] =
+ const [messagesResult, artifactsResult, activeTaskResult, hasMoreConvsResult] =
await Promise.allSettled([
queries.message.listMessages(db, convId, { limit: MESSAGE_LIMIT }),
queries.artifact.listArtifactsByConversation(db, convId, ws.workspaceId, {
limit: ARTIFACT_LIMIT,
}),
- queries.message.listBufferedMessages(db, convId),
queries.task.getActiveTaskByConversation(db, convId, ws.workspaceId),
queries.conversation.hasPreviousConversations(
db, ws.workspaceId, ctx.userId, id, convId, channel,
@@ -69,8 +67,6 @@ export const POST = withAuth(async (req, ctx) => {
: { messages: [] as never[], has_more: false };
const artifacts =
artifactsResult.status === "fulfilled" ? artifactsResult.value : [];
- const buffered =
- bufferedResult.status === "fulfilled" ? bufferedResult.value : [];
const activeTask =
activeTaskResult.status === "fulfilled"
? activeTaskResult.value
@@ -78,33 +74,19 @@ export const POST = withAuth(async (req, ctx) => {
const hasMoreConvs =
hasMoreConvsResult.status === "fulfilled" ? hasMoreConvsResult.value : false;
- // Recover orphaned buffered messages: if there are buffered messages but no
- // active task, dispatch the first one now (handles race where task completed
- // just before/after the message was buffered).
- let resolvedActiveTask = activeTask;
- let resolvedBuffered = buffered;
- if (resolvedBuffered.length > 0 && !resolvedActiveTask) {
- try {
- const taskService = new TaskService(db);
- const dispatched = await taskService.dispatchNextBufferedMessage(convId, ws.workspaceId);
- if (dispatched) {
- resolvedActiveTask = dispatched;
- resolvedBuffered = await queries.message.listBufferedMessages(db, convId);
- }
- } catch {
- // non-critical — user can still send a new message to unstick
- }
- }
-
let taskMessages: unknown[] = [];
- if (
- resolvedActiveTask &&
- !["completed", "failed", "cancelled", "superseded"].includes(resolvedActiveTask.status)
- ) {
+ if (activeTask) {
try {
- const tmsgs = await queries.taskMessage.listTaskMessages(
+ // Errors-only: the chat no longer renders thinking/tool steps (replies
+ // arrive via `send-dm`). We preload only `type:"error"` rows for the active
+ // task so a live error survives a reload while the run is still active.
+ // (A run that ended in error is settled to status:"failed" by the daemon and
+ // re-surfaces via its persisted assistant error message, not through here.)
+ // Filters type==="error" + scopes by workspace in SQL.
+ const tmsgs = await queries.taskMessage.listTaskErrorMessages(
db,
- resolvedActiveTask.id,
+ activeTask.id,
+ ws.workspaceId,
);
taskMessages = tmsgs.map(taskMessageToResponse);
} catch {
@@ -116,8 +98,7 @@ export const POST = withAuth(async (req, ctx) => {
conversation: conversationToResponse(conversation),
messages: messages.map(messageToResponse),
artifacts: artifacts.map(queries.artifact.artifactToResponse),
- buffered_messages: resolvedBuffered.map(messageToResponse),
- active_task: resolvedActiveTask ? taskToResponse(resolvedActiveTask) : null,
+ active_task: activeTask ? taskToResponse(activeTask) : null,
task_messages: taskMessages,
has_more_messages: hasMoreMessages,
has_more_conversations: hasMoreConvs,
diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts b/src/web/src/app/api/conversations/[id]/active-task/route.test.ts
index 9b0b487f0..ba4fb9d3d 100644
--- a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/active-task/route.test.ts
@@ -35,8 +35,6 @@ vi.mock("@alook/shared", () => ({
},
message: {
createMessage: vi.fn(),
- activateNextBufferedMessage: vi.fn(),
- revertToBuffered: vi.fn(),
},
},
}));
diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.test.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.test.ts
deleted file mode 100644
index e5a248409..000000000
--- a/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
-}));
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
-
-const mockGetConversation = vi.fn();
-const mockGetMessage = vi.fn();
-const mockDeleteBuffered = vi.fn();
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual("@alook/shared");
- return {
- ...actual,
- queries: {
- conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },
- message: {
- getMessage: (...a: unknown[]) => mockGetMessage(...a),
- deleteBufferedMessage: (...a: unknown[]) => mockDeleteBuffered(...a),
- },
- },
- };
-});
-
-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: "w1" })),
-}));
-vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));
-
-import { DELETE } from "./route";
-
-beforeEach(() => vi.clearAllMocks());
-
-function del(params: Record<string, string>) {
- const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages/m1", {
- method: "DELETE",
- });
- return DELETE(req, { params });
-}
-
-describe("DELETE /api/conversations/[id]/buffered-messages/[messageId]", () => {
- it("deletes a buffered message scoped to the workspace conversation", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1" });
- mockGetMessage.mockResolvedValue({ id: "m1", conversationId: "c1", status: "buffered" });
- mockDeleteBuffered.mockResolvedValue(undefined);
-
- const res = await del({ id: "c1", messageId: "m1" });
- expect(res.status).toBe(204);
- expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
- expect(mockDeleteBuffered).toHaveBeenCalledWith({}, "m1");
- });
-
- it("400 when conversation id missing", async () => {
- const res = await del({ messageId: "m1" });
- expect(res.status).toBe(400);
- });
-
- it("400 when message id missing", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1" });
- const res = await del({ id: "c1" });
- expect(res.status).toBe(400);
- });
-
- it("404 when conversation not in workspace", async () => {
- mockGetConversation.mockResolvedValue(null);
- const res = await del({ id: "c1", messageId: "m1" });
- expect(res.status).toBe(404);
- });
-
- it("404 when message not found or belongs to a different conversation (IDOR guard)", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1" });
- mockGetMessage.mockResolvedValue({ id: "m1", conversationId: "OTHER", status: "buffered" });
- const res = await del({ id: "c1", messageId: "m1" });
- expect(res.status).toBe(404);
- expect(mockDeleteBuffered).not.toHaveBeenCalled();
- });
-
- it("400 when message is not in buffered status", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1" });
- mockGetMessage.mockResolvedValue({ id: "m1", conversationId: "c1", status: "sent" });
- const res = await del({ id: "c1", messageId: "m1" });
- expect(res.status).toBe(400);
- expect((await res.json()).error).toBe("message is not buffered");
- });
-});
diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.ts
deleted file mode 100644
index 894cd6631..000000000
--- a/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { getCloudflareContext } from "@opennextjs/cloudflare";
-import { queries } from "@alook/shared";
-import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth";
-import { withWorkspaceMember } from "@/lib/middleware/workspace";
-import { writeError } from "@/lib/middleware/helpers";
-import { broadcastToUser } from "@/lib/broadcast";
-
-export const DELETE = withAuth(async (req, ctx) => {
- const ws = await withWorkspaceMember(req, ctx);
- if (ws instanceof Response) return ws;
-
- const { env } = getCloudflareContext();
- const db = getDb((env as Env).DB);
-
- const conversationId = ctx.params?.id;
- const messageId = ctx.params?.messageId;
- if (!conversationId) return writeError("conversation id is required", 400);
- if (!messageId) return writeError("message id is required", 400);
-
- const conversation = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
- if (!conversation) return writeError("conversation not found", 404);
-
- const msg = await queries.message.getMessage(db, messageId);
- if (!msg || msg.conversationId !== conversationId) {
- return writeError("message not found", 404);
- }
- if (msg.status !== "buffered") {
- return writeError("message is not buffered", 400);
- }
-
- await queries.message.deleteBufferedMessage(db, messageId);
-
- broadcastToUser(ctx.userId, {
- type: "followup.deleted",
- conversationId,
- messageId,
- }).catch(() => {});
-
- return new Response(null, { status: 204 });
-});
diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/route.test.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/route.test.ts
deleted file mode 100644
index 4bbd12759..000000000
--- a/src/web/src/app/api/conversations/[id]/buffered-messages/route.test.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { NextRequest } from "next/server";
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { put: vi.fn() } } })),
-}));
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
-vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "xyz") }));
-
-const mockGetConversation = vi.fn();
-const mockListBuffered = vi.fn();
-const mockCountBuffered = vi.fn();
-const mockCreateBuffered = vi.fn();
-const mockDeleteAllBuffered = vi.fn();
-const mockGetActiveTask = vi.fn();
-
-vi.mock("@alook/shared", async () => {
- const actual = await vi.importActual("@alook/shared");
- return {
- ...actual,
- parsePromptMentions: vi.fn((c: string) => ({ enrichedPrompt: c })),
- queries: {
- conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },
- message: {
- listBufferedMessages: (...a: unknown[]) => mockListBuffered(...a),
- countBufferedMessages: (...a: unknown[]) => mockCountBuffered(...a),
- createBufferedMessage: (...a: unknown[]) => mockCreateBuffered(...a),
- deleteAllBufferedMessages: (...a: unknown[]) => mockDeleteAllBuffered(...a),
- },
- task: { getActiveTaskByConversation: (...a: unknown[]) => mockGetActiveTask(...a) },
- artifact: { createArtifact: vi.fn() },
- agent: { listAgents: vi.fn().mockResolvedValue([]) },
- },
- };
-});
-
-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: "w1" })),
-}));
-vi.mock("@/lib/api/responses", () => ({
- messageToResponse: vi.fn((m: any) => ({ id: m.id, content: m.content })),
-}));
-vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));
-vi.mock("@/lib/cache", () => ({
- invalidate: vi.fn().mockResolvedValue(undefined),
- cacheKeys: { overviewTaskStats: (w: string, d: string) => `ov:${w}:${d}` },
-}));
-const mockDispatch = vi.fn().mockResolvedValue(null);
-vi.mock("@/lib/services/task", () => ({
- TaskService: function () { return { dispatchNextBufferedMessage: mockDispatch }; },
-}));
-
-import { GET, POST, DELETE } from "./route";
-
-beforeEach(() => vi.clearAllMocks());
-
-describe("GET /api/conversations/[id]/buffered-messages", () => {
- it("lists buffered messages for a workspace conversation", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
- mockListBuffered.mockResolvedValue([{ id: "m1", content: "hi" }]);
-
- const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages");
- const res = await GET(req, { params: { id: "c1" } });
- expect(res.status).toBe(200);
- expect(await res.json()).toEqual([{ id: "m1", content: "hi" }]);
- expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
- });
-
- it("400 when id missing", async () => {
- const req = new NextRequest("http://localhost/api/conversations/x/buffered-messages");
- const res = await GET(req, { params: {} });
- expect(res.status).toBe(400);
- });
-
- it("404 when conversation not in workspace", async () => {
- mockGetConversation.mockResolvedValue(null);
- const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages");
- const res = await GET(req, { params: { id: "c1" } });
- expect(res.status).toBe(404);
- });
-});
-
-describe("POST /api/conversations/[id]/buffered-messages (JSON)", () => {
- function post(body: unknown, id = "c1") {
- const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- });
- return POST(req, { params: { id } });
- }
-
- it("creates a buffered message and dispatches when no active task", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
- mockCountBuffered.mockResolvedValue(0);
- mockCreateBuffered.mockResolvedValue({ id: "m1", content: "hello" });
- mockGetActiveTask.mockResolvedValue(null);
-
- const res = await post({ content: "hello" });
- expect(res.status).toBe(201);
- expect((await res.json()).message).toEqual({ id: "m1", content: "hello" });
- expect(mockDispatch).toHaveBeenCalledWith("c1", "w1");
- });
-
- it("does NOT dispatch when an active task already exists", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
- mockCountBuffered.mockResolvedValue(0);
- mockCreateBuffered.mockResolvedValue({ id: "m1", content: "hello" });
- mockGetActiveTask.mockResolvedValue({ id: "t1" });
-
- const res = await post({ content: "hello" });
- expect(res.status).toBe(201);
- expect(mockDispatch).not.toHaveBeenCalled();
- });
-
- it("404 when conversation not in workspace", async () => {
- mockGetConversation.mockResolvedValue(null);
- const res = await post({ content: "hello" });
- expect(res.status).toBe(404);
- });
-
- it("429 when buffered limit reached", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
- mockCountBuffered.mockResolvedValue(20);
- const res = await post({ content: "hello" });
- expect(res.status).toBe(429);
- });
-
- it("400 on invalid JSON body (schema validation)", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
- mockCountBuffered.mockResolvedValue(0);
- const res = await post({ notContent: 1 });
- expect(res.status).toBe(400);
- });
-});
-
-describe("DELETE /api/conversations/[id]/buffered-messages", () => {
- it("clears all buffered messages (204)", async () => {
- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
- mockDeleteAllBuffered.mockResolvedValue([{ id: "m1" }, { id: "m2" }]);
-
- const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages", {
- method: "DELETE",
- });
- const res = await DELETE(req, { params: { id: "c1" } });
- expect(res.status).toBe(204);
- expect(mockDeleteAllBuffered).toHaveBeenCalledWith({}, "c1");
- });
-
- it("404 when conversation not in workspace", async () => {
- mockGetConversation.mockResolvedValue(null);
- const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages", {
- method: "DELETE",
- });
- const res = await DELETE(req, { params: { id: "c1" } });
- expect(res.status).toBe(404);
- });
-});
diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts
deleted file mode 100644
index 1320a7b24..000000000
--- a/src/web/src/app/api/conversations/[id]/buffered-messages/route.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import { NextRequest } from "next/server";
-import { getCloudflareContext } from "@opennextjs/cloudflare";
-import {
- queries,
- CreateBufferedMessageRequestSchema,
- parsePromptMentions,
-} from "@alook/shared";
-import { getDb } from "@/lib/db";
-import { nanoid } from "nanoid";
-import { withAuth } from "@/lib/middleware/auth";
-import { withWorkspaceMember } from "@/lib/middleware/workspace";
-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
-import { messageToResponse } from "@/lib/api/responses";
-import { broadcastToUser } from "@/lib/broadcast";
-import { TaskService } from "@/lib/services/task";
-import { invalidate, cacheKeys } from "@/lib/cache";
-
-const MAX_FILE_SIZE = 10 * 1024 * 1024;
-const MAX_FILES = 10;
-const MAX_BUFFERED = 20;
-
-function sanitizeFilename(name: string): string {
- return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
-}
-
-export const GET = withAuth(async (req, ctx) => {
- const ws = await withWorkspaceMember(req, ctx);
- if (ws instanceof Response) return ws;
-
- const { env } = getCloudflareContext();
- const db = getDb((env as Env).DB);
-
- const id = ctx.params?.id;
- if (!id) return writeError("conversation id is required", 400);
-
- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) return writeError("conversation not found", 404);
-
- const buffered = await queries.message.listBufferedMessages(db, id);
- return writeJSON(buffered.map(messageToResponse));
-});
-
-export const POST = withAuth(async (req: NextRequest, ctx) => {
- const ws = await withWorkspaceMember(req, ctx);
- if (ws instanceof Response) return ws;
-
- const { env } = getCloudflareContext();
- const db = getDb((env as Env).DB);
- const bucket = (env as Env).EMAIL_BUCKET;
-
- const id = ctx.params?.id;
- if (!id) return writeError("conversation id is required", 400);
-
- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) return writeError("conversation not found", 404);
-
- const existing = await queries.message.countBufferedMessages(db, id);
- if (existing >= MAX_BUFFERED) {
- return writeError(`maximum ${MAX_BUFFERED} buffered messages reached`, 429);
- }
-
- const contentType = req.headers.get("content-type") ?? "";
- const isMultipart = contentType.includes("multipart/form-data");
-
- let content: string;
- const files: File[] = [];
-
- if (isMultipart) {
- let formData: FormData;
- try {
- formData = await req.formData();
- } catch {
- return writeError("invalid form data", 400);
- }
- content = ((formData.get("content") as string) ?? "").trim();
- for (const [key, value] of formData.entries()) {
- if (key === "file" && value instanceof File) {
- files.push(value);
- }
- }
- if (!content) {
- return writeError("content is required", 400);
- }
- } else {
- const [body, valErr] = await parseBody(req, CreateBufferedMessageRequestSchema);
- if (valErr) return valErr;
- content = body.content;
- }
-
- if (files.length > MAX_FILES) {
- return writeError(`too many files (max ${MAX_FILES})`, 400);
- }
- for (const file of files) {
- if (file.size > MAX_FILE_SIZE) {
- return writeError(`file "${file.name}" exceeds 10 MB limit`, 413);
- }
- }
-
- const artifactIds: string[] = [];
- for (const file of files) {
- const filename = sanitizeFilename(file.name);
- const fileContentType = file.type || "application/octet-stream";
- const artifactId = "art_" + nanoid();
- const r2Key = `artifacts/${ws.workspaceId}/${conversation.agentId}/${id}/${artifactId}/${filename}`;
-
- await bucket.put(r2Key, await file.arrayBuffer(), {
- httpMetadata: { contentType: fileContentType },
- });
-
- await queries.artifact.createArtifact(db, {
- id: artifactId,
- conversationId: id,
- agentId: conversation.agentId,
- workspaceId: ws.workspaceId,
- filename,
- contentType: fileContentType,
- size: file.size,
- r2Key,
- source: "attachment",
- });
-
- artifactIds.push(artifactId);
- }
-
- let enrichedContent = content;
- if (content.includes("@")) {
- try {
- const agentList = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);
- const { enrichedPrompt } = parsePromptMentions(content, agentList);
- enrichedContent = enrichedPrompt;
- } catch {
- // Fail-open: pass content through unmodified
- }
- }
-
- const message = await queries.message.createBufferedMessage(db, {
- conversationId: id,
- content: enrichedContent,
- attachmentIds: artifactIds.length > 0 ? JSON.stringify(artifactIds) : null,
- });
-
- broadcastToUser(ctx.userId, {
- type: "followup.created",
- conversationId: id,
- message: messageToResponse(message),
- }).catch(() => {});
-
- // If no active task, dispatch immediately (handles race where task completed
- // just before this message was buffered)
- const activeTask = await queries.task.getActiveTaskByConversation(db, id, ws.workspaceId);
- if (!activeTask) {
- const taskService = new TaskService(db);
- taskService.dispatchNextBufferedMessage(id, ws.workspaceId).catch(() => {});
- const dateStr = new Date().toISOString().slice(0, 10);
- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});
- }
-
- return writeJSON({ message: messageToResponse(message) }, 201);
-});
-
-export const DELETE = withAuth(async (req, ctx) => {
- const ws = await withWorkspaceMember(req, ctx);
- if (ws instanceof Response) return ws;
-
- const { env } = getCloudflareContext();
- const db = getDb((env as Env).DB);
-
- const id = ctx.params?.id;
- if (!id) return writeError("conversation id is required", 400);
-
- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);
- if (!conversation) return writeError("conversation not found", 404);
-
- const deleted = await queries.message.deleteAllBufferedMessages(db, id);
- for (const msg of deleted) {
- broadcastToUser(ctx.userId, {
- type: "followup.deleted",
- conversationId: id,
- messageId: msg.id,
- }).catch(() => {});
- }
-
- return new Response(null, { status: 204 });
-});
diff --git a/src/web/src/app/api/conversations/[id]/init/route.test.ts b/src/web/src/app/api/conversations/[id]/init/route.test.ts
index 103266e2a..f35b30583 100644
--- a/src/web/src/app/api/conversations/[id]/init/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/init/route.test.ts
@@ -12,12 +12,10 @@ const m = {
getActiveMessageCount: vi.fn(),
listMessages: vi.fn(),
listArtifactsByConversation: vi.fn(),
- listBufferedMessages: vi.fn(),
getActiveTaskByConversation: vi.fn(),
listFlaggedMessageIds: vi.fn(),
hasPreviousConversations: vi.fn(),
- listTaskMessages: vi.fn(),
- countTextMessagesByTaskIds: vi.fn(),
+ listTaskErrorMessages: vi.fn(),
};
vi.mock("@alook/shared", async () => {
@@ -33,7 +31,6 @@ vi.mock("@alook/shared", async () => {
getNewestMessageId: (...a: unknown[]) => m.getNewestMessageId(...a),
getActiveMessageCount: (...a: unknown[]) => m.getActiveMessageCount(...a),
listMessages: (...a: unknown[]) => m.listMessages(...a),
- listBufferedMessages: (...a: unknown[]) => m.listBufferedMessages(...a),
},
artifact: {
listArtifactsByConversation: (...a: unknown[]) => m.listArtifactsByConversation(...a),
@@ -42,8 +39,7 @@ vi.mock("@alook/shared", async () => {
task: { getActiveTaskByConversation: (...a: unknown[]) => m.getActiveTaskByConversation(...a) },
messageFlag: { listFlaggedMessageIds: (...a: unknown[]) => m.listFlaggedMessageIds(...a) },
taskMessage: {
- listTaskMessages: (...a: unknown[]) => m.listTaskMessages(...a),
- countTextMessagesByTaskIds: (...a: unknown[]) => m.countTextMessagesByTaskIds(...a),
+ listTaskErrorMessages: (...a: unknown[]) => m.listTaskErrorMessages(...a),
},
},
};
@@ -64,17 +60,12 @@ vi.mock("@/lib/api/responses", () => ({
taskToResponse: (t: any) => ({ id: t.id }),
taskMessageToResponse: (tm: any) => ({ id: tm.id }),
}));
-vi.mock("@/lib/services/task", () => ({
- TaskService: function () { return { dispatchNextBufferedMessage: vi.fn().mockResolvedValue(null) }; },
-}));
-
import { GET } from "./route";
beforeEach(() => {
vi.clearAllMocks();
m.listMessages.mockResolvedValue({ messages: [], has_more: false });
m.listArtifactsByConversation.mockResolvedValue([]);
- m.listBufferedMessages.mockResolvedValue([]);
m.getActiveTaskByConversation.mockResolvedValue(null);
m.listFlaggedMessageIds.mockResolvedValue([]);
m.hasPreviousConversations.mockResolvedValue(false);
@@ -112,6 +103,39 @@ describe("GET /api/conversations/[id]/init", () => {
expect(body.cache_valid).toBe(false);
});
+ it("preloads error task messages (workspace-scoped) for a running active task", async () => {
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.getActiveTaskByConversation.mockResolvedValue({ id: "t1", status: "running" });
+ // The query filters to type:"error" in SQL, so the route maps whatever it returns.
+ m.listTaskErrorMessages.mockResolvedValue([
+ { id: "tm2", seq: 2, type: "error", content: "boom" },
+ ]);
+
+ const req = new NextRequest("http://localhost/api/conversations/c1/init");
+ const res = await GET(req, { params: { id: "c1" } });
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.task_messages).toEqual([{ id: "tm2" }]);
+ // Scoped to the authed workspace and the active task.
+ expect(m.listTaskErrorMessages).toHaveBeenCalledWith(expect.anything(), "t1", "w1");
+ });
+
+ it("does not query task errors when there is no active task", async () => {
+ // A run that ended in error is settled to status:"failed" and re-surfaces via
+ // its persisted assistant error message (not through this preload).
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.getActiveTaskByConversation.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/conversations/c1/init");
+ const res = await GET(req, { params: { id: "c1" } });
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.task_messages).toEqual([]);
+ expect(m.listTaskErrorMessages).not.toHaveBeenCalled();
+ });
+
it("returns cache_valid=true and null messages when client cache matches", async () => {
m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
m.getNewestMessageId.mockResolvedValue("m9");
diff --git a/src/web/src/app/api/conversations/[id]/init/route.ts b/src/web/src/app/api/conversations/[id]/init/route.ts
index ff4d85d02..c81912c3e 100644
--- a/src/web/src/app/api/conversations/[id]/init/route.ts
+++ b/src/web/src/app/api/conversations/[id]/init/route.ts
@@ -10,7 +10,6 @@ import {
taskToResponse,
taskMessageToResponse,
} from "@/lib/api/responses";
-import { TaskService } from "@/lib/services/task";
const MESSAGE_LIMIT = 20;
const ARTIFACT_LIMIT = 50;
@@ -48,13 +47,12 @@ export const GET = withAuth(async (req, ctx) => {
cacheValid = idMatches && countMatches;
}
- const [messagesResult, artifacts, buffered, activeTask, flaggedMessageIds, hasMoreConversations] =
+ const [messagesResult, artifacts, activeTask, flaggedMessageIds, hasMoreConversations] =
await Promise.all([
queries.message.listMessages(db, id, { limit: MESSAGE_LIMIT }),
queries.artifact.listArtifactsByConversation(db, id, ws.workspaceId, {
limit: ARTIFACT_LIMIT,
}).catch(() => [] as Awaited<ReturnType<typeof queries.artifact.listArtifactsByConversation>>),
- queries.message.listBufferedMessages(db, id).catch(() => [] as Awaited<ReturnType<typeof queries.message.listBufferedMessages>>),
queries.task.getActiveTaskByConversation(db, id, ws.workspaceId).catch(() => null),
queries.messageFlag.listFlaggedMessageIds(db, ctx.userId, ws.workspaceId, id).catch(() => [] as string[]),
queries.conversation.hasPreviousConversations(
@@ -69,60 +67,26 @@ export const GET = withAuth(async (req, ctx) => {
const { messages, has_more: hasMoreMessages } = messagesResult;
- // Orphaned-buffer recovery
- let resolvedActiveTask = activeTask;
- let resolvedBuffered = buffered;
- if (resolvedBuffered.length > 0 && !resolvedActiveTask) {
- try {
- const taskService = new TaskService(db);
- const dispatched = await taskService.dispatchNextBufferedMessage(id, ws.workspaceId);
- if (dispatched) {
- resolvedActiveTask = dispatched;
- resolvedBuffered = await queries.message.listBufferedMessages(db, id);
- }
- } catch {
- // non-critical
- }
- }
-
let taskMessages: unknown[] = [];
- if (
- resolvedActiveTask &&
- !["completed", "failed", "cancelled", "superseded"].includes(resolvedActiveTask.status)
- ) {
+ if (activeTask) {
try {
- const tmsgs = await queries.taskMessage.listTaskMessages(db, resolvedActiveTask.id);
+ // Errors-only: the chat no longer renders thinking/tool steps (replies
+ // arrive via `send-dm`). We preload only `type:"error"` rows for the active
+ // task so a live error survives a reload while the run is still active.
+ // (A run that ended in error is settled to status:"failed" by the daemon and
+ // re-surfaces via its persisted assistant error message, not through here.)
+ // Filters type==="error" + scopes by workspace in SQL.
+ const tmsgs = await queries.taskMessage.listTaskErrorMessages(
+ db,
+ activeTask.id,
+ ws.workspaceId,
+ );
taskMessages = tmsgs.map(taskMessageToResponse);
} catch {
// non-critical
}
}
- const thinkingCounts: Record<string, number> = {};
- if (messages.length > 0) {
- const taskIds = [
- ...new Set(
- messages
- .filter((m) => m.role === "assistant" && m.taskId)
- .map((m) => m.taskId!)
- ),
- ];
- if (taskIds.length > 0) {
- try {
- const rows = await queries.taskMessage.countTextMessagesByTaskIds(
- db,
- taskIds,
- ws.workspaceId
- );
- for (const row of rows) {
- thinkingCounts[row.taskId] = row.count;
- }
- } catch {
- // non-critical
- }
- }
- }
-
return writeJSON({
conversation: conversationToResponse(conversation),
messages: cacheValid ? null : messages.map(messageToResponse),
@@ -130,10 +94,8 @@ export const GET = withAuth(async (req, ctx) => {
has_more_conversations: hasMoreConversations,
has_more_artifacts: artifacts.length >= ARTIFACT_LIMIT,
artifacts: artifacts.map(queries.artifact.artifactToResponse),
- buffered_messages: resolvedBuffered.map(messageToResponse),
flagged_message_ids: flaggedMessageIds,
- thinking_counts: thinkingCounts,
- active_task: resolvedActiveTask ? taskToResponse(resolvedActiveTask) : null,
+ active_task: activeTask ? taskToResponse(activeTask) : null,
task_messages: taskMessages,
cache_valid: cacheValid,
message_count: serverMessageCount,
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.ts
index 1b5bf4966..abffca19a 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, TASK_TYPES, CreateMessageRequestSchema, parsePromptMentions } from "@alook/shared"
+import { queries, TASK_TYPES, CreateMessageRequestSchema, parsePromptMentions, truncateTitle } from "@alook/shared"
import { getDb } from "@/lib/db"
import { nanoid } from "nanoid";
import { withAuth } from "@/lib/middleware/auth";
@@ -15,15 +15,6 @@ import { invalidate, cacheKeys } from "@/lib/cache";
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
const MAX_FILES = 10;
-function truncateTitle(text: string, maxLen = 50): string {
- const trimmed = text.replace(/\s+/g, " ").trim();
- if (trimmed.length <= maxLen) return trimmed;
- const cut = trimmed.slice(0, maxLen);
- const lastSpace = cut.lastIndexOf(" ");
- const title = lastSpace > 20 ? cut.slice(0, lastSpace) : cut;
- return title + "...";
-}
-
function sanitizeFilename(name: string): string {
return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";
}
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
new file mode 100644
index 000000000..2a1429c35
--- /dev/null
+++ b/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts
@@ -0,0 +1,150 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const m = {
+ getConversation: vi.fn(),
+ createMessage: vi.fn(),
+ updateConversationTitle: vi.fn(),
+};
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ conversation: {
+ getConversation: (...a: unknown[]) => m.getConversation(...a),
+ updateConversationTitle: (...a: unknown[]) => m.updateConversationTitle(...a),
+ },
+ message: {
+ createMessage: (...a: unknown[]) => m.createMessage(...a),
+ },
+ },
+ };
+});
+
+// Faithful auth realm: a machine token (al_...) sets ctx.workspaceId; a user
+// session/JWT does NOT. This lets us exercise the route's 403 daemon-only guard.
+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;
+ const auth = (req.headers?.get?.("Authorization") as string) || "";
+ const isMachine = auth.startsWith("Bearer al_");
+ return handler(req, {
+ userId: "u1",
+ email: "[email protected]",
+ workspaceId: isMachine ? "w1" : undefined,
+ params,
+ });
+ }),
+}));
+
+const broadcastToUser = vi.fn().mockResolvedValue(undefined);
+vi.mock("@/lib/broadcast", () => ({
+ broadcastToUser: (...a: unknown[]) => broadcastToUser(...a),
+}));
+vi.mock("@/lib/api/responses", () => ({
+ messageToResponse: (msg: any) => ({ id: msg.id, content: msg.content, role: msg.role }),
+}));
+
+import { POST } from "./route";
+
+function makeReq(body: unknown, opts?: { machine?: boolean }) {
+ return new NextRequest("http://localhost/api/daemon/conversations/c1/messages", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ Authorization: opts?.machine === false ? "Bearer session-jwt" : "Bearer al_token",
+ },
+ body: JSON.stringify(body),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ m.getConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "owner-1" });
+ m.createMessage.mockImplementation((_db: unknown, data: any) => ({
+ id: "msg-1",
+ ...data,
+ }));
+ m.updateConversationTitle.mockResolvedValue(null);
+});
+
+describe("POST /api/daemon/conversations/[id]/messages", () => {
+ // TC1
+ it("creates one role:assistant message with taskId + metadata.kind=dm and broadcasts (201)", async () => {
+ const res = await POST(makeReq({ content: "hello", task_id: "t1" }), { params: { id: "c1" } });
+ expect(res.status).toBe(201);
+ const body = await res.json();
+ expect(body.message.content).toBe("hello");
+
+ expect(m.createMessage).toHaveBeenCalledTimes(1);
+ const [, data] = m.createMessage.mock.calls[0];
+ expect(data.role).toBe("assistant");
+ expect(data.content).toBe("hello");
+ expect(data.taskId).toBe("t1");
+ expect(JSON.parse(data.metadata)).toEqual({ kind: "dm" });
+
+ // Broadcast targets the conversation owner, not the token owner.
+ expect(broadcastToUser).toHaveBeenCalledTimes(1);
+ const [target, payload] = broadcastToUser.mock.calls[0];
+ expect(target).toBe("owner-1");
+ expect(payload.type).toBe("conversation.message");
+ expect(payload.conversationId).toBe("c1");
+ });
+
+ it("auto-titles the conversation from the message content", async () => {
+ await POST(makeReq({ content: "Summarize the backlog" }), { params: { id: "c1" } });
+ expect(m.updateConversationTitle).toHaveBeenCalledWith({}, "c1", "Summarize the backlog");
+ });
+
+ it("does not require a task_id (taskId null)", async () => {
+ const res = await POST(makeReq({ content: "no task" }), { params: { id: "c1" } });
+ expect(res.status).toBe(201);
+ const [, data] = m.createMessage.mock.calls[0];
+ expect(data.taskId).toBeNull();
+ });
+
+ // TC4 — foreign-workspace conversation id → 404 (scoped-ahead, no leak)
+ it("404 when conversation is not in the token's workspace", async () => {
+ m.getConversation.mockResolvedValue(null);
+ const res = await POST(makeReq({ content: "x" }), { params: { id: "other" } });
+ expect(res.status).toBe(404);
+ expect(m.createMessage).not.toHaveBeenCalled();
+ expect(broadcastToUser).not.toHaveBeenCalled();
+ });
+
+ // TC5 — a user JWT (no workspaceId) → 403 daemon-only
+ it("403 when called without a machine token (no workspaceId)", async () => {
+ const res = await POST(makeReq({ content: "x" }, { machine: false }), { params: { id: "c1" } });
+ expect(res.status).toBe(403);
+ expect(m.getConversation).not.toHaveBeenCalled();
+ expect(m.createMessage).not.toHaveBeenCalled();
+ });
+
+ // TC7 — empty content rejected by schema (min length)
+ it("400 when content is empty (schema min length)", async () => {
+ const res = await POST(makeReq({ content: "" }), { params: { id: "c1" } });
+ expect(res.status).toBe(400);
+ expect(m.createMessage).not.toHaveBeenCalled();
+ });
+
+ // TC6 — two sends in one task → two distinct rows, both broadcast
+ it("supports multiple sends in one task (each is its own message + broadcast)", async () => {
+ await POST(makeReq({ content: "on it", task_id: "t1" }), { params: { id: "c1" } });
+ await POST(makeReq({ content: "done", task_id: "t1" }), { params: { id: "c1" } });
+ expect(m.createMessage).toHaveBeenCalledTimes(2);
+ expect(broadcastToUser).toHaveBeenCalledTimes(2);
+ const first = m.createMessage.mock.calls[0][1];
+ const second = m.createMessage.mock.calls[1][1];
+ expect(first.taskId).toBe("t1");
+ expect(second.taskId).toBe("t1");
+ expect(first.content).toBe("on it");
+ expect(second.content).toBe("done");
+ });
+});
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
new file mode 100644
index 000000000..fa39e03ac
--- /dev/null
+++ b/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts
@@ -0,0 +1,57 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { queries, AgentDmRequestSchema, truncateTitle } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth";
+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
+import { messageToResponse } from "@/lib/api/responses";
+import { broadcastToUser } from "@/lib/broadcast";
+
+// Agent-authored DM endpoint (`alook sync send-dm`). The agent calls this to
+// push exactly what the user should see — a `role:"assistant"` chat bubble that
+// lands live in the open chat. Machine-token auth only (mirrors the other
+// daemon routes); explicitly does NOT enqueue a task (unlike the user-send
+// route at /api/conversations/[id]/messages, which would spawn another run).
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ if (!ctx.workspaceId) {
+ return writeError("Forbidden: machine token required", 403);
+ }
+
+ const { env } = getCloudflareContext()
+ const db = getDb((env as Env).DB)
+
+ const id = ctx.params?.id;
+ if (!id) {
+ return writeError("conversation id is required", 400);
+ }
+
+ const [body, err] = await parseBody(req, AgentDmRequestSchema);
+ if (err) return err;
+
+ // Scope-ahead: resolve the conversation by workspace id, never check ownership
+ // after (AGENTS.md rule). A foreign-workspace id simply 404s — no leak.
+ const conversation = await queries.conversation.getConversation(db, id, ctx.workspaceId);
+ if (!conversation) {
+ return writeError("conversation not found", 404);
+ }
+
+ const message = await queries.message.createMessage(db, {
+ conversationId: id,
+ role: "assistant",
+ content: body.content,
+ taskId: body.task_id ?? null,
+ metadata: JSON.stringify({ kind: "dm" }),
+ });
+
+ // Auto-title if still untitled — parity with the user-send route. The query's
+ // conditional WHERE title = '' makes this a no-op once a title exists.
+ queries.conversation.updateConversationTitle(db, id, truncateTitle(body.content)).catch(() => {});
+
+ broadcastToUser(conversation.userId, {
+ type: "conversation.message",
+ conversationId: id,
+ message: messageToResponse(message),
+ }).catch(() => {});
+
+ return writeJSON({ message: messageToResponse(message) }, 201);
+});
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
index 698957996..5192421c0 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts
@@ -48,6 +48,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const [body, err] = await parseBody(req, ReportMessagesRequestSchema);
if (err) return err;
+ // What we persist (INTENTIONAL — do not "clean up" as dead storage):
+ // - We DROP only "log" and "status" — pure transient runtime noise, never
+ // useful after the fact.
+ // - We KEEP text/tool-use/thinking/tool-result rows even though the chat UI
+ // no longer reads them (since the move to agent-authored `send-dm`, the UI
+ // only consumes type:"error" + the final reply bubble). These rows are
+ // retained for FUTURE DATA ANALYSIS of agent runs (tool usage, reasoning,
+ // etc.). The read paths (listTaskMessages*) filter them out for the UI, but
+ // the rows must stay in storage. Don't delete this write or narrow it to
+ // errors-only.
const filtered = body.messages.filter((m) => m.type !== "log" && m.type !== "status");
if (filtered.length === 0) {
return writeJSON({ status: "ok" });
@@ -61,6 +71,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
type: m.type,
tool: m.tool || "",
callId: m.call_id || "",
+ // tool-result content/input/output are intentionally blanked: those
+ // payloads can be very large (full tool stdout, file dumps), so we keep
+ // the row (for analysis: which tool ran, when) but not the heavy body.
content: m.type === "tool-result" ? "" : (m.content || ""),
input: m.type === "tool-result" ? undefined : m.input,
output: m.type === "tool-result" ? "" : (m.output || ""),
@@ -75,6 +88,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
});
const succeeded = filtered.filter((_, i) => results[i].status === "fulfilled");
+ // Broadcast is a separate concern from storage: we STORE tool-use/thinking/
+ // tool-result (for later analysis, above) but don't BROADCAST them — the live
+ // chat has no use for them. text is still broadcast (cheap, and harmless if the
+ // client ignores it); only type:"error" actually drives UI today.
const broadcastable = succeeded.filter((m) => m.type !== "tool-result" && m.type !== "tool-use" && m.type !== "thinking");
if (broadcastable.length > 0) {
const wsMessages: TaskMessageResponse[] = broadcastable.map((m) => ({
diff --git a/src/web/src/app/api/email/notify/route.test.ts b/src/web/src/app/api/email/notify/route.test.ts
index adcbfe5cb..d27690eda 100644
--- a/src/web/src/app/api/email/notify/route.test.ts
+++ b/src/web/src/app/api/email/notify/route.test.ts
@@ -157,6 +157,42 @@ describe("POST /api/email/notify", () => {
);
});
+ // TC4 (the bug): a human replies from their own mail client. Their reply carries
+ // In-Reply-To = the wire Message-ID of the agent's original email. Because the worker
+ // now puts that SAME id on the wire AND registers it in conversationMap, the inbound
+ // lookup keys on In-Reply-To and resolves back to the original conversation — instead
+ // of opening a brand-new one (the reported bug).
+ it("threads a human reply into the original conversation via In-Reply-To (no new conversation)", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
+ const WIRE_ID = "<[email protected]>"; // the id the agent put on the wire + registered
+ // The map was registered (on send) keyed on the wire id → the original conversation.
+ mockFindByKey.mockImplementation((_db: unknown, key: string) =>
+ key === `email:a1:${WIRE_ID}` ? "conv_original" : null,
+ );
+ mockGetConversation.mockResolvedValue({ id: "conv_original", type: "email_notification", userId: "u1" });
+ mockEnqueueTask.mockResolvedValue({ id: "t1" });
+
+ const res = await POST(makeNotifyReq({
+ ...baseBody,
+ messageId: "<[email protected]>", // the human's own new Message-ID
+ inReplyTo: WIRE_ID, // points at the agent's wire id
+ references: "",
+ }));
+ expect(res.status).toBe(200);
+
+ // Lookup keyed on the In-Reply-To (the wire id), NOT the human's own message id.
+ expect(mockFindByKey).toHaveBeenCalledWith(expect.anything(), `email:a1:${WIRE_ID}`, "ws1");
+ // Threaded into the original conversation — no new conversation, no new mapping.
+ expect(mockCreateConversation).not.toHaveBeenCalled();
+ expect(mockCreateMapping).not.toHaveBeenCalled();
+ expect(mockEnqueueTask).toHaveBeenCalledWith(
+ "a1", "conv_original", "ws1",
+ expect.any(String),
+ "email_notification",
+ expect.objectContaining({ contextKey: "conv_original" }),
+ );
+ });
+
it("reuses existing DM conversation and includes dmUser in context", async () => {
mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" });
mockFindByKey.mockResolvedValue("conv_dm");
diff --git a/src/web/src/app/api/issues/[id]/route.test.ts b/src/web/src/app/api/issues/[id]/route.test.ts
index 58d4aeb85..e62a7a86c 100644
--- a/src/web/src/app/api/issues/[id]/route.test.ts
+++ b/src/web/src/app/api/issues/[id]/route.test.ts
@@ -141,7 +141,7 @@ describe("DELETE /api/issues/[id]", () => {
const res = await DELETE(req, { params: { id: "iss_1" } } as any);
expect(res.status).toBe(204);
expect(mockDeleteIssue).toHaveBeenCalledWith({}, "iss_1", "w1");
- expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { skipDispatch: true, reason: "Task cancelled: issue deleted" });
+ expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { reason: "Task cancelled: issue deleted" });
});
it("cancels via traceId when latestTask has a traceId", async () => {
@@ -163,7 +163,7 @@ describe("DELETE /api/issues/[id]", () => {
const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });
const res = await DELETE(req, { params: { id: "iss_1" } } as any);
expect(res.status).toBe(204);
- expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { skipDispatch: true, reason: "Task cancelled: issue deleted" });
+ expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { reason: "Task cancelled: issue deleted" });
expect(mockCancelTrace).not.toHaveBeenCalled();
});
@@ -174,7 +174,7 @@ describe("DELETE /api/issues/[id]", () => {
const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });
const res = await DELETE(req, { params: { id: "iss_1" } } as any);
expect(res.status).toBe(204);
- expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { skipDispatch: true, reason: "Task cancelled: issue deleted" });
+ expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { reason: "Task cancelled: issue deleted" });
expect(mockCancelTrace).not.toHaveBeenCalled();
expect(mockDeleteIssue).toHaveBeenCalled();
});
diff --git a/src/web/src/app/api/issues/[id]/route.ts b/src/web/src/app/api/issues/[id]/route.ts
index 0bb390151..d8adf21f3 100644
--- a/src/web/src/app/api/issues/[id]/route.ts
+++ b/src/web/src/app/api/issues/[id]/route.ts
@@ -184,7 +184,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {
if (task?.traceId) {
await taskService.cancelTrace(task.traceId, ws.workspaceId, { reason });
} else {
- await taskService.cancelActiveTask(issue.conversationId, ws.workspaceId, { skipDispatch: true, reason });
+ await taskService.cancelActiveTask(issue.conversationId, ws.workspaceId, { reason });
}
} catch (err) {
log.warn("failed to cancel tasks during issue deletion", { issueId: id, err });
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index c457e3bfb..d0d84ea86 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -850,6 +850,20 @@
}
}
+/* iMessage-style typing dots for the presence line. */
+@keyframes typing-dot {
+ 0%,
+ 60%,
+ 100% {
+ opacity: 0.3;
+ transform: translateY(0);
+ }
+ 30% {
+ opacity: 1;
+ transform: translateY(-2px);
+ }
+}
+
@keyframes shimmer {
0% {
transform: translateX(-100%);
@@ -1203,6 +1217,41 @@
}
.chat-composer .tiptap > p:first-child { margin-top: 0; }
.chat-composer .tiptap > p:last-child { margin-bottom: 0; }
+
+/* Rotating capability-hint placeholder overlay. Sits over the empty editor's
+ first-line text origin, mirroring the muted ::before placeholder look. It is
+ absolutely positioned so it adds zero layout height (no composer jump), and
+ pointer-events:none so clicks fall through to the editor underneath. */
+.chat-placeholder-overlay {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 8px; /* matches EditorContent pr-2 so long hints ellipsize, not wrap */
+ line-height: 24px; /* matches .chat-input-line-height / .tiptap */
+ color: var(--muted-foreground);
+ opacity: 0.5;
+ pointer-events: none;
+ /* Single line: never wrap (no height change); ellipsize on overflow. */
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.chat-placeholder-overlay > span {
+ display: inline-block;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.chat-placeholder-fade {
+ transition: opacity 200ms ease;
+}
+@media (prefers-reduced-motion: reduce) {
+ /* Belt-and-braces: even if JS leaves the fade class on, kill the animation. */
+ .chat-placeholder-fade {
+ transition: none;
+ }
+}
.chat-composer .tiptap ul,
.chat-composer .tiptap ol {
margin: 0;
diff --git a/src/web/src/components/agent-chat/agent-chat-view.test.ts b/src/web/src/components/agent-chat/agent-chat-view.test.ts
index 2d21020b7..9483cd4b4 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.test.ts
+++ b/src/web/src/components/agent-chat/agent-chat-view.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect } from "vitest";
import type { Message, Artifact } from "@alook/shared";
-import { sortMessages, mergeMessages, buildTimeline, addBufferedIfNew, replaceOptimisticBuffered, getEventIconType, reorderArtifactsAfterAssistant, shouldPersistPointerForLoad, pointerRefreshTargetForTaskCreated } from "./agent-chat-view";
-import type { NapMarker } from "./agent-chat-view";
+import { sortMessages, mergeMessages, buildTimeline, computeGroupPositions, getEventIconType, eventTypeFromMessage, shouldPersistPointerForLoad, pointerRefreshTargetForTaskCreated } from "./chat-message-utils";
+import type { NapMarker } from "./chat-message-utils";
function msg(id: string, created_at: string, role: "user" | "assistant" | "event" = "user", content = ""): Message {
return { id, conversation_id: "conv1", role, content, task_id: null, attachment_ids: null, created_at };
@@ -215,6 +215,23 @@ describe("getEventIconType", () => {
});
});
+// Card type is metadata-driven first (robust if copy changes), content heuristic
+// only as a fallback when no resource id is present.
+describe("eventTypeFromMessage (metadata-driven)", () => {
+ it("uses the metadata resource id over the content heuristic", () => {
+ // Content says "email" but the metadata carries an issueId → issue wins.
+ expect(eventTypeFromMessage({ issueId: "iss_1" }, "email-ish text", null)).toBe("issue");
+ expect(eventTypeFromMessage({ emailId: "em_1" }, "no keywords here", null)).toBe("email");
+ expect(eventTypeFromMessage({ calendarEventId: "cal_1" }, "no keywords here", null)).toBe("calendar");
+ });
+
+ it("falls back to the content/conversation heuristic when metadata is absent", () => {
+ expect(eventTypeFromMessage(null, "Issue created: foo", "issue_event")).toBe("issue");
+ expect(eventTypeFromMessage(undefined, "New email from [email protected]: hi", "email_notification")).toBe("email");
+ expect(eventTypeFromMessage({}, "Standup reminder", "calendar_event")).toBe("calendar");
+ });
+});
+
function artifact(id: string, created_at: string): Artifact {
return {
id,
@@ -242,8 +259,9 @@ describe("buildTimeline", () => {
const naps: NapMarker[] = [];
const result = buildTimeline(msgs, arts, naps);
- // artifact is collected after user msg (no assistant to flush to), appended at end
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m3", "a1"]);
+ // Strictly chronological now (no artifact reorder): the file at 00:00:02
+ // sits between the two messages where it actually happened.
+ expect(result.map((i) => i.data.id)).toEqual(["m1", "a1", "m3"]);
});
it("places nap marker after messages at the same timestamp", () => {
@@ -367,8 +385,9 @@ describe("buildTimeline — conversation grouping", () => {
const naps = [nap("nap-convA", "2024-01-01T12:00:00Z")];
const result = buildTimeline(msgs, arts, naps, "convB");
- // artifact collected after user msg, no assistant to flush to, appended at end of group
- expect(result.map((i) => i.data.id)).toEqual(["a1", "a2", "art1", "nap-convA", "b1"]);
+ // Chronological within the conversation section: art1 at 01:00 sits between
+ // a1 (00:00) and a2 (02:00). No artifact reorder.
+ expect(result.map((i) => i.data.id)).toEqual(["a1", "art1", "a2", "nap-convA", "b1"]);
});
it("single conversation (no nap markers) behaves as before", () => {
@@ -439,251 +458,6 @@ describe("buildTimeline — conversation grouping", () => {
});
});
-describe("reorderArtifactsAfterAssistant", () => {
- it("basic reorder: user → artifact → assistant becomes user → assistant → artifact", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:00Z") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m2", "a1"]);
- });
-
- it("multiple turns: each turn reorders independently", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:00Z") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- { kind: "message" as const, data: msg("m3", "2024-01-01T00:03:00Z", "user") },
- { kind: "artifact" as const, data: artifact("a2", "2024-01-01T00:04:00Z") },
- { kind: "message" as const, data: msg("m4", "2024-01-01T00:05:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m2", "a1", "m3", "m4", "a2"]);
- });
-
- it("no assistant message (running task): artifact stays in place", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:00Z") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "a1"]);
- });
-
- it("no artifacts to reorder: unchanged", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:01:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m2"]);
- });
-
- it("artifact between two assistants (no user between): stays in place", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "assistant") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:00Z") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "a1", "m2"]);
- });
-
- it("event messages stay in place", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "message" as const, data: msg("e1", "2024-01-01T00:01:00Z", "event", "Email sent to [email protected]") },
- { kind: "message" as const, data: msg("e2", "2024-01-01T00:01:30Z", "event", "Issue created: Bug") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "e1", "e2", "m2"]);
- });
-
- it("mixed events + artifacts: events stay, artifacts move after assistant", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "message" as const, data: msg("e1", "2024-01-01T00:01:00Z", "event", "Email sent") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:30Z") },
- { kind: "artifact" as const, data: artifact("a2", "2024-01-01T00:01:45Z") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "e1", "m2", "a1", "a2"]);
- });
-
- it("nap markers are never relocated", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "nap" as const, data: nap("nap-1", "2024-01-01T00:01:00Z") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:30Z") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "nap-1", "m2", "a1"]);
- });
-
- it("conversation grouping path: reordering works within grouped conversations", () => {
- const msgs = [
- { ...msgInConv("m1", "2024-01-01T00:00:00Z", "convA"), role: "user" as const },
- { ...msgInConv("m2", "2024-01-01T02:00:00Z", "convA"), role: "assistant" as const },
- { ...msgInConv("m3", "2024-01-02T00:00:00Z", "convB"), role: "user" as const },
- { ...msgInConv("m4", "2024-01-02T02:00:00Z", "convB"), role: "assistant" as const },
- ];
- const arts = [
- artifactInConv("a1", "2024-01-01T01:00:00Z", "convA"),
- artifactInConv("a2", "2024-01-02T01:00:00Z", "convB"),
- ];
- const naps = [nap("nap-convA", "2024-01-01T12:00:00Z")];
-
- const result = buildTimeline(msgs, arts, naps, "convB");
- const ids = result.map((i) => i.data.id);
- expect(ids).toEqual(["m1", "m2", "a1", "nap-convA", "m3", "m4", "a2"]);
- });
-
- it("follow-up buffer pattern: user → user → artifact → assistant reorders correctly", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:00:30Z", "user") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:00Z") },
- { kind: "message" as const, data: msg("m3", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m2", "m3", "a1"]);
- });
-
- it("empty timeline returns empty array", () => {
- expect(reorderArtifactsAfterAssistant([])).toEqual([]);
- });
-
- it("artifact before any user message stays in place", () => {
- const items = [
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:00:00Z") },
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:01:00Z", "user") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["a1", "m1", "m2"]);
- });
-
- it("relative order preserved: user → artifact1 → artifact2 → assistant keeps artifact order", () => {
- const items = [
- { kind: "message" as const, data: msg("m1", "2024-01-01T00:00:00Z", "user") },
- { kind: "artifact" as const, data: artifact("a1", "2024-01-01T00:01:00Z") },
- { kind: "artifact" as const, data: artifact("a2", "2024-01-01T00:01:30Z") },
- { kind: "message" as const, data: msg("m2", "2024-01-01T00:02:00Z", "assistant") },
- ];
- const result = reorderArtifactsAfterAssistant(items);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m2", "a1", "a2"]);
- });
-});
-
-describe("addBufferedIfNew", () => {
- it("adds a new message when id is not present", () => {
- const prev = [msg("m1", "2024-01-01T00:00:00Z")];
- const incoming = msg("m2", "2024-01-02T00:00:00Z");
- const result = addBufferedIfNew(prev, incoming);
- expect(result).toHaveLength(2);
- expect(result[1].id).toBe("m2");
- });
-
- it("returns the same array when id already exists", () => {
- const prev = [msg("m1", "2024-01-01T00:00:00Z")];
- const incoming = msg("m1", "2024-01-01T00:00:00Z");
- const result = addBufferedIfNew(prev, incoming);
- expect(result).toBe(prev);
- expect(result).toHaveLength(1);
- });
-
- it("adds to empty array", () => {
- const result = addBufferedIfNew([], msg("m1", "2024-01-01T00:00:00Z"));
- expect(result).toHaveLength(1);
- });
-});
-
-describe("replaceOptimisticBuffered", () => {
- it("replaces optimistic message with real message (HTTP first)", () => {
- const prev = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("temp-123", "2024-01-02T00:00:00Z", "user", "hello"),
- ];
- const real = msg("real-abc", "2024-01-02T00:00:00Z", "user", "hello");
- const result = replaceOptimisticBuffered(prev, "temp-123", real);
- expect(result).toHaveLength(2);
- expect(result[1].id).toBe("real-abc");
- expect(result.find((m) => m.id === "temp-123")).toBeUndefined();
- });
-
- it("removes optimistic when WebSocket already delivered the real message (WS first — the race condition fix)", () => {
- const real = msg("real-abc", "2024-01-02T00:00:00Z", "user", "hello");
- const prev = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("temp-123", "2024-01-02T00:00:00Z", "user", "hello"),
- real,
- ];
- const result = replaceOptimisticBuffered(prev, "temp-123", real);
- expect(result).toHaveLength(2);
- expect(result.map((m) => m.id)).toEqual(["m1", "real-abc"]);
- expect(result.find((m) => m.id === "temp-123")).toBeUndefined();
- });
-
- it("full race simulation: optimistic → WS add (skipped) → HTTP replace produces no duplicates", () => {
- const optimisticId = "temp-1716000000000";
- const optimistic = msg(optimisticId, "2024-01-02T00:00:00Z", "user", "follow-up");
- const real = msg("PjddM86V1he-JYuedi9tY", "2024-01-02T00:00:00Z", "user", "follow-up");
-
- let state: Message[] = [msg("m1", "2024-01-01T00:00:00Z")];
-
- // Step 1: add optimistic
- state = [...state, optimistic];
- expect(state).toHaveLength(2);
-
- // Step 2: WebSocket delivers real message — skipped because temp entry with same timestamp exists
- state = addBufferedIfNew(state, real);
- expect(state).toHaveLength(2);
-
- // Step 3: HTTP response arrives, replaces optimistic
- state = replaceOptimisticBuffered(state, optimisticId, real);
- expect(state).toHaveLength(2);
- expect(state.map((m) => m.id)).toEqual(["m1", "PjddM86V1he-JYuedi9tY"]);
- });
-
- it("full normal flow: optimistic → HTTP replace → WS ignored produces no duplicates", () => {
- const optimisticId = "temp-1716000000000";
- const optimistic = msg(optimisticId, "2024-01-02T00:00:00Z", "user", "follow-up");
- const real = msg("server-id", "2024-01-02T00:00:00Z", "user", "follow-up");
-
- let state: Message[] = [msg("m1", "2024-01-01T00:00:00Z")];
-
- // Step 1: add optimistic
- state = [...state, optimistic];
-
- // Step 2: HTTP response arrives first, replaces optimistic
- state = replaceOptimisticBuffered(state, optimisticId, real);
- expect(state).toHaveLength(2);
- expect(state[1].id).toBe("server-id");
-
- // Step 3: WebSocket arrives late, dedup blocks it
- state = addBufferedIfNew(state, real);
- expect(state).toHaveLength(2);
- expect(state.map((m) => m.id)).toEqual(["m1", "server-id"]);
- });
-
- it("handles multiple buffered messages — only the targeted optimistic is affected", () => {
- const prev = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("temp-100", "2024-01-02T00:00:00Z", "user", "first"),
- msg("temp-200", "2024-01-03T00:00:00Z", "user", "second"),
- ];
- const real = msg("real-100", "2024-01-02T00:00:00Z", "user", "first");
- const result = replaceOptimisticBuffered(prev, "temp-100", real);
- expect(result).toHaveLength(3);
- expect(result.map((m) => m.id)).toEqual(["m1", "real-100", "temp-200"]);
- });
-});
-
// ---------------------------------------------------------------------------
// Wrong-conversation flash fix: per-channel "latest-created" pointer semantics.
//
@@ -811,3 +585,181 @@ describe("pointerRefreshTargetForTaskCreated (TODO-2: WS-driven refresh scope)",
).toBe("conv_new");
});
});
+
+// TC1 — grouping: same-role + <60s clusters into first/middle/last/solo;
+// event messages never group (stay null).
+describe("computeGroupPositions (TC1)", () => {
+ const positionsFor = (msgs: Message[]) =>
+ computeGroupPositions(buildTimeline(msgs, [], []));
+
+ it("groups three same-role messages within 60s as first/middle/last", () => {
+ const msgs = [
+ msg("a", "2024-01-01T00:00:00Z", "user", "1"),
+ msg("b", "2024-01-01T00:00:30Z", "user", "2"),
+ msg("c", "2024-01-01T00:00:50Z", "user", "3"),
+ ];
+ expect(positionsFor(msgs)).toEqual(["first", "middle", "last"]);
+ });
+
+ it("breaks a cluster when the gap exceeds 60s", () => {
+ const msgs = [
+ msg("a", "2024-01-01T00:00:00Z", "user", "1"),
+ msg("b", "2024-01-01T00:02:00Z", "user", "2"),
+ ];
+ expect(positionsFor(msgs)).toEqual(["solo", "solo"]);
+ });
+
+ it("breaks a cluster when the role changes", () => {
+ const msgs = [
+ msg("a", "2024-01-01T00:00:00Z", "user", "hi"),
+ msg("b", "2024-01-01T00:00:10Z", "assistant", "hello"),
+ ];
+ expect(positionsFor(msgs)).toEqual(["solo", "solo"]);
+ });
+
+ it("groups events into the agent cluster (assistant + event share one header)", () => {
+ const msgs = [
+ msg("a", "2024-01-01T00:00:00Z", "assistant", "1"),
+ msg("e", "2024-01-01T00:00:10Z", "event", "Email received"),
+ msg("c", "2024-01-01T00:00:20Z", "assistant", "2"),
+ ];
+ // assistant + event are all the AGENT side → one cluster (Slack/Discord
+ // model: a single avatar+name header, the rest continue in the gutter).
+ expect(positionsFor(msgs)).toEqual(["first", "middle", "last"]);
+ });
+
+ it("keeps user and agent as separate clusters", () => {
+ const msgs = [
+ msg("u", "2024-01-01T00:00:00Z", "user", "hi"),
+ msg("a", "2024-01-01T00:00:10Z", "assistant", "hello"),
+ msg("e", "2024-01-01T00:00:20Z", "event", "Email sent"),
+ ];
+ // user is its own side; assistant+event group together.
+ expect(positionsFor(msgs)).toEqual(["solo", "first", "last"]);
+ });
+
+ it("returns solo for a single message", () => {
+ expect(positionsFor([msg("a", "2024-01-01T00:00:00Z", "user", "1")])).toEqual(["solo"]);
+ });
+});
+
+// Planner's strengthened TODO-3 acceptance (cache-chat-cards): caching the
+// artifacts so they're present from the INSTANT paint fixes not just the
+// file-card pop-in but ALSO the event-card displacement. The event cards move
+// as a CONSEQUENCE of un-cached artifacts being inserted into the timeline on
+// the network response — same root cause. These tests prove that behavior
+// against the pure timeline/grouping functions (the render-timing assertions
+// remain QA browser checks since src/web has no jsdom/RTL harness).
+describe("cache-chat-cards: event cards don't reflow when artifacts are cached (TODO-3)", () => {
+ // An agent-side cluster: assistant → event(email) → assistant, all within
+ // 60s. Grouped alone, the event card is the MIDDLE of one cluster.
+ const agentCluster: Message[] = [
+ msg("a1", "2024-01-01T00:00:00Z", "assistant", "working on it"),
+ msg("e1", "2024-01-01T00:00:20Z", "event", "New email from [email protected]: Subject"),
+ msg("a2", "2024-01-01T00:00:40Z", "assistant", "done"),
+ ];
+ // An artifact uploaded chronologically BETWEEN the assistant and the event.
+ // On the network response this inserts into the timeline next to the event.
+ const arts = [artifact("art1", "2024-01-01T00:00:10Z")];
+
+ it("ROOT CAUSE: an un-cached instant paint (artifacts=[]) yields a DIFFERENT timeline order than post-network", () => {
+ const instantPaintUncached = buildTimeline(agentCluster, [], []);
+ const postNetwork = buildTimeline(agentCluster, arts, []);
+
+ // Without caching, the instant paint has no artifact; the network response
+ // inserts it between a1 and e1 → the timeline restructures (reflow).
+ expect(instantPaintUncached.map((i) => i.data.id)).toEqual(["a1", "e1", "a2"]);
+ expect(postNetwork.map((i) => i.data.id)).toEqual(["a1", "art1", "e1", "a2"]);
+ expect(instantPaintUncached.map((i) => i.data.id)).not.toEqual(
+ postNetwork.map((i) => i.data.id),
+ );
+ });
+
+ it("ROOT CAUSE: the inserted artifact flips the event card's cluster-header (group position) state", () => {
+ const uncachedPositions = computeGroupPositions(buildTimeline(agentCluster, [], []));
+ const postNetworkPositions = computeGroupPositions(buildTimeline(agentCluster, arts, []));
+
+ // Uncached: [assistant, event, assistant] = one agent cluster → first/middle/last.
+ expect(uncachedPositions).toEqual(["first", "middle", "last"]);
+ // Post-network: [assistant, artifact, event, assistant] — the artifact is
+ // still the same agent side, so it joins the cluster and the event card
+ // shifts from "middle" to a later middle; the positions array changes shape
+ // (now 4 items), so the per-card header state is NOT preserved across the
+ // resolve. This is the visible displacement Gus reported.
+ expect(postNetworkPositions).toEqual(["first", "middle", "middle", "last"]);
+ expect(uncachedPositions).not.toEqual(postNetworkPositions);
+ });
+
+ it("FIX: a cached instant paint (artifacts present from frame 1) is IDENTICAL to the post-network timeline — no reflow", () => {
+ // With conv_extras caching, setArtifacts(extras.artifacts) runs on the
+ // instant paint, so buildTimeline sees the artifacts immediately. That
+ // instant-paint timeline must equal the post-network one (same artifacts,
+ // same conversation) → the network resolve causes ZERO structural change.
+ const cachedInstantPaint = buildTimeline(agentCluster, arts, []);
+ const postNetwork = buildTimeline(agentCluster, arts, []);
+
+ expect(cachedInstantPaint.map((i) => i.data.id)).toEqual(
+ postNetwork.map((i) => i.data.id),
+ );
+ expect(cachedInstantPaint.map((i) => i.kind)).toEqual(
+ postNetwork.map((i) => i.kind),
+ );
+ });
+
+ it("FIX: event-card group positions are stable across the resolve when artifacts are cached", () => {
+ const cachedInstantPositions = computeGroupPositions(buildTimeline(agentCluster, arts, []));
+ const postNetworkPositions = computeGroupPositions(buildTimeline(agentCluster, arts, []));
+
+ // Identical group positions → no event card gains/loses its avatar+name
+ // header when the network lands (the exact stability planner asked for).
+ expect(cachedInstantPositions).toEqual(postNetworkPositions);
+ });
+
+ it("FIX: an event card that is first/solo on the cached paint stays first/solo after the network lands", () => {
+ // A standalone event card (its own cluster: a different role/side neighbor
+ // keeps it solo). An artifact landing in the SAME cluster window would flip
+ // it from solo→first; caching the artifact means it's already accounted for
+ // on the instant paint, so the position never changes.
+ const msgs: Message[] = [
+ msg("u1", "2024-01-01T00:00:00Z", "user", "hi"),
+ msg("e1", "2024-01-01T00:05:00Z", "event", "Calendar event: standup"),
+ ];
+ const lateArt = [artifact("art2", "2024-01-01T00:05:10Z")];
+
+ const cachedInstant = computeGroupPositions(buildTimeline(msgs, lateArt, []));
+ const postNetwork = computeGroupPositions(buildTimeline(msgs, lateArt, []));
+ expect(cachedInstant).toEqual(postNetwork);
+
+ // And contrast: WITHOUT the cached artifact the event is solo, but WITH it
+ // the event becomes "first" of a 2-card agent cluster — the very flip
+ // caching prevents from happening after the network resolve.
+ const uncached = computeGroupPositions(buildTimeline(msgs, [], []));
+ expect(uncached).toEqual(["solo", "solo"]);
+ expect(postNetwork).toEqual(["solo", "first", "last"]);
+ });
+
+ it("FIX: caching conversation_type keeps a metadata-less event card's icon stable (no heuristic→type flip)", () => {
+ // Metadata-less event message: the icon/label is resolved by
+ // eventTypeFromMessage → falls back to getEventIconType(content, type).
+ // On a cached paint conversation_type is seeded, so the type-driven icon is
+ // correct from frame 1 and does NOT change when the network confirms it.
+ // Content whose keyword heuristic ("email") DISAGREES with the real
+ // conversation type (calendar_event) — e.g. a calendar invite whose text
+ // mentions email. This is exactly the metadata-less case where the icon
+ // would flip if conversation.type isn't known on the instant paint.
+ const content = "Calendar invite — reply via email to confirm";
+ // Instant paint with cached conversation_type → correct (calendar) icon:
+ const cachedIcon = eventTypeFromMessage({}, content, "calendar_event");
+ // Post-network with the authoritative conversation_type → same icon:
+ const networkIcon = eventTypeFromMessage({}, content, "calendar_event");
+ expect(cachedIcon).toBe(networkIcon);
+ expect(cachedIcon).toBe("calendar");
+
+ // Without a cached type (conversation === null on the un-cached instant
+ // paint), the keyword heuristic picks "email" for this content → the flip
+ // to the type-driven "calendar" only happens after the network lands.
+ const uncachedIcon = eventTypeFromMessage({}, content, undefined);
+ expect(uncachedIcon).toBe("email");
+ expect(uncachedIcon).not.toBe(networkIcon);
+ });
+});
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 73d8a3031..a0d69c1b1 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -2,73 +2,30 @@
import React, {
useEffect,
+ useLayoutEffect,
useState,
useRef,
useCallback,
useMemo,
} from "react";
-import { flushSync } from "react-dom";
import { useParams, useSearchParams } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
import { Button } from "@/components/ui/button";
import { TaskStream } from "@/components/task-stream";
import {
- chatInit,
- checkFreshness,
- conversationInit,
- createConversation,
- listMessages,
- listMessagesAroundTask,
- listPreviousConversations,
- sendMessage,
getTask,
- getTaskMessages,
- listArtifacts,
- listBufferedMessages,
- createBufferedMessage,
- deleteBufferedMessage,
- cancelActiveTask,
- getActiveTask,
- retryTask,
- markInboxRead,
- getIssue,
- getTrace,
updateIssue,
- listFlaggedMessageIds,
- flagMessage as apiFlagMessage,
- unflagMessage as apiUnflagMessage,
getAgentSkills,
} from "@/lib/api";
-import {
- appendCachedMessage,
- getCachedMessages,
- getCachedMessagesBefore,
- getCacheMeta,
- mergeCachedMessages,
- getLastOpenConversation,
- setLastOpenConversation,
-} from "@/lib/chat-cache";
-import {
- createFastLoadGateState,
- fastLoadKey,
- shouldSkipFastLoad,
- markFastLoadCompleted,
-} from "@/components/agent-chat/fast-load-gate";
-import type { PreviousConversation, TraceTask } from "@/lib/api";
+import { useLatest } from "@/components/agent-chat/chat-message-utils";
import type {
Artifact,
- Conversation,
Issue,
- IssueComment,
- Message,
SkillEntry,
- TaskApi as Task,
- TaskMessageResponse,
WsMessage,
} from "@alook/shared";
import { useAgentContext } from "@/contexts/agent-context";
import { useInboxCount } from "@/contexts/inbox-count-context";
-import { useFlagCount } from "@/contexts/flag-count-context";
import { useChannel } from "@/contexts/channel-context";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
@@ -87,16 +44,20 @@ import {
MessageSquareQuote,
MoreHorizontal,
Paperclip,
- Square,
X,
} from "lucide-react";
-import { useCachedMessages } from "@/hooks/use-cached-messages";
+import { useAgentChat } from "@/hooks/use-agent-chat";
+import { useMessageFlags } from "@/hooks/use-message-flags";
+import { useChatSheets } from "@/hooks/use-chat-sheets";
+import { useFileAttachments } from "@/hooks/use-file-attachments";
+import { useTextSelectionQuote } from "@/hooks/use-text-selection-quote";
import { useSlashCommand } from "@/hooks/use-slash-command";
import { SlashCommandPopup } from "@/components/agent-chat/slash-command-popup";
import {
ChatComposer,
- type ChatComposerHandle,
+ RotatingPlaceholderOverlay,
} from "@/components/agent-chat/chat-composer";
+import { useRotatingPlaceholder } from "@/components/agent-chat/use-rotating-placeholder";
import {
ArtifactSheet,
formatSize,
@@ -109,429 +70,21 @@ import {
getArtifactUrl,
computeArtifactVersions,
} from "@/components/artifact-content-renderer";
-import { FollowUpBuffer } from "@/components/agent-chat/follow-up-buffer";
import { ScrollToBottomButton } from "@/components/ui/scroll-to-bottom-button";
-import { MessageItem } from "@/components/agent-chat/message-list";
-import { AgentPreviewCard } from "@/components/agent-preview-card";
+import { MessageItem, AgentRow } from "@/components/agent-chat/message-list";
+import { PresenceLine } from "@/components/agent-chat/presence-line";
+import { parseAvatarUrl } from "@/components/avatar";
+import {
+ MENTION_COMPONENTS,
+ NapSeparator,
+ ArtifactCard,
+} from "@/components/agent-chat/chat-view-parts";
import {
Popover,
PopoverTrigger,
PopoverContent,
} from "@/components/ui/popover";
-const MESSAGE_LIMIT = 20;
-const MAX_CONV_FETCHES_PER_CLICK = 5;
-const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
-
-function MentionHighlight(
- props: Record<string, unknown> & { children?: React.ReactNode },
-) {
- const { children, ...rest } = props;
- const { agents } = useAgentContext();
- const agentId = (rest["data-agent-id"] ?? rest.dataAgentId) as
- | string
- | undefined;
- let agent = agentId ? agents.find((a) => a.id === agentId) : undefined;
- if (!agent && typeof children === "string") {
- const nameToMatch = children.startsWith("@") ? children.slice(1) : children;
- agent = agents.find(
- (a) => a.name.toLowerCase() === nameToMatch.toLowerCase(),
- );
- }
- if (agent) {
- return (
- <Popover>
- <PopoverTrigger
- openOnHover
- delay={300}
- nativeButton={false}
- render={<span className="mention-highlight cursor-pointer" />}
- >
- {children}
- </PopoverTrigger>
- <PopoverContent side="top" className="w-fit max-w-80">
- <AgentPreviewCard agent={agent} />
- </PopoverContent>
- </Popover>
- );
- }
- return <span className="mention-highlight">{children}</span>;
-}
-const MENTION_COMPONENTS: Record<
- string,
- React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>
-> = {
- mention: MentionHighlight,
- p: ({
- children,
- node,
- ...rest
- }: Record<string, unknown> & { children?: React.ReactNode }) => {
- void node;
- return (
- <div data-md-p="" {...rest}>
- {children}
- </div>
- );
- },
-};
-
-type EventIconType = "issue" | "email" | "calendar";
-
-export function getEventIconType(
- content: string,
- conversationType?: string | null,
-): EventIconType {
- if (conversationType === "issue_event") return "issue";
- if (conversationType === "email_notification") return "email";
- if (conversationType === "calendar_event") return "calendar";
-
- const lower = content.toLowerCase();
- if (lower.startsWith("issue ") || lower.startsWith("issue:")) return "issue";
- if (lower.includes("email")) return "email";
- return "calendar";
-}
-
-/** Sort messages by (created_at, id) ascending — guarantees chronological order. */
-export function sortMessages(msgs: Message[]): Message[] {
- return msgs.slice().sort((a, b) => {
- const cmp = a.created_at.localeCompare(b.created_at);
- if (cmp !== 0) return cmp;
- return a.id.localeCompare(b.id);
- });
-}
-
-/** Merge two message arrays by ID (latest wins), then sort chronologically. */
-export function mergeMessages(
- existing: Message[],
- incoming: Message[],
-): Message[] {
- const merged = new Map<string, Message>();
- for (const m of existing) merged.set(m.id, m);
- for (const m of incoming) merged.set(m.id, m);
- return sortMessages([...merged.values()]);
-}
-
-export function addBufferedIfNew(
- prev: Message[],
- incoming: Message,
-): Message[] {
- if (prev.some((m) => m.id === incoming.id)) return prev;
- // Skip if there's a recent optimistic entry — avoids brief duplicate flash
- // when WS followup.created arrives before createBufferedMessage HTTP response.
- const t = new Date(incoming.created_at).getTime();
- if (
- prev.some(
- (m) =>
- m.id.startsWith("temp-") &&
- Math.abs(new Date(m.created_at).getTime() - t) < 2000,
- )
- ) {
- return prev;
- }
- return [...prev, incoming];
-}
-
-export function replaceOptimisticBuffered(
- prev: Message[],
- optimisticId: string,
- real: Message,
-): Message[] {
- if (prev.some((m) => m.id === real.id)) {
- return prev.filter((m) => m.id !== optimisticId);
- }
- return prev.map((m) => (m.id === optimisticId ? real : m));
-}
-
-export type NapMarker = { agentName: string; created_at: string; id: string };
-
-type TimelineItem =
- | { kind: "message"; data: Message }
- | { kind: "artifact"; data: Artifact }
- | { kind: "nap"; data: NapMarker };
-
-export type GroupPosition = "first" | "middle" | "last" | "solo";
-
-function computeGroupPositions(
- timeline: TimelineItem[],
-): (GroupPosition | null)[] {
- const positions: (GroupPosition | null)[] = new Array(timeline.length).fill(
- null,
- );
- const GROUP_THRESHOLD_MS = 60_000;
-
- // Only user/assistant messages group into tight iMessage-style stacks.
- // Event messages (email/issue/calendar notifications) must keep normal spacing.
- const isGroupable = (m: Message) =>
- m.role === "user" || m.role === "assistant";
-
- for (let i = 0; i < timeline.length; i++) {
- const item = timeline[i];
- if (item.kind !== "message") continue;
-
- const msg = item.data as Message;
- if (!isGroupable(msg)) continue; // leave as null → normal mt-4 spacing, full rounding
-
- const prev = i > 0 ? timeline[i - 1] : null;
- const next = i < timeline.length - 1 ? timeline[i + 1] : null;
-
- const sameAsPrev =
- prev?.kind === "message" &&
- isGroupable(prev.data as Message) &&
- (prev.data as Message).role === msg.role &&
- (!msg.created_at ||
- !(prev.data as Message).created_at ||
- Math.abs(
- new Date(msg.created_at).getTime() -
- new Date((prev.data as Message).created_at).getTime(),
- ) < GROUP_THRESHOLD_MS);
-
- const sameAsNext =
- next?.kind === "message" &&
- isGroupable(next.data as Message) &&
- (next.data as Message).role === msg.role &&
- (!msg.created_at ||
- !(next.data as Message).created_at ||
- Math.abs(
- new Date((next.data as Message).created_at).getTime() -
- new Date(msg.created_at).getTime(),
- ) < GROUP_THRESHOLD_MS);
-
- if (sameAsPrev && sameAsNext) positions[i] = "middle";
- else if (sameAsPrev && !sameAsNext) positions[i] = "last";
- else if (!sameAsPrev && sameAsNext) positions[i] = "first";
- else positions[i] = "solo";
- }
-
- return positions;
-}
-
-export function reorderArtifactsAfterAssistant(
- items: TimelineItem[],
-): TimelineItem[] {
- const result: TimelineItem[] = [];
- let pending: TimelineItem[] = [];
- let collecting = false;
-
- for (const item of items) {
- if (item.kind === "message" && item.data.role === "user") {
- collecting = true;
- result.push(item);
- } else if (item.kind === "message" && item.data.role === "assistant") {
- result.push(item);
- result.push(...pending);
- pending = [];
- collecting = false;
- } else if (collecting && item.kind === "artifact") {
- pending.push(item);
- } else {
- result.push(item);
- }
- }
-
- result.push(...pending);
- return result;
-}
-
-export function buildTimeline(
- messages: Message[],
- artifacts: Artifact[],
- napMarkers: NapMarker[],
- currentConversationId?: string | null,
-): TimelineItem[] {
- if (!currentConversationId || napMarkers.length === 0) {
- const items: TimelineItem[] = [
- ...messages.map((m): TimelineItem => ({ kind: "message", data: m })),
- ...artifacts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
- ...napMarkers.map((n): TimelineItem => ({ kind: "nap", data: n })),
- ];
- items.sort((a, b) => {
- const cmp = a.data.created_at.localeCompare(b.data.created_at);
- if (cmp !== 0) return cmp;
- if (a.kind === "nap" || b.kind === "nap") {
- if (a.kind === "nap" && b.kind !== "nap") return 1;
- if (a.kind !== "nap" && b.kind === "nap") return -1;
- }
- if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
- return a.data.id.localeCompare(b.data.id);
- });
- return reorderArtifactsAfterAssistant(items);
- }
-
- const napConvIds = new Set(napMarkers.map((n) => n.id.replace(/^nap-/, "")));
- const sortedNaps = [...napMarkers].sort((a, b) =>
- a.created_at.localeCompare(b.created_at),
- );
-
- const groupItems = (convId: string): TimelineItem[] => {
- const msgs: TimelineItem[] = messages
- .filter((m) => m.conversation_id === convId)
- .map((m) => ({ kind: "message" as const, data: m }));
- const arts: TimelineItem[] = artifacts
- .filter((a) => a.conversation_id === convId)
- .map((a) => ({ kind: "artifact" as const, data: a }));
- const sorted = [...msgs, ...arts].sort((a, b) => {
- const cmp = a.data.created_at.localeCompare(b.data.created_at);
- if (cmp !== 0) return cmp;
- if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
- return a.data.id.localeCompare(b.data.id);
- });
- return reorderArtifactsAfterAssistant(sorted);
- };
-
- const result: TimelineItem[] = [];
-
- for (const nap of sortedNaps) {
- const convId = nap.id.replace(/^nap-/, "");
- result.push(...groupItems(convId));
- result.push({ kind: "nap", data: nap });
- }
-
- result.push(...groupItems(currentConversationId));
-
- const knownConvIds = new Set([...napConvIds, currentConversationId]);
- const orphanMsgs = messages.filter(
- (m) => !knownConvIds.has(m.conversation_id),
- );
- const orphanArts = artifacts.filter(
- (a) => !knownConvIds.has(a.conversation_id),
- );
- if (orphanMsgs.length > 0 || orphanArts.length > 0) {
- const orphanItems: TimelineItem[] = [
- ...orphanMsgs.map((m): TimelineItem => ({ kind: "message", data: m })),
- ...orphanArts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
- ];
- orphanItems.sort((a, b) => {
- const cmp = a.data.created_at.localeCompare(b.data.created_at);
- if (cmp !== 0) return cmp;
- if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
- return a.data.id.localeCompare(b.data.id);
- });
- const reorderedOrphans = reorderArtifactsAfterAssistant(orphanItems);
- const napIdx = result.findIndex((item) => item.kind === "nap");
- if (napIdx >= 0) {
- result.splice(napIdx, 0, ...reorderedOrphans);
- } else {
- result.push(...reorderedOrphans);
- }
- }
-
- return result;
-}
-
-/**
- * Whether a completed conversation load may persist the per-channel `last_open`
- * pointer. Only the SLOW path (param-less open, `targetConvId` absent) resolves
- * the channel's latest-created conversation; the FAST path (`?conv=<id>`) loads
- * an explicit, possibly old conversation and must NOT touch the pointer (doing
- * so reintroduces the wrong-conversation flash). See {@link LastOpenEntry}.
- *
- * Pure mirror of the inline Phase B write guard, exported for unit testing the
- * fast-vs-slow decision without rendering the component.
- */
-export function shouldPersistPointerForLoad(
- targetConvId: string | null | undefined,
-): boolean {
- return !targetConvId;
-}
-
-/**
- * Decide whether a `task.created` WS event should refresh this view's
- * per-channel `last_open` pointer, and to which conversation.
- *
- * The `last_open` pointer carries "latest-created conversation for this
- * agent+channel" semantics (see {@link setLastOpenConversation}). A
- * `task.created` event is the client learning of a (possibly newer)
- * conversation in real time, so it is a valid moment to refresh the pointer —
- * but ONLY when the event belongs to exactly this agent + active channel.
- *
- * Returns the conversation id to point at, or `null` to skip the write
- * (different agent, different channel, or the pointer already points there).
- *
- * Pure so the scoping logic is unit-testable in the node-env web test suite
- * (no component render). The caller supplies `serverMessageCount` separately
- * (A1: derived from the locally-cached message count) when it performs the
- * actual `setLastOpenConversation` write.
- */
-export function pointerRefreshTargetForTaskCreated(args: {
- /** The TaskApi from the `task.created` event. */
- task: Pick<Task, "agent_id" | "channel" | "conversation_id">;
- /** The agent this view is rendering. */
- agentId: string;
- /** The active channel string (never null — null maps to "default"). */
- activeChannel: string;
- /** The conversation id the pointer currently references, if known. */
- currentPointerConvId: string | null;
-}): string | null {
- const { task, agentId, activeChannel, currentPointerConvId } = args;
- // Scope guard: never touch another agent's or channel's pointer. The event's
- // null channel normalizes to "default" to match the UI's channel string
- // (channel-context.tsx). activeChannel is always a non-null string.
- if (task.agent_id !== agentId) return null;
- if ((task.channel ?? "default") !== activeChannel) return null;
- // Already pointing here — nothing to do.
- if (task.conversation_id === currentPointerConvId) return null;
- return task.conversation_id;
-}
-
-function useLatest<T>(value: T) {
- const ref = useRef(value);
- useEffect(() => {
- ref.current = value;
- }, [value]);
- return ref;
-}
-
-function NapSeparator({ agentName }: { agentName: string }) {
- return (
- <div className="flex items-center gap-3 py-4 select-none" aria-hidden>
- <div className="flex-1 border-t border-border/40" />
- <span className="text-xs text-muted-foreground/60 whitespace-nowrap">
- {agentName} took a nap 💤
- </span>
- <div className="flex-1 border-t border-border/40" />
- </div>
- );
-}
-
-function ArtifactCard({
- artifact,
- version,
- hasDuplicates,
- onClick,
-}: {
- artifact: Artifact;
- version: number;
- hasDuplicates: boolean;
- onClick: (a: Artifact) => void;
-}) {
- return (
- <button
- onClick={() => onClick(artifact)}
- className={cn(
- "flex items-center gap-3 w-full max-w-sm rounded-lg border border-border/60 bg-muted/30",
- "px-3.5 py-2.5 text-left transition-colors duration-150",
- "hover:bg-muted/60 hover:border-border",
- )}
- >
- <FileText className="size-4 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate">
- {artifact.filename}
- {hasDuplicates && (
- <span className="ml-1.5 text-xs text-muted-foreground bg-muted rounded-full px-1.5 py-0.5 font-normal">
- v{version}
- </span>
- )}
- </p>
- <p className="text-xs text-muted-foreground">
- {formatSize(artifact.size)}
- </p>
- </div>
- </button>
- );
-}
-
export function AgentChatView({
agentId: propAgentId,
targetConvId: propTargetConvId,
@@ -581,8 +134,6 @@ export function AgentChatView({
? propTargetConvId
: searchParams.get("conv");
- const [conversation, setConversation] = useState<Conversation | null>(null);
- const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState(() => {
if (typeof window === "undefined") return "";
return (
@@ -591,54 +142,50 @@ export function AgentChatView({
) ?? ""
);
});
- const [sending, setSending] = useState(false);
- const [cancelling, setCancelling] = useState(false);
- const [activeTask, setActiveTask] = useState<Task | null>(null);
- const [taskMessages, setTaskMessages] = useState<TaskMessageResponse[]>([]);
- const [messagesLoading, setMessagesLoading] = useState(true);
- const [connectionLost, setConnectionLost] = useState(false);
- const [hasMore, setHasMore] = useState(false);
- const [loadingMore, setLoadingMore] = useState(false);
- const [artifacts, setArtifacts] = useState<Artifact[]>([]);
- const [artifactSheetOpen, setArtifactSheetOpen] = useState(false);
- const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(
- null,
- );
- const [emailSheetOpen, setEmailSheetOpen] = useState(false);
- const [selectedEmailId, setSelectedEmailId] = useState<string | null>(null);
- const [calendarEventSheetOpen, setCalendarEventSheetOpen] = useState(false);
- const [selectedCalendarEventId, setSelectedCalendarEventId] = useState<
- string | null
- >(null);
- const [issueSheetOpen, setIssueSheetOpen] = useState(false);
- const [selectedIssueId, setSelectedIssueId] = useState<string | null>(null);
- const [issueDetail, setIssueDetail] = useState<{
- issue: Issue & { trace_id?: string | null };
- messages: Message[];
- comments: IssueComment[];
- artifacts: Artifact[];
- } | null>(null);
- const [issueDetailLoading, setIssueDetailLoading] = useState(false);
- const [issueTraceTasks, setIssueTraceTasks] = useState<TraceTask[] | null>(
- null,
- );
- const [issueActiveTask, setIssueActiveTask] = useState<Task | null>(null);
- const [pendingFiles, setPendingFiles] = useState<File[]>([]);
- const [bufferedMessages, setBufferedMessages] = useState<Message[]>([]);
+ const [composerFocused, setComposerFocused] = useState(false);
+ const {
+ artifactSheetOpen,
+ setArtifactSheetOpen,
+ selectedArtifact,
+ setSelectedArtifact,
+ emailSheetOpen,
+ setEmailSheetOpen,
+ selectedEmailId,
+ setSelectedEmailId,
+ calendarEventSheetOpen,
+ setCalendarEventSheetOpen,
+ selectedCalendarEventId,
+ setSelectedCalendarEventId,
+ issueSheetOpen,
+ setIssueSheetOpen,
+ selectedIssueId,
+ setSelectedIssueId,
+ issueDetail,
+ setIssueDetail,
+ issueDetailLoading,
+ issueTraceTasks,
+ issueActiveTask,
+ setIssueActiveTask,
+ openIssue,
+ issueConvId,
+ issueTaskId,
+ } = useChatSheets(workspaceId);
+ const {
+ pendingFiles,
+ setPendingFiles,
+ fileInputRef,
+ addPendingFiles,
+ handleFileSelect,
+ removePendingFile,
+ dragging,
+ handleDragEnter,
+ handleDragLeave,
+ handleDragOver,
+ handleDrop,
+ } = useFileAttachments();
const [caretIndex, setCaretIndex] = useState<number | null>(null);
- const [previousConversations, setPreviousConversations] = useState<
- PreviousConversation[]
- >([]);
- const [hasMoreConversations, setHasMoreConversations] = useState(false);
- const [napMarkers, setNapMarkers] = useState<NapMarker[]>([]);
- const [thinkingCounts, setThinkingCounts] = useState<Record<string, number>>(
- {},
- );
const [renderNow] = useState(() => Date.now());
- const [pendingFilesByMessage, setPendingFilesByMessage] = useState<
- Map<string, File[]>
- >(() => new Map());
const [quotedText, setQuotedText] = useState<string | null>(() => {
if (typeof window === "undefined") return null;
try {
@@ -653,51 +200,105 @@ export function AgentChatView({
}
});
const [isMultiLine, setIsMultiLine] = useState(false);
- const [selectionPopup, setSelectionPopup] = useState<{
- text: string;
- x: number;
- y: number;
- } | null>(null);
- const [flaggedIds, setFlaggedIds] = useState<Set<string>>(new Set());
- const flaggedIdsRef = useRef(flaggedIds);
- useEffect(() => {
- flaggedIdsRef.current = flaggedIds;
- });
-
- const {
- increment: flagIncrement,
- decrement: flagDecrement,
- refresh: flagRefresh,
- } = useFlagCount();
-
- const { writeToCache } = useCachedMessages(targetConvId ?? null, workspaceId);
- const writeToCacheRef = useRef(writeToCache);
- useEffect(() => {
- writeToCacheRef.current = writeToCache;
- }, [writeToCache]);
+ const { flaggedIds, setFlaggedIds, handleToggleFlag } =
+ useMessageFlags(workspaceId);
useEffect(() => {
setChannelAgentId(agentId);
}, [agentId, setChannelAgentId]);
- const agentArtifacts = useMemo(
- () => artifacts.filter((a) => a.source === "agent"),
- [artifacts],
+ // Component-owned ref written by the hook's load effect; read by the
+ // draft-meta persist effect below to gate the first write until restore runs.
+ const draftMetaRestoredRef = useRef(false);
+
+ // Reader-refs for the externally-owned values the orchestration reads inside
+ // long-lived callbacks (handleSend). useLatest keeps them fresh without
+ // churning callback identity. `activeSkillRef` is a manual ref synced below,
+ // because `slashCommand` is defined after `useAgentChat` (it needs the
+ // hook-created `composerRef`).
+ const inputRef = useLatest(input);
+ const quotedTextRef = useLatest(quotedText);
+ const pendingFilesRef = useLatest(pendingFiles);
+ const activeSkillRef = useRef<SkillEntry | null>(null);
+ // Holds the `slashCommand` instance (created after this hook call, since it
+ // needs the hook's `composerRef`) so the hook's setActiveSkill/clearActiveSkill
+ // wrappers can reach it from inside the load effect.
+ const slashCommandRef = useRef<ReturnType<typeof useSlashCommand> | null>(
+ null,
);
+ const chat = useAgentChat(
+ {
+ agentId,
+ targetConvId,
+ scrollToTaskId,
+ scrollToMessageId,
+ propTargetConvId,
+ workspaceId,
+ agents,
+ activeChannel,
+ channelLoading,
+ subscribeWs,
+ subscribeReconnect,
+ refreshInboxCount,
+ },
+ {
+ setFlaggedIds,
+ setPendingFiles,
+ setInput,
+ setQuotedText,
+ setActiveSkill: (skill: SkillEntry | null) =>
+ slashCommandRef.current?.setActiveSkill(skill),
+ clearActiveSkill: () => slashCommandRef.current?.clearActiveSkill(),
+ inputRef,
+ quotedTextRef,
+ pendingFilesRef,
+ activeSkillRef,
+ draftMetaRestoredRef,
+ },
+ );
+
+ const {
+ conversation,
+ messages,
+ sending,
+ activeTask,
+ taskMessages,
+ messagesLoading,
+ connectionLost,
+ loadingMore,
+ artifacts,
+ napping,
+ pendingFilesByMessage,
+ failedSends,
+ agentArtifacts,
+ agentName,
+ timeline,
+ groupPositions,
+ activeTaskStreamMsgId,
+ canLoadMore,
+ currentConvHasMessages,
+ scrollRef,
+ composerRef,
+ loadOlderMessages,
+ handleScroll,
+ handleSend,
+ handleRetrySend,
+ handleRetryTask,
+ handleNap,
+ } = chat;
+
const { versionMap, duplicateFilenames } = useMemo(
() => computeArtifactVersions(agentArtifacts),
[agentArtifacts],
);
- const timeline = useMemo(
- () => buildTimeline(messages, agentArtifacts, napMarkers, conversation?.id),
- [messages, agentArtifacts, napMarkers, conversation?.id],
- );
- const groupPositions = useMemo(
- () => computeGroupPositions(timeline),
- [timeline],
+ const agentAvatarConfig = useMemo(
+ () => parseAvatarUrl(agents.find((a) => a.id === agentId)?.avatar_url ?? null),
+ [agents, agentId],
);
+ // First name only — presence copy reads socially ("Maya is typing…").
+ const agentFirstName = useMemo(() => agentName.split(/\s+/)[0] || agentName, [agentName]);
const handleArtifactClick = useCallback(
(artifact: Artifact) => {
@@ -723,37 +324,6 @@ export function AgentChatView({
[workspaceId],
);
- const scrollRef = useRef<HTMLDivElement>(null);
- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const markReadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const pollTaskIdRef = useRef<string | null>(null);
- const lastSeqRef = useRef(0);
- const pollFailures = useRef(0);
- const initialScrollDone = useRef(false);
- const loadingMoreRef = useRef(false);
- const isNearBottom = useRef(true);
- const scrollTargetActiveRef = useRef(false);
- const startPollingRef = useRef<
- | ((taskId: string, conversationId: string, initialSeq?: number) => void)
- | null
- >(null);
- const oldestConversationCursorRef = useRef<PreviousConversation | null>(null);
- const backfillAttemptsRef = useRef(0);
- const prevConversationIdRef = useRef<string | undefined>(undefined);
- // The server-confirmed conversation id for the current load. Cache writes
- // (mergeCachedMessages / appendCachedMessage / setLastOpenConversation) must
- // guard on this so a write never lands on an optimistically-rendered (not yet
- // confirmed) conversation during the cache-first window. Stays null until
- // checkFreshness / chatInit / conversationInit confirms an id.
- const loadConvIdRef = useRef<string | null>(null);
- // Dedup gate for the fast-path load: skips a redundant re-run when only
- // channel deps (activeChannel / channelLoading) change, WITHOUT stranding the
- // skeleton if a run is cancelled mid-flight. See fast-load-gate.ts (Part 2-a /
- // TODO 6 + stuck-skeleton fix).
- const fastLoadGateRef = useRef(createFastLoadGateState());
- const fileInputRef = useRef<HTMLInputElement>(null);
- // TipTap composer imperative handle (focus / clear / isEmpty / anchor coords).
- const composerRef = useRef<ChatComposerHandle>(null);
// Editor plain text + caret, reported up from the composer, drive the
// slash-command popup (mentions are handled natively inside the composer).
const [editorText, setEditorText] = useState("");
@@ -763,16 +333,16 @@ export function AgentChatView({
[agents, agentId],
);
- // Slash command skills — fetch from D1 on mount (and when agentId changes)
+ // Slash command skills — fetch from D1 on mount
const [agentSkills, setAgentSkills] = useState<SkillEntry[]>([]);
- const draftMetaRestoredRef = useRef(false);
+ const skillsFetchedRef = useRef(false);
useEffect(() => {
- let stale = false;
+ if (skillsFetchedRef.current) return;
+ skillsFetchedRef.current = true;
getAgentSkills(agentId, workspaceId)
- .then((res) => { if (!stale) setAgentSkills(res.skills as SkillEntry[]); })
- .catch(() => {});
- return () => { stale = true; };
+ .then((res) => setAgentSkills(res.skills as SkillEntry[]))
+ .catch(() => { });
}, [agentId, workspaceId]);
const [initialActiveSkill] = useState<SkillEntry | null>(() => {
@@ -805,6 +375,20 @@ export function AgentChatView({
}, []),
});
+ // Bridge `slashCommand` (defined here, after `useAgentChat` because it needs
+ // the hook-created `composerRef`) back to the orchestration: a ref the hook's
+ // setActiveSkill/clearActiveSkill wrappers call, and a useLatest-style sync of
+ // `activeSkill` into the `activeSkillRef` the hook reads inside handleSend.
+ // MUST be a layout effect, not a passive one: the hook's load effect (passive)
+ // runs on first mount and calls setActiveSkill to restore a saved skill draft.
+ // React fires all layout effects of a commit before any passive effect, so this
+ // populates slashCommandRef before the load effect reads it — a passive sync
+ // here would still be null then and silently drop the restore.
+ useLayoutEffect(() => {
+ slashCommandRef.current = slashCommand;
+ activeSkillRef.current = slashCommand.activeSkill;
+ });
+
useEffect(() => {
if (agentSkills.length === 0 || !slashCommand.activeSkill) return;
const exists = agentSkills.some(
@@ -852,1303 +436,8 @@ export function AgentChatView({
}
}, [sending]);
- const scrollToBottom = useCallback(() => {
- isNearBottom.current = true;
- setTimeout(() => {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- behavior: "smooth",
- });
- }, 50);
- }, []);
-
- useEffect(() => {
- // The slow path (no targetConvId) resolves the conversation id via the
- // server using activeChannel, so it must wait for the channel list. The
- // fast path (known targetConvId) and the cache-first optimistic paint need
- // neither activeChannel nor a loaded channel list, so they must NOT be
- // gated by channelLoading (Part 2-a). channelLoading stays in the dep array
- // so the slow path retries once channels load.
- if (!targetConvId && channelLoading) return;
-
- // Fast path: ignore channel-only dep changes (TODO 6). shouldSkipFastLoad
- // returns true only when a load for this identity has already COMPLETED, and
- // otherwise clears the completed marker so a run cancelled mid-flight leaves
- // no "done" marker — the recovery run then proceeds and clears the skeleton
- // instead of getting stuck forever. See fast-load-gate.ts.
- const fastKey = fastLoadKey({
- workspaceId,
- agentId,
- targetConvId,
- scrollToTaskId,
- });
- if (shouldSkipFastLoad(fastKey, fastLoadGateRef.current)) return;
-
- if (pollRef.current) clearInterval(pollRef.current);
- pollRef.current = null;
- pollTaskIdRef.current = null;
- loadConvIdRef.current = null;
- let ignore = false;
- setMessagesLoading(true);
- initialScrollDone.current = false;
- setActiveTask(null);
- setTaskMessages([]);
- setBufferedMessages([]);
- setPendingFilesByMessage(new Map());
- setNapMarkers([]);
- setThinkingCounts({});
- setPreviousConversations([]);
- setHasMoreConversations(false);
- oldestConversationCursorRef.current = null;
- setInput(
- localStorage.getItem(
- `chat-draft:${agentId}:${targetConvId ?? "default"}`,
- ) ?? "",
- );
- const metaRaw = localStorage.getItem(
- `chat-draft-meta:${agentId}:${targetConvId ?? "default"}`,
- );
- if (metaRaw) {
- try {
- const meta = JSON.parse(metaRaw);
- setQuotedText(meta.quote ?? null);
- slashCommand.setActiveSkill(
- meta.skill ? (meta.skill as SkillEntry) : null,
- );
- } catch {
- setQuotedText(null);
- slashCommand.setActiveSkill(null);
- }
- } else {
- setQuotedText(null);
- slashCommand.setActiveSkill(null);
- }
- draftMetaRestoredRef.current = true;
- setMessages([]);
-
- // Paint cached messages for a known conversation id without any network.
- // Returns true if it painted, so the caller can suppress the loading
- // skeleton until the background reconcile runs.
- async function paintFromCache(convId: string): Promise<{
- painted: boolean;
- cacheMeta: Awaited<ReturnType<typeof getCacheMeta>>;
- }> {
- const cacheMeta = await getCacheMeta(convId, workspaceId);
- if (cacheMeta?.newestMessageId) {
- const cached = await getCachedMessages(convId, workspaceId);
- if (ignore) return { painted: false, cacheMeta };
- if (cached && cached.length > 0) {
- setMessages(cached);
- setHasMore(cacheMeta.hasMore);
- setMessagesLoading(false);
- return { painted: true, cacheMeta };
- }
- }
- return { painted: false, cacheMeta };
- }
-
- async function load() {
- let hasCachedMessages = false;
- try {
- let convId: string | null = null;
- let cacheMeta: Awaited<ReturnType<typeof getCacheMeta>> = null;
- // The id we optimistically painted in the slow path; reconciled against
- // the server-confirmed id once checkFreshness returns.
- let optimisticConvId: string | null = null;
-
- if (targetConvId) {
- // Fast path: we already know the conv ID — render from cache immediately, no network needed
- convId = targetConvId;
- const res = await paintFromCache(convId);
- if (ignore) return;
- cacheMeta = res.cacheMeta;
- hasCachedMessages = res.painted;
- } else {
- // Slow path: resolve the conversation id locally first (last-open
- // pointer) and paint its cache immediately, then verify in the
- // background. Only paint optimistically when the pointer is plausibly
- // fresh (serverMessageCount > 0 and a non-empty cache), so a stale or
- // empty pointer falls back to the skeleton (review #4).
- //
- // The pointer now carries "latest-created conversation for this
- // agent+channel" semantics (see {@link setLastOpenConversation} and the
- // gated write in Phase B / the task.created WS handler), matching the
- // server's `check-fresh` definition of "current" (latest-created). So
- // the optimistic paint is correct-by-construction: in the common case
- // the painted id equals the check-fresh id below → no swap → no flash.
- // Do NOT reintroduce "last opened" semantics here (e.g. by writing the
- // pointer from a `?conv=` fast-path open) — that is exactly the bug this
- // fix removed.
- const lastOpen = await getLastOpenConversation(
- agentId,
- activeChannel,
- workspaceId,
- );
- if (ignore) return;
- if (lastOpen?.conversation_id && lastOpen.serverMessageCount > 0) {
- const res = await paintFromCache(lastOpen.conversation_id);
- if (ignore) return;
- if (res.painted) {
- hasCachedMessages = true;
- optimisticConvId = lastOpen.conversation_id;
- cacheMeta = res.cacheMeta;
- }
- }
-
- // Background freshness check — does NOT gate the paint above.
- try {
- const fresh = await checkFreshness(
- { agentId, channel: activeChannel },
- workspaceId,
- );
- if (ignore) return;
- convId = fresh.conversation_id;
-
- if (optimisticConvId && convId !== optimisticConvId) {
- // We painted the wrong/stale conversation. Swap to the correct
- // one and reset scroll intent so the initial-scroll effect
- // re-fires for the new message set (review #2).
- initialScrollDone.current = false;
- isNearBottom.current = true;
- const res = await paintFromCache(convId);
- if (ignore) return;
- cacheMeta = res.cacheMeta;
- hasCachedMessages = res.painted;
- if (!res.painted) {
- // The correct conversation has no cache — clear the stale
- // optimistic render so the Phase B merge below starts from an
- // empty list instead of mixing conversation A's messages into B.
- setMessages([]);
- setMessagesLoading(true);
- }
- } else if (!optimisticConvId) {
- // Nothing painted yet — read the resolved conversation's cache.
- const res = await paintFromCache(convId);
- if (ignore) return;
- cacheMeta = res.cacheMeta;
- hasCachedMessages = res.painted;
- }
- // else: optimistic id matched the confirmed id — keep the paint.
- //
- // We always fall through to Phase B: even when the cache is fresh
- // (idMatches && countMatches), conversationInit returns cache_valid
- // and is still needed for conversation meta / tasks / artifacts, and
- // it does NOT re-set messages — so a fresh cache means exactly one
- // setMessages (the instant paint), no flicker. Phase B also writes
- // the server-confirmed last_open pointer for both fresh and stale.
- } catch {
- // checkFreshness failed — fall back to chatInit below
- }
- }
-
- // Phase B: full data fetch (background hydration or stale-cache refresh)
- if (convId) {
- loadConvIdRef.current = convId;
- const data = await conversationInit(convId, workspaceId, {
- newestMessageId: cacheMeta?.newestMessageId ?? undefined,
- // 0 means "count unknown" (e.g. cached via the chatInit fallback,
- // which has no server total) — omit the param so the server skips
- // the count compare and relies on newestMessageId alone. Sending
- // "0" would make the server's `serverMessageCount === 0` check fail
- // for every non-empty conversation, forcing a needless full merge.
- messageCount: cacheMeta?.serverMessageCount || undefined,
- });
- if (ignore) return;
- setConversation(data.conversation);
- setHasMoreConversations(data.has_more_conversations);
- if (!data.cache_valid && data.messages) {
- // Stale cache — merge server data in place, preserving scroll
- // position unless the user was already near the bottom (A2 / TODO 5).
- const wasNearBottom = isNearBottom.current;
- setMessages((prev) => mergeMessages(prev, data.messages!));
- if (loadConvIdRef.current === convId) {
- mergeCachedMessages(
- convId,
- data.messages,
- data.has_more_messages,
- workspaceId,
- data.message_count,
- ).catch(() => {});
- }
- setHasMore(data.has_more_messages);
- if (
- hasCachedMessages &&
- initialScrollDone.current &&
- wasNearBottom
- ) {
- scrollToBottom();
- }
- } else if (cacheMeta) {
- setHasMore(cacheMeta.hasMore);
- }
- // Record the last-open pointer with server-confirmed freshness so the
- // next param-less open can resolve this conversation locally. Re-read
- // the cache meta (just updated by mergeCachedMessages on the stale
- // path) so the stored newest id is authoritative rather than inferred
- // from page order.
- //
- // GATED on `!targetConvId`: only the SLOW path (param-less, server-
- // resolved) may write the pointer. On the FAST path `convId ===
- // targetConvId` — an explicit, possibly OLD conversation the user
- // navigated to via `?conv=`. Persisting that would re-corrupt the
- // pointer back to "last-opened" semantics and reintroduce the
- // wrong-conversation flash on the next param-less open. The pointer
- // must only ever carry the channel's latest-created conversation.
- if (
- loadConvIdRef.current === convId &&
- shouldPersistPointerForLoad(targetConvId)
- ) {
- const confirmedMeta = await getCacheMeta(convId, workspaceId);
- if (ignore) return;
- setLastOpenConversation(
- agentId,
- activeChannel,
- {
- conversation_id: convId,
- newestMessageId:
- confirmedMeta?.newestMessageId ??
- cacheMeta?.newestMessageId ??
- null,
- serverMessageCount: data.message_count,
- },
- workspaceId,
- ).catch(() => {});
- }
- setThinkingCounts(data.thinking_counts);
- setArtifacts(data.artifacts);
- setBufferedMessages(data.buffered_messages);
- setFlaggedIds(new Set(data.flagged_message_ids));
- if (data.active_task) {
- setActiveTask(data.active_task);
- setTaskMessages(data.task_messages);
- if (data.task_messages.length > 0) {
- lastSeqRef.current = Math.max(
- ...data.task_messages.map((m) => m.seq),
- );
- }
- startPollingRef.current?.(
- data.active_task.id,
- convId,
- lastSeqRef.current,
- );
- }
- if (scrollToTaskId) {
- const task = await getTask(scrollToTaskId, workspaceId).catch(
- () => null,
- );
- if (ignore) return;
- if (
- task &&
- !["completed", "failed", "cancelled", "superseded"].includes(
- task.status,
- )
- ) {
- setActiveTask(task);
- const tmsgs = await getTaskMessages(
- scrollToTaskId,
- workspaceId,
- ).catch(() => [] as TaskMessageResponse[]);
- if (ignore) return;
- setTaskMessages(tmsgs);
- if (tmsgs.length > 0) {
- lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq));
- }
- startPollingRef.current?.(task.id, convId, lastSeqRef.current);
- }
- }
- } else {
- // checkFreshness failed entirely — fall back to chatInit
- const data = await chatInit(agentId, workspaceId, activeChannel);
- if (ignore) return;
- loadConvIdRef.current = data.conversation.id;
- setConversation(data.conversation);
- const wasNearBottom = isNearBottom.current;
- setMessages((prev) =>
- prev.length > 0
- ? mergeMessages(prev, data.messages)
- : data.messages,
- );
- setHasMore(data.has_more_messages);
- setArtifacts(data.artifacts);
- setBufferedMessages(data.buffered_messages);
- setHasMoreConversations(data.has_more_conversations);
- mergeCachedMessages(
- data.conversation.id,
- data.messages,
- data.has_more_messages,
- workspaceId,
- ).catch(() => {});
- // This branch is reached only when `convId` is null — i.e. the SLOW
- // path's checkFreshness failed and we fell back to chatInit. chatInit
- // returns the server's current (latest-created) conversation, so this
- // write carries the correct "latest-created" semantics. It is
- // slow-path-only by construction (the fast path sets convId =
- // targetConvId and never falls through here), so no `!targetConvId`
- // gate is needed.
- setLastOpenConversation(
- agentId,
- activeChannel,
- {
- conversation_id: data.conversation.id,
- newestMessageId:
- data.messages.length > 0
- ? data.messages[data.messages.length - 1].id
- : null,
- // chatInit returns no server total; data.messages is only the first
- // page. When more pages exist, the count is unknown — store 0, which
- // the read site treats as "unknown" and omits from the freshness
- // compare (relying on newestMessageId instead). Storing the partial
- // page length would otherwise force a needless full merge next open.
- serverMessageCount: data.has_more_messages
- ? 0
- : data.messages.length,
- },
- workspaceId,
- ).catch(() => {});
- if (hasCachedMessages && initialScrollDone.current && wasNearBottom) {
- scrollToBottom();
- }
- listFlaggedMessageIds(workspaceId, data.conversation.id)
- .then((r) => {
- if (!ignore) setFlaggedIds(new Set(r.message_ids));
- })
- .catch(() => {});
- if (data.active_task) {
- setActiveTask(data.active_task);
- if (data.task_messages.length > 0) {
- setTaskMessages(data.task_messages);
- lastSeqRef.current = Math.max(
- ...data.task_messages.map((m) => m.seq),
- );
- }
- if (
- !["completed", "failed", "cancelled", "superseded"].includes(
- data.active_task.status,
- )
- ) {
- startPollingRef.current?.(
- data.active_task.id,
- data.conversation.id,
- lastSeqRef.current,
- );
- }
- }
- }
- } catch {
- if (!hasCachedMessages) {
- toast.error("Failed to load conversation");
- } else {
- toast.error("Couldn't refresh conversation");
- }
- } finally {
- if (!ignore) {
- setMessagesLoading(false);
- // Mark this fast-path identity as completed only now, so a re-fire
- // caused purely by a channel-dep change is deduped (TODO 6) — while a
- // run cancelled before reaching here leaves no marker, letting the
- // successor run take over and clear the skeleton.
- markFastLoadCompleted(fastKey, fastLoadGateRef.current);
- }
- }
- }
- load();
- return () => {
- ignore = true;
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- agentId,
- workspaceId,
- targetConvId,
- scrollToTaskId,
- activeChannel,
- channelLoading,
- ]);
-
- const refreshInboxCountRef = useRef(refreshInboxCount);
- useEffect(() => {
- refreshInboxCountRef.current = refreshInboxCount;
- }, [refreshInboxCount]);
-
- const markedReadRef = useRef<string | null>(null);
- useEffect(() => {
- if (!conversation?.id || !workspaceId) return;
- if (markedReadRef.current === conversation.id) return;
- markedReadRef.current = conversation.id;
- const timer = setTimeout(() => {
- markInboxRead(conversation.id, workspaceId)
- .then(() => refreshInboxCountRef.current())
- .catch(() => {});
- }, 1000);
- return () => {
- markedReadRef.current = null;
- clearTimeout(timer);
- };
- }, [conversation?.id, workspaceId]);
-
- // Scroll to bottom on initial load (skip if scroll-to-task/message is active)
- useEffect(() => {
- if (!messagesLoading && messages.length > 0 && !initialScrollDone.current) {
- initialScrollDone.current = true;
- if (scrollToTaskId || scrollToMessageId) {
- isNearBottom.current = false;
- } else if (propTargetConvId) {
- setTimeout(() => {
- const assistantMsgs = scrollRef.current?.querySelectorAll(
- "[data-quote-source]",
- );
- if (assistantMsgs && assistantMsgs.length > 0) {
- const lastAssistant = assistantMsgs[assistantMsgs.length - 1];
- lastAssistant.scrollIntoView({
- behavior: "instant",
- block: "start",
- });
- } else {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- });
- }
- }, 50);
- } else {
- setTimeout(() => {
- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
- }, 50);
- }
- }
- }, [
- messagesLoading,
- messages.length,
- scrollToTaskId,
- scrollToMessageId,
- propTargetConvId,
- ]);
-
- // Scroll to task when ?task= param is present
- useEffect(() => {
- if (!scrollToTaskId || messagesLoading || !conversation) return;
- isNearBottom.current = false;
- scrollTargetActiveRef.current = true;
- let cancelled = false;
- let highlightTimerId: ReturnType<typeof setTimeout> | undefined;
- const tryScroll = () => {
- if (cancelled) return false;
- const el = document.querySelector(
- `[data-task-id="${CSS.escape(scrollToTaskId)}"]`,
- );
- if (!el) return false;
- el.scrollIntoView({ behavior: "smooth", block: "start" });
- el.classList.add("task-highlight");
- highlightTimerId = setTimeout(() => {
- el.classList.remove("task-highlight");
- if (!cancelled) scrollTargetActiveRef.current = false;
- }, 1500);
- return true;
- };
- const timerId = setTimeout(async () => {
- if (cancelled) return;
- if (tryScroll()) return;
- try {
- const around = await listMessagesAroundTask(
- conversation.id,
- workspaceId,
- scrollToTaskId,
- );
- if (cancelled) return;
- if (around.length > 0) {
- setMessages((prev) => mergeMessages(prev, around));
- requestAnimationFrame(() => {
- setTimeout(() => {
- if (!tryScroll()) {
- scrollTargetActiveRef.current = false;
- }
- }, 100);
- });
- } else {
- scrollTargetActiveRef.current = false;
- }
- } catch {
- if (!cancelled) scrollTargetActiveRef.current = false;
- }
- }, 100);
- return () => {
- cancelled = true;
- clearTimeout(timerId);
- if (highlightTimerId) clearTimeout(highlightTimerId);
- };
- }, [scrollToTaskId, messagesLoading, conversation, workspaceId]);
-
- // Scroll to message when ?msg= param is present (skip if task scroll is active)
- useEffect(() => {
- if (
- !scrollToMessageId ||
- scrollToTaskId ||
- messagesLoading ||
- !conversation
- )
- return;
- isNearBottom.current = false;
- scrollTargetActiveRef.current = true;
- let cancelled = false;
- let highlightTimerId: ReturnType<typeof setTimeout> | undefined;
- const tryScroll = () => {
- if (cancelled) return false;
- const el = document.querySelector(
- `[data-message-id="${CSS.escape(scrollToMessageId)}"]`,
- );
- if (!el) return false;
- el.scrollIntoView({ behavior: "smooth", block: "start" });
- el.classList.add("task-highlight");
- highlightTimerId = setTimeout(() => {
- el.classList.remove("task-highlight");
- if (!cancelled) scrollTargetActiveRef.current = false;
- }, 1500);
- return true;
- };
- const timerId = setTimeout(() => {
- if (cancelled) return;
- if (!tryScroll()) {
- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
- scrollTargetActiveRef.current = false;
- }
- }, 100);
- return () => {
- cancelled = true;
- clearTimeout(timerId);
- if (highlightTimerId) clearTimeout(highlightTimerId);
- };
- }, [scrollToMessageId, scrollToTaskId, messagesLoading, conversation]);
-
- // Auto-scroll when task badge appears or new task steps arrive
- const taskStatus = activeTask?.status;
- useEffect(() => {
- if (scrollTargetActiveRef.current) return;
- const isRunning = taskStatus === "running" || taskStatus === "queued";
- if (isRunning && isNearBottom.current) {
- scrollToBottom();
- }
- }, [taskMessages.length, taskStatus, scrollToBottom]);
-
- const agentName = useMemo(
- () => agents.find((a) => a.id === agentId)?.name ?? "Agent",
- [agents, agentId],
- );
-
- const messagesRef = useLatest(messages);
- const hasMoreRef = useLatest(hasMore);
- const prevConvsRef = useLatest(previousConversations);
- const hasMoreConvsRef = useLatest(hasMoreConversations);
- const agentNameRef = useLatest(agentName);
- const activeChannelRef = useLatest(activeChannel);
-
- const loadOlderMessages = useCallback(
- async (scrollToEnd = false) => {
- if (!conversation || loadingMoreRef.current) return;
- loadingMoreRef.current = true;
-
- const currentMessages = messagesRef.current;
- const currentHasMore = hasMoreRef.current;
- const currentHasMoreConvs = hasMoreConvsRef.current;
- const currentAgentName = agentNameRef.current;
- const currentChannel = activeChannelRef.current;
- const isSingleConvView = !!targetConvId;
-
- const oldest = currentMessages[0];
- const paginatingConvId =
- oldestConversationCursorRef.current?.id ?? conversation.id;
- const canLoadMoreInConv = currentHasMore && oldest;
- let prevConvsList = prevConvsRef.current;
-
- if (
- !isSingleConvView &&
- !canLoadMoreInConv &&
- prevConvsList.length === 0 &&
- currentHasMoreConvs
- ) {
- const oldestConv = oldestConversationCursorRef.current ?? {
- id: conversation.id,
- created_at: conversation.created_at,
- };
- try {
- const result = await listPreviousConversations(agentId, workspaceId, {
- exclude: conversation.id,
- before: oldestConv.created_at,
- channel: currentChannel,
- });
- prevConvsList = result.conversations;
- setPreviousConversations(result.conversations);
- setHasMoreConversations(result.has_more);
- } catch {
- setHasMoreConversations(false);
- }
- }
-
- const canLoadPrevConv = !isSingleConvView && prevConvsList.length > 0;
-
- if (!canLoadMoreInConv && !canLoadPrevConv) {
- loadingMoreRef.current = false;
- return;
- }
-
- setLoadingMore(true);
- const el = scrollRef.current;
- if (el) el.style.overflowAnchor = "none";
- const prevScrollHeight = el?.scrollHeight ?? 0;
-
- try {
- let phase1Messages: Message[] = [];
- let phase2Messages: Message[] = [];
- let remaining = MESSAGE_LIMIT;
- let lastHasMore = false;
- const napMarkersToAdd: {
- agentName: string;
- created_at: string;
- id: string;
- }[] = [];
-
- // --- Phase 1: Load from current/paginating conversation ---
- let phase1HasMore = false;
- if (canLoadMoreInConv) {
- const cached =
- paginatingConvId === conversation.id
- ? await getCachedMessagesBefore(
- paginatingConvId,
- oldest!.created_at,
- oldest!.id,
- MESSAGE_LIMIT,
- workspaceId,
- )
- : null;
-
- if (cached) {
- phase1Messages = cached.messages;
- remaining -= cached.messages.length;
- lastHasMore = cached.hasMore;
- } else {
- const result = await listMessages(paginatingConvId, workspaceId, {
- limit: MESSAGE_LIMIT,
- before: oldest!.created_at,
- beforeId: oldest!.id,
- });
- phase1Messages = result.messages;
- remaining -= result.messages.length;
- lastHasMore = result.has_more;
- }
- phase1HasMore = lastHasMore;
- }
-
- // --- Phase 2: Load from previous conversations (only in timeline mode) ---
- if (!isSingleConvView && !lastHasMore && remaining > 0) {
- if (prevConvsList.length === 0 && currentHasMoreConvs) {
- const oldestConv = oldestConversationCursorRef.current ?? {
- id: conversation.id,
- created_at: conversation.created_at,
- };
- try {
- const result = await listPreviousConversations(
- agentId,
- workspaceId,
- {
- exclude: conversation.id,
- before: oldestConv.created_at,
- channel: currentChannel,
- },
- );
- prevConvsList = result.conversations;
- setPreviousConversations(result.conversations);
- setHasMoreConversations(result.has_more);
- } catch {
- setHasMoreConversations(false);
- }
- }
-
- let consumed = 0;
- let fetchCount = 0;
-
- while (
- consumed < prevConvsList.length &&
- remaining > 0 &&
- fetchCount < MAX_CONV_FETCHES_PER_CLICK
- ) {
- const prevConv = prevConvsList[consumed]!;
- consumed++;
- fetchCount++;
- const result = await listMessages(prevConv.id, workspaceId, {
- limit: remaining,
- });
-
- if (result.messages.length === 0) {
- oldestConversationCursorRef.current = prevConv;
- continue;
- }
-
- const napTs =
- oldestConversationCursorRef.current?.created_at ??
- conversation.created_at;
- napMarkersToAdd.push({
- agentName: currentAgentName,
- created_at: napTs,
- id: `nap-${prevConv.id}`,
- });
-
- phase2Messages = [...result.messages, ...phase2Messages];
- remaining -= result.messages.length;
- lastHasMore = result.has_more;
- oldestConversationCursorRef.current = prevConv;
- }
-
- if (consumed > 0) {
- setPreviousConversations((prev) => prev.slice(consumed));
- }
- }
-
- // --- Final state update ---
- const allNewMessages = [...phase2Messages, ...phase1Messages];
- flushSync(() => {
- if (allNewMessages.length > 0) {
- if (napMarkersToAdd.length > 0) {
- setNapMarkers((prev) => {
- const existingIds = new Set(prev.map((m) => m.id));
- const newMarkers = napMarkersToAdd.filter(
- (m) => !existingIds.has(m.id),
- );
- return [...prev, ...newMarkers];
- });
- }
- setHasMore(lastHasMore);
- setMessages((prev) => {
- const existingIds = new Set(prev.map((m) => m.id));
- const unique = allNewMessages.filter(
- (m) => !existingIds.has(m.id),
- );
- return [...unique, ...prev];
- });
- } else {
- setHasMore(false);
- }
- });
-
- if (allNewMessages.length > 0 && conversation) {
- const currentConvMessages = allNewMessages.filter(
- (m) => m.conversation_id === conversation.id,
- );
- if (currentConvMessages.length > 0) {
- mergeCachedMessages(
- conversation.id,
- currentConvMessages,
- phase1HasMore,
- workspaceId,
- ).catch(() => {});
- }
- }
-
- loadingMoreRef.current = false;
- flushSync(() => setLoadingMore(false));
-
- if (el) {
- if (scrollToEnd) {
- el.scrollTop = el.scrollHeight;
- } else {
- const newScrollHeight = el.scrollHeight;
- el.scrollTop = newScrollHeight - prevScrollHeight;
- }
- }
- } catch {
- toast.error("Failed to load older messages");
- } finally {
- loadingMoreRef.current = false;
- setLoadingMore(false);
- if (scrollRef.current) scrollRef.current.style.overflowAnchor = "";
- }
- },
- [
- conversation,
- workspaceId,
- agentId,
- targetConvId,
- messagesRef,
- hasMoreRef,
- hasMoreConvsRef,
- agentNameRef,
- activeChannelRef,
- prevConvsRef,
- ],
- );
-
- const canLoadMore = targetConvId
- ? hasMore
- : hasMore || previousConversations.length > 0 || hasMoreConversations;
-
- useEffect(() => {
- if (conversation?.id === prevConversationIdRef.current) return;
- prevConversationIdRef.current = conversation?.id;
- backfillAttemptsRef.current = 0;
- }, [conversation?.id]);
-
- const MIN_MESSAGES = 10;
- useEffect(() => {
- if (messagesLoading || !conversation) return;
- if (scrollToTaskId || targetConvId) return;
- if (messages.length >= MIN_MESSAGES || !canLoadMore) return;
- if (loadingMore) return;
- if (backfillAttemptsRef.current >= 3) return;
- backfillAttemptsRef.current += 1;
- loadOlderMessages(true);
- }, [
- messagesLoading,
- messages.length,
- canLoadMore,
- loadingMore,
- conversation,
- loadOlderMessages,
- scrollToTaskId,
- targetConvId,
- ]);
-
- const handleScroll = useCallback(() => {
- const el = scrollRef.current;
- if (!el) return;
- isNearBottom.current =
- el.scrollHeight - el.scrollTop - el.clientHeight < 100;
- }, []);
-
- const startPolling = useCallback(
- (taskId: string, conversationId: string, initialSeq?: number) => {
- if (pollRef.current) clearInterval(pollRef.current);
- lastSeqRef.current = initialSeq ?? 0;
- pollFailures.current = 0;
- setConnectionLost(false);
- pollTaskIdRef.current = taskId;
-
- pollRef.current = setInterval(async () => {
- // A new poll was started (e.g. by followup.dispatched) — bail out
- if (pollTaskIdRef.current !== taskId) return;
-
- try {
- const [task, tmsgs] = await Promise.all([
- getTask(taskId, workspaceId),
- getTaskMessages(
- taskId,
- workspaceId,
- lastSeqRef.current || undefined,
- ),
- ]);
-
- // Re-check after await — a followup.dispatched may have started a new poll
- const isStale = pollTaskIdRef.current !== taskId;
-
- pollFailures.current = 0;
- setConnectionLost(false);
-
- if (tmsgs.length > 0 && !isStale) {
- setTaskMessages((prev) => {
- const existingSeqs = new Set(prev.map((m) => m.seq));
- const unique = tmsgs.filter((m) => !existingSeqs.has(m.seq));
- return unique.length > 0 ? [...prev, ...unique] : prev;
- });
- lastSeqRef.current = Math.max(
- ...tmsgs.map((m) => m.seq),
- lastSeqRef.current,
- );
- }
-
- if (
- task.status === "completed" ||
- task.status === "failed" ||
- task.status === "cancelled" ||
- task.status === "superseded"
- ) {
- if (isStale) {
- // Stale poll — still merge messages but don't touch activeTask or polling
- listMessages(conversationId, workspaceId)
- .then(({ messages: latest }) => {
- setMessages((prev) => mergeMessages(prev, latest));
- mergeCachedMessages(
- conversationId,
- latest,
- null,
- workspaceId,
- ).catch(() => {});
- })
- .catch(() => {});
- return;
- }
-
- if (pollRef.current) clearInterval(pollRef.current);
- pollRef.current = null;
-
- if (markReadTimerRef.current)
- clearTimeout(markReadTimerRef.current);
- markReadTimerRef.current = setTimeout(() => {
- markInboxRead(conversationId, workspaceId)
- .then(() => refreshInboxCountRef.current())
- .catch(() => {});
- }, 1000);
-
- const shouldScroll =
- !scrollTargetActiveRef.current && isNearBottom.current;
- try {
- const [latestResult, arts] = await Promise.all([
- listMessages(conversationId, workspaceId),
- listArtifacts(conversationId, workspaceId).catch(() => null),
- ]);
- setMessages((prev) => mergeMessages(prev, latestResult.messages));
- mergeCachedMessages(
- conversationId,
- latestResult.messages,
- null,
- workspaceId,
- ).catch(() => {});
- if (arts) setArtifacts(arts);
- setActiveTask(task);
- } catch {
- setActiveTask(task);
- toast.error("Failed to refresh messages");
- }
- if (shouldScroll) {
- requestAnimationFrame(() => {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- behavior: "smooth",
- });
- });
- }
-
- // Fallback: if a follow-up was dispatched but the WebSocket
- // message was lost, detect the new active task via API.
- // Also syncs buffered messages to catch orphans from race conditions.
- setTimeout(async () => {
- if (pollRef.current) return;
- try {
- const [nextTask, latestBuffered] = await Promise.all([
- getActiveTask(conversationId, workspaceId),
- listBufferedMessages(conversationId, workspaceId),
- ]);
- setBufferedMessages(latestBuffered);
- if (nextTask && nextTask.id !== taskId) {
- const { messages: latestMsgs } = await listMessages(
- conversationId,
- workspaceId,
- );
- setMessages((prev) => mergeMessages(prev, latestMsgs));
- mergeCachedMessages(
- conversationId,
- latestMsgs,
- null,
- workspaceId,
- ).catch(() => {});
- setActiveTask(nextTask);
- setTaskMessages([]);
- startPollingRef.current?.(nextTask.id, conversationId);
- }
- } catch {}
- }, 1000);
- } else if (!isStale) {
- setActiveTask(task);
- }
- } catch {
- if (pollTaskIdRef.current !== taskId) return;
- pollFailures.current += 1;
- if (pollFailures.current >= 3) {
- setConnectionLost(true);
- }
- if (pollFailures.current >= 10) {
- if (pollRef.current) clearInterval(pollRef.current);
- pollRef.current = null;
- toast.error("Lost connection to agent");
- }
- }
- }, 3000);
- },
- [workspaceId],
- );
- useEffect(() => {
- startPollingRef.current = startPolling;
- }, [startPolling]);
-
- useEffect(() => {
- return () => {
- if (pollRef.current) clearInterval(pollRef.current);
- if (markReadTimerRef.current) clearTimeout(markReadTimerRef.current);
- };
- }, []);
-
- const activeTaskIdRef = useRef<string | null>(null);
- useEffect(() => {
- activeTaskIdRef.current = activeTask?.id ?? null;
- }, [activeTask]);
-
- useEffect(() => {
- return subscribeWs((msg: WsMessage) => {
- if (
- msg.type === "task.messages" &&
- msg.taskId === activeTaskIdRef.current
- ) {
- const incoming = msg.messages.filter((m) => m.seq > lastSeqRef.current);
- if (incoming.length > 0) {
- setTaskMessages((prev) => {
- const existingSeqs = new Set(prev.map((m) => m.seq));
- const unique = incoming.filter((m) => !existingSeqs.has(m.seq));
- return unique.length > 0 ? [...prev, ...unique] : prev;
- });
- lastSeqRef.current = Math.max(
- ...incoming.map((m) => m.seq),
- lastSeqRef.current,
- );
- }
- }
- if (
- msg.type === "task.created" &&
- msg.conversationId === conversation?.id
- ) {
- listMessages(msg.conversationId, workspaceId)
- .then(({ messages: latest }) => {
- setMessages((prev) => mergeMessages(prev, latest));
- mergeCachedMessages(
- msg.conversationId,
- latest,
- null,
- workspaceId,
- ).catch(() => {});
- })
- .catch(() => {});
- const task = msg.task as Task;
- activeTaskIdRef.current = task.id;
- setActiveTask(task);
- setTaskMessages([]);
- lastSeqRef.current = 0;
- startPollingRef.current?.(task.id, msg.conversationId);
- }
- // Refresh the per-channel `last_open` pointer when a `task.created`
- // arrives — this is the client learning of a (possibly newer) conversation
- // for this agent+channel in real time, keeping the pointer's
- // "latest-created" semantics fresh while the user is on the page. Runs
- // independently of the active-conversation block above: a new thread spawned
- // in this channel often has a different conversationId than the one being
- // viewed, so it must NOT be gated on `msg.conversationId === conversation?.id`.
- // `activeChannelRef` is read (not `activeChannel`) because this effect does
- // not re-subscribe on channel change — the ref always holds the current value.
- if (msg.type === "task.created") {
- const task = msg.task as Task;
- const activeChannel = activeChannelRef.current;
- getLastOpenConversation(agentId, activeChannel, workspaceId)
- .then((current) => {
- const targetConvId = pointerRefreshTargetForTaskCreated({
- task,
- agentId,
- activeChannel,
- currentPointerConvId: current?.conversation_id ?? null,
- });
- if (!targetConvId) return;
- // A1: derive serverMessageCount from the locally-cached count for
- // this conversation. May under-count (e.g. brand-new thread with no
- // cache → 0), which only makes the next slow-path read fall back to
- // the skeleton (the `serverMessageCount > 0` gate) — never wrong
- // content. We never over-count, so the pointer can't claim a
- // conversation is more complete than it is.
- return getCacheMeta(targetConvId, workspaceId).then((meta) =>
- setLastOpenConversation(
- agentId,
- activeChannel,
- {
- conversation_id: targetConvId,
- newestMessageId: meta?.newestMessageId ?? null,
- serverMessageCount: meta?.messageCount ?? 0,
- },
- workspaceId,
- ),
- );
- })
- .catch(() => {});
- }
- if (msg.type === "conversation.message") {
- // Only cache for the server-confirmed loaded conversation — never write
- // during the optimistic cache-first window before the id is confirmed
- // (review #1).
- if (msg.conversationId === loadConvIdRef.current) {
- appendCachedMessage(
- msg.conversationId,
- msg.message,
- workspaceId,
- ).catch(() => {});
- }
- if (msg.conversationId === conversation?.id) {
- setMessages((prev) => {
- const incomingTime = new Date(msg.message.created_at).getTime();
- const optimisticIdx = prev.findIndex(
- (m) =>
- m.id.startsWith("temp-") &&
- m.role === msg.message.role &&
- m.content === msg.message.content &&
- Math.abs(new Date(m.created_at).getTime() - incomingTime) <
- 2000,
- );
- if (optimisticIdx !== -1) {
- const updated = [...prev];
- updated[optimisticIdx] = msg.message;
- return updated;
- }
- return mergeMessages(prev, [msg.message]);
- });
- }
- }
- if (
- msg.type === "task.updated" &&
- msg.taskId === activeTaskIdRef.current
- ) {
- setActiveTask((prev) =>
- prev ? { ...prev, status: msg.status } : prev,
- );
- }
- if (
- msg.type === "artifact.uploaded" &&
- msg.conversationId === conversation?.id
- ) {
- setArtifacts((prev) => {
- if (prev.some((a) => a.id === msg.artifact.id)) return prev;
- return [...prev, msg.artifact];
- });
- }
- if (
- msg.type === "followup.dispatched" &&
- msg.conversationId === conversation?.id
- ) {
- // Optimistically remove by real ID
- setBufferedMessages((prev) =>
- prev.filter((m) => m.id !== msg.message.id),
- );
- // Always sync from server to handle temp-ID / duplicate edge cases
- listBufferedMessages(msg.conversationId, workspaceId)
- .then(setBufferedMessages)
- .catch(() => {});
- listMessages(msg.conversationId, workspaceId)
- .then(({ messages: latest }) => {
- setMessages((prev) => mergeMessages(prev, latest));
- mergeCachedMessages(
- msg.conversationId,
- latest,
- null,
- workspaceId,
- ).catch(() => {});
- })
- .catch(() => {});
- const task = msg.task as Task;
- activeTaskIdRef.current = task.id;
- setActiveTask(task);
- setTaskMessages([]);
- startPollingRef.current?.(task.id, msg.conversationId);
- }
- if (
- msg.type === "followup.created" &&
- msg.conversationId === conversation?.id
- ) {
- setBufferedMessages((prev) => addBufferedIfNew(prev, msg.message));
- }
- if (
- msg.type === "followup.deleted" &&
- msg.conversationId === conversation?.id
- ) {
- setBufferedMessages((prev) =>
- prev.filter((m) => m.id !== msg.messageId),
- );
- }
- if (
- msg.type === "followup.dispatch_failed" &&
- msg.conversationId === conversation?.id
- ) {
- toast.error(msg.error || "Failed to dispatch follow-up");
- }
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps -- activeChannelRef is a stable ref read inside the callback, not a reactive dep
- }, [subscribeWs, conversation?.id, workspaceId, agentId]);
-
- useEffect(() => {
- return subscribeReconnect(() => {
- if (!conversation?.id) return;
- getCacheMeta(conversation.id, workspaceId).then((meta) => {
- conversationInit(conversation.id, workspaceId, {
- newestMessageId: meta?.newestMessageId ?? undefined,
- messageCount: meta?.serverMessageCount ?? undefined,
- })
- .then((data) => {
- if (!data.cache_valid && data.messages) {
- setMessages((prev) => mergeMessages(prev, data.messages!));
- writeToCacheRef
- .current(
- data.messages,
- data.has_more_messages,
- data.message_count,
- )
- .catch(() => {});
- }
- })
- .catch(() => {});
- });
- });
- }, [subscribeReconnect, conversation?.id, workspaceId]);
-
- // Validate (10 MB cap) + stage files. Shared by the file picker, drag/drop,
- // and the composer's paste/drop handlers.
- const addPendingFiles = useCallback((files: File[]) => {
- const valid: File[] = [];
- for (const file of files) {
- if (file.size > MAX_FILE_SIZE) {
- toast.error(`"${file.name}" exceeds 10 MB limit`);
- } else {
- valid.push(file);
- }
- }
- if (valid.length > 0) {
- setPendingFiles((prev) => [...prev, ...valid]);
- }
- }, []);
-
- const handleFileSelect = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- const fileList = e.target.files;
- if (!fileList) return;
- addPendingFiles(Array.from(fileList));
- // Reset input so re-selecting the same file works
- e.target.value = "";
- },
- [addPendingFiles],
- );
-
- const removePendingFile = useCallback((index: number) => {
- setPendingFiles((prev) => prev.filter((_, i) => i !== index));
- }, []);
-
- const handleTextSelect = useCallback(() => {
- const selection = window.getSelection();
- if (!selection || selection.isCollapsed || !selection.rangeCount) {
- setSelectionPopup(null);
- return;
- }
- const text = selection.toString().trim();
- if (!text) {
- setSelectionPopup(null);
- return;
- }
- // Only allow quoting from assistant message bubbles
- const range = selection.getRangeAt(0);
- const container =
- range.commonAncestorContainer instanceof HTMLElement
- ? range.commonAncestorContainer
- : range.commonAncestorContainer.parentElement;
- if (!container?.closest("[data-quote-source]")) {
- setSelectionPopup(null);
- return;
- }
- const rects = range.getClientRects();
- const lastRect = rects[rects.length - 1] || range.getBoundingClientRect();
- setSelectionPopup({ text, x: lastRect.right, y: lastRect.top - 4 });
- }, []);
-
- useEffect(() => {
- document.addEventListener("selectionchange", handleTextSelect);
- return () =>
- document.removeEventListener("selectionchange", handleTextSelect);
- }, [handleTextSelect]);
+ const { selectionPopup, setSelectionPopup } = useTextSelectionQuote();
const handleQuoteSelection = useCallback(() => {
if (selectionPopup) {
@@ -2159,311 +448,6 @@ export function AgentChatView({
}
}, [selectionPopup]);
- const [dragging, setDragging] = useState(false);
- const dragCounter = useRef(0);
-
- const handleDragEnter = useCallback((e: React.DragEvent) => {
- e.preventDefault();
- e.stopPropagation();
- dragCounter.current++;
- if (e.dataTransfer.types.includes("Files")) {
- setDragging(true);
- }
- }, []);
-
- const handleDragLeave = useCallback((e: React.DragEvent) => {
- e.preventDefault();
- e.stopPropagation();
- dragCounter.current--;
- if (dragCounter.current === 0) {
- setDragging(false);
- }
- }, []);
-
- const handleDragOver = useCallback((e: React.DragEvent) => {
- e.preventDefault();
- e.stopPropagation();
- }, []);
-
- const handleDrop = useCallback(
- (e: React.DragEvent) => {
- e.preventDefault();
- e.stopPropagation();
- setDragging(false);
- dragCounter.current = 0;
- addPendingFiles(Array.from(e.dataTransfer.files));
- },
- [addPendingFiles],
- );
-
- const handleStop = async () => {
- if (!conversation || cancelling) return;
- setCancelling(true);
- try {
- const cancelled = await cancelActiveTask(conversation.id, workspaceId);
- if (cancelled) {
- // If WS followup.dispatched already set a new active task, don't overwrite
- if (
- activeTaskIdRef.current &&
- activeTaskIdRef.current !== cancelled.id
- ) {
- return;
- }
- if (pollRef.current) clearInterval(pollRef.current);
- pollRef.current = null;
- const [latestResult, latestBuffered] = await Promise.all([
- listMessages(conversation.id, workspaceId),
- listBufferedMessages(conversation.id, workspaceId),
- ]);
- setMessages((prev) => mergeMessages(prev, latestResult.messages));
- mergeCachedMessages(
- conversation.id,
- latestResult.messages,
- null,
- workspaceId,
- ).catch(() => {});
- setBufferedMessages(latestBuffered);
- setActiveTask(cancelled as Task);
- setTaskMessages([]);
- }
- } catch {
- toast.error("Failed to cancel task");
- } finally {
- setCancelling(false);
- }
- };
-
- const handleSend = async () => {
- const rawContent = input.trim();
- if ((!rawContent && pendingFiles.length === 0) || sending || !conversation)
- return;
- if (!rawContent) {
- toast.error("Please type a message");
- return;
- }
-
- // Prepend quoted text as blockquote if present
- let content = quotedText
- ? `> ${quotedText.split("\n").join("\n> ")}\n\n${rawContent}`
- : rawContent;
-
- // Prepend skill instruction if active
- if (slashCommand.activeSkill) {
- content = `/${slashCommand.activeSkill.name} ${content}`;
- }
-
- const filesToSend = [...pendingFiles];
- setInput("");
- setPendingFiles([]);
- setQuotedText(null);
- slashCommand.clearActiveSkill();
- setSending(true);
-
- const taskActive =
- !!activeTask &&
- !["completed", "failed", "cancelled", "superseded"].includes(
- activeTask.status,
- );
-
- if (taskActive) {
- // Buffer mode: queue message for later dispatch
- const optimisticId = `temp-${Date.now()}`;
- const optimistic: Message = {
- id: optimisticId,
- conversation_id: conversation.id,
- role: "user",
- content,
- task_id: null,
- attachment_ids: null,
- status: "buffered",
- created_at: new Date().toISOString(),
- };
- setBufferedMessages((prev) => [...prev, optimistic]);
-
- try {
- const { message } = await createBufferedMessage(
- conversation.id,
- content,
- workspaceId,
- filesToSend.length > 0 ? filesToSend : undefined,
- );
- setBufferedMessages((prev) =>
- replaceOptimisticBuffered(prev, optimisticId, message),
- );
- } catch (err) {
- setBufferedMessages((prev) =>
- prev.filter((m) => m.id !== optimisticId),
- );
- setInput(content);
- setPendingFiles(filesToSend);
- toast.error(
- err instanceof Error ? err.message : "Failed to queue follow-up",
- );
- } finally {
- setSending(false);
- }
- return;
- }
-
- // Normal mode: send message and enqueue task
- const optimisticId = `temp-${Date.now()}`;
- const optimistic: Message = {
- id: optimisticId,
- conversation_id: conversation.id,
- role: "user",
- content,
- task_id: null,
- attachment_ids: null,
- created_at: new Date().toISOString(),
- };
-
- // Store pending files for the optimistic message rendering
- if (filesToSend.length > 0) {
- setPendingFilesByMessage((prev) => {
- const next = new Map(prev);
- next.set(optimisticId, filesToSend);
- return next;
- });
- }
-
- setMessages((prev) => [...prev, optimistic]);
- scrollToBottom();
-
- try {
- const { message, task } = await sendMessage(
- conversation.id,
- content,
- workspaceId,
- filesToSend.length > 0 ? filesToSend : undefined,
- );
- // Clean up pending files ref
- setPendingFilesByMessage((prev) => {
- if (!prev.has(optimisticId)) return prev;
- const next = new Map(prev);
- next.delete(optimisticId);
- return next;
- });
- setMessages((prev) => {
- const hasOptimistic = prev.some((m) => m.id === optimistic.id);
- if (!hasOptimistic) {
- const hasReal = prev.some((m) => m.id === message.id);
- return hasReal ? prev : sortMessages([...prev, message]);
- }
- const without = prev.filter(
- (m) => m.id !== optimistic.id && m.id !== message.id,
- );
- return sortMessages([...without, message]);
- });
- appendCachedMessage(conversation.id, message, workspaceId).catch(
- () => {},
- );
- if (message.attachment_ids && message.attachment_ids.length > 0) {
- listArtifacts(conversation.id, workspaceId)
- .then((arts) => setArtifacts(arts))
- .catch(() => {});
- }
- setActiveTask(task);
- setTaskMessages([]);
- startPolling(task.id, conversation.id);
- } catch (err) {
- setPendingFilesByMessage((prev) => {
- if (!prev.has(optimisticId)) return prev;
- const next = new Map(prev);
- next.delete(optimisticId);
- return next;
- });
- setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
- setInput(content);
- setPendingFiles(filesToSend);
- toast.error(
- err instanceof Error ? err.message : "Failed to send message",
- );
- } finally {
- setSending(false);
- composerRef.current?.focus();
- }
- };
-
- const handleRetryTask = useCallback(async () => {
- if (!activeTask || !conversation) return;
- const newTask = await retryTask(activeTask.id, workspaceId);
- setActiveTask(newTask);
- setTaskMessages([]);
- startPolling(newTask.id, conversation.id);
- }, [activeTask, conversation, workspaceId, startPolling]);
-
- const handleToggleFlag = useCallback(
- async (messageId: string) => {
- const wasFlagged = flaggedIdsRef.current.has(messageId);
- setFlaggedIds((prev) => {
- const next = new Set(prev);
- if (wasFlagged) next.delete(messageId);
- else next.add(messageId);
- return next;
- });
- if (wasFlagged) {
- flagDecrement();
- apiUnflagMessage(workspaceId, messageId)
- .then(() => {
- flagRefresh();
- })
- .catch(() => {
- setFlaggedIds((prev) => new Set(prev).add(messageId));
- flagIncrement();
- });
- } else {
- flagIncrement();
- apiFlagMessage(workspaceId, messageId)
- .then(() => {
- flagRefresh();
- })
- .catch(() => {
- setFlaggedIds((prev) => {
- const next = new Set(prev);
- next.delete(messageId);
- return next;
- });
- flagDecrement();
- });
- }
- },
- [workspaceId, flagIncrement, flagDecrement, flagRefresh],
- );
-
- const openIssue = useCallback(
- async (issueId: string) => {
- setSelectedIssueId(issueId);
- setIssueSheetOpen(true);
- setIssueDetailLoading(true);
- setIssueTraceTasks(null);
- setIssueActiveTask(null);
- try {
- const res = await getIssue(workspaceId, issueId);
- setIssueDetail(res);
- if (res.issue.latest_task_id) {
- getTask(res.issue.latest_task_id, workspaceId)
- .then((task) => setIssueActiveTask(task))
- .catch(() => setIssueActiveTask(null));
- }
- if (res.issue.trace_id) {
- getTrace(res.issue.trace_id, workspaceId)
- .then((t) => setIssueTraceTasks(t.tasks))
- .catch(() => setIssueTraceTasks(null));
- }
- } catch (err) {
- toast.error(
- err instanceof Error ? err.message : "Failed to load issue",
- );
- setIssueSheetOpen(false);
- } finally {
- setIssueDetailLoading(false);
- }
- },
- [workspaceId],
- );
-
- const issueConvId = issueDetail?.issue?.conversation_id ?? null;
- const issueTaskId = issueDetail?.issue?.latest_task_id ?? null;
useEffect(() => {
if (!issueSheetOpen || !selectedIssueId) return;
@@ -2476,7 +460,7 @@ export function AgentChatView({
) {
getTask(issueTaskId, workspaceId)
.then((task) => setIssueActiveTask(task))
- .catch(() => {});
+ .catch(() => { });
}
if (
msg.type === "conversation.message" &&
@@ -2497,12 +481,12 @@ export function AgentChatView({
setIssueDetail((prev) =>
prev
? {
- ...prev,
- issue: {
- ...prev.issue,
- status: match[1] as Issue["status"],
- },
- }
+ ...prev,
+ issue: {
+ ...prev.issue,
+ status: match[1] as Issue["status"],
+ },
+ }
: prev,
);
}
@@ -2525,103 +509,66 @@ export function AgentChatView({
subscribeWs,
]);
- const [napping, setNapping] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
- const currentConvHasMessages = useMemo(
- () =>
- !!conversation &&
- messages.some((m) => m.conversation_id === conversation.id),
- [conversation, messages],
- );
-
- const handleNap = async () => {
- if (!conversation || !currentConvHasMessages || napping) return;
- setNapping(true);
- try {
- if (pollRef.current) {
- clearInterval(pollRef.current);
- pollRef.current = null;
- }
- const newConv = await createConversation(
- agentId,
- workspaceId,
- activeChannel,
- );
-
- setNapMarkers((prev) => [
- ...prev,
- {
- agentName,
- created_at: newConv.created_at,
- id: `nap-${conversation.id}`,
- },
- ]);
-
- setPreviousConversations((prev) => [
- { id: conversation.id, created_at: conversation.created_at },
- ...prev,
- ]);
-
- setConversation(newConv);
- setActiveTask(null);
- setTaskMessages([]);
- setArtifacts([]);
- setBufferedMessages([]);
- setPendingFiles([]);
- setPendingFilesByMessage(new Map());
- lastSeqRef.current = 0;
- setConnectionLost(false);
- setHasMore(false);
- oldestConversationCursorRef.current = null;
-
- scrollToBottom();
- } catch {
- toast.error("Failed to start new conversation");
- } finally {
- setNapping(false);
- }
- };
-
const isTaskActive =
!!activeTask &&
!["completed", "failed", "cancelled", "superseded"].includes(
activeTask.status,
);
+ // Rotating capability-hint placeholder for the idle, empty composer. Freezes
+ // on focus/typing, resumes on empty blur; never rotates while a task is
+ // active (that path shows the static "Message {Name}" overlay below instead).
+ const rotatingPlaceholder = useRotatingPlaceholder({
+ isEmpty: input.trim() === "",
+ isFocused: composerFocused,
+ isTaskActive,
+ });
+
if (messagesLoading) {
return (
<>
<div className="flex-1 overflow-y-auto px-3 md:px-5">
- <div className="mx-auto max-w-2xl py-6 space-y-4">
- {/* Skeleton user message */}
- <div className="flex justify-end">
- <Skeleton className="h-10 w-48 rounded-lg" />
- </div>
- {/* Skeleton assistant message */}
- <div className="flex justify-start">
- <div className="space-y-2 px-1 py-1">
- <Skeleton className="h-4 w-72" />
- <Skeleton className="h-4 w-56" />
- <Skeleton className="h-4 w-64" />
+ <div className="mx-auto max-w-3xl py-6 space-y-4 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">
+ <Skeleton className="size-[30px] shrink-0 rounded-md" />
+ <div className="flex flex-col items-start gap-1 max-w-[86%]">
+ <Skeleton className="h-3 w-20 rounded mb-0.5" />
+ <Skeleton className="h-9 w-64 rounded-[1.05rem]" />
+ <Skeleton className="h-9 w-48 rounded-[1.05rem]" />
</div>
</div>
- {/* Another pair */}
- <div className="flex justify-end">
- <Skeleton className="h-10 w-36 rounded-lg" />
+ {/* User cluster — right pills, no avatar/name */}
+ <div className="flex flex-col items-end gap-1">
+ <Skeleton className="h-9 w-44 rounded-[1.05rem]" />
+ <Skeleton className="h-9 w-32 rounded-[1.05rem]" />
</div>
- <div className="flex justify-start">
- <div className="space-y-2 px-1 py-1">
- <Skeleton className="h-4 w-64" />
- <Skeleton className="h-4 w-48" />
+ {/* Another agent cluster */}
+ <div className="flex justify-start items-start gap-2">
+ <Skeleton className="size-[30px] shrink-0 rounded-md" />
+ <div className="flex flex-col items-start gap-1 max-w-[86%]">
+ <Skeleton className="h-3 w-20 rounded mb-0.5" />
+ <Skeleton className="h-9 w-56 rounded-[1.05rem]" />
</div>
</div>
</div>
</div>
- {/* Skeleton input area — mirrors the real rounded pill */}
- <div className="px-3 md:px-5 pt-3 pb-5 md:pb-6">
- <div className="mx-auto max-w-2xl">
- <Skeleton className="h-12 w-full rounded-3xl" />
+ {/* Presence line + input — mirror the real layout exactly so nothing
+ shifts on load: presence row (h-5 + mb-2) above, then the composer
+ row of [overflow button][pill][symmetric spacer]. */}
+ <div className="relative z-10 px-3 md:px-5 pt-3 pb-5 md:pb-6">
+ <div className="mx-auto max-w-3xl">
+ <div className="h-5 px-1 mb-2 flex items-center">
+ <Skeleton className="h-3.5 w-28 rounded" />
+ </div>
+ <div className="flex items-center gap-2">
+ <Skeleton className="size-8 shrink-0 rounded-full" />
+ <Skeleton className="h-10 flex-1 rounded-3xl" />
+ <Skeleton className="size-8 shrink-0 rounded-full" />
+ </div>
</div>
</div>
</>
@@ -2668,7 +615,7 @@ export function AgentChatView({
if (btn) toast.success("Copied to clipboard");
}}
>
- <div className="mx-auto max-w-2xl pt-6 pb-15 min-w-0">
+ <div className="mx-auto max-w-3xl pt-6 pb-15 min-w-0">
{conversation && canLoadMore && !loadingMore && (
<div className="flex justify-center py-2">
<button
@@ -2692,7 +639,7 @@ export function AgentChatView({
const isNewAgent =
agent?.created_at &&
renderNow - new Date(agent.created_at).getTime() <
- 5 * 60 * 1000;
+ 5 * 60 * 1000;
const hasEmailTask = (activeTaskCounts[agentId] ?? 0) > 0;
if (isNewAgent && hasEmailTask && activeChannel === "default") {
@@ -2718,8 +665,8 @@ export function AgentChatView({
}
return (
- <p className="text-center text-muted-foreground py-20 text-sm">
- Send a message to start chatting with the agent.
+ <p className="text-center text-muted-foreground py-20 text-base animate-[fade-up_400ms_ease-out_both]">
+ Say hi to {agentFirstName}.
</p>
);
})()}
@@ -2728,7 +675,9 @@ export function AgentChatView({
const pos = groupPositions[idx];
const isGroupStart =
pos === "first" || pos === "solo" || pos === null;
- const spacing = idx === 0 ? "" : isGroupStart ? "mt-4" : "mt-0.5";
+ // 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";
if (item.kind === "nap") {
return (
@@ -2739,14 +688,28 @@ export function AgentChatView({
}
if (item.kind === "artifact") {
+ // A file card is part of the agent's cluster (computeGroupPositions
+ // groups it with adjacent agent items). It shows the avatar + name
+ // only when it's the cluster HEAD (first/solo) — e.g. a file
+ // uploaded mid-task before any reply exists; otherwise a spacer, so
+ // it never renders as an orphaned, avatar-less "empty file" state.
+ const artifactPos = pos ?? "solo";
+ const isHead = artifactPos === "first" || artifactPos === "solo";
return (
<div key={`artifact-${item.data.id}`} className={spacing}>
- <ArtifactCard
- artifact={item.data}
- version={versionMap.get(item.data.id) ?? 1}
- hasDuplicates={duplicateFilenames.has(item.data.filename)}
- onClick={handleArtifactClick}
- />
+ <AgentRow
+ groupPosition={artifactPos}
+ agentName={agentName}
+ config={agentAvatarConfig}
+ forceSpacer={!isHead}
+ >
+ <ArtifactCard
+ artifact={item.data}
+ version={versionMap.get(item.data.id) ?? 1}
+ hasDuplicates={duplicateFilenames.has(item.data.filename)}
+ onClick={handleArtifactClick}
+ />
+ </AgentRow>
</div>
);
}
@@ -2759,17 +722,9 @@ export function AgentChatView({
agents={agents}
artifacts={artifacts}
activeTask={activeTask}
+ activeTaskStreamMsgId={activeTaskStreamMsgId}
taskMessages={taskMessages}
connectionLost={connectionLost}
- isLastMessage={
- messages.length > 0 &&
- messages[messages.length - 1].id === msg.id
- }
- thinkingCount={
- msg.task_id ? (thinkingCounts[msg.task_id] ?? 0) : 0
- }
- targetConvId={targetConvId}
- workspaceId={workspaceId}
conversationType={conversation?.type}
pendingFilesByMessage={pendingFilesByMessage}
onArtifactClick={handleArtifactClick}
@@ -2790,14 +745,22 @@ export function AgentChatView({
}
groupPosition={pos ?? "solo"}
provider={runtimeProvider}
+ agentName={agentName}
+ agentAvatarConfig={agentAvatarConfig}
+ isSendFailed={failedSends.has(msg.id)}
+ onRetrySend={handleRetrySend}
/>
</div>
);
})}
- {/* Show trace while task is in progress (no assistant message yet) */}
+ {/* Show trace while task is in progress (no assistant message yet).
+ Once a send-dm reply exists, the designated last message
+ (activeTaskStreamMsgId) owns the error surface — suppress this
+ standalone block then, so an error never renders twice (QA AC4). */}
{activeTask &&
activeTask.conversation_id === conversation?.id &&
+ activeTaskStreamMsgId == null &&
!["completed", "failed", "cancelled", "superseded"].includes(
activeTask.status,
) && (
@@ -2815,28 +778,17 @@ export function AgentChatView({
<ScrollToBottomButton scrollRef={scrollRef} />
</div>
- {/* Follow-up buffer indicator */}
- {conversation && (
- <FollowUpBuffer
- bufferedMessages={bufferedMessages}
- onDelete={(messageId) => {
- const prev = bufferedMessages;
- setBufferedMessages((cur) => cur.filter((m) => m.id !== messageId));
- deleteBufferedMessage(
- conversation.id,
- messageId,
- workspaceId,
- ).catch(() => {
- setBufferedMessages(prev);
- toast.error("Failed to delete follow-up");
- });
- }}
- />
- )}
-
{/* Input */}
- <div data-keyboard-offset className="relative z-10 px-3 md:px-5 pt-3 pb-[max(1.25rem,env(safe-area-inset-bottom))] md:pb-6">
- <div className="mx-auto max-w-2xl relative">
+ <div className="relative z-10 px-3 md:px-5 pt-3 pb-5 md:pb-6">
+ <div className="mx-auto max-w-3xl relative">
+ {/* Social presence line — "{Name} is typing…" while this conversation
+ has a live task (dispatched / queued / running), else nothing. */}
+ {conversation && (
+ <PresenceLine
+ agentFirstName={agentFirstName}
+ taskStatus={isTaskActive ? activeTask?.status : null}
+ />
+ )}
<div className="flex items-end gap-2">
{/* Overflow menu */}
{!targetConvId && (
@@ -2893,7 +845,7 @@ export function AgentChatView({
{isTaskActive
? "Wait for the task to finish"
: currentConvHasMessages
- ? "Take a nap"
+ ? "Take a nap and reset the current session"
: `${agentName} is well-rested and ready to go`}
</TooltipContent>
</Tooltip>
@@ -2907,7 +859,7 @@ export function AgentChatView({
"relative flex-1 min-w-0 flex flex-col rounded-3xl border border-border/50 bg-background/90 transition-[border-radius] duration-200",
"focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",
(isMultiLine || quotedText || slashCommand.activeSkill) &&
- "rounded-2xl",
+ "rounded-2xl",
sending && "opacity-50",
dragging && "border-ring ring-3 ring-ring/50",
)}
@@ -3024,8 +976,29 @@ export function AgentChatView({
setCaretIndex(caret);
}}
onSend={handleSend}
- placeholder={
- isTaskActive ? "Type a follow-up..." : "Type a task..."
+ onFocus={() => setComposerFocused(true)}
+ onBlur={() => setComposerFocused(false)}
+ // The overlay is the SOLE placeholder renderer (TipTap's own
+ // placeholder stays "" — it can't reactively update post-init,
+ // which is what caused the active↔idle double-image). Shown
+ // whenever the field is empty, in both states:
+ // • active task → static "Message {Name}" (no rotation). Warm,
+ // no period (Priya); reads the same whether or not a task runs.
+ // • idle → the rotating capability hint.
+ overlay={
+ input.trim() === "" ? (
+ isTaskActive ? (
+ <RotatingPlaceholderOverlay
+ hint={`Message ${agentFirstName}`}
+ animate={false}
+ />
+ ) : (
+ <RotatingPlaceholderOverlay
+ hint={rotatingPlaceholder.hint}
+ animate={rotatingPlaceholder.isRotating}
+ />
+ )
+ ) : undefined
}
disabled={sending}
onMultiLineChange={setIsMultiLine}
@@ -3055,51 +1028,31 @@ export function AgentChatView({
</TooltipTrigger>
<TooltipContent side="top">Attach files</TooltipContent>
</Tooltip>
- {/* Send / Stop button — fixed bottom-right */}
- {isTaskActive && !input.trim() && !sending ? (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="icon-sm"
- onClick={handleStop}
- disabled={cancelling}
- className="absolute right-2 bottom-2 size-8 rounded-full bg-red-500/10 text-red-500 hover:bg-red-500/20 transition-colors duration-200"
- />
- }
- >
- {cancelling ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <Square className="size-3.5 fill-current" />
- )}
- </TooltipTrigger>
- <TooltipContent side="top">Stop task</TooltipContent>
- </Tooltip>
- ) : (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="icon-sm"
- onClick={handleSend}
- disabled={!input.trim() || sending}
- className={cn(
- "absolute right-2 bottom-2 size-8 rounded-full bg-primary text-primary-foreground transition-opacity duration-200",
- !input.trim() && "opacity-30",
- )}
- />
- }
- >
- {sending ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <ArrowUp className="size-3.5" />
- )}
- </TooltipTrigger>
- <TooltipContent side="top">Send</TooltipContent>
- </Tooltip>
- )}
+ {/* Send button — fixed bottom-right. Always Send; never a
+ Stop/pause affordance (task-lifecycle chrome is gone). The
+ spinner is only the sub-second in-flight double-submit guard. */}
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="icon-sm"
+ onClick={handleSend}
+ disabled={!input.trim() || sending}
+ className={cn(
+ "absolute right-2 bottom-2 size-8 rounded-full bg-primary text-primary-foreground transition-opacity duration-200",
+ !input.trim() && "opacity-30",
+ )}
+ />
+ }
+ >
+ {sending ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <ArrowUp className="size-3.5" />
+ )}
+ </TooltipTrigger>
+ <TooltipContent side="top">Send</TooltipContent>
+ </Tooltip>
</div>
</div>
{/* Symmetric spacer: balances the leading overflow button so the
@@ -3164,11 +1117,11 @@ export function AgentChatView({
detail={
issueDetail
? {
- messages: issueDetail.messages,
- comments: issueDetail.comments,
- artifacts: issueDetail.artifacts,
- traceId: issueDetail.issue.trace_id,
- }
+ messages: issueDetail.messages,
+ comments: issueDetail.comments,
+ artifacts: issueDetail.artifacts,
+ traceId: issueDetail.issue.trace_id,
+ }
: null
}
detailLoading={issueDetailLoading}
@@ -3182,13 +1135,13 @@ export function AgentChatView({
setIssueDetail((prev) =>
prev && prev.issue.id === issueId
? {
- ...prev,
- issue: {
- ...prev.issue,
- ...patch,
- updated_at: updated.updated_at,
- },
- }
+ ...prev,
+ issue: {
+ ...prev.issue,
+ ...patch,
+ updated_at: updated.updated_at,
+ },
+ }
: prev,
);
} catch (err) {
@@ -3205,9 +1158,9 @@ export function AgentChatView({
setIssueDetail((prev) =>
prev && prev.issue.id === issueId
? {
- ...prev,
- issue: { ...prev.issue, status: status as Issue["status"] },
- }
+ ...prev,
+ issue: { ...prev.issue, status: status as Issue["status"] },
+ }
: prev,
);
} catch (err) {
diff --git a/src/web/src/components/agent-chat/chat-composer.tsx b/src/web/src/components/agent-chat/chat-composer.tsx
index c75b005fe..c6693dded 100644
--- a/src/web/src/components/agent-chat/chat-composer.tsx
+++ b/src/web/src/components/agent-chat/chat-composer.tsx
@@ -6,6 +6,7 @@ import {
useImperativeHandle,
useRef,
useState,
+ type ReactNode,
} from "react";
import { useKeyboardScroll } from "@/hooks/use-keyboard-scroll";
import { useEditor, EditorContent } from "@tiptap/react";
@@ -42,7 +43,19 @@ interface ChatComposerProps {
onEditorState: (plainText: string, caretIndex: number) => void;
/** Enter-to-send (only fires in a top-level paragraph, no popup open). */
onSend: () => void;
- placeholder?: string;
+ /** Editor gained focus (forwarded live via useEditor's onFocus — no re-mount). */
+ onFocus?: () => void;
+ /** Editor lost focus (forwarded live via useEditor's onBlur — no re-mount). */
+ onBlur?: () => void;
+ /**
+ * The placeholder, rendered as a decorative overlay over the empty editor.
+ * This is the SOLE placeholder renderer — TipTap's own Placeholder is kept
+ * permanently "" because its decoration is captured at plugin-init and does
+ * NOT re-read updated options in this @tiptap/extensions version (so it goes
+ * stale on the in-place active↔idle settle). The parent drives the text + fade
+ * for BOTH the idle rotating hint and the active static "Message {Name}".
+ */
+ overlay?: ReactNode;
disabled?: boolean;
/** Drives the rounded-3xl ↔ rounded-2xl pill switch. */
onMultiLineChange?: (multiline: boolean) => void;
@@ -134,6 +147,64 @@ function MentionList({ state }: { state: MentionPopupState }) {
);
}
+/** fade duration each way; total swap = 2× this. Matches the spec (200/200). */
+const PLACEHOLDER_FADE_MS = 200;
+
+/**
+ * Decorative overlay for the rotating capability-hint placeholder. Rendered as
+ * a sibling of <EditorContent> inside `.chat-composer` (which is `relative`),
+ * absolutely positioned at the editor's text origin so it overlaps the empty
+ * first paragraph exactly and adds zero layout height.
+ *
+ * Cross-fade: on `hint` change, fade the current text OUT (200ms), swap the
+ * text at zero opacity, then fade the new text IN — so the text never snaps
+ * mid-opacity (the flicker the overlay exists to avoid). With `animate=false`
+ * (reduced motion) the hint swaps instantly, no transition.
+ *
+ * aria-hidden: this is purely visual — the editor keeps its real accessible
+ * name and screen readers must NOT announce hint rotation.
+ */
+export function RotatingPlaceholderOverlay({
+ hint,
+ animate,
+}: {
+ hint: string;
+ /** false → reduced-motion: render the single hint with no fade. */
+ animate: boolean;
+}) {
+ // `shown` is the text currently painted; `visible` drives opacity. On a hint
+ // change we fade out, then swap `shown` + fade back in.
+ const [shown, setShown] = useState(hint);
+ const [visible, setVisible] = useState(true);
+
+ useEffect(() => {
+ if (!animate) {
+ // Reduced motion: no fade, just show the latest hint.
+ setShown(hint);
+ setVisible(true);
+ return;
+ }
+ if (hint === shown) return;
+ setVisible(false); // fade out
+ const id = setTimeout(() => {
+ setShown(hint); // swap at opacity 0
+ setVisible(true); // fade in
+ }, PLACEHOLDER_FADE_MS);
+ return () => clearTimeout(id);
+ }, [hint, shown, animate]);
+
+ return (
+ <div className="chat-placeholder-overlay" aria-hidden="true">
+ <span
+ className={animate ? "chat-placeholder-fade" : undefined}
+ style={animate ? { opacity: visible ? 1 : 0 } : undefined}
+ >
+ {shown}
+ </span>
+ </div>
+ );
+}
+
export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
function ChatComposer(
{
@@ -141,7 +212,9 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
onChange,
onEditorState,
onSend,
- placeholder,
+ onFocus,
+ onBlur,
+ overlay,
disabled,
onMultiLineChange,
onFiles,
@@ -168,6 +241,8 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
const onEditorStateRef = useRef(onEditorState);
const onChangeRef = useRef(onChange);
const onFilesRef = useRef(onFiles);
+ const onFocusRef = useRef(onFocus);
+ const onBlurRef = useRef(onBlur);
const slashIsOpenRef = useRef(slashIsOpen);
const onSlashKeyDownRef = useRef(onSlashKeyDown);
useEffect(() => { agentsRef.current = agents; }, [agents]);
@@ -177,6 +252,8 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
useEffect(() => { onEditorStateRef.current = onEditorState; }, [onEditorState]);
useEffect(() => { onChangeRef.current = onChange; }, [onChange]);
useEffect(() => { onFilesRef.current = onFiles; }, [onFiles]);
+ useEffect(() => { onFocusRef.current = onFocus; }, [onFocus]);
+ useEffect(() => { onBlurRef.current = onBlur; }, [onBlur]);
useEffect(() => { slashIsOpenRef.current = slashIsOpen; }, [slashIsOpen]);
useEffect(() => { onSlashKeyDownRef.current = onSlashKeyDown; }, [onSlashKeyDown]);
@@ -288,7 +365,12 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
listItem: false,
listKeymap: false,
}),
- Placeholder.configure({ placeholder: placeholder ?? "" }),
+ // TipTap's own placeholder is permanently empty: its decoration value is
+ // captured at plugin-init and does NOT re-read updated options in this
+ // @tiptap/extensions version, so a reactive value goes stale on the
+ // in-place active↔idle settle (the double-image). The `overlay` prop is
+ // the single source of truth for the placeholder instead — see below.
+ Placeholder.configure({ placeholder: "" }),
Markdown,
mentionExtension,
],
@@ -354,8 +436,8 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
},
handleDrop: () => false,
},
- onFocus: () => setEditorFocused(true),
- onBlur: () => setEditorFocused(false),
+ onFocus: () => { setEditorFocused(true); onFocusRef.current?.(); },
+ onBlur: () => { setEditorFocused(false); onBlurRef.current?.(); },
onUpdate: ({ editor }) => {
onChangeRef.current(decodeChatEntities(editor.getMarkdown()));
reportState(editor);
@@ -432,6 +514,12 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
editor={editor}
className="max-h-44 overflow-y-auto thin-scrollbar pr-2 text-base chat-input-line-height"
/>
+ {/* Decorative rotating-placeholder overlay. Renders over the empty
+ editor's text origin (mirrors the ::before float:left;height:0
+ position) so it adds zero layout height. aria-hidden — never
+ announced; the editor keeps its own accessible name. The parent
+ only mounts this while the field is empty + unfocused + idle. */}
+ {overlay}
<MentionList state={mentionPopup} />
</div>
);
diff --git a/src/web/src/components/agent-chat/chat-message-utils.ts b/src/web/src/components/agent-chat/chat-message-utils.ts
new file mode 100644
index 000000000..b7f98bb64
--- /dev/null
+++ b/src/web/src/components/agent-chat/chat-message-utils.ts
@@ -0,0 +1,273 @@
+import { useEffect, useRef } from "react";
+import type { Artifact, Message, TaskApi as Task } from "@alook/shared";
+
+type EventIconType = "issue" | "email" | "calendar";
+
+export function getEventIconType(
+ content: string,
+ conversationType?: string | null,
+): EventIconType {
+ if (conversationType === "issue_event") return "issue";
+ if (conversationType === "email_notification") return "email";
+ if (conversationType === "calendar_event") return "calendar";
+
+ const lower = content.toLowerCase();
+ if (lower.startsWith("issue ") || lower.startsWith("issue:")) return "issue";
+ if (lower.includes("email")) return "email";
+ return "calendar";
+}
+
+/**
+ * Classify a system-event message by its metadata resource id first (reliable,
+ * stamped at all creation sites), falling back to the content/conversationType
+ * heuristic only when no id is present. Drives both the card icon and label.
+ */
+export function eventTypeFromMessage(
+ metadata: Record<string, unknown> | null | undefined,
+ content: string,
+ conversationType?: string | null,
+): EventIconType {
+ if (metadata?.issueId) return "issue";
+ if (metadata?.emailId) return "email";
+ if (metadata?.calendarEventId) return "calendar";
+ return getEventIconType(content, conversationType);
+}
+
+/** Sort messages by (created_at, id) ascending — guarantees chronological order. */
+export function sortMessages(msgs: Message[]): Message[] {
+ return msgs.slice().sort((a, b) => {
+ const cmp = a.created_at.localeCompare(b.created_at);
+ if (cmp !== 0) return cmp;
+ return a.id.localeCompare(b.id);
+ });
+}
+
+/** Merge two message arrays by ID (latest wins), then sort chronologically. */
+export function mergeMessages(
+ existing: Message[],
+ incoming: Message[],
+): Message[] {
+ const merged = new Map<string, Message>();
+ for (const m of existing) merged.set(m.id, m);
+ for (const m of incoming) merged.set(m.id, m);
+ return sortMessages([...merged.values()]);
+}
+
+export type NapMarker = { agentName: string; created_at: string; id: string };
+
+type TimelineItem =
+ | { kind: "message"; data: Message }
+ | { kind: "artifact"; data: Artifact }
+ | { kind: "nap"; data: NapMarker };
+
+export type GroupPosition = "first" | "middle" | "last" | "solo";
+
+// Which conversational SIDE a timeline item belongs to. Items on the same side
+// that are adjacent (within the time threshold, no nap between) form one
+// Slack/Discord-style cluster sharing a single avatar + name header. The agent
+// side intentionally includes event cards (email/issue/calendar) and artifacts
+// (files), so a run like "card → reply → card → reply" reads as ONE Gwennie
+// cluster with one header — not four separate avatars.
+type GroupSide = "user" | "agent" | null;
+
+function groupSideOf(item: TimelineItem): GroupSide {
+ if (item.kind === "artifact") return "agent"; // files come from the agent
+ if (item.kind !== "message") return null; // nap markers break clusters
+ const role = item.data.role;
+ if (role === "user") return "user";
+ if (role === "assistant" || role === "event") return "agent";
+ return null;
+}
+
+function itemCreatedAt(item: TimelineItem): string | undefined {
+ return item.data.created_at;
+}
+
+export function computeGroupPositions(
+ timeline: TimelineItem[],
+): (GroupPosition | null)[] {
+ const positions: (GroupPosition | null)[] = new Array(timeline.length).fill(
+ null,
+ );
+ const GROUP_THRESHOLD_MS = 60_000;
+
+ const adjacentSameCluster = (a: TimelineItem | null, b: TimelineItem | null) => {
+ if (!a || !b) return false;
+ const sa = groupSideOf(a);
+ const sb = groupSideOf(b);
+ if (sa === null || sa !== sb) return false;
+ const ta = itemCreatedAt(a);
+ const tb = itemCreatedAt(b);
+ if (!ta || !tb) return true; // missing timestamp → don't split the cluster
+ return Math.abs(new Date(ta).getTime() - new Date(tb).getTime()) < GROUP_THRESHOLD_MS;
+ };
+
+ for (let i = 0; i < timeline.length; i++) {
+ const item = timeline[i];
+ if (groupSideOf(item) === null) continue; // nap → leave null
+
+ const prev = i > 0 ? timeline[i - 1] : null;
+ const next = i < timeline.length - 1 ? timeline[i + 1] : null;
+
+ const sameAsPrev = adjacentSameCluster(prev, item);
+ const sameAsNext = adjacentSameCluster(item, next);
+
+ if (sameAsPrev && sameAsNext) positions[i] = "middle";
+ else if (sameAsPrev && !sameAsNext) positions[i] = "last";
+ else if (!sameAsPrev && sameAsNext) positions[i] = "first";
+ else positions[i] = "solo";
+ }
+
+ return positions;
+}
+
+export function buildTimeline(
+ messages: Message[],
+ artifacts: Artifact[],
+ napMarkers: NapMarker[],
+ currentConversationId?: string | null,
+): TimelineItem[] {
+ if (!currentConversationId || napMarkers.length === 0) {
+ const items: TimelineItem[] = [
+ ...messages.map((m): TimelineItem => ({ kind: "message", data: m })),
+ ...artifacts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
+ ...napMarkers.map((n): TimelineItem => ({ kind: "nap", data: n })),
+ ];
+ items.sort((a, b) => {
+ const cmp = a.data.created_at.localeCompare(b.data.created_at);
+ if (cmp !== 0) return cmp;
+ if (a.kind === "nap" || b.kind === "nap") {
+ if (a.kind === "nap" && b.kind !== "nap") return 1;
+ if (a.kind !== "nap" && b.kind === "nap") return -1;
+ }
+ if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
+ return a.data.id.localeCompare(b.data.id);
+ });
+ // Strictly chronological — a file uploaded mid-task stays where it appeared
+ // and the agent's reply follows below it in the same cluster (no reorder, so
+ // nothing jumps when the reply lands). Gus's call, 2026-06-01.
+ return items;
+ }
+
+ const napConvIds = new Set(napMarkers.map((n) => n.id.replace(/^nap-/, "")));
+ const sortedNaps = [...napMarkers].sort((a, b) =>
+ a.created_at.localeCompare(b.created_at),
+ );
+
+ const groupItems = (convId: string): TimelineItem[] => {
+ const msgs: TimelineItem[] = messages
+ .filter((m) => m.conversation_id === convId)
+ .map((m) => ({ kind: "message" as const, data: m }));
+ const arts: TimelineItem[] = artifacts
+ .filter((a) => a.conversation_id === convId)
+ .map((a) => ({ kind: "artifact" as const, data: a }));
+ const sorted = [...msgs, ...arts].sort((a, b) => {
+ const cmp = a.data.created_at.localeCompare(b.data.created_at);
+ if (cmp !== 0) return cmp;
+ if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
+ return a.data.id.localeCompare(b.data.id);
+ });
+ return sorted; // chronological, no artifact reorder (see above)
+ };
+
+ const result: TimelineItem[] = [];
+
+ for (const nap of sortedNaps) {
+ const convId = nap.id.replace(/^nap-/, "");
+ result.push(...groupItems(convId));
+ result.push({ kind: "nap", data: nap });
+ }
+
+ result.push(...groupItems(currentConversationId));
+
+ const knownConvIds = new Set([...napConvIds, currentConversationId]);
+ const orphanMsgs = messages.filter(
+ (m) => !knownConvIds.has(m.conversation_id),
+ );
+ const orphanArts = artifacts.filter(
+ (a) => !knownConvIds.has(a.conversation_id),
+ );
+ if (orphanMsgs.length > 0 || orphanArts.length > 0) {
+ const orphanItems: TimelineItem[] = [
+ ...orphanMsgs.map((m): TimelineItem => ({ kind: "message", data: m })),
+ ...orphanArts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
+ ];
+ orphanItems.sort((a, b) => {
+ const cmp = a.data.created_at.localeCompare(b.data.created_at);
+ if (cmp !== 0) return cmp;
+ if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
+ return a.data.id.localeCompare(b.data.id);
+ });
+ const napIdx = result.findIndex((item) => item.kind === "nap");
+ if (napIdx >= 0) {
+ result.splice(napIdx, 0, ...orphanItems);
+ } else {
+ result.push(...orphanItems);
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Whether a completed conversation load may persist the per-channel `last_open`
+ * pointer. Only the SLOW path (param-less open, `targetConvId` absent) resolves
+ * the channel's latest-created conversation; the FAST path (`?conv=<id>`) loads
+ * an explicit, possibly old conversation and must NOT touch the pointer (doing
+ * so reintroduces the wrong-conversation flash). See {@link LastOpenEntry}.
+ *
+ * Pure mirror of the inline Phase B write guard, exported for unit testing the
+ * fast-vs-slow decision without rendering the component.
+ */
+export function shouldPersistPointerForLoad(
+ targetConvId: string | null | undefined,
+): boolean {
+ return !targetConvId;
+}
+
+/**
+ * Decide whether a `task.created` WS event should refresh this view's
+ * per-channel `last_open` pointer, and to which conversation.
+ *
+ * The `last_open` pointer carries "latest-created conversation for this
+ * agent+channel" semantics (see {@link setLastOpenConversation}). A
+ * `task.created` event is the client learning of a (possibly newer)
+ * conversation in real time, so it is a valid moment to refresh the pointer —
+ * but ONLY when the event belongs to exactly this agent + active channel.
+ *
+ * Returns the conversation id to point at, or `null` to skip the write
+ * (different agent, different channel, or the pointer already points there).
+ *
+ * Pure so the scoping logic is unit-testable in the node-env web test suite
+ * (no component render). The caller supplies `serverMessageCount` separately
+ * (A1: derived from the locally-cached message count) when it performs the
+ * actual `setLastOpenConversation` write.
+ */
+export function pointerRefreshTargetForTaskCreated(args: {
+ /** The TaskApi from the `task.created` event. */
+ task: Pick<Task, "agent_id" | "channel" | "conversation_id">;
+ /** The agent this view is rendering. */
+ agentId: string;
+ /** The active channel string (never null — null maps to "default"). */
+ activeChannel: string;
+ /** The conversation id the pointer currently references, if known. */
+ currentPointerConvId: string | null;
+}): string | null {
+ const { task, agentId, activeChannel, currentPointerConvId } = args;
+ // Scope guard: never touch another agent's or channel's pointer. The event's
+ // null channel normalizes to "default" to match the UI's channel string
+ // (channel-context.tsx). activeChannel is always a non-null string.
+ if (task.agent_id !== agentId) return null;
+ if ((task.channel ?? "default") !== activeChannel) return null;
+ // Already pointing here — nothing to do.
+ if (task.conversation_id === currentPointerConvId) return null;
+ return task.conversation_id;
+}
+
+export function useLatest<T>(value: T) {
+ const ref = useRef(value);
+ useEffect(() => {
+ ref.current = value;
+ }, [value]);
+ return ref;
+}
diff --git a/src/web/src/components/agent-chat/chat-view-parts.tsx b/src/web/src/components/agent-chat/chat-view-parts.tsx
new file mode 100644
index 000000000..74e6a2a0c
--- /dev/null
+++ b/src/web/src/components/agent-chat/chat-view-parts.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import React from "react";
+import { FileText } from "lucide-react";
+import type { Artifact } from "@alook/shared";
+import { useAgentContext } from "@/contexts/agent-context";
+import { AgentPreviewCard } from "@/components/agent-preview-card";
+import {
+ Popover,
+ PopoverTrigger,
+ PopoverContent,
+} from "@/components/ui/popover";
+import { SystemCard } from "@/components/agent-chat/message-list";
+import { formatSize } from "@/components/agent-chat/artifact-sheet";
+
+function MentionHighlight(
+ props: Record<string, unknown> & { children?: React.ReactNode },
+) {
+ const { children, ...rest } = props;
+ const { agents } = useAgentContext();
+ const agentId = (rest["data-agent-id"] ?? rest.dataAgentId) as
+ | string
+ | undefined;
+ let agent = agentId ? agents.find((a) => a.id === agentId) : undefined;
+ if (!agent && typeof children === "string") {
+ const nameToMatch = children.startsWith("@") ? children.slice(1) : children;
+ agent = agents.find(
+ (a) => a.name.toLowerCase() === nameToMatch.toLowerCase(),
+ );
+ }
+ if (agent) {
+ return (
+ <Popover>
+ <PopoverTrigger
+ openOnHover
+ delay={300}
+ nativeButton={false}
+ render={<span className="mention-highlight cursor-pointer" />}
+ >
+ {children}
+ </PopoverTrigger>
+ <PopoverContent side="top" className="w-fit max-w-80">
+ <AgentPreviewCard agent={agent} />
+ </PopoverContent>
+ </Popover>
+ );
+ }
+ return <span className="mention-highlight">{children}</span>;
+}
+
+export const MENTION_COMPONENTS: Record<
+ string,
+ React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>
+> = {
+ mention: MentionHighlight,
+ p: ({
+ children,
+ node,
+ ...rest
+ }: Record<string, unknown> & { children?: React.ReactNode }) => {
+ void node;
+ return (
+ <div data-md-p="" {...rest}>
+ {children}
+ </div>
+ );
+ },
+};
+
+export function NapSeparator({ agentName }: { agentName: string }) {
+ return (
+ <div className="flex items-center gap-3 py-4 select-none" aria-hidden>
+ <div className="flex-1 border-t border-border/40" />
+ <span className="text-xs text-muted-foreground/60 whitespace-nowrap">
+ {agentName} took a nap 💤
+ </span>
+ <div className="flex-1 border-t border-border/40" />
+ </div>
+ );
+}
+
+// Agent-side artifact (file) card — same shared SystemCard shell + card
+// language as the event cards (locked prototype: icon chip / FILE / filename /
+// size). The version badge rides along as the title's trailing element.
+export function ArtifactCard({
+ artifact,
+ version,
+ hasDuplicates,
+ onClick,
+}: {
+ artifact: Artifact;
+ version: number;
+ hasDuplicates: boolean;
+ onClick: (a: Artifact) => void;
+}) {
+ return (
+ <SystemCard
+ icon={FileText}
+ label="FILE"
+ title={artifact.filename}
+ preview={formatSize(artifact.size)}
+ trailing={
+ hasDuplicates ? (
+ <span className="shrink-0 text-xs text-muted-foreground bg-muted rounded-full px-1.5 py-0.5 font-normal">
+ v{version}
+ </span>
+ ) : undefined
+ }
+ onClick={() => onClick(artifact)}
+ />
+ );
+}
diff --git a/src/web/src/components/agent-chat/follow-up-buffer.tsx b/src/web/src/components/agent-chat/follow-up-buffer.tsx
deleted file mode 100644
index 40a52b197..000000000
--- a/src/web/src/components/agent-chat/follow-up-buffer.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-"use client";
-
-import React, { useState } from "react";
-import type { Message } from "@alook/shared";
-import { cn } from "@/lib/utils";
-import { Paperclip, X } from "lucide-react";
-
-interface FollowUpBufferProps {
- bufferedMessages: Message[];
- onDelete: (messageId: string) => void;
-}
-
-function truncate(text: string, max: number) {
- if (text.length <= max) return text;
- return text.slice(0, max).trimEnd() + "…";
-}
-
-const MAX_VISIBLE_STACK = 3;
-const CARD_H = 32;
-const STACK_GAP = 6;
-const EXPANDED_GAP = 4;
-
-export function FollowUpBuffer({
- bufferedMessages,
- onDelete,
-}: FollowUpBufferProps) {
- const [expanded, setExpanded] = useState(false);
- const count = bufferedMessages.length;
-
- if (count === 0) return null;
-
- const visibleCount = Math.min(count, MAX_VISIBLE_STACK);
- const collapsedH = CARD_H + (visibleCount - 1) * STACK_GAP;
- const expandedH = count * CARD_H + (count - 1) * EXPANDED_GAP;
-
- return (
- <div className="relative px-5 pb-1">
- <div className="mx-auto max-w-2xl flex justify-center">
- <div
- className="relative w-full max-w-lg transition-[height] duration-200 ease-out"
- style={{ height: expanded ? expandedH : collapsedH }}
- onMouseEnter={() => setExpanded(true)}
- onMouseLeave={() => setExpanded(false)}
- >
- {bufferedMessages.map((msg, i) => {
- const fromBottom = count - 1 - i;
- const inStack = i >= count - visibleCount;
-
- const collapsedBottom = inStack ? fromBottom * STACK_GAP : 0;
- const expandedBottom = fromBottom * (CARD_H + EXPANDED_GAP);
-
- const collapsedScale = inStack ? 1 - fromBottom * 0.03 : 0.91;
- const collapsedOpacity = inStack ? 1 - fromBottom * 0.2 : 0;
-
- return (
- <div
- key={msg.id}
- className="absolute right-0 left-0 transition-all duration-200 ease-out"
- style={{
- height: CARD_H,
- zIndex: i + 1,
- bottom: expanded ? expandedBottom : collapsedBottom,
- transform: expanded ? "scale(1)" : `scale(${collapsedScale})`,
- opacity: expanded ? 1 : collapsedOpacity,
- pointerEvents: expanded || inStack ? "auto" : "none",
- }}
- >
- <div
- className="h-full rounded-lg border bg-background/95 backdrop-blur-sm shadow-sm
- flex items-center gap-2 px-3"
- >
- <span className="shrink-0 text-[11px] text-primary/60 tabular-nums w-4 text-center">
- {i + 1}
- </span>
- <div className="min-w-0 flex-1 flex items-center gap-1.5">
- <p className="text-[13px] text-muted-foreground leading-snug truncate">
- {truncate(msg.content, 80)}
- </p>
- {msg.attachment_ids && msg.attachment_ids.length > 0 && (
- <span className="inline-flex items-center gap-0.5 shrink-0 text-[11px] text-muted-foreground/50">
- <Paperclip className="size-2.5" />
- {msg.attachment_ids.length}
- </span>
- )}
- </div>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onDelete(msg.id);
- }}
- className={cn(
- "shrink-0 rounded-sm p-0.5 transition-all duration-150",
- "text-muted-foreground/30 hover:text-foreground hover:bg-muted",
- expanded ? "opacity-100" : "opacity-0",
- )}
- tabIndex={expanded ? 0 : -1}
- >
- <X className="size-3" />
- </button>
- </div>
- </div>
- );
- })}
-
- {!expanded && count > visibleCount && (
- <span className="absolute -top-4 right-1 text-[10px] text-muted-foreground/40 tabular-nums">
- +{count - visibleCount} more
- </span>
- )}
- </div>
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/agent-chat/historical-task-thinking.tsx b/src/web/src/components/agent-chat/historical-task-thinking.tsx
deleted file mode 100644
index a2e4eaa09..000000000
--- a/src/web/src/components/agent-chat/historical-task-thinking.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-"use client";
-
-import { useState, useCallback } from "react";
-import { TaskStream } from "@/components/task-stream";
-import { getTaskMessages } from "@/lib/api";
-import type { TaskMessageResponse, TaskApi } from "@alook/shared";
-
-const COMPLETED_STUB: TaskApi = {
- id: "",
- agent_id: "",
- runtime_id: "",
- conversation_id: "",
- workspace_id: "",
- prompt: "",
- status: "completed",
- priority: 0,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "",
- type: "",
-};
-
-export function HistoricalTaskThinking({
- taskId,
- thinkingCount,
- workspaceId,
- provider,
-}: {
- taskId: string;
- thinkingCount: number;
- workspaceId: string;
- /** Provider of the conversation's agent runtime, used to attribute runtime errors (issue #236). */
- provider?: string | null;
-}) {
- const [messages, setMessages] = useState<TaskMessageResponse[]>([]);
- const [loading, setLoading] = useState(false);
- const [fetched, setFetched] = useState(false);
-
- const fetchMessages = useCallback(async () => {
- if (fetched || loading) return;
- setLoading(true);
- try {
- const msgs = await getTaskMessages(taskId, workspaceId);
- setMessages(msgs);
- } catch {
- setMessages([]);
- } finally {
- setLoading(false);
- setFetched(true);
- }
- }, [fetched, loading, taskId, workspaceId]);
-
- return (
- <TaskStream
- task={COMPLETED_STUB}
- messages={messages}
- thinkingCountHint={thinkingCount}
- onExpandThinking={fetchMessages}
- thinkingLoading={loading}
- provider={provider}
- />
- );
-}
diff --git a/src/web/src/components/agent-chat/message-list.test.ts b/src/web/src/components/agent-chat/message-list.test.ts
new file mode 100644
index 000000000..d999ab806
--- /dev/null
+++ b/src/web/src/components/agent-chat/message-list.test.ts
@@ -0,0 +1,33 @@
+import { describe, it, expect } from "vitest";
+import { shouldRenderAssistantBody } from "./message-list";
+
+// AC4 regression guard: a send-dm reply that is ALSO the message carrying the
+// live error stream must still render its own text bubble (error is additive),
+// while a runtime-error message stays surfaced by the stream alone when live.
+describe("shouldRenderAssistantBody", () => {
+ it("renders a normal text reply that carries the error stream (the AC4 fix)", () => {
+ // designated last send-dm message + an error stream attached
+ expect(
+ shouldRenderAssistantBody({ hasTaskStream: true, isRuntimeError: false }),
+ ).toBe(true);
+ });
+
+ it("renders a normal text reply with no stream (unchanged clean case)", () => {
+ expect(
+ shouldRenderAssistantBody({ hasTaskStream: false, isRuntimeError: false }),
+ ).toBe(true);
+ });
+
+ it("suppresses a runtime-error message's own block while the stream owns it", () => {
+ // The stream surfaces the error; rendering the block too would double it.
+ expect(
+ shouldRenderAssistantBody({ hasTaskStream: true, isRuntimeError: true }),
+ ).toBe(false);
+ });
+
+ it("renders a runtime-error message's block when no stream owns it", () => {
+ expect(
+ shouldRenderAssistantBody({ hasTaskStream: false, isRuntimeError: true }),
+ ).toBe(true);
+ });
+});
diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsx
index 355195d1f..3702ef19c 100644
--- a/src/web/src/components/agent-chat/message-list.tsx
+++ b/src/web/src/components/agent-chat/message-list.tsx
@@ -8,28 +8,50 @@ import { Streamdown } from "streamdown";
import { mermaid, cjk } from "@/lib/streamdown-plugins";
import { highlightMentions } from "@/lib/highlight-mentions";
import { TaskStream } from "@/components/task-stream";
-import { HistoricalTaskThinking } from "@/components/agent-chat/historical-task-thinking";
import { RuntimeErrorBlock } from "@/components/agent-chat/runtime-error-block";
-import { FileText, Calendar, CircleDot, Mail, Flag, Copy, Check } from "lucide-react";
+import { AnimatedAvatar, type AvatarConfig } from "@/components/avatar";
+import { FileText, Calendar, CircleDot, Mail, Flag, Copy, Check, ChevronRight } from "lucide-react";
-import { getEventIconType, type GroupPosition } from "@/components/agent-chat/agent-chat-view";
+import { eventTypeFromMessage, type GroupPosition } from "@/components/agent-chat/chat-message-utils";
import { toast } from "sonner";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
const MENTION_ALLOWED_TAGS = { mention: ["data-agent-id"] };
const MENTION_LITERAL_TAGS = ["mention"];
+/**
+ * Whether an assistant message renders its own body (text bubble or, for a
+ * runtime-error message, its RuntimeErrorBlock) — independent of the live error
+ * stream wrapper, which is ADDITIVE.
+ *
+ * The AC4 fix: a normal `send-dm` text reply must paint even when it's the
+ * message designated to carry the live error stream (`hasTaskStream`), so its
+ * text is never swallowed. The one exception is a runtime-error message: it IS
+ * the error and is already surfaced by the stream while live, so it only renders
+ * its own block when no stream owns it (`!hasTaskStream`) — avoiding a double
+ * error render.
+ */
+export function shouldRenderAssistantBody(opts: {
+ hasTaskStream: boolean;
+ isRuntimeError: boolean;
+}): boolean {
+ return !opts.hasTaskStream || !opts.isRuntimeError;
+}
+
export interface MessageItemProps {
msg: Message;
agents: Agent[];
artifacts: Artifact[];
activeTask: Task | null;
+ /**
+ * Id of the single assistant message for the active task that should carry the
+ * live error-surface (TaskStream). When a task emits multiple `send-dm`
+ * replies, only this one (the last) gets the stream wrapper — the rest fall to
+ * the clean bubble path. Null when there's no active-task assistant message.
+ */
+ activeTaskStreamMsgId?: string | null;
taskMessages: TaskMessageResponse[];
connectionLost: boolean;
- isLastMessage: boolean;
- thinkingCount: number;
- targetConvId: string | null;
- workspaceId: string;
conversationType?: string | null;
pendingFilesByMessage: Map<string, File[]>;
onArtifactClick: (a: Artifact) => void;
@@ -43,15 +65,128 @@ export interface MessageItemProps {
groupPosition?: GroupPosition;
/** Provider of the conversation's agent runtime, used to attribute runtime errors (issue #236). */
provider?: string | null;
+ /** Agent display name + avatar, for the agent-side IM bubbles and system cards. */
+ agentName: string;
+ agentAvatarConfig: AvatarConfig | null;
+ /** This optimistic user message failed to send — show the inline retry affordance. */
+ isSendFailed?: boolean;
+ onRetrySend?: (messageId: string) => void;
+}
+
+/**
+ * Shared visual shell for agent-side system cards (event + artifact). A tinted
+ * icon chip, an uppercase label, a title line, and an OPTIONAL muted preview
+ * line. Height follows content — a 2-line card (no preview) is genuinely
+ * shorter; we never reserve a blank row to force parity (Gus). Hairline border,
+ * quiet chevron, hover lift. Monochrome.
+ */
+export function SystemCard({
+ icon: Icon,
+ label,
+ title,
+ preview,
+ trailing,
+ onClick,
+}: {
+ icon: typeof Mail;
+ label: string;
+ title: string;
+ preview?: string | null;
+ /** Optional inline element after the title (e.g. an artifact version badge). */
+ trailing?: React.ReactNode;
+ onClick?: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={!onClick}
+ className={cn(
+ // Fixed footprint so email / issue / calendar / file cards are uniform
+ // when stacked — width + height don't follow content (Gus, 2026-06-01).
+ // h fits the 3-line variant; overflow-hidden + per-line truncate keep
+ // any longer content from spilling past the fixed box.
+ "group/card w-[26rem] max-w-full h-[4.75rem] overflow-hidden text-left rounded-md border bg-card",
+ "flex items-center gap-3 px-3 py-2",
+ onClick &&
+ "cursor-pointer transition-all duration-150 hover:-translate-y-px hover:shadow-sm hover:border-foreground/15",
+ )}
+ >
+ <span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ <Icon className="size-4" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground/70">
+ {label}
+ </span>
+ <span className="flex items-center gap-1.5 min-w-0">
+ <span className="truncate text-sm font-medium text-foreground">{title}</span>
+ {trailing}
+ </span>
+ {preview ? (
+ <span className="truncate text-xs text-muted-foreground">{preview}</span>
+ ) : null}
+ </span>
+ {onClick && (
+ <ChevronRight className="size-4 shrink-0 self-center text-muted-foreground/40 transition-colors duration-150 group-hover/card:text-muted-foreground" />
+ )}
+ </button>
+ );
}
-function EventMessageIcon({ content, conversationType }: { content: string; conversationType?: string | null }) {
- const iconType = getEventIconType(content, conversationType);
- const className = "h-4 w-4 mt-0.5 shrink-0";
+// Parse the honest label / title / preview out of a system-event message. The
+// card describes the EVENT (an immutable historical fact), never live state —
+// so no "current status" pill. Preview is honest or omitted (Gus/Priya).
+// Email: "New email from {sender}: {subject}" | "Email sent to {recipient}: {subject}"
+// Issue: "Issue created/opened: {title}" | "Issue status changed: {X} -> {Y}"
+// Calendar: "{title}" (sometimes "Calendar event: {title}")
+function parseEventCard(
+ type: "issue" | "email" | "calendar",
+ content: string,
+): { label: string; title: string; preview?: string } {
+ if (type === "email") {
+ const sent = /^Email sent to (.+?): ([\s\S]+)$/.exec(content);
+ if (sent) return { label: "EMAIL", title: sent[2], preview: `to ${sent[1]}` };
+ const inbound = /^New email from (.+?): ([\s\S]+)$/.exec(content);
+ if (inbound) return { label: "EMAIL", title: inbound[2], preview: `from ${inbound[1]}` };
+ const colon = content.indexOf(": ");
+ return colon > -1
+ ? { label: "EMAIL", title: content.slice(colon + 2) }
+ : { label: "EMAIL", title: content };
+ }
+ if (type === "issue") {
+ const status = /^Issue status changed: ([\s\S]+?) -> ([\s\S]+)$/.exec(content);
+ // The status transition is the immutable event fact — show it as the preview.
+ if (status) return { label: "ISSUE", title: "Status changed", preview: `Status: ${status[1]} → ${status[2]}` };
+ const created = /^Issue (?:created|opened): ([\s\S]+)$/.exec(content);
+ if (created) return { label: "ISSUE", title: created[1] }; // 2-line: no honest preview
+ return { label: "ISSUE", title: content.replace(/^Issue:?\s*/i, "") };
+ }
+ // calendar — title only; strip a "Calendar event:" prefix if present. No
+ // datetime/repeat preview unless it is later stamped into the message.
+ return { label: "CALENDAR", title: content.replace(/^Calendar event:\s*/i, "") };
+}
- if (iconType === "issue") return <CircleDot className={className} />;
- if (iconType === "email") return <Mail className={className} />;
- return <Calendar className={className} />;
+/**
+ * System event (email / issue / calendar) as a clickable card. Type + icon are
+ * metadata-driven (msg.metadata.{issueId,emailId,calendarEventId}), falling back
+ * to the content heuristic only if metadata is absent.
+ */
+function EventCard({
+ content,
+ metadata,
+ conversationType,
+ onClick,
+}: {
+ content: string;
+ metadata?: Record<string, unknown> | null;
+ conversationType?: string | null;
+ onClick?: () => void;
+}) {
+ const type = eventTypeFromMessage(metadata, content, conversationType);
+ const Icon = type === "issue" ? CircleDot : type === "email" ? Mail : Calendar;
+ const { label, title, preview } = parseEventCard(type, content);
+ return <SystemCard icon={Icon} label={label} title={title} preview={preview} onClick={onClick} />;
}
function AttachmentChips({
@@ -111,24 +246,85 @@ function PendingFileChips({
);
}
+// Bubble grouping (locked prototype v2): base radius 1.05rem; the corner FACING
+// the neighbor in the cluster tucks to 0.35rem. User bubbles tuck the RIGHT
+// edge; agent bubbles mirror to the LEFT edge.
+// first → tuck the bottom (corner toward the next bubble)
+// middle → tuck top + bottom
+// last → tuck the top (corner toward the previous bubble)
const USER_BUBBLE_RADIUS: Record<GroupPosition, string> = {
- solo: "rounded-2xl",
- first: "rounded-tl-2xl rounded-tr-2xl rounded-bl-2xl rounded-br-md",
- middle: "rounded-tl-2xl rounded-tr-md rounded-bl-2xl rounded-br-md",
- last: "rounded-tl-2xl rounded-tr-md rounded-bl-2xl rounded-br-2xl",
+ solo: "rounded-[1.05rem]",
+ first: "rounded-[1.05rem] rounded-br-[0.35rem]",
+ middle: "rounded-[1.05rem] rounded-tr-[0.35rem] rounded-br-[0.35rem]",
+ last: "rounded-[1.05rem] rounded-tr-[0.35rem]",
+};
+
+const AGENT_BUBBLE_RADIUS: Record<GroupPosition, string> = {
+ solo: "rounded-[1.05rem]",
+ first: "rounded-[1.05rem] rounded-bl-[0.35rem]",
+ middle: "rounded-[1.05rem] rounded-tl-[0.35rem] rounded-bl-[0.35rem]",
+ last: "rounded-[1.05rem] rounded-tl-[0.35rem]",
};
+// Slack/Discord cluster model (locked prototype): a TOP header [avatar] [name]
+// on the cluster's FIRST message (first/solo); bubbles/cards stack below it in
+// the gutter. Subsequent grouped messages get a spacer (no repeated
+// avatar/name). The avatar is TOP-aligned to the header — it anchors to the
+// name row, not a variable-height column, which dissolves the floating-avatar
+// bug. `forceSpacer` keeps the gutter width but never paints a header — for
+// items (e.g. an artifact card) that belong to the preceding message's cluster.
+const AVATAR_SIZE = 30; // matches the prototype's 30px gutter column
+const GUTTER_W = "w-[30px]";
+
+export function AgentRow({
+ groupPosition,
+ agentName,
+ config,
+ forceSpacer = false,
+ children,
+}: {
+ groupPosition: GroupPosition;
+ agentName: string;
+ config: AvatarConfig | null;
+ forceSpacer?: boolean;
+ children: React.ReactNode;
+}) {
+ const isClusterHead =
+ !forceSpacer && (groupPosition === "first" || groupPosition === "solo");
+ return (
+ <div className="flex justify-start items-start gap-2 min-w-0">
+ <div className={cn(GUTTER_W, "shrink-0")} aria-hidden={!isClusterHead}>
+ {isClusterHead && config && (
+ <AnimatedAvatar
+ config={config}
+ size={AVATAR_SIZE}
+ className="rounded-md"
+ isHovered={false}
+ />
+ )}
+ </div>
+ <div className="min-w-0 max-w-[86%] flex flex-col items-start gap-0.5">
+ {isClusterHead && (
+ // Top-aligned with the avatar (prototype v2): tight line-height + a
+ // hair of top padding so the name's top edge lines up with the avatar.
+ <span className="text-[0.85rem] font-semibold text-foreground leading-[1.15] pt-0.5 mb-1">
+ {agentName}
+ </span>
+ )}
+ {children}
+ </div>
+ </div>
+ );
+}
+
export const MessageItem = memo(function MessageItem({
msg,
agents,
artifacts,
activeTask,
+ activeTaskStreamMsgId,
taskMessages,
connectionLost,
- isLastMessage,
- thinkingCount,
- targetConvId,
- workspaceId,
conversationType,
pendingFilesByMessage,
onArtifactClick,
@@ -141,20 +337,53 @@ export const MessageItem = memo(function MessageItem({
onToggleFlag,
groupPosition = "solo",
provider,
+ agentName,
+ agentAvatarConfig,
+ isSendFailed,
+ onRetrySend,
}: MessageItemProps) {
const { copy, copied } = useCopyToClipboard();
+ // TaskStream owns this assistant message only while the task is still live OR
+ // it failed (it surfaces stream/task-level errors + Retry). A COMPLETED reply
+ // — and a cancelled/superseded notice — falls through to the clean bubble
+ // path below; otherwise the finished reply would render nowhere (TaskStream
+ // no longer renders success text).
const hasTaskStream =
- activeTask &&
+ !!activeTask &&
msg.role === "assistant" &&
msg.task_id === activeTask.id &&
msg.conversation_id === activeTask.conversation_id &&
- taskMessages.length > 0;
+ // Only the designated (last) assistant message of the active task carries
+ // the stream — so multiple `send-dm` replies don't each wrap it. When the
+ // parent didn't compute an id (legacy callers), fall back to per-message.
+ (activeTaskStreamMsgId == null || msg.id === activeTaskStreamMsgId) &&
+ taskMessages.length > 0 &&
+ !["completed", "cancelled", "superseded"].includes(activeTask.status);
+
+ // TaskStream renders only errors / connection-lost now. When it has nothing to
+ // show (a plain running task), skip its wrapper entirely so we don't paint a
+ // lone avatar in an empty gutter void.
+ const streamHasContent =
+ hasTaskStream &&
+ (taskMessages.some((m) => m.type === "error") ||
+ (activeTask!.status === "failed" && !!activeTask!.error) ||
+ connectionLost);
+
+ const isTaskDone = hasTaskStream && activeTask?.status === "failed";
- const isTaskDone = hasTaskStream && activeTask && ["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
+ // Lifecycle notice (cancelled/superseded) — a system line, not agent speech.
+ // Match the durable metadata flag, with a content fallback for older rows.
+ const isLifecycleNote =
+ msg.role === "assistant" &&
+ (msg.metadata?.kind === "lifecycle" ||
+ msg.content === "Task cancelled by you" ||
+ msg.content === "Task cancelled by user");
const actionButtons = msg.role === "assistant" ? (
- <div className="flex flex-row items-center gap-1">
+ // Vertical on mobile so the right-of-bubble actions don't get clipped at
+ // the screen edge; horizontal from md up where there's room.
+ <div className="flex flex-col sm:flex-row items-center gap-1">
<Tooltip>
<TooltipTrigger
render={
@@ -169,10 +398,9 @@ export const MessageItem = memo(function MessageItem({
else toast.error("Failed to copy");
}}
className={cn(
- "self-start mb-1",
copied
? "text-green-500 opacity-100"
- : "text-muted-foreground md:opacity-0 md:group-hover/msg:opacity-100"
+ : "text-muted-foreground sm:opacity-0 sm:group-hover/msg:opacity-100"
)}
/>
}
@@ -190,10 +418,9 @@ export const MessageItem = memo(function MessageItem({
size="icon-xs"
onClick={() => onToggleFlag(msg.id)}
className={cn(
- "self-start mb-1",
isFlagged
? "text-primary opacity-100"
- : "text-muted-foreground md:opacity-0 md:group-hover/msg:opacity-100"
+ : "text-muted-foreground sm:opacity-0 sm:group-hover/msg:opacity-100"
)}
/>
}
@@ -208,35 +435,38 @@ export const MessageItem = memo(function MessageItem({
return (
<React.Fragment>
- {hasTaskStream && (
- <div className={cn(
- "group/msg",
- isFlagged && "bg-muted/30 rounded-lg px-2 -mx-2"
- )} {...(isTaskDone ? { "data-quote-source": true } : {})}>
- <TaskStream
- task={activeTask}
- messages={taskMessages}
- connectionLost={connectionLost}
- onRetry={onRetry}
- provider={provider}
- />
- {isTaskDone && actionButtons}
+ {hasTaskStream && streamHasContent && (
+ <div
+ className={cn("group/msg", isFlagged && "bg-muted/30 rounded-lg px-2 -mx-2")}
+ {...(isTaskDone ? { "data-quote-source": true } : {})}
+ >
+ <AgentRow groupPosition={groupPosition} agentName={agentName} config={agentAvatarConfig}>
+ <div className="relative min-w-0 w-fit max-w-full">
+ <TaskStream
+ task={activeTask}
+ messages={taskMessages}
+ connectionLost={connectionLost}
+ onRetry={onRetry}
+ provider={provider}
+ />
+ {isTaskDone && actionButtons && (
+ <div className="absolute left-full top-0 ml-1 z-10">{actionButtons}</div>
+ )}
+ </div>
+ </AgentRow>
</div>
)}
{msg.role === "user" ? (() => {
- const awaitingRun = isLastMessage && !!activeTask && activeTask.status !== "running" && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
const slashMatch = msg.content.match(/^\/(\S+)\s?([\s\S]*)$/);
const skillName = slashMatch?.[1] ?? null;
const messageBody = slashMatch ? (slashMatch[2] || "") : msg.content;
return (
- <div className="flex justify-end" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
+ <div className="flex flex-col items-end" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
<div className={cn(
"max-w-[80%] px-4 py-2 bg-primary text-primary-foreground text-base relative",
USER_BUBBLE_RADIUS[groupPosition],
+ isSendFailed && "opacity-60",
)}>
- {awaitingRun && (
- <div className={cn("absolute inset-0 animate-pulse pointer-events-none", USER_BUBBLE_RADIUS[groupPosition])} style={{ boxShadow: "0 0 0 2px var(--bubble-glow)" }} />
- )}
{skillName && (
<span className="inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium bg-primary-foreground/15 text-primary-foreground mb-1">
/{skillName}
@@ -254,48 +484,82 @@ export const MessageItem = memo(function MessageItem({
<PendingFileChips pendingFiles={pendingFilesByMessage} messageId={msg.id} />
)}
</div>
+ {isSendFailed && (
+ <button
+ type="button"
+ onClick={() => onRetrySend?.(msg.id)}
+ className="mt-1 px-1 text-xs text-destructive hover:underline"
+ >
+ Not delivered · tap to retry
+ </button>
+ )}
</div>
);
})() : msg.role === "event" ? (() => {
const eventEmailId = msg.metadata?.emailId as string | undefined;
const eventIssueId = msg.metadata?.issueId as string | undefined;
const eventCalendarEventId = msg.metadata?.calendarEventId as string | undefined;
- const isClickable = !!eventEmailId || !!eventIssueId || !!eventCalendarEventId;
+ const onClick = eventEmailId
+ ? () => onEmailClick(eventEmailId)
+ : eventIssueId
+ ? () => onIssueClick(eventIssueId)
+ : eventCalendarEventId
+ ? () => onCalendarEventClick(eventCalendarEventId)
+ : undefined;
return (
- <div className="flex justify-start" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
- <div
- className={cn(
- "w-full rounded-md border bg-muted/50 text-muted-foreground text-sm px-3 py-2 flex items-start gap-2",
- isClickable && "cursor-pointer hover:bg-muted transition-colors"
- )}
- onClick={eventEmailId ? () => onEmailClick(eventEmailId) : eventIssueId ? () => onIssueClick(eventIssueId) : eventCalendarEventId ? () => onCalendarEventClick(eventCalendarEventId) : undefined}
- >
- <EventMessageIcon content={msg.content} conversationType={conversationType} />
- <span className="min-w-0 wrap-anywhere">{msg.content}</span>
- </div>
+ <div data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
+ <AgentRow groupPosition={groupPosition} agentName={agentName} config={agentAvatarConfig}>
+ <EventCard content={msg.content} metadata={msg.metadata} conversationType={conversationType} onClick={onClick} />
+ </AgentRow>
</div>
);
- })() : !hasTaskStream ? (
- <div className={cn(
- "group/msg flex flex-col justify-start min-w-0 overflow-x-clip",
- isFlagged && "bg-muted/30 rounded-lg px-2 -mx-2"
- )} data-message-id={msg.id} data-quote-source {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
- {targetConvId && msg.role === "assistant" && msg.task_id && thinkingCount > 1 && (
- <HistoricalTaskThinking taskId={msg.task_id} thinkingCount={thinkingCount - 1} workspaceId={workspaceId} provider={provider} />
- )}
- {msg.metadata?.error_source === "runtime" ? (
- <div className="px-1 py-1">
- <RuntimeErrorBlock
- provider={(msg.metadata.provider as string | null | undefined) ?? provider}
- message={msg.content}
- />
- </div>
- ) : (
- <div className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground">
- <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>
- )}
- {actionButtons}
+ })() : isLifecycleNote && msg.metadata?.error_source !== "runtime" ? (
+ // Lifecycle note (e.g. "Task cancelled by user") — a quiet centered
+ // system line, not agent speech. No bubble, no avatar gutter.
+ <div className="flex justify-center" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
+ <span className="text-xs text-muted-foreground/70 text-center px-2 py-1">
+ {msg.content}
+ </span>
+ </div>
+ ) : shouldRenderAssistantBody({
+ hasTaskStream,
+ isRuntimeError: msg.metadata?.error_source === "runtime",
+ }) ? (
+ // The agent's own send-dm text bubble renders even when this message is
+ // the one carrying the live error stream (hasTaskStream) — the error
+ // block above is ADDITIVE, not a replacement, so the reply text is never
+ // swallowed (QA AC4). A runtime-error message is the exception: it IS the
+ // error, surfaced by the TaskStream above while live, so it still only
+ // renders its own RuntimeErrorBlock when no stream owns it (!hasTaskStream).
+ <div className="group/msg overflow-x-clip" data-message-id={msg.id} data-quote-source {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
+ <AgentRow groupPosition={groupPosition} agentName={agentName} config={agentAvatarConfig}>
+ {msg.metadata?.error_source === "runtime" ? (
+ // A failure is a real message, not a bubble — surface it plainly
+ // with Retry. actionButtons render as an out-of-flow top-right
+ // overlay so the hidden hover row never reserves height.
+ <div className="relative min-w-0 w-fit max-w-full">
+ <RuntimeErrorBlock
+ provider={(msg.metadata.provider as string | null | undefined) ?? provider}
+ message={msg.content}
+ />
+ {actionButtons && (
+ <div className="absolute left-full top-0 ml-1 z-10">{actionButtons}</div>
+ )}
+ </div>
+ ) : (
+ <div className="relative min-w-0 w-fit max-w-full">
+ <div className={cn(
+ "markdown min-w-0 max-w-full px-4 py-2 bg-muted text-foreground text-base",
+ AGENT_BUBBLE_RADIUS[groupPosition],
+ )}>
+ <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>
+ {actionButtons && (
+ <div className="absolute left-full top-0 ml-1 z-10">{actionButtons}</div>
+ )}
+ </div>
+ )}
+ </AgentRow>
</div>
) : null}
</React.Fragment>
diff --git a/src/web/src/components/agent-chat/presence-line.tsx b/src/web/src/components/agent-chat/presence-line.tsx
new file mode 100644
index 000000000..a5011ebc4
--- /dev/null
+++ b/src/web/src/components/agent-chat/presence-line.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+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
+ *
+ * No "on something" / busy-elsewhere copy (dropped per Gus). Crossfades on
+ * change and gates the typing-dot animation behind prefers-reduced-motion.
+ */
+
+type Presence = "typing" | "idle";
+
+function derivePresence(taskStatus: string | null | undefined): Presence {
+ if (
+ taskStatus === "running" ||
+ taskStatus === "queued" ||
+ taskStatus === "dispatched"
+ ) {
+ return "typing";
+ }
+ return "idle";
+}
+
+function TypingDots() {
+ return (
+ <span className="inline-flex items-center gap-0.5" aria-hidden>
+ <span className="size-1 rounded-full bg-muted-foreground/60 motion-safe:animate-[typing-dot_1.2s_ease-in-out_infinite]" />
+ <span className="size-1 rounded-full bg-muted-foreground/60 motion-safe:animate-[typing-dot_1.2s_ease-in-out_0.2s_infinite]" />
+ <span className="size-1 rounded-full bg-muted-foreground/60 motion-safe:animate-[typing-dot_1.2s_ease-in-out_0.4s_infinite]" />
+ </span>
+ );
+}
+
+export function PresenceLine({
+ agentFirstName,
+ taskStatus,
+}: {
+ agentFirstName: string;
+ taskStatus: string | null | undefined;
+}) {
+ 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
+ key={presence}
+ className={cn(
+ "inline-flex items-center gap-1.5 text-sm text-muted-foreground",
+ presence !== "idle" && "motion-safe:animate-[fade-up_200ms_ease-out_both]",
+ )}
+ >
+ {presence === "typing" && (
+ <>
+ <span>{agentFirstName} is typing</span>
+ <TypingDots />
+ </>
+ )}
+ </span>
+ </div>
+ );
+}
diff --git a/src/web/src/components/agent-chat/use-rotating-placeholder.test.ts b/src/web/src/components/agent-chat/use-rotating-placeholder.test.ts
new file mode 100644
index 000000000..0a4764594
--- /dev/null
+++ b/src/web/src/components/agent-chat/use-rotating-placeholder.test.ts
@@ -0,0 +1,122 @@
+import { describe, it, expect } from "vitest";
+import {
+ CHAT_PLACEHOLDER_HINTS,
+ HINT_HOLD_MS,
+ randomStartIndex,
+ nextIndex,
+ shouldRotate,
+} from "./use-rotating-placeholder";
+
+// The web suite runs node-env (no jsdom/RTL — see agent-chat-view.test.ts), so
+// the hook itself can't be rendered here. All testable logic was extracted into
+// the pure helpers below, which is where every behavioral assertion lives.
+// Component-render / layout / aria checks are QA'd in a real browser.
+
+describe("CHAT_PLACEHOLDER_HINTS", () => {
+ it("contains the 5 LOCKED copy strings in order", () => {
+ expect([...CHAT_PLACEHOLDER_HINTS]).toEqual([
+ "Email the team this week's launch update",
+ "Recruit a QA agent to review my PRs",
+ "Remind me to follow up with Acme on Thursday",
+ "What did we ship last week?",
+ "Fix the failing test in the checkout flow",
+ ]);
+ });
+
+ it("keeps every hint ≤ 45 chars (guards mobile truncation)", () => {
+ for (const hint of CHAT_PLACEHOLDER_HINTS) {
+ expect(hint.length, hint).toBeLessThanOrEqual(45);
+ }
+ });
+
+ it("holds each hint ~6s", () => {
+ expect(HINT_HOLD_MS).toBe(6000);
+ });
+});
+
+describe("randomStartIndex", () => {
+ it("returns an index within [0, len)", () => {
+ const len = CHAT_PLACEHOLDER_HINTS.length;
+ // sweep rand across [0,1) and assert every result is a valid index
+ for (let r = 0; r < 1; r += 0.01) {
+ const i = randomStartIndex(len, () => r);
+ expect(i).toBeGreaterThanOrEqual(0);
+ expect(i).toBeLessThan(len);
+ }
+ });
+
+ it("maps rand=0 to the first and rand→1 to the last", () => {
+ const len = 5;
+ expect(randomStartIndex(len, () => 0)).toBe(0);
+ expect(randomStartIndex(len, () => 0.999999)).toBe(len - 1);
+ });
+
+ it("returns 0 for an empty list (defensive)", () => {
+ expect(randomStartIndex(0, () => 0.5)).toBe(0);
+ });
+});
+
+describe("nextIndex", () => {
+ it("advances sequentially", () => {
+ expect(nextIndex(0, 5)).toBe(1);
+ expect(nextIndex(1, 5)).toBe(2);
+ expect(nextIndex(3, 5)).toBe(4);
+ });
+
+ it("wraps to 0 after the last", () => {
+ expect(nextIndex(4, 5)).toBe(0);
+ });
+
+ it("cycles the full sequence back to start", () => {
+ const len = CHAT_PLACEHOLDER_HINTS.length;
+ let i = 2;
+ const seen: number[] = [i];
+ for (let n = 0; n < len; n++) {
+ i = nextIndex(i, len);
+ seen.push(i);
+ }
+ // after len steps we're back where we started
+ expect(seen[seen.length - 1]).toBe(2);
+ // and we visited every index exactly once along the way
+ expect(new Set(seen.slice(0, len)).size).toBe(len);
+ });
+
+ it("returns 0 for an empty list (defensive)", () => {
+ expect(nextIndex(0, 0)).toBe(0);
+ });
+});
+
+describe("shouldRotate", () => {
+ const base = {
+ isEmpty: true,
+ isFocused: false,
+ isTaskActive: false,
+ reducedMotion: false,
+ };
+
+ it("rotates only when empty, unfocused, idle, and motion allowed", () => {
+ expect(shouldRotate(base)).toBe(true);
+ });
+
+ it("freezes when focused", () => {
+ expect(shouldRotate({ ...base, isFocused: true })).toBe(false);
+ });
+
+ it("freezes when the field is non-empty (typing)", () => {
+ expect(shouldRotate({ ...base, isEmpty: false })).toBe(false);
+ });
+
+ it("freezes when a task is active", () => {
+ expect(shouldRotate({ ...base, isTaskActive: true })).toBe(false);
+ });
+
+ it("does not rotate under reduced motion", () => {
+ expect(shouldRotate({ ...base, reducedMotion: true })).toBe(false);
+ });
+
+ it("blur with an empty field re-enables rotation", () => {
+ // focused → frozen, then blur (isFocused:false) with empty field → rotates
+ expect(shouldRotate({ ...base, isFocused: true })).toBe(false);
+ expect(shouldRotate({ ...base, isFocused: false })).toBe(true);
+ });
+});
diff --git a/src/web/src/components/agent-chat/use-rotating-placeholder.ts b/src/web/src/components/agent-chat/use-rotating-placeholder.ts
new file mode 100644
index 000000000..ff88f4775
--- /dev/null
+++ b/src/web/src/components/agent-chat/use-rotating-placeholder.ts
@@ -0,0 +1,134 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+
+/**
+ * Rotating capability hints for the main chat composer's empty-state
+ * placeholder. Each maps to a REAL Alook capability — the placeholder teaches
+ * by example. Copy LOCKED by Gus 2026-06-01 (natural-imperative voice).
+ *
+ * This is the ONE place to edit the copy. Keep every entry ≤ ~45 chars so the
+ * overlay never wraps / truncates at the smallest mobile width.
+ */
+export const CHAT_PLACEHOLDER_HINTS = [
+ "Email the team this week's launch update",
+ "Recruit a QA agent to review my PRs",
+ "Remind me to follow up with Acme on Thursday",
+ "What did we ship last week?",
+ "Fix the failing test in the checkout flow",
+] as const;
+
+/** Hold each hint ~6s before cross-fading to the next. */
+export const HINT_HOLD_MS = 6000;
+
+const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
+
+/**
+ * Random start index in [0, len). Kept pure + exported so the "random start"
+ * behavior is unit-testable without rendering the hook (web suite is node-env,
+ * no jsdom/RTL). Pass a custom `rand` (defaulting to Math.random) in tests.
+ */
+export function randomStartIndex(
+ len: number,
+ rand: () => number = Math.random,
+): number {
+ if (len <= 0) return 0;
+ return Math.floor(rand() * len) % len;
+}
+
+/** Next index in a sequential cycle, wrapping to 0 after the last. */
+export function nextIndex(current: number, len: number): number {
+ if (len <= 0) return 0;
+ return (current + 1) % len;
+}
+
+/**
+ * The placeholder rotates ONLY when the field is empty, unfocused, not in a
+ * task-in-progress state, and reduced-motion is not requested. Pure predicate,
+ * exported for direct unit testing.
+ */
+export function shouldRotate(state: {
+ isEmpty: boolean;
+ isFocused: boolean;
+ isTaskActive: boolean;
+ reducedMotion: boolean;
+}): boolean {
+ return (
+ state.isEmpty &&
+ !state.isFocused &&
+ !state.isTaskActive &&
+ !state.reducedMotion
+ );
+}
+
+/**
+ * Reads + subscribes to `prefers-reduced-motion`. Inlines the same matchMedia
+ * convention used elsewhere in the codebase (home/feature-showcase.tsx) rather
+ * than adding a shared hook. SSR-safe (defaults to false when no window).
+ */
+function usePrefersReducedMotion(): boolean {
+ const [reduced, setReduced] = useState(false);
+
+ useEffect(() => {
+ if (typeof window === "undefined" || !window.matchMedia) return;
+ const mq = window.matchMedia(REDUCED_MOTION_QUERY);
+ setReduced(mq.matches);
+ const onChange = (e: MediaQueryListEvent) => setReduced(e.matches);
+ mq.addEventListener("change", onChange);
+ return () => mq.removeEventListener("change", onChange);
+ }, []);
+
+ return reduced;
+}
+
+export interface RotatingPlaceholderState {
+ isEmpty: boolean;
+ isFocused: boolean;
+ isTaskActive: boolean;
+}
+
+export interface RotatingPlaceholder {
+ /** The hint to show right now. */
+ hint: string;
+ /** True while the placeholder should actively cross-fade between hints. */
+ isRotating: boolean;
+}
+
+/**
+ * Owns the rotating-placeholder state: a random start index, a sequential
+ * ~3.5s cycle, freeze-on-focus/typing, resume-on-empty-blur, and the
+ * reduced-motion short-circuit (one static hint, never advances).
+ *
+ * NO TipTap / DOM dependency beyond matchMedia — the overlay rendering and
+ * cross-fade live in chat-composer.tsx.
+ */
+export function useRotatingPlaceholder(
+ state: RotatingPlaceholderState,
+): RotatingPlaceholder {
+ const reducedMotion = usePrefersReducedMotion();
+ const [index, setIndex] = useState(() =>
+ randomStartIndex(CHAT_PLACEHOLDER_HINTS.length),
+ );
+
+ const rotating = shouldRotate({ ...state, reducedMotion });
+
+ // Advance on a fixed interval only while rotating. Re-arming on `rotating`
+ // change means focus/typing freezes immediately and empty-blur resumes.
+ // The latest index is read from a ref so the effect doesn't re-run (and
+ // reset the timer) on every advance.
+ const indexRef = useRef(index);
+ indexRef.current = index;
+
+ useEffect(() => {
+ if (!rotating) return;
+ const id = setInterval(() => {
+ setIndex(nextIndex(indexRef.current, CHAT_PLACEHOLDER_HINTS.length));
+ }, HINT_HOLD_MS);
+ return () => clearInterval(id);
+ }, [rotating]);
+
+ return {
+ hint: CHAT_PLACEHOLDER_HINTS[index] ?? CHAT_PLACEHOLDER_HINTS[0],
+ isRotating: rotating,
+ };
+}
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
index b824d669c..6446c3f40 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
@@ -1042,14 +1042,10 @@ export function CloudCodeMonsterPet({
};
return subscribeWs((msg) => {
- if (msg.type === "task.created" || msg.type === "followup.dispatched") {
+ if (msg.type === "task.created") {
showTransientActivity("carrying", 3_000);
} else if (msg.type === "artifact.uploaded" || msg.type === "workspace.files") {
showTransientActivity("carrying", 3_000);
- } else if (msg.type === "followup.deleted") {
- showTransientActivity("sweeping", 3_000);
- } else if (msg.type === "followup.dispatch_failed") {
- showTransientActivity("error", CLOUD_CODE_MONSTER_ERROR_MS);
} else if (msg.type === "email.received") {
showTransientActivity("notification", CLOUD_CODE_MONSTER_ATTENTION_MS);
} else if (msg.type === "task.updated") {
diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsx
index d2c35d435..3eac44c22 100644
--- a/src/web/src/components/task-stream.tsx
+++ b/src/web/src/components/task-stream.tsx
@@ -1,240 +1,74 @@
"use client";
-import { useMemo, useRef, useEffect, useState } from "react";
-import { Badge } from "@/components/ui/badge";
-import { cn } from "@/lib/utils";
+import { useMemo } from "react";
import type { TaskMessageResponse } from "@alook/shared";
import type { TaskApi as Task } from "@alook/shared";
-import {
- ChevronRight,
- Loader2,
-} from "lucide-react";
-import { Streamdown } from "streamdown";
-import { mermaid, cjk } from "@/lib/streamdown-plugins";
import { RuntimeErrorBlock } from "@/components/agent-chat/runtime-error-block";
/* ── Grouped stream items ── */
-interface TextItem {
- kind: "text";
- id: string;
- content: string;
-}
-
interface ErrorItem {
kind: "error";
id: string;
content: string;
}
-type StreamItem = TextItem | ErrorItem;
-
function itemKey(msg: TaskMessageResponse): string {
return msg.id || `seq-${msg.seq}`;
}
-function groupMessages(messages: TaskMessageResponse[]): StreamItem[] {
- const items: StreamItem[] = [];
+// Only `type:"error"` task_messages ever reach TaskStream now — the chat no
+// longer renders intermediate text/thinking (replies arrive via `send-dm`), and
+// the WS/init paths filter to errors-only before this component sees them.
+function groupMessages(messages: TaskMessageResponse[]): ErrorItem[] {
+ const items: ErrorItem[] = [];
for (const msg of messages) {
- const key = itemKey(msg);
- if (msg.type === "text") {
- items.push({ kind: "text", id: key, content: msg.content });
- } else if (msg.type === "error") {
- items.push({ kind: "error", id: key, content: msg.content || msg.output });
+ if (msg.type === "error") {
+ items.push({ kind: "error", id: itemKey(msg), content: msg.content || msg.output });
}
}
return items;
}
-/* ── 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 ── */
+/* ── TaskStream ──
+ *
+ * The chat no longer surfaces intermediate reasoning/tool steps ("thinking")
+ * or a live status badge — the reply lands as one clean bubble (rendered by
+ * message-list once the task settles). TaskStream only renders FAILURES while
+ * a task is live: a runtime error is a real message, not thinking, and going
+ * silent on failure is worse. Both RuntimeErrorBlock paths are kept.
+ */
export function TaskStream({
task,
messages,
connectionLost,
onRetry,
- thinkingCountHint,
- onExpandThinking,
- thinkingLoading,
provider,
}: {
task: Task;
messages: TaskMessageResponse[];
connectionLost?: boolean;
onRetry?: () => void;
- thinkingCountHint?: number;
- onExpandThinking?: () => void;
- thinkingLoading?: boolean;
/** Provider of the conversation's agent runtime, used to attribute runtime errors (issue #236). */
provider?: string | null;
}) {
- const allItems = useMemo(() => groupMessages(messages), [messages]);
- const isRunning = task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled" && task.status !== "superseded";
-
- const textItems = allItems.filter((i): i is TextItem => i.kind === "text");
- const errorItems = allItems.filter((i): i is ErrorItem => i.kind === "error");
- const finalTextItem = textItems.length > 0 ? textItems[textItems.length - 1] : null;
-
- const textScrollRef = useRef<HTMLDivElement>(null);
- const expandedRef = useRef(false);
-
- useEffect(() => {
- if (isRunning && textScrollRef.current) {
- textScrollRef.current.scrollTop = textScrollRef.current.scrollHeight;
- }
- }, [textItems.length, isRunning]);
-
- const intermediateTextItems = isRunning ? textItems : textItems.slice(0, -1);
- const hasFinalText = !isRunning && finalTextItem !== null;
- const showThinkingSection = intermediateTextItems.length > 0 || (thinkingCountHint && thinkingCountHint > 0);
- const displayThinkingCount = intermediateTextItems.length > 0 ? intermediateTextItems.length : thinkingCountHint ?? 0;
-
- const handleThinkingToggle = (e: React.SyntheticEvent<HTMLDetailsElement>) => {
- if ((e.currentTarget as HTMLDetailsElement).open && !expandedRef.current && onExpandThinking) {
- expandedRef.current = true;
- onExpandThinking();
- }
- };
+ const errorItems = useMemo(() => groupMessages(messages), [messages]);
+
+ // Nothing to show unless the stream surfaced an error, the task failed, or
+ // the connection dropped — the successful reply is rendered as a bubble.
+ if (
+ errorItems.length === 0 &&
+ !(task.status === "failed" && task.error) &&
+ !connectionLost
+ ) {
+ return null;
+ }
return (
<div className="space-y-3 min-w-0 max-w-full">
- {/* Status badge — only for live tasks, not historical */}
- {!onExpandThinking && (
- <div className="flex items-center gap-2">
- {task.status === "running" ? (
- <Badge variant="secondary" className="gap-1.5 relative overflow-hidden">
- <span className="size-1.5 rounded-full bg-primary animate-pulse" />
- Working
- <div
- className="pointer-events-none absolute inset-0 -translate-x-full animate-[shimmer_2s_ease-in-out_infinite]"
- style={{
- background: "linear-gradient(90deg, transparent 0%, var(--shimmer) 40%, var(--shimmer-peak) 50%, var(--shimmer) 60%, transparent 100%)",
- }}
- />
- </Badge>
- ) : isRunning ? (
- <Badge variant="secondary" className="relative overflow-hidden">
- {task.status}
- <div
- className="pointer-events-none absolute inset-0 -translate-x-full animate-[shimmer_2s_ease-in-out_infinite]"
- style={{
- background: "linear-gradient(90deg, transparent 0%, var(--shimmer) 40%, var(--shimmer-peak) 50%, var(--shimmer) 60%, transparent 100%)",
- }}
- />
- </Badge>
- ) : (
- <Badge variant="secondary">{task.status}</Badge>
- )}
- </div>
- )}
-
- {/* Thinking section — intermediate text, open while running or when no final text */}
- {showThinkingSection && (
- <details className="group/midtext pl-1" open={!hasFinalText && !onExpandThinking || undefined} onToggle={handleThinkingToggle}>
- <summary
- className={cn(
- "flex items-center gap-1.5 py-1 cursor-pointer select-none",
- "text-xs text-muted-foreground transition-colors duration-150",
- "hover:text-foreground",
- "[&::-webkit-details-marker]:hidden [&::marker]:hidden"
- )}
- >
- <ChevronRight className="size-3 shrink-0 text-muted-foreground/60 transition-transform duration-150 group-open/midtext:rotate-90" />
- <span><AnimatedNumber value={displayThinkingCount} /> thinking</span>
- </summary>
- <div ref={textScrollRef} className="mt-1 pl-1">
- {thinkingLoading && intermediateTextItems.length === 0 && (
- <div className="flex items-center gap-2 py-2 text-xs text-muted-foreground">
- <Loader2 className="size-3 animate-spin" />
- <span>Loading...</span>
- </div>
- )}
- {intermediateTextItems.map((item) => (
- <div key={item.id} className="markdown max-w-full min-w-0 px-1 text-sm text-muted-foreground">
- <Streamdown plugins={{ mermaid, cjk }} controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{item.content}</Streamdown>
- </div>
- ))}
- </div>
- </details>
- )}
- {/* Final text — shown after completion (not for historical tasks which render it as a message) */}
- {hasFinalText && !onExpandThinking && (
- <div className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground">
- <Streamdown plugins={{ mermaid, cjk }} controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{finalTextItem.content}</Streamdown>
- </div>
- )}
-
{/* Stream error messages — attributed to the agent runtime (issue #236) */}
{errorItems.length > 0 && (
<div className="space-y-1 mt-1">
diff --git a/src/web/src/hooks/use-agent-chat.ts b/src/web/src/hooks/use-agent-chat.ts
new file mode 100644
index 000000000..ffa8db8c2
--- /dev/null
+++ b/src/web/src/hooks/use-agent-chat.ts
@@ -0,0 +1,1849 @@
+"use client";
+
+import {
+ useEffect,
+ useState,
+ useRef,
+ useCallback,
+ useMemo,
+ type MutableRefObject,
+} from "react";
+import { flushSync } from "react-dom";
+import {
+ chatInit,
+ checkFreshness,
+ conversationInit,
+ createConversation,
+ listMessages,
+ listMessagesAroundTask,
+ listPreviousConversations,
+ sendMessage,
+ getTask,
+ getTaskMessages,
+ listArtifacts,
+ getActiveTask,
+ retryTask,
+ markInboxRead,
+ listFlaggedMessageIds,
+} from "@/lib/api";
+import {
+ appendCachedMessage,
+ getCachedMessages,
+ getCachedMessagesBefore,
+ getCacheMeta,
+ mergeCachedMessages,
+ getLastOpenConversation,
+ setLastOpenConversation,
+ getConvExtras,
+ setConvExtras,
+} from "@/lib/chat-cache";
+import {
+ createFastLoadGateState,
+ fastLoadKey,
+ shouldSkipFastLoad,
+ markFastLoadCompleted,
+} from "@/components/agent-chat/fast-load-gate";
+import {
+ sortMessages,
+ mergeMessages,
+ computeGroupPositions,
+ buildTimeline,
+ shouldPersistPointerForLoad,
+ pointerRefreshTargetForTaskCreated,
+ useLatest,
+} from "@/components/agent-chat/chat-message-utils";
+import type { NapMarker } from "@/components/agent-chat/chat-message-utils";
+import type { PreviousConversation } from "@/lib/api";
+import type {
+ Agent,
+ Artifact,
+ Conversation,
+ Message,
+ SkillEntry,
+ TaskApi as Task,
+ TaskMessageResponse,
+ WsMessage,
+} from "@alook/shared";
+import { toast } from "sonner";
+import type { ChatComposerHandle } from "@/components/agent-chat/chat-composer";
+import { useCachedMessages } from "@/hooks/use-cached-messages";
+
+const MESSAGE_LIMIT = 20;
+const MAX_CONV_FETCHES_PER_CLICK = 5;
+
+export interface UseAgentChatProps {
+ agentId: string;
+ targetConvId: string | null;
+ scrollToTaskId: string | null;
+ scrollToMessageId: string | null;
+ propTargetConvId?: string | null;
+ workspaceId: string;
+ agents: Agent[];
+ activeChannel: string;
+ channelLoading: boolean;
+ subscribeWs: (cb: (msg: WsMessage) => void) => () => void;
+ subscribeReconnect: (cb: () => void) => () => void;
+ refreshInboxCount: () => void;
+}
+
+export interface UseAgentChatExternal {
+ // (a) Setters the hook WRITES — state owned outside the hook, passed IN.
+ setFlaggedIds: (ids: Set<string>) => void;
+ setPendingFiles: (files: File[]) => void;
+ setInput: (value: string) => void;
+ setQuotedText: (value: string | null) => void;
+ setActiveSkill: (skill: SkillEntry | null) => void;
+ clearActiveSkill: () => void;
+ // (b) Values the hook READS — owned outside, passed IN via useLatest ref.
+ inputRef: MutableRefObject<string>;
+ quotedTextRef: MutableRefObject<string | null>;
+ pendingFilesRef: MutableRefObject<File[]>;
+ activeSkillRef: MutableRefObject<SkillEntry | null>;
+ // Component-owned ref written by the load effect (gates draft-meta persist).
+ draftMetaRestoredRef: MutableRefObject<boolean>;
+}
+
+export function useAgentChat(
+ props: UseAgentChatProps,
+ external: UseAgentChatExternal,
+) {
+ const {
+ agentId,
+ targetConvId,
+ scrollToTaskId,
+ scrollToMessageId,
+ propTargetConvId,
+ workspaceId,
+ agents,
+ activeChannel,
+ channelLoading,
+ subscribeWs,
+ subscribeReconnect,
+ refreshInboxCount,
+ } = props;
+ const {
+ setFlaggedIds,
+ setPendingFiles,
+ setInput,
+ setQuotedText,
+ setActiveSkill,
+ clearActiveSkill,
+ inputRef,
+ quotedTextRef,
+ pendingFilesRef,
+ activeSkillRef,
+ draftMetaRestoredRef,
+ } = external;
+
+ const [conversation, setConversation] = useState<Conversation | null>(null);
+ const [messages, setMessages] = useState<Message[]>([]);
+ const [sending, setSending] = useState(false);
+ const [activeTask, setActiveTask] = useState<Task | null>(null);
+ const [taskMessages, setTaskMessages] = useState<TaskMessageResponse[]>([]);
+ const [messagesLoading, setMessagesLoading] = useState(true);
+ const [connectionLost, setConnectionLost] = useState(false);
+ const [hasMore, setHasMore] = useState(false);
+ const [loadingMore, setLoadingMore] = useState(false);
+ const [artifacts, setArtifacts] = useState<Artifact[]>([]);
+ const [previousConversations, setPreviousConversations] = useState<
+ PreviousConversation[]
+ >([]);
+ const [hasMoreConversations, setHasMoreConversations] = useState(false);
+ const [napMarkers, setNapMarkers] = useState<NapMarker[]>([]);
+
+ const [pendingFilesByMessage, setPendingFilesByMessage] = useState<
+ Map<string, File[]>
+ >(() => new Map());
+ // Optimistic sends that failed to reach the server. The bubble stays in place
+ // with an inline "Not delivered · tap to retry" affordance (iMessage-style),
+ // keyed by the optimistic message id → the content + files to resend.
+ const [failedSends, setFailedSends] = useState<
+ Map<string, { content: string; files: File[] }>
+ >(() => new Map());
+
+ const { writeToCache } = useCachedMessages(targetConvId ?? null, workspaceId);
+ const writeToCacheRef = useRef(writeToCache);
+ useEffect(() => {
+ writeToCacheRef.current = writeToCache;
+ }, [writeToCache]);
+
+ const agentArtifacts = useMemo(
+ () => artifacts.filter((a) => a.source === "agent"),
+ [artifacts],
+ );
+
+ const timeline = useMemo(
+ () => buildTimeline(messages, agentArtifacts, napMarkers, conversation?.id),
+ [messages, agentArtifacts, napMarkers, conversation?.id],
+ );
+ const groupPositions = useMemo(
+ () => computeGroupPositions(timeline),
+ [timeline],
+ );
+
+ // The live error-surface (TaskStream) must attach to at most ONE message per
+ // active task — otherwise multiple `send-dm` replies sharing a taskId would
+ // each render the (errors-only) stream wrapper. Pick the LAST assistant
+ // message of the active task; MessageItem gates `hasTaskStream` on this id.
+ const activeTaskStreamMsgId = useMemo(() => {
+ if (!activeTask) return null;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const m = messages[i];
+ if (m.role === "assistant" && m.task_id === activeTask.id) return m.id;
+ }
+ return null;
+ }, [messages, activeTask]);
+
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const markReadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pollTaskIdRef = useRef<string | null>(null);
+ const lastSeqRef = useRef(0);
+ const pollFailures = useRef(0);
+ const initialScrollDone = useRef(false);
+ const loadingMoreRef = useRef(false);
+ const isNearBottom = useRef(true);
+ const scrollTargetActiveRef = useRef(false);
+ const startPollingRef = useRef<
+ | ((taskId: string, conversationId: string, initialSeq?: number) => void)
+ | null
+ >(null);
+ const oldestConversationCursorRef = useRef<PreviousConversation | null>(null);
+ const backfillAttemptsRef = useRef(0);
+ const prevConversationIdRef = useRef<string | undefined>(undefined);
+ // The server-confirmed conversation id for the current load. Cache writes
+ // (mergeCachedMessages / appendCachedMessage / setLastOpenConversation) must
+ // guard on this so a write never lands on an optimistically-rendered (not yet
+ // confirmed) conversation during the cache-first window. Stays null until
+ // checkFreshness / chatInit / conversationInit confirms an id.
+ const loadConvIdRef = useRef<string | null>(null);
+ // Dedup gate for the fast-path load: skips a redundant re-run when only
+ // channel deps (activeChannel / channelLoading) change, WITHOUT stranding the
+ // skeleton if a run is cancelled mid-flight. See fast-load-gate.ts (Part 2-a /
+ // TODO 6 + stuck-skeleton fix).
+ const fastLoadGateRef = useRef(createFastLoadGateState());
+ // TipTap composer imperative handle (focus / clear / isEmpty / anchor coords).
+ const composerRef = useRef<ChatComposerHandle>(null);
+
+ // Persist a live-updated artifacts array to the cached card metadata so the
+ // next instant open includes it. Read-modify-write: reads the existing
+ // `conv_extras` row (which holds the conversation_type/title/channel/
+ // created_at from the last network write) and replaces only `artifacts`.
+ //
+ // Best-effort and fire-and-forget (review MEDIUM-2): if two updates race
+ // within the write window, the loser may write a momentarily-short list — NOT
+ // data loss, because the next `conversationInit` does a full-replace write of
+ // the authoritative server artifacts. We skip the write when no extras row
+ // exists yet (artifact arrived before the first network write) — the imminent
+ // network/post-task write lands the full row. Guarded on `loadConvIdRef` so a
+ // write never lands on a switched-away or not-yet-confirmed conversation.
+ const persistArtifactsToCache = useCallback(
+ (conversationId: string, nextArtifacts: Artifact[]) => {
+ if (loadConvIdRef.current !== conversationId) return;
+ getConvExtras(conversationId, workspaceId)
+ .then((extras) => {
+ if (!extras) return;
+ if (loadConvIdRef.current !== conversationId) return;
+ return setConvExtras(
+ conversationId,
+ {
+ artifacts: nextArtifacts,
+ conversation_type: extras.conversation_type,
+ conversation_title: extras.conversation_title,
+ conversation_channel: extras.conversation_channel,
+ conversation_created_at: extras.conversation_created_at,
+ hasMoreArtifacts: extras.hasMoreArtifacts,
+ },
+ workspaceId,
+ );
+ })
+ .catch(() => { });
+ },
+ [workspaceId],
+ );
+
+ const scrollToBottom = useCallback(() => {
+ isNearBottom.current = true;
+ setTimeout(() => {
+ scrollRef.current?.scrollTo({
+ top: scrollRef.current.scrollHeight,
+ behavior: "smooth",
+ });
+ }, 50);
+ }, []);
+
+ useEffect(() => {
+ // The slow path (no targetConvId) resolves the conversation id via the
+ // server using activeChannel, so it must wait for the channel list. The
+ // fast path (known targetConvId) and the cache-first optimistic paint need
+ // neither activeChannel nor a loaded channel list, so they must NOT be
+ // gated by channelLoading (Part 2-a). channelLoading stays in the dep array
+ // so the slow path retries once channels load.
+ if (!targetConvId && channelLoading) return;
+
+ // Fast path: ignore channel-only dep changes (TODO 6). shouldSkipFastLoad
+ // returns true only when a load for this identity has already COMPLETED, and
+ // otherwise clears the completed marker so a run cancelled mid-flight leaves
+ // no "done" marker — the recovery run then proceeds and clears the skeleton
+ // instead of getting stuck forever. See fast-load-gate.ts.
+ const fastKey = fastLoadKey({
+ workspaceId,
+ agentId,
+ targetConvId,
+ scrollToTaskId,
+ });
+ if (shouldSkipFastLoad(fastKey, fastLoadGateRef.current)) return;
+
+ if (pollRef.current) clearInterval(pollRef.current);
+ pollRef.current = null;
+ pollTaskIdRef.current = null;
+ loadConvIdRef.current = null;
+ let ignore = false;
+ setMessagesLoading(true);
+ initialScrollDone.current = false;
+ setActiveTask(null);
+ setTaskMessages([]);
+ setPendingFilesByMessage(new Map());
+ setFailedSends(new Map());
+ setNapMarkers([]);
+ setPreviousConversations([]);
+ setHasMoreConversations(false);
+ oldestConversationCursorRef.current = null;
+ setInput(
+ localStorage.getItem(
+ `chat-draft:${agentId}:${targetConvId ?? "default"}`,
+ ) ?? "",
+ );
+ const metaRaw = localStorage.getItem(
+ `chat-draft-meta:${agentId}:${targetConvId ?? "default"}`,
+ );
+ if (metaRaw) {
+ try {
+ const meta = JSON.parse(metaRaw);
+ setQuotedText(meta.quote ?? null);
+ setActiveSkill(
+ meta.skill ? (meta.skill as SkillEntry) : null,
+ );
+ } catch {
+ setQuotedText(null);
+ setActiveSkill(null);
+ }
+ } else {
+ setQuotedText(null);
+ setActiveSkill(null);
+ }
+ draftMetaRestoredRef.current = true;
+ setMessages([]);
+
+ // Paint cached messages for a known conversation id without any network.
+ // Returns true if it painted, so the caller can suppress the loading
+ // skeleton until the background reconcile runs.
+ async function paintFromCache(convId: string): Promise<{
+ painted: boolean;
+ cacheMeta: Awaited<ReturnType<typeof getCacheMeta>>;
+ }> {
+ const cacheMeta = await getCacheMeta(convId, workspaceId);
+ if (cacheMeta?.newestMessageId) {
+ const cached = await getCachedMessages(convId, workspaceId);
+ if (ignore) return { painted: false, cacheMeta };
+ if (cached && cached.length > 0) {
+ setMessages(cached);
+ setHasMore(cacheMeta.hasMore);
+ setMessagesLoading(false);
+ // Paint the cards (artifacts + event-card icon/label) from cache in
+ // the same frame as the text, so they don't pop in after the network
+ // round-trip. Both pieces are overwritten by the authoritative
+ // network values in Phase B — this is purely a no-reflow first paint.
+ await paintExtrasFromCache(convId, cached);
+ return { painted: true, cacheMeta };
+ }
+ }
+ return { painted: false, cacheMeta };
+ }
+
+ // Apply the cached card metadata (artifacts + a provisional conversation
+ // stub) for `convId`. The stub exists only so `conversationType` resolves
+ // the event-card icon/label correctly on first paint; the network's
+ // `setConversation(data.conversation)` overwrites the whole stub afterward.
+ // `paintedMessages` is the just-painted cached message list, used to derive
+ // a `created_at` fallback so we never seed an empty string (which would
+ // flip the scroll heuristic's `!conversation.created_at` branch).
+ async function paintExtrasFromCache(
+ convId: string,
+ paintedMessages: Message[],
+ ): Promise<void> {
+ const extras = await getConvExtras(convId, workspaceId);
+ if (ignore || !extras) return;
+ setArtifacts(extras.artifacts);
+ const createdAt =
+ extras.conversation_created_at ||
+ paintedMessages[0]?.created_at ||
+ paintedMessages[paintedMessages.length - 1]?.created_at ||
+ "";
+ setConversation((prev) =>
+ // Seed the provisional stub only when no conversation is set yet, OR
+ // when the existing one is for a DIFFERENT conversation (a switch from
+ // A→B: replace A's stale stub with B's). Never clobber an authoritative
+ // conversation already fetched for THIS `convId` — `prev.id === convId`
+ // means the network landed first (or this is a same-conversation
+ // re-run, e.g. a scrollToTaskId change), so keep the real value.
+ prev && prev.id === convId
+ ? prev
+ : {
+ id: convId,
+ agent_id: agentId,
+ title: extras.conversation_title,
+ type: extras.conversation_type,
+ channel: extras.conversation_channel,
+ created_at: createdAt,
+ },
+ );
+ }
+
+ async function load() {
+ let hasCachedMessages = false;
+ try {
+ let convId: string | null = null;
+ let cacheMeta: Awaited<ReturnType<typeof getCacheMeta>> = null;
+ // The id we optimistically painted in the slow path; reconciled against
+ // the server-confirmed id once checkFreshness returns.
+ let optimisticConvId: string | null = null;
+
+ if (targetConvId) {
+ // Fast path: we already know the conv ID — render from cache immediately, no network needed
+ convId = targetConvId;
+ const res = await paintFromCache(convId);
+ if (ignore) return;
+ cacheMeta = res.cacheMeta;
+ hasCachedMessages = res.painted;
+ } else {
+ // Slow path: resolve the conversation id locally first (last-open
+ // pointer) and paint its cache immediately, then verify in the
+ // background. Only paint optimistically when the pointer is plausibly
+ // fresh (serverMessageCount > 0 and a non-empty cache), so a stale or
+ // empty pointer falls back to the skeleton (review #4).
+ //
+ // The pointer now carries "latest-created conversation for this
+ // agent+channel" semantics (see {@link setLastOpenConversation} and the
+ // gated write in Phase B / the task.created WS handler), matching the
+ // server's `check-fresh` definition of "current" (latest-created). So
+ // the optimistic paint is correct-by-construction: in the common case
+ // the painted id equals the check-fresh id below → no swap → no flash.
+ // Do NOT reintroduce "last opened" semantics here (e.g. by writing the
+ // pointer from a `?conv=` fast-path open) — that is exactly the bug this
+ // fix removed.
+ const lastOpen = await getLastOpenConversation(
+ agentId,
+ activeChannel,
+ workspaceId,
+ );
+ if (ignore) return;
+ if (lastOpen?.conversation_id && lastOpen.serverMessageCount > 0) {
+ const res = await paintFromCache(lastOpen.conversation_id);
+ if (ignore) return;
+ if (res.painted) {
+ hasCachedMessages = true;
+ optimisticConvId = lastOpen.conversation_id;
+ cacheMeta = res.cacheMeta;
+ }
+ }
+
+ // Background freshness check — does NOT gate the paint above.
+ try {
+ const fresh = await checkFreshness(
+ { agentId, channel: activeChannel },
+ workspaceId,
+ );
+ if (ignore) return;
+ convId = fresh.conversation_id;
+
+ if (optimisticConvId && convId !== optimisticConvId) {
+ // We painted the wrong/stale conversation. Swap to the correct
+ // one and reset scroll intent so the initial-scroll effect
+ // re-fires for the new message set (review #2).
+ initialScrollDone.current = false;
+ isNearBottom.current = true;
+ const res = await paintFromCache(convId);
+ if (ignore) return;
+ cacheMeta = res.cacheMeta;
+ hasCachedMessages = res.painted;
+ if (!res.painted) {
+ // The correct conversation has no cache — clear the stale
+ // optimistic render so the Phase B merge below starts from an
+ // empty list instead of mixing conversation A's messages into B.
+ setMessages([]);
+ setMessagesLoading(true);
+ // Also clear the optimistically-painted cards from conversation
+ // A. With extras now seeding `artifacts` on the optimistic
+ // paint, a corrected conversation with no cache would otherwise
+ // keep showing A's artifact cards until Phase B responds. The
+ // provisional `conversation` stub is overwritten by Phase B's
+ // authoritative `setConversation(data.conversation)` (MEDIUM-3).
+ // When `res.painted` is true, paintFromCache already re-seeded
+ // the corrected conversation's own cards.
+ setArtifacts([]);
+ }
+ } else if (!optimisticConvId) {
+ // Nothing painted yet — read the resolved conversation's cache.
+ const res = await paintFromCache(convId);
+ if (ignore) return;
+ cacheMeta = res.cacheMeta;
+ hasCachedMessages = res.painted;
+ }
+ // else: optimistic id matched the confirmed id — keep the paint.
+ //
+ // We always fall through to Phase B: even when the cache is fresh
+ // (idMatches && countMatches), conversationInit returns cache_valid
+ // and is still needed for conversation meta / tasks / artifacts, and
+ // it does NOT re-set messages — so a fresh cache means exactly one
+ // setMessages (the instant paint), no flicker. Phase B also writes
+ // the server-confirmed last_open pointer for both fresh and stale.
+ } catch {
+ // checkFreshness failed — fall back to chatInit below
+ }
+ }
+
+ // Phase B: full data fetch (background hydration or stale-cache refresh)
+ if (convId) {
+ loadConvIdRef.current = convId;
+ const data = await conversationInit(convId, workspaceId, {
+ newestMessageId: cacheMeta?.newestMessageId ?? undefined,
+ // 0 means "count unknown" (e.g. cached via the chatInit fallback,
+ // which has no server total) — omit the param so the server skips
+ // the count compare and relies on newestMessageId alone. Sending
+ // "0" would make the server's `serverMessageCount === 0` check fail
+ // for every non-empty conversation, forcing a needless full merge.
+ messageCount: cacheMeta?.serverMessageCount || undefined,
+ });
+ if (ignore) return;
+ setConversation(data.conversation);
+ setHasMoreConversations(data.has_more_conversations);
+ if (!data.cache_valid && data.messages) {
+ // Stale cache — merge server data in place, preserving scroll
+ // position unless the user was already near the bottom (A2 / TODO 5).
+ const wasNearBottom = isNearBottom.current;
+ setMessages((prev) => mergeMessages(prev, data.messages!));
+ if (loadConvIdRef.current === convId) {
+ mergeCachedMessages(
+ convId,
+ data.messages,
+ data.has_more_messages,
+ workspaceId,
+ data.message_count,
+ ).catch(() => { });
+ }
+ setHasMore(data.has_more_messages);
+ if (
+ hasCachedMessages &&
+ initialScrollDone.current &&
+ wasNearBottom
+ ) {
+ scrollToBottom();
+ }
+ } else if (cacheMeta) {
+ setHasMore(cacheMeta.hasMore);
+ }
+ // Record the last-open pointer with server-confirmed freshness so the
+ // next param-less open can resolve this conversation locally. Re-read
+ // the cache meta (just updated by mergeCachedMessages on the stale
+ // path) so the stored newest id is authoritative rather than inferred
+ // from page order.
+ //
+ // GATED on `!targetConvId`: only the SLOW path (param-less, server-
+ // resolved) may write the pointer. On the FAST path `convId ===
+ // targetConvId` — an explicit, possibly OLD conversation the user
+ // navigated to via `?conv=`. Persisting that would re-corrupt the
+ // pointer back to "last-opened" semantics and reintroduce the
+ // wrong-conversation flash on the next param-less open. The pointer
+ // must only ever carry the channel's latest-created conversation.
+ if (
+ loadConvIdRef.current === convId &&
+ shouldPersistPointerForLoad(targetConvId)
+ ) {
+ const confirmedMeta = await getCacheMeta(convId, workspaceId);
+ if (ignore) return;
+ setLastOpenConversation(
+ agentId,
+ activeChannel,
+ {
+ conversation_id: convId,
+ newestMessageId:
+ confirmedMeta?.newestMessageId ??
+ cacheMeta?.newestMessageId ??
+ null,
+ serverMessageCount: data.message_count,
+ },
+ workspaceId,
+ ).catch(() => { });
+ }
+ setArtifacts(data.artifacts);
+ // Persist the authoritative card metadata so the next open paints the
+ // artifact cards + correct event-card types instantly from cache.
+ // Guarded on the stale-closure ref (same as the message write above)
+ // so we never write extras for a switched-away conversation;
+ // fire-and-forget, off the critical path.
+ if (loadConvIdRef.current === convId) {
+ setConvExtras(
+ convId,
+ {
+ artifacts: data.artifacts,
+ conversation_type: data.conversation.type,
+ conversation_title: data.conversation.title,
+ conversation_channel: data.conversation.channel,
+ conversation_created_at: data.conversation.created_at,
+ hasMoreArtifacts: data.has_more_artifacts,
+ },
+ workspaceId,
+ ).catch(() => { });
+ }
+ setFlaggedIds(new Set(data.flagged_message_ids));
+ if (data.active_task) {
+ setActiveTask(data.active_task);
+ setTaskMessages(data.task_messages);
+ if (data.task_messages.length > 0) {
+ lastSeqRef.current = Math.max(
+ ...data.task_messages.map((m) => m.seq),
+ );
+ }
+ startPollingRef.current?.(
+ data.active_task.id,
+ convId,
+ lastSeqRef.current,
+ );
+ }
+ if (scrollToTaskId) {
+ const task = await getTask(scrollToTaskId, workspaceId).catch(
+ () => null,
+ );
+ if (ignore) return;
+ if (
+ task &&
+ !["completed", "failed", "cancelled", "superseded"].includes(
+ task.status,
+ )
+ ) {
+ setActiveTask(task);
+ const tmsgs = await getTaskMessages(
+ scrollToTaskId,
+ workspaceId,
+ ).catch(() => [] as TaskMessageResponse[]);
+ if (ignore) return;
+ // Errors-only: thinking is no longer rendered (replies arrive via
+ // `send-dm`); we keep only the live error channel.
+ const errorMsgs = tmsgs.filter((m) => m.type === "error");
+ setTaskMessages(errorMsgs);
+ // Advance the cursor past all fetched seqs (incl. dropped
+ // thinking) so the poll/WS don't reconsider them.
+ if (tmsgs.length > 0) {
+ lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq));
+ }
+ startPollingRef.current?.(task.id, convId, lastSeqRef.current);
+ }
+ }
+ } else {
+ // checkFreshness failed entirely — fall back to chatInit
+ const data = await chatInit(agentId, workspaceId, activeChannel);
+ if (ignore) return;
+ loadConvIdRef.current = data.conversation.id;
+ setConversation(data.conversation);
+ const wasNearBottom = isNearBottom.current;
+ setMessages((prev) =>
+ prev.length > 0
+ ? mergeMessages(prev, data.messages)
+ : data.messages,
+ );
+ setHasMore(data.has_more_messages);
+ setArtifacts(data.artifacts);
+ setHasMoreConversations(data.has_more_conversations);
+ mergeCachedMessages(
+ data.conversation.id,
+ data.messages,
+ data.has_more_messages,
+ workspaceId,
+ ).catch(() => { });
+ // Persist the card metadata from the chatInit fallback too (same
+ // shape as the conversationInit write above), guarded on the
+ // stale-closure ref. ChatInit's response carries the same
+ // `artifacts` + `conversation` + `has_more_artifacts` fields.
+ if (loadConvIdRef.current === data.conversation.id) {
+ setConvExtras(
+ data.conversation.id,
+ {
+ artifacts: data.artifacts,
+ conversation_type: data.conversation.type,
+ conversation_title: data.conversation.title,
+ conversation_channel: data.conversation.channel,
+ conversation_created_at: data.conversation.created_at,
+ hasMoreArtifacts: data.has_more_artifacts,
+ },
+ workspaceId,
+ ).catch(() => { });
+ }
+ // This branch is reached only when `convId` is null — i.e. the SLOW
+ // path's checkFreshness failed and we fell back to chatInit. chatInit
+ // returns the server's current (latest-created) conversation, so this
+ // write carries the correct "latest-created" semantics. It is
+ // slow-path-only by construction (the fast path sets convId =
+ // targetConvId and never falls through here), so no `!targetConvId`
+ // gate is needed.
+ setLastOpenConversation(
+ agentId,
+ activeChannel,
+ {
+ conversation_id: data.conversation.id,
+ newestMessageId:
+ data.messages.length > 0
+ ? data.messages[data.messages.length - 1].id
+ : null,
+ // chatInit returns no server total; data.messages is only the first
+ // page. When more pages exist, the count is unknown — store 0, which
+ // the read site treats as "unknown" and omits from the freshness
+ // compare (relying on newestMessageId instead). Storing the partial
+ // page length would otherwise force a needless full merge next open.
+ serverMessageCount: data.has_more_messages
+ ? 0
+ : data.messages.length,
+ },
+ workspaceId,
+ ).catch(() => { });
+ if (hasCachedMessages && initialScrollDone.current && wasNearBottom) {
+ scrollToBottom();
+ }
+ listFlaggedMessageIds(workspaceId, data.conversation.id)
+ .then((r) => {
+ if (!ignore) setFlaggedIds(new Set(r.message_ids));
+ })
+ .catch(() => { });
+ if (data.active_task) {
+ setActiveTask(data.active_task);
+ if (data.task_messages.length > 0) {
+ setTaskMessages(data.task_messages);
+ lastSeqRef.current = Math.max(
+ ...data.task_messages.map((m) => m.seq),
+ );
+ }
+ if (
+ !["completed", "failed", "cancelled", "superseded"].includes(
+ data.active_task.status,
+ )
+ ) {
+ startPollingRef.current?.(
+ data.active_task.id,
+ data.conversation.id,
+ lastSeqRef.current,
+ );
+ }
+ }
+ }
+ } catch {
+ if (!hasCachedMessages) {
+ toast.error("Failed to load conversation");
+ } else {
+ toast.error("Couldn't refresh conversation");
+ }
+ } finally {
+ if (!ignore) {
+ setMessagesLoading(false);
+ // Mark this fast-path identity as completed only now, so a re-fire
+ // caused purely by a channel-dep change is deduped (TODO 6) — while a
+ // run cancelled before reaching here leaves no marker, letting the
+ // successor run take over and clear the skeleton.
+ markFastLoadCompleted(fastKey, fastLoadGateRef.current);
+ }
+ }
+ }
+ load();
+ return () => {
+ ignore = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ agentId,
+ workspaceId,
+ targetConvId,
+ scrollToTaskId,
+ activeChannel,
+ channelLoading,
+ ]);
+
+ const refreshInboxCountRef = useRef(refreshInboxCount);
+ useEffect(() => {
+ refreshInboxCountRef.current = refreshInboxCount;
+ }, [refreshInboxCount]);
+
+ const markedReadRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (!conversation?.id || !workspaceId) return;
+ if (markedReadRef.current === conversation.id) return;
+ markedReadRef.current = conversation.id;
+ const timer = setTimeout(() => {
+ markInboxRead(conversation.id, workspaceId)
+ .then(() => refreshInboxCountRef.current())
+ .catch(() => { });
+ }, 1000);
+ return () => {
+ markedReadRef.current = null;
+ clearTimeout(timer);
+ };
+ }, [conversation?.id, workspaceId]);
+
+ // Scroll to bottom on initial load (skip if scroll-to-task/message is active)
+ useEffect(() => {
+ if (!messagesLoading && messages.length > 0 && !initialScrollDone.current) {
+ initialScrollDone.current = true;
+ if (scrollToTaskId || scrollToMessageId) {
+ isNearBottom.current = false;
+ } else if (propTargetConvId) {
+ setTimeout(() => {
+ const assistantMsgs = scrollRef.current?.querySelectorAll(
+ "[data-quote-source]",
+ );
+ if (assistantMsgs && assistantMsgs.length > 0) {
+ const lastAssistant = assistantMsgs[assistantMsgs.length - 1];
+ lastAssistant.scrollIntoView({
+ behavior: "instant",
+ block: "start",
+ });
+ } else {
+ scrollRef.current?.scrollTo({
+ top: scrollRef.current.scrollHeight,
+ });
+ }
+ }, 50);
+ } else {
+ setTimeout(() => {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
+ }, 50);
+ }
+ }
+ }, [
+ messagesLoading,
+ messages.length,
+ scrollToTaskId,
+ scrollToMessageId,
+ propTargetConvId,
+ ]);
+
+ // Scroll to task when ?task= param is present
+ useEffect(() => {
+ if (!scrollToTaskId || messagesLoading || !conversation) return;
+ isNearBottom.current = false;
+ scrollTargetActiveRef.current = true;
+ let cancelled = false;
+ let highlightTimerId: ReturnType<typeof setTimeout> | undefined;
+ const tryScroll = () => {
+ if (cancelled) return false;
+ const el = document.querySelector(
+ `[data-task-id="${CSS.escape(scrollToTaskId)}"]`,
+ );
+ if (!el) return false;
+ el.scrollIntoView({ behavior: "smooth", block: "start" });
+ el.classList.add("task-highlight");
+ highlightTimerId = setTimeout(() => {
+ el.classList.remove("task-highlight");
+ if (!cancelled) scrollTargetActiveRef.current = false;
+ }, 1500);
+ return true;
+ };
+ const timerId = setTimeout(async () => {
+ if (cancelled) return;
+ if (tryScroll()) return;
+ try {
+ const around = await listMessagesAroundTask(
+ conversation.id,
+ workspaceId,
+ scrollToTaskId,
+ );
+ if (cancelled) return;
+ if (around.length > 0) {
+ setMessages((prev) => mergeMessages(prev, around));
+ requestAnimationFrame(() => {
+ setTimeout(() => {
+ if (!tryScroll()) {
+ scrollTargetActiveRef.current = false;
+ }
+ }, 100);
+ });
+ } else {
+ scrollTargetActiveRef.current = false;
+ }
+ } catch {
+ if (!cancelled) scrollTargetActiveRef.current = false;
+ }
+ }, 100);
+ return () => {
+ cancelled = true;
+ clearTimeout(timerId);
+ if (highlightTimerId) clearTimeout(highlightTimerId);
+ };
+ }, [scrollToTaskId, messagesLoading, conversation, workspaceId]);
+
+ // Scroll to message when ?msg= param is present (skip if task scroll is active)
+ useEffect(() => {
+ if (
+ !scrollToMessageId ||
+ scrollToTaskId ||
+ messagesLoading ||
+ !conversation
+ )
+ return;
+ isNearBottom.current = false;
+ scrollTargetActiveRef.current = true;
+ let cancelled = false;
+ let highlightTimerId: ReturnType<typeof setTimeout> | undefined;
+ const tryScroll = () => {
+ if (cancelled) return false;
+ const el = document.querySelector(
+ `[data-message-id="${CSS.escape(scrollToMessageId)}"]`,
+ );
+ if (!el) return false;
+ el.scrollIntoView({ behavior: "smooth", block: "start" });
+ el.classList.add("task-highlight");
+ highlightTimerId = setTimeout(() => {
+ el.classList.remove("task-highlight");
+ if (!cancelled) scrollTargetActiveRef.current = false;
+ }, 1500);
+ return true;
+ };
+ const timerId = setTimeout(() => {
+ if (cancelled) return;
+ if (!tryScroll()) {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
+ scrollTargetActiveRef.current = false;
+ }
+ }, 100);
+ return () => {
+ cancelled = true;
+ clearTimeout(timerId);
+ if (highlightTimerId) clearTimeout(highlightTimerId);
+ };
+ }, [scrollToMessageId, scrollToTaskId, messagesLoading, conversation]);
+
+ // Auto-scroll when task badge appears or new task steps arrive
+ const taskStatus = activeTask?.status;
+ useEffect(() => {
+ if (scrollTargetActiveRef.current) return;
+ const isRunning = taskStatus === "running" || taskStatus === "queued";
+ if (isRunning && isNearBottom.current) {
+ scrollToBottom();
+ }
+ }, [taskMessages.length, taskStatus, scrollToBottom]);
+
+ // Auto-scroll when a new agent-side item lands while the user is at the
+ // bottom — covers artifact (file) cards and event cards, which grow the
+ // thread via setArtifacts / setMessages without otherwise nudging scroll.
+ // (Previously only message text scrolled; cards appeared off-screen until the
+ // next message arrived.)
+ useEffect(() => {
+ if (scrollTargetActiveRef.current) return;
+ if (!initialScrollDone.current) return;
+ if (isNearBottom.current) scrollToBottom();
+ }, [artifacts.length, messages.length, scrollToBottom]);
+
+ const agentName = useMemo(
+ () => agents.find((a) => a.id === agentId)?.name ?? "Agent",
+ [agents, agentId],
+ );
+
+ const messagesRef = useLatest(messages);
+ const hasMoreRef = useLatest(hasMore);
+ const prevConvsRef = useLatest(previousConversations);
+ const hasMoreConvsRef = useLatest(hasMoreConversations);
+ const agentNameRef = useLatest(agentName);
+ const activeChannelRef = useLatest(activeChannel);
+
+ const loadOlderMessages = useCallback(
+ async (scrollToEnd = false) => {
+ if (!conversation || loadingMoreRef.current) return;
+ loadingMoreRef.current = true;
+
+ const currentMessages = messagesRef.current;
+ const currentHasMore = hasMoreRef.current;
+ const currentHasMoreConvs = hasMoreConvsRef.current;
+ const currentAgentName = agentNameRef.current;
+ const currentChannel = activeChannelRef.current;
+ const isSingleConvView = !!targetConvId;
+
+ const oldest = currentMessages[0];
+ const paginatingConvId =
+ oldestConversationCursorRef.current?.id ?? conversation.id;
+ const canLoadMoreInConv = currentHasMore && oldest;
+ let prevConvsList = prevConvsRef.current;
+
+ if (
+ !isSingleConvView &&
+ !canLoadMoreInConv &&
+ prevConvsList.length === 0 &&
+ currentHasMoreConvs
+ ) {
+ const oldestConv = oldestConversationCursorRef.current ?? {
+ id: conversation.id,
+ created_at: conversation.created_at,
+ };
+ try {
+ const result = await listPreviousConversations(agentId, workspaceId, {
+ exclude: conversation.id,
+ before: oldestConv.created_at,
+ channel: currentChannel,
+ });
+ prevConvsList = result.conversations;
+ setPreviousConversations(result.conversations);
+ setHasMoreConversations(result.has_more);
+ } catch {
+ setHasMoreConversations(false);
+ }
+ }
+
+ const canLoadPrevConv = !isSingleConvView && prevConvsList.length > 0;
+
+ if (!canLoadMoreInConv && !canLoadPrevConv) {
+ loadingMoreRef.current = false;
+ return;
+ }
+
+ setLoadingMore(true);
+ const el = scrollRef.current;
+ if (el) el.style.overflowAnchor = "none";
+ const prevScrollHeight = el?.scrollHeight ?? 0;
+
+ try {
+ let phase1Messages: Message[] = [];
+ let phase2Messages: Message[] = [];
+ let remaining = MESSAGE_LIMIT;
+ let lastHasMore = false;
+ const napMarkersToAdd: {
+ agentName: string;
+ created_at: string;
+ id: string;
+ }[] = [];
+
+ // --- Phase 1: Load from current/paginating conversation ---
+ let phase1HasMore = false;
+ if (canLoadMoreInConv) {
+ const cached =
+ paginatingConvId === conversation.id
+ ? await getCachedMessagesBefore(
+ paginatingConvId,
+ oldest!.created_at,
+ oldest!.id,
+ MESSAGE_LIMIT,
+ workspaceId,
+ )
+ : null;
+
+ if (cached) {
+ phase1Messages = cached.messages;
+ remaining -= cached.messages.length;
+ lastHasMore = cached.hasMore;
+ } else {
+ const result = await listMessages(paginatingConvId, workspaceId, {
+ limit: MESSAGE_LIMIT,
+ before: oldest!.created_at,
+ beforeId: oldest!.id,
+ });
+ phase1Messages = result.messages;
+ remaining -= result.messages.length;
+ lastHasMore = result.has_more;
+ }
+ phase1HasMore = lastHasMore;
+ }
+
+ // --- Phase 2: Load from previous conversations (only in timeline mode) ---
+ if (!isSingleConvView && !lastHasMore && remaining > 0) {
+ if (prevConvsList.length === 0 && currentHasMoreConvs) {
+ const oldestConv = oldestConversationCursorRef.current ?? {
+ id: conversation.id,
+ created_at: conversation.created_at,
+ };
+ try {
+ const result = await listPreviousConversations(
+ agentId,
+ workspaceId,
+ {
+ exclude: conversation.id,
+ before: oldestConv.created_at,
+ channel: currentChannel,
+ },
+ );
+ prevConvsList = result.conversations;
+ setPreviousConversations(result.conversations);
+ setHasMoreConversations(result.has_more);
+ } catch {
+ setHasMoreConversations(false);
+ }
+ }
+
+ let consumed = 0;
+ let fetchCount = 0;
+
+ while (
+ consumed < prevConvsList.length &&
+ remaining > 0 &&
+ fetchCount < MAX_CONV_FETCHES_PER_CLICK
+ ) {
+ const prevConv = prevConvsList[consumed]!;
+ consumed++;
+ fetchCount++;
+ const result = await listMessages(prevConv.id, workspaceId, {
+ limit: remaining,
+ });
+
+ if (result.messages.length === 0) {
+ oldestConversationCursorRef.current = prevConv;
+ continue;
+ }
+
+ const napTs =
+ oldestConversationCursorRef.current?.created_at ??
+ conversation.created_at;
+ napMarkersToAdd.push({
+ agentName: currentAgentName,
+ created_at: napTs,
+ id: `nap-${prevConv.id}`,
+ });
+
+ phase2Messages = [...result.messages, ...phase2Messages];
+ remaining -= result.messages.length;
+ lastHasMore = result.has_more;
+ oldestConversationCursorRef.current = prevConv;
+ }
+
+ if (consumed > 0) {
+ setPreviousConversations((prev) => prev.slice(consumed));
+ }
+ }
+
+ // --- Final state update ---
+ const allNewMessages = [...phase2Messages, ...phase1Messages];
+ flushSync(() => {
+ if (allNewMessages.length > 0) {
+ if (napMarkersToAdd.length > 0) {
+ setNapMarkers((prev) => {
+ const existingIds = new Set(prev.map((m) => m.id));
+ const newMarkers = napMarkersToAdd.filter(
+ (m) => !existingIds.has(m.id),
+ );
+ return [...prev, ...newMarkers];
+ });
+ }
+ setHasMore(lastHasMore);
+ setMessages((prev) => {
+ const existingIds = new Set(prev.map((m) => m.id));
+ const unique = allNewMessages.filter(
+ (m) => !existingIds.has(m.id),
+ );
+ return [...unique, ...prev];
+ });
+ } else {
+ setHasMore(false);
+ }
+ });
+
+ if (allNewMessages.length > 0 && conversation) {
+ const currentConvMessages = allNewMessages.filter(
+ (m) => m.conversation_id === conversation.id,
+ );
+ if (currentConvMessages.length > 0) {
+ mergeCachedMessages(
+ conversation.id,
+ currentConvMessages,
+ phase1HasMore,
+ workspaceId,
+ ).catch(() => { });
+ }
+ }
+
+ loadingMoreRef.current = false;
+ flushSync(() => setLoadingMore(false));
+
+ if (el) {
+ if (scrollToEnd) {
+ el.scrollTop = el.scrollHeight;
+ } else {
+ const newScrollHeight = el.scrollHeight;
+ el.scrollTop = newScrollHeight - prevScrollHeight;
+ }
+ }
+ } catch {
+ toast.error("Failed to load older messages");
+ } finally {
+ loadingMoreRef.current = false;
+ setLoadingMore(false);
+ if (scrollRef.current) scrollRef.current.style.overflowAnchor = "";
+ }
+ },
+ [
+ conversation,
+ workspaceId,
+ agentId,
+ targetConvId,
+ messagesRef,
+ hasMoreRef,
+ hasMoreConvsRef,
+ agentNameRef,
+ activeChannelRef,
+ prevConvsRef,
+ ],
+ );
+
+ const canLoadMore = targetConvId
+ ? hasMore
+ : hasMore || previousConversations.length > 0 || hasMoreConversations;
+
+ useEffect(() => {
+ if (conversation?.id === prevConversationIdRef.current) return;
+ prevConversationIdRef.current = conversation?.id;
+ backfillAttemptsRef.current = 0;
+ }, [conversation?.id]);
+
+ const MIN_MESSAGES = 10;
+ useEffect(() => {
+ if (messagesLoading || !conversation) return;
+ if (scrollToTaskId || targetConvId) return;
+ if (messages.length >= MIN_MESSAGES || !canLoadMore) return;
+ if (loadingMore) return;
+ if (backfillAttemptsRef.current >= 3) return;
+ backfillAttemptsRef.current += 1;
+ loadOlderMessages(true);
+ }, [
+ messagesLoading,
+ messages.length,
+ canLoadMore,
+ loadingMore,
+ conversation,
+ loadOlderMessages,
+ scrollToTaskId,
+ targetConvId,
+ ]);
+
+ const handleScroll = useCallback(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ isNearBottom.current =
+ el.scrollHeight - el.scrollTop - el.clientHeight < 100;
+ }, []);
+
+ const startPolling = useCallback(
+ (taskId: string, conversationId: string, initialSeq?: number) => {
+ if (pollRef.current) clearInterval(pollRef.current);
+ lastSeqRef.current = initialSeq ?? 0;
+ pollFailures.current = 0;
+ setConnectionLost(false);
+ pollTaskIdRef.current = taskId;
+
+ pollRef.current = setInterval(async () => {
+ // A new poll was started (e.g. by a steering task) — bail out
+ if (pollTaskIdRef.current !== taskId) return;
+
+ try {
+ // Thin status-only poll: fetch only task status/error as a resilience
+ // fallback for a dropped WebSocket. Replies arrive via `send-dm` ->
+ // `conversation.message`, and live errors via the `task.messages` WS
+ // (filtered to errors-only) — the poll no longer fetches task_messages.
+ const task = await getTask(taskId, workspaceId);
+
+ // Re-check after await — a steering task may have started a new poll
+ const isStale = pollTaskIdRef.current !== taskId;
+
+ pollFailures.current = 0;
+ setConnectionLost(false);
+
+ if (
+ task.status === "completed" ||
+ task.status === "failed" ||
+ task.status === "cancelled" ||
+ task.status === "superseded"
+ ) {
+ if (isStale) {
+ // Stale poll — still merge messages but don't touch activeTask or polling
+ listMessages(conversationId, workspaceId)
+ .then(({ messages: latest }) => {
+ setMessages((prev) => mergeMessages(prev, latest));
+ mergeCachedMessages(
+ conversationId,
+ latest,
+ null,
+ workspaceId,
+ ).catch(() => { });
+ })
+ .catch(() => { });
+ return;
+ }
+
+ if (pollRef.current) clearInterval(pollRef.current);
+ pollRef.current = null;
+
+ if (markReadTimerRef.current)
+ clearTimeout(markReadTimerRef.current);
+ markReadTimerRef.current = setTimeout(() => {
+ markInboxRead(conversationId, workspaceId)
+ .then(() => refreshInboxCountRef.current())
+ .catch(() => { });
+ }, 1000);
+
+ const shouldScroll =
+ !scrollTargetActiveRef.current && isNearBottom.current;
+ try {
+ const [latestResult, arts] = await Promise.all([
+ listMessages(conversationId, workspaceId),
+ listArtifacts(conversationId, workspaceId).catch(() => null),
+ ]);
+ setMessages((prev) => mergeMessages(prev, latestResult.messages));
+ mergeCachedMessages(
+ conversationId,
+ latestResult.messages,
+ null,
+ workspaceId,
+ ).catch(() => { });
+ if (arts) {
+ setArtifacts(arts);
+ // Full-replace persist of the authoritative post-task artifacts
+ // so the cache stays consistent with what's rendered.
+ persistArtifactsToCache(conversationId, arts);
+ }
+ setActiveTask(task);
+ } catch {
+ setActiveTask(task);
+ toast.error("Failed to refresh messages");
+ }
+ if (shouldScroll) {
+ requestAnimationFrame(() => {
+ scrollRef.current?.scrollTo({
+ top: scrollRef.current.scrollHeight,
+ behavior: "smooth",
+ });
+ });
+ }
+
+ // Fallback: if a steering task superseded this one but the
+ // WebSocket message was lost, detect the new active task via API.
+ setTimeout(async () => {
+ if (pollRef.current) return;
+ try {
+ const nextTask = await getActiveTask(
+ conversationId,
+ workspaceId,
+ );
+ if (nextTask && nextTask.id !== taskId) {
+ const { messages: latestMsgs } = await listMessages(
+ conversationId,
+ workspaceId,
+ );
+ setMessages((prev) => mergeMessages(prev, latestMsgs));
+ mergeCachedMessages(
+ conversationId,
+ latestMsgs,
+ null,
+ workspaceId,
+ ).catch(() => { });
+ setActiveTask(nextTask);
+ setTaskMessages([]);
+ startPollingRef.current?.(nextTask.id, conversationId);
+ }
+ } catch { }
+ }, 1000);
+ } else if (!isStale) {
+ setActiveTask(task);
+ }
+ } catch {
+ if (pollTaskIdRef.current !== taskId) return;
+ pollFailures.current += 1;
+ if (pollFailures.current >= 3) {
+ setConnectionLost(true);
+ }
+ if (pollFailures.current >= 10) {
+ if (pollRef.current) clearInterval(pollRef.current);
+ pollRef.current = null;
+ toast.error("Lost connection to agent");
+ }
+ }
+ }, 3000);
+ },
+ [workspaceId],
+ );
+ useEffect(() => {
+ startPollingRef.current = startPolling;
+ }, [startPolling]);
+
+ useEffect(() => {
+ return () => {
+ if (pollRef.current) clearInterval(pollRef.current);
+ if (markReadTimerRef.current) clearTimeout(markReadTimerRef.current);
+ };
+ }, []);
+
+ const activeTaskIdRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ activeTaskIdRef.current = activeTask?.id ?? null;
+ }, [activeTask]);
+
+ useEffect(() => {
+ return subscribeWs((msg: WsMessage) => {
+ if (
+ msg.type === "task.messages" &&
+ msg.taskId === activeTaskIdRef.current
+ ) {
+ const incoming = msg.messages.filter((m) => m.seq > lastSeqRef.current);
+ if (incoming.length > 0) {
+ // Thinking is no longer rendered — the reply lands via `send-dm`. Keep
+ // ONLY `type:"error"` items: they are a live error channel (opencode /
+ // codex emit them mid-run, sometimes without the task transitioning to
+ // failed) and dropping them would hide real failures.
+ const errorsOnly = incoming.filter((m) => m.type === "error");
+ if (errorsOnly.length > 0) {
+ setTaskMessages((prev) => {
+ const existingSeqs = new Set(prev.map((m) => m.seq));
+ const unique = errorsOnly.filter((m) => !existingSeqs.has(m.seq));
+ return unique.length > 0 ? [...prev, ...unique] : prev;
+ });
+ }
+ // Advance the cursor past every seq we've seen (incl. dropped
+ // thinking) so we never reconsider them.
+ lastSeqRef.current = Math.max(
+ ...incoming.map((m) => m.seq),
+ lastSeqRef.current,
+ );
+ }
+ }
+ if (
+ msg.type === "task.created" &&
+ msg.conversationId === conversation?.id
+ ) {
+ listMessages(msg.conversationId, workspaceId)
+ .then(({ messages: latest }) => {
+ setMessages((prev) => mergeMessages(prev, latest));
+ mergeCachedMessages(
+ msg.conversationId,
+ latest,
+ null,
+ workspaceId,
+ ).catch(() => { });
+ })
+ .catch(() => { });
+ const task = msg.task as Task;
+ activeTaskIdRef.current = task.id;
+ setActiveTask(task);
+ setTaskMessages([]);
+ lastSeqRef.current = 0;
+ startPollingRef.current?.(task.id, msg.conversationId);
+ }
+ // Refresh the per-channel `last_open` pointer when a `task.created`
+ // arrives — this is the client learning of a (possibly newer) conversation
+ // for this agent+channel in real time, keeping the pointer's
+ // "latest-created" semantics fresh while the user is on the page. Runs
+ // independently of the active-conversation block above: a new thread spawned
+ // in this channel often has a different conversationId than the one being
+ // viewed, so it must NOT be gated on `msg.conversationId === conversation?.id`.
+ // `activeChannelRef` is read (not `activeChannel`) because this effect does
+ // not re-subscribe on channel change — the ref always holds the current value.
+ if (msg.type === "task.created") {
+ const task = msg.task as Task;
+ const activeChannel = activeChannelRef.current;
+ getLastOpenConversation(agentId, activeChannel, workspaceId)
+ .then((current) => {
+ const targetConvId = pointerRefreshTargetForTaskCreated({
+ task,
+ agentId,
+ activeChannel,
+ currentPointerConvId: current?.conversation_id ?? null,
+ });
+ if (!targetConvId) return;
+ // A1: derive serverMessageCount from the locally-cached count for
+ // this conversation. May under-count (e.g. brand-new thread with no
+ // cache → 0), which only makes the next slow-path read fall back to
+ // the skeleton (the `serverMessageCount > 0` gate) — never wrong
+ // content. We never over-count, so the pointer can't claim a
+ // conversation is more complete than it is.
+ return getCacheMeta(targetConvId, workspaceId).then((meta) =>
+ setLastOpenConversation(
+ agentId,
+ activeChannel,
+ {
+ conversation_id: targetConvId,
+ newestMessageId: meta?.newestMessageId ?? null,
+ serverMessageCount: meta?.messageCount ?? 0,
+ },
+ workspaceId,
+ ),
+ );
+ })
+ .catch(() => { });
+ }
+ if (msg.type === "conversation.message") {
+ // Only cache for the server-confirmed loaded conversation — never write
+ // during the optimistic cache-first window before the id is confirmed
+ // (review #1).
+ if (msg.conversationId === loadConvIdRef.current) {
+ appendCachedMessage(
+ msg.conversationId,
+ msg.message,
+ workspaceId,
+ ).catch(() => { });
+ }
+ if (msg.conversationId === conversation?.id) {
+ setMessages((prev) => {
+ const incomingTime = new Date(msg.message.created_at).getTime();
+ const optimisticIdx = prev.findIndex(
+ (m) =>
+ m.id.startsWith("temp-") &&
+ m.role === msg.message.role &&
+ m.content === msg.message.content &&
+ Math.abs(new Date(m.created_at).getTime() - incomingTime) <
+ 2000,
+ );
+ if (optimisticIdx !== -1) {
+ const updated = [...prev];
+ updated[optimisticIdx] = msg.message;
+ return updated;
+ }
+ return mergeMessages(prev, [msg.message]);
+ });
+ }
+ }
+ if (
+ msg.type === "task.updated" &&
+ msg.taskId === activeTaskIdRef.current
+ ) {
+ setActiveTask((prev) =>
+ prev ? { ...prev, status: msg.status } : prev,
+ );
+ }
+ if (
+ msg.type === "artifact.uploaded" &&
+ msg.conversationId === conversation?.id
+ ) {
+ setArtifacts((prev) => {
+ if (prev.some((a) => a.id === msg.artifact.id)) return prev;
+ const next = [...prev, msg.artifact];
+ // Persist the appended artifact to the cached card metadata so it
+ // renders instantly on the next open. Dedupe by id is handled above
+ // (we only reach here for a genuinely new artifact). Guarded inside
+ // `persistArtifactsToCache` on `loadConvIdRef`. The persist is an
+ // idempotent fire-and-forget read-modify-write, so the Strict-Mode
+ // dev double-invoke just writes the same row twice — harmless.
+ persistArtifactsToCache(msg.conversationId, next);
+ return next;
+ });
+ }
+ });
+ }, [subscribeWs, conversation?.id, workspaceId, agentId, persistArtifactsToCache]);
+
+ useEffect(() => {
+ return subscribeReconnect(() => {
+ if (!conversation?.id) return;
+ getCacheMeta(conversation.id, workspaceId).then((meta) => {
+ conversationInit(conversation.id, workspaceId, {
+ newestMessageId: meta?.newestMessageId ?? undefined,
+ messageCount: meta?.serverMessageCount ?? undefined,
+ })
+ .then((data) => {
+ if (!data.cache_valid && data.messages) {
+ setMessages((prev) => mergeMessages(prev, data.messages!));
+ writeToCacheRef
+ .current(
+ data.messages,
+ data.has_more_messages,
+ data.message_count,
+ )
+ .catch(() => { });
+ }
+ })
+ .catch(() => { });
+ });
+ });
+ }, [subscribeReconnect, conversation?.id, workspaceId]);
+
+ const handleSend = async () => {
+ const rawContent = inputRef.current.trim();
+ if ((!rawContent && pendingFilesRef.current.length === 0) || sending || !conversation)
+ return;
+ if (!rawContent) {
+ toast.error("Please type a message");
+ return;
+ }
+
+ // Prepend quoted text as blockquote if present
+ let content = quotedTextRef.current
+ ? `> ${quotedTextRef.current.split("\n").join("\n> ")}\n\n${rawContent}`
+ : rawContent;
+
+ // Prepend skill instruction if active
+ if (activeSkillRef.current) {
+ content = `/${activeSkillRef.current.name} ${content}`;
+ }
+
+ const filesToSend = [...pendingFilesRef.current];
+ setInput("");
+ setPendingFiles([]);
+ setQuotedText(null);
+ clearActiveSkill();
+ setSending(true);
+
+ // Every send goes through the same enqueue-and-steer path: POST /messages
+ // enqueues a real task carrying contextKey=conversationId, so when a task
+ // is already running the daemon supersedes it (steering). No client-side
+ // buffering — sending while busy just drops a new bubble and steers.
+ const optimisticId = `temp-${Date.now()}`;
+ const optimistic: Message = {
+ id: optimisticId,
+ conversation_id: conversation.id,
+ role: "user",
+ content,
+ task_id: null,
+ attachment_ids: null,
+ created_at: new Date().toISOString(),
+ };
+
+ // Store pending files for the optimistic message rendering
+ if (filesToSend.length > 0) {
+ setPendingFilesByMessage((prev) => {
+ const next = new Map(prev);
+ next.set(optimisticId, filesToSend);
+ return next;
+ });
+ }
+
+ setMessages((prev) => [...prev, optimistic]);
+ scrollToBottom();
+
+ try {
+ const { message, task } = await sendMessage(
+ conversation.id,
+ content,
+ workspaceId,
+ filesToSend.length > 0 ? filesToSend : undefined,
+ );
+ // Clean up pending files ref
+ setPendingFilesByMessage((prev) => {
+ if (!prev.has(optimisticId)) return prev;
+ const next = new Map(prev);
+ next.delete(optimisticId);
+ return next;
+ });
+ setMessages((prev) => {
+ const hasOptimistic = prev.some((m) => m.id === optimistic.id);
+ if (!hasOptimistic) {
+ const hasReal = prev.some((m) => m.id === message.id);
+ return hasReal ? prev : sortMessages([...prev, message]);
+ }
+ const without = prev.filter(
+ (m) => m.id !== optimistic.id && m.id !== message.id,
+ );
+ return sortMessages([...without, message]);
+ });
+ appendCachedMessage(conversation.id, message, workspaceId).catch(
+ () => { },
+ );
+ if (message.attachment_ids && message.attachment_ids.length > 0) {
+ const convId = conversation.id;
+ listArtifacts(convId, workspaceId)
+ .then((arts) => {
+ setArtifacts(arts);
+ // Keep the cached card metadata consistent with the artifacts shown
+ // after a send-with-attachments refresh (full replace).
+ persistArtifactsToCache(convId, arts);
+ })
+ .catch(() => { });
+ }
+ setActiveTask(task);
+ setTaskMessages([]);
+ startPolling(task.id, conversation.id);
+ } catch {
+ // Keep the optimistic bubble in place and surface an inline
+ // "Not delivered · tap to retry" affordance instead of a toast (Priya).
+ setFailedSends((prev) => {
+ const next = new Map(prev);
+ next.set(optimisticId, { content, files: filesToSend });
+ return next;
+ });
+ } finally {
+ setSending(false);
+ composerRef.current?.focus();
+ }
+ };
+
+ // Resend a failed optimistic message: drop the dead bubble + its failed state,
+ // then run the normal send with the stored content/files.
+ const handleRetrySend = useCallback(
+ (messageId: string) => {
+ const failed = failedSends.get(messageId);
+ if (!failed || !conversation || sending) return;
+
+ setFailedSends((prev) => {
+ const next = new Map(prev);
+ next.delete(messageId);
+ return next;
+ });
+ setMessages((prev) => prev.filter((m) => m.id !== messageId));
+ setPendingFilesByMessage((prev) => {
+ if (!prev.has(messageId)) return prev;
+ const next = new Map(prev);
+ next.delete(messageId);
+ return next;
+ });
+ setSending(true);
+
+ const optimisticId = `temp-${Date.now()}`;
+ const optimistic: Message = {
+ id: optimisticId,
+ conversation_id: conversation.id,
+ role: "user",
+ content: failed.content,
+ task_id: null,
+ attachment_ids: null,
+ created_at: new Date().toISOString(),
+ };
+ if (failed.files.length > 0) {
+ setPendingFilesByMessage((prev) => {
+ const next = new Map(prev);
+ next.set(optimisticId, failed.files);
+ return next;
+ });
+ }
+ setMessages((prev) => [...prev, optimistic]);
+
+ sendMessage(
+ conversation.id,
+ failed.content,
+ workspaceId,
+ failed.files.length > 0 ? failed.files : undefined,
+ )
+ .then(({ message, task }) => {
+ setPendingFilesByMessage((prev) => {
+ if (!prev.has(optimisticId)) return prev;
+ const next = new Map(prev);
+ next.delete(optimisticId);
+ return next;
+ });
+ setMessages((prev) => {
+ const without = prev.filter(
+ (m) => m.id !== optimisticId && m.id !== message.id,
+ );
+ return sortMessages([...without, message]);
+ });
+ appendCachedMessage(conversation.id, message, workspaceId).catch(
+ () => { },
+ );
+ setActiveTask(task);
+ setTaskMessages([]);
+ startPolling(task.id, conversation.id);
+ })
+ .catch(() => {
+ setFailedSends((prev) => {
+ const next = new Map(prev);
+ next.set(optimisticId, failed);
+ return next;
+ });
+ })
+ .finally(() => {
+ setSending(false);
+ });
+ },
+ [failedSends, conversation, sending, workspaceId, startPolling],
+ );
+
+ const handleRetryTask = useCallback(async () => {
+ if (!activeTask || !conversation) return;
+ const newTask = await retryTask(activeTask.id, workspaceId);
+ setActiveTask(newTask);
+ setTaskMessages([]);
+ startPolling(newTask.id, conversation.id);
+ }, [activeTask, conversation, workspaceId, startPolling]);
+
+ const [napping, setNapping] = useState(false);
+
+ const currentConvHasMessages = useMemo(
+ () =>
+ !!conversation &&
+ messages.some((m) => m.conversation_id === conversation.id),
+ [conversation, messages],
+ );
+
+ const handleNap = async () => {
+ if (!conversation || !currentConvHasMessages || napping) return;
+ setNapping(true);
+ try {
+ if (pollRef.current) {
+ clearInterval(pollRef.current);
+ pollRef.current = null;
+ }
+ const newConv = await createConversation(
+ agentId,
+ workspaceId,
+ activeChannel,
+ );
+
+ setNapMarkers((prev) => [
+ ...prev,
+ {
+ agentName,
+ created_at: newConv.created_at,
+ id: `nap-${conversation.id}`,
+ },
+ ]);
+
+ setPreviousConversations((prev) => [
+ { id: conversation.id, created_at: conversation.created_at },
+ ...prev,
+ ]);
+
+ setConversation(newConv);
+ setActiveTask(null);
+ setTaskMessages([]);
+ setArtifacts([]);
+ setPendingFiles([]);
+ setPendingFilesByMessage(new Map());
+ setFailedSends(new Map());
+ lastSeqRef.current = 0;
+ setConnectionLost(false);
+ setHasMore(false);
+ oldestConversationCursorRef.current = null;
+
+ scrollToBottom();
+ } catch {
+ toast.error("Failed to start new conversation");
+ } finally {
+ setNapping(false);
+ }
+ };
+
+ return {
+ // hook-owned state
+ conversation,
+ messages,
+ sending,
+ activeTask,
+ taskMessages,
+ messagesLoading,
+ connectionLost,
+ hasMore,
+ loadingMore,
+ artifacts,
+ previousConversations,
+ hasMoreConversations,
+ napMarkers,
+ napping,
+ pendingFilesByMessage,
+ failedSends,
+ // derived
+ agentArtifacts,
+ agentName,
+ timeline,
+ groupPositions,
+ activeTaskStreamMsgId,
+ canLoadMore,
+ currentConvHasMessages,
+ // refs shared with the JSX
+ scrollRef,
+ composerRef,
+ // handlers
+ loadOlderMessages,
+ handleScroll,
+ handleSend,
+ handleRetrySend,
+ handleRetryTask,
+ handleNap,
+ scrollToBottom,
+ };
+}
diff --git a/src/web/src/hooks/use-chat-sheets.ts b/src/web/src/hooks/use-chat-sheets.ts
new file mode 100644
index 000000000..351453727
--- /dev/null
+++ b/src/web/src/hooks/use-chat-sheets.ts
@@ -0,0 +1,115 @@
+import { useCallback, useState } from "react";
+import { toast } from "sonner";
+import type {
+ Artifact,
+ Issue,
+ IssueComment,
+ Message,
+ TaskApi as Task,
+} from "@alook/shared";
+import { getIssue, getTask, getTrace } from "@/lib/api";
+import type { TraceTask } from "@/lib/api";
+
+export type IssueDetail = {
+ issue: Issue & { trace_id?: string | null };
+ messages: Message[];
+ comments: IssueComment[];
+ artifacts: Artifact[];
+} | null;
+
+/**
+ * Owns the chat view's detail-sheet state: the artifact / email / calendar /
+ * issue sheets (open flags + selected ids), the loaded issue detail (+ trace +
+ * active task + loading), and the `openIssue` loader.
+ *
+ * Extracted verbatim from agent-chat-view.tsx. NOTE: the issue-sheet WebSocket
+ * effect is intentionally LEFT IN the component — moving it into this hook
+ * (called early, where the sheet state must live) would register its effect out
+ * of order (it is currently the LAST effect, #26 in the canonical order), which
+ * would change effect timing. To preserve order exactly, the effect stays in
+ * the component and reads this hook's returned state/setters. The hook only
+ * exposes the state + `openIssue`; behavior is unchanged.
+ */
+export function useChatSheets(workspaceId: string) {
+ const [artifactSheetOpen, setArtifactSheetOpen] = useState(false);
+ const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(
+ null,
+ );
+ const [emailSheetOpen, setEmailSheetOpen] = useState(false);
+ const [selectedEmailId, setSelectedEmailId] = useState<string | null>(null);
+ const [calendarEventSheetOpen, setCalendarEventSheetOpen] = useState(false);
+ const [selectedCalendarEventId, setSelectedCalendarEventId] = useState<
+ string | null
+ >(null);
+ const [issueSheetOpen, setIssueSheetOpen] = useState(false);
+ const [selectedIssueId, setSelectedIssueId] = useState<string | null>(null);
+ const [issueDetail, setIssueDetail] = useState<IssueDetail>(null);
+ const [issueDetailLoading, setIssueDetailLoading] = useState(false);
+ const [issueTraceTasks, setIssueTraceTasks] = useState<TraceTask[] | null>(
+ null,
+ );
+ const [issueActiveTask, setIssueActiveTask] = useState<Task | null>(null);
+
+ const openIssue = useCallback(
+ async (issueId: string) => {
+ setSelectedIssueId(issueId);
+ setIssueSheetOpen(true);
+ setIssueDetailLoading(true);
+ setIssueTraceTasks(null);
+ setIssueActiveTask(null);
+ try {
+ const res = await getIssue(workspaceId, issueId);
+ setIssueDetail(res);
+ if (res.issue.latest_task_id) {
+ getTask(res.issue.latest_task_id, workspaceId)
+ .then((task) => setIssueActiveTask(task))
+ .catch(() => setIssueActiveTask(null));
+ }
+ if (res.issue.trace_id) {
+ getTrace(res.issue.trace_id, workspaceId)
+ .then((t) => setIssueTraceTasks(t.tasks))
+ .catch(() => setIssueTraceTasks(null));
+ }
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to load issue",
+ );
+ setIssueSheetOpen(false);
+ } finally {
+ setIssueDetailLoading(false);
+ }
+ },
+ [workspaceId],
+ );
+
+ const issueConvId = issueDetail?.issue?.conversation_id ?? null;
+ const issueTaskId = issueDetail?.issue?.latest_task_id ?? null;
+
+ return {
+ artifactSheetOpen,
+ setArtifactSheetOpen,
+ selectedArtifact,
+ setSelectedArtifact,
+ emailSheetOpen,
+ setEmailSheetOpen,
+ selectedEmailId,
+ setSelectedEmailId,
+ calendarEventSheetOpen,
+ setCalendarEventSheetOpen,
+ selectedCalendarEventId,
+ setSelectedCalendarEventId,
+ issueSheetOpen,
+ setIssueSheetOpen,
+ selectedIssueId,
+ setSelectedIssueId,
+ issueDetail,
+ setIssueDetail,
+ issueDetailLoading,
+ issueTraceTasks,
+ issueActiveTask,
+ setIssueActiveTask,
+ openIssue,
+ issueConvId,
+ issueTaskId,
+ };
+}
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
new file mode 100644
index 000000000..38df99c7f
--- /dev/null
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -0,0 +1,101 @@
+import React, { useCallback, useRef, useState } from "react";
+import { toast } from "sonner";
+
+const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
+
+/**
+ * Owns the composer's file-staging UI: the pending (not-yet-sent) files, the
+ * hidden file-input ref, add/remove handlers, and drag-and-drop state.
+ *
+ * Extracted verbatim from agent-chat-view.tsx. The optimistic-send bookkeeping
+ * (`failedSends`, `pendingFilesByMessage`) intentionally stays OWNED by the
+ * component — send/retry read and write it — so this hook only manages the
+ * staging concern. `pendingFiles` + `setPendingFiles` are returned so the
+ * component's send/retry path (Tier 3) can clear/restore them exactly as before.
+ *
+ * Has no effects, so it carries no effect-order constraints.
+ */
+export function useFileAttachments() {
+ const [pendingFiles, setPendingFiles] = useState<File[]>([]);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const addPendingFiles = useCallback((files: File[]) => {
+ const valid: File[] = [];
+ for (const file of files) {
+ if (file.size > MAX_FILE_SIZE) {
+ toast.error(`"${file.name}" exceeds 10 MB limit`);
+ } else {
+ valid.push(file);
+ }
+ }
+ if (valid.length > 0) {
+ setPendingFiles((prev) => [...prev, ...valid]);
+ }
+ }, []);
+
+ const handleFileSelect = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const fileList = e.target.files;
+ if (!fileList) return;
+ addPendingFiles(Array.from(fileList));
+ // Reset input so re-selecting the same file works
+ e.target.value = "";
+ },
+ [addPendingFiles],
+ );
+
+ const removePendingFile = useCallback((index: number) => {
+ setPendingFiles((prev) => prev.filter((_, i) => i !== index));
+ }, []);
+
+ const [dragging, setDragging] = useState(false);
+ const dragCounter = useRef(0);
+
+ const handleDragEnter = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ dragCounter.current++;
+ if (e.dataTransfer.types.includes("Files")) {
+ setDragging(true);
+ }
+ }, []);
+
+ const handleDragLeave = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ dragCounter.current--;
+ if (dragCounter.current === 0) {
+ setDragging(false);
+ }
+ }, []);
+
+ const handleDragOver = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }, []);
+
+ const handleDrop = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragging(false);
+ dragCounter.current = 0;
+ addPendingFiles(Array.from(e.dataTransfer.files));
+ },
+ [addPendingFiles],
+ );
+
+ return {
+ pendingFiles,
+ setPendingFiles,
+ fileInputRef,
+ addPendingFiles,
+ handleFileSelect,
+ removePendingFile,
+ dragging,
+ handleDragEnter,
+ handleDragLeave,
+ handleDragOver,
+ handleDrop,
+ };
+}
diff --git a/src/web/src/hooks/use-message-flags.ts b/src/web/src/hooks/use-message-flags.ts
new file mode 100644
index 000000000..bf8843481
--- /dev/null
+++ b/src/web/src/hooks/use-message-flags.ts
@@ -0,0 +1,72 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ flagMessage as apiFlagMessage,
+ unflagMessage as apiUnflagMessage,
+} from "@/lib/api";
+import { useFlagCount } from "@/contexts/flag-count-context";
+
+/**
+ * Owns the per-message "flagged" UI state for the chat view: the set of flagged
+ * message ids, an optimistic toggle handler (with rollback), and the flag-count
+ * context wiring. The conversation-load effect (which stays in the component)
+ * seeds the set via the returned `setFlaggedIds`.
+ *
+ * Extracted verbatim from agent-chat-view.tsx — same state, same effect, same
+ * optimistic/rollback logic. The `flaggedIdsRef`-sync effect runs on every
+ * render (no dep array), exactly as before, so it must remain the FIRST effect
+ * registered by the component (call this hook before any other effect-bearing
+ * hook).
+ */
+export function useMessageFlags(workspaceId: string) {
+ const [flaggedIds, setFlaggedIds] = useState<Set<string>>(new Set());
+ const flaggedIdsRef = useRef(flaggedIds);
+ useEffect(() => {
+ flaggedIdsRef.current = flaggedIds;
+ });
+
+ const {
+ increment: flagIncrement,
+ decrement: flagDecrement,
+ refresh: flagRefresh,
+ } = useFlagCount();
+
+ const handleToggleFlag = useCallback(
+ async (messageId: string) => {
+ const wasFlagged = flaggedIdsRef.current.has(messageId);
+ setFlaggedIds((prev) => {
+ const next = new Set(prev);
+ if (wasFlagged) next.delete(messageId);
+ else next.add(messageId);
+ return next;
+ });
+ if (wasFlagged) {
+ flagDecrement();
+ apiUnflagMessage(workspaceId, messageId)
+ .then(() => {
+ flagRefresh();
+ })
+ .catch(() => {
+ setFlaggedIds((prev) => new Set(prev).add(messageId));
+ flagIncrement();
+ });
+ } else {
+ flagIncrement();
+ apiFlagMessage(workspaceId, messageId)
+ .then(() => {
+ flagRefresh();
+ })
+ .catch(() => {
+ setFlaggedIds((prev) => {
+ const next = new Set(prev);
+ next.delete(messageId);
+ return next;
+ });
+ flagDecrement();
+ });
+ }
+ },
+ [workspaceId, flagIncrement, flagDecrement, flagRefresh],
+ );
+
+ return { flaggedIds, setFlaggedIds, handleToggleFlag };
+}
diff --git a/src/web/src/hooks/use-text-selection-quote.ts b/src/web/src/hooks/use-text-selection-quote.ts
new file mode 100644
index 000000000..839464962
--- /dev/null
+++ b/src/web/src/hooks/use-text-selection-quote.ts
@@ -0,0 +1,56 @@
+import { useCallback, useEffect, useState } from "react";
+
+export type SelectionPopup = {
+ text: string;
+ x: number;
+ y: number;
+} | null;
+
+/**
+ * Owns the "quote selected text" popup: tracks the current text selection
+ * (only inside `[data-quote-source]` regions) and positions the popup, via a
+ * document `selectionchange` listener.
+ *
+ * Extracted verbatim from agent-chat-view.tsx. Call this hook at the SAME
+ * position the `selectionchange` effect previously occupied so its registration
+ * order is preserved. The `selectionPopup` state + raw `setSelectionPopup`
+ * setter are returned so the component's quote handler (which also writes the
+ * composer draft + focuses the editor) stays byte-identical.
+ */
+export function useTextSelectionQuote() {
+ const [selectionPopup, setSelectionPopup] = useState<SelectionPopup>(null);
+
+ const handleTextSelect = useCallback(() => {
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed || !selection.rangeCount) {
+ setSelectionPopup(null);
+ return;
+ }
+ const text = selection.toString().trim();
+ if (!text) {
+ setSelectionPopup(null);
+ return;
+ }
+ // Only allow quoting from assistant message bubbles
+ const range = selection.getRangeAt(0);
+ const container =
+ range.commonAncestorContainer instanceof HTMLElement
+ ? range.commonAncestorContainer
+ : range.commonAncestorContainer.parentElement;
+ if (!container?.closest("[data-quote-source]")) {
+ setSelectionPopup(null);
+ return;
+ }
+ const rects = range.getClientRects();
+ const lastRect = rects[rects.length - 1] || range.getBoundingClientRect();
+ setSelectionPopup({ text, x: lastRect.right, y: lastRect.top - 4 });
+ }, []);
+
+ useEffect(() => {
+ document.addEventListener("selectionchange", handleTextSelect);
+ return () =>
+ document.removeEventListener("selectionchange", handleTextSelect);
+ }, [handleTextSelect]);
+
+ return { selectionPopup, setSelectionPopup };
+}
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index b714d0d0a..c342dbbe5 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -260,7 +260,6 @@ export interface ChatInitResponse {
conversation: Conversation;
messages: Message[];
artifacts: Artifact[];
- buffered_messages: Message[];
active_task: TaskApi | null;
task_messages: TaskMessageResponse[];
has_more_messages: boolean;
@@ -294,9 +293,7 @@ export interface ConversationInitResponse {
has_more_conversations: boolean;
has_more_artifacts: boolean;
artifacts: Artifact[];
- buffered_messages: Message[];
flagged_message_ids: string[];
- thinking_counts: Record<string, number>;
active_task: TaskApi | null;
task_messages: TaskMessageResponse[];
cache_valid: boolean;
@@ -423,82 +420,6 @@ export const sendMessage = async (
return res.json() as Promise<{ message: Message; task: TaskApi }>;
};
-// Buffered messages (follow-up queue)
-export const listBufferedMessages = (conversationId: string, workspaceId: string) =>
- apiFetch<Message[]>(
- `/api/conversations/${conversationId}/buffered-messages${wsQuery(workspaceId)}`
- );
-
-export const createBufferedMessage = async (
- conversationId: string,
- content: string,
- workspaceId: string,
- files?: File[],
-): Promise<{ message: Message }> => {
- if (!files || files.length === 0) {
- return apiFetch<{ message: Message }>(
- `/api/conversations/${conversationId}/buffered-messages${wsQuery(workspaceId)}`,
- {
- method: "POST",
- body: JSON.stringify({ content }),
- },
- );
- }
-
- const fd = new FormData();
- fd.append("content", content);
- for (const file of files) {
- fd.append("file", file);
- }
-
- let res: Response;
- try {
- res = await fetch(
- `/api/conversations/${conversationId}/buffered-messages${wsQuery(workspaceId)}`,
- { method: "POST", credentials: "include", body: fd },
- );
- } catch (err) {
- if (err instanceof TypeError) {
- throw new ApiError("Unable to connect — check your network", 0);
- }
- throw err;
- }
-
- if (res.status === 401) {
- if (typeof window !== "undefined") window.location.href = "/sign-in";
- throw new ApiError("Unauthorized", 401);
- }
-
- if (!res.ok) {
- let serverError: string | undefined;
- let details: string[] | undefined;
- try {
- const body = (await res.json()) as { error?: string; details?: string[] };
- serverError = body.error;
- details = body.details;
- } catch {
- // non-JSON body
- }
- if (res.status === 429) throw new ApiError(serverError || "Maximum follow-ups reached", 429);
- if (res.status >= 500) throw new ApiError(serverError || "Something went wrong — please try again", res.status, details);
- throw new ApiError(serverError || "Something went wrong", res.status, details);
- }
-
- return res.json() as Promise<{ message: Message }>;
-};
-
-export const deleteBufferedMessage = (conversationId: string, messageId: string, workspaceId: string) =>
- apiFetch<void>(
- `/api/conversations/${conversationId}/buffered-messages/${messageId}${wsQuery(workspaceId)}`,
- { method: "DELETE" },
- );
-
-export const deleteAllBufferedMessages = (conversationId: string, workspaceId: string) =>
- apiFetch<void>(
- `/api/conversations/${conversationId}/buffered-messages${wsQuery(workspaceId)}`,
- { method: "DELETE" },
- );
-
// Active task for conversation (recovery on page refresh)
export const getActiveTask = (conversationId: string, workspaceId: string) =>
apiFetch<TaskApi | undefined>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`);
diff --git a/src/web/src/lib/chat-cache.test.ts b/src/web/src/lib/chat-cache.test.ts
index 345d619c5..ccebc63ba 100644
--- a/src/web/src/lib/chat-cache.test.ts
+++ b/src/web/src/lib/chat-cache.test.ts
@@ -16,10 +16,42 @@ import {
getLastOpenConversation,
setLastOpenConversation,
clearLastOpenForConversation,
+ getConvExtras,
+ setConvExtras,
+ clearConvExtras,
} from "./chat-cache";
+import type { Artifact } from "@alook/shared";
const WORKSPACE_ID = "ws_test";
+function makeArtifact(overrides: Partial<Artifact> = {}): Artifact {
+ return {
+ id: `art_${Math.random().toString(36).slice(2)}`,
+ conversation_id: "conv_1",
+ agent_id: "agent_a",
+ filename: "report.pdf",
+ content_type: "application/pdf",
+ size: 1024,
+ source: "agent",
+ created_at: new Date().toISOString(),
+ ...overrides,
+ };
+}
+
+function makeExtras(
+ overrides: Partial<Parameters<typeof setConvExtras>[1]> = {},
+): Parameters<typeof setConvExtras>[1] {
+ return {
+ artifacts: [makeArtifact()],
+ conversation_type: "agent_chat",
+ conversation_title: "My chat",
+ conversation_channel: "general",
+ conversation_created_at: "2024-01-01T00:00:00Z",
+ hasMoreArtifacts: false,
+ ...overrides,
+ };
+}
+
function makeMessage(overrides: Partial<Message> = {}): Message {
return {
id: `msg_${Math.random().toString(36).slice(2)}`,
@@ -108,19 +140,6 @@ describe("chat-cache", () => {
expect(metaAfter!.messageCount).toBe(4);
});
- it("filters out buffered messages", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", status: "active" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", status: "buffered" }),
- ];
-
- await mergeCachedMessages("conv_1", msgs, false, WORKSPACE_ID);
-
- const cached = await getCachedMessages("conv_1", WORKSPACE_ID);
- expect(cached).toHaveLength(1);
- expect(cached![0].id).toBe("m1");
- });
-
it("filters out temp- messages", async () => {
const msgs = [
makeMessage({ id: "m1", conversation_id: "conv_1" }),
@@ -153,24 +172,6 @@ describe("chat-cache", () => {
expect(cached).toBeNull();
});
- it("excludes buffered messages on read", async () => {
- const db = await openCacheDB(WORKSPACE_ID)!;
- await db.put("messages", makeMessage({ id: "m1", conversation_id: "conv_1", status: "buffered" }));
- await db.put("messages", makeMessage({ id: "m2", conversation_id: "conv_1", status: "active" }));
- await db.put("cache_meta", {
- conversation_id: "conv_1",
- lastFetchedAt: Date.now(),
- lastAccessedAt: Date.now(),
- messageCount: 2,
- newestMessageId: "m2",
- hasMore: false,
- serverMessageCount: 0,
- });
-
- const cached = await getCachedMessages("conv_1", WORKSPACE_ID);
- expect(cached).toHaveLength(1);
- expect(cached![0].id).toBe("m2");
- });
});
describe("appendCachedMessage", () => {
@@ -184,16 +185,6 @@ describe("chat-cache", () => {
expect(cached).toHaveLength(2);
});
- it("skips buffered messages", async () => {
- const initial = [makeMessage({ id: "m1", conversation_id: "conv_1" })];
- await mergeCachedMessages("conv_1", initial, false, WORKSPACE_ID);
-
- await appendCachedMessage("conv_1", makeMessage({ id: "m2", conversation_id: "conv_1", status: "buffered" }), WORKSPACE_ID);
-
- const cached = await getCachedMessages("conv_1", WORKSPACE_ID);
- expect(cached).toHaveLength(1);
- });
-
it("skips temp- messages", async () => {
const initial = [makeMessage({ id: "m1", conversation_id: "conv_1" })];
await mergeCachedMessages("conv_1", initial, false, WORKSPACE_ID);
@@ -348,6 +339,175 @@ describe("chat-cache", () => {
});
});
+ describe("conv_extras (card metadata)", () => {
+ it("set then get round-trips artifacts array + conversation metadata", async () => {
+ const arts = [
+ makeArtifact({ id: "a1", conversation_id: "conv_1" }),
+ makeArtifact({ id: "a2", conversation_id: "conv_1" }),
+ ];
+ await setConvExtras("conv_1", makeExtras({
+ artifacts: arts,
+ conversation_type: "email_notification",
+ conversation_title: "Re: bug",
+ conversation_channel: "inbox",
+ conversation_created_at: "2024-02-02T00:00:00Z",
+ hasMoreArtifacts: true,
+ }), WORKSPACE_ID);
+
+ const entry = await getConvExtras("conv_1", WORKSPACE_ID);
+ expect(entry).not.toBeNull();
+ expect(entry!.conversation_id).toBe("conv_1");
+ expect(entry!.artifacts.map((a) => a.id)).toEqual(["a1", "a2"]);
+ expect(entry!.conversation_type).toBe("email_notification");
+ expect(entry!.conversation_title).toBe("Re: bug");
+ expect(entry!.conversation_channel).toBe("inbox");
+ expect(entry!.conversation_created_at).toBe("2024-02-02T00:00:00Z");
+ expect(entry!.hasMoreArtifacts).toBe(true);
+ // updatedAt is stamped at write time.
+ expect(typeof entry!.updatedAt).toBe("number");
+ });
+
+ it("returns null for an unknown conversation", async () => {
+ await setConvExtras("conv_1", makeExtras(), WORKSPACE_ID);
+ expect(await getConvExtras("conv_other", WORKSPACE_ID)).toBeNull();
+ });
+
+ it("upserts — a second write replaces the row", async () => {
+ await setConvExtras("conv_1", makeExtras({
+ artifacts: [makeArtifact({ id: "a1" })],
+ conversation_type: "agent_chat",
+ }), WORKSPACE_ID);
+ await setConvExtras("conv_1", makeExtras({
+ artifacts: [makeArtifact({ id: "a2" }), makeArtifact({ id: "a3" })],
+ conversation_type: "calendar_event",
+ }), WORKSPACE_ID);
+
+ const entry = await getConvExtras("conv_1", WORKSPACE_ID);
+ expect(entry!.artifacts.map((a) => a.id)).toEqual(["a2", "a3"]);
+ expect(entry!.conversation_type).toBe("calendar_event");
+ });
+
+ it("clearConvExtras removes only the target row", async () => {
+ await setConvExtras("conv_1", makeExtras(), WORKSPACE_ID);
+ await setConvExtras("conv_2", makeExtras(), WORKSPACE_ID);
+
+ await clearConvExtras("conv_1", WORKSPACE_ID);
+
+ expect(await getConvExtras("conv_1", WORKSPACE_ID)).toBeNull();
+ expect(await getConvExtras("conv_2", WORKSPACE_ID)).not.toBeNull();
+ });
+
+ it("invalidateCache clears the conversation's conv_extras row", async () => {
+ await mergeCachedMessages("conv_1", [makeMessage({ id: "m1", conversation_id: "conv_1" })], false, WORKSPACE_ID);
+ await setConvExtras("conv_1", makeExtras(), WORKSPACE_ID);
+
+ await invalidateCache("conv_1", WORKSPACE_ID);
+
+ expect(await getConvExtras("conv_1", WORKSPACE_ID)).toBeNull();
+ });
+
+ it("evictLRU prunes conv_extras for evicted conversations", async () => {
+ const db = await openCacheDB(WORKSPACE_ID)!;
+ for (let i = 0; i < 5; i++) {
+ await db.put("messages", makeMessage({ id: `m_${i}`, conversation_id: `conv_${i}`, created_at: `2024-01-0${i + 1}T00:00:00Z` }));
+ await db.put("cache_meta", {
+ conversation_id: `conv_${i}`,
+ lastFetchedAt: Date.now(),
+ lastAccessedAt: i * 1000,
+ messageCount: 1,
+ newestMessageId: `m_${i}`,
+ hasMore: false,
+ serverMessageCount: 0,
+ });
+ await setConvExtras(`conv_${i}`, makeExtras(), WORKSPACE_ID);
+ }
+
+ await evictLRU(3);
+
+ // conv_0 + conv_1 (least recently accessed) are evicted → extras gone.
+ expect(await getConvExtras("conv_0", WORKSPACE_ID)).toBeNull();
+ expect(await getConvExtras("conv_1", WORKSPACE_ID)).toBeNull();
+ // The 3 survivors keep their extras.
+ expect(await getConvExtras("conv_2", WORKSPACE_ID)).not.toBeNull();
+ expect(await getConvExtras("conv_3", WORKSPACE_ID)).not.toBeNull();
+ expect(await getConvExtras("conv_4", WORKSPACE_ID)).not.toBeNull();
+ });
+
+ it("no-ops safely when the DB is unavailable (getDB returns null)", async () => {
+ // clearAllCache nulls the module's dbPromise; calling the accessors with
+ // NO workspaceId then hits the same `getDB() === null` branch the SSR
+ // guard (`indexedDB === undefined`) takes — getConvExtras resolves null,
+ // setConvExtras/clearConvExtras resolve without throwing.
+ await clearAllCache();
+ expect(await getConvExtras("conv_x")).toBeNull();
+ await expect(setConvExtras("conv_x", makeExtras())).resolves.toBeUndefined();
+ await expect(clearConvExtras("conv_x")).resolves.toBeUndefined();
+ openCacheDB(WORKSPACE_ID);
+ });
+
+ it("clearAllCache removes conv_extras", async () => {
+ await setConvExtras("conv_1", makeExtras(), WORKSPACE_ID);
+ await clearAllCache();
+ // Re-open the (now-deleted) DB; the previously cached row is gone.
+ openCacheDB(WORKSPACE_ID);
+ expect(await getConvExtras("conv_1", WORKSPACE_ID)).toBeNull();
+ });
+ });
+
+ describe("v3 → v4 migration", () => {
+ it("upgrades a v3 DB to v4, adding conv_extras and preserving existing stores", async () => {
+ const MIGRATE_WS = "ws_migrate_v4";
+ await clearAllCache();
+
+ // Build a v3-shaped DB by hand (messages + cache_meta + last_open, v3).
+ const v3 = await openDB(`alook-chat-cache-${MIGRATE_WS}`, 3, {
+ upgrade(db) {
+ const msgStore = db.createObjectStore("messages", { keyPath: ["conversation_id", "id"] });
+ msgStore.createIndex("by-conversation", "conversation_id", { unique: false });
+ msgStore.createIndex("by-created", ["conversation_id", "created_at"], { unique: false });
+ db.createObjectStore("cache_meta", { keyPath: "conversation_id" });
+ const lastOpenStore = db.createObjectStore("last_open", { keyPath: "key" });
+ lastOpenStore.createIndex("by-conversation", "conversation_id", { unique: false });
+ },
+ });
+ await v3.put("messages", makeMessage({ id: "m1", conversation_id: "conv_old", created_at: "2024-01-01T00:00:00Z" }));
+ await v3.put("cache_meta", {
+ conversation_id: "conv_old",
+ lastFetchedAt: 1,
+ lastAccessedAt: 1,
+ messageCount: 1,
+ newestMessageId: "m1",
+ hasMore: false,
+ serverMessageCount: 1,
+ });
+ expect(v3.version).toBe(3);
+ expect(v3.objectStoreNames.contains("conv_extras")).toBe(false);
+ v3.close();
+
+ // Open via production code path — upgrades to v4, adds conv_extras.
+ const db = await openCacheDB(MIGRATE_WS)!;
+ expect(db.version).toBe(4);
+ expect(db.objectStoreNames.contains("conv_extras")).toBe(true);
+ // Existing v3 stores untouched.
+ expect(db.objectStoreNames.contains("messages")).toBe(true);
+ expect(db.objectStoreNames.contains("cache_meta")).toBe(true);
+ expect(db.objectStoreNames.contains("last_open")).toBe(true);
+
+ const cached = await getCachedMessages("conv_old", MIGRATE_WS);
+ expect(cached).toHaveLength(1);
+ expect(cached![0].id).toBe("m1");
+ const meta = await getCacheMeta("conv_old", MIGRATE_WS);
+ expect(meta!.newestMessageId).toBe("m1");
+
+ // New store works after the migration.
+ await setConvExtras("conv_old", makeExtras(), MIGRATE_WS);
+ expect((await getConvExtras("conv_old", MIGRATE_WS))?.conversation_id).toBe("conv_old");
+
+ await clearAllCache();
+ openCacheDB(WORKSPACE_ID);
+ });
+ });
+
describe("evictLRU", () => {
it("keeps only the N most recently accessed conversations", async () => {
const db = await openCacheDB(WORKSPACE_ID)!;
@@ -507,16 +667,15 @@ describe("chat-cache", () => {
expect(result!.messages.map((m) => m.id)).toEqual(["aaa", "bbb"]);
});
- it("filters out buffered and temp- messages", async () => {
+ it("filters out temp- messages", async () => {
const db = await openCacheDB(WORKSPACE_ID)!;
const msgs = [
makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z", status: "buffered" }),
makeMessage({ id: "temp-1", conversation_id: "conv_1", created_at: "2024-01-01T00:02:00Z" }),
makeMessage({ id: "m3", conversation_id: "conv_1", created_at: "2024-01-01T00:03:00Z" }),
makeMessage({ id: "m4", conversation_id: "conv_1", created_at: "2024-01-01T00:04:00Z" }),
];
- // Write directly to include buffered/temp that mergeCachedMessages would filter
+ // Write directly to include temp that mergeCachedMessages would filter
for (const msg of msgs) {
await db.put("messages", msg);
}
@@ -524,7 +683,7 @@ describe("chat-cache", () => {
conversation_id: "conv_1",
lastFetchedAt: Date.now(),
lastAccessedAt: Date.now(),
- messageCount: 5,
+ messageCount: 4,
newestMessageId: "m4",
hasMore: false,
serverMessageCount: 0,
@@ -595,10 +754,12 @@ describe("chat-cache", () => {
expect(v2.objectStoreNames.contains("last_open")).toBe(false);
v2.close();
- // Open via the production code path — should upgrade to v3.
+ // Open via the production code path — should upgrade to the current
+ // version (v4), running every intermediate migration branch in order.
const db = await openCacheDB(MIGRATE_WS)!;
- expect(db.version).toBe(3);
+ expect(db.version).toBe(4);
expect(db.objectStoreNames.contains("last_open")).toBe(true);
+ expect(db.objectStoreNames.contains("conv_extras")).toBe(true);
// Existing data is intact.
const cached = await getCachedMessages("conv_old", MIGRATE_WS);
diff --git a/src/web/src/lib/chat-cache.ts b/src/web/src/lib/chat-cache.ts
index c43d01a90..14416f3b0 100644
--- a/src/web/src/lib/chat-cache.ts
+++ b/src/web/src/lib/chat-cache.ts
@@ -1,5 +1,5 @@
import { openDB, type IDBPDatabase } from "idb";
-import type { Message } from "@alook/shared";
+import type { Message, Artifact } from "@alook/shared";
export interface CacheMeta {
conversation_id: string;
@@ -42,6 +42,41 @@ export interface LastOpenEntry {
updatedAt: number;
}
+/**
+ * Per-conversation "card metadata" — the non-message data the chat timeline
+ * needs to paint its cards (file/artifact cards + the event-card icon/label)
+ * WITHOUT waiting on the network. Mirrors how `messages` + `cache_meta` already
+ * power the instant text paint.
+ *
+ * The two pieces the network currently gates:
+ * - `artifacts`: the full per-conversation artifacts array (full server set,
+ * full-replace on every load — never merged, never the write authority).
+ * - the lightweight `conversation_*` fields: at minimum `conversation_type`,
+ * which drives the event-card icon/label on first paint for metadata-less
+ * event messages (the ones whose type would otherwise re-resolve from
+ * `conversation.type` only after the network lands).
+ *
+ * Cached values are only ever RENDERED; every load still fetches the
+ * authoritative `artifacts` + `conversation` and overwrites this row, so the
+ * worst case is a one-frame stale card that reconciles — never data loss (same
+ * guarantee as the message cache).
+ */
+export interface ConvExtrasEntry {
+ conversation_id: string;
+ artifacts: Artifact[];
+ conversation_type: string;
+ conversation_title: string;
+ conversation_channel: string;
+ // Server `conversation.created_at`. Seeded into the provisional conversation
+ // stub on the instant paint so the scroll heuristic
+ // (`agent-chat-view.tsx`, `wasScrolledToBottom`) reads a real value rather
+ // than an empty string (which would flip its `!conversation.created_at`
+ // branch and alter scroll behavior during the optimistic window).
+ conversation_created_at: string;
+ hasMoreArtifacts: boolean;
+ updatedAt: number;
+}
+
interface ChatCacheDB {
messages: {
key: [string, string];
@@ -62,9 +97,13 @@ interface ChatCacheDB {
"by-conversation": string;
};
};
+ conv_extras: {
+ key: string;
+ value: ConvExtrasEntry;
+ };
}
-const DB_VERSION = 3;
+const DB_VERSION = 4;
const MAX_CONVERSATIONS = 50;
let dbPromise: Promise<IDBPDatabase<ChatCacheDB>> | null = null;
@@ -97,6 +136,16 @@ export function openCacheDB(workspaceId: string): Promise<IDBPDatabase<ChatCache
const lastOpenStore = db.createObjectStore("last_open", { keyPath: "key" });
lastOpenStore.createIndex("by-conversation", "conversation_id", { unique: false });
}
+ if (oldVersion < 4) {
+ // v3 → v4: per-conversation card metadata (artifacts + conversation
+ // type/title/channel/created_at). Existing `messages`/`cache_meta`/
+ // `last_open` stores are untouched; this store starts empty, so the
+ // first open of any conversation is a clean cache miss (today's
+ // behavior — text paints, cards pop in after the network), then it
+ // populates and subsequent opens paint cards instantly. Keyed by
+ // `conversation_id` (single-row lookup), no index needed.
+ db.createObjectStore("conv_extras", { keyPath: "conversation_id" });
+ }
},
});
@@ -117,9 +166,7 @@ export async function getCachedMessages(conversationId: string, workspaceId?: st
const messages = await db.getAllFromIndex("messages", "by-conversation", conversationId);
if (messages.length === 0) return null;
- const filtered = messages.filter(
- (m) => m.status !== "buffered" && !m.id.startsWith("temp-")
- );
+ const filtered = messages.filter((m) => !m.id.startsWith("temp-"));
filtered.sort((a, b) => {
const cmp = a.created_at.localeCompare(b.created_at);
@@ -164,7 +211,7 @@ export async function getCachedMessagesBefore(
const allInRange = await db.getAllFromIndex("messages", "by-created", range);
const filtered = allInRange.filter((m) => {
- if (m.status === "buffered" || m.id.startsWith("temp-")) return false;
+ if (m.id.startsWith("temp-")) return false;
if (m.created_at === beforeCreatedAt && m.id >= beforeId) return false;
return true;
});
@@ -204,9 +251,7 @@ export async function mergeCachedMessages(
try {
const db = await p;
- const validMessages = messages.filter(
- (m) => m.status !== "buffered" && !m.id.startsWith("temp-")
- );
+ const validMessages = messages.filter((m) => !m.id.startsWith("temp-"));
if (validMessages.length === 0) return;
const tx = db.transaction(["messages", "cache_meta"], "readwrite");
@@ -263,7 +308,7 @@ export async function appendCachedMessage(
const p = getDB(workspaceId);
if (!p) return;
- if (message.status === "buffered" || message.id.startsWith("temp-")) return;
+ if (message.id.startsWith("temp-")) return;
try {
const db = await p;
@@ -412,16 +457,78 @@ export async function clearLastOpenForConversation(
}
}
+/**
+ * Read the cached card metadata for a conversation. IndexedDB only, no network.
+ * Returns null on cache miss, error, or SSR (no indexedDB).
+ */
+export async function getConvExtras(
+ conversationId: string,
+ workspaceId?: string
+): Promise<ConvExtrasEntry | null> {
+ const p = getDB(workspaceId);
+ if (!p) return null;
+
+ try {
+ const db = await p;
+ return (await db.get("conv_extras", conversationId)) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Upsert the card metadata for a conversation. Stamps `updatedAt` at write
+ * time. No-op when the DB is unavailable (SSR / private browsing). Callers
+ * should fire-and-forget (`.catch(() => {})`) — this is never on the critical
+ * render path, mirroring `mergeCachedMessages`.
+ */
+export async function setConvExtras(
+ conversationId: string,
+ entry: Omit<ConvExtrasEntry, "conversation_id" | "updatedAt">,
+ workspaceId?: string
+): Promise<void> {
+ const p = getDB(workspaceId);
+ if (!p) return;
+
+ try {
+ const db = await p;
+ await db.put("conv_extras", {
+ conversation_id: conversationId,
+ ...entry,
+ updatedAt: Date.now(),
+ });
+ } catch {
+ // Graceful degradation
+ }
+}
+
+/** Remove the cached card metadata for a single conversation. */
+export async function clearConvExtras(
+ conversationId: string,
+ workspaceId?: string
+): Promise<void> {
+ const p = getDB(workspaceId);
+ if (!p) return;
+
+ try {
+ const db = await p;
+ await db.delete("conv_extras", conversationId);
+ } catch {
+ // Graceful degradation
+ }
+}
+
export async function invalidateCache(conversationId: string, workspaceId?: string): Promise<void> {
const p = getDB(workspaceId);
if (!p) return;
try {
const db = await p;
- const tx = db.transaction(["messages", "cache_meta", "last_open"], "readwrite");
+ const tx = db.transaction(["messages", "cache_meta", "last_open", "conv_extras"], "readwrite");
const msgStore = tx.objectStore("messages");
const metaStore = tx.objectStore("cache_meta");
const lastOpenStore = tx.objectStore("last_open");
+ const extrasStore = tx.objectStore("conv_extras");
const keys = await msgStore.index("by-conversation").getAllKeys(conversationId);
for (const key of keys) {
@@ -436,6 +543,10 @@ export async function invalidateCache(conversationId: string, workspaceId?: stri
await lastOpenStore.delete(key);
}
+ // Drop the cached card metadata so an invalidated conversation doesn't
+ // render stale cards then wipe.
+ await extrasStore.delete(conversationId);
+
await tx.done;
} catch {
// Graceful degradation
@@ -454,10 +565,11 @@ export async function evictLRU(maxConversations = MAX_CONVERSATIONS): Promise<vo
allMeta.sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);
const toEvict = allMeta.slice(0, allMeta.length - maxConversations);
- const tx = db.transaction(["messages", "cache_meta", "last_open"], "readwrite");
+ const tx = db.transaction(["messages", "cache_meta", "last_open", "conv_extras"], "readwrite");
const msgStore = tx.objectStore("messages");
const metaStore = tx.objectStore("cache_meta");
const lastOpenStore = tx.objectStore("last_open");
+ const extrasStore = tx.objectStore("conv_extras");
for (const meta of toEvict) {
const keys = await msgStore.index("by-conversation").getAllKeys(meta.conversation_id);
@@ -472,6 +584,10 @@ export async function evictLRU(maxConversations = MAX_CONVERSATIONS): Promise<vo
for (const key of lastOpenKeys) {
await lastOpenStore.delete(key);
}
+
+ // Prune the evicted conversation's card metadata in the same pass so no
+ // dangling artifacts/type row outlives its messages.
+ await extrasStore.delete(meta.conversation_id);
}
await tx.done;
diff --git a/src/web/src/lib/services/sweep.test.ts b/src/web/src/lib/services/sweep.test.ts
index 8974d7f03..4171315d2 100644
--- a/src/web/src/lib/services/sweep.test.ts
+++ b/src/web/src/lib/services/sweep.test.ts
@@ -5,7 +5,6 @@ const mockFailStaleKillTasks = vi.fn();
const mockFailStaleRunningTasks = vi.fn();
const mockCountRunningTasks = vi.fn();
const mockUpdateAgentStatus = vi.fn();
-const mockActivateNextBufferedMessage = vi.fn();
const mockGetConversation = vi.fn();
const mockGetAgent = vi.fn();
const mockCreateTask = vi.fn();
@@ -26,7 +25,6 @@ vi.mock("@alook/shared", () => ({
updateAgentStatus: (...args: unknown[]) => mockUpdateAgentStatus(...args),
},
message: {
- activateNextBufferedMessage: (...args: unknown[]) => mockActivateNextBufferedMessage(...args),
createMessage: vi.fn(),
},
conversation: {
@@ -60,7 +58,6 @@ describe("sweepStaleState", () => {
_resetSweepThrottle();
mockFailStaleKillTasks.mockResolvedValue([]);
mockFailStaleRunningTasks.mockResolvedValue([]);
- mockActivateNextBufferedMessage.mockResolvedValue(null);
});
it("calls failStaleDispatchedTasks with workspace", async () => {
@@ -109,34 +106,6 @@ describe("sweepStaleState", () => {
expect(mockUpdateAgentStatus).not.toHaveBeenCalled();
});
- it("dispatches buffered messages for affected conversations", async () => {
- mockFailStaleDispatchedTasks.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },
- { agentId: "a2", workspaceId: "w1", conversationId: "c2" },
- ]);
- mockCountRunningTasks.mockResolvedValue(0);
- mockUpdateAgentStatus.mockResolvedValue(undefined);
-
- await sweepStaleState(db, "w1");
-
- expect(mockActivateNextBufferedMessage).toHaveBeenCalledTimes(2);
- expect(mockActivateNextBufferedMessage).toHaveBeenCalledWith(db, "c1");
- expect(mockActivateNextBufferedMessage).toHaveBeenCalledWith(db, "c2");
- });
-
- it("deduplicates dispatch calls by conversationId", async () => {
- mockFailStaleDispatchedTasks.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },
- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },
- ]);
- mockCountRunningTasks.mockResolvedValue(0);
- mockUpdateAgentStatus.mockResolvedValue(undefined);
-
- await sweepStaleState(db, "w1");
-
- expect(mockActivateNextBufferedMessage).toHaveBeenCalledTimes(1);
- });
-
it("calls failStaleKillTasks with workspace", async () => {
mockFailStaleDispatchedTasks.mockResolvedValue([]);
@@ -185,31 +154,4 @@ describe("sweepStaleState", () => {
expect(mockUpdateAgentStatus).toHaveBeenCalledTimes(1);
});
- it("dispatches buffered messages for stale running tasks", async () => {
- mockFailStaleDispatchedTasks.mockResolvedValue([]);
- mockFailStaleRunningTasks.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },
- ]);
- mockCountRunningTasks.mockResolvedValue(0);
- mockUpdateAgentStatus.mockResolvedValue(undefined);
-
- await sweepStaleState(db, "w1");
-
- expect(mockActivateNextBufferedMessage).toHaveBeenCalledWith(db, "c1");
- });
-
- it("deduplicates conversations across both sweeps", async () => {
- mockFailStaleDispatchedTasks.mockResolvedValue([
- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },
- ]);
- mockFailStaleRunningTasks.mockResolvedValue([
- { agentId: "a2", workspaceId: "w1", conversationId: "c1" },
- ]);
- mockCountRunningTasks.mockResolvedValue(0);
- mockUpdateAgentStatus.mockResolvedValue(undefined);
-
- await sweepStaleState(db, "w1");
-
- expect(mockActivateNextBufferedMessage).toHaveBeenCalledTimes(1);
- });
});
diff --git a/src/web/src/lib/services/sweep.ts b/src/web/src/lib/services/sweep.ts
index 063a00609..5027d0f28 100644
--- a/src/web/src/lib/services/sweep.ts
+++ b/src/web/src/lib/services/sweep.ts
@@ -32,7 +32,7 @@ export async function sweepStaleState(db: Database, workspaceId: string) {
// 2. Fail tasks stuck in "running" with no message activity for >1h
const staleRunning = await queries.task.failStaleRunningTasks(db, workspaceId);
- // 3. Reconcile agent status + dispatch buffered messages for all affected
+ // 3. Reconcile agent status for all affected agents
const allStale = [...staleDispatched, ...staleRunning];
if (allStale.length > 0) {
const taskService = new TaskService(db);
@@ -44,13 +44,6 @@ export async function sweepStaleState(db: Database, workspaceId: string) {
await taskService.reconcileAgentStatus(r.agentId, r.workspaceId);
}
- const seenConversations = new Set<string>();
- for (const r of allStale) {
- if (seenConversations.has(r.conversationId)) continue;
- seenConversations.add(r.conversationId);
- await taskService.dispatchNextBufferedMessage(r.conversationId, r.workspaceId);
- }
-
// Invalidate caches that sweep modified
const dateStr = new Date().toISOString().slice(0, 10);
await Promise.all([
diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.ts
index 93151dc6d..d3cb0af0c 100644
--- a/src/web/src/lib/services/task.test.ts
+++ b/src/web/src/lib/services/task.test.ts
@@ -38,8 +38,6 @@ vi.mock("@alook/shared", () => ({
},
message: {
createMessage: vi.fn(),
- activateNextBufferedMessage: vi.fn(),
- revertToBuffered: vi.fn().mockResolvedValue(null),
updateMessageTaskId: vi.fn().mockResolvedValue(undefined),
},
conversation: {
@@ -101,8 +99,6 @@ const service = new TaskService({} as any);
describe("TaskService", () => {
beforeEach(() => {
vi.clearAllMocks();
- // Default: no buffered messages to dispatch
- messageQ.activateNextBufferedMessage.mockResolvedValue(null);
// Default: no kill tasks to claim
taskQ.claimKillTasks.mockResolvedValue([]);
});
@@ -336,7 +332,9 @@ describe("TaskService", () => {
// ── completeTask ─────────────────────────────────────────────────
describe("completeTask", () => {
- it("creates assistant message from result.output", async () => {
+ it("does NOT create an assistant message or broadcast from result.output (A1)", async () => {
+ // A1: the agent owns its voice via `sync send-dm`. completeTask must no
+ // longer auto-extract the final output into a chat bubble.
const task = {
id: "t1",
agentId: "a1",
@@ -355,12 +353,11 @@ describe("TaskService", () => {
"sess-1"
);
- expect(messageQ.createMessage).toHaveBeenCalledWith({}, {
- conversationId: "c1",
- role: "assistant",
- content: "Here is the answer",
- taskId: "t1",
- });
+ expect(messageQ.createMessage).not.toHaveBeenCalled();
+ expect(broadcastToUser).not.toHaveBeenCalled();
+ // lifecycle side-effects still run
+ expect(taskQ.completeTask).toHaveBeenCalled();
+ expect(agentQ.updateAgentStatus).toHaveBeenCalled();
});
it("does not create message when result has no output", async () => {
@@ -618,196 +615,35 @@ describe("TaskService", () => {
});
});
- // ── dispatchNextBufferedMessage ─────────────────────────────────
-
- describe("dispatchNextBufferedMessage", () => {
- it("returns null when no buffered messages exist", async () => {
- messageQ.activateNextBufferedMessage.mockResolvedValue(null);
-
- const result = await service.dispatchNextBufferedMessage("c1", "w1");
-
- expect(result).toBeNull();
- expect(conversationQ.getConversation).not.toHaveBeenCalled();
- });
-
- it("activates first buffered message and enqueues task", async () => {
- const activated = {
- id: "msg1",
- conversationId: "c1",
- role: "user",
- content: "follow-up",
- taskId: null,
- attachmentIds: null,
- status: "active",
- createdAt: "2026-01-01T00:00:00.000Z",
- };
- messageQ.activateNextBufferedMessage.mockResolvedValue(activated);
- conversationQ.getConversation.mockResolvedValue({
- id: "c1",
- agentId: "a1",
- userId: "u1",
- workspaceId: "w1",
- });
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });
- taskQ.createTask.mockResolvedValue({
- id: "t1",
- agentId: "a1",
- runtimeId: "r1",
- workspaceId: "w1",
- conversationId: "c1",
- prompt: "follow-up",
- status: "queued",
- priority: 0,
- createdAt: "2026-01-01",
- dispatchedAt: null,
- startedAt: null,
- completedAt: null,
- });
-
- const result = await service.dispatchNextBufferedMessage("c1", "w1");
+ // ── failTask creates a runtime-error assistant message (TC6) ────
- expect(result).toBeTruthy();
- expect(result!.id).toBe("t1");
- expect(broadcastToUser).toHaveBeenCalledWith(
- "u1",
- expect.objectContaining({ type: "followup.dispatched" })
- );
- });
-
- it("forwards attachment context when buffered message has attachments", async () => {
- const activated = {
- id: "msg2",
- conversationId: "c1",
- role: "user",
- content: "with files",
- taskId: null,
- attachmentIds: '["art_1","art_2"]',
- status: "active",
- createdAt: "2026-01-01T00:00:00.000Z",
- };
- messageQ.activateNextBufferedMessage.mockResolvedValue(activated);
- conversationQ.getConversation.mockResolvedValue({
- id: "c1",
- agentId: "a1",
- userId: "u1",
- workspaceId: "w1",
- });
- agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });
- taskQ.createTask.mockResolvedValue({
- id: "t2",
- agentId: "a1",
- runtimeId: "r1",
- workspaceId: "w1",
- conversationId: "c1",
- prompt: "with files",
- status: "queued",
- priority: 0,
- createdAt: "2026-01-01",
- dispatchedAt: null,
- startedAt: null,
- completedAt: null,
- });
-
- await service.dispatchNextBufferedMessage("c1", "w1");
-
- expect(taskQ.createTask).toHaveBeenCalledWith(
- {},
- expect.objectContaining({
- context: { attachment_ids: ["art_1", "art_2"] },
- })
- );
- });
-
- it("does NOT re-throw when enqueueTask fails", async () => {
- const activated = {
- id: "msg3",
- conversationId: "c1",
- role: "user",
- content: "will fail",
- taskId: null,
- attachmentIds: null,
- status: "active",
- createdAt: "2026-01-01T00:00:00.000Z",
- };
- messageQ.activateNextBufferedMessage.mockResolvedValue(activated);
- conversationQ.getConversation.mockResolvedValue({
- id: "c1",
- agentId: "a1",
- userId: "u1",
- workspaceId: "w1",
- });
- agentQ.getAgent.mockResolvedValue(null);
-
- const result = await service.dispatchNextBufferedMessage("c1", "w1");
-
- expect(result).toBeNull();
- expect(messageQ.revertToBuffered).toHaveBeenCalledWith({}, "msg3");
- expect(broadcastToUser).toHaveBeenCalledWith(
- "u1",
- expect.objectContaining({ type: "followup.dispatch_failed" })
- );
- });
-
- it("returns null when conversation not found", async () => {
- const activated = {
- id: "msg4",
- conversationId: "c1",
- role: "user",
- content: "test",
- taskId: null,
- attachmentIds: null,
- status: "active",
- createdAt: "2026-01-01T00:00:00.000Z",
- };
- messageQ.activateNextBufferedMessage.mockResolvedValue(activated);
- conversationQ.getConversation.mockResolvedValue(null);
-
- const result = await service.dispatchNextBufferedMessage("c1", "w1");
-
- expect(result).toBeNull();
- expect(messageQ.revertToBuffered).toHaveBeenCalledWith({}, "msg4");
- });
- });
-
- // ── completeTask dispatches buffered ─────────────────────────────
-
- describe("completeTask dispatches buffered messages", () => {
- it("calls dispatchNextBufferedMessage after completion", async () => {
- const task = {
- id: "t1",
- agentId: "a1",
- workspaceId: "w1",
- conversationId: "c1",
- status: "completed",
- };
- taskQ.completeTask.mockResolvedValue(task);
- taskQ.countRunningTasks.mockResolvedValue(0);
- agentQ.updateAgentStatus.mockResolvedValue(undefined);
-
- await service.completeTask("t1", "w1", JSON.stringify({}), "sess-1");
-
- expect(messageQ.activateNextBufferedMessage).toHaveBeenCalledWith({}, "c1");
- });
- });
-
- // ── failTask dispatches buffered ────────────────────────────────
-
- describe("failTask dispatches buffered messages", () => {
- it("calls dispatchNextBufferedMessage after failure", async () => {
+ describe("failTask runtime-error message", () => {
+ it("creates a role=assistant message with metadata.error_source=runtime + provider", async () => {
const task = {
id: "t1",
agentId: "a1",
workspaceId: "w1",
conversationId: "c1",
status: "failed",
+ runtimeId: "r1",
};
taskQ.failTask.mockResolvedValue(task);
taskQ.countRunningTasks.mockResolvedValue(0);
agentQ.updateAgentStatus.mockResolvedValue(undefined);
+ runtimeQ.getAgentRuntime.mockResolvedValue({ provider: "claude_code" });
- await service.failTask("t1", "w1", "err");
+ await service.failTask("t1", "w1", "boom");
- expect(messageQ.activateNextBufferedMessage).toHaveBeenCalledWith({}, "c1");
+ expect(messageQ.createMessage).toHaveBeenCalledWith(
+ {},
+ expect.objectContaining({
+ conversationId: "c1",
+ role: "assistant",
+ content: "boom",
+ taskId: "t1",
+ metadata: JSON.stringify({ error_source: "runtime", provider: "claude_code" }),
+ })
+ );
});
});
@@ -831,7 +667,6 @@ describe("TaskService", () => {
expect(messageQ.createMessage).not.toHaveBeenCalled();
expect(taskQ.countRunningTasks).not.toHaveBeenCalled();
expect(agentQ.updateAgentStatus).not.toHaveBeenCalled();
- expect(messageQ.activateNextBufferedMessage).not.toHaveBeenCalled();
});
});
@@ -856,8 +691,11 @@ describe("TaskService", () => {
expect(result!.status).toBe("cancelled");
expect(taskQ.createTask).not.toHaveBeenCalled();
expect(messageQ.createMessage).toHaveBeenCalledWith({}, expect.objectContaining({
- content: "Task cancelled by user",
+ content: "Task cancelled by you",
taskId: "t1",
+ // Stamped as a lifecycle note so the chat renders it as a centered
+ // system line, not an agent bubble.
+ metadata: JSON.stringify({ kind: "lifecycle" }),
}));
});
@@ -942,19 +780,6 @@ describe("TaskService", () => {
}));
});
- it("dispatches next buffered message after cancel", async () => {
- const task = { id: "t1", status: "running", agentId: "a1", runtimeId: "r1", conversationId: "c1" };
- taskQ.getActiveTaskByConversation.mockResolvedValue(task);
- taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });
- taskQ.createTask.mockResolvedValue({ id: "kt1" });
- taskQ.countRunningTasks.mockResolvedValue(0);
- runtimeQ.getAgentRuntime.mockResolvedValue({ daemonId: "d1" });
-
- await service.cancelActiveTask("c1", "w1");
-
- expect(messageQ.activateNextBufferedMessage).toHaveBeenCalledWith({}, "c1");
- });
-
it("daemon.kill payload includes agentId from active task", async () => {
const task = { id: "t1", status: "running", agentId: "agent_xyz", runtimeId: "r1", conversationId: "c1" };
taskQ.getActiveTaskByConversation.mockResolvedValue(task);
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
index e895b5647..be634ee63 100644
--- a/src/web/src/lib/services/task.ts
+++ b/src/web/src/lib/services/task.ts
@@ -2,7 +2,7 @@ import type { Database } from "@alook/shared";
import { queries, TASK_TYPES, MAX_TASKS_PER_TRACE } from "@alook/shared";
import { log } from "@/lib/logger";
import { broadcastToUser, broadcastToDaemon } from "@/lib/broadcast";
-import { messageToResponse, taskToResponse } from "@/lib/api/responses";
+import { messageToResponse } from "@/lib/api/responses";
import { invalidate, cacheKeys } from "@/lib/cache";
import { TaskPayloadBuilder } from "@/lib/services/task-payload-builder";
@@ -158,34 +158,13 @@ export class TaskService {
throw new Error(`cannot complete task in '${status}' status`);
}
- const payload = parsed as Record<string, unknown>;
- const output =
- typeof payload?.output === "string" ? payload.output : "";
-
- if (output) {
- const msg = await messageQueries.createMessage(this.db, {
- conversationId: task.conversationId,
- role: "assistant",
- content: output,
- taskId,
- });
-
- try {
- const conversation = await conversationQueries.getConversation(this.db, task.conversationId, workspaceId);
- if (conversation) {
- broadcastToUser(conversation.userId, {
- type: "conversation.message",
- conversationId: task.conversationId,
- message: messageToResponse(msg),
- }).catch(() => {});
- }
- } catch {
- // non-critical: don't let broadcast failure block task lifecycle
- }
- }
-
+ // The agent owns its voice: the success reply bubble is now authored
+ // explicitly via `alook sync send-dm` (the agent-DM endpoint), NOT extracted
+ // from the task's final `output`. So completeTask no longer creates a
+ // `role:"assistant"` message — it only settles the task lifecycle. `output`
+ // 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);
- await this.dispatchNextBufferedMessage(task.conversationId, task.workspaceId);
return task;
}
@@ -242,7 +221,6 @@ export class TaskService {
await this.reconcileAgentStatus(task.agentId, task.workspaceId);
await this.syncIssueStatusFromTask(task, "failed");
- await this.dispatchNextBufferedMessage(task.conversationId, task.workspaceId);
return task;
}
@@ -291,7 +269,6 @@ export class TaskService {
}
await this.reconcileAgentStatus(task.agentId, task.workspaceId);
- await this.dispatchNextBufferedMessage(task.conversationId, task.workspaceId);
return task;
}
@@ -321,7 +298,7 @@ export class TaskService {
return { oldTask: marked, newTask };
}
- async cancelActiveTask(conversationId: string, workspaceId: string, opts?: { skipDispatch?: boolean; reason?: string }) {
+ async cancelActiveTask(conversationId: string, workspaceId: string, opts?: { reason?: string }) {
const activeTask = await taskQueries.getActiveTaskByConversation(this.db, conversationId, workspaceId);
if (!activeTask) return null;
@@ -355,17 +332,17 @@ export class TaskService {
}
}
+ // Stamp lifecycle messages (cancelled/superseded) so the chat renders them
+ // as quiet centered system notes, not agent speech bubbles.
await messageQueries.createMessage(this.db, {
conversationId,
role: "assistant",
- content: opts?.reason ?? "Task cancelled by user",
+ content: opts?.reason ?? "Task cancelled by you",
taskId: activeTask.id,
+ metadata: JSON.stringify({ kind: "lifecycle" }),
});
await this.reconcileAgentStatus(activeTask.agentId, workspaceId);
- if (!opts?.skipDispatch) {
- await this.dispatchNextBufferedMessage(conversationId, workspaceId);
- }
return cancelled;
}
@@ -376,65 +353,6 @@ export class TaskService {
invalidate(cacheKeys.activeTaskCounts(workspaceId)).catch(() => {});
}
- async dispatchNextBufferedMessage(conversationId: string, workspaceId: string) {
- const activated = await messageQueries.activateNextBufferedMessage(this.db, conversationId);
- if (!activated) return null;
-
- const conversation = await conversationQueries.getConversation(this.db, conversationId, workspaceId);
- if (!conversation) {
- log.warn("dispatchNextBufferedMessage: conversation not found", { conversationId });
- await messageQueries.revertToBuffered(this.db, activated.id).catch((revertErr) => {
- log.error("dispatchNextBufferedMessage: failed to revert message status", { messageId: activated.id, revertErr });
- });
- return null;
- }
-
- const userId = conversation.userId;
-
- try {
- const contextKey = conversationId;
- const attachmentIds = activated.attachmentIds ? JSON.parse(activated.attachmentIds) as string[] : [];
- const latestTask = await taskQueries.getLatestTaskForConversation(this.db, conversationId);
- const traceId = latestTask?.traceId ?? null;
- const task = await this.enqueueTask(
- conversation.agentId,
- conversationId,
- workspaceId,
- activated.content,
- TASK_TYPES.USER_DM_MESSAGE,
- {
- contextKey,
- context: attachmentIds.length > 0 ? { attachment_ids: attachmentIds } : undefined,
- traceId,
- parentTaskId: null,
- },
- );
-
- await messageQueries.updateMessageTaskId(this.db, activated.id, task.id);
-
- broadcastToUser(userId, {
- type: "followup.dispatched",
- conversationId,
- message: messageToResponse(activated),
- task: taskToResponse(task),
- }).catch(() => {});
-
- return task;
- } catch (err) {
- log.warn("dispatchNextBufferedMessage: enqueueTask failed", { conversationId, err });
- await messageQueries.revertToBuffered(this.db, activated.id).catch((revertErr) => {
- log.error("dispatchNextBufferedMessage: failed to revert message status", { messageId: activated.id, revertErr });
- });
- broadcastToUser(userId, {
- type: "followup.dispatch_failed",
- conversationId,
- messageId: activated.id,
- error: err instanceof Error ? err.message : "Failed to dispatch follow-up",
- }).catch(() => {});
- return null;
- }
- }
-
async cancelTrace(traceId: string, workspaceId: string, opts?: { reason?: string }) {
const tasks = await taskQueries.getTraceTree(this.db, traceId, workspaceId);
const activeConvIds = [...new Set(
@@ -444,7 +362,7 @@ export class TaskService {
)];
for (const convId of activeConvIds) {
try {
- await this.cancelActiveTask(convId, workspaceId, { skipDispatch: true, reason: opts?.reason });
+ await this.cancelActiveTask(convId, workspaceId, { reason: opts?.reason });
} catch (err) {
log.warn("cancelTrace: failed to cancel task", { traceId, convId, err });
}
diff --git a/src/web/src/test/e2e/agent-link-upsert.test.ts b/src/web/src/test/e2e/agent-link-upsert.test.ts
new file mode 100644
index 000000000..49776727c
--- /dev/null
+++ b/src/web/src/test/e2e/agent-link-upsert.test.ts
@@ -0,0 +1,96 @@
+import { describe, it, expect, beforeAll, afterAll } from "vitest"
+import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun } from "@alook/test-utils"
+import { nanoid } from "nanoid"
+
+let seed: TestSeed
+let targetAgentId: string
+
+beforeAll(() => {
+ seed = seedTestData()
+ // Second agent in the same workspace, owned by the same user, to link against.
+ targetAgentId = `ag_${nanoid()}`
+ const now = new Date().toISOString()
+ sqlRun(
+ `INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+ targetAgentId, seed.workspaceId, "Target Agent", seed.runtimeId, `target-${nanoid(6).toLowerCase()}`, seed.userId, now, now,
+ )
+})
+
+afterAll(() => {
+ sqlRun(
+ `DELETE FROM agent_link WHERE (source_agent_id = ? AND target_agent_id = ?) OR (source_agent_id = ? AND target_agent_id = ?)`,
+ seed.agentId, targetAgentId, targetAgentId, seed.agentId,
+ )
+ sqlRun(`DELETE FROM agent WHERE id = ?`, targetAgentId)
+ cleanupTestData(seed)
+})
+
+function upsert(body: unknown) {
+ return tokenRequest(
+ `/api/agent-links?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}`,
+ seed.machineToken,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ },
+ )
+}
+
+describe("PUT /api/agent-links (upsert)", () => {
+ it("creates the link on first call (201, created:true)", async () => {
+ const res = await upsert({ target_agent_id: targetAgentId, instruction: "first instruction" })
+ expect(res.status).toBe(201)
+ const data = await res.json() as { created: boolean; instruction: string; source_agent_id: string; target_agent_id: string }
+ expect(data.created).toBe(true)
+ expect(data.instruction).toBe("first instruction")
+ const ids = [data.source_agent_id, data.target_agent_id]
+ expect(ids).toContain(seed.agentId)
+ expect(ids).toContain(targetAgentId)
+ })
+
+ it("replaces the instruction on second call (200, created:false) — single row", async () => {
+ const res = await upsert({ target_agent_id: targetAgentId, instruction: "second instruction" })
+ expect(res.status).toBe(200)
+ const data = await res.json() as { created: boolean; instruction: string }
+ expect(data.created).toBe(false)
+ expect(data.instruction).toBe("second instruction")
+
+ // Exactly one row for this pair (canonicalization held); instruction replaced.
+ const list = await tokenRequest(
+ `/api/agent-links?workspace_id=${seed.workspaceId}&limit=500`,
+ seed.machineToken,
+ { method: "GET" },
+ )
+ const links = await list.json() as Array<{ source_agent_id: string; target_agent_id: string; instruction: string }>
+ const forPair = links.filter((l) =>
+ (l.source_agent_id === seed.agentId && l.target_agent_id === targetAgentId) ||
+ (l.source_agent_id === targetAgentId && l.target_agent_id === seed.agentId),
+ )
+ expect(forPair).toHaveLength(1)
+ expect(forPair[0].instruction).toBe("second instruction")
+ })
+
+ it("returns 400 on self-link", async () => {
+ const res = await upsert({ target_agent_id: seed.agentId, instruction: "x" })
+ expect(res.status).toBe(400)
+ })
+
+ it("returns 404 for a target not in the workspace", async () => {
+ const res = await upsert({ target_agent_id: "ag_nonexistent_xyz", instruction: "x" })
+ expect(res.status).toBe(404)
+ })
+
+ it("returns 400 without agentId query param", async () => {
+ const res = await tokenRequest(
+ `/api/agent-links?workspace_id=${seed.workspaceId}`,
+ seed.machineToken,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ target_agent_id: targetAgentId, instruction: "x" }),
+ },
+ )
+ expect(res.status).toBe(400)
+ })
+})
diff --git a/src/web/src/test/e2e/buffered-messages.test.ts b/src/web/src/test/e2e/buffered-messages.test.ts
deleted file mode 100644
index 5dfb12189..000000000
--- a/src/web/src/test/e2e/buffered-messages.test.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"
-
-let seed: TestSeed
-let conversationId: string
-let activeTaskId: string
-
-beforeAll(async () => {
- seed = seedTestData()
- // Create a conversation
- const res = await tokenRequest(
- `/api/conversations?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ agent_id: seed.agentId }),
- },
- )
- const data = await res.json() as { id: string }
- conversationId = data.id
-
- activeTaskId = `task_${Date.now()}`
- const now = new Date().toISOString()
- sqlRun(
- `INSERT INTO agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, status, type, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, activeTaskId, seed.agentId, seed.runtimeId, seed.workspaceId, conversationId, 'active task', 'running', 'user_dm_message', now
- )
-})
-afterAll(() => cleanupTestData(seed))
-
-describe("buffered messages CRUD", () => {
- let bufferedMsgId: string
-
- it("POST creates a buffered message", async () => {
- const res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Follow-up 1" }),
- },
- )
- expect(res.status).toBe(201)
- const data = await res.json() as { message: Record<string, unknown> }
- expect(data.message.content).toBe("Follow-up 1")
- expect(data.message.status).toBe("buffered")
- bufferedMsgId = data.message.id as string
- })
-
- it("GET returns buffered messages in order", async () => {
- // Create a second one
- await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Follow-up 2" }),
- },
- )
-
- const res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- )
- expect(res.status).toBe(200)
- const data = await res.json() as Array<Record<string, unknown>>
- expect(data.length).toBeGreaterThanOrEqual(2)
- expect(data[0].content).toBe("Follow-up 1")
- expect(data[1].content).toBe("Follow-up 2")
- })
-
- it("buffered messages are excluded from normal message listing", async () => {
- const res = await tokenRequest(
- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- )
- expect(res.status).toBe(200)
- const body = await res.json() as { messages: Array<Record<string, unknown>>; has_more: boolean }
- const buffered = body.messages.filter((m) => m.status === "buffered")
- expect(buffered.length).toBe(0)
- })
-
- it("DELETE single removes a specific buffered message", async () => {
- const res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages/${bufferedMsgId}?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- { method: "DELETE" },
- )
- expect(res.status).toBe(204)
-
- // Verify it's gone
- const listRes = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- )
- const remaining = await listRes.json() as Array<Record<string, unknown>>
- expect(remaining.find((m) => m.id === bufferedMsgId)).toBeUndefined()
- })
-
- it("DELETE bulk removes all buffered messages", async () => {
- // Create a couple more
- await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Bulk delete test 1" }),
- },
- )
- await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Bulk delete test 2" }),
- },
- )
-
- const res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- { method: "DELETE" },
- )
- expect(res.status).toBe(204)
-
- const listRes = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- )
- const remaining = await listRes.json() as Array<Record<string, unknown>>
- expect(remaining.length).toBe(0)
- })
-
- it("POST rejects with 429 when 20 buffered messages exist", async () => {
- // Create 20 messages
- for (let i = 0; i < 20; i++) {
- await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: `Cap test ${i}` }),
- },
- )
- }
-
- // 21st should fail
- const res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Over the limit" }),
- },
- )
- expect(res.status).toBe(429)
-
- // Cleanup
- await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- { method: "DELETE" },
- )
- })
-
- it("cannot delete a non-buffered message via buffered endpoint", async () => {
- // Create a normal message via SQL
- const msgId = `test_active_${Date.now()}`
- const now = new Date().toISOString()
- sqlRun(
- `INSERT INTO message (id, conversation_id, role, content, status, created_at) VALUES (?, ?, ?, ?, ?, ?)`, msgId, conversationId, 'user', 'normal msg', 'active', now
- )
-
- const res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages/${msgId}?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- { method: "DELETE" },
- )
- expect(res.status).toBe(400)
-
- // Cleanup
- sqlRun(`DELETE FROM message WHERE id = ?`, msgId)
- })
-})
diff --git a/src/web/src/test/e2e/conversation-init.test.ts b/src/web/src/test/e2e/conversation-init.test.ts
index 154c71cf9..dd6ad9dd8 100644
--- a/src/web/src/test/e2e/conversation-init.test.ts
+++ b/src/web/src/test/e2e/conversation-init.test.ts
@@ -48,9 +48,7 @@ describe("GET /api/conversations/[id]/init", () => {
expect(typeof data.has_more_conversations).toBe("boolean")
expect(typeof data.has_more_artifacts).toBe("boolean")
expect(Array.isArray(data.artifacts)).toBe(true)
- expect(Array.isArray(data.buffered_messages)).toBe(true)
expect(Array.isArray(data.flagged_message_ids)).toBe(true)
- expect(typeof data.thinking_counts).toBe("object")
expect(typeof data.cache_valid).toBe("boolean")
expect(typeof data.message_count).toBe("number")
})
diff --git a/src/web/src/test/e2e/follow-up-auto-dispatch.test.ts b/src/web/src/test/e2e/follow-up-auto-dispatch.test.ts
deleted file mode 100644
index 353e633da..000000000
--- a/src/web/src/test/e2e/follow-up-auto-dispatch.test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * Regression: Follow-up messages auto-dispatch after task completion
- * Bug pattern: Buffered messages sent during an active task were not automatically
- * dispatched as a new task when the active task completed.
- * Refs: #194 (Priority 2)
- */
-import { describe, it, expect, beforeAll, afterAll } from "vitest"
-import { randomUUID } from "crypto"
-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlQuery } from "@alook/test-utils"
-
-let seed: TestSeed
-let conversationId: string
-let firstTaskId: string
-
-beforeAll(async () => {
- seed = seedTestData()
-
- // Create conversation and first task
- const convRes = await tokenRequest(
- `/api/conversations?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ agent_id: seed.agentId }),
- },
- )
- const convData = await convRes.json() as { id: string }
- conversationId = convData.id
-
- // Send initial message → creates first task
- const msgRes = await tokenRequest(
- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Initial task" }),
- },
- )
- const msgData = await msgRes.json() as { task?: { id: string } | null }
- firstTaskId = msgData.task!.id
-
- // Poll + start the task
- await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),
- })
- await tokenRequest(`/api/daemon/tasks/${firstTaskId}/start`, seed.machineToken, { method: "POST" })
-})
-afterAll(() => cleanupTestData(seed))
-
-describe("regression: follow-up auto-dispatch on task completion", () => {
- it("buffered messages are created while task is running", async () => {
- const buf1Res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Follow-up message 1" }),
- },
- )
- expect(buf1Res.status).toBe(201)
-
- const buf2Res = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: "Follow-up message 2" }),
- },
- )
- expect(buf2Res.status).toBe(201)
-
- // Verify they exist as buffered
- const listRes = await tokenRequest(
- `/api/conversations/${conversationId}/buffered-messages?workspace_id=${seed.workspaceId}`,
- seed.machineToken,
- )
- const buffered = await listRes.json() as Array<Record<string, unknown>>
- expect(buffered.length).toBeGreaterThanOrEqual(2)
- })
-
- it("completing first task auto-dispatches a new task with first buffered message", async () => {
- const completeRes = await tokenRequest(
- `/api/daemon/tasks/${firstTaskId}/complete`,
- seed.machineToken,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ output: "First task done", session_id: `sess_${randomUUID().slice(0, 8)}` }),
- },
- )
- expect(completeRes.status).toBe(200)
-
- // Wait for auto-dispatch
- await new Promise((r) => setTimeout(r, 1500))
-
- // There should be a new task created with the buffered content
- const tasks = sqlQuery<Record<string, unknown>>(
- `SELECT * FROM agent_task_queue WHERE conversation_id = '${conversationId}' AND id != '${firstTaskId}' AND status IN ('queued', 'dispatched') ORDER BY created_at ASC`,
- )
- expect(tasks.length).toBeGreaterThanOrEqual(1)
- expect(tasks[0].prompt).toBe("Follow-up message 1")
- expect(tasks[0].type).toBe("user_dm_message")
- })
-
- it("second buffered message dispatches after the first follow-up completes", async () => {
- // Find and complete the auto-dispatched task
- const tasks = sqlQuery<{ id: string; status: string }>(
- `SELECT id, status FROM agent_task_queue WHERE conversation_id = '${conversationId}' AND prompt = 'Follow-up message 1'`,
- )
- expect(tasks).toHaveLength(1)
- const followUpTaskId = tasks[0].id
-
- // Poll + start + complete
- if (tasks[0].status === "queued") {
- await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),
- })
- }
- await tokenRequest(`/api/daemon/tasks/${followUpTaskId}/start`, seed.machineToken, { method: "POST" })
- await tokenRequest(`/api/daemon/tasks/${followUpTaskId}/complete`, seed.machineToken, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ output: "Follow-up 1 done", session_id: `sess_${randomUUID().slice(0, 8)}` }),
- })
-
- // Wait for second follow-up dispatch
- await new Promise((r) => setTimeout(r, 1500))
-
- const tasks2 = sqlQuery<Record<string, unknown>>(
- `SELECT * FROM agent_task_queue WHERE conversation_id = '${conversationId}' AND prompt = 'Follow-up message 2'`,
- )
- expect(tasks2.length).toBeGreaterThanOrEqual(1)
- expect(tasks2[0].type).toBe("user_dm_message")
- })
-})
diff --git a/vitest.config.ts b/vitest.config.ts
index 0208d2233..8de331279 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -19,6 +19,18 @@ export default defineConfig({
"**/*.d.ts",
"src/cli/src/index.ts",
"src/web/src/**/*.tsx",
+ // React hooks (useEffect/useState/render-time refs) with no jsdom/RTL
+ // test path — excluded for the same reason as the .tsx exclude above.
+ // Their pure helpers are covered via separate unit tests where extracted
+ // (e.g. chat-message-utils.ts, which IS covered). Listed individually
+ // (not a blanket hooks glob) so genuinely-testable non-React hooks stay
+ // included.
+ "src/web/src/hooks/use-agent-chat.ts",
+ "src/web/src/hooks/use-chat-sheets.ts",
+ "src/web/src/hooks/use-file-attachments.ts",
+ "src/web/src/hooks/use-message-flags.ts",
+ "src/web/src/hooks/use-text-selection-quote.ts",
+ "src/web/src/components/agent-chat/use-rotating-placeholder.ts",
],
},
},