fix(composer): scope live activity to active turns

Keep observer headlines within currently live turn IDs and use a bounded per-scope completion watermark for replay-safe typing cleanup.

Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz>
Co-authored-by: Mongo <5398c5fd039b963ce132b3e078e7c4af097dd997517bb5e14c2682fe68c25197@buzz.block.builderlab.xyz>
Co-authored-by: Princess Donut <0366ccd5ee09c2779a9d6bd6683daa17c16a508a51f6a7e7314018dab8fdc49b@buzz.block.builderlab.xyz>
Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
This commit is contained in:
Taylor Ho
2026-08-23 14:52:26 -07:00
committed by Carl
parent a5be90af58
commit f37c431b8c
8 changed files with 214 additions and 32 deletions

View File

@@ -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<string, number>();
// 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<string, { startedAt: number; turnIds: string[] }>();
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);

View File

@@ -35,6 +35,8 @@ export type AgentWorkingChannel = {
/** Desktop-clock anchor for elapsed displays (turn start / first typing). */
anchorAt: number;
source: Exclude<AgentWorkingSource, "none">;
/** 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: [],
});
}
}

View File

@@ -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

View File

@@ -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({

View File

@@ -89,15 +89,22 @@ export function deriveActivityPillPresentation({
* pill then falls back to its generic "<name> is working…" label.
*/
export function deriveActivityPillLabel({
activeTurnIds,
channelId,
transcript,
}: {
activeTurnIds?: ReadonlySet<string>;
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) {

View File

@@ -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, {});
});

View File

@@ -25,11 +25,63 @@ type TypingEntry = {
threadHeadId: string | null;
};
type TypingState = Record<string, TypingEntry>;
type TypingCompletionWatermarks = Record<string, number>;
type TypingSuppressionDeadlines = Record<string, number>;
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<Record<string, number>>({});
const latestMessageCreatedAtByPubkeyRef = useRef<Record<string, number>>({});
const processedCompletionEventIdsRef = useRef<Set<string>>(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)) {

View File

@@ -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 ({