From b571d8e51f3615ba67091f4d7391dcffcf7f6b90 Mon Sep 17 00:00:00 2001 From: zrmarley Date: Tue, 8 Sep 2026 16:12:05 -0400 Subject: [PATCH] fix: tighten thread activity scoping Co-authored-by: Zach Marley Signed-off-by: Zach Marley --- .../activity/ThreadActivityPanel.test.mjs | 49 ++++++ .../agents/activity/ThreadActivityPanel.tsx | 152 +++++++++++++++--- .../agents/activity/useThreadScope.test.mjs | 86 ++++++++++ .../agents/activity/useThreadScope.ts | 86 +++++++--- .../agent-activity-panel-screenshots.spec.ts | 93 ++++++++++- 5 files changed, 419 insertions(+), 47 deletions(-) create mode 100644 desktop/src/features/agents/activity/ThreadActivityPanel.test.mjs create mode 100644 desktop/src/features/agents/activity/useThreadScope.test.mjs diff --git a/desktop/src/features/agents/activity/ThreadActivityPanel.test.mjs b/desktop/src/features/agents/activity/ThreadActivityPanel.test.mjs new file mode 100644 index 0000000000..e2d5626047 --- /dev/null +++ b/desktop/src/features/agents/activity/ThreadActivityPanel.test.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { + agentsWithThreadActivity, + threadScopeIsLive, + turnFilterForThreadAgents, +} from "./ThreadActivityPanel.tsx"; + +describe("threadScopeIsLive", () => { + it("requires a normalized pubkey to be both open in the thread and working in the channel", () => { + assert.equal(threadScopeIsLive(new Set(["Agent-A"]), []), false); + assert.equal(threadScopeIsLive(new Set(), ["agent-a"]), false); + assert.equal(threadScopeIsLive(new Set(["agent-a"]), ["agent-b"]), false); + assert.equal(threadScopeIsLive(new Set([" AGENT-A "]), ["agent-a"]), true); + assert.equal(threadScopeIsLive(new Set(["agent-a"]), [" AGENT-A "]), true); + }); +}); + +describe("agentsWithThreadActivity", () => { + it("keeps only agents with turn activity in the thread, matching pubkeys case-insensitively", () => { + const agents = [ + { pubkey: "Agent-A", name: "Has activity" }, + { pubkey: "agent-b", name: "Other thread only" }, + { pubkey: "agent-c", name: "Empty bucket" }, + ]; + const turnIdsByAgent = new Map([ + ["agent-a", new Set(["turn-1"])], + ["agent-c", new Set()], + ]); + + assert.deepEqual(agentsWithThreadActivity(agents, turnIdsByAgent), [ + agents[0], + ]); + }); +}); + +describe("turnFilterForThreadAgents", () => { + it("keys the thread turn filter by input agent pubkey casing", () => { + const turnIds = new Set(["turn-1"]); + const filter = turnFilterForThreadAgents( + [{ pubkey: "Agent-A", name: "Has activity" }], + new Map([["agent-a", turnIds]]), + ); + + assert.equal(filter.get("Agent-A"), turnIds); + assert.equal(filter.has("agent-a"), false); + }); +}); diff --git a/desktop/src/features/agents/activity/ThreadActivityPanel.tsx b/desktop/src/features/agents/activity/ThreadActivityPanel.tsx index 1de132159a..5e7b3e28d0 100644 --- a/desktop/src/features/agents/activity/ThreadActivityPanel.tsx +++ b/desktop/src/features/agents/activity/ThreadActivityPanel.tsx @@ -11,7 +11,7 @@ import * as React from "react"; import { useAgentSession } from "@/shared/context/AgentSessionContext"; import { cn } from "@/shared/lib/cn"; -import { truncatePubkey } from "@/shared/lib/pubkey"; +import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey"; import { useChannelWorkingAgentPubkeys } from "../agentWorkingSignal"; import { ActivityPanelBody } from "./AgentActivityPanel"; import { colorForAgent } from "./activityModel"; @@ -33,6 +33,7 @@ export interface ThreadActivityPanelProps { } const EMPTY_TURNS: ReturnType = []; +const EMPTY_AGENTS: readonly MultiAgentActivityInput[] = []; export function ThreadActivityPanel({ channelId, @@ -43,24 +44,64 @@ export function ThreadActivityPanel({ const { onOpenAgentSession } = useAgentSession(); const [agentFilter, setAgentFilter] = React.useState(null); - const { scene, agents: sceneAgents } = useMultiAgentActivityScene( - agentFilter - ? agents.filter((agent) => agent.pubkey === agentFilter) - : agents, - channelId, - threadGroup.turnIdsByAgent, + const threadAgents = React.useMemo( + () => agentsWithThreadActivity(agents, threadGroup.turnIdsByAgent), + [agents, threadGroup], + ); + const threadTurnFilter = React.useMemo( + () => turnFilterForThreadAgents(threadAgents, threadGroup.turnIdsByAgent), + [threadAgents, threadGroup], ); - // Reset a filter pointing at an agent that no longer has activity. + const filteredAgents = React.useMemo( + () => + agentFilter + ? threadAgents.filter( + (agent) => normalizePubkey(agent.pubkey) === agentFilter, + ) + : threadAgents, + [agentFilter, threadAgents], + ); + + const sceneState = useMultiAgentActivityScene( + filteredAgents, + channelId, + threadTurnFilter, + ); + const allThreadSceneState = useMultiAgentActivityScene( + agentFilter ? threadAgents : EMPTY_AGENTS, + channelId, + threadTurnFilter, + ); + const scene = sceneState.scene ?? allThreadSceneState.scene; + const sceneAgents = sceneState.scene + ? sceneState.agents + : allThreadSceneState.agents; + + // Reset a filter pointing at an agent that no longer belongs to this thread. + // If the agent still belongs but currently yields no file events, the panel + // falls back to the all-thread scene so the All-agents recovery chip remains + // reachable. React.useEffect(() => { if (!agentFilter) return; - if (!agents.some((agent) => agent.pubkey === agentFilter)) { + if ( + !threadAgents.some( + (agent) => normalizePubkey(agent.pubkey) === agentFilter, + ) + ) { setAgentFilter(null); } - }, [agentFilter, agents]); + }, [agentFilter, threadAgents]); const workingPubkeys = useChannelWorkingAgentPubkeys(channelId); - const anyWorking = workingPubkeys.length > 0; + const threadWorking = threadScopeIsLive( + threadGroup.agentsWithOpenTurn, + workingPubkeys, + ); + const workingSet = React.useMemo( + () => new Set(workingPubkeys.map((pubkey) => normalizePubkey(pubkey))), + [workingPubkeys], + ); const openAgent = React.useCallback( (agentId: string) => { @@ -94,16 +135,18 @@ export function ThreadActivityPanel({ label="All agents" onClick={() => setAgentFilter(null)} /> - {sceneAgentsOrInputs(agents, sceneAgents).map((agent) => ( + {sceneAgentsOrInputs(threadAgents, sceneAgents).map((agent) => ( setAgentFilter((current) => - current === agent.pubkey ? null : agent.pubkey, + current === agent.normalizedPubkey + ? null + : agent.normalizedPubkey, ) } onDoubleClick={() => openAgent(agent.pubkey)} @@ -117,7 +160,7 @@ export function ThreadActivityPanel({ key={`thread:${channelId}:${threadGroup.rootId ?? "unthreaded"}:${agentFilter ?? "all"}`} className={className} scene={scene} - scopeIsLive={anyWorking} + scopeIsLive={threadWorking} scope={scope} setScope={setScope} turns={EMPTY_TURNS} @@ -129,25 +172,84 @@ export function ThreadActivityPanel({ interface ChipAgent { pubkey: string; + normalizedPubkey: string; name: string; index: number; } +export function threadScopeIsLive( + agentsWithOpenTurn: ReadonlySet, + workingPubkeys: readonly string[], +): boolean { + if (workingPubkeys.length === 0 || agentsWithOpenTurn.size === 0) { + return false; + } + const workingSet = new Set( + workingPubkeys.map((pubkey) => normalizePubkey(pubkey)), + ); + return [...agentsWithOpenTurn].some((pubkey) => + workingSet.has(normalizePubkey(pubkey)), + ); +} + +export function agentsWithThreadActivity( + agents: readonly MultiAgentActivityInput[], + turnIdsByAgent: ReadonlyMap>, +): MultiAgentActivityInput[] { + const activePubkeys = new Set( + [...turnIdsByAgent.entries()] + .filter(([, turnIds]) => turnIds.size > 0) + .map(([pubkey]) => normalizePubkey(pubkey)), + ); + return agents.filter((agent) => + activePubkeys.has(normalizePubkey(agent.pubkey)), + ); +} + +export function turnFilterForThreadAgents( + agents: readonly MultiAgentActivityInput[], + turnIdsByAgent: ReadonlyMap>, +): ReadonlyMap> { + if (agents.length === 0) return turnIdsByAgent; + const turnIdsByNormalizedPubkey = new Map( + [...turnIdsByAgent.entries()].map(([pubkey, turnIds]) => [ + normalizePubkey(pubkey), + turnIds, + ]), + ); + const filter = new Map>(); + for (const agent of agents) { + const turnIds = turnIdsByNormalizedPubkey.get( + normalizePubkey(agent.pubkey), + ); + if (turnIds?.size) filter.set(agent.pubkey, turnIds); + } + return filter; +} + /** - * Chip list source: the input agent set, labeled with scene names when the - * derivation produced them (scene agents carry resolved display names). + * Chip list source: the thread-active input agent set, labeled with scene names + * when derivation produced them (scene agents carry resolved display names). */ function sceneAgentsOrInputs( inputs: readonly MultiAgentActivityInput[], sceneAgents: readonly { id: string; name: string }[], ): ChipAgent[] { - const nameById = new Map(sceneAgents.map((agent) => [agent.id, agent.name])); - return inputs.map((input, index) => ({ - pubkey: input.pubkey, - name: - nameById.get(input.pubkey) ?? input.name ?? truncatePubkey(input.pubkey), - index, - })); + const nameById = new Map( + sceneAgents.map((agent) => [normalizePubkey(agent.id), agent.name]), + ); + return inputs.map((input, index) => { + const normalizedPubkey = normalizePubkey(input.pubkey); + return { + pubkey: input.pubkey, + normalizedPubkey, + name: + nameById.get(normalizedPubkey) ?? + input.name ?? + truncatePubkey(input.pubkey), + index, + }; + }); } function AgentChip({ diff --git a/desktop/src/features/agents/activity/useThreadScope.test.mjs b/desktop/src/features/agents/activity/useThreadScope.test.mjs new file mode 100644 index 0000000000..03d09667a4 --- /dev/null +++ b/desktop/src/features/agents/activity/useThreadScope.test.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { + createThreadEventCache, + resolveTurnThreadsRetriable, +} from "./useThreadScope.ts"; + +function relayEvent(id) { + return { + id, + pubkey: "f".repeat(64), + created_at: 1, + kind: 9, + tags: [], + content: "hello", + sig: "sig", + }; +} + +describe("createThreadEventCache", () => { + it("caches successful event lookups", async () => { + let fetches = 0; + const cache = createThreadEventCache(async (eventId) => { + fetches += 1; + return relayEvent(eventId); + }); + + const first = await cache.fetchEventCached("evt"); + const second = await cache.fetchEventCached("evt"); + + assert.equal(first?.id, "evt"); + assert.equal(second, first); + assert.equal(fetches, 1); + }); + + it("caches definitive event-not-found misses", async () => { + let fetches = 0; + const cache = createThreadEventCache(async () => { + fetches += 1; + throw new Error("get_event: event not found"); + }); + + assert.equal(await cache.fetchEventCached("missing"), null); + assert.equal(await cache.fetchEventCached("missing"), null); + assert.equal(fetches, 1); + }); + + it("rejects and evicts transient lookups so later calls can retry", async () => { + let fetches = 0; + const cache = createThreadEventCache(async (eventId) => { + fetches += 1; + if (fetches === 1) { + throw new Error("relay temporarily unavailable"); + } + return relayEvent(eventId); + }); + + await assert.rejects( + () => cache.fetchEventCached("eventual"), + /relay temporarily unavailable/, + ); + assert.equal((await cache.fetchEventCached("eventual"))?.id, "eventual"); + assert.equal(fetches, 2); + }); +}); + +describe("resolveTurnThreadsRetriable", () => { + it("does not record a resolution when a transient lookup rejects", async () => { + const resolved = await resolveTurnThreadsRetriable( + [ + { + id: "turn-1", + startT: 1, + source: "channel", + triggeringEventIds: ["event-1"], + }, + ], + async () => { + throw new Error("relay temporarily unavailable"); + }, + ); + + assert.equal(resolved.has("turn-1"), false); + }); +}); diff --git a/desktop/src/features/agents/activity/useThreadScope.ts b/desktop/src/features/agents/activity/useThreadScope.ts index dc3bc09611..7e09d76f48 100644 --- a/desktop/src/features/agents/activity/useThreadScope.ts +++ b/desktop/src/features/agents/activity/useThreadScope.ts @@ -4,36 +4,77 @@ // // The event cache is module-level (not per-mount) because thread roots are // immutable once fetched — a channel revisit or a second surface mounting the -// map should never refetch the same roots. Failed lookups cache as null so a -// deleted trigger message doesn't refetch on every recompute. +// map should never refetch the same roots. Successful lookups and definitive +// not-found errors are cached; transient failures evict their entry so a later +// mount can retry. import * as React from "react"; import { getEventById } from "@/shared/api/tauri"; import type { RelayEvent } from "@/shared/api/types"; +import { isDefinitiveEventNotFound } from "@/shared/lib/eventLookupError"; import type { ObserverEvent } from "../ui/agentSessionTypes"; import { buildThreadGroups, - resolveTurnThreads, + resolveTurnThread, type ThreadGroups, type TurnThreadResolution, } from "./activityThreads"; import { type ActivityTurn, deriveActivityTurns } from "./activityTurns"; -const eventCache = new Map>(); +export type EventByIdFetcher = (eventId: string) => Promise; + +export function createThreadEventCache(fetchEventById: EventByIdFetcher): { + fetchEventCached: (eventId: string) => Promise; + clear: () => void; +} { + const cache = new Map>(); + return { + fetchEventCached(eventId) { + let promise = cache.get(eventId); + if (!promise) { + promise = fetchEventById(eventId).catch((error) => { + if (isDefinitiveEventNotFound(error)) { + return null; + } + cache.delete(eventId); + throw error; + }); + cache.set(eventId, promise); + } + return promise; + }, + clear() { + cache.clear(); + }, + }; +} + +const moduleEventCache = createThreadEventCache(getEventById); function fetchEventCached(eventId: string): Promise { - let promise = eventCache.get(eventId); - if (!promise) { - promise = getEventById(eventId).catch(() => null); - eventCache.set(eventId, promise); - } - return promise; + return moduleEventCache.fetchEventCached(eventId); +} + +export async function resolveTurnThreadsRetriable( + turns: readonly ActivityTurn[], + fetchEvent: (eventId: string) => Promise, +): Promise> { + const entries = await Promise.all( + turns.map(async (turn) => { + try { + return [turn.id, await resolveTurnThread(turn, fetchEvent)] as const; + } catch { + return null; + } + }), + ); + return new Map(entries.filter((entry) => entry !== null)); } /** Test-only: reset the module cache between specs. */ export function _testResetThreadEventCache() { - eventCache.clear(); + moduleEventCache.clear(); } export interface ThreadScopeState { @@ -100,16 +141,19 @@ export function useThreadScope( const generation = ++generationRef.current; let cancelled = false; - void resolveTurnThreads(unresolved, fetchEventCached).then((resolved) => { - if (cancelled || generation !== generationRef.current) return; - setResolutions((current) => { - const next = new Map(current); - for (const [turnId, resolution] of resolved) { - next.set(turnId, resolution); - } - return next; - }); - }); + void resolveTurnThreadsRetriable(unresolved, fetchEventCached).then( + (resolved) => { + if (cancelled || generation !== generationRef.current) return; + if (resolved.size === 0) return; + setResolutions((current) => { + const next = new Map(current); + for (const [turnId, resolution] of resolved) { + next.set(turnId, resolution); + } + return next; + }); + }, + ); return () => { cancelled = true; diff --git a/desktop/tests/e2e/agent-activity-panel-screenshots.spec.ts b/desktop/tests/e2e/agent-activity-panel-screenshots.spec.ts index a841edce64..2d61899e46 100644 --- a/desktop/tests/e2e/agent-activity-panel-screenshots.spec.ts +++ b/desktop/tests/e2e/agent-activity-panel-screenshots.spec.ts @@ -11,6 +11,8 @@ const AGENT_PUBKEY = TEST_IDENTITIES.tyler.pubkey; const CHANNEL_ID = "94a444a4-c0a3-5966-ab05-530c6ddc2301"; // #agents const T0 = Date.parse("2025-06-15T12:00:00Z"); +const IDLE_THREAD_AGENT_PUBKEY = `${"c".repeat(63)}D`; + const MANAGED_AGENTS = [ { pubkey: AGENT_PUBKEY, @@ -20,6 +22,16 @@ const MANAGED_AGENTS = [ }, ]; +const MULTI_AGENT_MANAGED_AGENTS = [ + ...MANAGED_AGENTS, + { + pubkey: IDLE_THREAD_AGENT_PUBKEY, + name: "Idle Thread Agent", + status: "running" as const, + channelNames: ["agents"], + }, +]; + type SeededObserverEvent = { seq: number; timestamp: string; @@ -247,6 +259,7 @@ async function openObserverFeedPanel(page: import("@playwright/test").Page) { async function seedObserverEvents( page: import("@playwright/test").Page, events: SeededObserverEvent[], + pubkey = AGENT_PUBKEY, ) { await page.evaluate( ({ pubkey, evts }) => { @@ -255,7 +268,7 @@ async function seedObserverEvents( events: evts, }); }, - { pubkey: AGENT_PUBKEY, evts: events }, + { pubkey, evts: events }, ); // Let React re-render and the rAF loop paint a frame. await page.waitForTimeout(400); @@ -467,6 +480,84 @@ test.describe("agent activity panel screenshots", () => { expect(readmeBox.height).toBeLessThan(evictionBox.height); }); + test("05 — thread popover only shows agents active in that thread", async ({ + page, + }) => { + await installMockBridge(page, { + managedAgents: MULTI_AGENT_MANAGED_AGENTS, + }); + await page.goto("/", { waitUntil: "domcontentloaded" }); + await waitForSeedHook(page); + + await page.getByTestId("channel-agents").click(); + await expect(page.getByTestId("chat-title")).toHaveText("agents"); + + await seedThreadedChannel(page); + await seedObserverEvents(page, activityFrames()); + await seedObserverEvents( + page, + [ + frame(1, 141_000, "turn_started", "idle-thread-turn", { + source: "channel", + triggeringEventIds: ["b".repeat(64)], + }), + frame(2, 142_000, "acp_read", "idle-thread-turn", { + jsonrpc: "2.0", + method: "session/update", + params: { + sessionId: "session-002", + update: { + sessionUpdate: "tool_call", + toolCallId: "idle-call-1", + status: "pending", + title: "read_file", + kind: "read", + locations: [{ path: "/Users/idle/repo/docs/idle.md" }], + }, + }, + }), + frame(3, 143_000, "turn_completed", "idle-thread-turn", {}), + ], + IDLE_THREAD_AGENT_PUBKEY, + ); + + const pills = page.getByTestId("thread-activity-pill"); + await expect(pills).toHaveCount(2, { timeout: 5_000 }); + + // README thread has both agents; selecting one chip must not trap the + // popover, and the older eviction thread must not show the unrelated agent. + await pills.nth(1).click(); + let popover = page.getByTestId("thread-activity-popover"); + await expect(popover).toBeVisible({ timeout: 5_000 }); + await expect( + popover.getByRole("button", { name: "Observer Agent" }), + ).toBeVisible(); + await expect( + popover.getByRole("button", { name: "Idle Thread Agent" }), + ).toBeVisible(); + + await popover.getByRole("button", { name: "Idle Thread Agent" }).click(); + await expect( + popover.getByRole("button", { name: "All agents" }), + ).toBeVisible(); + await expect( + popover.locator('section[aria-label="Agent file activity"]'), + ).toBeVisible(); + + await page.keyboard.press("Escape"); + await expect(popover).toHaveCount(0); + + await pills.first().click(); + popover = page.getByTestId("thread-activity-popover"); + await expect(popover).toBeVisible({ timeout: 5_000 }); + await expect( + popover.getByRole("button", { name: "Observer Agent" }), + ).toBeVisible(); + await expect( + popover.getByRole("button", { name: "Idle Thread Agent" }), + ).toHaveCount(0); + }); + test("02 — turn-scoped replay", async ({ page }) => { await installMockBridge(page, { managedAgents: MANAGED_AGENTS }); const feedPanel = await openObserverFeedPanel(page);