diff --git a/desktop/src/features/agents/activeAgentTurnsStore.ts b/desktop/src/features/agents/activeAgentTurnsStore.ts index ebafb3f197..15efb73523 100644 --- a/desktop/src/features/agents/activeAgentTurnsStore.ts +++ b/desktop/src/features/agents/activeAgentTurnsStore.ts @@ -62,6 +62,8 @@ type ActiveTurn = { export type ActiveTurnSummary = { channelId: string; anchorAt: number; + /** Live turn ids in this channel, used to scope current observer activity. */ + turnIds: string[]; }; /** One channel with active agent work, aggregated across agents. */ @@ -505,21 +507,30 @@ export function getActiveTurnsForAgent( const offset = clockOffsetByAgent.get(key) ?? 0; - // Collapse multiple turns in one channel to the earliest start — the badge - // should count from when the channel's oldest live turn began. Anchors are - // derived here (startedAt + offset) so the latest skew estimate applies. - const earliestByChannel = new Map(); + // Collapse multiple turns in one channel to the earliest start while + // retaining every live turn id. The badge counts from the oldest live turn; + // current observer headlines need the ids to reject prior-turn transcript. + const byChannel = new Map(); for (const turn of agentTurns.values()) { - const prior = earliestByChannel.get(turn.channelId); - if (prior === undefined || turn.startedAt < prior) { - earliestByChannel.set(turn.channelId, turn.startedAt); + const summary = byChannel.get(turn.channelId); + if (!summary) { + byChannel.set(turn.channelId, { + startedAt: turn.startedAt, + turnIds: [turn.turnId], + }); + continue; + } + summary.turnIds.push(turn.turnId); + if (turn.startedAt < summary.startedAt) { + summary.startedAt = turn.startedAt; } } - const result = [...earliestByChannel.entries()] - .map(([channelId, startedAt]) => ({ + const result = [...byChannel.entries()] + .map(([channelId, { startedAt, turnIds }]) => ({ channelId, anchorAt: startedAt + offset, + turnIds: turnIds.sort(), })) .sort((a, b) => a.channelId.localeCompare(b.channelId)); cachedTurnSummaries.set(key, result); diff --git a/desktop/src/features/agents/agentWorkingSignal.ts b/desktop/src/features/agents/agentWorkingSignal.ts index 6a4e4378c3..16c240dfea 100644 --- a/desktop/src/features/agents/agentWorkingSignal.ts +++ b/desktop/src/features/agents/agentWorkingSignal.ts @@ -35,6 +35,8 @@ export type AgentWorkingChannel = { /** Desktop-clock anchor for elapsed displays (turn start / first typing). */ anchorAt: number; source: Exclude; + /** Live observer turn ids; empty for typing-backed fallback channels. */ + turnIds: string[]; }; export type AgentWorkingState = { @@ -162,6 +164,7 @@ function computeAgentWorkingState( channelId: turn.channelId, anchorAt: turn.anchorAt, source: "observer" as const, + turnIds: turn.turnIds, })); const observerChannelIds = new Set(turns.map((turn) => turn.channelId)); @@ -175,6 +178,7 @@ function computeAgentWorkingState( channelId: typingChannelId, anchorAt: since, source: "typing", + turnIds: [], }); } } diff --git a/desktop/src/features/channels/ui/BotActivityBar.tsx b/desktop/src/features/channels/ui/BotActivityBar.tsx index 5afb6acad3..16b404b5b3 100644 --- a/desktop/src/features/channels/ui/BotActivityBar.tsx +++ b/desktop/src/features/channels/ui/BotActivityBar.tsx @@ -264,14 +264,23 @@ function BotActivityAgentPill({ const shouldReduceMotion = useReducedMotion(); const avatarMorphLayoutId = useComposerStripAvatarLayoutId(agent.pubkey); const transcript = useAgentTranscript(true, agent.pubkey); - const headline = React.useMemo( - () => deriveActivityPillLabel({ channelId, transcript }), - [channelId, transcript], - ); const workingState = React.useSyncExternalStore( subscribeAgentWorkingSignal, () => getAgentWorkingState(agent.pubkey, channelId), ); + const activeTurnIds = React.useMemo(() => { + if (workingState.source !== "observer") return undefined; + const scoped = workingState.channels.find( + (workingChannel) => + workingChannel.source === "observer" && + workingChannel.channelId === channelId, + ); + return new Set(scoped?.turnIds ?? []); + }, [channelId, workingState]); + const headline = React.useMemo( + () => deriveActivityPillLabel({ activeTurnIds, channelId, transcript }), + [activeTurnIds, channelId, transcript], + ); // Raw typing remains available even when getAgentWorkingState folds it under // observer precedence. It supplies the fallback before observer telemetry // arrives and after the observer turn completes; it must not hide live diff --git a/desktop/src/features/channels/ui/composerLiveActivity.test.mjs b/desktop/src/features/channels/ui/composerLiveActivity.test.mjs index 7b3dc55589..5b57dc5c67 100644 --- a/desktop/src/features/channels/ui/composerLiveActivity.test.mjs +++ b/desktop/src/features/channels/ui/composerLiveActivity.test.mjs @@ -16,7 +16,12 @@ const NOW = Date.parse("2026-07-23T00:01:00.000Z"); const NOW_ISO = new Date(NOW).toISOString(); /** Thought item: spine, headlined by its title. */ -const thought = (title, timestamp, channelId = CHANNEL) => ({ +const thought = ( + title, + timestamp, + channelId = CHANNEL, + turnId = undefined, +) => ({ id: `thought-${title}-${timestamp}`, type: "thought", renderClass: "thought", @@ -24,6 +29,7 @@ const thought = (title, timestamp, channelId = CHANNEL) => ({ text: "", timestamp, channelId, + turnId, }); /** Metadata item: meaningful but NOT spine — recedes when real work exists. */ @@ -198,6 +204,35 @@ test("deriveActivityPillLabel keeps a stable id while a message streams", () => assert.equal(extended.label, "Pass 1: reading the composer wiring"); }); +test("deriveActivityPillLabel scopes observer headlines to every live turn", () => { + const turnTwo = thought( + "Current turn work", + secondsBeforeNow(1), + CHANNEL, + "turn-2", + ); + const headline = deriveActivityPillLabel({ + activeTurnIds: new Set(["turn-2", "turn-3"]), + channelId: CHANNEL, + transcript: [ + thought("Previous turn work", secondsBeforeNow(2), CHANNEL, "turn-1"), + turnTwo, + ], + }); + assert.deepEqual(headline, { id: turnTwo.id, label: "Current turn work" }); + + assert.equal( + deriveActivityPillLabel({ + activeTurnIds: new Set(["turn-3"]), + channelId: CHANNEL, + transcript: [ + thought("Previous turn work", secondsBeforeNow(2), CHANNEL, "turn-1"), + ], + }), + null, + ); +}); + test("deriveActivityPillPresentation keeps observer activity authoritative over typing", () => { const headline = { id: "action-1", label: "Inspect composer state" }; const presentation = deriveActivityPillPresentation({ diff --git a/desktop/src/features/channels/ui/composerLiveActivity.ts b/desktop/src/features/channels/ui/composerLiveActivity.ts index 910abef420..cc74aae36c 100644 --- a/desktop/src/features/channels/ui/composerLiveActivity.ts +++ b/desktop/src/features/channels/ui/composerLiveActivity.ts @@ -89,15 +89,22 @@ export function deriveActivityPillPresentation({ * pill then falls back to its generic " is working…" label. */ export function deriveActivityPillLabel({ + activeTurnIds, channelId, transcript, }: { + activeTurnIds?: ReadonlySet; channelId: string | null; transcript: readonly TranscriptItem[]; }): ActivityPillHeadline | null { - const scoped = channelId - ? transcript.filter((item) => item.channelId === channelId) - : transcript; + const scoped = transcript.filter( + (item) => + (!channelId || item.channelId === channelId) && + (!activeTurnIds || + (item.turnId !== null && + item.turnId !== undefined && + activeTurnIds.has(item.turnId))), + ); const passFilter = scoped.some(isSpineItem) ? isSpineItem : isMeaningfulItem; for (let index = scoped.length - 1; index >= 0; index -= 1) { diff --git a/desktop/src/features/messages/useChannelTyping.test.mjs b/desktop/src/features/messages/useChannelTyping.test.mjs new file mode 100644 index 0000000000..cf357ea5f0 --- /dev/null +++ b/desktop/src/features/messages/useChannelTyping.test.mjs @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { recordTypingCompletion } from "./useChannelTyping.ts"; + +const TYPING_KEY = "agent:thread"; +const NOW = 2_000_000_000_000; +const NOW_SECONDS = NOW / 1_000; + +function makeState() { + return { + latestMessageCreatedAtByPubkey: {}, + suppressUntilByPubkey: {}, + }; +} + +function record(state, createdAt) { + return recordTypingCompletion({ + createdAt, + latestMessageCreatedAtByPubkey: state.latestMessageCreatedAtByPubkey, + now: NOW, + suppressUntilByPubkey: state.suppressUntilByPubkey, + typingKey: TYPING_KEY, + }); +} + +test("duplicate full-array replay does not reprocess completion events", () => { + const state = makeState(); + + assert.equal(record(state, NOW_SECONDS), true); + assert.equal(record(state, NOW_SECONDS), false); + assert.deepEqual(state.latestMessageCreatedAtByPubkey, { + [TYPING_KEY]: NOW_SECONDS, + }); + assert.deepEqual(state.suppressUntilByPubkey, { + [TYPING_KEY]: NOW + 2_000, + }); +}); + +test("newer-then-older completion arrival keeps the newer watermark", () => { + const state = makeState(); + + assert.equal(record(state, NOW_SECONDS), true); + assert.equal(record(state, NOW_SECONDS - 1), false); + assert.equal(state.latestMessageCreatedAtByPubkey[TYPING_KEY], NOW_SECONDS); + assert.equal(state.suppressUntilByPubkey[TYPING_KEY], NOW + 2_000); +}); + +test("older-then-newer completion arrival advances the watermark", () => { + const state = makeState(); + + assert.equal(record(state, NOW_SECONDS - 1), true); + assert.equal(record(state, NOW_SECONDS), true); + assert.equal(state.latestMessageCreatedAtByPubkey[TYPING_KEY], NOW_SECONDS); + assert.equal(state.suppressUntilByPubkey[TYPING_KEY], NOW + 2_000); +}); + +test("historical thread load creates neither a watermark nor fresh suppression", () => { + const state = makeState(); + + assert.equal(record(state, NOW_SECONDS - 60), false); + assert.deepEqual(state.latestMessageCreatedAtByPubkey, {}); + assert.deepEqual(state.suppressUntilByPubkey, {}); +}); diff --git a/desktop/src/features/messages/useChannelTyping.ts b/desktop/src/features/messages/useChannelTyping.ts index 1751cf8386..52d8397dd9 100644 --- a/desktop/src/features/messages/useChannelTyping.ts +++ b/desktop/src/features/messages/useChannelTyping.ts @@ -25,11 +25,63 @@ type TypingEntry = { threadHeadId: string | null; }; type TypingState = Record; +type TypingCompletionWatermarks = Record; +type TypingSuppressionDeadlines = Record; const TYPING_INDICATOR_TTL_MS = 8_000; const TYPING_PRUNE_INTERVAL_MS = 1_000; const TYPING_POST_MESSAGE_SUPPRESS_MS = 2_000; +/** + * Advance one author + thread completion watermark when it can still affect + * an acceptable typing indicator. Returns whether matching typing state should + * be cleared. Exported so replay and out-of-order behavior stays unit-tested. + */ +export function recordTypingCompletion({ + createdAt, + latestMessageCreatedAtByPubkey, + now = Date.now(), + suppressUntilByPubkey, + typingKey, +}: { + createdAt: number; + latestMessageCreatedAtByPubkey: TypingCompletionWatermarks; + now?: number; + suppressUntilByPubkey: TypingSuppressionDeadlines; + typingKey: string; +}) { + for (const [key, watermark] of Object.entries( + latestMessageCreatedAtByPubkey, + )) { + if (watermark * 1_000 + TYPING_INDICATOR_TTL_MS <= now) { + delete latestMessageCreatedAtByPubkey[key]; + } + } + for (const [key, suppressUntil] of Object.entries(suppressUntilByPubkey)) { + if (suppressUntil <= now) { + delete suppressUntilByPubkey[key]; + } + } + + if (createdAt * 1_000 + TYPING_INDICATOR_TTL_MS <= now) { + return false; + } + + const latestMessageCreatedAt = latestMessageCreatedAtByPubkey[typingKey] ?? 0; + if (createdAt <= latestMessageCreatedAt) { + return false; + } + latestMessageCreatedAtByPubkey[typingKey] = createdAt; + + const suppressUntil = createdAt * 1_000 + TYPING_POST_MESSAGE_SUPPRESS_MS; + if (suppressUntil > now) { + suppressUntilByPubkey[typingKey] = suppressUntil; + } else { + delete suppressUntilByPubkey[typingKey]; + } + return true; +} + function pruneTypingState(state: TypingState, now = Date.now()) { let changed = false; const next: TypingState = {}; @@ -78,7 +130,6 @@ export function useChannelTyping( const normalizedCurrentPubkey = currentPubkey?.toLowerCase(); const typingSuppressUntilByPubkeyRef = useRef>({}); const latestMessageCreatedAtByPubkeyRef = useRef>({}); - const processedCompletionEventIdsRef = useRef>(new Set()); const registerTyping = useEffectEvent((event: RelayEvent) => { if (!channelId || event.kind !== KIND_TYPING_INDICATOR) { @@ -137,7 +188,6 @@ export function useChannelTyping( setTypingByPubkey({}); typingSuppressUntilByPubkeyRef.current = {}; latestMessageCreatedAtByPubkeyRef.current = {}; - processedCompletionEventIdsRef.current = new Set(); }, [channelId]); const clearTypingForMessage = useEffectEvent((event: RelayEvent) => { @@ -149,11 +199,6 @@ export function useChannelTyping( return; } - if (processedCompletionEventIdsRef.current.has(event.id)) { - return; - } - processedCompletionEventIdsRef.current.add(event.id); - const authorPubkey = resolveEventAuthorPubkey({ event, preferActorTag: true, @@ -162,12 +207,16 @@ export function useChannelTyping( }).toLowerCase(); const threadHeadId = getTypingScopeId(event); const typingKey = getTypingStateKey(authorPubkey, threadHeadId); - latestMessageCreatedAtByPubkeyRef.current[typingKey] = Math.max( - latestMessageCreatedAtByPubkeyRef.current[typingKey] ?? 0, - event.created_at, - ); - typingSuppressUntilByPubkeyRef.current[typingKey] = - Date.now() + TYPING_POST_MESSAGE_SUPPRESS_MS; + const shouldClearTyping = recordTypingCompletion({ + createdAt: event.created_at, + latestMessageCreatedAtByPubkey: latestMessageCreatedAtByPubkeyRef.current, + suppressUntilByPubkey: typingSuppressUntilByPubkeyRef.current, + typingKey, + }); + if (!shouldClearTyping) { + return; + } + setTypingByPubkey((current) => { const next = pruneTypingState(current); if (!(typingKey in next)) { diff --git a/desktop/tests/e2e/channels.spec.ts b/desktop/tests/e2e/channels.spec.ts index 55be7587ab..9da1ebfcdc 100644 --- a/desktop/tests/e2e/channels.spec.ts +++ b/desktop/tests/e2e/channels.spec.ts @@ -2163,7 +2163,8 @@ test("shows and clears activity indicators for active channel agents", async ({ 0, ); - // A fresh turn re-mounts the pill — the cleared state is not sticky. + // A fresh turn re-mounts the pill without presenting the prior turn's last + // action as current work. await page.evaluate( ({ channelId, pubkey }) => { window.__BUZZ_E2E_SEED_ACTIVE_TURNS__?.({ @@ -2174,7 +2175,9 @@ test("shows and clears activity indicators for active channel agents", async ({ }, { channelId: AGENTS_CHANNEL_ID, pubkey: TEST_IDENTITIES.alice.pubkey }, ); - await expect(page.getByTestId("bot-activity-composer-trigger")).toBeVisible(); + await expect(page.getByTestId("bot-activity-composer-trigger")).toContainText( + "alice is working", + ); }); test("thread agent typing promotes only when activity exists", async ({