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.

4.1 KB
Raw Blame
// Turn core's session-memory rows into rows the panel can render: whose node is this, which
// project does it belong to, and is there a node at all?
//
// Pure and store-free (the caller passes the projects and the agent states), so the whole
// orphan/closed-project policy is unit-testable without mounting anything.

import type { AgentState } from '@shared/agents/normalize'
import type { AppSelfGroup, Project, SessionHostOverhead, SessionMemoryRow } from '@shared/types'

export interface SessionMemoryView {
  row: SessionMemoryRow
  /** The node's title, or the session name when there is no node to name it. */
  title: string
  projectId: string | null
  projectName: string | null
  orphan: boolean
  /** Agent state for the dot. Always null for an orphan — see below. */
  state: AgentState | null
}

/**
 * Resolve each row against EVERY project, not just the active one.
 *
 * A CLOSED project is deliberately included: `closeProject` only sets `closed = true` and keeps
 * the project and its nodes on disk, so its sessions resolve to a real title. Treating them as
 * orphans would invite the user to kill sessions they deliberately parked.
 *
 * Order is preserved — core already sorted by `totalMb` descending, and re-sorting here would let
 * the panel and the report disagree.
 */
export function resolveSessionRows(
  rows: readonly SessionMemoryRow[],
  projects: readonly Project[],
  states: Readonly<Record<string, AgentState | undefined>>
): SessionMemoryView[] {
  const index = new Map<string, { projectId: string; projectName: string; title: string }>()
  for (const p of projects) {
    for (const n of p.nodes ?? []) {
      if (index.has(n.id)) continue
      index.set(n.id, {
        projectId: p.id,
        projectName: p.name,
        title: n.title?.trim() || n.id
      })
    }
  }

  return rows.map((row) => {
    const hit = index.get(row.nodeId)
    if (!hit) {
      // No node on any canvas. A state without a node is meaningless — the panel could not
      // explain a "working" dot on a row it cannot travel to — so it is dropped, not passed on.
      return {
        row,
        title: row.session,
        projectId: null,
        projectName: null,
        orphan: true,
        state: null
      }
    }
    return {
      row,
      title: hit.title,
      projectId: hit.projectId,
      projectName: hit.projectName,
      orphan: false,
      state: states[row.nodeId] ?? null
    }
  })
}

/**
 * Grand total — the panel header's number: every resolved row, plus the Windows session host's own
 * cost when it was measured (it belongs to no row, so leaving it out understates what nodeterm's
 * sessions hold; absent = not measured, which adds nothing rather than a guess).
 */
export function totalMb(views: readonly SessionMemoryView[], host?: SessionHostOverhead): number {
  return views.reduce((sum, v) => sum + v.row.totalMb, 0) + (host?.totalMb ?? 0)
}

/** The host line's label: `nodeterm session host (3 consoles)`. */
export function hostOverheadLabel(host: SessionHostOverhead): string {
  const n = host.consoleCount
  return `nodeterm session host (${n} console${n === 1 ? '' : 's'})`
}

/** "nodeterm itself" sub-line label: `GPU`, `Renderers ×2`, `Main process`, `Helpers ×3`. */
export function appGroupLabel(g: AppSelfGroup): string {
  const n = g.count > 1 ? ` ×${g.count}` : ''
  switch (g.kind) {
    case 'gpu':
      return `GPU${n}`
    case 'renderer':
      return `Renderer${g.count > 1 ? 's' : ''}${n}`
    case 'main':
      return `Main process${n}`
    default:
      return `Helper${g.count > 1 ? 's' : ''}${n}`
  }
}

/**
 * CPU TIME, not a rate: `cumulativeCPUUsage` is seconds since each process started, and a
 * percentage would need a second sample the panel's one-shot sweep does not take (Electron's own
 * `percentCPUUsage` answers 0 on the first call — a fake zero). `42s`, `12m`, `3h 05m`.
 */
export function formatCpuTime(seconds: number): string {
  const s = Math.max(0, Math.round(seconds))
  if (s < 60) return `${s}s`
  const m = Math.floor(s / 60)
  if (m < 60) return `${m}m`
  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
}