Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(desktop): keep the pet busy while any conversation's agent works (#2401)

Maxa0195a27421c
diff --git a/docs/plans/2026-10-01-desktop-pet.md b/docs/plans/2026-10-01-desktop-pet.md
index 097c3fa31..011986f03 100644
--- a/docs/plans/2026-10-01-desktop-pet.md
+++ b/docs/plans/2026-10-01-desktop-pet.md
@@ -374,6 +374,28 @@ comes from an API the Workbench already uses:
(`turn_state.background_activities`) do not change the state. The panel
shows them as an activity strip, and the collapsed pet shows a count. The pet
is "Running" only when the agent itself is working.
+- **Other conversations move the pose only.** When the bound session is
+ Idle (or nothing is bound) and an agent is mid-turn in any other
+ conversation the user can see, the avatar shows the Running pose and does
+ not fall asleep. The state, the panel, the badge and `data-state` still
+ describe the bound session alone, so the panel never claims `S` is running.
+ - "Working" means an `active` instance of a `foreground` session in the
+ running-agents snapshot (`GET /api/running-agents`, the Agents page's
+ source), on any surface. Background runs, Runtime-owned sessions and
+ session-less processes do not count; an unreachable snapshot counts as
+ nothing working.
+ - It is read only with `can_use_agents`. It is re-read on every event that
+ can change an input of the rule, declared once as `REFRESH_TRIGGERS`:
+ agent state (`turn.start`, `turn.end`, `session.status`,
+ `runs.updated`), a session's visibility or existence
+ (`session.activity`), what the reader may see (authorization changes),
+ and gaps (reconnect, page return). A 30-second reconcile while visible
+ covers IM turns and agents that stop without an event.
+ - `turn.start` is published before the backend registers the agent as
+ active, so a started session is re-read every 2 seconds until the
+ snapshot shows it active, its `turn.end` arrives, or 30 seconds pass.
+ - `derivePetPose(state, {othersWorking, asleep})` is the pure rule; the
+ bound session's non-Idle states always win.
- **Reading.** The pet marks read only what it rendered. The expanded panel
renders every unread agent result in the loaded tail, oldest first, in a
scrollable list, rather than only the latest one.
@@ -400,6 +422,13 @@ indefinitely with no action that clears it. Older groups stay clickable in the
Workbench, reached with "Open in Avibe". This also keeps the state computable
from the bounded tail, with no history scan.
+A group is also answered by any user input after it (a row whose type lists
+`user` in the catalog's `inputAuthors`; a display-only Show Page annotation is
+not input). The user often answers
+in free text, and that message starts a turn: until the next result lands the
+agent is working on the answer, so the pet shows Running rather than Needs
+input for the whole turn.
+
Tool approvals and `AskUserQuestion`-style waits do not exist today. Claude
runs with permissions bypassed and Codex auto-approves, so vault requests and
quick replies are the complete "needs input" set for now. A future backend that
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ec52345c7..9e3d553cd 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1836,6 +1836,8 @@ export type RunningAgent = {
platform: string | null;
scope_type: string | null;
scope_display_name: string | null;
+ /** The session's visibility; null for a process with no session row. */
+ visibility: 'foreground' | 'background' | 'system' | null;
trigger_source: 'human' | 'agent' | 'scheduled' | 'watch' | 'webhook' | 'callback' | null;
agent_name: string | null;
openable_in_chat: boolean;
diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsx
index 30adb5bc2..4b18055d0 100644
--- a/ui/src/pet/PetPage.test.tsx
+++ b/ui/src/pet/PetPage.test.tsx
@@ -4,7 +4,13 @@ import { act, cleanup, render, screen, waitFor, within } from '@testing-library/
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { WorkbenchEventHandlers, WorkbenchMessage, WorkbenchSession, WorkbenchSessionReadResult } from '@/context/ApiContext';
+import type {
+ RunningAgentsResult,
+ WorkbenchEventHandlers,
+ WorkbenchMessage,
+ WorkbenchSession,
+ WorkbenchSessionReadResult,
+} from '@/context/ApiContext';
import { ApiError } from '@/context/ApiContext';
@@ -89,6 +95,17 @@ let sessionReads: Record<string, () => Promise<WorkbenchSessionReadResult>> = {}
let tails: Record<string, WorkbenchMessage[]> = {};
let switcherSessions: WorkbenchSession[] = [];
let unreadBySession: Record<string, number> = {};
+let runningAgents: RunningAgentsResult = { ok: true, agents: [], counts: { total: 0, active: 0, idle: 0, orphan: 0, by_backend: {} } };
+const workingIn = (sessionId: string): RunningAgentsResult => ({
+ ok: true,
+ agents: [{
+ backend: 'claude', state: 'active', base_session_id: sessionId, composite_key: null, workdir: null, pid: null,
+ pid_shared: false, native_session_id: null, model: null, elapsed_seconds: 1, session_id: sessionId, title: null,
+ platform: 'avibe', scope_type: 'project', scope_display_name: null, visibility: 'foreground',
+ trigger_source: 'human', agent_name: 'claude', openable_in_chat: true,
+ }],
+ counts: { total: 1, active: 1, idle: 0, orphan: 0, by_backend: { claude: 1 } },
+});
// Like the provider, a mark-read response installs a new unread map, so every
// consumer re-renders with a new inbox object.
let inboxVersion = 0;
@@ -110,6 +127,7 @@ const api = {
getTurnState: vi.fn(async () => idleTurn),
listSessions: vi.fn(async () => ({ sessions: switcherSessions, next_before_id: null })),
getVaultRequests: vi.fn(async () => ({ requests: [] })),
+ getRunningAgents: vi.fn(async (): Promise<RunningAgentsResult> => runningAgents),
sendSessionMessage: vi.fn(async () => message('sent', 'S', { author: 'user', type: 'user' })),
connectWorkbenchEvents: (h: WorkbenchEventHandlers) => {
handlers.add(h);
@@ -122,8 +140,9 @@ vi.mock('@/context/ApiContext', async (importOriginal) => ({
useApi: () => api,
}));
let canChat = true;
+let canUseAgents = false;
vi.mock('@/context/InstanceAuthorizationContext', () => ({
- useInstanceAuthorization: () => ({ capabilities: { can_chat: canChat } }),
+ useInstanceAuthorization: () => ({ capabilities: { can_chat: canChat, can_use_agents: canUseAgents } }),
}));
vi.mock('@/context/WorkbenchInboxContext', async () => {
const { useSyncExternalStore } = await import('react');
@@ -190,6 +209,9 @@ beforeEach(async () => {
setupDone = true;
windowFocused = true;
canChat = true;
+ canUseAgents = false;
+ runningAgents = { ok: true, agents: [], counts: { total: 0, active: 0, idle: 0, orphan: 0, by_backend: {} } };
+ api.getRunningAgents.mockClear();
sessionReads = {};
tails = {};
switcherSessions = [];
@@ -338,6 +360,73 @@ describe('PetPage state', () => {
});
});
+describe('PetPage other conversations', () => {
+ const dataState = () => document.querySelector('[data-state]')?.getAttribute('data-state');
+
+ it('looks busy while another conversation\'s agent works, and the bound session stays idle', async () => {
+ canUseAgents = true;
+ runningAgents = workingIn('T');
+ devBind('S');
+ render(<PetPage />);
+ await waitFor(() => expect(pose()).toBe('running'));
+ expect(dataState()).toBe('idle');
+ runningAgents = { ...runningAgents, agents: [] };
+ await emit((h) => h.onTurnEnd?.({ session_id: 'T' }));
+ await waitFor(() => expect(pose()).toBe('idle'));
+ });
+
+ it('keeps re-reading a started turn until the backend registers it', async () => {
+ canUseAgents = true;
+ devBind('S');
+ render(<PetPage />);
+ await waitFor(() => expect(api.getRunningAgents).toHaveBeenCalled());
+ // turn.start lands before the agent is active in the snapshot.
+ await emit((h) => h.onTurnStart?.({ session_id: 'T' }));
+ await waitFor(() => expect(api.getRunningAgents.mock.calls.length).toBeGreaterThanOrEqual(2));
+ expect(pose()).toBe('idle');
+ runningAgents = workingIn('T');
+ await waitFor(() => expect(pose()).toBe('running'), { timeout: 5000 });
+ // Registered: no more retries for it.
+ const settled = api.getRunningAgents.mock.calls.length;
+ await new Promise((resolve) => setTimeout(resolve, 2500));
+ expect(api.getRunningAgents.mock.calls.length).toBe(settled);
+ }, 15000);
+
+ it('re-reads on every event that can change who is working, and catches up on visibility', async () => {
+ const { REFRESH_TRIGGERS } = await import('./useConversationAgentWorking');
+ canUseAgents = true;
+ runningAgents = workingIn('T');
+ devBind('S');
+ render(<PetPage />);
+ await waitFor(() => expect(pose()).toBe('running'));
+ for (const trigger of REFRESH_TRIGGERS) {
+ const before = api.getRunningAgents.mock.calls.length;
+ await emit((h) => (h[trigger] as ((data: unknown) => void) | undefined)?.({ session_id: 'T', scope_id: null, event: 'updated' }));
+ await waitFor(() => expect(api.getRunningAgents.mock.calls.length, trigger).toBeGreaterThan(before));
+ }
+ // T moved to the background: its agent no longer counts.
+ runningAgents = { ...runningAgents, agents: runningAgents.agents.map((agent) => ({ ...agent, visibility: 'background' })) };
+ await emit((h) => h.onSessionActivity?.({ session_id: 'T', scope_id: null, event: 'visibility', visibility: 'background' }));
+ await waitFor(() => expect(pose()).toBe('idle'));
+ });
+
+ it('also looks busy with no binding at all', async () => {
+ canUseAgents = true;
+ runningAgents = workingIn('T');
+ render(<PetPage />);
+ await waitFor(() => expect(pose()).toBe('running'));
+ });
+
+ it('never reads other conversations without the agents permission', async () => {
+ runningAgents = workingIn('T');
+ devBind('S');
+ render(<PetPage />);
+ await waitFor(() => expect(api.getTurnState).toHaveBeenCalled());
+ expect(pose()).toBe('idle');
+ expect(api.getRunningAgents).not.toHaveBeenCalled();
+ });
+});
+
describe('PetPage review fixes', () => {
it('marks a rendered row read once, however often the inbox state changes', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r1', 'S', { read_at: null })];
diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsx
index c45a0031e..8726fb82e 100644
--- a/ui/src/pet/PetPage.tsx
+++ b/ui/src/pet/PetPage.tsx
@@ -29,7 +29,8 @@ import {
import { petComposer, usePetComposer } from './petComposer';
import { petPanel, usePetPanel } from './petPanel';
import { petShell, useOnSummon, usePetBinding } from './petShell';
-import { derivePetState, latestExchange, openQuickReplies } from './petState';
+import { derivePetPose, derivePetState, latestExchange, openQuickReplies } from './petState';
+import { useConversationAgentWorking } from './useConversationAgentWorking';
import { usePetSession } from './usePetSession';
import { usePetSetup } from './usePetSetup';
import { useSessionSwitcher } from './useSessionSwitcher';
@@ -122,6 +123,8 @@ const PetSurface: React.FC = () => {
pendingVaultRequests: vaultRequests.length,
unreadCount,
});
+ // Reading every conversation's agents is the Agents page's permission.
+ const othersWorking = useConversationAgentWorking(capabilities.can_use_agents === true);
const summon = useCallback((intent: PetIntent, bound: string | null) => {
void setPanel(true);
@@ -177,15 +180,15 @@ const PetSurface: React.FC = () => {
return () => window.removeEventListener('blur', onBlur);
}, [expanded, draft, setPanel]);
- // Idle → asleep after a while without a state change.
+ // Idle → asleep after a while with nothing working anywhere.
const [asleep, setAsleep] = useState(false);
useEffect(() => {
setAsleep(false);
- if (state !== 'idle') return undefined;
+ if (state !== 'idle' || othersWorking) return undefined;
const timer = window.setTimeout(() => setAsleep(true), SLEEP_AFTER_MS);
return () => window.clearTimeout(timer);
- }, [state, binding]);
- const pose: PetPose = state === 'idle' && asleep ? 'sleeping' : state;
+ }, [state, binding, othersWorking]);
+ const pose: PetPose = derivePetPose(state, { othersWorking, asleep });
const exchange = useMemo(
() => latestExchange(data.messages, data.hasOlder, unreadCount),
diff --git a/ui/src/pet/petState.test.ts b/ui/src/pet/petState.test.ts
index 16b9538ff..2044b5ef7 100644
--- a/ui/src/pet/petState.test.ts
+++ b/ui/src/pet/petState.test.ts
@@ -1,8 +1,16 @@
import { describe, expect, it } from 'vitest';
-import type { WorkbenchMessage } from '@/context/ApiContext';
+import type { RunningAgent, RunningAgentsResult, WorkbenchMessage } from '@/context/ApiContext';
-import { derivePetState, latestExchange, openQuickReplies, type PetStateInputs } from './petState';
+import {
+ conversationAgentWorking,
+ derivePetPose,
+ derivePetState,
+ latestExchange,
+ openQuickReplies,
+ type PetState,
+ type PetStateInputs,
+} from './petState';
let nextId = 0;
const row = (overrides: Partial<WorkbenchMessage>): WorkbenchMessage => ({
@@ -77,6 +85,16 @@ describe('derivePetState', () => {
expect(derivePetState({ ...quiet, messages: [user(), asking('Yes')] })).toBe('idle');
});
+ it('treats a free-text reply after the group as its answer, while that turn runs', () => {
+ const messages = [user(), asking(), user('free text')];
+ expect(openQuickReplies(messages)).toBeNull();
+ expect(derivePetState({ ...quiet, messages, turn: { foreground: 'running', in_flight: true } })).toBe('running');
+ // Rows that are not the user's input do not answer it: a harness message,
+ // or the user's own display-only Show Page annotation.
+ expect(openQuickReplies([user(), asking(), row({ author: 'harness', type: 'harness' })])).not.toBeNull();
+ expect(openQuickReplies([user(), asking(), row({ author: 'user', type: 'annotation', source: 'user' })])).not.toBeNull();
+ });
+
it('ignores an older unanswered group once a newer result exists', () => {
const messages = [user(), asking(), user('free text'), result()];
expect(openQuickReplies(messages)).toBeNull();
@@ -123,3 +141,67 @@ describe('latestExchange', () => {
expect(exchange.results.map((message) => message.text)).toEqual(['done']);
});
});
+
+const agent = (overrides: Partial<RunningAgent>): RunningAgent => ({
+ backend: 'claude',
+ state: 'active',
+ base_session_id: 'S',
+ composite_key: 'S:/w',
+ workdir: '/w',
+ pid: 1,
+ pid_shared: false,
+ native_session_id: null,
+ model: null,
+ elapsed_seconds: 1,
+ session_id: 'S',
+ title: 'S',
+ platform: 'avibe',
+ scope_type: 'project',
+ scope_display_name: 'p',
+ visibility: 'foreground',
+ trigger_source: 'human',
+ agent_name: 'claude',
+ openable_in_chat: true,
+ ...overrides,
+});
+const snapshot = (agents: RunningAgent[]): RunningAgentsResult => ({
+ ok: true,
+ agents,
+ counts: { total: agents.length, active: 0, idle: 0, orphan: 0, by_backend: {} },
+});
+
+describe('conversationAgentWorking', () => {
+ it('is true only for an active agent in a foreground conversation', () => {
+ expect(conversationAgentWorking(snapshot([agent({})]))).toBe(true);
+ expect(conversationAgentWorking(snapshot([agent({ state: 'idle' }), agent({ state: 'orphan' })]))).toBe(false);
+ expect(conversationAgentWorking(snapshot([agent({ visibility: 'background' })]))).toBe(false);
+ expect(conversationAgentWorking(snapshot([agent({ visibility: 'system' })]))).toBe(false);
+ expect(conversationAgentWorking(snapshot([agent({ session_id: null, visibility: null })]))).toBe(false);
+ expect(conversationAgentWorking(snapshot([agent({ state: 'idle' }), agent({ session_id: 'T' })]))).toBe(true);
+ });
+
+ it('is false when the Runtime cannot answer', () => {
+ expect(conversationAgentWorking({ ok: false, unreachable: true, agents: [agent({})], counts: {} })).toBe(false);
+ });
+});
+
+describe('derivePetPose', () => {
+ const states: PetState[] = ['needs_input', 'blocked', 'ready', 'running', 'idle'];
+
+ it('keeps every bound-session state other than idle, whatever else is working', () => {
+ for (const state of states.filter((value) => value !== 'idle')) {
+ for (const othersWorking of [false, true]) {
+ for (const asleep of [false, true]) {
+ expect(derivePetPose(state, { othersWorking, asleep })).toBe(state);
+ }
+ }
+ }
+ });
+
+ it('shows another conversation\'s work over idle and sleep', () => {
+ expect(derivePetPose('idle', { othersWorking: true, asleep: true })).toBe('running');
+ expect(derivePetPose('idle', { othersWorking: true, asleep: false })).toBe('running');
+ expect(derivePetPose('idle', { othersWorking: false, asleep: true })).toBe('sleeping');
+ expect(derivePetPose('idle', { othersWorking: false, asleep: false })).toBe('idle');
+ });
+});
diff --git a/ui/src/pet/petState.ts b/ui/src/pet/petState.ts
index 06b5c2987..1aaea588a 100644
--- a/ui/src/pet/petState.ts
+++ b/ui/src/pet/petState.ts
@@ -1,5 +1,13 @@
-import type { SessionRuntimeState, WorkbenchMessage, WorkbenchSession } from '@/context/ApiContext';
+import type {
+ RunningAgentsResult,
+ SessionRuntimeState,
+ WorkbenchMessage,
+ WorkbenchSession,
+} from '@/context/ApiContext';
import { isTranscriptMessage } from '@/lib/chatMessageTypes';
+import { specFor } from '@/lib/messageTypes';
+
+import type { PetPose } from './PetAvatar';
/**
* What the desktop pet shows for its bound session. One pure derivation from
@@ -34,6 +42,11 @@ export const quickReplyChosen = (message: WorkbenchMessage): string | null => {
const isAgentResult = (message: WorkbenchMessage): boolean =>
message.author === 'agent' && message.type === 'result';
+/** A row the user sent the agent as input (the catalog's `inputAuthors`), not
+ * a display-only row such as a Show Page annotation. */
+const isUserInput = (message: WorkbenchMessage): boolean =>
+ message.author === 'user' && specFor(message.type).inputAuthors.includes('user');
+
/** The latest agent result in the tail, or null. */
export const latestAgentResult = (messages: WorkbenchMessage[]): WorkbenchMessage | null => {
for (let index = messages.length - 1; index >= 0; index -= 1) {
@@ -44,15 +57,22 @@ export const latestAgentResult = (messages: WorkbenchMessage[]): WorkbenchMessag
/**
* The quick-reply group the agent is waiting on now: the latest agent result's
- * group, while unanswered. An older unanswered group is not an open question —
- * once a newer result exists the agent has moved on — so it never counts
- * (it stays clickable in the Workbench).
+ * group, while unanswered. A group is answered by a chosen option or by any
+ * user input after it (a free-text reply, which then runs as a turn). An
+ * older unanswered group is not an open question either — once a newer result
+ * exists the agent has moved on — so it never counts (it stays clickable in
+ * the Workbench).
*/
export const openQuickReplies = (messages: WorkbenchMessage[]): { message: WorkbenchMessage; options: string[] } | null => {
- const latest = latestAgentResult(messages);
- if (!latest || quickReplyChosen(latest)) return null;
- const options = quickReplyOptions(latest);
- return options.length > 0 ? { message: latest, options } : null;
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (isUserInput(message)) return null;
+ if (!isAgentResult(message)) continue;
+ if (quickReplyChosen(message)) return null;
+ const options = quickReplyOptions(message);
+ return options.length > 0 ? { message, options } : null;
+ }
+ return null;
};
const isRunning = (turn: PetStateInputs['turn']): boolean =>
@@ -67,6 +87,31 @@ export const derivePetState = (inputs: PetStateInputs): PetState => {
return 'idle';
};
+/**
+ * Whether an agent is mid-turn in any conversation the user can see: an
+ * active instance of a foreground session, on any surface. Background runs,
+ * Runtime-owned sessions and processes without a session do not count, and
+ * an unreachable snapshot says nothing is known to be working.
+ */
+export const conversationAgentWorking = (result: RunningAgentsResult): boolean =>
+ result.ok === true
+ && result.agents.some((agent) => agent.state === 'active' && agent.visibility === 'foreground');
+
+/**
+ * What the avatar draws. The bound session's state wins; when it has nothing
+ * to say, an agent working in another conversation keeps the pet busy (and
+ * awake). Only the pose follows other sessions: the panel, badge and
+ * `data-state` describe the bound session alone.
+ */
+export const derivePetPose = (
+ state: PetState,
+ { othersWorking, asleep }: { othersWorking: boolean; asleep: boolean },
+): PetPose => {
+ if (state !== 'idle') return state;
+ if (othersWorking) return 'running';
+ return asleep ? 'sleeping' : 'idle';
+};
+
/**
* The rows the panel shows as the latest exchange: the last user message, then
* every unread agent result (oldest first), or the last agent result when none
diff --git a/ui/src/pet/useConversationAgentWorking.ts b/ui/src/pet/useConversationAgentWorking.ts
new file mode 100644
index 000000000..283ee63fe
--- /dev/null
+++ b/ui/src/pet/useConversationAgentWorking.ts
@@ -0,0 +1,134 @@
+import { useEffect, useMemo, useState } from 'react';
+
+import { useApi, type RunningAgentsResult, type WorkbenchEventHandlers } from '@/context/ApiContext';
+import { onPageReactivated } from '@/lib/pageActivity';
+
+import { FencedSource } from './fencedSource';
+import { conversationAgentWorking } from './petState';
+
+// Turn and status events cover Workbench sessions. This slower read catches
+// IM turns and agents that stop without an event.
+const RECONCILE_INTERVAL_MS = 30 * 1000;
+// `turn.start` is published before the backend registers the agent as active
+// (a cold Claude or Codex turn first creates its client), so a started
+// session is re-read at this pace until the snapshot shows it, its turn ends,
+// or the cap passes.
+const REGISTRATION_RETRY_MS = 2 * 1000;
+const REGISTRATION_CAP_MS = 30 * 1000;
+const ALL = 'all';
+
+/**
+ * Every event that can change an input of `conversationAgentWorking` and is
+ * answered by a plain re-read: an agent's state (`session.status`,
+ * `runs.updated`), a session's visibility or existence (`session.activity`),
+ * which agents this reader may see (authorization), and an event gap
+ * (reconnect). `turn.start` and `turn.end` also re-read, through the
+ * registration wait below.
+ */
+export const REFRESH_TRIGGERS = [
+ 'onConnected',
+ 'onSessionStatus',
+ 'onRunsUpdated',
+ 'onSessionActivity',
+ 'onAuthorizationChanged',
+] as const satisfies readonly (keyof WorkbenchEventHandlers)[];
+
+/** Sessions with an active agent in the snapshot, whatever their visibility. */
+const activeSessions = (result: RunningAgentsResult): Set<string> =>
+ new Set(
+ result.ok
+ ? result.agents.flatMap((agent) => (agent.state === 'active' && agent.session_id ? [agent.session_id] : []))
+ : [],
+ );
+
+/**
+ * The running-agents snapshot for the pet, fenced and coalesced, plus the
+ * started turns it is still waiting to see registered.
+ */
+class ConversationWorkingSource {
+ private readonly fenced: FencedSource<typeof ALL, RunningAgentsResult>;
+ /** Started sessions not yet seen active, with when to stop waiting. */
+ private readonly awaiting = new Map<string, number>();
+ private retry: number | undefined;
+
+ constructor(read: () => Promise<RunningAgentsResult>, onWorking: (working: boolean) => void) {
+ this.fenced = new FencedSource({
+ read,
+ apply: (_key, result) => {
+ onWorking(conversationAgentWorking(result));
+ this.settle(activeSessions(result));
+ },
+ fail: () => onWorking(false),
+ });
+ }
+
+ /** Read while enabled; disabled, drop whatever is in flight or waiting. */
+ setEnabled(enabled: boolean): void {
+ this.fenced.setKey(enabled ? ALL : null);
+ if (enabled) return;
+ this.awaiting.clear();
+ window.clearTimeout(this.retry);
+ }
+
+ refresh(): void {
+ this.fenced.refresh();
+ }
+
+ turnStarted(sessionId: string): void {
+ this.awaiting.set(sessionId, Date.now() + REGISTRATION_CAP_MS);
+ this.refresh();
+ }
+
+ turnEnded(sessionId: string): void {
+ this.awaiting.delete(sessionId);
+ this.refresh();
+ }
+
+ private settle(active: Set<string>): void {
+ const now = Date.now();
+ for (const [sessionId, until] of this.awaiting) {
+ if (active.has(sessionId) || until <= now) this.awaiting.delete(sessionId);
+ }
+ window.clearTimeout(this.retry);
+ if (this.awaiting.size > 0) {
+ this.retry = window.setTimeout(() => this.refresh(), REGISTRATION_RETRY_MS);
+ }
+ }
+}
+
+/**
+ * Whether an agent is working in any conversation the user can see, from the
+ * running-agents snapshot the Agents page reads. `enabled` is the caller's
+ * permission to read it; without it the answer is always false.
+ */
+export function useConversationAgentWorking(enabled: boolean): boolean {
+ const api = useApi();
+ const [working, setWorking] = useState(false);
+ const source = useMemo(() => new ConversationWorkingSource(() => api.getRunningAgents(), setWorking), [api]);
+
+ useEffect(() => {
+ // Disabled, the return value below ignores whatever was last read.
+ source.setEnabled(enabled);
+ if (!enabled) return undefined;
+ const refresh = () => source.refresh();
+ refresh();
+ const handlers: WorkbenchEventHandlers = {
+ onTurnStart: ({ session_id }) => source.turnStarted(session_id),
+ onTurnEnd: ({ session_id }) => source.turnEnded(session_id),
+ };
+ for (const trigger of REFRESH_TRIGGERS) handlers[trigger] = refresh;
+ const disconnect = api.connectWorkbenchEvents(handlers);
+ const stopReactivation = onPageReactivated(refresh);
+ const interval = window.setInterval(() => {
+ if (document.visibilityState === 'visible') refresh();
+ }, RECONCILE_INTERVAL_MS);
+ return () => {
+ disconnect();
+ stopReactivation();
+ window.clearInterval(interval);
+ source.setEnabled(false);
+ };
+ }, [api, enabled, source]);
+
+ return enabled && working;
+}