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.

4.3 KB
Raw Blame
import { isTailscaleEndpoint } from '../../../src/shared/remote-runtime/remote-runtime-tailscale-hint'
import { clampUtf8TextPrefix } from '../../../src/shared/utf8-byte-limits'
import type {
  ConnectionLogEntry,
  ConnectionState,
  MobileConnectionDiagnosticPath
} from '../transport/types'
import { normalizeHostAppVersion } from '../transport/host-app-version'
import { formatEndpoint } from './host-reachability'
import { diagnoseConnection } from './connection-diagnostics-analysis'
import { redactConnectionLogEntry, redactConnectionLogText } from './connection-log-redaction'

const MAX_EVENT_LINE_BYTES = 2 * 1024
const EVENT_TRUNCATION_MARKER = ' … [truncated]'

// Include endpoints, connection state, attempts, versions and lifecycle history in one shareable report.
export function buildConnectionDiagnosticsReport(args: {
  hostName: string
  endpoint: string
  state: ConnectionState
  reconnectAttempts: number
  lastConnectedAt: number | null
  platform: string
  appVersion: string
  desktopAppVersion?: string | null
  entries: readonly ConnectionLogEntry[]
  activePath?: MobileConnectionDiagnosticPath
  pendingPath?: MobileConnectionDiagnosticPath | null
  bridgeProtocolVersion: number
  nowMs?: number
}): string {
  const now = args.nowMs ?? Date.now()
  const entries = args.entries.map(redactConnectionLogEntry)
  const diagnosis = diagnoseConnection({
    endpoint: args.endpoint,
    state: args.state,
    activePath: args.activePath,
    pendingPath: args.pendingPath,
    entries
  })
  const lines: string[] = []
  lines.push('Orca Mobile connection diagnostics')
  lines.push(`Generated: ${new Date(now).toISOString()}`)
  lines.push(`App: Orca Mobile ${args.appVersion} · ${args.platform}`)
  lines.push(`Bridge protocol: ${args.bridgeProtocolVersion}`)
  const desktopAppVersion =
    args.state === 'connected' ? normalizeHostAppVersion(args.desktopAppVersion) : null
  lines.push(
    `Host Orca version: ${desktopAppVersion ?? (args.state === 'connected' ? 'unknown' : 'unknown (not currently connected)')}`
  )
  lines.push(`Host: ${redactConnectionLogText(args.hostName)}`)
  lines.push(
    `Endpoint: ${formatEndpoint(args.endpoint)}${isTailscaleEndpoint(args.endpoint) ? ' (Tailscale)' : ''}`
  )
  lines.push(`State: ${args.state} (reconnect attempts: ${args.reconnectAttempts})`)
  if (args.activePath) {
    lines.push(
      `Path: active=${args.activePath}${args.pendingPath ? `; recovery=${args.pendingPath}` : ''}`
    )
  }
  lines.push(
    args.lastConnectedAt == null
      ? 'Last connected: never this session'
      : `Last connected: ${new Date(args.lastConnectedAt).toISOString()} (${formatAgo(now - args.lastConnectedAt)} ago)`
  )
  lines.push('')
  lines.push(`Likely cause: ${diagnosis.likelyCause}`)
  lines.push(`Next step: ${diagnosis.nextStep}`)
  lines.push('')
  lines.push(formatConnectionLogHistory(entries))
  return lines.join('\n')
}

export function formatConnectionLogHistory(entries: readonly ConnectionLogEntry[]): string {
  const lines: string[] = []
  if (entries.length === 0) {
    lines.push('No connection events recorded.')
  } else {
    lines.push(`Recent connection history (${entries.length} events, oldest first):`)
    for (const rawEntry of entries) {
      const entry = redactConnectionLogEntry(rawEntry)
      const detail = entry.detail ? ` — ${entry.detail}` : ''
      const evidence = [entry.code, entry.path].filter(Boolean).join(' · ')
      lines.push(
        truncateUtf8WithMarker(
          `${new Date(entry.ts).toISOString()} [${entry.level}]${evidence ? ` [${evidence}]` : ''} ${entry.message}${detail}`,
          MAX_EVENT_LINE_BYTES,
          EVENT_TRUNCATION_MARKER
        )
      )
    }
  }
  return lines.join('\n')
}

function truncateUtf8WithMarker(value: string, maxBytes: number, marker: string): string {
  if (new TextEncoder().encode(value).byteLength <= maxBytes) {
    return value
  }
  const markerBytes = new TextEncoder().encode(marker).byteLength
  return `${clampUtf8TextPrefix(value, maxBytes - markerBytes)}${marker}`
}

function formatAgo(ms: number): string {
  const seconds = Math.max(0, Math.round(ms / 1000))
  if (seconds < 60) {
    return `${seconds}s`
  }
  const minutes = Math.floor(seconds / 60)
  if (minutes < 60) {
    return `${minutes}m ${seconds % 60}s`
  }
  const hours = Math.floor(minutes / 60)
  return `${hours}h ${minutes % 60}m`
}