Add per-task terminals over WebSocket with an xterm.js Terminal tab
This commit is contained in:
+50
-1
@@ -456,6 +456,25 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/tasks/{taskId}/terminal": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
taskId: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** @description A WebSocket attached to the task's terminal, a login shell in its worktree, started at cols by rows if none is running. The server first sends what the terminal has recently printed, then its output as it comes, all as binary messages. The client sends input as binary messages and resizes as text messages holding a TerminalSize. When the shell exits the server closes with code 4000 and the exit status as the reason. */
|
||||
get: operations["getTaskTerminal"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/tasks/{taskId}/snapshots": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -1052,7 +1071,11 @@ export interface components {
|
||||
focused: boolean;
|
||||
};
|
||||
/** @enum {string} */
|
||||
TaskTab: "transcript" | "changes" | "files" | "inbox" | "project";
|
||||
TaskTab: "transcript" | "changes" | "files" | "terminal" | "inbox" | "project";
|
||||
TerminalSize: {
|
||||
cols: number;
|
||||
rows: number;
|
||||
};
|
||||
Status: {
|
||||
/** @description Agent processes currently running. */
|
||||
live_agents: number;
|
||||
@@ -1897,6 +1920,32 @@ export interface operations {
|
||||
409: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getTaskTerminal: {
|
||||
parameters: {
|
||||
query: {
|
||||
cols: number;
|
||||
rows: number;
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
taskId: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description Switched to the WebSocket protocol. */
|
||||
101: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content?: never;
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
404: components["responses"]["Error"];
|
||||
409: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
listSnapshots: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
+15
-5
@@ -52,11 +52,7 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<M extends Method, P extends PathsWith<M>>(
|
||||
method: M,
|
||||
path: P,
|
||||
opts: Options<Op<P, M>> = {},
|
||||
): Promise<Result<Op<P, M>>> {
|
||||
function target(path: string, opts: { path?: unknown; query?: unknown }): string {
|
||||
const pathParams = (opts.path ?? {}) as Record<string, unknown>;
|
||||
let url: string = path.replace(/\{(\w+)\}/g, (_, key: string) => {
|
||||
const value = pathParams[key];
|
||||
@@ -75,7 +71,15 @@ export async function request<M extends Method, P extends PathsWith<M>>(
|
||||
if (query.size > 0) {
|
||||
url += `?${query}`;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function request<M extends Method, P extends PathsWith<M>>(
|
||||
method: M,
|
||||
path: P,
|
||||
opts: Options<Op<P, M>> = {},
|
||||
): Promise<Result<Op<P, M>>> {
|
||||
const url = target(path, opts);
|
||||
const init: RequestInit = { method: method.toUpperCase(), keepalive: opts.keepalive ?? false };
|
||||
if (opts.body instanceof Blob) {
|
||||
init.headers = { "Content-Type": opts.body.type || "application/octet-stream" };
|
||||
@@ -105,6 +109,12 @@ export const post = <P extends PathsWith<"post">>(path: P, opts?: Options<Op<P,
|
||||
export const put = <P extends PathsWith<"put">>(path: P, opts?: Options<Op<P, "put">>) => request("put", path, opts);
|
||||
export const del = <P extends PathsWith<"delete">>(path: P, opts?: Options<Op<P, "delete">>) => request("delete", path, opts);
|
||||
|
||||
export function socket<P extends PathsWith<"get">>(path: P, opts: Options<Op<P, "get">>): WebSocket {
|
||||
const ws = new WebSocket(`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}${target(path, opts)}`);
|
||||
ws.binaryType = "arraybuffer";
|
||||
return ws;
|
||||
}
|
||||
|
||||
const staleAfterMs = 40_000;
|
||||
const retryAfterMs = 2_000;
|
||||
|
||||
|
||||
@@ -8,11 +8,13 @@ import { openSwitcher } from "./navbar.js";
|
||||
import { findTask, focusedProject, focusTab, on, onEach, state, tabs } from "./state.js";
|
||||
import { mountProject } from "./project.js";
|
||||
import { mountTranscript } from "./task.js";
|
||||
import { mountTerminal } from "./terminal.js";
|
||||
|
||||
const views: Record<TaskTab, { label: string; mount: (root: HTMLElement) => () => void }> = {
|
||||
transcript: { label: "Transcript", mount: mountTranscript },
|
||||
changes: { label: "Changes", mount: (root) => mountChanges(root) },
|
||||
files: { label: "Files", mount: mountFiles },
|
||||
terminal: { label: "Terminal", mount: mountTerminal },
|
||||
inbox: { label: "Inbox", mount: mountInbox },
|
||||
project: { label: "Project", mount: mountProject },
|
||||
};
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ export type Topic =
|
||||
| "lead.transcript"
|
||||
| "lead.stream";
|
||||
|
||||
export const tabs: TaskTab[] = ["transcript", "changes", "files", "inbox", "project"];
|
||||
export const tabs: TaskTab[] = ["transcript", "changes", "files", "terminal", "inbox", "project"];
|
||||
|
||||
export const state = {
|
||||
me: undefined as User | undefined,
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import type { FitAddon } from "@xterm/addon-fit";
|
||||
import type { Terminal } from "@xterm/xterm";
|
||||
import { socket, type Schemas } from "./api.js";
|
||||
import { errorText, h, replace } from "./dom.js";
|
||||
import { findTask, onEach, state } from "./state.js";
|
||||
|
||||
type Xterm = { Terminal: typeof Terminal; FitAddon: typeof FitAddon };
|
||||
|
||||
const exitedCode = 4000;
|
||||
const internalErrorCode = 1011;
|
||||
const retryAfterMs = 2_000;
|
||||
|
||||
let loading: Promise<Xterm> | undefined;
|
||||
|
||||
function load(): Promise<Xterm> {
|
||||
loading ??= (async () => {
|
||||
document.head.append(h("link", { rel: "stylesheet", href: "/vendor/xterm.css" }));
|
||||
const xtermUrl = "/vendor/xterm.mjs";
|
||||
const fitUrl = "/vendor/addon-fit.mjs";
|
||||
const [x, f] = (await Promise.all([import(xtermUrl), import(fitUrl)])) as [{ Terminal: typeof Terminal }, { FitAddon: typeof FitAddon }];
|
||||
await document.fonts.load(`13px ${getComputedStyle(document.documentElement).getPropertyValue("--font")}`);
|
||||
return { Terminal: x.Terminal, FitAddon: f.FitAddon };
|
||||
})();
|
||||
return loading;
|
||||
}
|
||||
|
||||
type Show = (text: string, exited: boolean) => void;
|
||||
|
||||
function attach(taskId: string, screen: HTMLElement, show: Show): () => void {
|
||||
const encoder = new TextEncoder();
|
||||
let term: Terminal | undefined;
|
||||
let ws: WebSocket | undefined;
|
||||
let observer: ResizeObserver | undefined;
|
||||
let retry = 0;
|
||||
let done = false;
|
||||
|
||||
const send = (data: Uint8Array) => {
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
ws.send(data);
|
||||
}
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
if (!term || done) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(retry);
|
||||
show("connecting…", false);
|
||||
const t = term;
|
||||
const s = socket("/api/tasks/{taskId}/terminal", { path: { taskId }, query: { cols: t.cols, rows: t.rows } });
|
||||
ws = s;
|
||||
s.onopen = () => {
|
||||
t.reset();
|
||||
show("", false);
|
||||
};
|
||||
s.onmessage = (e: MessageEvent<ArrayBuffer>) => {
|
||||
t.write(new Uint8Array(e.data));
|
||||
};
|
||||
s.onclose = (e) => {
|
||||
if (ws !== s || done) {
|
||||
return;
|
||||
}
|
||||
ws = undefined;
|
||||
if (e.code === exitedCode) {
|
||||
show(`shell ended: ${e.reason}`, true);
|
||||
return;
|
||||
}
|
||||
if (e.code === internalErrorCode) {
|
||||
show(e.reason, true);
|
||||
return;
|
||||
}
|
||||
if (findTask(taskId)?.status !== "active") {
|
||||
show("task closed", false);
|
||||
return;
|
||||
}
|
||||
show("disconnected, reconnecting…", false);
|
||||
retry = setTimeout(connect, retryAfterMs);
|
||||
};
|
||||
};
|
||||
|
||||
load()
|
||||
.then(({ Terminal, FitAddon }) => {
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
const v = (name: string) => css.getPropertyValue(name).trim();
|
||||
const t = new Terminal({
|
||||
fontFamily: v("--font"),
|
||||
fontSize: 13,
|
||||
cursorBlink: true,
|
||||
scrollback: 5000,
|
||||
theme: {
|
||||
background: v("--bg"),
|
||||
foreground: v("--text"),
|
||||
cursor: v("--accent"),
|
||||
cursorAccent: v("--bg"),
|
||||
selectionBackground: v("--accent-tint"),
|
||||
},
|
||||
});
|
||||
const fit = new FitAddon();
|
||||
t.loadAddon(fit);
|
||||
t.open(screen);
|
||||
fit.fit();
|
||||
t.onData((data) => send(encoder.encode(data)));
|
||||
t.onBinary((data) => send(Uint8Array.from(data, (c) => c.charCodeAt(0))));
|
||||
t.onResize(({ cols, rows }) => {
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ cols, rows } satisfies Schemas["TerminalSize"]));
|
||||
}
|
||||
});
|
||||
observer = new ResizeObserver(() => fit.fit());
|
||||
observer.observe(screen);
|
||||
term = t;
|
||||
t.focus();
|
||||
connect();
|
||||
})
|
||||
.catch((err: unknown) => show(`terminal not loaded: ${errorText(err)}`, false));
|
||||
|
||||
return () => {
|
||||
done = true;
|
||||
clearTimeout(retry);
|
||||
observer?.disconnect();
|
||||
ws?.close();
|
||||
term?.dispose();
|
||||
};
|
||||
}
|
||||
|
||||
export function mountTerminal(root: HTMLElement): () => void {
|
||||
const status = h("span", { class: "terminal-status" });
|
||||
const restart = h("button", { type: "button", hidden: true }, "New shell");
|
||||
const screen = h("div", { class: "terminal-screen" });
|
||||
let attached: string | undefined;
|
||||
let detach: () => void = () => {};
|
||||
|
||||
const show: Show = (text, exited) => {
|
||||
status.textContent = text;
|
||||
restart.hidden = !exited;
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
detach();
|
||||
detach = () => {};
|
||||
attached = undefined;
|
||||
replace(screen);
|
||||
show("", false);
|
||||
const taskId = state.selectedTaskId;
|
||||
if (!taskId) {
|
||||
replace(screen, h("div", { class: "empty" }, "No task selected."));
|
||||
return;
|
||||
}
|
||||
if (findTask(taskId)?.status !== "active") {
|
||||
replace(screen, h("div", { class: "empty" }, "The task is closed; its worktree is gone."));
|
||||
return;
|
||||
}
|
||||
attached = taskId;
|
||||
detach = attach(taskId, screen, show);
|
||||
};
|
||||
|
||||
restart.onclick = open;
|
||||
|
||||
screen.addEventListener("keydown", (e) => {
|
||||
if (e.ctrlKey && !e.metaKey) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
|
||||
const offs = [
|
||||
onEach(["selection"], open),
|
||||
onEach(["tasks"], () => {
|
||||
if (attached && findTask(attached)?.status !== "active") {
|
||||
open();
|
||||
}
|
||||
}),
|
||||
];
|
||||
|
||||
replace(root, h("div", { class: "terminal-view" }, h("header", { class: "terminal-header" }, h("span", { class: "terminal-title" }, "Shell in the task's worktree"), status, restart), screen));
|
||||
open();
|
||||
return () => {
|
||||
detach();
|
||||
for (const off of offs) {
|
||||
off();
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user