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.

5.4 KB
Raw Blame
import type { SshConnection } from '@shared/ssh'
import { groupBoundBranch, nearestBoundBranch } from '@shared/pull-card-links'
import type { NodeIcon } from '@shared/node-icon'
import { normalizeIssueRef } from '@shared/github-issue-ref'
import { SYSTEM_NODE_COLORS, type CanvasNode } from '../state/workspace'
import type { KanbanSession } from '../components/kanban/KanbanView'
import type { PendingLaunch } from '@shared/types'

/** One canvas node as a board card, or null when this kind is not a card at all (a group frame, an
 *  editor, a diff). The board derives its cards from the canvas live, so this is the single
 *  definition of that mapping — the card list and the board-log's `cardTitle` lookup must agree on
 *  what a node is called, or a title change would log as a card appearing and disappearing. */
export function toKanbanSession(n: CanvasNode): KanbanSession | null {
  if (n.type === 'browser') {
    return {
      id: n.id,
      title: (n.data.title as string) || 'Browser',
      color: (n.data.color as string) ?? SYSTEM_NODE_COLORS[0],
      kind: 'browser',
      url: n.data.url as string | undefined,
      partition: n.data.partition as string | undefined,
      spawn: {}
    }
  }
  if (n.type === 'sticky') {
    // The card modal's textarea is CONTROLLED by this text: it must be the node's raw value.
    // Trimming here strips the trailing space/newline the user just typed on every round-trip,
    // which reads as "the space key doesn't work" in the kanban note editor (issue #285).
    const text = (n.data.text as string) ?? ''
    return {
      id: n.id,
      // A note has no title of its own — its trimmed first line is the card label. Bodies are
      // markdown, so a leading heading marker is presentation, not part of the label.
      title: text.trim().split('\n')[0].replace(/^#{1,6}\s+/, '').trim().slice(0, 80) || 'Note',
      color: (n.data.color as string) ?? SYSTEM_NODE_COLORS[2],
      kind: 'sticky',
      text,
      textUpdatedAt: n.data.textUpdatedAt as number | undefined,
      textUpdatedBy: n.data.textUpdatedBy as string | undefined,
      // Sticky cards never open a live terminal — the modal reads no spawn info.
      spawn: {}
    }
  }
  if (n.type !== 'terminal') return null
  const pending = n.data.pendingLaunch as PendingLaunch | undefined
  return {
    id: n.id,
    title: (n.data.title as string) ?? '',
    color: (n.data.color as string) ?? SYSTEM_NODE_COLORS[0],
    kind: 'terminal',
    agentId: n.data.agentId as string | undefined,
    icon: n.data.icon as NodeIcon | undefined,
    // Re-validated, like everything read off node data for display: the issue card groups sessions
    // by this, and a malformed value must bind to nothing rather than to a wrong card.
    issueRef: normalizeIssueRef(n.data.issueRef),
    // The held launch always rides the card; whether a first-open launch still in flight hides the
    // chip is decided by the chip itself (lib/pendingLaunch `firstOpenInFlight`, the node's own
    // predicate), because only it reads the delivery store — a delivery that failed before the
    // `initialCommand` alias cleared must show ⚠ QUEUED on the card exactly as it does on the node.
    ...(pending ? { pendingLaunch: pending, ...(n.data.initialCommand ? { launchFirstOpen: true } : {}) } : {}),
    // What the card modal's co-attach terminal needs to join THIS node's session the same way the
    // canvas TerminalNode does.
    spawn: {
      shell: n.data.shell as string | undefined,
      cwd: n.data.cwd as string | undefined,
      agentId: n.data.agentId as string | undefined,
      accountId: n.data.accountId as string | undefined,
      ssh: n.data.ssh as SshConnection | undefined,
      sshRemoteTmux: !!n.data.sshRemoteTmux,
      terminalFontSize: n.data.terminalFontSize as number | undefined,
      agentSessionId: n.data.agentSessionId as string | undefined
    }
  }
}

/** The branch of the worktree the node's nearest BOUND ancestor group works in — the same frame
 *  `cwdForNewNodeIn` hands a worktree path from. A pull request whose head is this branch links to
 *  the node's card. Read from the persisted binding (`data.worktree.branch`), so it needs no git
 *  read; a stale binding (directory deleted) still names the branch, which is exactly when its PR
 *  tends to merge. Cycle-safe: a hand-edited parent loop ends the walk. */
export function worktreeBranchOf(n: CanvasNode, byId: ReadonlyMap<string, CanvasNode>): string | undefined {
  return nearestBoundBranch(n.parentId, (id) => {
    const parent = byId.get(id)
    return parent && {
      parentId: parent.parentId,
      boundBranch: groupBoundBranch(parent.type === 'group', parent.data?.worktree)
    }
  })
}

/**
 * The board's session cards, from the canvas nodes. On an SSH project the cards carry NO worktree
 * branch: worktree groups are local-only, so a branch link there is not supported — and leaving the
 * branch off HERE is what keeps the card face, the merge-driven move and the card modal (which says
 * so) in agreement. An issue-bound card still links through its issue.
 */
export function kanbanSessionsFrom(nodes: CanvasNode[], options: { ssh: boolean }): KanbanSession[] {
  const byId = new Map(nodes.map((n) => [n.id, n]))
  return nodes.flatMap((n): KanbanSession[] => {
    const card = toKanbanSession(n)
    if (!card) return []
    const worktreeBranch = options.ssh ? undefined : worktreeBranchOf(n, byId)
    return [worktreeBranch ? { ...card, worktreeBranch } : card]
  })
}