Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

10.0 KB
Raw Blame
import {
  decodeBrowserScreencastFrame,
  type BrowserScreencastFrame
} from './browser-screencast-protocol'
import {
  buildRequestStreamUnsubscribe,
  updateTerminalSubscriptionViewport
} from './rpc-client-terminal-subscription'
import { buildReadyStreamUnsubscribe, isReadyIdStream } from './rpc-client-server-subscription'
import { isStreamingOpenerReply } from './rpc-acceptance-policies'
import {
  isStreamEndResult,
  isStreamingSubscriptionReadyResult,
  isTerminalSubscribedResult
} from './rpc-subscription-result-shapes'
import { RpcClientTerminalStreamRouter } from './rpc-client-terminal-stream-router'
import * as sessionTabsStream from './rpc-client-session-tabs-stream'
import type { RpcEnvelopeFields, RpcRequestFrame } from './rpc-envelope-fields'
import type { ConnectionState, RpcResponse, RpcSuccess } from './types'
import { translate } from '../i18n/mobile-i18n'

export type RpcStreamingListener = (result: unknown) => void

export type RpcStreamSubscribeOptions = {
  onBinaryFrame?: (frame: BrowserScreencastFrame) => void
  envelope?: RpcEnvelopeFields
}

type StreamRequest = {
  method: string
  params: unknown
  envelope?: RpcEnvelopeFields
  listener?: RpcStreamingListener
  onBinaryFrame?: (frame: BrowserScreencastFrame) => void
  subscriptionId?: string
  cancelled?: boolean
  sent?: boolean
  receivedSnapshot?: boolean
}

type StreamRegistryOptions = {
  nextId: () => string
  getState: () => ConnectionState
  sendFrame: (frame: RpcRequestFrame) => boolean
}

export class RpcClientStreamRegistry {
  private readonly streams = new Map<string, StreamRequest>()
  private readonly terminalRouter = new RpcClientTerminalStreamRouter()
  private activeBrowserRequestId: string | null = null
  private pendingBrowserRequestId: string | null = null

  constructor(private readonly options: StreamRegistryOptions) {}

  subscribe(
    method: string,
    params: unknown,
    listener: RpcStreamingListener,
    subscribeOptions?: RpcStreamSubscribeOptions
  ): () => void {
    const id = this.options.nextId()
    const stream: StreamRequest = {
      method,
      params,
      envelope: subscribeOptions?.envelope,
      listener,
      onBinaryFrame: subscribeOptions?.onBinaryFrame
    }
    this.streams.set(id, stream)
    if (method === 'browser.screencast') {
      this.replaceBrowserStream(id)
    }
    if (this.options.getState() === 'connected') {
      if (this.send(id, stream)) {
        stream.sent = true
      } else {
        this.finish(id, stream, {
          type: 'error',
          message: translate(
            'connection.rpcClientStreamRegistry.interrupted',
            'Connection interrupted'
          )
        })
      }
    } else {
      console.log('[net] subscribe queued — waiting for connected', {
        method,
        state: this.options.getState()
      })
    }
    return () => this.dispose(id)
  }

  replayAfterAuthentication(): void {
    for (const [id, stream] of this.streams) {
      if (stream.cancelled) {
        this.remove(id)
        continue
      }
      if (stream.sent) {
        continue
      }
      if (stream.method === 'browser.screencast') {
        this.pendingBrowserRequestId = id
        this.activeBrowserRequestId = null
      }
      this.resetTerminalRouting(id)
      if (this.send(id, stream)) {
        stream.sent = true
      } else {
        this.markForReplay()
        break
      }
    }
  }

  markForReplay(): void {
    this.activeBrowserRequestId = null
    this.pendingBrowserRequestId = null
    for (const [id, stream] of this.streams) {
      stream.sent = false
      stream.receivedSnapshot = false
      // The id named a registration on the closed socket; the replay's ready brings the new one.
      stream.subscriptionId = undefined
      this.resetTerminalRouting(id)
    }
  }

  handleResponse(response: RpcResponse): boolean {
    if (isStreamingOpenerReply(response)) {
      this.handleStreamingResponse(response)
      return true
    }
    const stream = this.streams.get(response.id)
    if (response.ok) {
      const result = (response as RpcSuccess).result as Record<string, unknown> | null
      if (stream && isStreamEndResult(result)) {
        this.finish(response.id, stream, result)
        return true
      }
      if (stream && result?.type === 'scrollback') {
        stream.listener?.(result)
        return true
      }
    }
    if (!stream) {
      return false
    }
    this.finish(response.id, stream, {
      type: 'error',
      message: response.ok
        ? translate(
            'connection.rpcClientStreamRegistry.endedBeforeReady',
            'Streaming request ended before it was ready.'
          )
        : response.error.message,
      error: response.ok ? undefined : response.error
    })
    return true
  }

  handleBinary(bytes: Uint8Array): void {
    const browserFrame = decodeBrowserScreencastFrame(bytes)
    if (browserFrame) {
      this.handleBrowserFrame(browserFrame)
      return
    }
    this.terminalRouter.handle(bytes)
  }

  updateTerminalViewport(terminal: string, viewport: { cols: number; rows: number }): void {
    updateTerminalSubscriptionViewport(this.streams.values(), terminal, viewport)
  }

  size(): number {
    return this.streams.size
  }

  private handleStreamingResponse(response: RpcSuccess): void {
    const stream = this.streams.get(response.id)
    if (!stream) {
      return
    }
    const result = response.result
    if (isStreamEndResult(result)) {
      this.finish(response.id, stream, result)
      return
    }
    if (sessionTabsStream.recordSnapshot(stream, result) && stream.cancelled) {
      this.dispose(response.id)
      return
    }
    if (isStreamingSubscriptionReadyResult(result)) {
      stream.subscriptionId = result.subscriptionId
      if (stream.cancelled) {
        this.sendServerSubscriptionUnsubscribe(stream)
        this.remove(response.id)
        return
      }
      if (stream.method === 'browser.screencast') {
        if (
          this.pendingBrowserRequestId !== response.id &&
          this.activeBrowserRequestId !== response.id
        ) {
          this.sendBrowserUnsubscribe(result.subscriptionId, stream.envelope)
          this.remove(response.id)
          return
        }
        this.pendingBrowserRequestId = null
        this.activeBrowserRequestId = response.id
      }
    }
    if (isTerminalSubscribedResult(result) && stream.listener) {
      this.terminalRouter.register(response.id, result.streamId, stream.listener)
    }
    if (!stream.cancelled) {
      stream.listener?.(result)
    }
  }

  private dispose(id: string): void {
    const stream = this.streams.get(id)
    if (stream) {
      // A canceled opener may never reply; only its host cleanup route must survive.
      stream.listener = undefined
      stream.onBinaryFrame = undefined
    }
    if (stream && isReadyIdStream(stream.method)) {
      if (stream.method === 'browser.screencast') {
        this.clearBrowserRequest(id)
      }
      this.disposeServerSubscription(id, stream)
      return
    }
    if (stream && sessionTabsStream.holdUnsubscribe(stream)) {
      return
    }
    const unsubscribe = buildRequestStreamUnsubscribe(stream?.method, stream?.params, id)
    if (unsubscribe) {
      this.sendRpc(unsubscribe.method, unsubscribe.params, stream?.envelope)
    }
    this.remove(id)
  }

  private replaceBrowserStream(id: string): void {
    if (this.activeBrowserRequestId && this.activeBrowserRequestId !== id) {
      this.dispose(this.activeBrowserRequestId)
    }
    if (this.pendingBrowserRequestId && this.pendingBrowserRequestId !== id) {
      this.dispose(this.pendingBrowserRequestId)
    }
    this.pendingBrowserRequestId = id
    this.activeBrowserRequestId = null
  }

  private disposeServerSubscription(id: string, stream: StreamRequest): void {
    stream.cancelled = true
    if (stream.subscriptionId) {
      this.sendServerSubscriptionUnsubscribe(stream)
      this.remove(id)
    } else if (!stream.sent) {
      this.remove(id)
    }
  }

  private sendServerSubscriptionUnsubscribe(stream: StreamRequest): void {
    if (!stream.subscriptionId) {
      return
    }
    const unsubscribe = buildReadyStreamUnsubscribe(stream.method, stream.subscriptionId)
    if (unsubscribe) {
      this.sendRpc(unsubscribe.method, unsubscribe.params, stream.envelope)
    }
  }

  private sendBrowserUnsubscribe(subscriptionId: string, envelope?: RpcEnvelopeFields): void {
    this.sendRpc('browser.screencast.unsubscribe', { subscriptionId }, envelope)
  }

  // The stream's envelope rides its unsubscribes too: a routing field must reach the same host.
  private sendRpc(method: string, params: unknown, envelope?: RpcEnvelopeFields): boolean {
    return this.options.sendFrame({ id: this.options.nextId(), method, params, envelope })
  }

  private send(id: string, stream: StreamRequest): boolean {
    const { method, params, envelope } = stream
    return this.options.sendFrame({ id, method, params, envelope })
  }

  private remove(id: string): void {
    const stream = this.streams.get(id)
    this.streams.delete(id)
    this.clearBrowserRequest(id)
    this.resetTerminalRouting(id)
    if (stream?.method === 'browser.screencast') {
      stream.cancelled = true
    }
  }

  private clearBrowserRequest(id: string): void {
    if (this.activeBrowserRequestId === id) {
      this.activeBrowserRequestId = null
    }
    if (this.pendingBrowserRequestId === id) {
      this.pendingBrowserRequestId = null
    }
  }

  private resetTerminalRouting(id: string): void {
    this.terminalRouter.reset(id)
  }

  private handleBrowserFrame(frame: BrowserScreencastFrame): void {
    if (!this.activeBrowserRequestId) {
      return
    }
    const stream = this.streams.get(this.activeBrowserRequestId)
    if (!stream || stream.cancelled || stream.method !== 'browser.screencast') {
      return
    }
    stream.onBinaryFrame?.(frame)
  }

  /** Removed first, so neither the listener's dispose nor a replay can name a host-ended stream. */
  private finish(id: string, stream: StreamRequest, result: unknown): void {
    const listener = stream.cancelled ? undefined : stream.listener
    this.remove(id)
    listener?.(result)
  }
}