Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

14.3 KB
Raw Blame
/**
 * One embedded, interactive agent terminal — xterm.js wired bidirectionally to
 * the workspace PTY WebSocket (`/api/workspace/pty/{key}`). The agent (Claude
 * Code / Codex) runs in a real PTY in the Jarvis project folder; keystrokes go
 * up as `{t:"i"}`, output comes down as `{t:"o"}`, resizes as `{t:"r"}`.
 *
 * Conventions copied from PtyTerminal: xterm instance in a ref (never state, or
 * it rerenders per chunk), dispose() on unmount (WebGL context cap).
 */
import { cn } from "@/lib/utils";
import { useCallback, useEffect, useRef, useState } from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { WebLinksAddon } from "@xterm/addon-web-links";
import "@xterm/xterm/css/xterm.css";
import { Terminal as TerminalIcon, AlertCircle } from "lucide-react";
import { installNewlineBridge } from "../agentic/terminalNewline";
import { usePaneFileDrag } from "../agentic/paneFileDrag";
import { announceSkillRefused, pasteSkillText, type SkillDragPayload } from "../agentic/skillDrag";
import { SkillDropCard } from "../agentic/sidePanel/skills/SkillDropCard";
import { useIdeSkillsStore } from "@/store/ideSkills";
import { requestConnect } from "@/lib/connectBudget";
import { FONT_DEFAULT } from "../agentic/paneFont";
import {
  MINIMUM_CONTRAST_RATIO,
  PANE_CHROME,
  themeFor,
  type TerminalAppearance,
} from "../agentic/terminalThemes";
import { useThemeValue } from "@/hooks/useTheme";
import { fill, translate, useT } from "@/i18n";
import { TERMINAL_FONT_STACK, syncTerminalFont } from "@/lib/terminalFont";
import {
  activateTerminalLink,
  TERMINAL_OSC_LINK_HANDLER,
} from "@/lib/terminalLinks";

type Status = "connecting" | "live" | "exited" | "error";

interface WorkspaceTerminalProps {
  /** A stable key for this pane (used only as the WS path segment). */
  paneKey: string;
  /** Run an agent by name (e.g. "claude"); mutually exclusive with installName. */
  agentName?: string;
  /** Run an agent's installer by name; mutually exclusive with agentName. */
  installName?: string;
  /** Plain terminals are pinned to the workspace chosen when the tab opens. */
  workspaceId?: string;
  /**
   * Or to a folder of their own — a thread's terminal drawer, whose folder may
   * be a worktree no workspace has open. Ignored when `workspaceId` is set.
   */
  folder?: string;
  /**
   * Typed into the shell once, the first time it is ready — a project action
   * ("npm run dev") opened in a fresh terminal. End it with "\r" to run it.
   */
  initialInput?: string;
  /** No header or frame: the host draws its own tabs around the terminal. */
  bare?: boolean;
  active?: boolean;
  appearance?: TerminalAppearance;
  /**
   * A line to print before anything the process says.
   *
   * For a pane whose process is SLOW to speak: an installer can be silent for
   * ten seconds or more, and an empty black rectangle is how a user reads
   * "nothing is happening". Printed locally the moment the terminal exists, so
   * it is on screen before the socket has even connected. Newlines may be
   * plain `\n`. Absent for an agent pane, which draws its own UI at once.
   */
  banner?: string;
  /** Header label shown above the terminal. */
  title: string;
}

function buildUrl(paneKey: string, params: Record<string, string>): string {
  const proto = window.location.protocol === "https:" ? "wss" : "ws";
  const query = new URLSearchParams(params).toString();
  return `${proto}://${window.location.host}/api/workspace/pty/${encodeURIComponent(
    paneKey,
  )}?${query}`;
}

export function WorkspaceTerminal({
  paneKey,
  agentName,
  installName,
  title,
  banner,
  workspaceId,
  folder,
  initialInput,
  bare = false,
  active = true,
  appearance: requestedAppearance,
}: WorkspaceTerminalProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const termRef = useRef<Terminal | null>(null);
  const [status, setStatus] = useState<Status>("connecting");
  const [error, setError] = useState<string | null>(null);
  const appAppearance = useThemeValue();
  const t = useT();
  const appearance = requestedAppearance ?? appAppearance;
  const activeRef = useRef(active);
  activeRef.current = active;
  const resizeRef = useRef<() => void>(() => {});
  // Read through a ref inside the setup effect: the theme must NOT be a
  // dependency there, or switching it would tear down the PTY WebSocket and
  // restart the agent. Recolouring happens in its own effect below.
  const appearanceRef = useRef(appearance);
  appearanceRef.current = appearance;
  // Read through a ref for the same reason as the theme above: the banner is
  // printed once during setup, and making it a dependency there would tear the
  // PTY down and restart the installer whenever the string changed identity.
  const bannerRef = useRef(banner);
  bannerRef.current = banner;
  // Same reason: the input is sent once at `ready`, never a reason to respawn.
  const initialInputRef = useRef(initialInput);
  initialInputRef.current = initialInput;

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const term = new Terminal({
      convertEol: false,
      fontFamily: TERMINAL_FONT_STACK,
      fontSize: FONT_DEFAULT,
      lineHeight: 1.15,
      cursorBlink: true,
      scrollback: 5000,
      linkHandler: TERMINAL_OSC_LINK_HANDLER,
      // The full 16-slot palette rather than four values, and the same one the
      // Agentic IDE panes use — a coding agent's ANSI output is only readable
      // if the "bright" row was re-derived for the ground it lands on.
      theme: themeFor(appearanceRef.current),
      // Truecolor output bypasses that palette entirely; the floor catches it
      // (see terminalThemes.ts).
      minimumContrastRatio: MINIMUM_CONTRAST_RATIO,
    });
    termRef.current = term;
    const fit = new FitAddon();
    term.loadAddon(fit);
    term.loadAddon(new WebLinksAddon(activateTerminalLink));
    term.open(container);
    // Shift+Enter breaks the line instead of sending a half-written
    // instruction — the same binding the Agentic IDE panes have, because it is
    // the same kind of agent prompt on the other end (see
    // ../agentic/terminalNewline).
    const disposeNewlineBridge = installNewlineBridge(term);
    // Before the socket, deliberately: the gap this fills is the one at the
    // very start, and a banner that waited for `ready` would arrive after it.
    if (bannerRef.current) {
      term.write(`${bannerRef.current.replace(/\n/g, "\r\n")}\r\n`);
    }
    try {
      fit.fit();
    } catch {
      /* container not measured yet — ResizeObserver will fit shortly */
    }

    let ws: WebSocket | null = null;
    let disposed = false;
    let everLive = false;

    const sendResize = () => {
      if (disposed || !activeRef.current || container.clientWidth === 0 || container.clientHeight === 0) return;
      try {
        fit.fit();
      } catch {
        return;
      }
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ t: "r", cols: term.cols, rows: term.rows }));
      }
    };
    resizeRef.current = sendResize;

    // The fit above measured whatever font had loaded by then. If the display
    // font lands afterwards, the grid keeps the fallback's cell width while the
    // real glyphs are drawn wider, and the text smears out of its columns — see
    // ../../lib/terminalFont.
    const disposeFontSync = syncTerminalFont(term, () => {
      if (disposed) return;
      term.clearTextureAtlas?.();
      sendResize();
    });

    // Workspace panes share the same connection budget as the app and IDE
    // sockets. A grid mounting at once must not bypass the wake-storm cap.
    const cancelConnect = requestConnect(() => {
      if (disposed) return;
      const params: Record<string, string> = {
        cols: String(term.cols || 80),
        rows: String(term.rows || 24),
      };
      if (agentName) params.agent = agentName;
      else if (installName) params.install = installName;
      if (workspaceId) params.workspace_id = workspaceId;
      else if (folder) params.folder = folder;

      try {
        ws = new WebSocket(buildUrl(paneKey, params));
      } catch {
        setStatus("error");
        setError(translate("workspace_terminal.connection_failed"));
        return;
      }
      ws.onopen = () => {
        setStatus("connecting");
        // Push the ACTUAL pane size to the PTY now that we can send. The spawn
        // used a best-effort size (the mount-time fit often runs before the
        // grid cell is measured), and resizes fired while the socket was still
        // connecting were dropped — so without this the agent's full-screen TUI
        // keeps drawing at the wrong dimensions (cramped / clipped on the
        // right). A second deferred fit catches any late grid layout.
        sendResize();
        requestAnimationFrame(sendResize);
      };
      ws.onmessage = (ev) => {
        let msg: { t?: string; d?: string; code?: number; message?: string };
        try {
          msg = JSON.parse(ev.data as string);
        } catch {
          return;
        }
        if (msg.t === "o") term.write(msg.d ?? "");
        else if (msg.t === "ready") {
          const firstReady = !everLive;
          everLive = true;
          setStatus("live");
          if (activeRef.current) term.focus();
          const input = initialInputRef.current;
          if (firstReady && input && ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({ t: "i", d: input }));
          }
        } else if (msg.t === "exit") {
          setStatus("exited");
          term.write(
            `\r\n\x1b[33m[${fill(translate("workspace_terminal.process_exited"), { code: msg.code ?? "?" })}]\x1b[0m\r\n`,
          );
        } else if (msg.t === "error") {
          setStatus("error");
          setError(msg.message ?? translate("workspace_terminal.terminal_error"));
        }
      };
      ws.onerror = () => {
        setStatus("error");
        setError(translate("workspace_terminal.connection_failed"));
      };
      ws.onclose = (ev) => {
        if (everLive) {
          setStatus("exited");
        } else if (!disposed) {
          // Closed during the handshake (e.g. 4401 auth) — surface it honestly
          // instead of hanging on "connecting" forever (mirrors PtyTerminal).
          setStatus("error");
          setError((e) =>
            e ??
            (ev.code === 4401
              ? translate("workspace_terminal.auth_failed")
              : fill(translate("workspace_terminal.connection_closed"), { code: ev.code || "?" })),
          );
        }
      };

      term.onData((data) => {
        if (ws && ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify({ t: "i", d: data }));
        }
      });
    });

    window.addEventListener("resize", sendResize);
    const ro = new ResizeObserver(() => sendResize());
    ro.observe(container);

    return () => {
      disposed = true;
      cancelConnect();
      resizeRef.current = () => {};
      window.removeEventListener("resize", sendResize);
      ro.disconnect();
      disposeFontSync();
      disposeNewlineBridge();
      try {
        ws?.close();
      } catch {
        /* The socket is already closed; terminal cleanup still must run. */
      }
      term.dispose();
      termRef.current = null;
    };
  }, [paneKey, agentName, installName, workspaceId, folder]);

  useEffect(() => {
    if (!active) return;
    const frame = requestAnimationFrame(() => {
      resizeRef.current();
      termRef.current?.focus();
    });
    return () => cancelAnimationFrame(frame);
  }, [active]);

  // Recolour in place on a theme switch. xterm repaints from the new palette
  // without touching the buffer, so scrollback and the live PTY both survive.
  useEffect(() => {
    const term = termRef.current;
    if (term) term.options.theme = themeFor(appearance);
  }, [appearance]);

  // A skill from the Skills tab, dropped here: one bracketed paste, not sent
  // (a plain shell without bracketed paste refuses a multi-line one).
  // Files have no route into a plain shell; the drop is only claimed so it
  // cannot navigate the IDE away.
  const pasteSkill = useCallback((skill: SkillDragPayload) => {
    const term = termRef.current;
    if (!term || !skill.content) return;
    if (!pasteSkillText(term, skill.content)) {
      announceSkillRefused(title);
      return;
    }
    useIdeSkillsStore.getState().recordUse(skill.id, title);
  }, [title]);
  const ignoreFiles = useCallback(() => {}, []);
  const { dragging, carrying, handlers: dragHandlers } = usePaneFileDrag(ignoreFiles, pasteSkill);
  const skillInFlight = useIdeSkillsStore((state) => (carrying === "skill" ? state.dragging : null));

  return (
    <div
      {...dragHandlers}
      className={cn("relative flex h-full w-full flex-col overflow-hidden", !bare && "rounded-lg border border-border")}
      style={{ background: PANE_CHROME[appearance].shell }}
    >
      {!bare && <header className="flex items-center justify-between gap-2 border-b border-border bg-card/40 px-3 py-1.5">
        <div className="flex items-center gap-2 text-xs text-muted-foreground">
          <TerminalIcon className="h-3.5 w-3.5 text-primary" />
          <span className="font-mono">{title}</span>
        </div>
        <span className="text-micro uppercase tracking-wider">
          {status === "live" ? (
            <span className="text-muted-foreground">{t("workspace_terminal.status_live")}</span>
          ) : status === "error" ? (
            <span className="flex items-center gap-1 text-destructive">
              <AlertCircle className="h-3 w-3" />
              {t("workspace_terminal.status_error")}
            </span>
          ) : status === "exited" ? (
            <span className="text-muted-foreground">{t("workspace_terminal.status_exited")}</span>
          ) : (
            <span className="text-muted-foreground">{t("workspace_terminal.status_connecting")}</span>
          )}
        </span>
      </header>}
      <div ref={containerRef} className="flex-1 overflow-hidden p-1" />
      {dragging && carrying === "skill" && <SkillDropCard skill={skillInFlight} target={title}
        blocked={Boolean(skillInFlight?.multiline) && !termRef.current?.modes.bracketedPasteMode} />}
      {error && (
        <div className="border-t border-border bg-destructive/10 px-3 py-1.5 text-xs text-destructive">
          {error}
        </div>
      )}
    </div>
  );
}