feat(composer): merged live activity feed in agents-working popover

Replace the plain agent list in the below-composer 'Agents working'
popover with an h-48 merged live activity preview. Per-agent observer
transcripts for the channel's working agents are interleaved into one
chronological stream (stable k-way merge on item timestamps), rendered
with the compact transcript presenters from the agent activity view,
and badged per consecutive same-agent run.

- composerLiveActivity.ts: channel-scoped merge + consecutive-run
  grouping helpers, capped at 80 entries for the preview window
- ComposerLiveActivityFeed.tsx: compactPreview-variant feed with
  auto-tail via useAnchoredScroll (memoized entry snapshot so streaming
  updates re-anchor without effect churn) and explicit agent-badge
  click-through buttons — no nested interactive wrappers
- useObserverEvents.ts: useAgentTranscripts hook for index-aligned
  multi-agent snapshots with referential caching to keep
  useSyncExternalStore stable
- BotActivityBar.tsx: popover widened to w-80, feed above a compact
  per-agent footer that keeps the existing click-through rows

Co-authored-by: Taylor Ho <taylorkmho@gmail.com>
Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
This commit is contained in:
npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w
2026-07-06 19:08:52 -07:00
committed by npub14vtk7pvazqrq9639qu7e560wnqtl0d53ca4gjuvq6jzf3k2el23qqlwa7f
parent 1f5ba5bb27
commit 4435090f02
5 changed files with 450 additions and 6 deletions

View File

@@ -52,6 +52,37 @@ export function useAgentTranscript(
return React.useSyncExternalStore(subscribeToStore, getSnapshot);
}
/**
* Live transcripts for several agents at once, index-aligned with
* `agentPubkeys`. The snapshot is cached so `useSyncExternalStore` only sees
* a new array when at least one underlying per-agent transcript changed —
* required to avoid render loops.
*/
export function useAgentTranscripts(
enabled: boolean,
agentPubkeys: readonly string[],
): TranscriptItem[][] {
const cacheRef = React.useRef<TranscriptItem[][] | null>(null);
const getSnapshot = React.useCallback(() => {
const next = agentPubkeys.map((pubkey) =>
getAgentTranscript(pubkey, enabled),
);
const cached = cacheRef.current;
if (
cached &&
cached.length === next.length &&
cached.every((transcript, index) => transcript === next[index])
) {
return cached;
}
cacheRef.current = next;
return next;
}, [agentPubkeys, enabled]);
return React.useSyncExternalStore(subscribeToStore, getSnapshot);
}
const ARCHIVED_EVENTS_PAGE_SIZE = 50;
/**

View File

@@ -13,6 +13,7 @@ import { cn } from "@/shared/lib/cn";
import { Popover, PopoverContent, PopoverTrigger } from "@/shared/ui/popover";
import { Shimmer } from "@/shared/ui/Shimmer";
import { UserAvatar } from "@/shared/ui/UserAvatar";
import { ComposerLiveActivityFeed } from "./ComposerLiveActivityFeed";
export type BotActivityAgent = Pick<ManagedAgent, "pubkey" | "name">;
@@ -217,24 +218,35 @@ export function BotActivityComposerAction({
</PopoverTrigger>
<PopoverContent
align={isInline ? "start" : "end"}
className="w-64 p-1"
className="w-80 p-0"
onMouseEnter={keepOpen}
onMouseLeave={closeWithDelay}
onOpenAutoFocus={(event) => event.preventDefault()}
side="top"
sideOffset={8}
>
<div className="px-2 py-1 text-xs font-medium text-muted-foreground">
<div className="px-3 pb-1 pt-2 text-xs font-medium text-muted-foreground">
Agents working
</div>
<div className="mt-1 flex flex-col gap-1">
<ComposerLiveActivityFeed
agents={workingAgents}
channelId={channelId}
className="h-48"
onOpenAgentSession={(pubkey) => {
clearHoverTimer();
setOpen(false);
onOpenAgentSession(pubkey, channelId);
}}
profiles={profiles}
/>
<div className="flex flex-col gap-0.5 border-t border-border/60 p-1">
{workingAgents.map((agent) => {
const isSelected = selectedPubkey === agent.pubkey.toLowerCase();
return (
<button
className={cn(
"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm transition-colors",
"flex w-full items-center gap-2 rounded-lg px-2 py-1 text-left text-xs transition-colors",
isSelected
? "bg-primary/10 text-primary"
: "text-foreground hover:bg-accent hover:text-accent-foreground",
@@ -252,10 +264,10 @@ export function BotActivityComposerAction({
avatarUrl={agentAvatarUrl(agent)}
className="shrink-0"
displayName={agent.name}
size="sm"
size="xs"
/>
<span className="min-w-0 flex-1 truncate">{agent.name}</span>
<Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground/70" />
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground/70" />
</button>
);
})}

View File

@@ -0,0 +1,144 @@
import * as React from "react";
import { AgentSessionTranscriptVariantProvider } from "@/features/agents/ui/agentSessionTranscriptContext";
import { TranscriptActivityItem } from "@/features/agents/ui/activityRenderClasses/TranscriptActivityItem";
import { useAgentTranscripts } from "@/features/agents/ui/useObserverEvents";
import { useAnchoredScroll } from "@/features/messages/ui/useAnchoredScroll";
import type { UserProfileLookup } from "@/features/profile/lib/identity";
import { cn } from "@/shared/lib/cn";
import { FuzzyLogo } from "@/shared/ui/buzz-logo/FuzzyLogo";
import { UserAvatar } from "@/shared/ui/UserAvatar";
import {
groupLiveActivity,
mergeLiveActivity,
type LiveActivityAgent,
} from "./composerLiveActivity";
/**
* Merged multi-agent live activity preview for the composer popover.
*
* Interleaves the working agents' transcripts (scoped to the current channel)
* into one chronological stream, badges each same-agent run with the agent's
* identity, and auto-tails streaming updates. Rendering reuses the compact
* transcript presenters from the full activity view.
*/
export function ComposerLiveActivityFeed({
agents,
channelId,
className,
onOpenAgentSession,
profiles,
}: {
agents: LiveActivityAgent[];
channelId: string | null;
className?: string;
onOpenAgentSession: (pubkey: string) => void;
profiles?: UserProfileLookup;
}) {
const agentPubkeys = React.useMemo(
() => agents.map((agent) => agent.pubkey),
[agents],
);
const transcripts = useAgentTranscripts(agents.length > 0, agentPubkeys);
const entries = React.useMemo(
() => mergeLiveActivity(agents, transcripts, channelId),
[agents, channelId, transcripts],
);
const groups = React.useMemo(() => groupLiveActivity(entries), [entries]);
const scrollContainerRef = React.useRef<HTMLDivElement>(null);
const contentRef = React.useRef<HTMLDivElement>(null);
// Stable identity per entries snapshot — useAnchoredScroll keys effects on
// `messages`, so a fresh array every render would re-run them needlessly.
const anchoredMessages = React.useMemo(
() => entries.map((entry) => ({ id: entry.key })),
[entries],
);
const anchoredScroll = useAnchoredScroll({
channelId: `composer-live-activity:${channelId ?? "all"}`,
contentRef,
isLoading: false,
messages: anchoredMessages,
scrollContainerRef,
});
const agentAvatarUrl = (agent: LiveActivityAgent) =>
profiles?.[agent.pubkey.toLowerCase()]?.avatarUrl ?? null;
if (entries.length === 0) {
return (
<div
className={cn(
"flex flex-col items-center justify-center px-6 text-center",
className,
)}
data-testid="composer-live-activity-empty"
>
<FuzzyLogo
ariaLabel="Waiting for agent activity"
className="mx-auto text-muted-foreground"
fuzz={false}
loop
/>
</div>
);
}
return (
<div
className={cn("overflow-y-auto overscroll-contain", className)}
data-testid="composer-live-activity-feed"
onScroll={anchoredScroll.onScroll}
ref={scrollContainerRef}
>
<div
aria-label="Live agent activity"
aria-live="polite"
className="flex w-full flex-col gap-2 px-3 py-2"
ref={contentRef}
role="log"
>
<AgentSessionTranscriptVariantProvider value="compactPreview">
{groups.map((group) => (
<div
className="flex flex-col gap-1"
data-message-id={group.key}
data-testid={`composer-live-activity-group-${group.agent.pubkey}`}
key={group.key}
>
<button
aria-label={`Open ${group.agent.name} activity`}
className="flex w-fit max-w-full items-center gap-1.5 rounded-md px-1 py-0.5 text-left transition-colors hover:bg-accent"
onClick={() => onOpenAgentSession(group.agent.pubkey)}
type="button"
>
<UserAvatar
avatarUrl={agentAvatarUrl(group.agent)}
className="!h-[18px] !w-[18px] shrink-0 text-3xs"
displayName={group.agent.name}
size="xs"
/>
<span className="truncate text-xs font-semibold text-muted-foreground">
{group.agent.name}
</span>
</button>
<div className="flex min-w-0 flex-col gap-1 pl-2">
{group.entries.map((entry) => (
<div data-message-id={entry.key} key={entry.key}>
<TranscriptActivityItem
agentAvatarUrl={agentAvatarUrl(group.agent)}
agentName={group.agent.name}
agentPubkey={group.agent.pubkey}
item={entry.item}
profiles={profiles}
/>
</div>
))}
</div>
</div>
))}
</AgentSessionTranscriptVariantProvider>
</div>
</div>
);
}

View File

@@ -0,0 +1,147 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
groupLiveActivity,
mergeLiveActivity,
} from "./composerLiveActivity.ts";
const CHANNEL = "channel-1";
const OTHER_CHANNEL = "channel-2";
const alice = { pubkey: "alice-pubkey", name: "Alice" };
const bob = { pubkey: "bob-pubkey", name: "Bob" };
function makeItem(overrides = {}) {
return {
id: "item:1",
type: "tool",
title: "Read file",
toolName: "read_file",
buzzToolName: "read_file",
status: "completed",
args: {},
result: "",
isError: false,
renderClass: "tool-run",
channelId: CHANNEL,
timestamp: "2026-07-07T00:00:00.000Z",
startedAt: "2026-07-07T00:00:00.000Z",
completedAt: null,
...overrides,
};
}
test("mergeLiveActivity interleaves per-agent transcripts chronologically", () => {
const merged = mergeLiveActivity(
[alice, bob],
[
[
makeItem({ id: "a1", timestamp: "2026-07-07T00:00:01.000Z" }),
makeItem({ id: "a2", timestamp: "2026-07-07T00:00:04.000Z" }),
],
[
makeItem({ id: "b1", timestamp: "2026-07-07T00:00:02.000Z" }),
makeItem({ id: "b2", timestamp: "2026-07-07T00:00:03.000Z" }),
],
],
CHANNEL,
);
assert.deepEqual(
merged.map((entry) => entry.key),
["alice-pubkey:a1", "bob-pubkey:b1", "bob-pubkey:b2", "alice-pubkey:a2"],
);
});
test("mergeLiveActivity scopes to the requested channel", () => {
const merged = mergeLiveActivity(
[alice],
[
[
makeItem({ id: "in-scope" }),
makeItem({ id: "out-of-scope", channelId: OTHER_CHANNEL }),
],
],
CHANNEL,
);
assert.deepEqual(
merged.map((entry) => entry.item.id),
["in-scope"],
);
});
test("mergeLiveActivity drops suppressed tool items", () => {
const merged = mergeLiveActivity(
[alice],
[
[
makeItem({ id: "visible" }),
makeItem({ id: "hidden", renderClass: "suppressed" }),
],
],
CHANNEL,
);
assert.deepEqual(
merged.map((entry) => entry.item.id),
["visible"],
);
});
test("mergeLiveActivity keeps ties in agent order (stable merge)", () => {
const timestamp = "2026-07-07T00:00:05.000Z";
const merged = mergeLiveActivity(
[alice, bob],
[[makeItem({ id: "a1", timestamp })], [makeItem({ id: "b1", timestamp })]],
CHANNEL,
);
assert.deepEqual(
merged.map((entry) => entry.agent.pubkey),
["alice-pubkey", "bob-pubkey"],
);
});
test("mergeLiveActivity caps the merged stream at the preview limit", () => {
const items = Array.from({ length: 120 }, (_, index) =>
makeItem({
id: `a${index}`,
timestamp: new Date(Date.UTC(2026, 6, 7, 0, 0, index)).toISOString(),
}),
);
const merged = mergeLiveActivity([alice], [items], CHANNEL);
assert.equal(merged.length, 80);
assert.equal(merged[0].item.id, "a40");
assert.equal(merged.at(-1).item.id, "a119");
});
test("groupLiveActivity groups consecutive same-agent runs", () => {
const merged = mergeLiveActivity(
[alice, bob],
[
[
makeItem({ id: "a1", timestamp: "2026-07-07T00:00:01.000Z" }),
makeItem({ id: "a2", timestamp: "2026-07-07T00:00:02.000Z" }),
makeItem({ id: "a3", timestamp: "2026-07-07T00:00:09.000Z" }),
],
[makeItem({ id: "b1", timestamp: "2026-07-07T00:00:05.000Z" })],
],
CHANNEL,
);
const groups = groupLiveActivity(merged);
assert.deepEqual(
groups.map((group) => ({
agent: group.agent.pubkey,
ids: group.entries.map((entry) => entry.item.id),
})),
[
{ agent: "alice-pubkey", ids: ["a1", "a2"] },
{ agent: "bob-pubkey", ids: ["b1"] },
{ agent: "alice-pubkey", ids: ["a3"] },
],
);
});

View File

@@ -0,0 +1,110 @@
import type { TranscriptItem } from "@/features/agents/ui/agentSessionTypes";
import { scopeByChannel } from "@/features/agents/ui/agentSessionPanelLayout";
import { isMeaningfulItem } from "@/features/agents/ui/agentSessionTranscriptPresentation";
/** Identity shown on merged feed rows. */
export type LiveActivityAgent = {
pubkey: string;
name: string;
};
export type LiveActivityEntry = {
agent: LiveActivityAgent;
item: TranscriptItem;
/** Unique across agents — transcript item ids are only per-agent unique. */
key: string;
};
/** Consecutive run of entries from the same agent in the merged stream. */
export type LiveActivityGroup = {
agent: LiveActivityAgent;
entries: LiveActivityEntry[];
key: string;
};
/**
* Cap on merged entries kept for the preview window. The composer popover is
* a peek, not the archive — click-through opens the full activity view.
*/
const MERGED_ENTRY_LIMIT = 80;
function parseTimestamp(timestamp: string): number {
const parsed = Date.parse(timestamp);
return Number.isNaN(parsed) ? 0 : parsed;
}
/**
* Merge several per-agent transcripts into one interleaved, chronological
* stream scoped to a channel. Inputs are index-aligned: `transcripts[i]`
* belongs to `agents[i]`. Each per-agent transcript is already chronological,
* so this is a stable k-way merge on item timestamps (ties keep agent order).
*/
export function mergeLiveActivity(
agents: readonly LiveActivityAgent[],
transcripts: readonly TranscriptItem[][],
channelId: string | null,
): LiveActivityEntry[] {
const cursors = agents.map((agent, index) => ({
agent,
items: scopeByChannel(transcripts[index] ?? [], channelId).filter(
isMeaningfulItem,
),
position: 0,
}));
const merged: LiveActivityEntry[] = [];
for (;;) {
let best: (typeof cursors)[number] | null = null;
let bestTime = Number.POSITIVE_INFINITY;
for (const cursor of cursors) {
const item = cursor.items[cursor.position];
if (!item) {
continue;
}
const time = parseTimestamp(item.timestamp);
if (time < bestTime) {
best = cursor;
bestTime = time;
}
}
if (!best) {
break;
}
const item = best.items[best.position];
if (item) {
merged.push({
agent: best.agent,
item,
key: `${best.agent.pubkey}:${item.id}`,
});
}
best.position += 1;
}
return merged.length > MERGED_ENTRY_LIMIT
? merged.slice(merged.length - MERGED_ENTRY_LIMIT)
: merged;
}
/**
* Group consecutive same-agent entries so the feed can render one agent
* badge per run instead of per row.
*/
export function groupLiveActivity(
entries: readonly LiveActivityEntry[],
): LiveActivityGroup[] {
const groups: LiveActivityGroup[] = [];
for (const entry of entries) {
const current = groups[groups.length - 1];
if (current && current.agent.pubkey === entry.agent.pubkey) {
current.entries.push(entry);
continue;
}
groups.push({
agent: entry.agent,
entries: [entry],
key: entry.key,
});
}
return groups;
}