# All files / src/trpc subscriptions.ts

15.9% Statements 7/44
0% Branches 0/10
0% Functions 0/7
16.66% Lines 7/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219

    11x

    11x

    11x

    11x

    11x

    11x

    11x

     /**
     * tRPC Subscription Helpers
     *
     * Bridges EventBus domain events into tRPC async generator subscriptions.
     * Uses a queue-based approach: EventBus handlers push events into a queue,
     * the async generator yields from the queue, and waits on a promise when empty.
     */

    import { tracked, type TrackedEnvelope } from '@trpc/server';
    import type { EventBus, DomainEvent, DomainEventType } from '../events/types.js';

    /**
     * Shape of events yielded by subscription procedures.
     */
    export interface SubscriptionEventData {
      id: string;
      type: string;
      payload: unknown;
      timestamp: string;
    }

    /**
     * All domain event types in the system.
     */
    export const ALL_EVENT_TYPES: DomainEventType[] = [
      'process:spawned',
      'process:stopped',
      'process:crashed',
      'server:started',
      'server:stopped',
      'log:entry',
      'worktree:created',
      'worktree:removed',
      'worktree:merged',
      'worktree:conflict',
      'agent:spawned',
      'agent:stopped',
      'agent:crashed',
      'agent:resumed',
      'agent:account_switched',
      'agent:deleted',
      'agent:waiting',
      'agent:output',
      'task:queued',
      'task:dispatched',
      'task:completed',
      'task:blocked',
      'phase:queued',
      'phase:started',
      'phase:completed',
      'phase:blocked',
      'phase:pending_review',
      'phase:merged',
      'task:merged',
      'merge:queued',
      'merge:started',
      'merge:completed',
      'merge:conflicted',
      'page:created',
      'page:updated',
      'page:deleted',
      'changeset:created',
      'changeset:reverted',
      'conversation:created',
      'conversation:answered',
    ];

    /**
     * Agent-specific event types.
     */
    export const AGENT_EVENT_TYPES: DomainEventType[] = [
      'agent:spawned',
      'agent:stopped',
      'agent:crashed',
      'agent:resumed',
      'agent:account_switched',
      'agent:deleted',
      'agent:waiting',
      'agent:output',
    ];

    /**
     * Task and phase event types.
     */
    export const TASK_EVENT_TYPES: DomainEventType[] = [
      'task:queued',
      'task:dispatched',
      'task:completed',
      'task:blocked',
      'task:merged',
      'phase:queued',
      'phase:started',
      'phase:completed',
      'phase:blocked',
      'phase:pending_review',
      'phase:merged',
    ];

    /**
     * Page event types.
     */
    export const PAGE_EVENT_TYPES: DomainEventType[] = [
      'page:created',
      'page:updated',
      'page:deleted',
    ];

    /** Counter for generating unique event IDs */
    let eventCounter = 0;

    /** Drop oldest events when the queue exceeds this size */
    const MAX_QUEUE_SIZE = 1000;

    /** Yield a synthetic heartbeat after this many ms of silence */
    const HEARTBEAT_INTERVAL_MS = 30_000;

    /**
     * Creates an async generator that bridges EventBus events into a pull-based stream.
     *
     * Uses a queue + deferred promise pattern:
     * - EventBus handlers push events into a queue array
     * - The async generator yields from the queue
     * - When the queue is empty, it waits on a promise that resolves when the next event arrives
     * - Cleans up handlers on AbortSignal abort
     *
     * Bounded queue: events beyond MAX_QUEUE_SIZE are dropped (oldest first).
     * Heartbeat: a synthetic `__heartbeat__` event is yielded when no real events
     * arrive within HEARTBEAT_INTERVAL_MS, allowing clients to detect silent disconnects.
     *
     * Each yielded event is wrapped with `tracked(id, data)` to enable client-side reconnection.
     *
     * @param eventBus - The EventBus to subscribe to
     * @param eventTypes - Array of event type strings to listen for
     * @param signal - AbortSignal to cancel the subscription
     */
    export async function* eventBusIterable(
      eventBus: EventBus,
      eventTypes: DomainEventType[],
      signal: AbortSignal,
    ): AsyncGenerator<TrackedEnvelope<SubscriptionEventData>> {
      const queue: DomainEvent[] = [];
      let resolve: (() => void) | null = null;

      // Handler that pushes events into the queue and resolves the waiter
      const handler = (event: DomainEvent) => {
        queue.push(event);
        // Drop oldest when queue overflows
        while (queue.length > MAX_QUEUE_SIZE) {
          queue.shift();
        }
        if (resolve) {
          const r = resolve;
          resolve = null;
          r();
        }
      };

      // Subscribe to all requested event types
      for (const eventType of eventTypes) {
        eventBus.on(eventType as DomainEvent['type'], handler);
      }

      // Cleanup function
      const cleanup = () => {
        for (const eventType of eventTypes) {
          eventBus.off(eventType as DomainEvent['type'], handler);
        }
        // Resolve any pending waiter so the generator can exit
        if (resolve) {
          const r = resolve;
          resolve = null;
          r();
        }
      };

      // Clean up when the client disconnects
      signal.addEventListener('abort', cleanup, { once: true });

      try {
        while (!signal.aborted) {
          // Drain the queue
          while (queue.length > 0) {
            const event = queue.shift()!;
            const id = `${Date.now()}-${eventCounter++}`;
            const data: SubscriptionEventData = {
              id,
              type: event.type,
              payload: event.payload,
              timestamp: event.timestamp.toISOString(),
            };
            yield tracked(id, data);
          }

          // Wait for the next event, abort, or heartbeat timeout
          if (!signal.aborted) {
            const gotEvent = await Promise.race([
              new Promise<true>((r) => {
                resolve = () => r(true);
              }),
              new Promise<false>((r) => setTimeout(() => r(false), HEARTBEAT_INTERVAL_MS)),
            ]);

            if (!gotEvent && !signal.aborted) {
              // No real event arrived — yield heartbeat
              const id = `${Date.now()}-${eventCounter++}`;
              yield tracked(id, {
                id,
                type: '__heartbeat__',
                payload: null,
                timestamp: new Date().toISOString(),
              });
            }
          }
        }
      } finally {
        cleanup();
      }
    }