feat(companion): add pending work snapshot helper

This commit is contained in:
William Valentin
2026-02-16 21:57:34 -08:00
parent c5bc2c1754
commit b4cef5235e
7 changed files with 95 additions and 2 deletions
+2 -2
View File
@@ -1190,7 +1190,7 @@ Methods:
- `system.capabilities` returns gateway protocol and node policy snapshot.
Companion runtime helper:
- `src/companion/runtimeClient.ts` provides a typed Node/WebSocket client for companion runtimes (macOS/iOS/Android workers) with wrappers for `node.register`, `node.capabilities.get`, `node.location.set/get`, `node.status.set`, `node.push_token.set`, `system.capabilities`, `system.nodes`, and canvas artifact RPCs (`canvas.put/get/list/delete/clear`), plus convenience helpers (`bootstrapNode`, optional `autoConnect`, `dispose()`, `waitForIdle()` for pending-work drain synchronization) and event helpers (`subscribeEvents()`, `subscribeEvent()`, `subscribeAgentStream()`, `subscribeAgentTyping()`, `subscribeContextWarning()`, `waitForEvent()` with timeout/predicate/abort support, non-empty event-name validation, and deterministic teardown cancellation (including socket-close rejection), `waitForAnyEvent()` (with non-empty event-name-list validation), `waitForAgentStream()`, `waitForAgentTyping()`, `waitForContextWarning()`, `clearEventSubscriptions()`, `listKnownEventNames()`, `eventSubscriptionCount`) plus in-flight observability via `pendingRequestCount`, `pendingEventWaitCount`, and `hasPendingWork`.
- `src/companion/runtimeClient.ts` provides a typed Node/WebSocket client for companion runtimes (macOS/iOS/Android workers) with wrappers for `node.register`, `node.capabilities.get`, `node.location.set/get`, `node.status.set`, `node.push_token.set`, `system.capabilities`, `system.nodes`, and canvas artifact RPCs (`canvas.put/get/list/delete/clear`), plus convenience helpers (`bootstrapNode`, optional `autoConnect`, `dispose()`, `waitForIdle()` for pending-work drain synchronization) and event helpers (`subscribeEvents()`, `subscribeEvent()`, `subscribeAgentStream()`, `subscribeAgentTyping()`, `subscribeContextWarning()`, `waitForEvent()` with timeout/predicate/abort support, non-empty event-name validation, and deterministic teardown cancellation (including socket-close rejection), `waitForAnyEvent()` (with non-empty event-name-list validation), `waitForAgentStream()`, `waitForAgentTyping()`, `waitForContextWarning()`, `clearEventSubscriptions()`, `listKnownEventNames()`, `eventSubscriptionCount`) plus in-flight observability via `pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, and `getPendingWorkSnapshot()`.
- `src/companion/platformClients.ts` provides platform-focused wrappers:
- `MacOSCompanionClient` (`platform: "macos"`, APNs push registration)
- `IOSCompanionClient` (`platform: "ios"`, APNs push registration)
@@ -1201,7 +1201,7 @@ Companion runtime helper:
- optional `defaultSessionId` for canvas helper calls so `sessionId` can be omitted per call
- lifecycle passthroughs for connection state/teardown (`connected`, `dispose(code?, reason?)`)
- stream passthrough helpers (`subscribeEvents`, `subscribeEvent`, `clearEventSubscriptions`, `listKnownEventNames`, `eventSubscriptionCount`, `subscribeAgentStream/Typing/ContextWarning`, `waitForEvent`, `waitForAnyEvent`, `waitForAgentStream/Typing/ContextWarning`)
- runtime observability/control passthroughs (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `connected`, `waitForIdle()`)
- runtime observability/control passthroughs (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `getPendingWorkSnapshot()`, `connected`, `waitForIdle()`)
- `src/companion/heartbeatLoop.ts` provides `CompanionHeartbeatLoop` for periodic heartbeat scheduling (`publishHeartbeat`) with start/stop safety, optional interval jitter (`jitterRatio`) to spread load (with safe normalization for invalid random samples), `tickNow()` for manual sends, success/error hooks, loop observability (`successCount`, `lastSuccessAt`, `failureCount`, `lastFailure`, `getState()`), and optional auto-stop after repeated failures.
## Canvas / A2UI Foundation
+16
View File
@@ -963,6 +963,22 @@
],
"test_status": "pnpm test:run src/companion/heartbeatLoop.test.ts src/companion/platformClients.test.ts src/companion/runtimeClient.test.ts src/companion/platformClients.integration.test.ts + pnpm typecheck passing"
},
"companion-runtime-pending-work-snapshot-helper": {
"status": "completed",
"date": "2026-02-17",
"updated": "2026-02-17",
"summary": "Added runtime `getPendingWorkSnapshot()` helper and platform passthroughs for single-call pending-work state inspection (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`).",
"files_modified": [
"src/companion/runtimeClient.ts",
"src/companion/runtimeClient.test.ts",
"src/companion/platformClients.ts",
"src/companion/platformClients.test.ts",
"src/companion/index.ts",
"README.md",
"docs/plans/state.json"
],
"test_status": "pnpm test:run src/companion/runtimeClient.test.ts src/companion/platformClients.test.ts src/companion/heartbeatLoop.test.ts src/companion/platformClients.integration.test.ts + pnpm typecheck passing"
},
"browser-tools-activation-clarity": {
"status": "completed",
"date": "2026-02-17",
+1
View File
@@ -13,6 +13,7 @@ export { CompanionHeartbeatLoop } from './heartbeatLoop.js';
export type {
CompanionRuntimeClientOptions,
WaitForIdleOptions,
PendingWorkSnapshot,
CompanionEventHandler,
CompanionTypedEventHandler,
CompanionEventName,
+22
View File
@@ -34,6 +34,7 @@ function createRuntimeMock(): {
listKnownEventNames: ReturnType<typeof vi.fn>;
waitForEvent: ReturnType<typeof vi.fn>;
waitForIdle: ReturnType<typeof vi.fn>;
getPendingWorkSnapshot: ReturnType<typeof vi.fn>;
waitForAgentStream: ReturnType<typeof vi.fn>;
waitForAgentTyping: ReturnType<typeof vi.fn>;
waitForContextWarning: ReturnType<typeof vi.fn>;
@@ -77,6 +78,11 @@ function createRuntimeMock(): {
const listKnownEventNames = vi.fn(() => ['agent.stream', 'agent.typing', 'context_warning']);
const waitForEvent = vi.fn(async () => ({ token: 'evented' }));
const waitForIdle = vi.fn(async () => undefined);
const getPendingWorkSnapshot = vi.fn(() => ({
pendingRequestCount: 2,
pendingEventWaitCount: 1,
hasPendingWork: true,
}));
const waitForAgentStream = vi.fn(async () => ({ token: 'streamed' }));
const waitForAgentTyping = vi.fn(async () => ({ active: true }));
const waitForContextWarning = vi.fn(async () => ({ thresholdPct: 75, estimatedPct: 90 }));
@@ -114,6 +120,7 @@ function createRuntimeMock(): {
listKnownEventNames,
waitForEvent,
waitForIdle,
getPendingWorkSnapshot,
waitForAgentStream,
waitForAgentTyping,
waitForContextWarning,
@@ -163,6 +170,7 @@ function createRuntimeMock(): {
listKnownEventNames,
waitForEvent,
waitForIdle,
getPendingWorkSnapshot,
waitForAgentStream,
waitForAgentTyping,
waitForContextWarning,
@@ -346,6 +354,20 @@ describe('platform companion clients', () => {
expect(mock.waitForIdle).toHaveBeenCalledWith({ timeoutMs: 250, pollIntervalMs: 10 });
});
it('platform getPendingWorkSnapshot forwards to runtime client', async () => {
const mock = createRuntimeMock();
const client = new IOSCompanionClient({ runtime: mock.runtime, nodeId: 'ios-node' });
const snapshot = client.getPendingWorkSnapshot();
expect(mock.getPendingWorkSnapshot).toHaveBeenCalledOnce();
expect(snapshot).toEqual({
pendingRequestCount: 2,
pendingEventWaitCount: 1,
hasPendingWork: true,
});
});
it('macOS client forwards canvas methods to runtime client', async () => {
const mock = createRuntimeMock();
const client = new MacOSCompanionClient({ runtime: mock.runtime, nodeId: 'mac-node' });
+13
View File
@@ -18,6 +18,7 @@ import type {
NodeRegisterResult,
NodeStatusSetResult,
PutCanvasArtifactInput,
PendingWorkSnapshot,
NodePushTokenSetResult,
SetNodeLocationInput,
SystemCapabilitiesResult,
@@ -288,6 +289,10 @@ export class MacOSCompanionClient {
return this.runtime.hasPendingWork;
}
getPendingWorkSnapshot(): PendingWorkSnapshot {
return this.runtime.getPendingWorkSnapshot();
}
waitForAnyEvent<TData = unknown>(
eventNames: readonly (CompanionEventName | string)[],
options?: {
@@ -546,6 +551,10 @@ export class IOSCompanionClient {
return this.runtime.hasPendingWork;
}
getPendingWorkSnapshot(): PendingWorkSnapshot {
return this.runtime.getPendingWorkSnapshot();
}
waitForAnyEvent<TData = unknown>(
eventNames: readonly (CompanionEventName | string)[],
options?: {
@@ -802,6 +811,10 @@ export class AndroidCompanionClient {
return this.runtime.hasPendingWork;
}
getPendingWorkSnapshot(): PendingWorkSnapshot {
return this.runtime.getPendingWorkSnapshot();
}
waitForAnyEvent<TData = unknown>(
eventNames: readonly (CompanionEventName | string)[],
options?: {
+27
View File
@@ -643,6 +643,33 @@ describe('CompanionRuntimeClient', () => {
expect(client.hasPendingWork).toBe(false);
});
it('returns pending work snapshot', async () => {
const client = new CompanionRuntimeClient({
url: 'ws://127.0.0.1:1',
});
expect(client.getPendingWorkSnapshot()).toEqual({
pendingRequestCount: 0,
pendingEventWaitCount: 0,
hasPendingWork: false,
});
const pendingWait = client.waitForEvent('agent.stream', { timeoutMs: 10_000 }).catch(() => undefined);
expect(client.getPendingWorkSnapshot()).toEqual({
pendingRequestCount: 0,
pendingEventWaitCount: 1,
hasPendingWork: true,
});
client.clearEventSubscriptions();
await pendingWait;
expect(client.getPendingWorkSnapshot()).toEqual({
pendingRequestCount: 0,
pendingEventWaitCount: 0,
hasPendingWork: false,
});
});
it('waitForIdle resolves immediately when no work is pending', async () => {
const client = new CompanionRuntimeClient({
url: 'ws://127.0.0.1:1',
+14
View File
@@ -47,6 +47,12 @@ export interface WaitForIdleOptions {
signal?: AbortSignal;
}
export interface PendingWorkSnapshot {
pendingRequestCount: number;
pendingEventWaitCount: number;
hasPendingWork: boolean;
}
export type CompanionEventHandler = (event: string, data: unknown) => void;
export type CompanionTypedEventHandler<TData = unknown> = (data: TData) => void;
export type CompanionEventPredicate<TData = unknown> = (data: TData) => boolean;
@@ -320,6 +326,14 @@ export class CompanionRuntimeClient {
return this.pendingRequestCount > 0 || this.pendingEventWaitCount > 0;
}
getPendingWorkSnapshot(): PendingWorkSnapshot {
return {
pendingRequestCount: this.pendingRequestCount,
pendingEventWaitCount: this.pendingEventWaitCount,
hasPendingWork: this.hasPendingWork,
};
}
async connect(): Promise<void> {
if (this.connected) {
return;