mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
PTY output goes through a gate before xterm instead of being written chunk by chunk. While the window is hidden it flushes at most every 250 ms, so terminals running btop or agent animations stop burning CPU in background windows. Tools | Terminal | Maximum refresh rate (Unlimited by default; 60/30/15/10 FPS) optionally caps painting while visible. Closes #4216 Co-authored-by: GGVidal <52431033+GGVidal@users.noreply.github.com>
1068 lines
41 KiB
TypeScript
1068 lines
41 KiB
TypeScript
/**
|
||
* One terminal session: an xterm.js instance bound to a backend PTY. The xterm
|
||
* lives in a detached host element owned by the session (not by React), so a
|
||
* session survives its tool window being hidden or its pane being re-mounted.
|
||
*/
|
||
import { writeClipboardText } from "@/platform/clipboard";
|
||
import { noteCopySource } from "@/platform/clipboardSource";
|
||
import { Terminal, type IDisposable, type ILink, type ILinkHandler } from "@xterm/xterm";
|
||
import { FitAddon } from "@xterm/addon-fit";
|
||
import { SearchAddon, type ISearchOptions } from "@xterm/addon-search";
|
||
import "@xterm/xterm/css/xterm.css";
|
||
import "./xtermInput.css";
|
||
import { Channel } from "@tauri-apps/api/core";
|
||
import { call, commands, isTauri, type TerminalId } from "@/platform/ipc";
|
||
import { tx } from "@/platform/i18n";
|
||
import { editorService, notifications, registerFontZoomSurface } from "@/workbench/contributions";
|
||
import { OutputActivity } from "./activity";
|
||
import { fitScheduler, settledResize } from "./fit";
|
||
import { OutputGate, type TerminalMaxFps } from "./outputGate";
|
||
import { watchWindowsPty, windowsPtyOptions } from "./windowsPty";
|
||
import { installTerminalDrop } from "./drop";
|
||
import { installDomRowCache } from "./domRowCache";
|
||
import { installSelectionHighlights, type SelectionHighlightController } from "./highlight";
|
||
import { installLinkHighlights, xtermLink, type LinkHighlightController } from "./linkHighlights";
|
||
import { installTerminalPaste, pasteIntoTerminal, pasteTerminalClipboard } from "./paste";
|
||
import { ImeCommitGate } from "./imeCommit";
|
||
import { ownTerminalInput } from "./imeInput";
|
||
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
|
||
import { parseShellCommand } from "@/platform/commandLine";
|
||
import { useProject } from "@/platform/project";
|
||
import { hostOs, useRemote } from "@/platform/remote";
|
||
import { usePlatform } from "@/platform/platformInfo";
|
||
import { workflowSettings, type TerminalSettingsValid } from "@/platform/workflowSettings";
|
||
import { editorPrefs } from "@/platform/editorSettings";
|
||
import type { CompletionInfo } from "./completion";
|
||
import {
|
||
readLinkColor,
|
||
readSearchDecorations,
|
||
readTerminalTheme,
|
||
remeasureWhenFontsLoad,
|
||
terminalFont,
|
||
type EditorFont,
|
||
type TerminalFontSettings,
|
||
MIN_CONTRAST_RATIO,
|
||
} from "./theme";
|
||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||
|
||
export interface TerminalSearchOptions {
|
||
caseSensitive: boolean;
|
||
regex: boolean;
|
||
wholeWord: boolean;
|
||
}
|
||
|
||
export interface TerminalSearchResult {
|
||
/** -1 when the active match is unknown (more matches than the highlight limit). */
|
||
index: number;
|
||
count: number;
|
||
}
|
||
|
||
export type SessionStatus = "idle" | "starting" | "running" | "exited" | "error";
|
||
|
||
export interface SessionSnapshot {
|
||
status: SessionStatus;
|
||
exitCode: number | null;
|
||
/** Shell name reported by the backend (`zsh`). */
|
||
title: string;
|
||
/** Window title set by the running program (OSC 0/2), null when unset or blank. */
|
||
appTitle: string | null;
|
||
/** A command is running (shell integration's OSC 133 C … D), or the session runs a non-shell program. */
|
||
commandRunning: boolean;
|
||
/**
|
||
* The running program's own progress report (OSC 9;4, #3831): "active" while it
|
||
* shows itself as working, "cleared" once it reports being done, null while it
|
||
* has said nothing. An interactive CLI is one command from OSC 133's point of
|
||
* view, so only its own report separates working from waiting for input.
|
||
*/
|
||
progress: "active" | "cleared" | null;
|
||
/**
|
||
* The running command is at work (#3831): as its progress report says; without
|
||
* one, always for a plain command, and for an interactive program (an agent
|
||
* CLI, a REPL, an editor) only while it keeps producing output, not while it
|
||
* waits for input.
|
||
*/
|
||
working: boolean;
|
||
/** Current directory (initial cwd, updated by OSC 7). */
|
||
cwd: string;
|
||
/**
|
||
* A finished command has not been seen yet (#3712): the tab shows a dot
|
||
* until it is focused or opened from its notification.
|
||
*/
|
||
unseenDone: boolean;
|
||
}
|
||
|
||
export interface SessionOptions {
|
||
key: string;
|
||
cwd: string;
|
||
onChange: (key: string, snapshot: SessionSnapshot) => void;
|
||
onFocus: (key: string) => void;
|
||
/** The shell exited (after the exit message was printed). */
|
||
onExit?: (key: string) => void;
|
||
/**
|
||
* A shell-integration command finished (OSC 133 D): how long it ran, its
|
||
* exit status, and whether it was stopped with Ctrl-C (#3712).
|
||
*/
|
||
onCompletion?: (key: string, info: CompletionInfo) => void;
|
||
/**
|
||
* Run this program instead of the configured shell (e.g. `docker exec -it <id> sh`).
|
||
* `shell`: it is a shell (a predefined session), so shell integration still applies.
|
||
*/
|
||
command?: {
|
||
program: string;
|
||
args: string[];
|
||
shell?: boolean;
|
||
env?: Record<string, string>;
|
||
spawn?: (cols: number, rows: number, output: Channel<string>) => Promise<import("@/bindings").TerminalInfo>;
|
||
onExit?: (status: number | null, closed: boolean) => void;
|
||
};
|
||
/**
|
||
* Restored tabs only: the project root, used when `cwd` no longer exists
|
||
* (deleted since the last run, see `resolveStartCwd`).
|
||
*/
|
||
fallbackRoot?: string;
|
||
}
|
||
|
||
/** Mouse-tracking DEC private modes (X10, normal, button, any-event, encodings). */
|
||
const MOUSE_MODES = new Set([9, 1000, 1001, 1002, 1003, 1005, 1006, 1015, 1016]);
|
||
/** Bracketed paste and the alternate screen: DEC private modes of a program that reads the keyboard itself. */
|
||
const INPUT_MODES = new Set([47, 1047, 1049, 2004]);
|
||
const CLEAR_SCROLLBACK_MARKER = "\x1b]133;OpenIDEA;ClearScrollback\x07";
|
||
|
||
let audio: AudioContext | null = null;
|
||
|
||
/** A short beep for BEL (Settings › Terminal › Audible bell). */
|
||
function beep() {
|
||
try {
|
||
audio ??= new AudioContext();
|
||
const osc = audio.createOscillator();
|
||
const gain = audio.createGain();
|
||
osc.frequency.value = 880;
|
||
gain.gain.setValueAtTime(0.08, audio.currentTime);
|
||
gain.gain.exponentialRampToValueAtTime(0.0001, audio.currentTime + 0.12);
|
||
osc.connect(gain).connect(audio.destination);
|
||
osc.start();
|
||
osc.stop(audio.currentTime + 0.13);
|
||
} catch {
|
||
/* no audio */
|
||
}
|
||
}
|
||
|
||
/** The terminal font for `t`, resolved against the current editor font (also used by embedded terminals). */
|
||
export function fontFor(t: TerminalFontSettings) {
|
||
const e = useProject.getState().settings?.editor as EditorFont | undefined;
|
||
return terminalFont(t, { ...e, fallbackFont: editorPrefs().fallbackFont });
|
||
}
|
||
|
||
const CURSOR: Record<TerminalSettingsValid["cursorShape"], "block" | "underline" | "bar"> = {
|
||
block: "block",
|
||
underline: "underline",
|
||
bar: "bar",
|
||
};
|
||
|
||
const RESTART_HINT = "\x1b[2mPress Enter to restart\x1b[0m";
|
||
|
||
export async function openExternal(url: string) {
|
||
try {
|
||
if (isTauri()) {
|
||
const { openUrl } = await import("@tauri-apps/plugin-opener");
|
||
await openUrl(url);
|
||
} else {
|
||
window.open(url, "_blank", "noopener");
|
||
}
|
||
} catch (e) {
|
||
notifications().notify({ level: "error", title: "Cannot open link", body: String(e) });
|
||
}
|
||
}
|
||
|
||
/**
|
||
* OSC 8 hyperlinks (`claude` / `gh` login links…): open in the system browser.
|
||
* xterm's default confirms with `window.confirm` and then calls `window.open`,
|
||
* which does nothing in the app's webview.
|
||
*/
|
||
export const LINK_HANDLER: ILinkHandler = {
|
||
activate: (event, uri) => {
|
||
event.preventDefault();
|
||
if (/^https?:\/\//i.test(uri)) void openExternal(uri);
|
||
},
|
||
};
|
||
|
||
export async function openFileLink(link: Extract<TerminalLink, { kind: "file" }>, cwd: string) {
|
||
const selection = link.line ? { line: link.line - 1, col: Math.max(0, (link.col ?? 1) - 1) } : undefined;
|
||
const path = resolvePath(link.path, cwd);
|
||
const rel = link.path.replace(/\\/g, "/");
|
||
const name = rel.split("/").pop() ?? rel;
|
||
try {
|
||
const slash = path.lastIndexOf("/");
|
||
const entries = await call(commands.fsReadDir(slash > 0 ? path.slice(0, slash) : "/"));
|
||
if (entries.some((e) => e.name === name && e.kind !== "dir")) {
|
||
await editorService().openFile(path, { selection, focus: true });
|
||
return;
|
||
}
|
||
} catch {
|
||
/* fall back to a project-wide lookup */
|
||
}
|
||
// The basename alone is ambiguous (`a/x.ts` vs `b/x.ts`): rank the link's
|
||
// directory part too and verify the hit actually sits on that path, settling
|
||
// for a basename match only when the link names no directory.
|
||
for (const q of rel === name ? [name] : [rel, name]) {
|
||
try {
|
||
const hits = await call(commands.findFiles(q, 5));
|
||
const hit = hits.find((h) => h.relPath === q || h.relPath.endsWith(`/${q}`));
|
||
if (hit) {
|
||
await editorService().openFile(hit.path, { selection, focus: true });
|
||
return;
|
||
}
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
notifications().notify({ level: "warning", title: "File not found", body: link.path });
|
||
}
|
||
|
||
/**
|
||
* A tab restored from the last session may remember a directory that has since
|
||
* been deleted. The backend would silently start such a shell in $HOME; when a
|
||
* `fallbackRoot` (the project root) is given, start there instead.
|
||
*/
|
||
export async function resolveStartCwd(cwd: string, fallbackRoot: string | undefined): Promise<string> {
|
||
if (!fallbackRoot || cwd === fallbackRoot) return cwd;
|
||
try {
|
||
if ((await call(commands.fsEntryKind(cwd))) === "dir") return cwd;
|
||
} catch {
|
||
/* deleted or unreachable */
|
||
}
|
||
return fallbackRoot;
|
||
}
|
||
|
||
export class TerminalSession {
|
||
readonly key: string;
|
||
readonly host: HTMLDivElement;
|
||
readonly term: Terminal;
|
||
private readonly fit = new FitAddon();
|
||
private readonly searchAddon = new SearchAddon({ highlightLimit: 2000 });
|
||
private searchDecorations: ISearchOptions["decorations"] | null = null;
|
||
private readonly searchListeners = new Set<(r: TerminalSearchResult) => void>();
|
||
private selectingSearchMatch = false;
|
||
private searchSelection = false;
|
||
private readonly selectionHighlights: SelectionHighlightController;
|
||
private readonly linkHighlights: LinkHighlightController;
|
||
private opts: SessionOptions;
|
||
private snapshot: SessionSnapshot;
|
||
private ptyId: TerminalId | null = null;
|
||
private opened = false;
|
||
/** `focus()` arrived before the textarea existed (the pane is focused while xterm is still closed). */
|
||
private pendingFocus = false;
|
||
/** Bounds retries when the pane has no box yet, or xterm cannot measure a cell. */
|
||
private fitAttempts = 0;
|
||
private disposed = false;
|
||
private disposables: IDisposable[] = [];
|
||
private resizeObserver: ResizeObserver | null = null;
|
||
private readonly fitter = fitScheduler(() => this.doFit());
|
||
private readonly ptyResize = settledResize((cols, rows) => this.resizePty(cols, rows));
|
||
/** Keystrokes typed while the PTY is still starting; sent as soon as it exists. */
|
||
private pendingInput = "";
|
||
private outputTail = "";
|
||
private readonly outputGate = new OutputGate({
|
||
maxFps: () => workflowSettings().terminal.maxFps as TerminalMaxFps,
|
||
hidden: () => typeof document !== "undefined" && document.hidden,
|
||
write: (data) => this.term.write(data),
|
||
});
|
||
private lastSize = { cols: 0, rows: 0 };
|
||
/** Per-tab font size offset (px) relative to `workflowSettings().terminal.fontSize`. */
|
||
private fontZoom = 0;
|
||
/** Kept while a shell-integration command runs, for its completion time (#3712). */
|
||
private commandStartedAt: number | null = null;
|
||
/** Ctrl-C was typed while the current command ran: it was stopped, not finished. */
|
||
private commandInterrupted = false;
|
||
private readonly activity = new OutputActivity();
|
||
private activityTimer: ReturnType<typeof setTimeout> | null = null;
|
||
/** Input modes the running command asked for; see `interactive`. */
|
||
private readonly inputModes = new Set<number>();
|
||
/** Bumped on restart so late output from a previous PTY is ignored. */
|
||
private generation = 0;
|
||
/** WebKitGTK delivers one IME commit' worth of text more than once; see `ImeCommitGate`. */
|
||
private readonly ime = new ImeCommitGate(() => {
|
||
if (this.term.textarea) this.term.textarea.value = "";
|
||
});
|
||
|
||
/**
|
||
* Hands the session to another owner (a terminal tab moved to the editor): its
|
||
* snapshots, focus and exit go there from now on. The PTY keeps running.
|
||
*/
|
||
rebind(owner: Pick<SessionOptions, "onChange" | "onFocus" | "onExit" | "onCompletion">) {
|
||
this.opts = { ...this.opts, ...owner, onExit: owner.onExit };
|
||
this.opts.onChange(this.key, this.snapshot);
|
||
}
|
||
|
||
constructor(opts: SessionOptions) {
|
||
this.opts = opts;
|
||
this.key = opts.key;
|
||
this.snapshot = {
|
||
status: "idle",
|
||
exitCode: null,
|
||
title: "Local",
|
||
appTitle: null,
|
||
commandRunning: false,
|
||
progress: null,
|
||
working: false,
|
||
cwd: opts.cwd,
|
||
unseenDone: false,
|
||
};
|
||
this.host = document.createElement("div");
|
||
this.host.className = "openidea-terminal-host";
|
||
this.host.dataset.terminalSession = opts.key;
|
||
this.host.style.width = "100%";
|
||
this.host.style.height = "100%";
|
||
|
||
const settings = workflowSettings().terminal;
|
||
const font = fontFor(settings);
|
||
this.term = new Terminal({
|
||
...windowsPtyOptions(),
|
||
fontFamily: font.family,
|
||
fontSize: font.size,
|
||
lineHeight: font.lineHeight,
|
||
letterSpacing: font.letterSpacing,
|
||
fontWeight: font.weight,
|
||
fontWeightBold: font.boldWeight,
|
||
cursorBlink: settings.cursorBlink,
|
||
cursorStyle: CURSOR[settings.cursorShape],
|
||
cursorWidth: 2,
|
||
cursorInactiveStyle: "outline",
|
||
allowProposedApi: true,
|
||
scrollback: 10_000,
|
||
macOptionIsMeta: settings.optionAsMeta,
|
||
macOptionClickForcesSelection: true,
|
||
rightClickSelectsWord: false,
|
||
drawBoldTextInBrightColors: false,
|
||
minimumContrastRatio: MIN_CONTRAST_RATIO,
|
||
smoothScrollDuration: 0,
|
||
// Same width as the IDE's scrollbars (global.css); the slider is styled there too (Terminal.module.css).
|
||
overviewRuler: { width: 10 },
|
||
theme: readTerminalTheme(),
|
||
linkHandler: LINK_HANDLER,
|
||
});
|
||
this.term.loadAddon(this.fit);
|
||
this.term.loadAddon(this.searchAddon);
|
||
// Promote active search decorations to the top layer so xterm's DOM renderer
|
||
// keeps activeMatchBackground above `.xterm-selection` when FindBar holds focus.
|
||
const registerDecoration = this.term.registerDecoration.bind(this.term);
|
||
this.term.registerDecoration = (options) => {
|
||
const active = this.searchDecorations?.activeMatchBackground;
|
||
const isActive = !!active && options.backgroundColor?.toLowerCase() === active.toLowerCase();
|
||
const d = registerDecoration(isActive ? { ...options, layer: "top" } : options);
|
||
if (d && isActive) d.onRender((el) => el.classList.add("xterm-find-active-result-decoration"));
|
||
return d;
|
||
};
|
||
const runSearch =
|
||
<T extends unknown[]>(fn: (...args: T) => boolean) =>
|
||
(...args: T) => {
|
||
this.selectingSearchMatch = true;
|
||
try {
|
||
const found = fn(...args);
|
||
if (found) {
|
||
this.searchSelection = this.term.hasSelection();
|
||
this.selectionHighlights.clear();
|
||
}
|
||
return found;
|
||
} finally {
|
||
this.selectingSearchMatch = false;
|
||
if (this.term.rows > 0) this.term.refresh(0, this.term.rows - 1);
|
||
}
|
||
};
|
||
this.searchAddon.findNext = runSearch(this.searchAddon.findNext.bind(this.searchAddon));
|
||
this.searchAddon.findPrevious = runSearch(this.searchAddon.findPrevious.bind(this.searchAddon));
|
||
|
||
this.disposables.push(
|
||
watchWindowsPty(this.term),
|
||
this.searchAddon.onDidChangeResults((r) => {
|
||
for (const l of this.searchListeners) l({ index: r.resultIndex, count: r.resultCount });
|
||
}),
|
||
this.term.onData((data) => this.fromTerminal(data)),
|
||
this.term.onBinary((data) => this.input(data)),
|
||
this.term.onWriteParsed(() => {
|
||
this.activity.output(Date.now());
|
||
this.syncWorking();
|
||
}),
|
||
this.term.onTitleChange((title) => this.update({ appTitle: title.trim() || null })),
|
||
// OSC 7: `file://host/path` — shells report their cwd so relative links resolve correctly.
|
||
this.term.parser.registerOscHandler(7, (data) => {
|
||
try {
|
||
const url = new URL(data);
|
||
if (url.protocol === "file:") this.update({ cwd: decodeURIComponent(url.pathname) });
|
||
} catch {
|
||
/* ignore malformed */
|
||
}
|
||
return true;
|
||
}),
|
||
// OSC 133 (shell integration): C = a command starts, D;<status> = it
|
||
// finished (plain D carries no status; both are accepted).
|
||
this.term.parser.registerOscHandler(133, (data) => {
|
||
if (data === "C") {
|
||
this.commandStartedAt = Date.now();
|
||
this.commandInterrupted = false;
|
||
// A new command in the tab: the previous completion has been seen, and
|
||
// the new program has not reported progress yet.
|
||
this.resetActivity();
|
||
this.update({ commandRunning: true, unseenDone: false, progress: null });
|
||
} else if (data === "D" || data.startsWith("D;")) {
|
||
const status = data.length > 2 ? Number.parseInt(data.slice(2), 10) : Number.NaN;
|
||
const startedAt = this.commandStartedAt;
|
||
this.commandStartedAt = null;
|
||
const interrupted = this.commandInterrupted;
|
||
this.commandInterrupted = false;
|
||
this.resetActivity();
|
||
this.update({ commandRunning: false, progress: null });
|
||
// A D without a C (shell startup, a restored tab's first prompt) is
|
||
// not a command finishing.
|
||
if (startedAt !== null) {
|
||
this.opts.onCompletion?.(this.key, {
|
||
durationMs: Date.now() - startedAt,
|
||
exitCode: Number.isFinite(status) ? status : null,
|
||
interrupted,
|
||
});
|
||
}
|
||
}
|
||
return true;
|
||
}),
|
||
// OSC 9;4 (ConEmu-style progress): agent CLIs (Claude Code, Gemini CLI, …)
|
||
// and long jobs report their own working state — state 0 removes it, 1–4
|
||
// report work in flight. A program that reports progress decides the tab's
|
||
// spinner itself (#3831): it clears the report when it waits for input,
|
||
// while OSC 133 still sees one command running from launch to exit.
|
||
this.term.parser.registerOscHandler(9, (data) => {
|
||
if (!data.startsWith("4;")) return false;
|
||
const state = Number.parseInt(data.slice(2), 10);
|
||
if (Number.isFinite(state)) this.update({ progress: state === 0 ? "cleared" : "active" });
|
||
return true;
|
||
}),
|
||
this.term.registerLinkProvider({
|
||
provideLinks: (y, callback) =>
|
||
callback(workflowSettings().terminal.highlightHyperlinks ? this.linksAt(y) : undefined),
|
||
}),
|
||
this.term.onBell(() => {
|
||
if (workflowSettings().terminal.audibleBell) beep();
|
||
}),
|
||
this.term.onSelectionChange(() => {
|
||
this.searchSelection = this.selectingSearchMatch && this.term.hasSelection();
|
||
if (!this.searchSelection && workflowSettings().terminal.copyOnSelection && this.term.hasSelection())
|
||
this.copySelection();
|
||
}),
|
||
this.term.parser.registerCsiHandler({ prefix: "?", final: "h" }, (params) => this.noteInputModes(params, true)),
|
||
this.term.parser.registerCsiHandler({ prefix: "?", final: "l" }, (params) => this.noteInputModes(params, false)),
|
||
// Mouse reporting off: ignore the application's requests to enable mouse tracking.
|
||
this.term.parser.registerCsiHandler({ prefix: "?", final: "h" }, (params) => {
|
||
if (workflowSettings().terminal.mouseReporting) return false;
|
||
const modes = params.map((p) => (Array.isArray(p) ? p[0] : p) ?? 0);
|
||
return modes.length > 0 && modes.every((m) => MOUSE_MODES.has(m));
|
||
}),
|
||
);
|
||
this.selectionHighlights = installSelectionHighlights(this.term, {
|
||
isSearchSelection: () => this.searchSelection,
|
||
});
|
||
this.linkHighlights = installLinkHighlights(this.term, readLinkColor);
|
||
this.disposables.push(this.selectionHighlights, this.linkHighlights);
|
||
this.disposables.push(
|
||
{ dispose: installTerminalPaste(this.host, (text) => this.paste(text), this.clipboardTarget) },
|
||
{ dispose: installTerminalDrop(this.host, (text) => this.paste(text), this.clipboardTarget) },
|
||
);
|
||
this.host.addEventListener("mousedown", this.onMiddleClick);
|
||
this.host.addEventListener("wheel", this.onWheelZoom, { capture: true, passive: false });
|
||
this.disposables.push({ dispose: registerFontZoomSurface(this.host, (delta) => this.stepFontSize(delta)) });
|
||
}
|
||
|
||
private onWheelZoom = (e: WheelEvent) => {
|
||
if (!editorPrefs().general.wheelZoom) return;
|
||
const zoom = wheelZoomStep(e);
|
||
if (zoom === null) return;
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
if (zoom) this.stepFontSize(zoom);
|
||
};
|
||
|
||
private onMiddleClick = (e: MouseEvent) => {
|
||
if (e.button !== 1 || !workflowSettings().terminal.pasteOnMiddleClick) return;
|
||
e.preventDefault();
|
||
void this.pasteClipboard();
|
||
};
|
||
|
||
private clipboardTarget = () => {
|
||
const remote = useRemote.getState().session;
|
||
const id = this.ptyId;
|
||
if (id === null || this.disposed) return null;
|
||
const generation = this.generation;
|
||
return {
|
||
id,
|
||
supported: !remote || remote.commands.includes("term_store_image"),
|
||
remote: !!remote,
|
||
shell: this.snapshot.title,
|
||
current: () =>
|
||
!this.disposed &&
|
||
this.ptyId === id &&
|
||
this.generation === generation &&
|
||
useRemote.getState().session === remote,
|
||
};
|
||
};
|
||
|
||
pasteClipboard() {
|
||
if (this.clipboardTarget()) this.focus();
|
||
return pasteTerminalClipboard((text) => this.paste(text), this.clipboardTarget);
|
||
}
|
||
/** Applies Settings › Tools › Terminal changes to a live session. */
|
||
applySettings(t: TerminalSettingsValid) {
|
||
const font = fontFor(t);
|
||
const o = this.term.options;
|
||
if (o.fontFamily !== font.family) {
|
||
o.fontFamily = font.family;
|
||
if (this.opened)
|
||
remeasureWhenFontsLoad(
|
||
this.term,
|
||
font,
|
||
() => !this.disposed,
|
||
() => this.scheduleFit(),
|
||
);
|
||
}
|
||
const targetSize = Math.max(8, Math.min(36, font.size + this.fontZoom));
|
||
if (o.fontSize !== targetSize) o.fontSize = targetSize;
|
||
if (o.lineHeight !== font.lineHeight) o.lineHeight = font.lineHeight;
|
||
if (o.letterSpacing !== font.letterSpacing) o.letterSpacing = font.letterSpacing;
|
||
if (o.fontWeight !== font.weight) o.fontWeight = font.weight;
|
||
if (o.fontWeightBold !== font.boldWeight) o.fontWeightBold = font.boldWeight;
|
||
o.cursorStyle = CURSOR[t.cursorShape];
|
||
o.cursorBlink = t.cursorBlink;
|
||
o.macOptionIsMeta = t.optionAsMeta;
|
||
this.selectionHighlights.refresh();
|
||
this.linkHighlights.refresh();
|
||
this.scheduleFit();
|
||
}
|
||
|
||
/** Steps this terminal tab's font size by `delta` px (or resets to 0 when `delta === 0`). */
|
||
stepFontSize(delta: number) {
|
||
const base = fontFor(workflowSettings().terminal).size;
|
||
if (delta === 0) {
|
||
this.fontZoom = 0;
|
||
} else {
|
||
const nextSize = Math.max(8, Math.min(36, base + this.fontZoom + delta));
|
||
this.fontZoom = nextSize - base;
|
||
}
|
||
const targetSize = Math.max(8, Math.min(36, base + this.fontZoom));
|
||
if (this.term.options.fontSize !== targetSize) {
|
||
this.term.options.fontSize = targetSize;
|
||
this.refit();
|
||
}
|
||
}
|
||
|
||
get state(): SessionSnapshot {
|
||
return this.snapshot;
|
||
}
|
||
|
||
/** Marks the tab: a finished command here has not been seen yet (#3712). */
|
||
markUnseenDone() {
|
||
if (!this.snapshot.unseenDone) this.update({ unseenDone: true });
|
||
}
|
||
|
||
/** The completion has been seen (the tab was focused). */
|
||
private clearUnseenDone() {
|
||
if (this.snapshot.unseenDone) this.update({ unseenDone: false });
|
||
}
|
||
|
||
get hasSelection(): boolean {
|
||
return this.term.hasSelection();
|
||
}
|
||
|
||
get isSearchSelection(): boolean {
|
||
return this.searchSelection;
|
||
}
|
||
|
||
private update(patch: Partial<SessionSnapshot>) {
|
||
this.snapshot = { ...this.snapshot, ...patch };
|
||
this.snapshot.working = this.isWorking();
|
||
this.opts.onChange(this.key, this.snapshot);
|
||
}
|
||
|
||
/**
|
||
* The running program takes input itself: it asked for bracketed paste or the
|
||
* alternate screen. Only its own requests count, not a mode an earlier program
|
||
* left on (one killed inside the alternate screen).
|
||
*/
|
||
private get interactive(): boolean {
|
||
return this.inputModes.size > 0;
|
||
}
|
||
|
||
private noteInputModes(params: (number | number[])[], on: boolean): boolean {
|
||
for (const p of params) {
|
||
const mode = Array.isArray(p) ? p[0] : p;
|
||
if (mode === undefined || !INPUT_MODES.has(mode)) continue;
|
||
if (on) this.inputModes.add(mode);
|
||
else this.inputModes.delete(mode);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/** A command starts or ends: what the previous one asked for and drew no longer counts. */
|
||
private resetActivity() {
|
||
this.inputModes.clear();
|
||
this.activity.reset();
|
||
}
|
||
|
||
private isWorking(): boolean {
|
||
const { status, commandRunning, progress } = this.snapshot;
|
||
if (!commandRunning || status === "exited" || status === "error") return false;
|
||
if (progress) return progress === "active";
|
||
return !this.interactive || this.activity.active(Date.now());
|
||
}
|
||
|
||
/** Re-judges `working` after output, and again once the output has been quiet long enough. */
|
||
private syncWorking() {
|
||
if (this.disposed) return;
|
||
if (this.activityTimer !== null) clearTimeout(this.activityTimer);
|
||
this.activityTimer = null;
|
||
const working = this.isWorking();
|
||
if (working !== this.snapshot.working) this.update({});
|
||
if (!this.snapshot.commandRunning || !this.interactive) return;
|
||
const wait = this.activity.quietAt - Date.now();
|
||
if (wait >= 0) this.activityTimer = setTimeout(() => this.syncWorking(), wait + 1);
|
||
}
|
||
|
||
private linksAt(y: number): ILink[] | undefined {
|
||
const line = this.term.buffer.active.getLine(y - 1);
|
||
if (!line) return undefined;
|
||
const text = line.translateToString(true);
|
||
const found = findTerminalLinks(text);
|
||
if (found.length === 0) return undefined;
|
||
return found.map((l) =>
|
||
xtermLink(this.term, line, y, l, (event) => {
|
||
// Plain click opens; a click that ends a drag-selection never reaches here.
|
||
event.preventDefault();
|
||
if (l.kind === "url") void openExternal(l.url);
|
||
else void openFileLink(l, this.snapshot.cwd);
|
||
}),
|
||
);
|
||
}
|
||
|
||
/** Moves the host into `container` and fits / starts once the pane has a size. */
|
||
attach(container: HTMLElement) {
|
||
if (this.disposed) return;
|
||
if (this.host.parentElement !== container) container.appendChild(this.host);
|
||
this.resizeObserver?.disconnect();
|
||
this.resizeObserver = new ResizeObserver(() => {
|
||
this.fitAttempts = 0;
|
||
this.scheduleFit();
|
||
});
|
||
this.resizeObserver.observe(container);
|
||
this.scheduleFit();
|
||
}
|
||
|
||
/**
|
||
* Opens xterm only after the host has a box. `open()` measures the cell size
|
||
* immediately; doing it while the tool window is still 0×0 (the first layout
|
||
* pass, or a tab under `display: none`) leaves the helper textarea unable to
|
||
* take keys for the rest of the session.
|
||
*/
|
||
private openIfReady() {
|
||
if (this.opened || this.disposed) return;
|
||
if (this.host.offsetWidth === 0 || this.host.offsetHeight === 0) return;
|
||
// xterm's DOM renderer: the WebGL one rasterizes glyphs per background, so
|
||
// selected text rendered at a visibly different weight than the rest.
|
||
this.term.open(this.host);
|
||
installDomRowCache(this.term);
|
||
this.opened = true;
|
||
remeasureWhenFontsLoad(
|
||
this.term,
|
||
fontFor(workflowSettings().terminal),
|
||
() => !this.disposed,
|
||
() => this.scheduleFit(),
|
||
);
|
||
this.term.textarea?.addEventListener("focus", () => {
|
||
this.clearUnseenDone();
|
||
this.opts.onFocus(this.key);
|
||
});
|
||
this.watchImeCommit();
|
||
if (this.pendingFocus) this.focus();
|
||
}
|
||
|
||
detach(container: HTMLElement) {
|
||
this.resizeObserver?.disconnect();
|
||
this.resizeObserver = null;
|
||
if (this.host.parentElement === container) container.removeChild(this.host);
|
||
}
|
||
|
||
private scheduleFit() {
|
||
this.ptyResize.cancel();
|
||
this.fitter.schedule();
|
||
}
|
||
|
||
/**
|
||
* Delivers the IME commits xterm loses on macOS, and routes a WebKitGTK / fcitx5 commit
|
||
* through `ImeCommitGate` elsewhere (that platform reports the commit's own keystroke code
|
||
* 229 and its input event, but reports `compositionstart` only for composed words).
|
||
*/
|
||
private watchImeCommit() {
|
||
const textarea = this.term.textarea;
|
||
if (!textarea) return;
|
||
// WKWebView: xterm drops commits IMEs without composition events inject (Doubao) and
|
||
// misses text that lands after its textarea snapshot. Deliver those here.
|
||
if (usePlatform.getState().os === "macos") {
|
||
this.disposables.push({
|
||
dispose: ownTerminalInput({ host: this.host, textarea, send: (data) => this.send(data) }),
|
||
});
|
||
return;
|
||
}
|
||
// WebKitGTK (Linux) and WebView2 keep the fcitx5 deduplication gate.
|
||
const onKeyDown = (e: KeyboardEvent) => {
|
||
if (e.keyCode === 229) this.ime.begin();
|
||
else this.ime.keystroke();
|
||
};
|
||
const onInput = (e: InputEvent) => {
|
||
if (e.inputType === "insertFromComposition" || e.inputType === "insertCompositionText") this.ime.input();
|
||
};
|
||
const onCompositionStart = () => this.ime.compositionStart();
|
||
// Bubble phase, i.e. after xterm's own listener: the rebase must land behind the emissions
|
||
// that xterm's composition and textarea-diff paths already scheduled.
|
||
const onCompositionEnd = () => this.ime.finish();
|
||
this.host.addEventListener("keydown", onKeyDown, true);
|
||
textarea.addEventListener("input", onInput, true);
|
||
textarea.addEventListener("compositionstart", onCompositionStart, true);
|
||
textarea.addEventListener("compositionend", onCompositionEnd);
|
||
this.disposables.push({
|
||
dispose: () => {
|
||
this.ime.close();
|
||
this.host.removeEventListener("keydown", onKeyDown, true);
|
||
textarea.removeEventListener("input", onInput, true);
|
||
textarea.removeEventListener("compositionstart", onCompositionStart, true);
|
||
textarea.removeEventListener("compositionend", onCompositionEnd);
|
||
},
|
||
});
|
||
}
|
||
|
||
/** xterm's data event, with one IME commit's repeated emissions collapsed. */
|
||
private fromTerminal(data: string) {
|
||
if (this.ime.accept(data)) this.input(data);
|
||
}
|
||
|
||
private writePtyOutput(chunk: string) {
|
||
const data = this.outputTail + chunk;
|
||
let output = data.replaceAll(CLEAR_SCROLLBACK_MARKER, "\x1b[2J\x1b[3J");
|
||
let held = 0;
|
||
for (let n = Math.min(CLEAR_SCROLLBACK_MARKER.length - 1, output.length); n > 0; n--) {
|
||
if (output.endsWith(CLEAR_SCROLLBACK_MARKER.slice(0, n))) {
|
||
held = n;
|
||
break;
|
||
}
|
||
}
|
||
this.outputTail = output.slice(output.length - held);
|
||
output = output.slice(0, output.length - held);
|
||
if (output) this.outputGate.push(output);
|
||
}
|
||
|
||
private doFit() {
|
||
if (this.disposed || !this.host.isConnected) return;
|
||
// The grid row is still 0 on the first layout pass (the track is set by a
|
||
// parent layout effect after this one). Keep asking until it has a box;
|
||
// ResizeObserver also resets the budget when the size actually changes.
|
||
if (this.host.offsetWidth === 0 || this.host.offsetHeight === 0) {
|
||
if (this.fitAttempts++ < 20) this.scheduleFit();
|
||
return;
|
||
}
|
||
this.openIfReady();
|
||
if (!this.opened) return;
|
||
const dims = this.fit.proposeDimensions();
|
||
if (!dims || !Number.isFinite(dims.cols) || !Number.isFinite(dims.rows)) {
|
||
if (this.fitAttempts++ < 20) this.scheduleFit();
|
||
return;
|
||
}
|
||
this.fitAttempts = 0;
|
||
if (dims.cols !== this.term.cols || dims.rows !== this.term.rows) this.term.resize(dims.cols, dims.rows);
|
||
if (this.snapshot.status === "idle") {
|
||
void this.start();
|
||
} else if (this.ptyId !== null) {
|
||
this.ptyResize.resized(dims.cols, dims.rows);
|
||
}
|
||
}
|
||
|
||
private resizePty(cols: number, rows: number) {
|
||
if (this.disposed || this.ptyId === null) return;
|
||
if (this.lastSize.cols === cols && this.lastSize.rows === rows) return;
|
||
this.lastSize = { cols, rows };
|
||
void commands.termResize(this.ptyId, cols, rows);
|
||
}
|
||
|
||
/** Spawns the PTY with the current size. */
|
||
async start() {
|
||
if (this.disposed || this.snapshot.status === "starting" || this.snapshot.status === "running") return;
|
||
const generation = ++this.generation;
|
||
this.outputTail = "";
|
||
this.outputGate.clear();
|
||
this.resetActivity();
|
||
const custom = this.opts.command;
|
||
this.update({
|
||
status: "starting",
|
||
exitCode: null,
|
||
appTitle: null,
|
||
commandRunning: !!custom && !custom.shell,
|
||
progress: null,
|
||
});
|
||
if (!isTauri()) {
|
||
this.term.writeln("\x1b[2mTerminal is unavailable outside the desktop app.\x1b[0m");
|
||
this.update({ status: "error", commandRunning: false, progress: null });
|
||
return;
|
||
}
|
||
const cols = Math.max(2, this.term.cols);
|
||
const rows = Math.max(1, this.term.rows);
|
||
this.lastSize = { cols, rows };
|
||
const channel = new Channel<string>();
|
||
channel.onmessage = (chunk) => {
|
||
if (generation === this.generation && !this.disposed) this.writePtyOutput(chunk);
|
||
};
|
||
try {
|
||
const t = workflowSettings().terminal;
|
||
const [shellPath, ...shellArgs] = parseShellCommand(t.shellPath, hostOs() === "windows");
|
||
const shell = custom ? custom.program : shellPath;
|
||
const args = custom ? custom.args : shellArgs;
|
||
const cwd = await resolveStartCwd(this.opts.cwd, this.opts.fallbackRoot);
|
||
if (cwd !== this.opts.cwd) this.update({ cwd });
|
||
const info = custom?.spawn
|
||
? await custom.spawn(cols, rows, channel)
|
||
: await call(
|
||
commands.termSpawn(
|
||
{
|
||
cwd,
|
||
shell: shell ?? null,
|
||
args,
|
||
env: custom?.onExit ? { ...custom.env } : { ...t.env, ...custom?.env },
|
||
cols,
|
||
rows,
|
||
shellIntegration: (!custom || !!custom.shell) && t.shellIntegration,
|
||
},
|
||
channel,
|
||
),
|
||
);
|
||
if (this.disposed || generation !== this.generation) {
|
||
void commands.termKill(info.id);
|
||
return;
|
||
}
|
||
this.ptyId = info.id;
|
||
this.update({ status: "running", title: info.title || "Local" });
|
||
this.flushPendingInput();
|
||
} catch (e) {
|
||
this.pendingInput = "";
|
||
this.term.writeln(`\x1b[31mFailed to start terminal: ${e instanceof Error ? e.message : String(e)}\x1b[0m`);
|
||
if (!custom?.onExit) this.term.writeln(RESTART_HINT);
|
||
// Nothing runs: a non-shell command tab must not keep its running marker.
|
||
this.update({ status: "error", commandRunning: false, progress: null });
|
||
}
|
||
}
|
||
|
||
get terminalId(): TerminalId | null {
|
||
return this.ptyId;
|
||
}
|
||
|
||
/**
|
||
* Whether ending the session would kill something the user started (as IDEA
|
||
* judges it): a program run instead of a shell always counts;
|
||
* a shell counts while a command runs in it.
|
||
*/
|
||
async isBusy(): Promise<boolean> {
|
||
if (this.snapshot.status !== "running" || this.ptyId === null) return false;
|
||
const custom = this.opts.command;
|
||
if (custom && !custom.shell) return true;
|
||
try {
|
||
return await call(commands.termIsBusy(this.ptyId));
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/** Called when the backend reports the PTY exited. */
|
||
exited(code: number | null) {
|
||
if (this.disposed) return;
|
||
this.ptyId = null;
|
||
this.opts.command?.onExit?.(code, false);
|
||
this.pendingInput = "";
|
||
// The process is gone: a non-shell command tab never sees OSC 133's D, so
|
||
// the running marker stops here rather than spinning over the dead tab.
|
||
this.update({ status: "exited", exitCode: code, commandRunning: false, progress: null });
|
||
// Let output still in flight on the channel land first.
|
||
setTimeout(() => {
|
||
if (this.disposed || this.snapshot.status !== "exited") return;
|
||
const suffix = code !== null && code !== 0 ? ` (exit code ${code})` : "";
|
||
const hint = this.opts.command?.onExit ? "" : `${RESTART_HINT}\r\n`;
|
||
this.term.write(`\r\n\x1b[2m[Process completed${suffix}]\x1b[0m\r\n${hint}`);
|
||
this.opts.onExit?.(this.key);
|
||
}, 60);
|
||
}
|
||
|
||
restart() {
|
||
if (this.opts.command?.onExit) return;
|
||
if (this.snapshot.status === "running" || this.snapshot.status === "starting") return;
|
||
this.term.write("\r\n");
|
||
this.pendingInput = "";
|
||
this.update({ status: "idle" });
|
||
void this.start();
|
||
}
|
||
|
||
/**
|
||
* Sends input to the PTY. Keystrokes are not coalesced: WebKit delivers at most one key
|
||
* event per frame already, and a frame-based batch only made input wait for rendering.
|
||
*/
|
||
input(data: string) {
|
||
if (!data) return;
|
||
const status = this.snapshot.status;
|
||
if (status === "exited" || status === "error") {
|
||
// Shift+Enter sends Esc+Return.
|
||
if (data === "\r" || data === "\x1b\r") this.restart();
|
||
return;
|
||
}
|
||
if (this.ptyId === null) {
|
||
// The shell is still being spawned (tens of ms); keep the keystrokes and send them
|
||
// once the PTY exists instead of dropping them.
|
||
this.pendingInput += data;
|
||
return;
|
||
}
|
||
// Ctrl-C stops the running command: its D mark must not count as a completion (#3712).
|
||
if (this.snapshot.commandRunning && data.includes("\x03")) this.commandInterrupted = true;
|
||
this.activity.input(Date.now());
|
||
void call(commands.termWrite(this.ptyId, data)).catch((error) => {
|
||
notifications().notify({
|
||
level: "error",
|
||
title: tx("Cannot write to terminal"),
|
||
body: error instanceof Error ? tx(error.message) : String(error),
|
||
});
|
||
});
|
||
}
|
||
|
||
/** Sends keystrokes buffered while the PTY was starting. */
|
||
private flushPendingInput() {
|
||
const queued = this.pendingInput;
|
||
this.pendingInput = "";
|
||
if (queued && this.ptyId !== null) this.input(queued);
|
||
}
|
||
|
||
/** Writes input immediately (shortcuts translated outside xterm). */
|
||
send(data: string) {
|
||
this.term.scrollToBottom();
|
||
this.input(data);
|
||
}
|
||
|
||
paste(text: string) {
|
||
if (this.disposed) return;
|
||
pasteIntoTerminal(this.term, text);
|
||
}
|
||
|
||
clearSelection() {
|
||
this.term.clearSelection();
|
||
}
|
||
|
||
/** The last `max` lines down to the cursor (wrapped rows joined), for an agent's context. */
|
||
recentOutput(max = 80): { title: string; text: string } {
|
||
const buffer = this.term.buffer.active;
|
||
const end = buffer.baseY + buffer.cursorY;
|
||
const lines: string[] = [];
|
||
for (let y = Math.max(0, end - max + 1); y <= end; y++) {
|
||
const line = buffer.getLine(y);
|
||
if (!line) continue;
|
||
const text = line.translateToString(true);
|
||
if (line.isWrapped && lines.length) lines[lines.length - 1] += text;
|
||
else lines.push(text);
|
||
}
|
||
while (lines.length && !lines.at(-1)!.trim()) lines.pop();
|
||
while (lines.length && !lines[0]!.trim()) lines.shift();
|
||
return { title: this.snapshot.appTitle ?? this.snapshot.title, text: lines.join("\n") };
|
||
}
|
||
|
||
copySelection(): boolean {
|
||
const text = this.term.getSelection();
|
||
if (!text) return false;
|
||
noteCopySource(text, { kind: "terminal", title: this.snapshot.appTitle ?? this.snapshot.title });
|
||
void writeClipboardText(text).catch(() => undefined);
|
||
return true;
|
||
}
|
||
|
||
clear() {
|
||
this.term.clear();
|
||
}
|
||
|
||
/** Asks xterm to take the caret. Remembered when the textarea does not exist yet. */
|
||
focus() {
|
||
if (this.disposed) return;
|
||
// The tab is becoming visible either way: its finished command counts as seen.
|
||
this.clearUnseenDone();
|
||
if (!this.opened || !this.term.textarea) {
|
||
this.pendingFocus = true;
|
||
this.scheduleFit();
|
||
return;
|
||
}
|
||
this.pendingFocus = false;
|
||
this.term.focus();
|
||
}
|
||
|
||
/** Fits again after the tool window is shown or its box changes. */
|
||
refit() {
|
||
this.fitAttempts = 0;
|
||
this.scheduleFit();
|
||
}
|
||
|
||
applyTheme() {
|
||
this.term.options.theme = readTerminalTheme();
|
||
this.searchDecorations = null;
|
||
this.linkHighlights.refresh();
|
||
}
|
||
|
||
/** Finds `query` (highlighting every match); `incremental` keeps the current match while typing. */
|
||
find(query: string, opts: TerminalSearchOptions, direction: "next" | "previous", incremental = false): boolean {
|
||
if (!query) {
|
||
this.clearSearch();
|
||
return false;
|
||
}
|
||
this.selectionHighlights.clear();
|
||
this.searchDecorations ??= readSearchDecorations();
|
||
const options: ISearchOptions = {
|
||
...opts,
|
||
incremental: direction === "next" && incremental,
|
||
decorations: this.searchDecorations,
|
||
};
|
||
try {
|
||
return direction === "next"
|
||
? this.searchAddon.findNext(query, options)
|
||
: this.searchAddon.findPrevious(query, options);
|
||
} catch {
|
||
// Invalid regular expression.
|
||
this.clearSearch();
|
||
return false;
|
||
}
|
||
}
|
||
|
||
clearSearch() {
|
||
this.searchAddon.clearDecorations();
|
||
this.term.clearSelection();
|
||
this.searchSelection = false;
|
||
this.selectionHighlights.clear();
|
||
for (const l of this.searchListeners) l({ index: -1, count: 0 });
|
||
}
|
||
|
||
onSearchResults(listener: (r: TerminalSearchResult) => void): () => void {
|
||
this.searchListeners.add(listener);
|
||
return () => this.searchListeners.delete(listener);
|
||
}
|
||
|
||
dispose() {
|
||
if (this.disposed) return;
|
||
this.disposed = true;
|
||
if (this.snapshot.status === "running" || this.snapshot.status === "starting")
|
||
this.opts.command?.onExit?.(null, true);
|
||
this.fitter.cancel();
|
||
this.ptyResize.cancel();
|
||
this.outputGate.dispose();
|
||
if (this.activityTimer !== null) clearTimeout(this.activityTimer);
|
||
this.pendingInput = "";
|
||
this.resizeObserver?.disconnect();
|
||
this.host.removeEventListener("mousedown", this.onMiddleClick);
|
||
this.host.removeEventListener("wheel", this.onWheelZoom, { capture: true });
|
||
// A session with an owner (`onExit`) is ended by that owner.
|
||
if (this.ptyId !== null && !this.opts.command?.onExit) void commands.termKill(this.ptyId);
|
||
this.ptyId = null;
|
||
this.disposables.forEach((d) => d.dispose());
|
||
this.term.dispose();
|
||
this.host.remove();
|
||
}
|
||
}
|