Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

42.1 KB
Raw Blame
import { useContextEnsure } from '../../terminal/useContextEnsure'
import { transcriptSessionFor } from '../../lib/transcriptSession'
import { FIND_DECORATIONS } from '../../lib/palette'
import { isLocalOnSshCanvas } from '../../lib/localOnSshCanvas'
import { ptyRefusal } from '@shared/pty-refusal'

import { patchImeModeSwitch } from '../../terminal/ime-mode-switch'
import { patchShrinkTrim } from '../../terminal/shrink-trim'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Terminal } from '@xterm/xterm'
import { FitAddon } from '@xterm/addon-fit'
import { SearchAddon } from '@xterm/addon-search'
import { quantizeCharSize } from '../../terminal/char-size-quantize'
import { reportsOwnCopy } from '@shared/agents/config'
import type { AgentId } from '@shared/agents/config'
import { effectiveAccountId } from '../../lib/accountChip'
import { readsClaudeTranscript } from '../../lib/transcriptGates'
import { liveProjectJumpTarget } from '../../lib/projectJump'
import { terminalChordBubbles, terminalShortcutPolicy } from '../../lib/keybindingOverrides'
import { focusXtermUnlessCovered, useMdModeFocus } from '../../terminal/useMdModeFocus'
import { FindBar } from '../FindBar'
import { useProjects } from '../../state/projects'
import { isRemoteProjectId, useSession, useSessionStores } from '../../session/session'
import { relayStatusGates } from '../../terminal/relay-status-gates'
import { REMOTE_PROJECT_SPAWN_REFUSAL, spawnBelongsElsewhere, useOwningProjectId } from '../../session/owning-project'
import { isHostedReadOnly } from '../../state/hostedTeams'
import { useSettings } from '../../state/settings'
import { isMacPlatform, isWindowsPlatform } from '@shared/platform-utils'
import {
  FONT_ZOOM_NODE_ATTR,
  requestTerminalFontZoom,
  terminalFontZoomAction
} from '../../terminal/terminal-font-zoom'
import { useTerminalSearch } from '../../terminal/useTerminalSearch'
import { useTerminalGlass } from '../../lib/useTerminalGlass'
import { LocalTransport } from '../../terminal/local-transport'
import {
  clipboardImages,
  dropDialect,
  droppedPaths,
  pasteHasText,
  pastedFiles
} from '../../terminal/file-drop'
import { guardMiddleClickPaste } from '../../terminal/middle-click'
import { attachCopyOnSelect } from '../../terminal/copy-on-select'
import {
  cachedCwd,
  createFileLinkProvider,
  createOsc8LinkHandler,
  createUrlLinkProvider,
  fileMissMessage,
  installLinkClickFallback,
  installLinkContextMenu,
  makeDirListingLookup,
  type UnverifiedPath
} from '../../terminal/file-links'
import { isBrowserRuntime } from '../../bridge/runtime'
import { fileLinkDialect } from '../../terminal/file-link-dialect'
import { hostPlatformFor } from '../../terminal/host-platform'
import { sshFs } from '../../terminal/ssh-fs'
import { cardFileLinkRoute } from '../../lib/cardFileLinks'
import { projectSessionSource } from '../../lib/projectSessionSource'
import type { LocalFileTarget } from './LocalFilePreviewModal'
import type { FsApi } from '@shared/types'
import { urlLinkMenuItems } from '../../terminal/link-menu'
import { ContextMenu } from '../ContextMenu'
import { parseOsc52 } from '../../terminal/osc52'
import { createOsc52Notice, dispatchOsc52Toast, handleOsc52Write } from '../../terminal/osc52-policy'
import { activateUnicode11 } from '../../terminal/unicode-width'
import { useCopyFeedback } from '../../terminal/useCopyFeedback'
import { pasteWithImageReceipt } from '../../terminal/image-paste-confirm'
import { usePasteReceipt } from '../../terminal/usePasteReceipt'
import { agentProcessInPane } from '../../terminal/live-work'
import {
  attachReplay,
  cursorPlacementSeq,
  seedPaint,
  stripTrailingNewline,
  terminalKeyAction,
  toXtermText,
  applyLiveOptions,
  xtermOptionsFromSettings,
  SHIFT_ENTER_SEQ,
  CO_ATTACH_MOUSE_SEQ,
  CO_ATTACH_ALT_SCREEN_SEQ
} from '../../terminal/terminal-config'
import { useXtermVisualSettings } from '../../terminal/useXtermVisualSettings'
import {
  nodeUploadScope,
  owningProjectId,
  resolveSshRemote,
  reportSshDrop,
  sshConnectionScope
} from '../../nodes/TerminalNode'
import { buildSshArgs, type SshConnection } from '@shared/ssh'

/** The subset of a node's `data` a SECOND client needs to attach to its session the same way the
 *  canvas TerminalNode does. Canvas fills it from the node's data; sticky/chat cards pass `{}`. */
export interface ModalSpawn {
  shell?: string
  cwd?: string
  agentId?: string
  accountId?: string
  /** The node's `data.ssh` — a local `ssh <host>` node runs ssh as its pty program. */
  ssh?: SshConnection
  /** SSH-project node: tmux runs on the REMOTE host (over the project's ControlMaster). */
  sshRemoteTmux?: boolean
  /** One-shot launch command for a fresh session (agent CLIs). */
  initialCommand?: string
  /** The node's own font size (issue #915, `data.terminalFontSize`). The modal is a second view of
   *  the SAME session, so it renders at the node's size, not the global one — and, being a
   *  co-attach subscriber, re-reports its grid when that changes like any font change. */
  terminalFontSize?: number
  /** The session id the node was launched with (`data.agentSessionId`) — the transcript readers'
   *  fallback when no hook confirmed one (lib/transcriptSession.ts). Never used to spawn. */
  agentSessionId?: string
}

/**
 * A SECOND live client on the node's tmux session, living only while the card modal is open.
 *
 * It rides the viewer-identity seam (Task 2a): a per-mount `viewerId` makes this a distinct
 * subscriber of the SAME session as the canvas node — its create/resize/kill co-attach and detach
 * independently, so opening or closing the modal never disturbs the canvas node's client (live or
 * parked). Deliberately minimal vs. TerminalNode: NO park, NO WebGL budget, NO hover-guard — a modal
 * is short-lived and always on top. Closing kills ONLY this viewer (the last-view release stays with
 * the canvas node). The MIRROR-tagged blocks below are copied byte-for-byte from TerminalNode.
 */
interface ModalTerminalProps {
  nodeId: string
  spawn: ModalSpawn
  /** The modal header's 🔍 toggle — the FindBar renders inside this pane. */
  searchOpen: boolean
  onCloseSearch: () => void
  /**
   * The card modal's ⌘M view (output markdown / ChatPanel) is laid OVER this viewer. It stays
   * mounted underneath — its co-attach is a second pty client whose attach/detach is expensive and
   * must not churn — so it only has to stop holding the keyboard: blur on cover, restore on uncover
   * when it had focus, and never take focus while covered (the async attach below focuses on
   * completion, which a quick ⌘M can precede). Same rules as the canvas node's ⌘M face.
   */
  covered?: boolean
  /** The project this CARD belongs to — not necessarily the active one (the Omni board opens cards
   *  from every project). File links resolve against this project's filesystem; absent = no file
   *  links (see `cardFileLinkRoute`). */
  projectId?: string
  /** A file link was activated: the card modal previews it in its own overlay instead of uncovering
   *  the canvas. Absent = file links are not offered at all. */
  onOpenFile?: (file: LocalFileTarget) => void
}

export function ModalTerminal({
  nodeId,
  spawn,
  searchOpen,
  onCloseSearch,
  covered = false,
  projectId,
  onOpenFile
}: ModalTerminalProps) {
  const session = useSession()
  const { api } = session
  // MIRROR TerminalNode: which status-driven readers this viewer may run (relay-status-gates.ts) —
  // all of them on the local session, none on a relay / team tab, whose status is its host's.
  const gates = relayStatusGates(session.source)
  // The agent status of the session this card's project runs under (mounted through
  // `ProjectSessionScope`), never the default store: a team tab's node shares its id with the
  // handed-off SSH project, whose entry is the default store's.
  const agentStatusStore = useSessionStores().agentStatus.store
  // Read at click time from the lifecycle effect, which runs once per mount.
  const projectIdRef = useRef(projectId)
  projectIdRef.current = projectId
  // MIRROR TerminalNode: the project this viewer's node belongs to, as the board's
  // `ProjectSessionScope` provides it — read by the create path below, which runs once per mount.
  const owningProject = useOwningProjectId()
  const owningProjectRef = useRef(owningProject)
  owningProjectRef.current = owningProject
  const onOpenFileRef = useRef(onOpenFile)
  onOpenFileRef.current = onOpenFile
  // MIRROR TerminalNode: the path dialect belongs to the core that owns the filesystem, never this
  // window's OS. A ref, so resolving it never re-runs the lifecycle effect.
  const corePlatformRef = useRef<string | null>(null)
  useEffect(() => {
    let live = true
    corePlatformRef.current = null
    void hostPlatformFor(api).then((platform) => {
      if (live) corePlatformRef.current = platform
    })
    return () => {
      live = false
    }
  }, [api])
  const hostRef = useRef<HTMLDivElement>(null)
  const middleClickPaste = useSettings((st) => st.settings.terminalMiddleClickPaste)
  // Chromium pastes the X PRIMARY selection into xterm's hidden textarea on middle click — a path
  // this app never built and the user could not switch off (issue #84). Its own effect, keyed on
  // the setting alone, so it applies to a PARKED terminal being re-adopted just as much as to a
  // fresh one: the guard belongs to the host ELEMENT, not to the pty lifecycle.
  useEffect(() => {
    const host = hostRef.current
    if (!host) return
    return guardMiddleClickPaste(host, () => middleClickPaste)
  }, [middleClickPaste])

  const termRef = useRef<Terminal | null>(null)
  const coveredRef = useRef(covered)
  coveredRef.current = covered
  useMdModeFocus(covered, () => termRef.current, () => hostRef.current?.closest('.kanban-modal'), nodeId)
  const searchAddonRef = useRef<SearchAddon | null>(null)
  // The live pty session + its fit addon, reachable from OUTSIDE the lifecycle effect's closure —
  // the appearance effect below has to re-fit and re-REPORT this viewer's grid, and under co-attach
  // a report that never happens leaves the shared pty clamped to the pre-change size.
  const sessionIdRef = useRef<string | null>(null)
  const fitRef = useRef<FitAddon | null>(null)
  const transportRef = useRef<LocalTransport | null>(null)
  const agentSessionId = agentStatusStore((s) => s.byId[nodeId]?.sessionId)
  const observedAgentId = agentStatusStore((s) => s.byId[nodeId]?.agentId)
  // MIRROR TerminalNode: transcript READS go to the account the session is actually running as,
  // which for a plain terminal is only ever the observed one. The spawn below keeps
  // `spawn.accountId` — launch identity stays creation-time.
  const observedAccount = agentStatusStore((s) => s.byId[nodeId]?.account)
  // …resolved against the live account list, so linking the dir repoints the reader at once.
  const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)
  // MIRROR TerminalNode: the meter's rehydration reads the same session the ⌘M view does.
  const transcript = transcriptSessionFor({ live: agentSessionId, persisted: spawn.agentSessionId, cwd: spawn.cwd })
  useContextEnsure(api.context, nodeId, spawn.agentId ?? observedAgentId, transcript.sessionId, transcript.cwd,
    effectiveAccountId(spawn.accountId, observedAccount, claudeAccounts))
  // One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.
  // MIRROR TerminalNode: scoped to the OWNING project (`owningProjectId`, the active one — a modal
  // only ever opens over it), deliberately NOT this card's connection scope. `sshConnectionScope`
  // answers a project×host attachment id for a session on a foreign host, which names no project at
  // all — the per-project appearance would silently vanish for exactly those cards.
  // …and the NODE's own font size (issue #915), so this second view matches the canvas one.
  const visual = useXtermVisualSettings(owningProjectId(), spawn.terminalFontSize)
  // MIRROR TerminalNode: the xterm is BUILT from the effective appearance, not the bare globals.
  const visualRef = useRef(visual)
  visualRef.current = visual
  // Liquid Glass: the same glass as the canvas node (a second view of one session must look like
  // it). The DOM renderer keeps app-painted cell backgrounds opaque (see CLAUDE.md).
  const { glass, vars: glassVars } = useTerminalGlass(visual.terminalTheme, true)
  const glassRef = useRef(glass)
  glassRef.current = glass
  const [dropping, setDropping] = useState(false)
  const [uploading, setUploading] = useState(false)
  const pasteReceipt = usePasteReceipt()
  // Same copy feedback as the canvas node — a copy here is the same act as a copy there, including
  // the agent gate: a claude card stays silent because claude prints its own copy line.
  const copy = useCopyFeedback({
    hostRef,
    hasSelection: () => !!termRef.current?.hasSelection(),
    enabled: !reportsOwnCopy(spawn.agentId as AgentId | undefined)
  })
  // Right-click on a URL → the canvas node's link menu, URL rows only (file rows act on the active
  // project — see the link wiring in the lifecycle effect).
  const [linkMenu, setLinkMenu] = useState<{ x: number; y: number; url: string } | null>(null)

  // Same search machinery as the canvas node: capture-indexed matches + xterm highlight.
  const readBuffer = useCallback((): string => {
    const b = termRef.current?.buffer.active
    if (!b) return ''
    const lines: string[] = []
    for (let i = 0; i < b.length; i++) lines[i] = b.getLine(i)?.translateToString() ?? ''
    return lines.join('\n')
  }, [])
  const search = useTerminalSearch({
    nodeId,
    sessionId: agentSessionId,
    cwd: spawn.cwd,
    accountId: effectiveAccountId(spawn.accountId, observedAccount, claudeAccounts),
    // MIRROR TerminalNode: the transcript index reads claude's JSONL through claude's resolver, so
    // it is gated on the claude-transcript fact, NOT on the context meter's `hasUsage` (which now
    // spans codex and gemini too) — see lib/transcriptGates.ts. And on `gates.transcriptSearch`: it
    // reads THIS machine's transcripts (`window.nodeTerminal.claude`), never a relay host's, and a
    // team tab's card holds the HOST's session id.
    searchTranscript: gates.transcriptSearch && readsClaudeTranscript(spawn.agentId),
    open: searchOpen,
    readBuffer
  })
  // MIRROR TerminalNode's findOpts — one source for the highlight colors.
  const findOpts = {
    decorations: FIND_DECORATIONS
  }
  const handleNext = useCallback(() => {
    search.next()
    if (search.query.trim()) searchAddonRef.current?.findNext(search.query, findOpts)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search])
  const handlePrev = useCallback(() => {
    search.prev()
    if (search.query.trim()) searchAddonRef.current?.findPrevious(search.query, findOpts)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search])

  useEffect(() => {
    // A unique viewerId per mount: the core namespaces it per connection, so uniqueness only has to
    // hold within THIS window. It makes the modal a second subscriber of the node's shared session.
    const viewerId = `modal-${nodeId}-${Math.random().toString(36).slice(2, 8)}`
    const transport = new LocalTransport(api, viewerId)
    const s = useSettings.getState().settings
    // Appearance comes from the SAME source as the canvas node's terminal — this modal is a second
    // view of one session, and a card that renders it in different colours reads as a different
    // terminal. (It used to hardcode its own background, which is exactly what happened.)
    const term = new Terminal(xtermOptionsFromSettings(visualRef.current, glassRef.current))
    // The same read-only rule as the canvas node: a hosted team's Viewer/Commenter never types here.
    if (isHostedReadOnly(session.id)) term.options.disableStdin = true
    // Without a handler xterm answers an OSC 8 click with a window.confirm — the one surface
    // where this session's links would prompt instead of opening like the canvas node's.
    term.options.linkHandler = createOsc8LinkHandler((uri) =>
      window.nodeTerminal.shell.openExternal(uri)
    )
    // The modal is a second view of the SAME tmux session, so it has to measure characters the way
    // the canvas node does. Two views on two width tables would disagree about where the columns
    // are — and the pty runs at the SMALLEST subscriber's grid, so the disagreement would be live.
    activateUnicode11(term)
    const fit = new FitAddon()
    term.loadAddon(fit)
    const searchAddon = new SearchAddon()
    term.loadAddon(searchAddon)
    termRef.current = term
    searchAddonRef.current = searchAddon
    fitRef.current = fit
    transportRef.current = transport
    term.open(hostRef.current!)
    patchImeModeSwitch(term)
    // Renderer-parity with the canvas terminals (see char-size-quantize): the modal co-views
    // the same session, so its column math must match what the canvas draws.
    quantizeCharSize(term)
    // The card's find bar crashes on an untrimmed alternate buffer, same as the canvas node.
    patchShrinkTrim(term)
    fit.fit()

    let sessionId: string | null = null
    let dead = false
    const cleanups: Array<() => void> = []

    // MIRROR TerminalNode's link wiring. The URL provider handles Cmd/Ctrl+click on URL text when
    // mouse-reporting is off (plain-shell sessions); the capture-phase fallback is what works under
    // tmux/agent mouse-reporting — the norm, and the only path on which the OSC 8 linkHandler above
    // can ever fire in a tmux-backed session (xterm's own link activation is swallowed by the mouse
    // report, see installLinkClickFallback).
    // File links use main's token model and lookup unchanged, but resolve against the CARD's project
    // (`cardFileLinkRoute`), not the active one: the Omni board opens cards from every project, and
    // resolving a path against the wrong machine is worse than not linking it — so any doubt (no
    // project, a relay/server core, a session on a host the project's fs does not cover, an unknown
    // core platform) turns file links off. An activated file opens in the card's own preview.
    const openUrl = (uri: string): void => window.nodeTerminal.shell.openExternal(uri)
    const route = () => {
      const id = projectIdRef.current
      if (!id || !onOpenFileRef.current) return null
      const project = useProjects.getState().projects.find((p) => p.id === id)
      return cardFileLinkRoute({ project, source: projectSessionSource(id), spawn })
    }
    const projectFs = (): FsApi | null => {
      const r = route()
      if (!r) return null
      return r.ssh ? sshFs(projectIdRef.current!) : api.fs
    }
    const pathConvention = (): { windows?: boolean } | null => {
      const r = route()
      if (!r) return null
      const dialect = fileLinkDialect({
        source: 'local',
        browserRuntime: isBrowserRuntime(),
        viewerWindows: isWindowsPlatform(),
        corePlatform: corePlatformRef.current,
        sshProject: r.sshProject,
        standaloneSsh: r.standaloneSsh
      })
      return dialect ? { windows: dialect === 'windows' } : null
    }
    const lookup = makeDirListingLookup(
      async (dir) => {
        const fs = projectFs()
        if (!fs) throw new Error('no filesystem to check it on')
        return fs.list(dir)
      },
      3000,
      pathConvention
    )
    const getCwd = (): string | undefined => spawn.cwd || undefined
    // The pane's CURRENT directory — the second anchor for a relative path (see CwdSources).
    const getLiveCwd = cachedCwd(() => api.pty.paneCwd(nodeId))
    const fileEnabled = (): boolean => pathConvention() !== null
    const openFile = (abs: string, isDir: boolean): void => {
      const r = route()
      const id = projectIdRef.current
      if (!r || !id) return
      if (isDir) {
        // The Explorer drawer only shows the ACTIVE project; revealing a folder of another project's
        // card there would show the wrong tree.
        if (id === useProjects.getState().activeProjectId)
          window.dispatchEvent(new CustomEvent('nodeterm:reveal-file', { detail: { path: abs } }))
        else
          window.dispatchEvent(
            new CustomEvent('nodeterm:toast', {
              detail: { kind: 'error', message: `Open this card's project to reveal ${abs}` }
            })
          )
        return
      }
      onOpenFileRef.current?.({ path: abs, projectId: id, ssh: r.ssh })
    }
    const onMissing = (token: string, miss: { tried: string[]; unverified?: UnverifiedPath[] }): void => {
      window.dispatchEvent(
        new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: fileMissMessage(token, miss) } })
      )
    }
    term.registerLinkProvider(createUrlLinkProvider(term, openUrl))
    term.registerLinkProvider(
      createFileLinkProvider(term, {
        getCwd,
        getLiveCwd,
        lookup,
        activate: openFile,
        convention: pathConvention
      })
    )
    if (term.element) {
      cleanups.push(
        installLinkClickFallback(term, term.element, {
          getCwd,
          getLiveCwd,
          lookup,
          activateFile: openFile,
          onMissing,
          openUrl,
          fileEnabled,
          convention: pathConvention
        }).dispose
      )
      // Right-click stays URL-only here: the canvas node's file rows (download, reveal in the OS,
      // open a terminal) act on the active project, which may not be this card's.
      cleanups.push(
        installLinkContextMenu(term, term.element, {
          getCwd: () => undefined,
          fileEnabled: () => false,
          openMenu: (hit, x, y) => {
            if (hit.kind === 'url') setLinkMenu({ x, y, url: hit.url })
          }
        }).dispose
      )
    }

    // MIRROR TerminalNode's copy-on-select (issue #759): same helper, same live setting read, same
    // quiet clipboard path. This xterm is created and disposed by this one effect (no park), so the
    // per-mount `cleanups` is its whole lifetime.
    cleanups.push(
      attachCopyOnSelect(term, {
        enabled: () => useSettings.getState().settings.copyOnSelect,
        write: (text) => window.nodeTerminal.clipboard.writeText(text, { quiet: true })
      })
    )

    // MIRROR TerminalNode "WRITE-ONLY — `parseOsc52` returns null" — the OSC 52 clipboard-write path.
    // tmux's mouse is ON, so a drag-select in copy-mode emits OSC 52 to this client; this handler
    // writes the system clipboard. `parseOsc52` returns null for a `?` read query so a remote program
    // can never read the local clipboard. Returning true swallows the sequence (also the read query).
    // MIRROR TerminalNode: a RELAY tab's writes are refused (osc52-policy.ts).
    const osc52Notice = createOsc52Notice()
    term.parser.registerOscHandler(52, (data) => {
      const text = parseOsc52(data)
      if (text !== null) {
        handleOsc52Write(text, session.source, {
          write: (t) => window.nodeTerminal.clipboard.writeText(t),
          notifyCopied: (t) => copy.notifyCopy(t),
          shouldNotify: osc52Notice,
          toast: dispatchOsc52Toast
        })
      }
      return true
    })

    // MIRROR TerminalNode "const action = terminalKeyAction" — Cmd+C / Ctrl+Shift+C / Ctrl+Insert copy
    // the xterm selection (a canvas can't be DOM-copied), and Shift+Enter → ESC+CR (`SHIFT_ENTER_SEQ`)
    // so agent CLIs insert a newline instead of submitting. A copy chord is always swallowed (else
    // Ctrl+Shift+C would fall through to the pty as \x03/SIGINT); plain Ctrl+C is left alone.
    // MIRROR TerminalNode: Cmd/Ctrl+1-9 (jump to the Nth project) is swallowed here, before xterm
    // turns Ctrl+2..Ctrl+8 into control bytes — but only when the app owns the key (desktop shell,
    // digit addressing an open project, AND app-first: under terminal-first the digit belongs to
    // the PTY), which `liveProjectJumpTarget` + the policy decide for both surfaces.
    term.attachCustomKeyEventHandler((e) => {
      // MIRROR TerminalNode: ⌘+ / ⌘− / ⌘0 step the NODE's own font size (issue #915) when opted
      // in. The modal renders `spawn.terminalFontSize`, so the step lands on both views at once.
      const fontZoom = terminalFontZoomAction(e, {
        enabled: useSettings.getState().settings.terminalFontZoomKeys,
        isMac: isMacPlatform()
      })
      if (fontZoom) {
        e.preventDefault()
        requestTerminalFontZoom(nodeId, fontZoom)
        return false
      }
      const ownsProjectJump =
        terminalShortcutPolicy() !== 'terminal-first' && liveProjectJumpTarget(e) !== null
      // MIRROR TerminalNode's registryOwns — but with `kanbanOpen: true` ALWAYS: the modal only
      // exists over the board, where the resolver refuses canvas-scope commands (directional
      // focus etc. mean nothing here), so those chords keep reaching the pty; app-scope
      // allowInTerminal commands still bubble, matching what the dispatcher would claim.
      const registryOwns = terminalChordBubbles(e, true)
      const action = terminalKeyAction(e, term.hasSelection(), ownsProjectJump, registryOwns)
      if (action === 'pass') return true
      // 'bubble': hand the chord to the window dispatcher — no preventDefault (it bails on
      // defaultPrevented), no xterm processing. 'native' leaves the event uncancelled for the
      // PLATFORM's own paste (Windows Ctrl+V). See TerminalNode's twin comment.
      if (action === 'bubble' || action === 'native') return false
      e.preventDefault()
      if (action === 'copy') window.nodeTerminal.clipboard.writeText(term.getSelection())
      else if (action === 'shift-enter' && sessionId) transport.write(sessionId, SHIFT_ENTER_SEQ)
      return false
    })

    // MIRROR TerminalNode's `dialsSsh`: a RELAY card's SSH-project node lives on the HOST's side,
    // so this machine never dials for it (session/relay-ssh.ts). Its create goes to the host's
    // core with `requireRemote`, which joins the session when the host holds it live and refuses
    // otherwise. This machine has no master to resolve for it and must not refuse it for lacking one.
    const dialsSsh = !!spawn.sshRemoteTmux && session.source !== 'relay'
    void (async () => {
      // MIRROR TerminalNode: a node of a REMOTE project (a relay / hosted team tab) under a session
      // that is not a relay session would create the host's node id on THIS desktop's core. The
      // board mounts the modal under the card's project session (`ProjectSessionScope`), so this
      // is the defensive half: start nothing, before any SSH resolve. `isRemoteProjectId` is
      // sessionForProject's own rule, so a tab the store deleted still counts.
      const owner = owningProjectRef.current
      if (spawnBelongsElsewhere(isRemoteProjectId(owner ?? ''), session.source)) {
        term.write(
          `\r\n\x1b[90m${REMOTE_PROJECT_SPAWN_REFUSAL}\x1b[0m\r\n`
        )
        return
      }
      // Read here, not at click time. A dialing node's reconnect coordinator is keyed by CONNECTION
      // SCOPE (same choice resolveSshRemote makes) — the project's own id, or the host attachment
      // when this card's session is on a machine the project isn't. Any other node's pane is owned
      // by the CARD's project (the Omni board opens cards of every project), else the active one.
      const projectId =
        dialsSsh && spawn.ssh
          ? sshConnectionScope(spawn.ssh)
          : (owner ?? useProjects.getState().activeProjectId)
      // SSH-project node: resolve the live ControlMaster (may not be up yet on a cold load).
      const sshRemote =
        dialsSsh && spawn.ssh
          ? await resolveSshRemote(spawn.ssh, spawn.cwd, { nodeId, pty: api.pty })
          : undefined
      if (dead) return
      // The host is unreachable: spawn NOTHING. A create with no `sshRemote` falls through to
      // core's LOCAL tmux branch, and opening a card for a remote session would silently start a
      // local shell under that node's id — see PtyCreateOptions.requireRemote. The card says so
      // and the node is queued for the reconnect coordinator, exactly like the canvas node.
      if (dialsSsh && !sshRemote) {
        term.write(
          `\r\n\x1b[90m[not connected — this session lives on ${spawn.ssh ? `${spawn.ssh.user}@${spawn.ssh.host}` : 'the remote host'}; nothing was started locally]\x1b[0m\r\n`
        )
        if (projectId) reportSshDrop(projectId, nodeId)
        return
      }
      // A local `ssh <host>` node runs ssh as its own pty program (shell:'ssh' + buildSshArgs); an
      // SSH-PROJECT node uses tmux on the remote host instead (sshRemote), so it is NOT localSsh.
      const localSsh = !!spawn.ssh && !spawn.sshRemoteTmux
      const res = await transport.create({
        cols: term.cols,
        rows: term.rows,
        shell: localSsh ? 'ssh' : spawn.shell,
        shellArgs: localSsh ? buildSshArgs(spawn.ssh!) : undefined,
        cwd: spawn.cwd,
        persistKey: nodeId,
        // Pane-ownership ledger parity with TerminalNode (agent messaging, PR #237 fix round 2):
        // if this modal is ever the FIRST/sole fresh spawner of the node (a card for a node whose
        // project is not the active canvas), the pane must still record its true owner. Use the
        // CARD's project resolved above, NOT the active canvas id — the modal may be for a
        // non-active project. Recorded main-side only on a genuine fresh spawn.
        ownerProjectId: projectId,
        agentId: spawn.agentId,
        accountId: spawn.accountId,
        sshRemote,
        requireRemote: spawn.sshRemoteTmux,
        restoreScrollback: true,
        // Same local-login exemption as the canvas node (issue #1186).
        ...(isLocalOnSshCanvas(nodeId) ? { localOnSshCanvas: true } : {})
      }).catch((err: unknown): Error => (err instanceof Error ? err : new Error(String(err))))
      // A create that REJECTS started nothing — the core could not be asked (a relay tab whose
      // connection is gone, e.g. the offline relay session, answers every call with E_DISCONNECTED).
      // Say so, like TerminalNode's spawn-error overlay, instead of a blank viewer and an unhandled
      // rejection out of this effect.
      if (res instanceof Error) {
        if (!dead) {
          // eslint-disable-next-line no-control-regex -- the message is written INTO the terminal
          const why = res.message.replace(/[\x00-\x1f\x7f]/g, ' ')
          term.write(`\r\n\x1b[90m[this terminal could not be started: ${why}]\x1b[0m\r\n`)
        }
        return
      }
      // Refused core-side (the master died inside our round-trip, or `ssh` is missing).
      if (res.unavailable) {
        const refusal = ptyRefusal(res.unavailable)
        term.write(`\r\n\x1b[90m[${refusal.message}]\x1b[0m\r\n`)
        if (refusal.connectionLost && projectId && dialsSsh) reportSshDrop(projectId, nodeId)
        return
      }
      // Another client permanently deleted this node's session — never resurrect it (no live session
      // to join, and the tombstone refused a fresh spawn). Show the state and stop.
      if (res.closed) {
        term.write('\r\n\x1b[90m[session closed by another user]\x1b[0m\r\n')
        return
      }
      // Unmounted while the create was in flight: detach the viewer we just registered so it doesn't
      // linger as a phantom subscriber constraining the shared pty's size.
      if (dead) {
        transport.kill(res.sessionId)
        return
      }
      sessionId = res.sessionId
      sessionIdRef.current = res.sessionId
      cleanups.push(transport.onData(res.sessionId, (d) => term.write(d)))
      cleanups.push(
        transport.onExit(res.sessionId, () =>
          term.write('\r\n\x1b[90m[session ended]\x1b[0m\r\n')
        )
      )
      // The pty runs at the SMALLEST subscriber's grid; render exactly what it tells us and letterbox
      // the rest (the canvas node votes independently — the modal's smaller pane may shrink it).
      if (transport.onSize)
        cleanups.push(
          transport.onSize(res.sessionId, (size) => term.resize(size.cols, size.rows))
        )
      term.onData((d) => sessionId && transport.write(sessionId, d))
      // DELIBERATELY omitted vs. TerminalNode: no flow-control pause (transport.setFlow) and no
      // onResync handler. The pty's pacing/backpressure comes from the canvas node's client — the
      // modal is a transient, always-on-top second view and never drives the shared session's flow.

      // A fresh (cold-restart / first-open) session's tmux pane is gone, so replay the persisted
      // scrollback. A warm join is painted from the server-captured screen inside create(). Agent
      // auto-resume is deliberately canvas-only — the modal never re-launches a CLI. Both the
      // snapshot and `res.screen` come from `capture-pane -p` (LF-separated, no CR bytes) and this
      // xterm runs with convertEol:false, so they MUST go through toXtermText or they staircase.
      const snapshot = res.fresh ? await api.pty.readScrollback(nodeId) : null
      // The read above is a suspension point: bail if the modal closed while it was in flight, so we
      // never write into a disposed xterm or observe a null host ref (mirrors TerminalNode's
      // post-await onDisposed check).
      if (dead) return
      // Same as TerminalNode: a joiner (which the modal always is) must enter the alternate
      // buffer BEFORE the paint — see PtyCreateResult.coAttachAltScreen.
      if (res.coAttachAltScreen) term.write(CO_ATTACH_ALT_SCREEN_SEQ)
      const paint = seedPaint({
        replay: attachReplay({ parked: false, fresh: res.fresh, hasInitialCommand: false }),
        superseded: false,
        snapshot,
        screen: res.screen,
        coreSeeded: res.scrollbackSeeded
      })
      if (paint === 'snapshot') {
        if (snapshot) term.write(toXtermText(snapshot))
        term.write('\r\n\x1b[90m— cold start · agent auto-resume happens on canvas —\x1b[0m\r\n')
      } else if (paint === 'create-screen' && res.screen) {
        // Start from a known-clean SGR state, then convert the capture's LFs to CRLFs.
        term.write('\x1b[0m' + toXtermText(stripTrailingNewline(res.screen)))
        // The capture is TEXT, so the paint above left the cursor after its last character rather
        // than where the pane has it. The modal is a co-attach joiner by definition — it is the
        // path this affects most, not an edge case (see `cursorPlacementSeq`).
        term.write(cursorPlacementSeq(res.cursor))
      }

      // Co-attach joiners miss the mouse-tracking mode tmux only sends at its own attach, so the
      // wheel can't scroll tmux history until a keystroke wakes it. Enable it here (see
      // CO_ATTACH_MOUSE_SEQ). Painting content first, then the modes, keeps the seed untouched.
      if (res.coAttachMouse) term.write(CO_ATTACH_MOUSE_SEQ)

      const ro = new ResizeObserver(() => {
        fit.fit()
        if (sessionId) transport.resize(sessionId, term.cols, term.rows)
      })
      ro.observe(hostRef.current!)
      cleanups.push(() => ro.disconnect())
      transport.resize(res.sessionId, term.cols, term.rows)
      focusXtermUnlessCovered(term, coveredRef.current)
    })()

    return () => {
      dead = true
      cleanups.forEach((fn) => fn())
      // Kill ONLY this modal's viewer — the instance appends its viewerId. The canvas node's PRIMARY
      // (or parked) client is a different composite subscriber and is untouched; the shared pty lives
      // on until its last view goes.
      if (sessionId) transport.kill(sessionId)
      term.dispose()
      sessionIdRef.current = null
      fitRef.current = null
      transportRef.current = null
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [nodeId])

  // Live-apply the appearance settings, mirroring the canvas node's effect (see TerminalNode) —
  // without this the modal kept whatever it was built with, so changing the font or the theme with
  // a card open changed the canvas terminal and left its own second view of the SAME session
  // looking different until the modal was reopened.
  //
  // Re-fitting here is not cosmetic: this viewer is a co-attach subscriber, and the pty runs at the
  // smallest subscriber's grid. A viewer that changes its cell geometry without re-reporting keeps
  // clamping the shared pty to its pre-change size — i.e. shrinks the canvas terminal too.
  useEffect(() => {
    const term = termRef.current
    if (!term) return
    const { metricsChanged } = applyLiveOptions(term, visual, glass)
    if (!metricsChanged) return
    fitRef.current?.fit()
    const sid = sessionIdRef.current
    if (sid) transportRef.current?.resize(sid, term.cols, term.rows)
  }, [visual, glass])

  // File drop → paste the path(s) into the co-attached session, just like the canvas node.
  const onDragOver = (e: React.DragEvent) => {
    if (!Array.from(e.dataTransfer.types).includes('Files')) return
    e.preventDefault()
    e.dataTransfer.dropEffect = 'copy'
    if (!dropping) setDropping(true)
  }
  const onDragLeave = (e: React.DragEvent) => {
    const rt = e.relatedTarget as Node | null
    if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)
  }
  /** Drop and paste share one path — same rule as the canvas node (see TerminalNode.insertFiles):
   *  files become paths in the terminal, and only the window-raise differs. */
  const insertFiles = async (files: File[], opts: { raiseWindow: boolean }) => {
    const term = termRef.current
    if (!term || !files.length) return
    // Clipboard bytes must be written before they have a path, which is not instant either.
    const needsWrite = files.some((f) => !window.nodeTerminal.getPathForFile(f))
    const st = agentStatusStore.getState().byId[nodeId]
    const paneAgent = spawn.agentId ?? st?.agentId
    const agentPane = agentProcessInPane(paneAgent, st)
    // MIRROR TerminalNode.dropDialectFor: spelled for the core that owns the pane, not this window.
    const dialect = dropDialect({
      corePlatform: corePlatformRef.current,
      remote: !!spawn.sshRemoteTmux || !!spawn.ssh,
      shell: spawn.shell || useSettings.getState().settings.defaultShell || undefined,
      agentPane,
      localDesktop: session.source === 'local' && !isBrowserRuntime(),
      viewerWindows: isWindowsPlatform()
    })
    let paths: string[]
    if (spawn.sshRemoteTmux) {
      // Uploads go over the master this card's PTY runs on — its scope, not the project's.
      const projectId = nodeUploadScope(spawn.ssh)
      setUploading(true)
      try {
        paths = await droppedPaths(files, { sshRemoteTmux: true, projectId })
      } finally {
        setUploading(false)
      }
    } else if (needsWrite) {
      setUploading(true)
      try {
        paths = await droppedPaths(files, { sshRemoteTmux: false, projectId: '', dialect })
      } finally {
        setUploading(false)
      }
    } else {
      paths = await droppedPaths(files, { sshRemoteTmux: false, projectId: '', dialect })
    }
    if (!paths.length) return
    // A drag-drop from another OS app doesn't bring our window forward (esp. macOS), so the
    // drag-source keeps keyboard focus — the user's next keystrokes would land in the wrong app.
    // Raise our window FIRST, then focus the terminal, so typing after the drop reaches it.
    // A paste came from this window, which already has focus.
    if (opts.raiseWindow) window.nodeTerminal.focusWindow()
    term.focus()
    // Same receipt as the canvas node (TerminalNode.insertFiles): attached only once the pane
    // shows it.
    pasteWithImageReceipt(
      term,
      paths.join(' ') + ' ',
      paths,
      agentPane ? paneAgent : undefined,
      pasteReceipt.report
    )
  }

  const onDrop = async (e: React.DragEvent) => {
    const files = Array.from(e.dataTransfer.files)
    setDropping(false)
    if (!files.length) return
    e.preventDefault()
    e.stopPropagation()
    await insertFiles(files, { raiseWindow: true })
  }

  // Cmd/Ctrl+V of a file or of raw image bytes; a text paste falls through to xterm untouched.
  // Capture phase, because xterm's own paste listener sits on the textarea below this wrapper.
  const onPaste = (e: React.ClipboardEvent) => {
    const files = pastedFiles(e.clipboardData)
    if (files.length) {
      e.preventDefault()
      e.stopPropagation()
      void insertFiles(files, { raiseWindow: false })
      return
    }
    // Files nor text — the filtered image-only clipboard. Same fallback as the canvas node.
    if (pasteHasText(e.clipboardData)) return
    void clipboardImages().then((images) => {
      if (images.length) void insertFiles(images, { raiseWindow: false })
    })
  }

  return (
    <div
      className={`kanban-modal__termwrap${glassVars ? ' kanban-modal__termwrap--glass' : ''}${
        dropping ? ' kanban-modal__termwrap--drop' : ''
      }`}
      style={glassVars ?? undefined}
      onDragOver={onDragOver}
      onDragLeave={onDragLeave}
      onDrop={onDrop}
      onPasteCapture={onPaste}
    >
      {uploading && <div className="kanban-modal__upload">Uploading…</div>}
      {/* Same pill, same class, same corner as the canvas node — one session seen twice should
          not speak in two different voices. */}
      {copy.feedback && (
        <div className={`term-copy-pill term-copy-pill--${copy.feedback.kind}`}>
          {copy.feedback.label}
        </div>
      )}
      {pasteReceipt.receipt && (
        <div className={`term-paste-pill${pasteReceipt.receipt.ok ? '' : ' term-paste-pill--warn'}`}>
          {pasteReceipt.receipt.text}
        </div>
      )}
      {searchOpen && (
        <FindBar
          query={search.query}
          onQueryChange={search.setQuery}
          matchIndex={search.matchIndex}
          matchCount={search.matchCount}
          current={search.current}
          onNext={handleNext}
          onPrev={handlePrev}
          onClose={onCloseSearch}
        />
      )}
      <div ref={hostRef} className="kanban-modal__term" {...{ [FONT_ZOOM_NODE_ATTR]: nodeId }} />
      {linkMenu && (
        <ContextMenu
          x={linkMenu.x}
          y={linkMenu.y}
          zIndex={60}
          // No "Open in canvas browser": the node would open on the canvas UNDER the board,
          // out of sight of the click that asked for it.
          items={urlLinkMenuItems(linkMenu.url, {
            openUrl: (url) => window.nodeTerminal.shell.openExternal(url),
            copy: (text) => window.nodeTerminal.clipboard.writeText(text)
          })}
          onClose={() => setLinkMenu(null)}
        />
      )}
    </div>
  )
}