Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(chat): cache per-channel latest-created conversation to kill wrong-conversation flash

Gus5b66150a0427
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 15af26e13..2d21020b7 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,6 +1,6 @@
import { describe, it, expect } from "vitest";
import type { Message, Artifact } from "@alook/shared";
-import { sortMessages, mergeMessages, buildTimeline, addBufferedIfNew, replaceOptimisticBuffered, getEventIconType, reorderArtifactsAfterAssistant } from "./agent-chat-view";
+import { sortMessages, mergeMessages, buildTimeline, addBufferedIfNew, replaceOptimisticBuffered, getEventIconType, reorderArtifactsAfterAssistant, shouldPersistPointerForLoad, pointerRefreshTargetForTaskCreated } from "./agent-chat-view";
import type { NapMarker } from "./agent-chat-view";
function msg(id: string, created_at: string, role: "user" | "assistant" | "event" = "user", content = ""): Message {
@@ -683,3 +683,131 @@ describe("replaceOptimisticBuffered", () => {
expect(result.map((m) => m.id)).toEqual(["m1", "real-100", "temp-200"]);
});
});
+
+// ---------------------------------------------------------------------------
+// Wrong-conversation flash fix: per-channel "latest-created" pointer semantics.
+//
+// These cover the pure decision logic the fix is built on. The full component
+// load/swap flow (paint → check-fresh → swap) cannot be rendered in this
+// node-env Vitest suite (no jsdom/RTL), so the FLOW-level cases from the plan
+// (TC2/TC3/TC7/TC10) are exercised through the pure predicates the flow now
+// delegates to, plus the IndexedDB round-trip in chat-cache.test.ts (TC1).
+// ---------------------------------------------------------------------------
+
+describe("shouldPersistPointerForLoad (TODO-1: slow-path-only write gate)", () => {
+ it("TC9 — fast path (targetConvId present) does NOT write the pointer", () => {
+ // Opening ?conv=<old-id>: targetConvId is the explicit, possibly-old conv.
+ expect(shouldPersistPointerForLoad("conv_old")).toBe(false);
+ });
+
+ it("TC2/TC3 — slow path (no targetConvId) DOES write the pointer", () => {
+ // Param-less open: convId is server-resolved (latest-created) → persist it.
+ expect(shouldPersistPointerForLoad(null)).toBe(true);
+ expect(shouldPersistPointerForLoad(undefined)).toBe(true);
+ });
+
+ it("treats empty string targetConvId as no explicit target (slow path)", () => {
+ // `?conv=` with an empty value never resolves a real conversation; the load
+ // falls through to the slow path, so writing the resolved latest is correct.
+ expect(shouldPersistPointerForLoad("")).toBe(true);
+ });
+});
+
+describe("pointerRefreshTargetForTaskCreated (TODO-2: WS-driven refresh scope)", () => {
+ const base = {
+ agentId: "agent_a",
+ activeChannel: "default",
+ currentPointerConvId: "conv_current",
+ };
+ const task = (over: Partial<{ agent_id: string; channel: string | null; conversation_id: string }>) => ({
+ agent_id: over.agent_id ?? "agent_a",
+ channel: over.channel === undefined ? null : over.channel,
+ conversation_id: over.conversation_id ?? "conv_new",
+ });
+
+ it("TC4 — newer conversation for this agent+channel → returns the new conv id", () => {
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ task: task({ agent_id: "agent_a", channel: "default", conversation_id: "conv_new" }),
+ }),
+ ).toBe("conv_new");
+ });
+
+ it("TC4 — null event channel normalizes to 'default' and matches the active default channel", () => {
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ task: task({ channel: null, conversation_id: "conv_new" }),
+ }),
+ ).toBe("conv_new");
+ });
+
+ it("matches a non-default named channel", () => {
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ activeChannel: "ops",
+ task: task({ channel: "ops", conversation_id: "conv_new" }),
+ }),
+ ).toBe("conv_new");
+ });
+
+ it("TC5 — different agent → SKIP (returns null, never touches this pointer)", () => {
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ task: task({ agent_id: "agent_b", conversation_id: "conv_new" }),
+ }),
+ ).toBeNull();
+ });
+
+ it("TC5 — different channel → SKIP", () => {
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ activeChannel: "default",
+ task: task({ channel: "ops", conversation_id: "conv_new" }),
+ }),
+ ).toBeNull();
+ });
+
+ it("no-op when the event already points at the current pointer conversation", () => {
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ currentPointerConvId: "conv_new",
+ task: task({ conversation_id: "conv_new" }),
+ }),
+ ).toBeNull();
+ });
+
+ it("writes even when there is no current pointer yet (null current)", () => {
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ currentPointerConvId: null,
+ task: task({ conversation_id: "conv_new" }),
+ }),
+ ).toBe("conv_new");
+ });
+
+ it("TC6 — undefined channel on the event normalizes to 'default' (no incorrect cross-channel write)", () => {
+ // An event with no channel info is treated as the default channel, so it only
+ // affects the default-channel pointer — never a named channel's pointer.
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ activeChannel: "ops",
+ task: { agent_id: "agent_a", channel: undefined, conversation_id: "conv_new" },
+ }),
+ ).toBeNull();
+ expect(
+ pointerRefreshTargetForTaskCreated({
+ ...base,
+ activeChannel: "default",
+ task: { agent_id: "agent_a", channel: undefined, conversation_id: "conv_new" },
+ }),
+ ).toBe("conv_new");
+ });
+});
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 390006f6b..21c623de6 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -420,6 +420,61 @@ export function buildTimeline(
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(() => {
@@ -930,6 +985,16 @@ export function AgentChatView({
// 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,
@@ -1037,7 +1102,18 @@ export function AgentChatView({
// the cache meta (just updated by mergeCachedMessages on the stale
// path) so the stored newest id is authoritative rather than inferred
// from page order.
- if (loadConvIdRef.current === convId) {
+ //
+ // 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(
@@ -1118,6 +1194,13 @@ export function AgentChatView({
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,
@@ -1852,6 +1935,48 @@ export function AgentChatView({
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
@@ -1950,7 +2075,7 @@ export function AgentChatView({
toast.error(msg.error || "Failed to dispatch follow-up");
}
});
- }, [subscribeWs, conversation?.id, workspaceId]);
+ }, [subscribeWs, conversation?.id, workspaceId, agentId]);
useEffect(() => {
return subscribeReconnect(() => {
diff --git a/src/web/src/lib/chat-cache.test.ts b/src/web/src/lib/chat-cache.test.ts
index 1a8af6415..345d619c5 100644
--- a/src/web/src/lib/chat-cache.test.ts
+++ b/src/web/src/lib/chat-cache.test.ts
@@ -325,6 +325,27 @@ describe("chat-cache", () => {
// Pointer to conv_2 is untouched.
expect((await getLastOpenConversation("agent_c", "chan_z", WORKSPACE_ID))?.conversation_id).toBe("conv_2");
});
+
+ // TC8 — the WS-driven refresh (task.created) may write serverMessageCount=0
+ // when there is no local cache for a brand-new conversation. The store must
+ // round-trip that 0 faithfully so the slow-path read's `serverMessageCount >
+ // 0` gate sees it and falls back to the skeleton (never optimistically
+ // paints empty/wrong content). This asserts the storage half of that
+ // invariant; the read-site gate itself lives in agent-chat-view.tsx.
+ it("TC8 — round-trips serverMessageCount=0 (non-poisoning WS-path write)", async () => {
+ await setLastOpenConversation("agent_ws", "chan_x", {
+ conversation_id: "conv_brand_new",
+ newestMessageId: null,
+ serverMessageCount: 0,
+ }, WORKSPACE_ID);
+
+ const entry = await getLastOpenConversation("agent_ws", "chan_x", WORKSPACE_ID);
+ expect(entry?.conversation_id).toBe("conv_brand_new");
+ // The read site gates optimism on `serverMessageCount > 0`; a stored 0
+ // therefore disables the optimistic paint for this pointer.
+ expect(entry?.serverMessageCount).toBe(0);
+ expect(entry!.serverMessageCount > 0).toBe(false);
+ });
});
describe("evictLRU", () => {
diff --git a/src/web/src/lib/chat-cache.ts b/src/web/src/lib/chat-cache.ts
index e61bdb860..c43d01a90 100644
--- a/src/web/src/lib/chat-cache.ts
+++ b/src/web/src/lib/chat-cache.ts
@@ -12,10 +12,24 @@ export interface CacheMeta {
}
/**
- * Pointer to the last-open conversation for a given agent+channel, used to
- * render the multi-conversation chat page cache-first (without a gating
+ * Pointer to the **latest-created** conversation for a given agent+channel, used
+ * to render the multi-conversation chat page cache-first (without a gating
* network round-trip to resolve "which conversation is this?").
*
+ * Semantics: this is the latest-created conversation as last known to THIS
+ * client — matching the server's `check-fresh` definition of "current"
+ * (`getOrCreateAgentConversation` → `orderBy(desc(createdAt))`). It is NOT "the
+ * conversation the user last manually opened". Honoring those two as the same
+ * concept caused the wrong-conversation flash: an explicit `?conv=<old-id>` open
+ * would record an old conversation, then the param-less open painted it and
+ * visibly swapped to the server's latest. Only writes that establish
+ * "latest-created" (slow-path server-resolved load, chatInit fallback, and the
+ * `task.created` WS refresh) may update this pointer.
+ *
+ * Cross-device caveat: if another device/tab just created a newer conversation
+ * this client hasn't heard of yet, the pointer may briefly lag until the next
+ * `check-fresh` corrects it — the rare residual case, no longer the common one.
+ *
* The DB is already scoped per-workspace (`alook-chat-cache-${workspaceId}`),
* so the key only needs to encode agent + channel.
*/
@@ -338,9 +352,17 @@ export async function getLastOpenConversation(
}
/**
- * Write the last-open conversation pointer for an agent+channel. Should only be
- * called with server-confirmed values (newest id / count) so the next open's
- * freshness compare is accurate.
+ * Write the per-channel pointer to the **latest-created** conversation for an
+ * agent+channel (see {@link LastOpenEntry}). Call ONLY when establishing
+ * latest-created semantics — i.e. from a server-resolved (slow-path) load, the
+ * chatInit fallback, or the `task.created` WS refresh. Do NOT call it for an
+ * explicit `?conv=<id>` (fast-path) open: that records "last opened", not
+ * "latest", and reintroduces the wrong-conversation flash.
+ *
+ * Values should be server-confirmed where available so the next open's freshness
+ * compare is accurate. The `task.created` path derives `serverMessageCount` from
+ * the locally-cached count (may under-count → at worst the next read falls back
+ * to the skeleton via the `serverMessageCount > 0` gate, never wrong content).
*/
export async function setLastOpenConversation(
agentId: string,