feat(companion): add cancellable pending event wait helper

This commit is contained in:
William Valentin
2026-02-16 22:18:17 -08:00
parent c41332a643
commit c4a8d099d6
6 changed files with 69 additions and 2 deletions
+2 -2
View File
@@ -1190,7 +1190,7 @@ Methods:
- `system.capabilities` returns gateway protocol and node policy snapshot. - `system.capabilities` returns gateway protocol and node policy snapshot.
Companion runtime helper: 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()`, `listKnownEventNames()`, `eventSubscriptionCount`) plus in-flight observability via `pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `idle`, and `getPendingWorkSnapshot()`. - `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()`, `listKnownEventNames()`, `eventSubscriptionCount`) plus in-flight observability via `pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `idle`, and `getPendingWorkSnapshot()`.
- `src/companion/platformClients.ts` provides platform-focused wrappers: - `src/companion/platformClients.ts` provides platform-focused wrappers:
- `MacOSCompanionClient` (`platform: "macos"`, APNs push registration) - `MacOSCompanionClient` (`platform: "macos"`, APNs push registration)
- `IOSCompanionClient` (`platform: "ios"`, APNs push registration) - `IOSCompanionClient` (`platform: "ios"`, APNs push registration)
@@ -1200,7 +1200,7 @@ Companion runtime helper:
- `createHeartbeatLoop()` convenience helper that returns a bound `CompanionHeartbeatLoop` - `createHeartbeatLoop()` convenience helper that returns a bound `CompanionHeartbeatLoop`
- optional `defaultSessionId` for canvas helper calls so `sessionId` can be omitted per call - optional `defaultSessionId` for canvas helper calls so `sessionId` can be omitted per call
- lifecycle passthroughs for connection state/teardown (`connected`, `dispose(code?, reason?)`) - 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`) - 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()`, `connected`, `waitForIdle()`) - runtime observability/control passthroughs (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `idle`, `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. - `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.
+15
View File
@@ -1040,6 +1040,21 @@
], ],
"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" "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",
"updated": "2026-02-17",
"summary": "Added `cancelPendingEventWaits()` on runtime and platform wrappers so pending waiters can be cancelled without clearing active event subscriptions.",
"files_modified": [
"src/companion/runtimeClient.ts",
"src/companion/runtimeClient.test.ts",
"src/companion/platformClients.ts",
"src/companion/platformClients.test.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": { "browser-tools-activation-clarity": {
"status": "completed", "status": "completed",
"date": "2026-02-17", "date": "2026-02-17",
+13
View File
@@ -31,6 +31,7 @@ function createRuntimeMock(): {
subscribeEvents: ReturnType<typeof vi.fn>; subscribeEvents: ReturnType<typeof vi.fn>;
subscribeEvent: ReturnType<typeof vi.fn>; subscribeEvent: ReturnType<typeof vi.fn>;
clearEventSubscriptions: ReturnType<typeof vi.fn>; clearEventSubscriptions: ReturnType<typeof vi.fn>;
cancelPendingEventWaits: ReturnType<typeof vi.fn>;
listKnownEventNames: ReturnType<typeof vi.fn>; listKnownEventNames: ReturnType<typeof vi.fn>;
waitForEvent: ReturnType<typeof vi.fn>; waitForEvent: ReturnType<typeof vi.fn>;
waitForIdle: ReturnType<typeof vi.fn>; waitForIdle: ReturnType<typeof vi.fn>;
@@ -76,6 +77,7 @@ function createRuntimeMock(): {
const subscribeEvents = vi.fn(() => () => undefined); const subscribeEvents = vi.fn(() => () => undefined);
const subscribeEvent = vi.fn(() => () => undefined); const subscribeEvent = vi.fn(() => () => undefined);
const clearEventSubscriptions = vi.fn(() => undefined); const clearEventSubscriptions = vi.fn(() => undefined);
const cancelPendingEventWaits = vi.fn(() => undefined);
const listKnownEventNames = vi.fn(() => ['agent.stream', 'agent.typing', 'context_warning']); const listKnownEventNames = vi.fn(() => ['agent.stream', 'agent.typing', 'context_warning']);
const waitForEvent = vi.fn(async () => ({ token: 'evented' })); const waitForEvent = vi.fn(async () => ({ token: 'evented' }));
const waitForIdle = vi.fn(async () => undefined); const waitForIdle = vi.fn(async () => undefined);
@@ -119,6 +121,7 @@ function createRuntimeMock(): {
subscribeEvents, subscribeEvents,
subscribeEvent, subscribeEvent,
clearEventSubscriptions, clearEventSubscriptions,
cancelPendingEventWaits,
listKnownEventNames, listKnownEventNames,
waitForEvent, waitForEvent,
waitForIdle, waitForIdle,
@@ -172,6 +175,7 @@ function createRuntimeMock(): {
subscribeEvents, subscribeEvents,
subscribeEvent, subscribeEvent,
clearEventSubscriptions, clearEventSubscriptions,
cancelPendingEventWaits,
listKnownEventNames, listKnownEventNames,
waitForEvent, waitForEvent,
waitForIdle, waitForIdle,
@@ -313,6 +317,15 @@ describe('platform companion clients', () => {
expect(mock.clearEventSubscriptions).toHaveBeenCalledOnce(); expect(mock.clearEventSubscriptions).toHaveBeenCalledOnce();
}); });
it('platform cancelPendingEventWaits forwards to runtime client', async () => {
const mock = createRuntimeMock();
const client = new IOSCompanionClient({ runtime: mock.runtime, nodeId: 'ios-node' });
client.cancelPendingEventWaits('manual');
expect(mock.cancelPendingEventWaits).toHaveBeenCalledWith('manual');
});
it('platform listKnownEventNames forwards to runtime client', async () => { it('platform listKnownEventNames forwards to runtime client', async () => {
const mock = createRuntimeMock(); const mock = createRuntimeMock();
const client = new IOSCompanionClient({ runtime: mock.runtime, nodeId: 'ios-node' }); const client = new IOSCompanionClient({ runtime: mock.runtime, nodeId: 'ios-node' });
+12
View File
@@ -269,6 +269,10 @@ export class MacOSCompanionClient {
this.runtime.clearEventSubscriptions(); this.runtime.clearEventSubscriptions();
} }
cancelPendingEventWaits(reason?: string): void {
this.runtime.cancelPendingEventWaits(reason);
}
listKnownEventNames(): CompanionEventName[] { listKnownEventNames(): CompanionEventName[] {
return this.runtime.listKnownEventNames(); return this.runtime.listKnownEventNames();
} }
@@ -535,6 +539,10 @@ export class IOSCompanionClient {
this.runtime.clearEventSubscriptions(); this.runtime.clearEventSubscriptions();
} }
cancelPendingEventWaits(reason?: string): void {
this.runtime.cancelPendingEventWaits(reason);
}
listKnownEventNames(): CompanionEventName[] { listKnownEventNames(): CompanionEventName[] {
return this.runtime.listKnownEventNames(); return this.runtime.listKnownEventNames();
} }
@@ -799,6 +807,10 @@ export class AndroidCompanionClient {
this.runtime.clearEventSubscriptions(); this.runtime.clearEventSubscriptions();
} }
cancelPendingEventWaits(reason?: string): void {
this.runtime.cancelPendingEventWaits(reason);
}
listKnownEventNames(): CompanionEventName[] { listKnownEventNames(): CompanionEventName[] {
return this.runtime.listKnownEventNames(); return this.runtime.listKnownEventNames();
} }
+23
View File
@@ -389,6 +389,29 @@ describe('CompanionRuntimeClient', () => {
await awaited; await awaited;
}); });
it('cancelPendingEventWaits rejects waiters without clearing subscriptions', async () => {
const client = new CompanionRuntimeClient({
url: 'ws://127.0.0.1:1',
});
const handler = vi.fn();
client.subscribeEvents(handler);
const awaited = expect(
client.waitForEvent('agent.stream', { timeoutMs: 10_000 }),
).rejects.toThrow('manually cancelled');
client.cancelPendingEventWaits('manually cancelled');
await awaited;
(client as unknown as { handleMessage: (raw: string) => void }).handleMessage(
JSON.stringify({
id: 99,
event: 'agent.stream',
data: { token: 'still-subscribed' },
}),
);
expect(handler).toHaveBeenCalledWith('agent.stream', { token: 'still-subscribed' });
});
it('waitForEvent rejects immediately on disconnect', async () => { it('waitForEvent rejects immediately on disconnect', async () => {
const client = new CompanionRuntimeClient({ const client = new CompanionRuntimeClient({
url: 'ws://127.0.0.1:1', url: 'ws://127.0.0.1:1',
+4
View File
@@ -435,6 +435,10 @@ export class CompanionRuntimeClient {
this.rejectEventWaits(new Error('Event subscriptions cleared')); this.rejectEventWaits(new Error('Event subscriptions cleared'));
} }
cancelPendingEventWaits(reason = 'Event waits cancelled'): void {
this.rejectEventWaits(new Error(reason));
}
subscribeEvent<TData = unknown>( subscribeEvent<TData = unknown>(
eventName: CompanionEventName | string, eventName: CompanionEventName | string,
handler: CompanionTypedEventHandler<TData>, handler: CompanionTypedEventHandler<TData>,