Skip to content

Commit 43f5022

Browse files
kalvinnchauam
andauthored
feat: show channel session usage in a dedicated tab (#723)
Signed-off-by: am <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz> Co-authored-by: am <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz>
1 parent 41dd3d0 commit 43f5022

25 files changed

Lines changed: 2072 additions & 7 deletions

‎crates/plugin-manager/src/lib.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,10 @@ pub fn bundled_manifests() -> Vec<Manifest> {
159159
.expect("emoji manifest"),
160160
serde_json::from_str(include_str!("../../../src/bundled/channels/manifest.json"))
161161
.expect("channels manifest"),
162+
serde_json::from_str(include_str!(
163+
"../../../src/bundled/channel-usage/manifest.json"
164+
))
165+
.expect("channel usage manifest"),
162166
serde_json::from_str(include_str!("../../../src/bundled/github/manifest.json"))
163167
.expect("github manifest"),
164168
serde_json::from_str(include_str!("../../../src/bundled/inbox/manifest.json"))
@@ -500,6 +504,7 @@ impl Manager {
500504
| "buzz.diffs"
501505
| "buzz.identity-naming"
502506
| "buzz.agent-activity"
507+
| "buzz.channel-usage"
503508
| "buzz.terminal"
504509
| "buzz.profiles"
505510
| "buzz.links"

‎docs/agents.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,3 +728,36 @@ status. Native cards keep their controls. Other known identities appear in a
728728
read-only section. Each card offers its own Import; the separate installation
729729
browser appears only for repair.
730730
No keys, config, memory, membership, or runtime state are changed by discovery.
731+
732+
### Channel session usage
733+
734+
The Usage tab reads saved kind-44200 metrics from the current account/community's
735+
host archive. Its strip and detail are **channel-associated session**
736+
usage, not thread attribution or context-window capacity. Each signed agent key
737+
and reported harness session remains separate; missing session IDs are individual
738+
unidentified records. The latest cumulative snapshot is selected by turn sequence;
739+
turn deltas are shown only when reliable. Unknown counters are not zero and cache
740+
counters are subsets of input. Cost is a publisher-supplied estimate, not a bill.
741+
742+
The Usage tab's agent dropdown shows each agent's latest total or session count;
743+
selecting an agent reveals an aggregate of the latest trustworthy cumulative
744+
snapshot from each of its sessions. Counters missing in any session remain unknown
745+
rather than silently understating the total. The outlined Session dropdown then
746+
selects one session for provenance and turn detail without filling the pane with
747+
session buttons. The aggregate may cover other threads and is limited to loaded
748+
archive history.
749+
750+
The channel's **Channel actions → View channel usage** item opens a dedicated
751+
**Usage** tab in the channel's side pane. It is available only while this
752+
account has positive access to the current channel and the default-on Channel Usage
753+
plugin is enabled under Settings → Plugins. Closing the tab unmounts its
754+
archive reader; disabling the plugin removes the tab and stops reads. It
755+
does not change metric capture or retention. Opening the Usage tab reads archive
756+
pages automatically until exhaustion or the 2,000-record limit; an early page
757+
without channel matches does not prove the archive has none. **Refresh** starts
758+
a new scan from the newest page; neither action fetches relay history. The client
759+
retains at most 2,000 decoded records while this tab lives and fences late reads
760+
on channel/access changes. Saved metrics remain
761+
subject to the independent 90-day/byte eviction policy above, so loaded history
762+
is never a completeness guarantee. Restored usage is display-only and cannot
763+
establish working, typing, or online status.

‎docs/plugin-architecture.md‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ features/relay/ shared channel data, queries, profiles and durable deliv
4747
features/messages/ reusable timeline, message, thread and composer UI
4848
features/channel-navigation/ persistent sidebar, scoped draft handoff, Channels routes
4949
bundled/channels/ conversation navigation, page layout and panel placement
50+
bundled/channel-usage/ optional archive-backed Usage panel and Channels menu launcher
5051
bundled/projects/ repository/project pages, issue/PR details and Git views
5152
features/projects/ entity route/data contracts and bounded Git read bridge
5253
bundled/agents/ local control UI and read-only current-Buzz library page
@@ -113,9 +114,9 @@ contracts with their own layout and local navigation.
113114

114115
### Bundled defaults
115116

116-
All 22 plugins remain bundled. **Channels is the only required plugin.** Bestie,
117+
All 24 plugins are bundled. **Channels is the only required plugin.** Bestie,
117118
Todos, and Templates & teams are off by default. Feedback, Diff viewer, Identity
118-
Naming, Agent Activity, Terminal, Profiles, Links, Mentions, Emoji, GitHub, Inbox,
119+
Naming, Agent Activity, Channel Usage, Terminal, Profiles, Links, Mentions, Emoji, GitHub, Inbox,
119120
Projects, Agents, Workflows, Sessions, Builderlab, Hosted communities, and Community admin are
120121
on by default, but optional. Both browser and native catalogs declare that policy.
121122

@@ -137,6 +138,21 @@ pull request, issue, and commit URLs and loads public object details on demand.
137138
Unsupported URLs retain ordinary link behavior. Private GitHub connections and
138139
agent execution remain future shared capabilities.
139140

141+
### Optional channel menu panels
142+
143+
A panel can register `channelMenu: { label, eligible(channel, session) }` for
144+
placement in Channels → Channel actions. Channels owns the menu, selected channel,
145+
tab geometry, focus, and close behavior; it opens the **exact active contribution**
146+
without resolving a target matcher. Eligibility is evaluated again at activation
147+
against the current connected session, selected non-cached channel and membership.
148+
Disabling or replacing a plugin retires its open tab; a channel change or loss of
149+
eligibility closes it and unmounts its archive reader. Re-enabling never reopens a
150+
stale tab. Eligibility and `channelContext` are presentation, **not authority**:
151+
the panel must independently verify access before reading any sensitive data and
152+
fence asynchronous reads on revocation. Channel Usage owns this panel and its
153+
archive projection; the session continues to own archive capture, access and
154+
retention. Plugin enablement controls visibility without changing capture settings.
155+
140156
### Optional channel templates and Settings cards
141157

142158
`ctx.settingsCards.register({ id, title, icon, component })` contributes a card under

‎src/app/AgentSettings.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { NavigationItem } from "../shared/design-system/ui/NavigationItem";
3030
import { IconButton } from "../shared/design-system/ui/IconButton";
3131
import { PreferenceRow } from "../shared/design-system/ui/PreferenceRow";
3232
import { SwitchPreferenceRow } from "../shared/design-system/ui/SwitchPreferenceRow";
33+
3334
import { ToastNotice } from "../shared/design-system/ui/Toast";
3435
import { Tooltip } from "../shared/design-system/ui/Tooltip";
3536
import type { ReactNode } from "react";

‎src/app/pages.integration.test.mjs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,30 @@ test("the app runtime exposes ready bundled pages and removes them on disable",
244244
),
245245
);
246246

247+
const usage = services.panels
248+
.snapshot()
249+
.find((panel) => panel.pluginId === "buzz.channel-usage");
250+
assert.equal(usage.channelMenu.label, "View channel usage");
251+
assert.equal(usage.matches("channel"), false);
252+
await services.plugins.change("disable", "buzz.channel-usage");
253+
assert.equal(services.panels.snapshot().includes(usage), false);
254+
assert.ok(
255+
services.pages
256+
.snapshot()
257+
.some((page) => page.pluginId === "buzz.channels"),
258+
);
259+
await services.plugins.change("enable", "buzz.channel-usage");
260+
await vi.waitFor(() =>
261+
assert.ok(
262+
services.panels
263+
.snapshot()
264+
.some(
265+
(panel) =>
266+
panel.pluginId === "buzz.channel-usage" && panel !== usage,
267+
),
268+
),
269+
);
270+
247271
const activity = services.panels
248272
.snapshot()
249273
.find((panel) => panel.pluginId === "buzz.agent-activity");
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
.owner {
2+
display: flex;
3+
flex-direction: column;
4+
height: 100%;
5+
min-height: 0;
6+
min-width: 0;
7+
overflow-y: auto;
8+
font-size: var(--text-body);
9+
}
10+
.strip {
11+
display: flex;
12+
flex: none;
13+
min-inline-size: 0;
14+
align-items: center;
15+
flex-wrap: wrap;
16+
gap: var(--space-1);
17+
padding: var(--space-1) var(--space-panel-inset);
18+
}
19+
.strip > span:first-child {
20+
color: var(--text-subtle);
21+
white-space: nowrap;
22+
}
23+
.agentPicker {
24+
min-width: 0;
25+
max-width: min(100%, 20rem);
26+
}
27+
.details {
28+
min-height: 0;
29+
padding: var(--space-2) var(--space-panel-inset);
30+
overflow-wrap: anywhere;
31+
}
32+
.details h2,
33+
.details h3 {
34+
font-size: var(--text-label);
35+
margin: var(--space-2) 0;
36+
}
37+
.heading,
38+
.turnHead {
39+
display: flex;
40+
align-items: center;
41+
justify-content: space-between;
42+
gap: var(--space-1);
43+
}
44+
.sessionPicker {
45+
max-width: min(100%, 24rem);
46+
margin-top: var(--space-2);
47+
}
48+
.breakdown {
49+
display: grid;
50+
grid-template-columns: minmax(7rem, 1fr) minmax(0, 1fr);
51+
gap: var(--space-1) var(--space-2);
52+
max-width: 32rem;
53+
}
54+
.breakdown dd {
55+
min-width: 0;
56+
margin: 0;
57+
text-align: end;
58+
font-variant-numeric: tabular-nums;
59+
overflow-wrap: anywhere;
60+
}
61+
.turnList {
62+
overscroll-behavior: contain;
63+
}
64+
.turn {
65+
border-top: 1px solid var(--border-subtle);
66+
padding: var(--space-1) 0;
67+
}
68+
.turnHead {
69+
font-variant-numeric: tabular-nums;
70+
flex-wrap: wrap;
71+
}
72+
.turnHead time {
73+
color: var(--text-subtle);
74+
}
75+
@media (max-width: 440px) {
76+
.turnHead {
77+
justify-content: flex-start;
78+
}
79+
}
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
// @vitest-environment jsdom
2+
import { act, cleanup, render, screen, within } from "@testing-library/react";
3+
import userEvent from "@testing-library/user-event";
4+
import { afterEach, expect, it, vi } from "vitest";
5+
import type { RelaySession } from "../../features/relay/session";
6+
import type { ArchiveHost, ArchivePage } from "../../features/archive/types";
7+
import { ChannelUsage } from "./ChannelUsage";
8+
9+
const key = (n: number) => n.toString(16).padStart(64, "0");
10+
const frame = (
11+
agent: number,
12+
session: string,
13+
turn: number,
14+
total?: number,
15+
): ArchivePage["records"][number] => ({
16+
id: key(agent * 100 + turn + (session === "b" ? 50 : 0)),
17+
agent: key(agent),
18+
createdAt: turn,
19+
receivedAt: turn,
20+
plaintext: JSON.stringify({
21+
harness: "goose",
22+
model: "model",
23+
timestamp: new Date((turn + 1) * 1000).toISOString(),
24+
channelId: "channel",
25+
sessionId: session,
26+
turnId: `turn-${turn}`,
27+
turnSeq: turn,
28+
turn: { inputTokens: 0, costUsd: 0 },
29+
cumulative: { inputTokens: 10, totalTokens: total ?? null, costUsd: 0 },
30+
}),
31+
});
32+
const host = (records: ArchivePage["records"]): ArchiveHost => ({
33+
location: "device",
34+
settings: vi.fn(async () => ({
35+
observer: true,
36+
metrics: true,
37+
observerDays: 30,
38+
revision: 1,
39+
location: "device" as const,
40+
path: "isolated",
41+
bytes: 0,
42+
})),
43+
read: vi.fn(async () => ({
44+
records,
45+
before: null,
46+
agents: [],
47+
skipped: 0,
48+
revision: 1,
49+
})),
50+
configure: vi.fn(),
51+
clear: vi.fn(),
52+
});
53+
function fixture(records: ArchivePage["records"]) {
54+
const archive = host(records);
55+
let access = true;
56+
const listeners = new Set<() => void>();
57+
const list = {
58+
status: "ready",
59+
channels: [{ id: "channel", name: "Channel", members: [key(9)] }],
60+
};
61+
const empty = { status: "ready", channels: [] };
62+
const session = {
63+
viewer: key(9),
64+
agentActivity: { archive },
65+
channels: {
66+
list: () => (access ? list : empty),
67+
subscribeList: (listener: () => void) => {
68+
listeners.add(listener);
69+
return () => listeners.delete(listener);
70+
},
71+
},
72+
} as unknown as RelaySession;
73+
return {
74+
session,
75+
archive,
76+
revoke: () =>
77+
act(() => {
78+
access = false;
79+
for (const listener of listeners) listener();
80+
}),
81+
};
82+
}
83+
afterEach(cleanup);
84+
it("opens the selected agent, requires explicit multi-session selection, and expands zero-valued turn details", async () => {
85+
const records = [
86+
frame(1, "a", 1, 0),
87+
frame(1, "b", 2, 20),
88+
frame(2, "a", 1, 30),
89+
];
90+
const { session } = fixture(records);
91+
render(<ChannelUsage session={session} channelId="channel" />);
92+
const user = userEvent.setup();
93+
const picker = screen.getByRole("combobox", { name: "Agent usage" });
94+
expect(picker.textContent).toContain("Select agent");
95+
await user.click(picker);
96+
await user.click(await screen.findByRole("option", { name: /2 sessions/ }));
97+
expect(picker.textContent).toContain("2 sessions");
98+
const totals = screen.getByRole("region", { name: "All session totals" });
99+
expect(within(totals).getByText("Totals across 2 sessions")).toBeTruthy();
100+
expect(within(totals).getAllByText("20")).toHaveLength(2);
101+
// Both latest snapshots report input; token totals and costs use different coverage.
102+
expect(within(totals).getByText("$0.00")).toBeTruthy();
103+
expect(screen.queryByText("Latest reported session counters")).toBeNull();
104+
const sessions = screen.getByRole("combobox", { name: "Session" });
105+
expect(sessions.textContent).toContain("Select session");
106+
await user.click(sessions);
107+
await user.click(await screen.findByRole("option", { name: /Session 1 ·/ }));
108+
expect(screen.getByText("Latest reported session counters")).toBeTruthy();
109+
const list = screen.getByRole("region", { name: /recorded turns/ });
110+
await user.click(within(list).getByRole("button", { name: /Show turn/ }));
111+
expect(within(list).getByText("Input")).toBeTruthy();
112+
expect(within(list).getAllByText("$0.00").length).toBeGreaterThan(0);
113+
await user.click(sessions);
114+
await user.click(await screen.findByRole("option", { name: /Session 2 ·/ }));
115+
expect(
116+
within(screen.getByRole("region", { name: /recorded turns/ })).queryByText(
117+
"Input",
118+
),
119+
).toBeNull();
120+
const close = screen.getByRole("button", { name: "Close" });
121+
close.focus();
122+
await user.keyboard("{Enter}");
123+
expect(document.activeElement).toBe(picker);
124+
expect(
125+
screen.queryByRole("region", { name: "Session usage details" }),
126+
).toBeNull();
127+
});
128+
it("hides decoded usage when the authorized channel disappears", async () => {
129+
const { session, revoke } = fixture([frame(1, "a", 1, 10)]);
130+
render(<ChannelUsage session={session} channelId="channel" />);
131+
expect(
132+
await screen.findByRole("combobox", { name: "Agent usage" }),
133+
).toBeTruthy();
134+
revoke();
135+
expect(screen.queryByRole("combobox", { name: "Agent usage" })).toBeNull();
136+
expect(screen.queryByText("Channel session usage")).toBeNull();
137+
});
138+
it("keeps incomplete cross-session counters unknown and handles a hundred sessions in one dropdown", async () => {
139+
const records = Array.from({ length: 100 }, (_, index) => ({
140+
...frame(1, `session-${index}`, index + 1, index + 1),
141+
id: key(index + 1000),
142+
...(index === 0
143+
? {
144+
plaintext: JSON.stringify({
145+
harness: "goose",
146+
timestamp: new Date(2000).toISOString(),
147+
channelId: "channel",
148+
turnSeq: 1,
149+
turn: { inputTokens: 1 },
150+
}),
151+
}
152+
: {}),
153+
}));
154+
// One unidentified session has no trustworthy cumulative snapshot.
155+
const { session } = fixture(records);
156+
render(<ChannelUsage session={session} channelId="channel" />);
157+
const user = userEvent.setup();
158+
await user.click(screen.getByRole("combobox", { name: "Agent usage" }));
159+
await user.click(await screen.findByRole("option", { name: /100 sessions/ }));
160+
const totals = screen.getByRole("region", { name: "All session totals" });
161+
expect(within(totals).getByText(/99 of 100 sessions/)).toBeTruthy();
162+
expect(within(totals).getAllByText("—").length).toBe(6);
163+
const picker = screen.getByRole("combobox", { name: "Session" });
164+
await user.click(picker);
165+
expect(await screen.findAllByRole("option")).toHaveLength(100);
166+
await user.click(screen.getByRole("option", { name: /Session 99 ·/ }));
167+
expect(screen.getByText("Latest reported session counters")).toBeTruthy();
168+
});

0 commit comments

Comments
 (0)