feat(companion): add connection snapshot helper

This commit is contained in:
William Valentin
2026-02-16 22:24:16 -08:00
parent 965267d67e
commit c8f6d76638
7 changed files with 107 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 plus event-name/timeout validation and deterministic teardown cancellation including socket-close rejection, `waitForAnyEvent()` with event-list/timeout validation, `waitForAgentStream()`, `waitForAgentTyping()`, `waitForContextWarning()`, `clearEventSubscriptions()`, `cancelPendingEventWaits()` returning cancelled waiter count, `listKnownEventNames()`, `eventSubscriptionCount`) plus in-flight observability via `pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `idle`, `getPendingWorkSnapshot()`, and `getEventSurfaceSnapshot()`.
- `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 plus event-name/timeout validation and deterministic teardown cancellation including socket-close rejection, `waitForAnyEvent()` with event-list/timeout validation, `waitForAgentStream()`, `waitForAgentTyping()`, `waitForContextWarning()`, `clearEventSubscriptions()`, `cancelPendingEventWaits()` returning cancelled waiter count, `listKnownEventNames()`, `eventSubscriptionCount`) plus in-flight observability via `pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `idle`, `getPendingWorkSnapshot()`, `getEventSurfaceSnapshot()`, and `getConnectionSnapshot()`.
- `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`, `cancelPendingEventWaits`, `listKnownEventNames`, `eventSubscriptionCount`, `subscribeAgentStream/Typing/ContextWarning`, `waitForEvent`, `waitForAnyEvent`, `waitForAgentStream/Typing/ContextWarning`)
- runtime observability/control passthroughs (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `idle`, `getPendingWorkSnapshot()`, `getEventSurfaceSnapshot()`, `connected`, `waitForIdle()`)
- runtime observability/control passthroughs (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `idle`, `getPendingWorkSnapshot()`, `getEventSurfaceSnapshot()`, `getConnectionSnapshot()`, `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
@@ -1056,6 +1056,22 @@
],
"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"
},
"companion-runtime-connection-snapshot-helper": {
"status": "completed",
"date": "2026-02-17",
"updated": "2026-02-17",
"summary": "Added `getConnectionSnapshot()` on runtime and platform wrappers for one-call connection/activity snapshot (`connected`, pending counts, subscription counts, idle/busy flags).",
"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"
},
"companion-runtime-cancel-pending-event-waits": {
"status": "completed",
"date": "2026-02-17",
+1
View File
@@ -15,6 +15,7 @@ export type {
WaitForIdleOptions,
PendingWorkSnapshot,
EventSurfaceSnapshot,
ConnectionSnapshot,
CompanionEventHandler,
CompanionTypedEventHandler,
CompanionEventName,
+28
View File
@@ -37,6 +37,7 @@ function createRuntimeMock(): {
waitForIdle: ReturnType<typeof vi.fn>;
getPendingWorkSnapshot: ReturnType<typeof vi.fn>;
getEventSurfaceSnapshot: ReturnType<typeof vi.fn>;
getConnectionSnapshot: ReturnType<typeof vi.fn>;
waitForAgentStream: ReturnType<typeof vi.fn>;
waitForAgentTyping: ReturnType<typeof vi.fn>;
waitForContextWarning: ReturnType<typeof vi.fn>;
@@ -92,6 +93,14 @@ function createRuntimeMock(): {
eventSubscriptionCount: 3,
pendingEventWaitCount: 1,
}));
const getConnectionSnapshot = vi.fn(() => ({
connected: true,
eventSubscriptionCount: 3,
pendingRequestCount: 2,
pendingEventWaitCount: 1,
hasPendingWork: true,
idle: false,
}));
const waitForAgentStream = vi.fn(async () => ({ token: 'streamed' }));
const waitForAgentTyping = vi.fn(async () => ({ active: true }));
const waitForContextWarning = vi.fn(async () => ({ thresholdPct: 75, estimatedPct: 90 }));
@@ -133,6 +142,7 @@ function createRuntimeMock(): {
waitForIdle,
getPendingWorkSnapshot,
getEventSurfaceSnapshot,
getConnectionSnapshot,
waitForAgentStream,
waitForAgentTyping,
waitForContextWarning,
@@ -188,6 +198,7 @@ function createRuntimeMock(): {
waitForIdle,
getPendingWorkSnapshot,
getEventSurfaceSnapshot,
getConnectionSnapshot,
waitForAgentStream,
waitForAgentTyping,
waitForContextWarning,
@@ -417,6 +428,23 @@ describe('platform companion clients', () => {
});
});
it('platform getConnectionSnapshot forwards to runtime client', async () => {
const mock = createRuntimeMock();
const client = new IOSCompanionClient({ runtime: mock.runtime, nodeId: 'ios-node' });
const snapshot = client.getConnectionSnapshot();
expect(mock.getConnectionSnapshot).toHaveBeenCalledOnce();
expect(snapshot).toEqual({
connected: true,
eventSubscriptionCount: 3,
pendingRequestCount: 2,
pendingEventWaitCount: 1,
hasPendingWork: true,
idle: false,
});
});
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
@@ -2,6 +2,7 @@ import type {
CompanionEventName,
CompanionEventEnvelope,
EventSurfaceSnapshot,
ConnectionSnapshot,
CompanionEventHandler,
CanvasClearResult,
CanvasDeleteResult,
@@ -306,6 +307,10 @@ export class MacOSCompanionClient {
return this.runtime.getEventSurfaceSnapshot();
}
getConnectionSnapshot(): ConnectionSnapshot {
return this.runtime.getConnectionSnapshot();
}
waitForAnyEvent<TData = unknown>(
eventNames: readonly (CompanionEventName | string)[],
options?: {
@@ -580,6 +585,10 @@ export class IOSCompanionClient {
return this.runtime.getEventSurfaceSnapshot();
}
getConnectionSnapshot(): ConnectionSnapshot {
return this.runtime.getConnectionSnapshot();
}
waitForAnyEvent<TData = unknown>(
eventNames: readonly (CompanionEventName | string)[],
options?: {
@@ -852,6 +861,10 @@ export class AndroidCompanionClient {
return this.runtime.getEventSurfaceSnapshot();
}
getConnectionSnapshot(): ConnectionSnapshot {
return this.runtime.getConnectionSnapshot();
}
waitForAnyEvent<TData = unknown>(
eventNames: readonly (CompanionEventName | string)[],
options?: {
+27
View File
@@ -721,6 +721,33 @@ describe('CompanionRuntimeClient', () => {
await pendingWait;
});
it('returns connection snapshot', async () => {
const client = new CompanionRuntimeClient({
url: 'ws://127.0.0.1:1',
});
const pendingWait = client.waitForEvent('agent.stream', { timeoutMs: 10_000 }).catch(() => undefined);
expect(client.getConnectionSnapshot()).toEqual({
connected: false,
eventSubscriptionCount: 1,
pendingRequestCount: 0,
pendingEventWaitCount: 1,
hasPendingWork: true,
idle: false,
});
client.clearEventSubscriptions();
await pendingWait;
expect(client.getConnectionSnapshot()).toEqual({
connected: false,
eventSubscriptionCount: 0,
pendingRequestCount: 0,
pendingEventWaitCount: 0,
hasPendingWork: false,
idle: true,
});
});
it('waitForIdle resolves immediately when no work is pending', async () => {
const client = new CompanionRuntimeClient({
url: 'ws://127.0.0.1:1',
+20
View File
@@ -59,6 +59,15 @@ export interface EventSurfaceSnapshot {
pendingEventWaitCount: number;
}
export interface ConnectionSnapshot {
connected: boolean;
eventSubscriptionCount: number;
pendingRequestCount: number;
pendingEventWaitCount: number;
hasPendingWork: boolean;
idle: 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;
@@ -352,6 +361,17 @@ export class CompanionRuntimeClient {
};
}
getConnectionSnapshot(): ConnectionSnapshot {
return {
connected: this.connected,
eventSubscriptionCount: this.eventSubscriptionCount,
pendingRequestCount: this.pendingRequestCount,
pendingEventWaitCount: this.pendingEventWaitCount,
hasPendingWork: this.hasPendingWork,
idle: this.idle,
};
}
async connect(): Promise<void> {
if (this.connected) {
return;