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.

feat(verse): live coding-agent terminals on the ship's screens (#887)

Ruben Lütke3a63cb91c679
diff --git a/art/verse/decks/engineering/eng_sockets.py b/art/verse/decks/engineering/eng_sockets.py
index 4e57968090..06f58d3baf 100644
--- a/art/verse/decks/engineering/eng_sockets.py
+++ b/art/verse/decks/engineering/eng_sockets.py
@@ -61,6 +61,12 @@ def stations() -> None:
"master_wall", b(c.MASTER_X, c.FAR_WALL_Z + 0.165, 3.4), 9.4, 2.4,
station="master", group="wall",
) # fmt: skip
+ # The plot table's glass (eng_rooms.plot_table), flat and facing up: the
+ # station's big screen showing every coding pane in a grid.
+ scene.add_screen(
+ "plot_table", b(c.MASTER_X, 9.6, 0.947), 4.5, 2.1, tilt_deg=90.0,
+ station="master", group="plot",
+ ) # fmt: skip
# Turbolift: the kit door carries SOCKET_lift_main and a spawn point in
# front of it, which becomes the commander's spawn.
z1 = c.CONTROL_SOUTH_Z[1]
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json b/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json
index e1dbbfbbfc..55bf3d5282 100644
--- a/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json
+++ b/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json
@@ -1052,6 +1052,52 @@
"group": "wall"
}
},
+ {
+ "id": "plot_table",
+ "kind": "screen",
+ "position": [
+ 17,
+ 0.947,
+ 9.6
+ ],
+ "yaw_deg": 0,
+ "room": "control",
+ "station": "master",
+ "size": [
+ 4.5,
+ 2.1
+ ],
+ "normal": [
+ 0,
+ 1,
+ 0
+ ],
+ "corners": [
+ [
+ 14.75,
+ 0.947,
+ 8.55
+ ],
+ [
+ 19.25,
+ 0.947,
+ 8.55
+ ],
+ [
+ 19.25,
+ 0.947,
+ 10.65
+ ],
+ [
+ 14.75,
+ 0.947,
+ 10.65
+ ]
+ ],
+ "props": {
+ "group": "plot"
+ }
+ },
{
"id": "reactor_ring__ring_1",
"kind": "screen",
@@ -3170,7 +3216,8 @@
"master__3",
"master__4",
"master__5",
- "master_wall"
+ "master_wall",
+ "plot_table"
],
"station": [
"master"
diff --git a/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index 1d9c78c702..f2f82096d2 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -132,6 +132,7 @@ import {
import { installPasteBridge } from "./terminalPaste";
import { installCopyBridge } from "./terminalCopy";
import { createKeyEventChain } from "./terminalKeyChain";
+import { registerLiveTerminal } from "@/lib/liveTerminals";
import { PANE_INPUT_EVENT, type PaneInputDetail } from "./ideHotkeys";
import { installNewlineBridge } from "./terminalNewline";
import { cancelPaneReflow, queuePaneReflow } from "./paneReflowQueue";
@@ -1098,6 +1099,8 @@ export function AgenticTerminal({
// invalidates every existing pane's cache just to open an empty terminal.
alignTerminalCells(term);
term.open(container);
+ // The ship's monitors draw this pane from the same buffer; see lib/liveTerminals.
+ const unregisterLive = registerLiveTerminal(workspaceId ?? "", name, term);
// The wheel always moves xterm's own history, even while a normal-buffer
// CLI has negotiated mouse tracking — otherwise scrolling only "works"
// when the CLI feels like it, which is the per-provider inconsistency the
@@ -2485,6 +2488,7 @@ export function AgenticTerminal({
heldLeadRef.current = holdsSizeLead(leadKey, leadToken);
releaseSizeLead(leadKey, leadToken);
// Before the terminal: frees this pane's WebGL context slot.
+ unregisterLive();
renderer.dispose();
term.dispose();
termRef.current = null;
diff --git a/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.ts
index 7a600f6b85..1c0feeb703 100644
--- a/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.ts
+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.ts
@@ -52,10 +52,13 @@ export function mergeScreens(
return next ?? prev;
}
-export function usePaneScreens(targets: PaneScreenTarget[], awake: boolean): ReadonlyMap<string, PaneScreen> {
+/** `seatedOnly`: poll only agents at their desk; off for screens that show every pane. */
+export function usePaneScreens(targets: PaneScreenTarget[], awake: boolean, seatedOnly = true): ReadonlyMap<string, PaneScreen> {
const [screens, setScreens] = useState<ReadonlyMap<string, PaneScreen>>(new Map());
const targetsRef = useRef(targets);
targetsRef.current = targets;
+ const seatedOnlyRef = useRef(seatedOnly);
+ seatedOnlyRef.current = seatedOnly;
const active = awake && targets.length > 0;
useEffect(() => {
if (!active) return;
@@ -64,7 +67,9 @@ export function usePaneScreens(targets: PaneScreenTarget[], awake: boolean): Rea
let timer: ReturnType<typeof setTimeout>;
const schedule = () => { timer = setTimeout(() => void tick(), POLL_MIN_MS + Math.random() * POLL_JITTER_MS); };
const tick = async () => {
- const due = dueTargets(targetsRef.current, seatedCrew);
+ const due = seatedOnlyRef.current
+ ? dueTargets(targetsRef.current, seatedCrew)
+ : targetsRef.current.slice(0, MAX_SCREEN_TARGETS);
if (due.length > 0) {
try {
const fetched = await fetchPaneScreens(due.map((t) => ({ workspaceId: t.workspaceId, key: t.key })));
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx b/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
index ed8804fe0f..6375a05a3c 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
@@ -60,7 +60,7 @@ import { useDevDuty } from "./life/devOverrides";
import { pickFloor } from "./nav/floorPick";
import { nearestWalkable } from "./nav/pathfind";
import { ScreensLayer } from "./effects/ScreensLayer";
-import { useScreenFaces } from "./effects/useScreenFaces";
+import { terminalSocketIds, useScreenFaces } from "./effects/useScreenFaces";
import { HoloLayer } from "./effects/HoloLayer";
import { BeaconsLayer } from "./effects/BeaconsLayer";
import { LightsLayer } from "./effects/LightsLayer";
@@ -180,6 +180,7 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
const library = useCharacterLibrary(awake);
const life = useCrewLife(deck, deckId, awake, messUntil > Date.now());
const faces = useScreenFaces(deck, life, awake, t);
+ const terminalSockets = useMemo(() => terminalSocketIds(deck), [deck]);
const runningTeams = useMemo(() => new Set(life.rounds.keys()), [life.rounds]);
useWorldActions(runtime, deck, deckId, awake, runningTeams);
// The crew salute when the commander is promoted.
@@ -867,7 +868,7 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
<DeckBackdrop runtime={runtime} deck={deck} debug={debug} awake={awake} active={!eyeOn} onReady={onPlateReady} onError={onFailure}>
<DeckEnvironment url={deck.envUrl} />
{library && <ActorsLayer runtime={runtime} deck={deck} library={library} cast={cast} commanderId={COMMANDER_ID} reduced={reduced} saluteAt={saluteAt} />}
- <ScreensLayer deck={deck} faces={faces} />
+ <ScreensLayer deck={deck} faces={faces} terminalSockets={terminalSockets} plateView={!eyeOn} />
<HoloLayer sockets={holos} lit={litHolos} reduced={reduced} />
<LightsLayer deck={deck} alarm={alarm} reduced={reduced} runtime={runtime} />
<BeaconsLayer runtime={runtime} statuses={deckStatuses} reduced={reduced} />
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/ScreensLayer.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/effects/ScreensLayer.test.ts
new file mode 100644
index 0000000000..6b7420447b
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/ScreensLayer.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import { BoxGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, Vector3 } from "three";
+import { BACKDROP_LAYER } from "../engine/renderOrder";
+import { occluderClearance, terminalCanvasSize } from "./ScreensLayer";
+
+function occluderBox(min: [number, number, number], max: [number, number, number]): Group {
+ const size = max.map((v, i) => v - min[i]) as [number, number, number];
+ const mesh = new Mesh(new BoxGeometry(...size), new MeshBasicMaterial({ side: DoubleSide }));
+ mesh.position.set((min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2);
+ mesh.layers.set(BACKDROP_LAYER);
+ const group = new Group();
+ group.add(mesh);
+ group.updateMatrixWorld(true);
+ return group;
+}
+
+describe("screen placement", () => {
+ // The engineering plate camera looks down at 60 degrees toward -z.
+ const toCamera = new Vector3(0, Math.sqrt(3) / 2, 0.5);
+
+ it("moves a screen inside its console's occluder just out of it, toward the camera", () => {
+ // term_1: the occluder spans z 13.9..14.42, y 0.78..1.45 around the tilted glass.
+ const box = occluderBox([6.68, 0.78, 13.9], [8.12, 1.45, 14.42]);
+ const corners: [number, number, number][] = [[6.75, 1.415, 14.08], [8.05, 1.415, 14.08], [8.05, 0.89, 14.41], [6.75, 0.89, 14.41]];
+ const lift = occluderClearance(corners, toCamera, box);
+ // The middle of the tilted glass sits deepest: it sets the lift (top face y 1.45 from y 1.15).
+ expect(lift).toBeGreaterThan(0.3);
+ expect(lift).toBeLessThan(0.4);
+ });
+
+ it("leaves a screen outside every occluder where it is", () => {
+ const box = occluderBox([0, 0, 0], [1, 1, 1]);
+ expect(occluderClearance([[5, 5, 5], [6, 5, 5], [6, 4, 5], [5, 4, 5]], toCamera, box)).toBe(0);
+ expect(occluderClearance([[5, 5, 5]], toCamera, undefined)).toBe(0);
+ });
+
+ it("gives terminal screens a sharp canvas within texture bounds", () => {
+ expect(terminalCanvasSize(1.3, 0.62)).toEqual({ width: 1066, height: 508 });
+ expect(terminalCanvasSize(9.4, 2.4)).toEqual({ width: 2048, height: 523 });
+ expect(terminalCanvasSize(4.5, 2.1)).toEqual({ width: 2048, height: 956 });
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/ScreensLayer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/effects/ScreensLayer.tsx
index 42508c845d..50fd1468d4 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/effects/ScreensLayer.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/ScreensLayer.tsx
@@ -3,17 +3,40 @@
* quad the cook exported, nudged 2 cm toward the viewer so it sits on the
* glass of the photographed monitor. Redrawn only when what it shows changes
* (and for the cursor blink), a few screens per frame at most.
+ *
+ * Two kinds of screen: a text face (a bridge console, a standby page) and a
+ * terminal face, which draws coding panes cell for cell from the IDE's own
+ * xterm buffers (lib/liveTerminals), falling back to the server's plain
+ * replay for a pane the IDE has not mounted.
*/
import { useEffect, useMemo, useRef } from "react";
import { useFrame, useThree } from "@react-three/fiber";
-import { BufferAttribute, BufferGeometry, CanvasTexture, Group, LinearFilter, Mesh, MeshBasicMaterial, SRGBColorSpace } from "three";
+import { BufferAttribute, BufferGeometry, CanvasTexture, Group, LinearFilter, Mesh, MeshBasicMaterial, Raycaster, SRGBColorSpace, Vector3, type Object3D } from "three";
+import { liveTerminal } from "@/lib/liveTerminals";
+import { themeFor } from "@/components/agentic/terminalThemes";
import type { Deck, Socket } from "../content/deck";
-import { RENDER_ORDER } from "../engine/renderOrder";
+import { BACKDROP_LAYER, RENDER_ORDER } from "../engine/renderOrder";
+import { cameraBasis } from "../engine/plateMath";
import { paintScreen, screenCanvasSize, type ScreenFace } from "./screenPainter";
+import { paintTerminalGrid, snapshotText, snapshotXterm, type GridTile, type TerminalFace, type TerminalTileFace } from "./terminalCanvas";
const LIFT_M = 0.02;
+/** Never push a screen further toward the camera than this to clear its console's occluder. */
+const MAX_CLEARANCE_M = 1.5;
const BLINK_MS = 560;
const MAX_PAINTS_PER_FRAME = 3;
+/** A terminal screen repaints at most this often, however fast its pane streams. */
+const TERMINAL_MIN_MS = 90;
+/** Canvas pixels per metre for terminal screens, bounded by the texture limits below. */
+const TERMINAL_PX_PER_M = 820;
+const TERMINAL_MAX_W = 2048, TERMINAL_MAX_H = 1024;
+const TERMINAL_BLEED_M = 0.015;
+
+export type ScreenView = ScreenFace | TerminalFace;
+
+export function isTerminalFace(view: ScreenView): view is TerminalFace {
+ return (view as TerminalFace).kind === "terminals";
+}
interface Screen {
socket: Socket;
@@ -21,19 +44,45 @@ interface Screen {
ctx: CanvasRenderingContext2D;
texture: CanvasTexture;
/** The face last read for this screen, and the text it stands for (built once per new face, not per frame). */
- face: ScreenFace | null;
+ face: ScreenView | null;
content: string;
/** What the canvas shows now. */
painted: string;
paintedBlink: boolean;
+ paintedAt: number;
+ /** Where the quad sits in the plate view: slid out of its console's occluder toward the plate camera. */
+ plateOffset: Vector3;
}
-/** Everything a face draws except the cursor blink. */
-function faceContent(face: ScreenFace): string {
+/** Everything a text face draws except the cursor blink. */
+function faceContent(face: ScreenView): string {
+ if (isTerminalFace(face)) return face.tiles.map((t) => `${t.header.tone}|${t.header.title}|${t.header.status}`).join("\n");
return `${face.tone}|${face.title}|${face.status}|${face.lines.join("\n")}`;
}
-function screenQuad(socket: Socket): BufferGeometry | null {
+/** What a terminal tile shows right now: the live buffer's version, or the replay's stamp. */
+function tileStamp(tile: TerminalTileFace): string {
+ const live = liveTerminal(tile.workspaceId, tile.names);
+ if (live) return `L${live.version}`;
+ const f = tile.fallback;
+ return f ? `F${f.at}:${f.cursor?.join(",") ?? ""}` : "-";
+}
+
+function tileSnapshot(tile: TerminalTileFace): GridTile {
+ const live = liveTerminal(tile.workspaceId, tile.names);
+ if (live) return { header: tile.header, snap: snapshotXterm(live.term) };
+ if (tile.fallback) return { header: tile.header, snap: snapshotText(tile.fallback, themeFor("dark")) };
+ return { header: tile.header, snap: null };
+}
+
+/** Canvas size for a terminal screen of the given metres: sharp enough to read a pane when zoomed in. Pure. */
+export function terminalCanvasSize(widthM: number, heightM: number): { width: number; height: number } {
+ const scale = Math.min(TERMINAL_PX_PER_M, TERMINAL_MAX_W / widthM, TERMINAL_MAX_H / heightM);
+ return { width: Math.max(64, Math.round(widthM * scale)), height: Math.max(32, Math.round(heightM * scale)) };
+}
+
+/** Corners of a screen, lifted off the glass along its normal and grown by `bleed` metres on every edge. Pure. */
+export function screenCorners(socket: Socket, bleed = 0): [number, number, number][] | null {
const c = socket.corners;
if (!c || c.length !== 4) return null;
// Normal from the corners (TL, TR, BR, BL as the viewer sees them).
@@ -43,7 +92,56 @@ function screenQuad(socket: Socket): BufferGeometry | null {
const len = Math.hypot(nx, ny, nz) || 1;
// TL→TR × TL→BL points away from the viewer; flip toward them.
nx = -nx / len; ny = -ny / len; nz = -nz / len;
- const p = c.flatMap((q) => [q[0] + nx * LIFT_M, q[1] + ny * LIFT_M, q[2] + nz * LIFT_M]);
+ const ul = Math.hypot(ux, uy, uz) || 1, vl = Math.hypot(vx, vy, vz) || 1;
+ // TL, TR, BR, BL: which way each corner moves along the screen's width and height.
+ const signs = [[-1, -1], [1, -1], [1, 1], [-1, 1]];
+ return c.map((q, i): [number, number, number] => {
+ const su = (signs[i][0] * bleed) / ul, sv = (signs[i][1] * bleed) / vl;
+ return [
+ q[0] + nx * LIFT_M + ux * su + vx * sv,
+ q[1] + ny * LIFT_M + uy * su + vy * sv,
+ q[2] + nz * LIFT_M + uz * su + vz * sv,
+ ];
+ });
+}
+
+/**
+ * How far a screen (TL, TR, BR, BL corners) must move toward the camera to
+ * leave every occluder it sits inside. The cook's console occluders enclose
+ * their monitor glass, so a screen on the glass would be hidden by its own
+ * console. The plate camera is orthographic: sliding the quad along the view
+ * ray changes its depth, never where it lands in the picture. The occluder
+ * is not a plain box around the glass, so a grid of points is tested, not
+ * just the corners.
+ */
+export function occluderClearance(corners: readonly [number, number, number][], toCamera: Vector3, occluders: Object3D | undefined): number {
+ if (!occluders || corners.length !== 4) return 0;
+ const ray = new Raycaster();
+ ray.layers.set(BACKDROP_LAYER);
+ ray.far = MAX_CLEARANCE_M;
+ let lift = 0;
+ const normal = new Vector3();
+ const [tl, tr, , bl] = corners.map((c) => new Vector3(c[0], c[1], c[2]));
+ const across = tr.clone().sub(tl), down = bl.clone().sub(tl);
+ const steps = 6;
+ for (let i = 0; i <= steps; i += 1) for (let j = 0; j <= steps; j += 1) {
+ const point = tl.clone().addScaledVector(across, i / steps).addScaledVector(down, j / steps);
+ ray.set(point, toCamera);
+ // The cook merges every occluder box into one mesh, so count faces, not objects:
+ // a face whose outward normal points toward the camera is a way out of a box.
+ // The corner is clear after the last exit that comes before any entry.
+ for (const hit of ray.intersectObject(occluders, true)) {
+ if (!hit.face) continue;
+ normal.copy(hit.face.normal).transformDirection(hit.object.matrixWorld);
+ if (normal.dot(toCamera) <= 0) break;
+ lift = Math.max(lift, hit.distance);
+ }
+ }
+ return lift > 0 ? lift + 0.015 : 0;
+}
+
+function screenQuad(corners: readonly [number, number, number][]): BufferGeometry {
+ const p = corners.flatMap((q) => [q[0], q[1], q[2]]);
const g = new BufferGeometry();
g.setAttribute("position", new BufferAttribute(new Float32Array(p), 3));
g.setAttribute("uv", new BufferAttribute(new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]), 2));
@@ -51,20 +149,40 @@ function screenQuad(socket: Socket): BufferGeometry | null {
return g;
}
-export function ScreensLayer({ deck, faces }: { deck: Deck; faces: ReadonlyMap<string, ScreenFace> }) {
+export function ScreensLayer({ deck, faces, terminalSockets, plateView = true }: {
+ deck: Deck;
+ faces: ReadonlyMap<string, ScreenView>;
+ /** Sockets that show terminals and get a sharper canvas. */
+ terminalSockets: ReadonlySet<string>;
+ /**
+ * Is the photographed plate the view on screen? Only there is a screen slid out of its
+ * occluder; the eye-level view renders the same scene in perspective, where it stays on the glass.
+ */
+ plateView?: boolean;
+}) {
const scene = useThree((s) => s.scene);
+ const plateViewRef = useRef(plateView);
+ plateViewRef.current = plateView;
const facesRef = useRef(faces);
facesRef.current = faces;
const group = useMemo(() => new Group(), []);
+ // Where the next frame starts looking, so a busy screen early in the list never starves the rest.
+ const startRef = useRef(0);
const screens = useMemo(() => {
const out: Screen[] = [];
for (const socket of deck.sockets) {
if (socket.kind !== "screen" || !socket.size) continue;
- const geometry = screenQuad(socket);
- if (!geometry) continue;
+ // A terminal covers the photographed glass edge to edge; the cooked socket is a little inset.
+ const corners = screenCorners(socket, terminalSockets.has(socket.id) ? TERMINAL_BLEED_M : 0);
+ if (!corners) continue;
+ const toCamera = new Vector3(...cameraBasis(deck.camera.pitchDeg).dir).negate().normalize();
+ const geometry = screenQuad(corners);
+ const plateOffset = toCamera.clone().multiplyScalar(occluderClearance(corners, toCamera, scene.getObjectByName("occluders")));
const canvas = document.createElement("canvas");
- const size = screenCanvasSize(socket.size[0], socket.size[1]);
+ const size = terminalSockets.has(socket.id)
+ ? terminalCanvasSize(socket.size[0], socket.size[1])
+ : screenCanvasSize(socket.size[0], socket.size[1]);
canvas.width = size.width;
canvas.height = size.height;
const ctx = canvas.getContext("2d");
@@ -73,14 +191,15 @@ export function ScreensLayer({ deck, faces }: { deck: Deck; faces: ReadonlyMap<s
texture.colorSpace = SRGBColorSpace;
texture.minFilter = LinearFilter;
texture.generateMipmaps = false;
+ texture.anisotropy = 8;
const material = new MeshBasicMaterial({ map: texture, toneMapped: false, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -2 });
const mesh = new Mesh(geometry, material);
mesh.renderOrder = RENDER_ORDER.screen;
mesh.name = `screen:${socket.id}`;
- out.push({ socket, mesh, ctx, texture, face: null, content: "", painted: "", paintedBlink: false });
+ out.push({ socket, mesh, ctx, texture, face: null, content: "", painted: "", paintedBlink: false, paintedAt: 0, plateOffset });
}
return out;
- }, [deck]);
+ }, [deck, terminalSockets, scene]);
useEffect(() => {
for (const s of screens) group.add(s.mesh);
@@ -97,22 +216,38 @@ export function ScreensLayer({ deck, faces }: { deck: Deck; faces: ReadonlyMap<s
}, [screens, group, scene]);
useFrame(() => {
- const blinkOn = Math.floor(performance.now() / BLINK_MS) % 2 === 0;
- let budget = MAX_PAINTS_PER_FRAME;
+ const now = performance.now();
+ const plate = plateViewRef.current;
for (const s of screens) {
- if (budget === 0) break;
+ if (plate) s.mesh.position.copy(s.plateOffset); else s.mesh.position.set(0, 0, 0);
+ }
+ const blinkOn = Math.floor(now / BLINK_MS) % 2 === 0;
+ let budget = MAX_PAINTS_PER_FRAME;
+ const n = screens.length;
+ for (let k = 0; k < n; k += 1) {
+ const s = screens[(startRef.current + k) % n];
const face = facesRef.current.get(s.socket.id);
if (!face) { s.mesh.visible = false; continue; }
s.mesh.visible = true;
// The feed hands over a new face object only when something changed; the same one is not re-read.
if (face !== s.face) { s.face = face; s.content = faceContent(face); }
- const blink = face.cursor && blinkOn;
- if (s.content === s.painted && blink === s.paintedBlink) continue;
- paintScreen(s.ctx, face, blinkOn);
+ if (isTerminalFace(face)) {
+ // Live buffers change without React knowing: their version is part of what is shown.
+ const shown = `${s.content}\n${face.tiles.map(tileStamp).join(",")}`;
+ if (shown === s.painted || now - s.paintedAt < TERMINAL_MIN_MS) continue;
+ paintTerminalGrid(s.ctx, face.tiles.map(tileSnapshot), true);
+ s.painted = shown;
+ s.paintedAt = now;
+ } else {
+ const blink = face.cursor && blinkOn;
+ if (s.content === s.painted && blink === s.paintedBlink) continue;
+ paintScreen(s.ctx, face, blinkOn);
+ s.painted = s.content;
+ s.paintedBlink = blink;
+ }
s.texture.needsUpdate = true;
- s.painted = s.content;
- s.paintedBlink = blink;
budget -= 1;
+ if (budget === 0) { startRef.current = (startRef.current + k + 1) % n; break; }
}
});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/terminalCanvas.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/effects/terminalCanvas.test.ts
new file mode 100644
index 0000000000..5632d66c23
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/terminalCanvas.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+import { Terminal } from "@xterm/xterm";
+import { drawGlyph, fitTerminal, gridShape, opaque, paletteFor, shownRows, snapshotText, snapshotXterm, type TermSnapshot } from "./terminalCanvas";
+
+function write(term: Terminal, data: string): Promise<void> {
+ return new Promise((resolve) => term.write(data, resolve));
+}
+
+describe("terminal palette", () => {
+ it("uses the theme's 16 colours and the standard cube and greys", () => {
+ const p = paletteFor({ red: "#ff0000" });
+ expect(p).toHaveLength(256);
+ expect(p[1]).toBe("#ff0000");
+ expect(p[16]).toBe("#000000");
+ expect(p[231]).toBe("#ffffff");
+ expect(p[232]).toBe("#080808");
+ });
+
+ it("drops the alpha of a glass ground", () => {
+ expect(opaque("rgba(18, 20, 26, 0)", "#000")).toBe("#12141a");
+ expect(opaque("#fcfbf8", "#000")).toBe("#fcfbf8");
+ expect(opaque(undefined, "#121212")).toBe("#121212");
+ });
+});
+
+describe("xterm snapshot", () => {
+ it("copies cells with their colours, cell for cell", async () => {
+ const term = new Terminal({ cols: 20, rows: 4, allowProposedApi: true, theme: { foreground: "#dddddd", background: "rgba(1, 2, 3, 0)", red: "#aa0000", brightRed: "#ff5555" } });
+ await write(term, "\x1b[31mred\x1b[0m ok\r\n\x1b[1;31mbold\x1b[0m\r\n\x1b[38;2;1;2;3mrgb\x1b[0m");
+ const snap = snapshotXterm(term);
+ expect(snap.cols).toBe(20);
+ expect(snap.ground).toBe("#010203");
+ const [first, second, third] = snap.lines;
+ expect(first[0]).toMatchObject({ col: 0, text: "red", fg: "#aa0000" });
+ expect(first.map((r) => r.text).join("")).toMatch(/^red ok/);
+ expect(first[1]).toMatchObject({ col: 3, fg: "#dddddd" });
+ // Bold low colours draw bright, like xterm.
+ expect(second[0]).toMatchObject({ text: "bold", fg: "#ff5555", bold: true });
+ expect(third[0]).toMatchObject({ text: "rgb", fg: "#010203" });
+ term.dispose();
+ });
+
+ it("keeps a wide glyph as one run of two cells", async () => {
+ const term = new Terminal({ cols: 10, rows: 2, allowProposedApi: true });
+ await write(term, "a中b");
+ const runs = snapshotXterm(term).lines[0];
+ const wide = runs.find((r) => r.text === "中");
+ expect(wide).toMatchObject({ col: 1, cells: 2 });
+ expect(runs.find((r) => r.text.startsWith("b"))).toMatchObject({ col: 3 });
+ term.dispose();
+ });
+});
+
+describe("text fallback and layout", () => {
+ const snap: TermSnapshot = snapshotText({ cols: 80, lines: ["one", " two spaced", "", "", ""], cursor: null }, { foreground: "#eee" });
+
+ it("keeps the server replay's spacing", () => {
+ expect(snap.lines[1][0].text).toBe(" two spaced");
+ expect(snap.lines[2]).toEqual([]);
+ });
+
+ it("shows the bottom block that fits, ending at the last row with content", () => {
+ expect(shownRows(snap, 1)).toEqual({ first: 1, end: 2 });
+ expect(shownRows(snap, 10)).toEqual({ first: 0, end: 5 });
+ expect(shownRows({ ...snap, cursor: [3, 0] }, 2)).toEqual({ first: 2, end: 4 });
+ });
+
+ it("fits the terminal's width and counts the rows that fit", () => {
+ const f = fitTerminal(80, 960, 400, 0.6);
+ expect(f.font).toBe(20);
+ expect(f.fit).toBe(Math.floor(400 / (20 * 1.22)));
+ });
+
+ it("chooses the grid that gives each pane the largest text", () => {
+ expect(gridShape(1, 1000, 500, 0)).toEqual({ cols: 1, rows: 1 });
+ expect(gridShape(4, 2048, 956, 10)).toEqual({ cols: 2, rows: 2 });
+ expect(gridShape(6, 2048, 523, 8)).toEqual({ cols: 6, rows: 1 });
+ });
+});
+
+describe("box and block glyphs", () => {
+ function recorder() {
+ const rects: number[][] = [];
+ const ctx = { fillRect: (...a: number[]) => rects.push(a), beginPath() {}, moveTo() {}, arcTo() {}, lineTo() {}, stroke() {}, globalAlpha: 1, lineWidth: 1 };
+ return { ctx: ctx as unknown as CanvasRenderingContext2D, rects };
+ }
+
+ it("draws a horizontal rule edge to edge, so neighbouring cells join", () => {
+ const { ctx, rects } = recorder();
+ expect(drawGlyph(ctx, "─", 10, 0, 8, 16)).toBe(true);
+ const left = Math.min(...rects.map((r) => r[0])), right = Math.max(...rects.map((r) => r[0] + r[2]));
+ expect(left).toBe(10);
+ expect(right).toBe(18);
+ });
+
+ it("fills block quadrants", () => {
+ const { ctx, rects } = recorder();
+ drawGlyph(ctx, "▛", 0, 0, 8, 16);
+ expect(rects).toHaveLength(3);
+ expect(drawGlyph(ctx, "a", 0, 0, 8, 16)).toBe(false);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/terminalCanvas.ts b/dodaios/ui/web/frontend/src/components/society/verse/effects/terminalCanvas.ts
new file mode 100644
index 0000000000..935f29ca9f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/terminalCanvas.ts
@@ -0,0 +1,440 @@
+/**
+ * A coding pane's terminal drawn onto a ship monitor, cell for cell.
+ *
+ * `snapshotXterm` copies the live screen out of the pane's own xterm buffer
+ * (the one the IDE draws), with every cell's colours and attributes resolved
+ * against the pane's theme. `snapshotText` turns the server's plain-text
+ * replay into the same shape for a pane the IDE has not mounted. The painters
+ * then lay one or several snapshots onto a canvas: the width of the terminal
+ * fills the tile, the bottom block of rows that fits is shown (TUIs keep their
+ * prompt and newest output there), and box-drawing and block characters are
+ * drawn as geometry, the way xterm does, so frames join without gaps.
+ *
+ * Pure apart from the canvas it is handed.
+ */
+import type { IBufferCell, ITheme, Terminal } from "@xterm/xterm";
+import { TERMINAL_FONT_STACK } from "@/lib/terminalFont";
+import type { ScreenTone } from "./screenPainter";
+
+/** A run of neighbouring cells sharing one look. */
+export interface CellRun {
+ col: number;
+ /** Cells covered; a wide glyph counts two. */
+ cells: number;
+ text: string;
+ fg: string;
+ /** Null: the terminal's own ground. */
+ bg: string | null;
+ bold: boolean;
+ italic: boolean;
+ underline: boolean;
+ strike: boolean;
+}
+
+export interface TermSnapshot {
+ cols: number;
+ /** Rows of the visible screen, top first. */
+ lines: CellRun[][];
+ /** `[row, col]` of a visible cursor, or null. */
+ cursor: [number, number] | null;
+ ground: string;
+ ink: string;
+ cursorColor: string;
+}
+
+const ANSI_KEYS = [
+ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white",
+ "brightBlack", "brightRed", "brightGreen", "brightYellow", "brightBlue", "brightMagenta", "brightCyan", "brightWhite",
+] as const;
+/** xterm's own defaults, for a theme that leaves a slot out. */
+const ANSI_DEFAULT = [
+ "#2e3436", "#cc0000", "#4e9a06", "#c4a000", "#3465a4", "#75507b", "#06989a", "#d3d7cf",
+ "#555753", "#ef2929", "#8ae234", "#fce94f", "#729fcf", "#ad7fa8", "#34e2e2", "#eeeeec",
+];
+
+function hex2(n: number): string {
+ return n.toString(16).padStart(2, "0");
+}
+
+/** The 256-colour palette for a theme: its 16 ANSI slots, then the standard cube and greys. Pure. */
+export function paletteFor(theme: ITheme): string[] {
+ const out: string[] = ANSI_KEYS.map((k, i) => theme[k] ?? ANSI_DEFAULT[i]);
+ const steps = [0, 95, 135, 175, 215, 255];
+ for (let r = 0; r < 6; r += 1) {
+ for (let g = 0; g < 6; g += 1) {
+ for (let b = 0; b < 6; b += 1) out.push(`#${hex2(steps[r])}${hex2(steps[g])}${hex2(steps[b])}`);
+ }
+ }
+ for (let i = 0; i < 24; i += 1) { const v = 8 + i * 10; out.push(`#${hex2(v)}${hex2(v)}${hex2(v)}`); }
+ const extended = theme.extendedAnsi ?? [];
+ extended.forEach((c, i) => { if (c && 16 + i < 256) out[16 + i] = c; });
+ return out;
+}
+
+/** A CSS colour with its alpha dropped, so a glass pane's ground becomes a solid one. Pure. */
+export function opaque(color: string | undefined, fallback: string): string {
+ if (!color) return fallback;
+ const m = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i.exec(color);
+ if (m) return `#${hex2(+m[1])}${hex2(+m[2])}${hex2(+m[3])}`;
+ if (/^#[0-9a-f]{8}$/i.test(color)) return color.slice(0, 7);
+ return color;
+}
+
+function rgb(n: number): string {
+ return `#${hex2((n >> 16) & 255)}${hex2((n >> 8) & 255)}${hex2(n & 255)}`;
+}
+
+/** Mix two #rrggbb colours: the terminal's dim attribute. */
+function mix(a: string, b: string, t: number): string {
+ const pa = parseInt(a.slice(1, 7), 16), pb = parseInt(b.slice(1, 7), 16);
+ if (Number.isNaN(pa) || Number.isNaN(pb)) return a;
+ const ch = (s: number) => Math.round(((pa >> s) & 255) * (1 - t) + ((pb >> s) & 255) * t);
+ return `#${hex2(ch(16))}${hex2(ch(8))}${hex2(ch(0))}`;
+}
+
+/** The cells of one buffer line as runs, colours resolved. */
+function lineRuns(cellAt: (x: number) => IBufferCell | undefined, cols: number, palette: string[], ink: string, ground: string): CellRun[] {
+ const runs: CellRun[] = [];
+ let cur: CellRun | null = null;
+ for (let x = 0; x < cols; x += 1) {
+ const cell = cellAt(x);
+ if (!cell) break;
+ const width = cell.getWidth();
+ if (width === 0) continue; // the second half of a wide glyph
+ const bold = cell.isBold() !== 0;
+ let fg: string;
+ if (cell.isFgRGB()) fg = rgb(cell.getFgColor());
+ else if (cell.isFgPalette()) {
+ let idx = cell.getFgColor();
+ // xterm's drawBoldTextInBrightColors default.
+ if (bold && idx < 8) idx += 8;
+ fg = palette[idx] ?? ink;
+ } else fg = ink;
+ let bg: string | null = null;
+ if (cell.isBgRGB()) bg = rgb(cell.getBgColor());
+ else if (cell.isBgPalette()) bg = palette[cell.getBgColor()] ?? null;
+ if (cell.isInverse()) { const f = fg; fg = bg ?? ground; bg = f; }
+ if (cell.isDim()) fg = mix(fg, bg ?? ground, 0.45);
+ const chars = cell.isInvisible() ? " " : (cell.getChars() || " ");
+ const italic = cell.isItalic() !== 0, underline = cell.isUnderline() !== 0, strike = cell.isStrikethrough() !== 0;
+ if (cur && width === 1 && cur.fg === fg && cur.bg === bg && cur.bold === bold && cur.italic === italic
+ && cur.underline === underline && cur.strike === strike && cur.col + cur.cells === x) {
+ cur.text += chars;
+ cur.cells += 1;
+ } else {
+ cur = { col: x, cells: width, text: chars, fg, bg, bold, italic, underline, strike };
+ runs.push(cur);
+ // A wide glyph stands alone, so every run is either one wide glyph or one cell per character.
+ if (width !== 1) cur = null;
+ }
+ }
+ return runs;
+}
+
+/** Is xterm's cursor hidden (DECTCEM)? Read defensively from the private core. */
+function cursorHidden(term: Terminal): boolean {
+ const core = (term as unknown as { _core?: { coreService?: { isCursorHidden?: boolean } } })._core;
+ return core?.coreService?.isCursorHidden ?? true;
+}
+
+/** The live screen of a pane's xterm, read-only. */
+export function snapshotXterm(term: Terminal): TermSnapshot {
+ const theme = term.options.theme ?? {};
+ const ground = opaque(theme.background, "#121212");
+ const ink = theme.foreground ?? "#e6e6e6";
+ const palette = paletteFor(theme);
+ const buffer = term.buffer.active;
+ const cols = term.cols;
+ const lines: CellRun[][] = [];
+ const reuse = buffer.getNullCell();
+ for (let y = 0; y < term.rows; y += 1) {
+ const line = buffer.getLine(buffer.baseY + y);
+ lines.push(line ? lineRuns((x) => line.getCell(x, reuse), cols, palette, ink, ground) : []);
+ }
+ const cursor: [number, number] | null = cursorHidden(term) ? null : [buffer.cursorY, buffer.cursorX];
+ return { cols, lines, cursor, ground, ink, cursorColor: theme.cursor ?? ink };
+}
+
+/** The server's plain replay of a pane, in the same shape (one colour, layout intact). Pure. */
+export function snapshotText(screen: { cols: number; lines: readonly string[]; cursor: [number, number] | null }, theme: ITheme): TermSnapshot {
+ const ground = opaque(theme.background, "#121212");
+ const ink = theme.foreground ?? "#e6e6e6";
+ const lines = screen.lines.map((text): CellRun[] => (text
+ ? [{ col: 0, cells: [...text].length, text, fg: ink, bg: null, bold: false, italic: false, underline: false, strike: false }]
+ : []));
+ return { cols: Math.max(1, screen.cols), lines, cursor: screen.cursor, ground, ink, cursorColor: theme.cursor ?? ink };
+}
+
+function runText(run: CellRun): string {
+ return run.text;
+}
+
+/**
+ * The rows to show when only `fit` rows fit: the block ending at the last
+ * row with content, or at the cursor row if that is lower. Pure.
+ */
+export function shownRows(snap: TermSnapshot, fit: number): { first: number; end: number } {
+ let end = snap.lines.length;
+ while (end > 0 && !snap.lines[end - 1].some((r) => runText(r).trim() || r.bg)) end -= 1;
+ if (snap.cursor && snap.cursor[0] + 1 > end) end = snap.cursor[0] + 1;
+ end = Math.max(end, Math.min(snap.lines.length, Math.max(1, fit)));
+ return { first: Math.max(0, end - Math.max(1, fit)), end };
+}
+
+// ── Box drawing and blocks, as geometry ──────────────────────────────────
+
+/** Arms of a box-drawing glyph: left, right, up, down; 1 light, 2 heavy, 3 double. */
+const BOX: Record<string, [number, number, number, number]> = {
+ "─": [1, 1, 0, 0], "━": [2, 2, 0, 0], "│": [0, 0, 1, 1], "┃": [0, 0, 2, 2],
+ "┌": [0, 1, 0, 1], "┐": [1, 0, 0, 1], "└": [0, 1, 1, 0], "┘": [1, 0, 1, 0],
+ "╭": [0, 1, 0, 1], "╮": [1, 0, 0, 1], "╰": [0, 1, 1, 0], "╯": [1, 0, 1, 0],
+ "┏": [0, 2, 0, 2], "┓": [2, 0, 0, 2], "┗": [0, 2, 2, 0], "┛": [2, 0, 2, 0],
+ "├": [0, 1, 1, 1], "┤": [1, 0, 1, 1], "┬": [1, 1, 0, 1], "┴": [1, 1, 1, 0], "┼": [1, 1, 1, 1],
+ "═": [3, 3, 0, 0], "║": [0, 0, 3, 3], "╔": [0, 3, 0, 3], "╗": [3, 0, 0, 3], "╚": [0, 3, 3, 0], "╝": [3, 0, 3, 0],
+ "╴": [1, 0, 0, 0], "╶": [0, 1, 0, 0], "╵": [0, 0, 1, 0], "╷": [0, 0, 0, 1],
+};
+const ROUNDED = new Set(["╭", "╮", "╰", "╯"]);
+/** Quadrants lit: top-left, top-right, bottom-left, bottom-right. */
+const QUAD: Record<string, [number, number, number, number]> = {
+ "▘": [1, 0, 0, 0], "▝": [0, 1, 0, 0], "▖": [0, 0, 1, 0], "▗": [0, 0, 0, 1],
+ "▀": [1, 1, 0, 0], "▄": [0, 0, 1, 1], "▌": [1, 0, 1, 0], "▐": [0, 1, 0, 1],
+ "▚": [1, 0, 0, 1], "▞": [0, 1, 1, 0], "▙": [1, 0, 1, 1], "▛": [1, 1, 1, 0],
+ "▜": [1, 1, 0, 1], "▟": [0, 1, 1, 1], "█": [1, 1, 1, 1],
+};
+const SHADE: Record<string, number> = { "░": 0.25, "▒": 0.5, "▓": 0.75 };
+
+/** Draw `ch` as geometry if it is a box or block glyph; false when it is not one. */
+export function drawGlyph(ctx: CanvasRenderingContext2D, ch: string, x: number, y: number, w: number, h: number): boolean {
+ const quad = QUAD[ch];
+ if (quad) {
+ const hw = w / 2, hh = h / 2;
+ if (quad[0]) ctx.fillRect(x, y, hw, hh);
+ if (quad[1]) ctx.fillRect(x + hw, y, w - hw, hh);
+ if (quad[2]) ctx.fillRect(x, y + hh, hw, h - hh);
+ if (quad[3]) ctx.fillRect(x + hw, y + hh, w - hw, h - hh);
+ return true;
+ }
+ const shade = SHADE[ch];
+ if (shade) {
+ const a = ctx.globalAlpha;
+ ctx.globalAlpha = a * shade;
+ ctx.fillRect(x, y, w, h);
+ ctx.globalAlpha = a;
+ return true;
+ }
+ const arms = BOX[ch];
+ if (!arms) return false;
+ const light = Math.max(1, Math.round(w / 8));
+ const cx = x + w / 2, cy = y + h / 2;
+ if (ROUNDED.has(ch)) {
+ const r = Math.min(w, h) / 2;
+ ctx.lineWidth = light;
+ ctx.beginPath();
+ const [l, , u] = arms;
+ const ex = l ? x : x + w, ey = u ? y : y + h;
+ ctx.moveTo(ex, cy);
+ ctx.arcTo(cx, cy, cx, ey, r);
+ ctx.lineTo(cx, ey);
+ ctx.stroke();
+ return true;
+ }
+ const thick = (k: number) => (k === 2 ? light * 2 : light);
+ const [l, rr, u, d] = arms;
+ const hline = (x0: number, x1: number, k: number) => {
+ if (k === 3) { ctx.fillRect(x0, cy - light * 1.5, x1 - x0, light); ctx.fillRect(x0, cy + light * 0.5, x1 - x0, light); }
+ else ctx.fillRect(x0, cy - thick(k) / 2, x1 - x0, thick(k));
+ };
+ const vline = (y0: number, y1: number, k: number) => {
+ if (k === 3) { ctx.fillRect(cx - light * 1.5, y0, light, y1 - y0); ctx.fillRect(cx + light * 0.5, y0, light, y1 - y0); }
+ else ctx.fillRect(cx - thick(k) / 2, y0, thick(k), y1 - y0);
+ };
+ const ov = light; // overlap at the centre so the arms meet
+ if (l) hline(x, cx + (rr ? 0 : ov), l);
+ if (rr) hline(cx - (l ? 0 : ov), x + w, rr);
+ if (u) vline(y, cy + (d ? 0 : ov), u);
+ if (d) vline(cy - (u ? 0 : ov), y + h, d);
+ return true;
+}
+
+// ── Painting ─────────────────────────────────────────────────────────────
+
+export const LINE_RATIO = 1.22;
+const MIN_FONT = 5;
+const MAX_FONT = 30;
+
+const TONE_DOT: Readonly<Record<ScreenTone, string>> = { live: "#4ade80", attention: "#fbbf24", fault: "#f87171", standby: "#6b7280" };
+const SANS = "Inter, system-ui, -apple-system, 'Segoe UI', sans-serif";
+
+/** Monospace advance per pixel of font size, measured once per context. */
+const ratioCache = new WeakMap<CanvasRenderingContext2D, number>();
+function charRatio(ctx: CanvasRenderingContext2D): number {
+ let r = ratioCache.get(ctx);
+ if (r === undefined) {
+ ctx.font = `500 100px ${TERMINAL_FONT_STACK}`;
+ r = (ctx.measureText("MMMMMMMMMM").width / 10) / 100 || 0.6;
+ ratioCache.set(ctx, r);
+ }
+ return r;
+}
+
+export interface TileHeader {
+ title: string;
+ status: string;
+ tone: ScreenTone;
+}
+
+/** Font and rows for a terminal `cols` wide in a body `w` x `h`. Pure. */
+export function fitTerminal(cols: number, w: number, h: number, ratio: number): { font: number; cellW: number; lineH: number; fit: number } {
+ const font = Math.max(MIN_FONT, Math.min(MAX_FONT, w / (Math.max(20, cols) * ratio)));
+ const cellW = font * ratio;
+ const lineH = font * LINE_RATIO;
+ return { font, cellW, lineH, fit: Math.max(1, Math.floor(h / lineH)) };
+}
+
+/** One pane: a slim title row over its terminal, inside the rectangle. */
+export function paintTerminalTile(
+ ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number,
+ header: TileHeader, snap: TermSnapshot | null, blinkOn: boolean,
+): void {
+ const ground = snap?.ground ?? "#121212";
+ const ink = snap?.ink ?? "#e6e6e6";
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(x, y, w, h);
+ ctx.clip();
+ ctx.fillStyle = ground;
+ ctx.fillRect(x, y, w, h);
+ // Title row: status dot, name, status word.
+ const headH = Math.max(12, Math.min(48, Math.round(h * 0.07)));
+ ctx.fillStyle = mix(ground, ink, 0.07);
+ ctx.fillRect(x, y, w, headH);
+ ctx.fillStyle = mix(ground, ink, 0.18);
+ ctx.fillRect(x, y + headH - 1, w, 1);
+ const hf = Math.round(headH * 0.56);
+ ctx.textBaseline = "middle";
+ ctx.fillStyle = TONE_DOT[header.tone];
+ ctx.beginPath();
+ ctx.arc(x + headH * 0.5, y + headH / 2, Math.max(2, headH * 0.16), 0, Math.PI * 2);
+ ctx.fill();
+ ctx.font = `600 ${hf}px ${SANS}`;
+ const status = header.status;
+ const statusW = ctx.measureText(status).width;
+ ctx.textAlign = "right";
+ ctx.fillStyle = mix(ink, ground, 0.35);
+ ctx.fillText(status, x + w - headH * 0.4, y + headH / 2 + 1);
+ ctx.textAlign = "left";
+ ctx.fillStyle = ink;
+ const titleMax = w - headH - statusW - headH * 0.8;
+ let title = header.title;
+ while (title.length > 1 && ctx.measureText(title).width > titleMax) title = title.slice(0, -2);
+ if (title !== header.title) title = `${title}…`;
+ ctx.fillText(title, x + headH, y + headH / 2 + 1);
+
+ const pad = Math.max(2, Math.round(Math.min(w, h) * 0.015));
+ const bx = x + pad, by = y + headH + pad, bw = w - 2 * pad, bh = h - headH - 2 * pad;
+ if (!snap) {
+ ctx.fillStyle = mix(ground, ink, 0.25);
+ ctx.font = `500 ${Math.round(Math.min(bh * 0.3, bw * 0.12))}px ${TERMINAL_FONT_STACK}`;
+ ctx.textAlign = "center";
+ ctx.fillText(">_", x + w / 2, by + bh / 2);
+ ctx.restore();
+ return;
+ }
+ const ratio = charRatio(ctx);
+ const { font, cellW, lineH, fit } = fitTerminal(snap.cols, bw, bh, ratio);
+ const { first, end } = shownRows(snap, fit);
+ const top = by;
+ ctx.textBaseline = "middle";
+ ctx.textAlign = "left";
+ for (let row = first; row < end; row += 1) {
+ const ry = top + (row - first) * lineH;
+ for (const run of snap.lines[row] ?? []) {
+ if (!run.bg) continue;
+ ctx.fillStyle = run.bg;
+ ctx.fillRect(bx + run.col * cellW, ry, run.cells * cellW + 0.5, lineH + 0.5);
+ }
+ for (const run of snap.lines[row] ?? []) {
+ if (!run.text.trim()) continue;
+ ctx.fillStyle = run.fg;
+ ctx.strokeStyle = run.fg;
+ ctx.font = `${run.italic ? "italic " : ""}${run.bold ? 700 : 500} ${font}px ${TERMINAL_FONT_STACK}`;
+ const rx = bx + run.col * cellW;
+ const chars = [...run.text];
+ const perCell = chars.length === run.cells;
+ // One fillText per run when the font keeps to the grid; cell by cell otherwise.
+ const plain = perCell && !chars.some((ch) => BOX[ch] || QUAD[ch] || SHADE[ch])
+ && Math.abs(ctx.measureText(run.text).width - run.cells * cellW) < cellW * 0.25;
+ if (plain) ctx.fillText(run.text, rx, ry + lineH / 2);
+ else {
+ let col = 0;
+ for (const ch of chars) {
+ const step = perCell ? 1 : run.cells;
+ const cx = rx + col * cellW;
+ if (!drawGlyph(ctx, ch, cx, ry, cellW * step, lineH) && ch !== " ") ctx.fillText(ch, cx, ry + lineH / 2);
+ col += step;
+ }
+ }
+ if (run.underline) ctx.fillRect(rx, ry + lineH - Math.max(1, font / 12), run.cells * cellW, Math.max(1, font / 12));
+ if (run.strike) ctx.fillRect(rx, ry + lineH / 2, run.cells * cellW, Math.max(1, font / 12));
+ }
+ }
+ if (snap.cursor && blinkOn) {
+ const [cr, cc] = snap.cursor;
+ if (cr >= first && cr < end) {
+ ctx.fillStyle = snap.cursorColor;
+ ctx.fillRect(bx + cc * cellW, top + (cr - first) * lineH + 1, Math.max(1, cellW * 0.15), lineH - 2);
+ }
+ }
+ ctx.restore();
+}
+
+/** Columns x rows for `n` tiles in a `w` x `h` screen, so each terminal gets the largest text. Pure. */
+export function gridShape(n: number, w: number, h: number, gap: number): { cols: number; rows: number } {
+ let best = { cols: 1, rows: Math.max(1, n), score: -1 };
+ for (let cols = 1; cols <= Math.max(1, n); cols += 1) {
+ const rows = Math.ceil(n / cols);
+ const tw = (w - gap * (cols + 1)) / cols, th = (h - gap * (rows + 1)) / rows;
+ // A coding pane is about 80 x 30: score by the font that such a terminal gets.
+ const score = Math.min(tw / (80 * 0.6), th / (30 * LINE_RATIO));
+ if (score > best.score) best = { cols, rows, score };
+ }
+ return { cols: best.cols, rows: best.rows };
+}
+
+export interface GridTile {
+ header: TileHeader;
+ snap: TermSnapshot | null;
+}
+
+/** All panes on one screen, in a grid; a single pane fills the screen. */
+export function paintTerminalGrid(ctx: CanvasRenderingContext2D, tiles: readonly GridTile[], blinkOn: boolean, ground = "#0b0c0f"): void {
+ const { width: w, height: h } = ctx.canvas;
+ ctx.fillStyle = ground;
+ ctx.fillRect(0, 0, w, h);
+ if (tiles.length === 0) return;
+ const gap = tiles.length === 1 ? 0 : Math.max(4, Math.round(Math.min(w, h) * 0.012));
+ const { cols, rows } = gridShape(tiles.length, w, h, gap);
+ const tw = (w - gap * (cols + 1)) / cols, th = (h - gap * (rows + 1)) / rows;
+ tiles.forEach((tile, i) => {
+ const c = i % cols, r = Math.floor(i / cols);
+ paintTerminalTile(ctx, Math.round(gap + c * (tw + gap)), Math.round(gap + r * (th + gap)), Math.floor(tw), Math.floor(th), tile.header, tile.snap, blinkOn);
+ });
+}
+
+// ── What a terminal screen shows ─────────────────────────────────────────
+
+/** A pane to draw: where its live terminal is registered, and the server's replay as a fallback. */
+export interface TerminalTileFace {
+ header: TileHeader;
+ workspaceId: string;
+ /** Names the pane may be registered under (call-sign, title). */
+ names: readonly string[];
+ /** The server's plain replay, for a pane the IDE has not mounted. */
+ fallback?: { cols: number; lines: readonly string[]; cursor: [number, number] | null; at: number };
+}
+
+/** A screen that shows one pane (a desk) or every pane (the grid screens). */
+export interface TerminalFace {
+ kind: "terminals";
+ tiles: readonly TerminalTileFace[];
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/useScreenFaces.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/effects/useScreenFaces.test.ts
new file mode 100644
index 0000000000..a0133a3bfa
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/useScreenFaces.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import type { Deck } from "../content/deck";
+import { masterScreenPanes, terminalSocketIds } from "./useScreenFaces";
+
+function deck(id: string): Deck {
+ const sockets = [
+ { id: "term_1", kind: "seat" }, { id: "term_1", kind: "screen" },
+ { id: "plot_table", kind: "screen", station: "master" }, { id: "master__2", kind: "screen", station: "master" },
+ { id: "reactor_ring__ring_1", kind: "screen" },
+ ];
+ return { id, sockets } as unknown as Deck;
+}
+
+describe("terminal screens", () => {
+ it("are the engineering desks and the master station's screens", () => {
+ expect([...terminalSocketIds(deck("engineering"))].sort()).toEqual(["master__2", "plot_table", "term_1"]);
+ expect(terminalSocketIds(deck("bridge")).size).toBe(0);
+ expect(terminalSocketIds(null).size).toBe(0);
+ });
+
+ it("show every pane on the big screens and one pane on a numbered console", () => {
+ expect(masterScreenPanes({ id: "plot_table" }, ["a", "b", "c"])).toEqual(["a", "b", "c"]);
+ expect(masterScreenPanes({ id: "master__2" }, ["a", "b", "c"])).toEqual(["b"]);
+ expect(masterScreenPanes({ id: "master__5" }, ["a"])).toEqual([]);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/useScreenFaces.ts b/dodaios/ui/web/frontend/src/components/society/verse/effects/useScreenFaces.ts
index b2f5c5f31b..de109c5b79 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/effects/useScreenFaces.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/useScreenFaces.ts
@@ -1,24 +1,31 @@
/**
* What every screen on the deck shows, from the feeds that already exist:
* a bridge console shows the tail of its officer's chat (useDeskChats), an
- * engineering terminal its pane's terminal (usePaneScreens), a briefing-room
- * wall screen the running round's transcript, any other screen a standby
- * page. Consoles belong to their officer whether or not the officer sits
- * there right now; an empty console says so.
+ * engineering terminal its pane's terminal, cell for cell (the IDE's own
+ * xterm buffer, or the server replay for a pane the IDE has not mounted),
+ * the engineering master station's big screens every coding pane in a grid,
+ * a briefing-room wall screen the running round's transcript, any other
+ * screen a standby page. Consoles belong to their officer whether or not the
+ * officer sits there right now; an empty console says so.
*/
-import { useMemo } from "react";
-import type { Deck } from "../content/deck";
+import { useMemo, useSyncExternalStore } from "react";
+import type { Deck, Socket } from "../content/deck";
+import { liveTerminal, liveTerminalsGeneration, subscribeLiveTerminals } from "@/lib/liveTerminals";
import { useDeskChats } from "../../crewFeeds/useDeskChats";
import { MAX_SCREEN_TARGETS, usePaneScreens, type PaneScreenTarget } from "../../crewFeeds/usePaneScreens";
-import { visibleRows } from "../../crewFeeds/terminalScreen";
import { useTeamwork } from "../../crewFeeds/teamwork";
import type { ChatLine } from "../../crewFeeds/deskChat";
import type { CrewLife } from "../life/useCrewLife";
import type { DutyStatus } from "../ranks";
-import type { ScreenFace, ScreenTone } from "./screenPainter";
+import type { ScreenTone } from "./screenPainter";
+import type { ScreenView } from "./ScreensLayer";
+import type { TerminalTileFace } from "./terminalCanvas";
const TONE: Readonly<Record<DutyStatus, ScreenTone>> = { working: "live", waiting: "attention", error: "fault", idle: "standby", paused: "standby" };
-const TERMINAL_ROWS = 14;
+/** The station whose screens show every coding pane. */
+const MASTER_STATION = "master";
+/** Its consoles show one pane each, in order: `master__1` the first. */
+const MASTER_CONSOLE = /^master__(\d+)$/;
function chatText(line: ChatLine): string {
switch (line.kind) {
@@ -35,9 +42,29 @@ function chunk<T>(list: readonly T[], size: number, count: number): T[][] {
return Array.from({ length: count }, (_, k) => list.slice(k * size, (k + 1) * size));
}
-export function useScreenFaces(deck: Deck | null, life: CrewLife, awake: boolean, t: (key: string) => string): ReadonlyMap<string, ScreenFace> {
+/** Sockets on `deck` that show coding-pane terminals: the engineering desks and the master station. Pure. */
+export function terminalSocketIds(deck: Deck | null): ReadonlySet<string> {
+ const out = new Set<string>();
+ if (deck?.id !== "engineering") return out;
+ const seats = new Set(deck.sockets.filter((s) => s.kind === "seat").map((s) => s.id));
+ for (const s of deck.sockets) {
+ if (s.kind === "screen" && (seats.has(s.id) || s.station === MASTER_STATION)) out.add(s.id);
+ }
+ return out;
+}
+
+/** Which panes a master-station screen shows: one for a numbered console, all of them otherwise. Pure. */
+export function masterScreenPanes<T>(socket: Pick<Socket, "id">, panes: readonly T[]): T[] {
+ const m = MASTER_CONSOLE.exec(socket.id);
+ if (!m) return [...panes];
+ const pane = panes[Number(m[1]) - 1];
+ return pane === undefined ? [] : [pane];
+}
+
+export function useScreenFaces(deck: Deck | null, life: CrewLife, awake: boolean, t: (key: string) => string): ReadonlyMap<string, ScreenView> {
// Seat id (= screen id) → its member.
const homes = useMemo(() => new Map([...life.homes].map(([member, seat]) => [seat, member])), [life.homes]);
+ const engineering = deck?.id === "engineering";
const sessions = useMemo(() => {
const m = new Map<string, string>();
@@ -50,28 +77,59 @@ export function useScreenFaces(deck: Deck | null, life: CrewLife, awake: boolean
}, [deck, homes, life.agents]);
const chats = useDeskChats(sessions, awake && deck?.id === "bridge");
+ // Panes the IDE has mounted are read straight from their terminal; only the rest are polled.
+ const liveGeneration = useSyncExternalStore(subscribeLiveTerminals, liveTerminalsGeneration);
const targets = useMemo(() => {
const list: PaneScreenTarget[] = [];
- if (deck?.id !== "engineering") return chunk(list, MAX_SCREEN_TARGETS, 2);
- for (const member of homes.values()) {
- const pane = life.panes.get(member)?.pane;
- if (pane) list.push({ agentId: member, workspaceId: pane.workspace_id, key: pane.key });
+ if (engineering) {
+ for (const [member, occupant] of life.panes) {
+ const pane = occupant.pane;
+ if (liveTerminal(pane.workspace_id, [pane.name, pane.key])) continue;
+ list.push({ agentId: member, workspaceId: pane.workspace_id, key: pane.key });
+ }
}
return chunk(list, MAX_SCREEN_TARGETS, 2);
- }, [deck, homes, life.panes]);
- const terminalsA = usePaneScreens(targets[0], awake);
- const terminalsB = usePaneScreens(targets[1], awake);
+ // liveGeneration: a pane mounting or unmounting in the IDE changes who needs polling.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [engineering, life.panes, liveGeneration]);
+ const terminalsA = usePaneScreens(targets[0], awake, false);
+ const terminalsB = usePaneScreens(targets[1], awake, false);
const rounds = useTeamwork((s) => s.rounds);
return useMemo(() => {
- const faces = new Map<string, ScreenFace>();
+ const faces = new Map<string, ScreenView>();
if (!deck) return faces;
const running = Object.values(rounds).find((r) => r.running && r.lines.length > 0);
+ const statusWord = (status: DutyStatus) => (status === "waiting" ? t("verse.screen.waiting") : status === "error" ? t("verse.screen.fault")
+ : status === "working" ? t("verse.state.working") : t("verse.screen.standby"));
+
+ const tileFor = (member: string): TerminalTileFace | null => {
+ const occupant = life.panes.get(member);
+ if (!occupant) return null;
+ const crew = life.crew.get(member);
+ const status = crew?.status ?? "idle";
+ const screen = terminalsA.get(member) ?? terminalsB.get(member);
+ return {
+ header: { title: crew?.name ?? occupant.pane.name, status: statusWord(status), tone: TONE[status] },
+ workspaceId: occupant.pane.workspace_id,
+ names: [occupant.pane.name, occupant.pane.key],
+ fallback: screen ? { cols: screen.cols, lines: screen.lines, cursor: screen.cursor, at: screen.at } : undefined,
+ };
+ };
+ const allTiles = engineering ? [...life.panes.keys()].map(tileFor).filter((x): x is TerminalTileFace => x !== null) : [];
+
for (const socket of deck.sockets) {
if (socket.kind !== "screen") continue;
const member = homes.get(socket.id);
const isConsole = deck.sockets.some((s) => s.kind === "seat" && s.id === socket.id);
+ if (engineering && socket.station === MASTER_STATION) {
+ const tiles = masterScreenPanes(socket, allTiles);
+ faces.set(socket.id, tiles.length > 0
+ ? { kind: "terminals", tiles }
+ : { tone: "standby", title: deck.name, status: t("verse.screen.standby"), lines: [], cursor: false });
+ continue;
+ }
if (!isConsole) {
// Wall screens: a running round's transcript in the briefing room, a quiet page elsewhere.
const station = socket.station ? deck.stations.find((s) => s.id === socket.station) : undefined;
@@ -90,18 +148,14 @@ export function useScreenFaces(deck: Deck | null, life: CrewLife, awake: boolean
faces.set(socket.id, { tone: "standby", title: t("verse.screen.vacant"), status: t("verse.screen.vacant"), lines: [], cursor: false });
continue;
}
- const tone = TONE[crew.status];
- const status = crew.status === "waiting" ? t("verse.screen.waiting") : crew.status === "error" ? t("verse.screen.fault")
- : crew.status === "working" ? t("verse.state.working") : t("verse.screen.standby");
- let lines: string[] = [];
- if (crew.role === "officer") lines = (chats.get(crew.id)?.lines ?? []).map(chatText);
- else {
- const screen = terminalsA.get(crew.id) ?? terminalsB.get(crew.id);
- if (screen) lines = visibleRows(screen.lines, TERMINAL_ROWS, screen.cursor).rows;
- else if (life.panes.get(crew.id)?.pane.last_prompt) lines = [`> ${life.panes.get(crew.id)?.pane.last_prompt}`];
+ if (crew.role !== "officer") {
+ const tile = tileFor(crew.id);
+ if (tile) { faces.set(socket.id, { kind: "terminals", tiles: [tile] }); continue; }
}
- faces.set(socket.id, { tone, title: crew.name, status, lines: tone === "standby" ? lines.slice(-3) : lines, cursor: tone === "live" || tone === "attention" });
+ const tone = TONE[crew.status];
+ const lines = crew.role === "officer" ? (chats.get(crew.id)?.lines ?? []).map(chatText) : [];
+ faces.set(socket.id, { tone, title: crew.name, status: statusWord(crew.status), lines: tone === "standby" ? lines.slice(-3) : lines, cursor: tone === "live" || tone === "attention" });
}
return faces;
- }, [deck, homes, life.crew, life.agents, life.panes, chats, terminalsA, terminalsB, rounds, t]);
+ }, [deck, engineering, homes, life.crew, life.agents, life.panes, chats, terminalsA, terminalsB, rounds, t]);
}
diff --git a/dodaios/ui/web/frontend/src/lib/liveTerminals.test.ts b/dodaios/ui/web/frontend/src/lib/liveTerminals.test.ts
new file mode 100644
index 0000000000..ca5c2bb577
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/lib/liveTerminals.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it, vi } from "vitest";
+import { Terminal } from "@xterm/xterm";
+import { liveTerminal, liveTerminalsGeneration, registerLiveTerminal, subscribeLiveTerminals } from "./liveTerminals";
+
+describe("live terminal registry", () => {
+ it("finds a pane by any of its names and counts its writes", async () => {
+ const term = new Terminal({ cols: 10, rows: 2 });
+ const listener = vi.fn();
+ const stop = subscribeLiveTerminals(listener);
+ const before = liveTerminalsGeneration();
+ const unregister = registerLiveTerminal("ws1", "T1", term);
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(liveTerminalsGeneration()).toBe(before + 1);
+ const entry = liveTerminal("ws1", ["Claude", "T1"]);
+ expect(entry?.term).toBe(term);
+ await new Promise<void>((resolve) => term.write("hi", resolve));
+ expect(entry!.version).toBeGreaterThan(0);
+ unregister();
+ expect(liveTerminal("ws1", ["T1"])).toBeUndefined();
+ stop();
+ term.dispose();
+ });
+
+ it("leaves a newer viewer of the same pane registered", () => {
+ const a = new Terminal(), b = new Terminal();
+ const offA = registerLiveTerminal("ws2", "T1", a);
+ const offB = registerLiveTerminal("ws2", "T1", b);
+ offA();
+ expect(liveTerminal("ws2", ["T1"])?.term).toBe(b);
+ offB();
+ expect(liveTerminal("ws2", ["T1"])).toBeUndefined();
+ a.dispose(); b.dispose();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/lib/liveTerminals.ts b/dodaios/ui/web/frontend/src/lib/liveTerminals.ts
new file mode 100644
index 0000000000..cd1635a32d
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/lib/liveTerminals.ts
@@ -0,0 +1,70 @@
+/**
+ * The IDE's live pane terminals, readable by anything that wants to show them.
+ *
+ * Every mounted Agentic-IDE pane registers its xterm instance here under
+ * `<workspaceId>:<name>`. The ship's monitors read the very same buffer the
+ * pane draws from, so a monitor shows the pane's screen cell for cell, with
+ * its colours, instead of a server-side text replay.
+ *
+ * Read-only by contract: nothing here writes to, resizes or focuses a
+ * terminal. `version` grows on every parsed write and resize, so a reader
+ * can tell cheaply whether there is anything new to draw.
+ */
+import type { Terminal } from "@xterm/xterm";
+
+export interface LiveTerminal {
+ readonly term: Terminal;
+ /** Bumped on every parsed write and resize. */
+ version: number;
+}
+
+const live = new Map<string, LiveTerminal>();
+const listeners = new Set<() => void>();
+let generation = 0;
+
+function keyOf(workspaceId: string, name: string): string {
+ return `${workspaceId}:${name}`;
+}
+
+function changed(): void {
+ generation += 1;
+ for (const listener of listeners) listener();
+}
+
+/** Register a pane's terminal; returns the matching unregister. */
+export function registerLiveTerminal(workspaceId: string, name: string, term: Terminal): () => void {
+ const key = keyOf(workspaceId, name);
+ const entry: LiveTerminal = { term, version: 0 };
+ const bump = () => { entry.version += 1; };
+ // Optional calls: a monitor feed must never be able to break the pane that registers it.
+ const subs = [term.onWriteParsed?.(bump), term.onResize?.(bump)].filter((s): s is { dispose(): void } => !!s);
+ live.set(key, entry);
+ changed();
+ return () => {
+ for (const sub of subs) sub.dispose();
+ // A newer viewer of the same pane may have taken the slot meanwhile.
+ if (live.get(key) === entry) {
+ live.delete(key);
+ changed();
+ }
+ };
+}
+
+/** The live terminal of a pane, trying each of its names (call-sign, title). */
+export function liveTerminal(workspaceId: string, names: readonly string[]): LiveTerminal | undefined {
+ for (const name of names) {
+ const entry = live.get(keyOf(workspaceId, name));
+ if (entry) return entry;
+ }
+ return undefined;
+}
+
+/** For useSyncExternalStore: changes whenever a terminal comes or goes. */
+export function subscribeLiveTerminals(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+}
+
+export function liveTerminalsGeneration(): number {
+ return generation;
+}