Skip to content

The agent that grows with you

22.3 KB
Raw Blame
import { randomUuid } from '@hermes/shared'
import type { WebglAddon } from '@xterm/addon-webgl'
import type { Terminal } from '@xterm/xterm'
import { atom, computed, type ReadableAtom } from 'nanostores'

import { readKey, writeKey } from '@/lib/storage'
import { notifyError } from '@/store/notifications'
import { $currentCwd } from '@/store/session'

import { setTerminalTakeover } from '../store'

import { seedAgentTerminalCommand } from './agent-terminal-stream'
import type { TerminalGateway } from './terminal-gateway'

// xterm WebGL terminals that share one glyph atlas (same font/theme/DPR) keep
// per-terminal render models over a SHARED texture. Clearing one terminal's
// atlas (theme switch, tab activation) wipes the shared texture pages, and
// xterm 0.19 never tells the sibling renderers to rebuild their models — so
// their stale cells draw whatever glyphs land in the freed atlas rows: garbled
// text until a resize forces a full refresh. Upstream fixed this in
// xtermjs/xterm.js#6055 (atlas clear bumps the shared page-layout version);
// we stay pinned on 0.19.0, so every terminal that mutates the shared atlas
// must refresh its siblings itself. Registration is the inverse: each xterm
// registers its own redraw+atlas-rebuild and unregisters on dispose.
// Two-phase fan-out: all clears FIRST, then all refreshes. A sequential
// clear+refresh per terminal would let a later clear wipe the atlas that an
// earlier terminal just rebuilt, leaving it with dangling glyph references.
// Splitting the phases guarantees every terminal rebuilds against a clean atlas.
const webglClearFns = new Map<Terminal, () => void>()
const webglRefreshFns = new Map<Terminal, () => void>()

/** Register a terminal's atlas-rebuild+redraw so sibling refreshes reach it.
 *  Returns an unregister function (call on dispose). */
export function registerWebglRefresh(term: Terminal, getWebgl: () => WebglAddon | null): () => void {
  webglClearFns.set(term, () => {
    try {
      getWebgl()?.clearTextureAtlas()
    } catch {
      // WebGL context lost or uninitialized — the DOM fallback has no atlas.
    }
  })
  webglRefreshFns.set(term, () => {
    term.refresh(0, term.rows - 1)
  })

  return () => {
    webglClearFns.delete(term)
    webglRefreshFns.delete(term)
  }
}

let refreshFrame = 0

/** Rebuild the glyph atlas + redraw every live xterm EXCEPT *skipTerm* (when
 *  given). Callers that are about to mutate the shared atlas (clearTextureAtlas)
 *  must fan out so the OTHER terminals sharing it don't keep drawing stale
 *  cells. Coalesced into one frame per tick: a theme switch fires N
 *  per-terminal effects, and fanning out on each would clear+rebuild the atlas
 *  N times over.
 *
 *  Two-phase execution: all atlas clears run first, then all terminal refreshes.
 *  This prevents a later clear from invalidating an earlier terminal's rebuilt
 *  glyph model (GottZ triage, PR #76463).
 *
 *  Skip the caller only when it already clears+redraws itself inline (font
 *  change); theme/activation callers must NOT skip — they need their own atlas
 *  rebuilt too (the theme colors changed / the frame was stale while hidden).
 *  Terminals on a different atlas (different font/theme/DPR) are force-cleared
 *  harmlessly; DOM-fallback terminals aren't registered at all. */
export function redrawAllTerminals(skipTerm?: Terminal): void {
  if (refreshFrame) {
    return
  }

  refreshFrame = requestAnimationFrame(() => {
    refreshFrame = 0

    // Phase 1: clear all atlases first.
    for (const [term, clear] of webglClearFns) {
      if (skipTerm && term === skipTerm) {
        continue
      }

      clear()
    }

    // Phase 2: rebuild render models against the now-clean atlas.
    for (const [term, refresh] of webglRefreshFns) {
      if (skipTerm && term === skipTerm) {
        continue
      }

      refresh()
    }
  })
}

// An OS resume can evict the GPU's glyph textures without ever firing
// 'webglcontextlost' (common on macOS after sleep/wake): every terminal then
// paints from an empty atlas. The main process broadcasts powerMonitor
// 'resume'/'unlock-screen' as 'hermes:power-resume'; rebuild every registered
// terminal's atlas + render model when it arrives. Import-for-side-effect,
// same pattern as store/power.ts.
if (typeof window !== 'undefined') {
  window.hermesDesktop?.onPowerResume?.(() => {
    redrawAllTerminals()
  })
}

/** One in-app terminal tab. `id` is the renderer-side handle (distinct from the
 *  PTY session id the main process mints); each instance owns its own shell. */
export interface TerminalEntry {
  id: string
  /** Display label. `auto` adopts the resolved shell name until the user renames. */
  title: string
  auto: boolean
  /** Working directory, snapshotted once at creation. Terminals live outside
   *  session/project state — the only thing they inherit is this initial cwd
   *  (the project root if opened in one, else the backend's default). Switching
   *  sessions never moves or recreates a terminal; at most it re-SELECTS a tab
   *  already pointed at the session's cwd (see the $currentCwd listener). */
  cwd: string
  /** Last observed working directory of the live shell (tracked via the PTY
   *  cwd probe / OSC 7). Used to reopen the tab where the user last `cd`'d
   *  rather than the original launch dir. User tabs only. */
  restoreCwd?: string
  /** Serialized xterm scrollback from the last session, replayed on relaunch so
   *  the tab reopens with its recent history (VS Code parity). Processes are NOT
   *  revived — a fresh shell starts beneath the restored buffer. Captured live
   *  for user tabs only; agent mirrors stay runtime-only. */
  reviveBuffer?: string
  /** A server shell was created for this tab; restoration must never respawn it. */
  persistent?: boolean
  /** `user` = interactive PTY shell. `agent` = read-only mirror of an agent
   *  background process (`terminal(background=true)`), keyed by `procId`. */
  kind: 'user' | 'agent'
  procId?: string
  /** The gateway this tab was opened on (`local` = This device). The shell
   *  runs on that host whichever gateway the window shows later; absent on a
   *  tab from an older Desktop until its first start reports where it ran. */
  connectionId?: string
  /** Gateway profile the SSH tunnel is keyed by (with `connectionId`). */
  profile?: string
  /** `connectionId` left the registry. Ids are reusable label slugs, so a
   *  gateway added later under the same name is another machine: this tab
   *  never reconnects, even after relaunch. */
  gatewayRemoved?: boolean
}

interface PersistedTerminalEntry {
  auto: boolean
  connectionId?: string
  gatewayRemoved?: boolean
  cwd: string
  id: string
  restoreCwd?: string
  reviveBuffer?: string
  /** A server shell was created for this tab; restoration must never respawn it. */
  persistent?: boolean
  profile?: string
  title: string
}

interface PersistedTerminalState {
  activeTerminalId: null | string
  terminals: PersistedTerminalEntry[]
}

const TERMINALS_STORAGE_KEY = 'hermes.desktop.terminals.v1'

// Cap a single tab's replayed history so the persisted layout can't blow the
// localStorage quota. Roughly mirrors VS Code's persistentSessionScrollback
// default (100 lines) once the serialized escape codes are counted in.
const MAX_REVIVE_BUFFER_CHARS = 48_000

function persistedGateway(record: Record<string, unknown>): Pick<PersistedTerminalEntry, 'connectionId' | 'profile'> {
  const connectionId = typeof record.connectionId === 'string' ? record.connectionId.trim() : ''
  const profile = typeof record.profile === 'string' ? record.profile.trim() : ''

  return connectionId ? { connectionId, ...(profile ? { profile } : {}) } : {}
}

function sanitizePersistedTerminal(value: unknown): PersistedTerminalEntry | null {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    return null
  }

  const record = value as Record<string, unknown>
  const id = typeof record.id === 'string' ? record.id.trim() : ''
  const title = typeof record.title === 'string' ? record.title.trim() : ''
  const cwd = typeof record.cwd === 'string' ? record.cwd : ''
  const restoreCwd = typeof record.restoreCwd === 'string' && record.restoreCwd ? record.restoreCwd : undefined
  const reviveBuffer = typeof record.reviveBuffer === 'string' ? record.reviveBuffer : undefined

  if (!id) {
    return null
  }

  return {
    auto: typeof record.auto === 'boolean' ? record.auto : true,
    ...persistedGateway(record),
    ...(record.gatewayRemoved === true ? { gatewayRemoved: true } : {}),
    cwd,
    id,
    ...(restoreCwd ? { restoreCwd } : {}),
    ...(reviveBuffer ? { reviveBuffer } : {}),
    ...(record.persistent === true ? { persistent: true } : {}),
    title: title || 'Terminal'
  }
}

function loadPersistedTerminals(): PersistedTerminalState {
  const fallback: PersistedTerminalState = { activeTerminalId: null, terminals: [] }
  const raw = readKey(TERMINALS_STORAGE_KEY)

  if (!raw) {
    return fallback
  }

  try {
    const parsed = JSON.parse(raw) as unknown

    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
      return fallback
    }

    const record = parsed as Record<string, unknown>

    const terminals = Array.isArray(record.terminals)
      ? record.terminals.map(sanitizePersistedTerminal).filter((term): term is PersistedTerminalEntry => Boolean(term))
      : []

    const active =
      typeof record.activeTerminalId === 'string' && terminals.some(term => term.id === record.activeTerminalId)
        ? record.activeTerminalId
        : (terminals[0]?.id ?? null)

    return { activeTerminalId: active, terminals }
  } catch {
    return fallback
  }
}

// Persist synchronously on every change (the app-wide convention — see panes.ts
// / layout.ts). Capturing history this way means a snapshot is already on disk
// well before the renderer tears down, so app quit needs no unload hook.
function persistTerminals(list: readonly TerminalEntry[], activeTerminalId: null | string) {
  const terminals = list
    .filter(term => term.kind === 'user')
    .map(term => ({
      auto: term.auto,
      ...(term.connectionId ? { connectionId: term.connectionId } : {}),
      ...(term.gatewayRemoved ? { gatewayRemoved: true } : {}),
      cwd: term.cwd,
      id: term.id,
      ...(term.profile ? { profile: term.profile } : {}),
      ...(term.restoreCwd ? { restoreCwd: term.restoreCwd } : {}),
      ...(term.reviveBuffer ? { reviveBuffer: term.reviveBuffer } : {}),
      ...(term.persistent ? { persistent: true } : {}),
      title: term.title
    }))

  if (!terminals.length) {
    writeKey(TERMINALS_STORAGE_KEY, null)

    return
  }

  const active = terminals.some(term => term.id === activeTerminalId) ? activeTerminalId : (terminals[0]?.id ?? null)
  writeKey(TERMINALS_STORAGE_KEY, JSON.stringify({ activeTerminalId: active, terminals }))
}

const restored = loadPersistedTerminals()

export const $terminals = atom<readonly TerminalEntry[]>(
  restored.terminals.map(term => ({ ...term, kind: 'user' as const }))
)
export const $activeTerminalId = atom<string | null>(restored.activeTerminalId)

$terminals.subscribe(list => persistTerminals(list, $activeTerminalId.get()))
$activeTerminalId.subscribe(active => persistTerminals($terminals.get(), active))

export const $activeTerminal = computed(
  [$terminals, $activeTerminalId],
  (list, id) => list.find(term => term.id === id) ?? null
)

const newId = () => randomUuid()

// The gateway picked in Sessions, as a shell host. terminal-gateway.ts binds the
// registry-backed store on load; this module stays free of the connection
// stores. Unbound (or with no registry, like the Webapp) there is one host.
let $defaultGateway: ReadableAtom<TerminalGateway | undefined> = atom(undefined)

let unbindDefaultGateway = () => {}

/** Append a fresh terminal and focus it. Captures the current cwd once (its only
 *  tie to session/project state) and the gateway: an explicit one, else the one
 *  picked in Sessions now, so a failed first start can never retry elsewhere.
 *  Returns the id. */
export function createTerminal(cwd: string = $currentCwd.get(), gateway?: TerminalGateway): string {
  const id = newId()
  const owner = gateway ?? $defaultGateway.get()
  $terminals.set([...$terminals.get(), { id, title: 'Terminal', auto: true, cwd, kind: 'user', ...owner }])
  $activeTerminalId.set(id)

  return id
}

/** Record where a tab that had no gateway first ran. A recorded gateway never
 *  changes: a later Sessions pick must not move a shell to another host. */
export function adoptTerminalGateway(id: string, gateway: TerminalGateway): void {
  $terminals.set(
    $terminals.get().map(term =>
      term.id === id && term.kind === 'user' && !term.connectionId ? { ...term, ...gateway } : term
    )
  )
}

/** Mark tabs whose gateway is no longer registered. Sticky: see `gatewayRemoved`. */
export function forgetRemovedTerminalGateways(registered: ReadonlySet<string>): void {
  const list = $terminals.get()

  const gone = (term: TerminalEntry) =>
    term.kind === 'user' && Boolean(term.connectionId) && !term.gatewayRemoved && !registered.has(term.connectionId!)

  if (list.some(gone)) {
    $terminals.set(list.map(term => (gone(term) ? { ...term, gatewayRemoved: true } : term)))
  }
}

/** True once user tabs run on more than one host: only then do This device
 *  tabs need a label too. */
export const $terminalHostsMixed = computed(
  $terminals,
  list => new Set(list.filter(term => term.kind === 'user' && term.connectionId).map(term => term.connectionId)).size > 1
)

// Procs we've already surfaced a tab for — so closing an agent tab doesn't
// resurrect it on the next poll while the process is still running.
const surfacedProcs = new Set<string>()

const findByProc = (procId: string) => $terminals.get().find(term => term.procId === procId)

/** Auto-surface an agent background process as a read-only tab — once. Returns
 *  the tab id, or null if it was already surfaced and the user has since closed it. */
export function ensureAgentTerminal(procId: string, title: string): string | null {
  const existing = findByProc(procId)

  if (existing) {
    return existing.id
  }

  if (surfacedProcs.has(procId)) {
    return null
  }

  surfacedProcs.add(procId)
  const id = newId()
  $terminals.set([...$terminals.get(), { id, title: title || 'agent', auto: false, cwd: '', kind: 'agent', procId }])

  return id
}

/** Open + focus an agent process's tab (the status-stack link), recreating it if
 *  the user had closed it. Opens the pane. */
export function openAgentTerminal(procId: string, title: string): void {
  surfacedProcs.add(procId)
  seedAgentTerminalCommand(procId, title)
  let id = findByProc(procId)?.id

  if (!id) {
    id = newId()
    $terminals.set([...$terminals.get(), { id, title: title || 'agent', auto: false, cwd: '', kind: 'agent', procId }])
  }

  $activeTerminalId.set(id)
  setTerminalTakeover(true)
}

/** Guarantee at least one tab exists when the pane opens.
 *  If a status-stack click already opened an agent tab, don't create a
 *  second, unrelated user shell just because the pane became visible. */
export function ensureTerminal(): void {
  if ($terminals.get().length === 0) {
    createTerminal()
  }
}

export function selectTerminal(id: string): void {
  if ($terminals.get().some(term => term.id === id)) {
    $activeTerminalId.set(id)
  }
}

// Compare-ready form of a directory path: trimmed, trailing separators dropped
// (keeping a bare root intact) so `/repo/` and `/repo` are the same place.
const normalizePath = (value: string) => {
  const trimmed = value.trim()

  return trimmed.length > 1 ? trimmed.replace(/[\\/]+$/, '') || trimmed : trimmed
}

/** The directory a tab points at right now — the live shell cwd once observed
 *  (survives a `cd`), else the launch dir. */
const terminalCwd = (term: TerminalEntry) => normalizePath(term.restoreCwd || term.cwd)

// Session ↔ terminal linking. Entering a session whose cwd already has a user
// terminal pointed at it re-selects that tab, so the terminal pane follows the
// workspace you're in. Selection ONLY — it never creates a shell, never closes
// one, and never reveals the pane; a detached session (empty cwd) or a cwd no
// tab lives in leaves the tabs exactly where they were. `listen` (not
// `subscribe`) so boot keeps the persisted active tab.
//
// A path names a directory on one host: `/repo` on the NAS is not `/repo` here,
// so only tabs on the session's gateway (or a fresh tab that has not recorded
// one yet) can match. The link follows the (host, cwd) pair, so picking another
// gateway re-selects even when both hosts report the same path string.
export function bindTerminalDefaultGateway(source: ReadableAtom<TerminalGateway | undefined>): void {
  unbindDefaultGateway()
  $defaultGateway = source
  let host = source.get()?.connectionId

  unbindDefaultGateway = source.listen(gateway => {
    if (gateway?.connectionId !== host) {
      host = gateway?.connectionId
      followSessionCwd($currentCwd.get())
    }
  })
}

function followSessionCwd(cwd: string) {
  const target = normalizePath(cwd)

  if (!target) {
    return
  }

  const host = $defaultGateway.get()?.connectionId

  const linked = (term: TerminalEntry | undefined) =>
    term?.kind === 'user' &&
    terminalCwd(term) === target &&
    !term.gatewayRemoved &&
    (!host || !term.connectionId || term.connectionId === host)

  const list = $terminals.get()

  if (linked(list.find(term => term.id === $activeTerminalId.get()))) {
    return
  }

  const match = list.find(linked)

  if (match) {
    $activeTerminalId.set(match.id)
  }
}

$currentCwd.listen(followSessionCwd)

/** Move the active tab by `direction` (+1 next / -1 prev), wrapping around. */
export function cycleTerminal(direction: 1 | -1): void {
  const list = $terminals.get()

  if (list.length < 2) {
    return
  }

  const current = Math.max(
    0,
    list.findIndex(term => term.id === $activeTerminalId.get())
  )

  $activeTerminalId.set(list[(current + direction + list.length) % list.length].id)
}

const closingTerminals = new Set<string>()

/** Drop a terminal. Focus slides to the neighbor that fills its slot; closing
 *  the last one closes the whole pane. */
export function closeTerminal(id: string): void {
  const entry = $terminals.get().find(term => term.id === id)
  const closeSaved = window.hermesDesktop?.terminal?.closeSaved

  if (entry?.kind !== 'user' || !closeSaved) {
    removeExitedTerminal(id)

    return
  }

  if (closingTerminals.has(id)) {return}
  closingTerminals.add(id)
  // Keep the tab and its resume handle until the server confirms termination.
  void closeSaved(id).then(closed => {
    if (!closed) {throw new Error('Terminal close was not confirmed; retry closing this tab')}
    removeExitedTerminal(id)
  }).catch(error => notifyError(error, 'Could not close terminal')).finally(() => closingTerminals.delete(id))
}

export function removeExitedTerminal(id: string): void {
  const list = $terminals.get()
  const index = list.findIndex(term => term.id === id)

  if (index < 0) {
    return
  }

  const next = list.filter(term => term.id !== id)
  $terminals.set(next)

  if ($activeTerminalId.get() === id) {
    $activeTerminalId.set((next[index] ?? next[index - 1])?.id ?? null)
  }

  if (!next.length) {
    setTerminalTakeover(false)
  }
}

/** Close the read-only agent tab mirroring a background process. The agent
 *  drives this via the desktop-gated `close_terminal` tool → `terminal.close`.
 *  The process is NOT killed — only the view is dropped; `surfacedProcs` keeps
 *  it from auto-resurfacing, and the status-stack row can reopen it on demand.
 *  No-op when no such tab exists. */
export function closeAgentTerminalByProc(procId: string): boolean {
  const term = $terminals.get().find(t => t.kind === 'agent' && t.procId === procId)

  if (!term) {
    return false
  }

  closeTerminal(term.id)

  return true
}

export function closeActiveTerminal(): void {
  const id = $activeTerminalId.get()

  if (id) {
    closeTerminal(id)
  }
}

export function closeAllTerminals(): void {
  $terminals.get().forEach(term => closeTerminal(term.id))
}

export function closeOtherTerminals(id: string): void {
  const keep = $terminals.get().find(term => term.id === id)

  if (keep) {
    $terminals.get().filter(term => term.id !== id).forEach(term => closeTerminal(term.id))
    $activeTerminalId.set(keep.id)
  }
}

/** Server replay replaces renderer-only history once persistence is negotiated. */
export function markTerminalPersistent(id: string): void {
  $terminals.set($terminals.get().map(term =>
    term.id === id ? { ...term, persistent: true, reviveBuffer: undefined } : term
  ))
}

export function updateTerminalReviveBuffer(id: string, reviveBuffer: string): void {
  const terminals = $terminals.get()
  const index = terminals.findIndex(term => term.id === id)
  const term = terminals[index]

  if (!term || term.kind !== 'user' || term.persistent) {
    return
  }

  const capped =
    reviveBuffer.length > MAX_REVIVE_BUFFER_CHARS ? reviveBuffer.slice(-MAX_REVIVE_BUFFER_CHARS) : reviveBuffer

  // Publishing also serializes every user tab and updates workspace subscribers.
  // Stable TUI screens can produce identical snapshots for every capture.
  if (term.reviveBuffer === capped) {
    return
  }

  const next = terminals.slice()
  next[index] = { ...term, reviveBuffer: capped }
  $terminals.set(next)
}

/** Record the shell's latest working directory for a tab so the next launch can
 *  restart the PTY there instead of the original launch dir. User tabs only;
 *  no-ops when the value is empty or unchanged to avoid redundant persistence. */
export function updateTerminalRestoreCwd(id: string, restoreCwd: string): void {
  const next = restoreCwd.trim()

  if (!next) {
    return
  }

  $terminals.set(
    $terminals.get().map(term => {
      if (term.id !== id || term.kind !== 'user' || term.restoreCwd === next) {
        return term
      }

      return { ...term, restoreCwd: next }
    })
  )
}

export function renameTerminal(id: string, title: string): void {
  const trimmed = title.trim()

  $terminals.set(
    $terminals.get().map(term => (term.id === id ? { ...term, title: trimmed || term.title, auto: false } : term))
  )
}

/** A live terminal reports its resolved shell; adopt it as the label only while
 *  the user hasn't named the tab themselves. */
export function reportTerminalShell(id: string, shell: string): void {
  const name = shell.trim()

  if (!name) {
    return
  }

  $terminals.set($terminals.get().map(term => (term.id === id && term.auto ? { ...term, title: name } : term)))
}