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.

9.4 KB
Raw Blame
/**
 * Live terminal for a worker. xterm.js + FitAddon + backpressure.
 *
 * Mandatory conventions:
 *  - Terminal instance via useRef (NOT useState) — otherwise it re-renders per chunk.
 *  - dispose() in cleanup: without it, every worker selection leaks a
 *    WebGL context (Chrome caps at 16 contexts per origin).
 *  - Backpressure: bytesPending is counted locally; past 128 KB pending we
 *    send a `{type:"pause"}` to the PTY stream, and `resume` again at 16 KB.
 *
 * MVP note: the backend PTY endpoint is planned as a stub (Phase 6, separate
 * Jarvis-Agent). Until it's ready, this component shows a "stream not
 * available" placeholder as soon as the WS connect fails.
 */
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 { SearchAddon } from "@xterm/addon-search";
import "@xterm/xterm/css/xterm.css";
import { AlertCircle, Terminal as TerminalIcon } from "lucide-react";
import { fill, useT } from "@/i18n";
import { useThemeValue } from "@/hooks/useTheme";
import {
  MINIMUM_CONTRAST_RATIO,
  PANE_CHROME,
  themeFor,
} from "../agentic/terminalThemes";
import { buildMissionSocketUrl, fetchMissionToken } from "@/lib/missionAuth";
import { TERMINAL_FONT_STACK, syncTerminalFont } from "@/lib/terminalFont";
import {
  activateTerminalLink,
  TERMINAL_OSC_LINK_HANDLER,
} from "@/lib/terminalLinks";
import {
  disposeTerminal,
  getTerminal,
  setTerminal,
} from "./terminalRegistry";

const PAUSE_THRESHOLD = 128 * 1024;
const RESUME_THRESHOLD = 16 * 1024;

interface PtyTerminalProps {
  workerId: string;
}

function buildPtyUrl(workerId: string): string {
  return buildMissionSocketUrl(
    `/api/missions/pty/${encodeURIComponent(workerId)}`,
  );
}

export function PtyTerminal({ workerId }: PtyTerminalProps) {
  const t = useT();
  const containerRef = useRef<HTMLDivElement | null>(null);
  const termRef = useRef<Terminal | null>(null);
  const fitRef = useRef<FitAddon | null>(null);
  const wsRef = useRef<WebSocket | null>(null);
  const bytesPendingRef = useRef(0);
  const pausedRef = useRef(false);
  const [streamError, setStreamError] = useState<string | null>(null);
  const [connected, setConnected] = useState(false);
  const appearance = useThemeValue();
  // Via a ref in the setup effect so a theme switch never re-runs it — that
  // would drop the PTY socket and, worse, dispose a terminal the registry is
  // still handing out to the next worker selection.
  const appearanceRef = useRef(appearance);
  appearanceRef.current = appearance;

  const sendControl = useCallback(
    (type: "pause" | "resume") => {
      const ws = wsRef.current;
      if (ws && ws.readyState === WebSocket.OPEN) {
        try {
          ws.send(JSON.stringify({ type, worker_id: workerId }));
        } catch {
          // ignore — the backpressure signal is best-effort
        }
      }
    },
    [workerId],
  );

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

    let term = getTerminal(workerId);
    if (!term) {
      term = new Terminal({
        convertEol: true,
        fontFamily: TERMINAL_FONT_STACK,
        fontSize: 12,
        lineHeight: 1.2,
        cursorBlink: false,
        scrollback: 5000,
        linkHandler: TERMINAL_OSC_LINK_HANDLER,
        // Shared with the Agentic IDE panes: all 16 ANSI slots, re-derived per
        // ground. A worker's diffs and dimmed hints are drawn with the "bright"
        // row, which is unreadable on paper unless it was built for paper.
        theme: themeFor(appearanceRef.current),
        // Truecolor output bypasses that palette entirely; the floor catches
        // it (see terminalThemes.ts).
        minimumContrastRatio: MINIMUM_CONTRAST_RATIO,
      });
      const fit = new FitAddon();
      term.loadAddon(fit);
      term.loadAddon(new WebLinksAddon(activateTerminalLink));
      term.loadAddon(new SearchAddon());
      term.open(containerRef.current);
      fit.fit();
      setTerminal(workerId, term);
      termRef.current = term;
      fitRef.current = fit;
    } else {
      term.open(containerRef.current);
      const fit = new FitAddon();
      term.loadAddon(fit);
      fit.fit();
      termRef.current = term;
      fitRef.current = fit;
    }

    const handleResize = () => {
      try {
        fitRef.current?.fit();
      } catch {
        // resize failures aren't critical
      }
    };
    window.addEventListener("resize", handleResize);

    // The fit above measured whatever font had loaded by then; if the display
    // font arrives later, the cell grid keeps the fallback's width while the
    // wider real glyphs are drawn into it — see ../../lib/terminalFont.
    const disposeFontSync = syncTerminalFont(term, () => {
      termRef.current?.clearTextureAtlas?.();
      handleResize();
    });

    let ws: WebSocket | null = null;
    let disposed = false;
    const openSocket = (token: string) => {
      try {
        ws = new WebSocket(buildPtyUrl(workerId));
        ws.binaryType = "arraybuffer";
        wsRef.current = ws;

        ws.addEventListener("open", () => {
          ws?.send(JSON.stringify({ type: "hello", token }));
          setConnected(true);
          setStreamError(null);
        });

        ws.addEventListener("message", (ev) => {
          const term = termRef.current;
          if (!term) return;
          let data: string;
          let size = 0;
          if (typeof ev.data === "string") {
            data = ev.data;
            size = data.length;
          } else if (ev.data instanceof ArrayBuffer) {
            const decoder = new TextDecoder();
            data = decoder.decode(ev.data);
            size = ev.data.byteLength;
          } else {
            return;
          }

          bytesPendingRef.current += size;
          if (
            !pausedRef.current &&
            bytesPendingRef.current > PAUSE_THRESHOLD
          ) {
            pausedRef.current = true;
            sendControl("pause");
          }

          term.write(data, () => {
            bytesPendingRef.current = Math.max(
              0,
              bytesPendingRef.current - size,
            );
            if (
              pausedRef.current &&
              bytesPendingRef.current < RESUME_THRESHOLD
            ) {
              pausedRef.current = false;
              sendControl("resume");
            }
          });
        });

        ws.addEventListener("error", () => {
          setStreamError(t("pty_terminal.stream_unreachable"));
        });

        ws.addEventListener("close", (ev) => {
          setConnected(false);
          if (ev.code !== 1000 && ev.code !== 1001) {
            setStreamError(
              `${t("pty_terminal.stream_disconnected")} ${fill(t("pty_terminal.close_code"), { code: ev.code })}.`,
            );
          }
        });
      } catch (e) {
        setStreamError(`${t("pty_terminal.connect_failed")}: ${(e as Error).message}`);
      }
    };

    void fetchMissionToken()
      .then((token) => {
        if (!disposed) openSocket(token);
      })
      .catch((error: unknown) => {
        if (!disposed) {
          const message = error instanceof Error ? error.message : String(error);
          setStreamError(`${t("pty_terminal.connect_failed")}: ${message}`);
        }
      });

    return () => {
      disposed = true;
      window.removeEventListener("resize", handleResize);
      disposeFontSync();
      try {
        wsRef.current?.close(1000, "unmount");
      } catch {
        // ignore
      }
      wsRef.current = null;
      // The terminal is disposed when the WORKER changes (see the key prop
      // in MissionsView), not on every re-render
      disposeTerminal(workerId);
      termRef.current = null;
      fitRef.current = null;
    };
  }, [workerId, sendControl, t]);

  // Recolour in place on a theme switch — the buffer, the scrollback and the
  // live socket all survive; only the palette is swapped.
  useEffect(() => {
    const term = termRef.current;
    if (term) term.options.theme = themeFor(appearance);
  }, [appearance]);

  return (
    <div
      className="relative flex h-full w-full flex-col overflow-hidden rounded-md border border-border"
      style={{ background: PANE_CHROME[appearance].shell }}
    >
      <header className="flex items-center justify-between gap-2 border-b border-border bg-card/40 px-3 py-2">
        <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">
            {fill(t("pty_terminal.worker_label"), { id: workerId.slice(0, 12) })}
          </span>
        </div>
        <div className="flex items-center gap-2 text-micro uppercase tracking-wider">
          {streamError ? (
            <span className="flex items-center gap-1 text-destructive">
              <AlertCircle className="h-3 w-3" />
              {t("pty_terminal.status_offline")}
            </span>
          ) : connected ? (
            <span className="text-muted-foreground">{t("pty_terminal.status_live")}</span>
          ) : (
            <span className="text-muted-foreground">{t("pty_terminal.connecting")}</span>
          )}
        </div>
      </header>
      <div ref={containerRef} className="flex-1 overflow-hidden p-1" />
      {streamError && (
        <div className="border-t border-border bg-destructive/10 px-3 py-2 text-xs text-destructive">
          {streamError}
        </div>
      )}
    </div>
  );
}