源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
This commit is contained in:
commit
2ed3415fb7
8018 files changed
+1936476
No files matched your search
@@ -0,0 +1,57 @@
|
||||
# Workspace Terminal
|
||||
|
||||
Reusable terminal node contracts and shared frontend surface for Tutti
|
||||
workspace hosts.
|
||||
|
||||
The package owns host-agnostic terminal semantics. Hosts own concrete process
|
||||
launching, daemon clients, VM routing, Electron bridges, product copy, and
|
||||
durable terminal storage.
|
||||
|
||||
See `docs/architecture/workspace-terminal.md` for the current architecture and
|
||||
package boundary.
|
||||
|
||||
## Internal Layering
|
||||
|
||||
The shared terminal surface is intentionally split into narrow layers:
|
||||
|
||||
- `src/core/sessionController.ts`
|
||||
Owns terminal session orchestration. It composes recovery, state storage,
|
||||
input queueing, and transport lifetime, but should stay thin.
|
||||
- `src/core/sessionControllerStore.ts`
|
||||
Owns in-memory terminal session state such as `rawOutput`, `inputReady`, and
|
||||
`surfaceError`.
|
||||
- `src/core/sessionControllerRecovery.ts`
|
||||
Owns `snapshot -> attach -> replay` recovery semantics and transport event
|
||||
hydration.
|
||||
- `src/core/sessionDiagnostics.ts`
|
||||
Owns diagnostic event shaping so core and react layers do not scatter event
|
||||
names and payload shapes.
|
||||
- `src/react/terminalSurfaceRuntime.ts`
|
||||
Owns xterm wiring, buffered terminal writes, screen-cache restore/persist,
|
||||
resize observation, and host-agnostic terminal view behavior.
|
||||
- `src/react/TerminalSurface.tsx`
|
||||
Owns composition only. It should bind hooks, runtime handles, and UI
|
||||
controls, but should not become the owner of terminal transport recovery.
|
||||
|
||||
## Guardrails
|
||||
|
||||
- React view remounts must not directly own `snapshot`, `attach`, or `detach`.
|
||||
- Recovery behavior should be testable in `src/core/*` without mounting React.
|
||||
- Terminal view sync behavior should be testable in small `src/react/*` helper
|
||||
tests without constructing full host adapters.
|
||||
- New diagnostics should be added through `sessionDiagnostics.ts` instead of
|
||||
scattering raw event strings across the package.
|
||||
- Host-specific bridges, preload APIs, daemon clients, and absolute-path
|
||||
policies stay outside this package.
|
||||
|
||||
## Maintenance Rule Of Thumb
|
||||
|
||||
When adding new behavior, prefer:
|
||||
|
||||
1. pure helper in `src/core` or `src/react`
|
||||
2. narrow composition in `sessionController` or `terminalSurfaceRuntime`
|
||||
3. minimal wiring in `TerminalSurface` or `TerminalNode`
|
||||
|
||||
If a change wants to put transport lifetime, recovery sequencing, or daemon
|
||||
policy back into a React component, that is usually a sign the boundary is
|
||||
slipping.
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"name": "@tutti-os/workspace-terminal",
|
||||
"version": "0.1.0",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./contracts": "./src/contracts/index.ts",
|
||||
"./i18n": "./src/i18n/index.ts",
|
||||
"./react": "./src/react/index.ts",
|
||||
"./styles.css": "./src/styles/terminal.css",
|
||||
"./workbench": "./src/workbench/index.ts"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tutti-os/tutti.git",
|
||||
"directory": "packages/workspace/terminal"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup --config tsup.config.ts && node ../../../tools/scripts/copy-package-assets.mjs src/styles dist/styles",
|
||||
"test": "node --test --experimental-strip-types ./src/**/*.test.ts",
|
||||
"typecheck": "node ../../../tools/scripts/run-tsgo-typecheck.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tutti-os/ui-i18n-runtime": "workspace:*",
|
||||
"@tutti-os/ui-react-hooks": "workspace:*",
|
||||
"@tutti-os/ui-system": "workspace:*",
|
||||
"@tutti-os/workbench-surface": "workspace:*",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
"@xterm/addon-serialize": "^0.14.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/xterm": "^6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tutti-os/config-tsconfig": "workspace:*",
|
||||
"@types/node": "^24.0.1",
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
"tutti": {
|
||||
"tailwindSourceRoot": "src"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./contracts": {
|
||||
"types": "./dist/contracts/index.d.ts",
|
||||
"import": "./dist/contracts/index.js"
|
||||
},
|
||||
"./i18n": {
|
||||
"types": "./dist/i18n/index.d.ts",
|
||||
"import": "./dist/i18n/index.js"
|
||||
},
|
||||
"./react": {
|
||||
"types": "./dist/react/index.d.ts",
|
||||
"import": "./dist/react/index.js"
|
||||
},
|
||||
"./styles.css": "./dist/styles/terminal.css",
|
||||
"./workbench": {
|
||||
"types": "./dist/workbench/index.d.ts",
|
||||
"import": "./dist/workbench/index.js"
|
||||
}
|
||||
},
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export type TerminalRuntimeKind = "local" | "vm" | "remote" | (string & {});
|
||||
|
||||
export type TerminalSessionStatus =
|
||||
| "created"
|
||||
| "starting"
|
||||
| "running"
|
||||
| "detached"
|
||||
| "exited"
|
||||
| "failed";
|
||||
|
||||
export type TerminalWriteEncoding = "utf8" | "binary";
|
||||
|
||||
export type TerminalWriteProvenance = "auto" | "user";
|
||||
|
||||
export interface TerminalTransportAttachInput {
|
||||
afterSeq?: number;
|
||||
clientId?: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface TerminalTransportDetachInput {
|
||||
clientId?: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface TerminalTransportWriteInput {
|
||||
data: string;
|
||||
encoding?: TerminalWriteEncoding;
|
||||
provenance?: TerminalWriteProvenance;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface TerminalTransportResizeInput {
|
||||
cols: number;
|
||||
rows: number;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface TerminalTransportSnapshotInput {
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface TerminalSnapshot {
|
||||
data: string;
|
||||
fromSeq?: number;
|
||||
toSeq?: number;
|
||||
truncated?: boolean;
|
||||
updatedAt?: number;
|
||||
}
|
||||
|
||||
export interface TerminalDataEvent {
|
||||
data: string;
|
||||
seq?: number;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface TerminalExitEvent {
|
||||
code?: number | null;
|
||||
reason?: string | null;
|
||||
sessionId: string;
|
||||
signal?: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalMetadataEvent {
|
||||
cwd?: string | null;
|
||||
profileId?: string | null;
|
||||
resumeSessionId?: string | null;
|
||||
runtimeKind?: TerminalRuntimeKind;
|
||||
sessionId: string;
|
||||
title?: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalStateEvent {
|
||||
error?: string | null;
|
||||
gapEndSeq?: number | null;
|
||||
gapStartSeq?: number | null;
|
||||
sessionId: string;
|
||||
status: TerminalSessionStatus;
|
||||
}
|
||||
|
||||
export interface TerminalTransport {
|
||||
attach(input: TerminalTransportAttachInput): Promise<void>;
|
||||
detach(input: TerminalTransportDetachInput): Promise<void>;
|
||||
onData(listener: (event: TerminalDataEvent) => void): () => void;
|
||||
onExit(listener: (event: TerminalExitEvent) => void): () => void;
|
||||
onMetadata?(listener: (event: TerminalMetadataEvent) => void): () => void;
|
||||
onState(listener: (event: TerminalStateEvent) => void): () => void;
|
||||
resize(input: TerminalTransportResizeInput): Promise<void>;
|
||||
snapshot(input: TerminalTransportSnapshotInput): Promise<TerminalSnapshot>;
|
||||
write(input: TerminalTransportWriteInput): Promise<void>;
|
||||
}
|
||||
|
||||
export interface TerminalLaunchInput {
|
||||
cwd?: string | null;
|
||||
initialInput?: string | null;
|
||||
profileId?: string | null;
|
||||
reason: "dock" | "intent" | "restore";
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
export interface TerminalSessionDescriptor {
|
||||
cwd: string | null;
|
||||
profileId: string | null;
|
||||
runtimeKind: TerminalRuntimeKind;
|
||||
sessionId: string;
|
||||
status: TerminalSessionStatus;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface TerminalLaunchService {
|
||||
create(input: TerminalLaunchInput): Promise<TerminalSessionDescriptor>;
|
||||
get?(sessionId: string): Promise<TerminalSessionDescriptor | null>;
|
||||
terminate(input: { sessionId: string }): Promise<void>;
|
||||
}
|
||||
|
||||
export type TerminalCloseGuardReason =
|
||||
| "foreground-process"
|
||||
| "not-running"
|
||||
| "running"
|
||||
| "unknown";
|
||||
|
||||
export interface TerminalCloseGuardResult {
|
||||
leaderCommand?: string | null;
|
||||
reason: TerminalCloseGuardReason;
|
||||
requiresConfirmation: boolean;
|
||||
status: TerminalSessionStatus;
|
||||
}
|
||||
|
||||
export interface TerminalCloseGuardService {
|
||||
check(input: { sessionId: string }): Promise<TerminalCloseGuardResult>;
|
||||
}
|
||||
|
||||
export interface TerminalLinkTarget {
|
||||
cwd?: string | null;
|
||||
column?: number;
|
||||
line?: number;
|
||||
path?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface TerminalLinkHandler {
|
||||
open(target: TerminalLinkTarget): Promise<void> | void;
|
||||
}
|
||||
|
||||
export interface TerminalDropInput {
|
||||
cwd: string | null;
|
||||
dataTransfer: DataTransfer;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export type TerminalDropInputResolver = (
|
||||
input: TerminalDropInput
|
||||
) => Promise<string | null> | string | null;
|
||||
|
||||
export type TerminalOutputTransform = (input: {
|
||||
data: string;
|
||||
sessionId: string;
|
||||
}) => string | null;
|
||||
|
||||
export type TerminalDiagnosticEvent =
|
||||
| "attach-complete"
|
||||
| "attach-error"
|
||||
| "attach-start"
|
||||
| "close-confirmed"
|
||||
| "close-requested"
|
||||
| "dispose"
|
||||
| "hydration-complete"
|
||||
| "hydration-gap"
|
||||
| "hydration-start"
|
||||
| "mount"
|
||||
| "output-projected"
|
||||
| "resize"
|
||||
| "snapshot-complete"
|
||||
| "snapshot-start"
|
||||
| "surface-output-sync"
|
||||
| "surface-output-written"
|
||||
| "write-error";
|
||||
|
||||
export interface TerminalDiagnostics {
|
||||
log(
|
||||
event: TerminalDiagnosticEvent,
|
||||
details?: Record<string, string | number | boolean | null>
|
||||
): void;
|
||||
}
|
||||
|
||||
export interface TerminalNodeExternalState<
|
||||
THostMetadata extends Record<string, unknown> = Record<string, unknown>
|
||||
> {
|
||||
createdAt: string | null;
|
||||
cwd: string | null;
|
||||
endedAt: string | null;
|
||||
host: THostMetadata | null;
|
||||
lastError: string | null;
|
||||
profileId: string | null;
|
||||
runtimeKind: TerminalRuntimeKind;
|
||||
sessionId: string | null;
|
||||
status: TerminalSessionStatus;
|
||||
title: string;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalNodeLimits {
|
||||
maxScrollbackLines: number;
|
||||
maxWriteBatchBytes: number;
|
||||
snapshotChunkBytes: number;
|
||||
}
|
||||
|
||||
export interface TerminalTheme {
|
||||
background?: string;
|
||||
cursor?: string;
|
||||
foreground?: string;
|
||||
selectionBackground?: string;
|
||||
}
|
||||
|
||||
export interface TerminalPreviewSegmentStyle {
|
||||
background?: string;
|
||||
bold?: boolean;
|
||||
color?: string;
|
||||
dim?: boolean;
|
||||
italic?: boolean;
|
||||
overline?: boolean;
|
||||
strikethrough?: boolean;
|
||||
underline?: boolean;
|
||||
}
|
||||
|
||||
export interface TerminalPreviewSegment {
|
||||
style?: TerminalPreviewSegmentStyle;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface TerminalPreviewLine {
|
||||
segments: readonly TerminalPreviewSegment[];
|
||||
}
|
||||
|
||||
export interface TerminalPreviewSnapshot {
|
||||
cols: number;
|
||||
cursorX: number;
|
||||
cursorY: number;
|
||||
lines: readonly TerminalPreviewLine[];
|
||||
revision: string;
|
||||
rows: number;
|
||||
updatedAtUnixMs: number;
|
||||
}
|
||||
|
||||
export interface TerminalPreviewChange {
|
||||
nodeId: string;
|
||||
sessionId: string;
|
||||
snapshot: TerminalPreviewSnapshot | null;
|
||||
}
|
||||
|
||||
export type TerminalPreviewChangeHandler = (
|
||||
change: TerminalPreviewChange
|
||||
) => void;
|
||||
|
||||
export type TerminalThemeResolver = (input: {
|
||||
runtimeKind: TerminalRuntimeKind;
|
||||
sessionId: string | null;
|
||||
status: TerminalSessionStatus;
|
||||
}) => TerminalTheme;
|
||||
|
||||
export interface TerminalHeaderAccessoryContext {
|
||||
externalState: TerminalNodeExternalState | null;
|
||||
sessionId: string | null;
|
||||
}
|
||||
|
||||
export type TerminalHeaderAccessoryRenderer = (
|
||||
context: TerminalHeaderAccessoryContext
|
||||
) => ReactNode;
|
||||
@@ -0,0 +1,61 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createTerminalAttachmentController } from "./attachmentController.ts";
|
||||
|
||||
function createDeferred<T>() {
|
||||
let reject!: (error: unknown) => void;
|
||||
let resolve!: (value: T | PromiseLike<T>) => void;
|
||||
const promise = new Promise<T>((nextResolve, nextReject) => {
|
||||
resolve = nextResolve;
|
||||
reject = nextReject;
|
||||
});
|
||||
return { promise, reject, resolve };
|
||||
}
|
||||
|
||||
test("attachment controller detaches only after an in-flight attach completes", async () => {
|
||||
const attachDeferred = createDeferred<void>();
|
||||
const events: string[] = [];
|
||||
const controller = createTerminalAttachmentController({
|
||||
clientId: "client-1",
|
||||
sessionId: "term-1",
|
||||
transport: {
|
||||
attach: async () => {
|
||||
events.push("attach");
|
||||
return attachDeferred.promise;
|
||||
},
|
||||
detach: async () => {
|
||||
events.push("detach");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const attachPromise = controller.attach(7);
|
||||
const detachPromise = controller.detach();
|
||||
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(events, ["attach"]);
|
||||
|
||||
attachDeferred.resolve();
|
||||
await attachPromise;
|
||||
await detachPromise;
|
||||
|
||||
assert.deepEqual(events, ["attach", "detach"]);
|
||||
});
|
||||
|
||||
test("attachment controller does not detach after a failed attach", async () => {
|
||||
const controller = createTerminalAttachmentController({
|
||||
clientId: "client-1",
|
||||
sessionId: "term-1",
|
||||
transport: {
|
||||
attach: async () => {
|
||||
throw new Error("attach failed");
|
||||
},
|
||||
detach: async () => {
|
||||
throw new Error("detach should not run");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await assert.rejects(() => controller.attach(), /attach failed/);
|
||||
await controller.detach();
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { TerminalTransport } from "../contracts/index.ts";
|
||||
|
||||
export interface TerminalAttachmentController {
|
||||
attach(afterSeq?: number): Promise<void>;
|
||||
detach(): Promise<void>;
|
||||
markDetached(): void;
|
||||
}
|
||||
|
||||
export function createTerminalAttachmentController(input: {
|
||||
clientId: string;
|
||||
sessionId: string;
|
||||
transport: Pick<TerminalTransport, "attach" | "detach">;
|
||||
}): TerminalAttachmentController {
|
||||
let attached = false;
|
||||
let attachPromise: Promise<void> | null = null;
|
||||
let detachIssued = false;
|
||||
let detachPromise: Promise<void> | null = null;
|
||||
let detachRequested = false;
|
||||
|
||||
const issueDetach = async () => {
|
||||
if (detachIssued || !attached) {
|
||||
return;
|
||||
}
|
||||
detachIssued = true;
|
||||
attached = false;
|
||||
await input.transport.detach({
|
||||
clientId: input.clientId,
|
||||
sessionId: input.sessionId
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
attach(afterSeq) {
|
||||
if (attachPromise) {
|
||||
return attachPromise;
|
||||
}
|
||||
if (attached) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
attachPromise = input.transport
|
||||
.attach({
|
||||
afterSeq,
|
||||
clientId: input.clientId,
|
||||
sessionId: input.sessionId
|
||||
})
|
||||
.then(async () => {
|
||||
attached = true;
|
||||
attachPromise = null;
|
||||
if (detachRequested) {
|
||||
await issueDetach();
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
attachPromise = null;
|
||||
throw error;
|
||||
});
|
||||
|
||||
return attachPromise;
|
||||
},
|
||||
async detach() {
|
||||
detachRequested = true;
|
||||
if (detachPromise) {
|
||||
return detachPromise;
|
||||
}
|
||||
detachPromise = Promise.resolve(attachPromise)
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await issueDetach();
|
||||
})
|
||||
.finally(() => {
|
||||
attachPromise = null;
|
||||
detachIssued = false;
|
||||
detachPromise = null;
|
||||
detachRequested = false;
|
||||
});
|
||||
return detachPromise;
|
||||
},
|
||||
markDetached() {
|
||||
attached = false;
|
||||
attachPromise = null;
|
||||
detachIssued = false;
|
||||
detachPromise = null;
|
||||
detachRequested = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { closeTerminalSession } from "./closeFlow.ts";
|
||||
import type { TerminalNodeFeature } from "./feature.ts";
|
||||
|
||||
test("closeTerminalSession terminates immediately when guard allows close", async () => {
|
||||
const events: string[] = [];
|
||||
const feature = createCloseFeature({
|
||||
events,
|
||||
reason: "running",
|
||||
requiresConfirmation: false,
|
||||
terminate: async () => {
|
||||
events.push("terminate");
|
||||
}
|
||||
});
|
||||
|
||||
const result = await closeTerminalSession({
|
||||
feature,
|
||||
sessionId: "term-1"
|
||||
});
|
||||
|
||||
assert.equal(result, "closed");
|
||||
assert.deepEqual(events, [
|
||||
"diagnostic:close-requested",
|
||||
"terminate",
|
||||
"diagnostic:close-confirmed"
|
||||
]);
|
||||
});
|
||||
|
||||
test("closeTerminalSession keeps session open when confirmation is rejected", async () => {
|
||||
const events: string[] = [];
|
||||
const feature = createCloseFeature({
|
||||
events,
|
||||
requiresConfirmation: true,
|
||||
terminate: async () => {
|
||||
events.push("terminate");
|
||||
}
|
||||
});
|
||||
|
||||
const result = await closeTerminalSession({
|
||||
confirm: () => false,
|
||||
feature,
|
||||
sessionId: "term-1"
|
||||
});
|
||||
|
||||
assert.equal(result, "kept-open");
|
||||
assert.deepEqual(events, ["diagnostic:close-requested"]);
|
||||
});
|
||||
|
||||
test("closeTerminalSession closes ended sessions without host calls", async () => {
|
||||
const events: string[] = [];
|
||||
let terminateCalls = 0;
|
||||
const feature = createCloseFeature({
|
||||
events,
|
||||
requiresConfirmation: false,
|
||||
terminate: async () => {
|
||||
terminateCalls += 1;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await closeTerminalSession({
|
||||
feature,
|
||||
sessionId: "term-1",
|
||||
status: "failed"
|
||||
});
|
||||
|
||||
assert.equal(result, "closed");
|
||||
assert.equal(terminateCalls, 0);
|
||||
assert.deepEqual(events, []);
|
||||
});
|
||||
|
||||
test("closeTerminalSession still terminates idle sessions when guard reports not-running", async () => {
|
||||
const events: string[] = [];
|
||||
let terminateCalls = 0;
|
||||
const feature = createCloseFeature({
|
||||
events,
|
||||
requiresConfirmation: false,
|
||||
reason: "not-running",
|
||||
status: "running",
|
||||
terminate: async () => {
|
||||
terminateCalls += 1;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await closeTerminalSession({
|
||||
feature,
|
||||
sessionId: "term-1"
|
||||
});
|
||||
|
||||
assert.equal(result, "closed");
|
||||
assert.equal(terminateCalls, 1);
|
||||
assert.deepEqual(events, [
|
||||
"diagnostic:close-requested",
|
||||
"diagnostic:close-confirmed"
|
||||
]);
|
||||
});
|
||||
|
||||
test("closeTerminalSession treats ended not-running guards as already closed", async () => {
|
||||
const events: string[] = [];
|
||||
let terminateCalls = 0;
|
||||
const feature = createCloseFeature({
|
||||
events,
|
||||
requiresConfirmation: false,
|
||||
reason: "not-running",
|
||||
status: "failed",
|
||||
terminate: async () => {
|
||||
terminateCalls += 1;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await closeTerminalSession({
|
||||
feature,
|
||||
sessionId: "term-1"
|
||||
});
|
||||
|
||||
assert.equal(result, "closed");
|
||||
assert.equal(terminateCalls, 0);
|
||||
assert.deepEqual(events, [
|
||||
"diagnostic:close-requested",
|
||||
"diagnostic:close-confirmed"
|
||||
]);
|
||||
});
|
||||
|
||||
function createCloseFeature(input: {
|
||||
events: string[];
|
||||
reason?: "running" | "not-running";
|
||||
requiresConfirmation: boolean;
|
||||
status?: "running" | "failed";
|
||||
terminate(): Promise<void>;
|
||||
}): Pick<TerminalNodeFeature, "closeGuard" | "diagnostics" | "launchService"> {
|
||||
return {
|
||||
closeGuard: {
|
||||
async check() {
|
||||
return {
|
||||
reason:
|
||||
input.reason ??
|
||||
(input.requiresConfirmation ? "running" : "not-running"),
|
||||
requiresConfirmation: input.requiresConfirmation,
|
||||
status: input.status ?? "running"
|
||||
};
|
||||
}
|
||||
},
|
||||
diagnostics: {
|
||||
log(event) {
|
||||
input.events.push(`diagnostic:${event}`);
|
||||
}
|
||||
},
|
||||
launchService: {
|
||||
async create() {
|
||||
throw new Error("not used");
|
||||
},
|
||||
terminate: () => input.terminate()
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type {
|
||||
TerminalCloseGuardResult,
|
||||
TerminalLaunchService,
|
||||
TerminalSessionStatus
|
||||
} from "../contracts/index.ts";
|
||||
import { createTerminalCloseDiagnostics } from "./sessionDiagnostics.ts";
|
||||
import type { TerminalNodeFeature } from "./feature.ts";
|
||||
import { isTerminalSessionEndedStatus } from "./sessionProjection.ts";
|
||||
|
||||
export type TerminalCloseConfirmation = (
|
||||
guard: TerminalCloseGuardResult
|
||||
) => Promise<boolean> | boolean;
|
||||
|
||||
export type TerminalCloseResult = "closed" | "kept-open";
|
||||
|
||||
export interface CloseTerminalSessionInput {
|
||||
confirm?: TerminalCloseConfirmation;
|
||||
feature: Pick<TerminalNodeFeature, "closeGuard" | "diagnostics"> & {
|
||||
launchService: Pick<TerminalLaunchService, "terminate">;
|
||||
};
|
||||
sessionId: string | null | undefined;
|
||||
status?: TerminalSessionStatus | null | undefined;
|
||||
}
|
||||
|
||||
export async function closeTerminalSession({
|
||||
confirm,
|
||||
feature,
|
||||
sessionId,
|
||||
status
|
||||
}: CloseTerminalSessionInput): Promise<TerminalCloseResult> {
|
||||
if (!sessionId || (status && isTerminalSessionEndedStatus(status))) {
|
||||
return "closed";
|
||||
}
|
||||
|
||||
const closeDiagnostics = createTerminalCloseDiagnostics({
|
||||
diagnostics: feature.diagnostics,
|
||||
sessionId
|
||||
});
|
||||
|
||||
closeDiagnostics.requested();
|
||||
const guard = await feature.closeGuard.check({ sessionId });
|
||||
if (isTerminalSessionEndedStatus(guard.status)) {
|
||||
closeDiagnostics.confirmed();
|
||||
return "closed";
|
||||
}
|
||||
if (guard.requiresConfirmation) {
|
||||
const confirmed = await confirm?.(guard);
|
||||
if (!confirmed) {
|
||||
return "kept-open";
|
||||
}
|
||||
}
|
||||
|
||||
await feature.launchService.terminate({ sessionId });
|
||||
closeDiagnostics.confirmed();
|
||||
return "closed";
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { resolveInitialTerminalDimensions } from "./dimensions.ts";
|
||||
|
||||
test("resolveInitialTerminalDimensions floors valid dimensions", () => {
|
||||
assert.deepEqual(
|
||||
resolveInitialTerminalDimensions({
|
||||
cols: 120.8,
|
||||
rows: 33.2
|
||||
}),
|
||||
{
|
||||
cols: 120,
|
||||
rows: 33
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("resolveInitialTerminalDimensions rejects missing or invalid dimensions", () => {
|
||||
assert.equal(resolveInitialTerminalDimensions(null), null);
|
||||
assert.equal(resolveInitialTerminalDimensions({ cols: 80, rows: 0 }), null);
|
||||
assert.equal(
|
||||
resolveInitialTerminalDimensions({ cols: Number.NaN, rows: 24 }),
|
||||
null
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
export interface TerminalScreenDimensionsLike {
|
||||
cols?: number | null;
|
||||
rows?: number | null;
|
||||
}
|
||||
|
||||
export interface TerminalScreenDimensions {
|
||||
cols: number;
|
||||
rows: number;
|
||||
}
|
||||
|
||||
export function resolveInitialTerminalDimensions(
|
||||
state: TerminalScreenDimensionsLike | null | undefined
|
||||
): TerminalScreenDimensions | null {
|
||||
if (!state) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cols = normalizeTerminalDimension(state.cols);
|
||||
const rows = normalizeTerminalDimension(state.rows);
|
||||
|
||||
if (cols === null || rows === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { cols, rows };
|
||||
}
|
||||
|
||||
function normalizeTerminalDimension(
|
||||
value: number | null | undefined
|
||||
): number | null {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = Math.floor(value);
|
||||
return normalized > 0 ? normalized : null;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { I18nRuntime } from "@tutti-os/ui-i18n-runtime";
|
||||
import {
|
||||
createTerminalNodeI18nRuntime,
|
||||
type TerminalNodeI18nRuntime
|
||||
} from "../i18n/terminalNodeI18n.ts";
|
||||
import type {
|
||||
TerminalCloseGuardService,
|
||||
TerminalDiagnostics,
|
||||
TerminalDropInputResolver,
|
||||
TerminalLaunchService,
|
||||
TerminalLinkHandler,
|
||||
TerminalNodeLimits,
|
||||
TerminalOutputTransform,
|
||||
TerminalThemeResolver,
|
||||
TerminalTransport
|
||||
} from "../contracts/index.ts";
|
||||
|
||||
export interface TerminalNodeFeature {
|
||||
closeGuard: TerminalCloseGuardService;
|
||||
diagnostics: TerminalDiagnostics;
|
||||
dropInput?: TerminalDropInputResolver;
|
||||
i18n: TerminalNodeI18nRuntime;
|
||||
launchService: TerminalLaunchService;
|
||||
limits: TerminalNodeLimits;
|
||||
linkHandler?: TerminalLinkHandler;
|
||||
outputTransform?: TerminalOutputTransform;
|
||||
resolveTheme: TerminalThemeResolver;
|
||||
transport: TerminalTransport;
|
||||
}
|
||||
|
||||
export interface CreateTerminalNodeFeatureInput {
|
||||
closeGuard: TerminalCloseGuardService;
|
||||
diagnostics?: TerminalDiagnostics;
|
||||
dropInput?: TerminalDropInputResolver;
|
||||
i18n?: I18nRuntime<string>;
|
||||
launchService: TerminalLaunchService;
|
||||
limits?: Partial<TerminalNodeLimits>;
|
||||
linkHandler?: TerminalLinkHandler;
|
||||
outputTransform?: TerminalOutputTransform;
|
||||
resolveTheme?: TerminalThemeResolver;
|
||||
transport: TerminalTransport;
|
||||
}
|
||||
|
||||
export const defaultTerminalNodeLimits: TerminalNodeLimits = {
|
||||
maxScrollbackLines: 10_000,
|
||||
maxWriteBatchBytes: 64 * 1024,
|
||||
snapshotChunkBytes: 256 * 1024
|
||||
};
|
||||
|
||||
const noopTerminalDiagnostics: TerminalDiagnostics = {
|
||||
log() {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const defaultResolveTerminalTheme: TerminalThemeResolver = () => ({});
|
||||
|
||||
export function createTerminalNodeFeature(
|
||||
input: CreateTerminalNodeFeatureInput
|
||||
): TerminalNodeFeature {
|
||||
return {
|
||||
closeGuard: input.closeGuard,
|
||||
diagnostics: input.diagnostics ?? noopTerminalDiagnostics,
|
||||
dropInput: input.dropInput,
|
||||
i18n: createTerminalNodeI18nRuntime(input.i18n),
|
||||
launchService: input.launchService,
|
||||
limits: {
|
||||
...defaultTerminalNodeLimits,
|
||||
...input.limits
|
||||
},
|
||||
linkHandler: input.linkHandler,
|
||||
outputTransform: input.outputTransform,
|
||||
resolveTheme: input.resolveTheme ?? defaultResolveTerminalTheme,
|
||||
transport: input.transport
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
export {
|
||||
createTerminalAttachmentController,
|
||||
type TerminalAttachmentController
|
||||
} from "./attachmentController.ts";
|
||||
export {
|
||||
closeTerminalSession,
|
||||
type CloseTerminalSessionInput,
|
||||
type TerminalCloseConfirmation,
|
||||
type TerminalCloseResult
|
||||
} from "./closeFlow.ts";
|
||||
export {
|
||||
createTerminalNodeFeature,
|
||||
defaultTerminalNodeLimits,
|
||||
type CreateTerminalNodeFeatureInput,
|
||||
type TerminalNodeFeature
|
||||
} from "./feature.ts";
|
||||
export {
|
||||
createBufferedTerminalInputQueue,
|
||||
writeQueuedTerminalInput,
|
||||
type BufferedTerminalInputQueue,
|
||||
type QueuedTerminalInput
|
||||
} from "./inputQueue.ts";
|
||||
export {
|
||||
detectTerminalFileLinks,
|
||||
toTerminalLinkTarget,
|
||||
type DetectedTerminalFileLink
|
||||
} from "./linkDetection.ts";
|
||||
export {
|
||||
resolveInitialTerminalDimensions,
|
||||
type TerminalScreenDimensions,
|
||||
type TerminalScreenDimensionsLike
|
||||
} from "./dimensions.ts";
|
||||
export {
|
||||
applyTerminalSessionStatusProjection,
|
||||
applyTerminalSessionTitleProjection,
|
||||
createTerminalSessionExitProjection,
|
||||
createTerminalSessionFailedProjection,
|
||||
isTerminalSessionEndedStatus,
|
||||
terminalSessionLostMessage,
|
||||
type TerminalSessionStatusProjection
|
||||
} from "./sessionProjection.ts";
|
||||
export {
|
||||
createTerminalScreenStateCache,
|
||||
type CachedTerminalScreenState,
|
||||
type TerminalScreenStateCache
|
||||
} from "./screenStateCache.ts";
|
||||
export {
|
||||
defaultMaxTerminalScrollbackChars,
|
||||
mergeTerminalScrollbackSnapshots,
|
||||
resolveTerminalScrollbackDelta,
|
||||
truncateTerminalScrollback,
|
||||
type TerminalScrollbackOptions
|
||||
} from "./scrollback.ts";
|
||||
export { resolveSuffixPrefixOverlap } from "./stringOverlap.ts";
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
createBufferedTerminalInputQueue,
|
||||
writeQueuedTerminalInput
|
||||
} from "./inputQueue.ts";
|
||||
|
||||
test("buffered terminal input queue preserves binary and utf8 ordering", async () => {
|
||||
const queue = createBufferedTerminalInputQueue();
|
||||
const writes: Array<{ data: string; encoding?: string }> = [];
|
||||
|
||||
queue.enqueue("ls\n");
|
||||
queue.enqueue("\u0003", "binary");
|
||||
|
||||
await writeQueuedTerminalInput({
|
||||
queue,
|
||||
sessionId: "term-1",
|
||||
transport: {
|
||||
async write(input) {
|
||||
writes.push({
|
||||
data: input.data,
|
||||
encoding: input.encoding
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
assert.deepEqual(writes, [
|
||||
{
|
||||
data: "ls\n",
|
||||
encoding: "utf8"
|
||||
},
|
||||
{
|
||||
data: "\u0003",
|
||||
encoding: "binary"
|
||||
}
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type {
|
||||
TerminalTransport,
|
||||
TerminalWriteEncoding
|
||||
} from "../contracts/index.ts";
|
||||
|
||||
export interface QueuedTerminalInput {
|
||||
data: string;
|
||||
encoding: TerminalWriteEncoding;
|
||||
}
|
||||
|
||||
export interface BufferedTerminalInputQueue {
|
||||
enqueue(data: string, encoding?: TerminalWriteEncoding): void;
|
||||
flush(writer: (entry: QueuedTerminalInput) => Promise<void>): Promise<void>;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
export function createBufferedTerminalInputQueue(): BufferedTerminalInputQueue {
|
||||
const entries: QueuedTerminalInput[] = [];
|
||||
|
||||
return {
|
||||
enqueue(data, encoding = "utf8") {
|
||||
if (data.length === 0) {
|
||||
return;
|
||||
}
|
||||
entries.push({ data, encoding });
|
||||
},
|
||||
async flush(writer) {
|
||||
const queued = entries.splice(0);
|
||||
for (const entry of queued) {
|
||||
await writer(entry);
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
entries.length = 0;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export async function writeQueuedTerminalInput(input: {
|
||||
queue: BufferedTerminalInputQueue;
|
||||
sessionId: string;
|
||||
transport: Pick<TerminalTransport, "write">;
|
||||
}): Promise<void> {
|
||||
await input.queue.flush((entry) =>
|
||||
input.transport.write({
|
||||
data: entry.data,
|
||||
encoding: entry.encoding,
|
||||
provenance: "user",
|
||||
sessionId: input.sessionId
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { detectTerminalFileLinks } from "./linkDetection.ts";
|
||||
|
||||
test("detectTerminalFileLinks detects absolute and relative paths with locations", () => {
|
||||
assert.deepEqual(
|
||||
detectTerminalFileLinks(
|
||||
"src/main.ts:12:4 /tmp/demo.txt ./pkg/index.ts(9, 2)"
|
||||
).map(({ column, line, path, text }) => ({ column, line, path, text })),
|
||||
[
|
||||
{
|
||||
column: 4,
|
||||
line: 12,
|
||||
path: "src/main.ts",
|
||||
text: "src/main.ts:12:4"
|
||||
},
|
||||
{
|
||||
column: undefined,
|
||||
line: undefined,
|
||||
path: "/tmp/demo.txt",
|
||||
text: "/tmp/demo.txt"
|
||||
},
|
||||
{
|
||||
column: 2,
|
||||
line: 9,
|
||||
path: "./pkg/index.ts",
|
||||
text: "./pkg/index.ts(9, 2)"
|
||||
}
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test("detectTerminalFileLinks skips urls and pure numeric locations", () => {
|
||||
assert.deepEqual(
|
||||
detectTerminalFileLinks(
|
||||
"https://example.com/a/b 10:20 ~/project/file.md[7]"
|
||||
).map(({ line, path, text }) => ({ line, path, text })),
|
||||
[
|
||||
{
|
||||
line: 7,
|
||||
path: "~/project/file.md",
|
||||
text: "~/project/file.md[7]"
|
||||
}
|
||||
]
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import type { TerminalLinkTarget } from "../contracts/index.ts";
|
||||
|
||||
export interface DetectedTerminalFileLink {
|
||||
column?: number;
|
||||
index: number;
|
||||
line?: number;
|
||||
path: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
const pathCandidatePattern =
|
||||
/(?<path>(?:~|\.{1,2}|\/)[^\s"'`<>|:([\]]+|[A-Za-z0-9_.-]+\/[^\s"'`<>|:([\]]+)(?<suffix>(?::(?<lineColon>\d+)(?::(?<columnColon>\d+))?)|(?:\((?<lineParen>\d+)(?:,\s*(?<columnParen>\d+))?\))|(?:\[(?<lineBracket>\d+)(?:,\s*(?<columnBracket>\d+))?\]))?/g;
|
||||
|
||||
export function detectTerminalFileLinks(
|
||||
text: string
|
||||
): DetectedTerminalFileLink[] {
|
||||
const links: DetectedTerminalFileLink[] = [];
|
||||
pathCandidatePattern.lastIndex = 0;
|
||||
|
||||
let match = pathCandidatePattern.exec(text);
|
||||
while (match) {
|
||||
const groups = match.groups ?? {};
|
||||
const rawPath = groups.path ?? "";
|
||||
const suffix = groups.suffix ?? "";
|
||||
const candidateText = `${rawPath}${suffix}`;
|
||||
const trimmed = trimTerminalPathCandidate(rawPath);
|
||||
const trimAmount = rawPath.length - trimmed.length;
|
||||
|
||||
if (isTerminalPathCandidate(trimmed, text, match.index)) {
|
||||
const line = parsePositiveInteger(
|
||||
groups.lineColon ?? groups.lineParen ?? groups.lineBracket
|
||||
);
|
||||
const column = parsePositiveInteger(
|
||||
groups.columnColon ?? groups.columnParen ?? groups.columnBracket
|
||||
);
|
||||
links.push({
|
||||
column,
|
||||
index: match.index,
|
||||
line,
|
||||
path: trimmed,
|
||||
text: candidateText.slice(0, candidateText.length - trimAmount)
|
||||
});
|
||||
}
|
||||
|
||||
match = pathCandidatePattern.exec(text);
|
||||
}
|
||||
|
||||
return links;
|
||||
}
|
||||
|
||||
export function toTerminalLinkTarget(
|
||||
link: DetectedTerminalFileLink
|
||||
): TerminalLinkTarget {
|
||||
return {
|
||||
column: link.column,
|
||||
line: link.line,
|
||||
path: link.path
|
||||
};
|
||||
}
|
||||
|
||||
function trimTerminalPathCandidate(value: string): string {
|
||||
let result = value.trim();
|
||||
while (/[),.;:!?]$/.test(result) && !looksLikeFileExtension(result)) {
|
||||
result = result.slice(0, -1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function looksLikeFileExtension(value: string): boolean {
|
||||
return /\.[A-Za-z0-9]{1,8}$/.test(value);
|
||||
}
|
||||
|
||||
function isTerminalPathCandidate(
|
||||
value: string,
|
||||
sourceText: string,
|
||||
index: number
|
||||
): boolean {
|
||||
if (value.length === 0) {
|
||||
return false;
|
||||
}
|
||||
if (/^\d+(?::\d+)*$/.test(value)) {
|
||||
return false;
|
||||
}
|
||||
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
|
||||
return false;
|
||||
}
|
||||
if (value.startsWith("//") || sourceText[index - 1] === ":") {
|
||||
return false;
|
||||
}
|
||||
if (value.startsWith("node:")) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
value.startsWith("/") ||
|
||||
value.startsWith("./") ||
|
||||
value.startsWith("../") ||
|
||||
value.startsWith("~/") ||
|
||||
value.includes("/")
|
||||
);
|
||||
}
|
||||
|
||||
function parsePositiveInteger(value: string | undefined): number | undefined {
|
||||
if (!value) {
|
||||
return undefined;
|
||||
}
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createTerminalScreenStateCache } from "./screenStateCache.ts";
|
||||
|
||||
test("terminal screen cache returns state only for matching node and session", () => {
|
||||
const cache = createTerminalScreenStateCache();
|
||||
|
||||
cache.set(" node-1 ", {
|
||||
cols: 80.7,
|
||||
rawSnapshot: "raw",
|
||||
rows: 24.2,
|
||||
serialized: "screen",
|
||||
sessionId: " session-1 "
|
||||
});
|
||||
|
||||
assert.deepEqual(cache.get("node-1", "session-1"), {
|
||||
cols: 80,
|
||||
rawSnapshot: "raw",
|
||||
rows: 24,
|
||||
serialized: "screen",
|
||||
sessionId: "session-1"
|
||||
});
|
||||
assert.equal(cache.get("node-1", "session-2"), null);
|
||||
});
|
||||
|
||||
test("terminal screen cache invalidation blocks stale writes once", () => {
|
||||
const cache = createTerminalScreenStateCache();
|
||||
|
||||
cache.set("node-1", {
|
||||
cols: 80,
|
||||
rawSnapshot: "raw",
|
||||
rows: 24,
|
||||
serialized: "screen",
|
||||
sessionId: "session-1"
|
||||
});
|
||||
cache.invalidate("node-1", "session-1");
|
||||
|
||||
assert.equal(cache.isInvalidated("node-1", "session-1"), true);
|
||||
assert.equal(cache.get("node-1", "session-1"), null);
|
||||
|
||||
cache.set("node-1", {
|
||||
cols: 80,
|
||||
rawSnapshot: "late",
|
||||
rows: 24,
|
||||
serialized: "late-screen",
|
||||
sessionId: "session-1"
|
||||
});
|
||||
|
||||
assert.equal(cache.isInvalidated("node-1", "session-1"), false);
|
||||
assert.equal(cache.get("node-1", "session-1"), null);
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
export interface CachedTerminalScreenState {
|
||||
cols: number;
|
||||
rawSnapshot: string;
|
||||
rows: number;
|
||||
serialized: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export interface TerminalScreenStateCache {
|
||||
clear(): void;
|
||||
clearInvalidation(nodeId: string, sessionId: string): void;
|
||||
get(nodeId: string, sessionId: string): CachedTerminalScreenState | null;
|
||||
invalidate(nodeId: string, sessionId: string): void;
|
||||
isInvalidated(nodeId: string, sessionId: string): boolean;
|
||||
peek(nodeId: string): CachedTerminalScreenState | null;
|
||||
remove(nodeId: string, sessionId: string): void;
|
||||
set(nodeId: string, state: CachedTerminalScreenState): void;
|
||||
}
|
||||
|
||||
export function createTerminalScreenStateCache(): TerminalScreenStateCache {
|
||||
const screenStateByNodeId = new Map<string, CachedTerminalScreenState>();
|
||||
const invalidatedSessionIdByNodeId = new Map<string, string>();
|
||||
|
||||
const get = (
|
||||
nodeId: string,
|
||||
sessionId: string
|
||||
): CachedTerminalScreenState | null => {
|
||||
const normalizedNodeId = normalizeId(nodeId);
|
||||
const normalizedSessionId = normalizeId(sessionId);
|
||||
|
||||
if (normalizedNodeId.length === 0 || normalizedSessionId.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
invalidatedSessionIdByNodeId.get(normalizedNodeId) === normalizedSessionId
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cached = screenStateByNodeId.get(normalizedNodeId);
|
||||
if (!cached || cached.sessionId !== normalizedSessionId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return cached;
|
||||
};
|
||||
|
||||
const peek = (nodeId: string): CachedTerminalScreenState | null => {
|
||||
const normalizedNodeId = normalizeId(nodeId);
|
||||
if (normalizedNodeId.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return screenStateByNodeId.get(normalizedNodeId) ?? null;
|
||||
};
|
||||
|
||||
const set = (nodeId: string, state: CachedTerminalScreenState): void => {
|
||||
const normalizedNodeId = normalizeId(nodeId);
|
||||
const normalizedSessionId = normalizeId(state.sessionId);
|
||||
|
||||
if (
|
||||
normalizedNodeId.length === 0 ||
|
||||
normalizedSessionId.length === 0 ||
|
||||
state.serialized.length === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
invalidatedSessionIdByNodeId.get(normalizedNodeId) === normalizedSessionId
|
||||
) {
|
||||
invalidatedSessionIdByNodeId.delete(normalizedNodeId);
|
||||
return;
|
||||
}
|
||||
|
||||
invalidatedSessionIdByNodeId.delete(normalizedNodeId);
|
||||
screenStateByNodeId.set(normalizedNodeId, {
|
||||
cols: normalizeDimension(state.cols, 80),
|
||||
rawSnapshot: state.rawSnapshot,
|
||||
rows: normalizeDimension(state.rows, 24),
|
||||
serialized: state.serialized,
|
||||
sessionId: normalizedSessionId
|
||||
});
|
||||
};
|
||||
|
||||
const remove = (nodeId: string, sessionId: string): void => {
|
||||
const normalizedNodeId = normalizeId(nodeId);
|
||||
const normalizedSessionId = normalizeId(sessionId);
|
||||
|
||||
if (normalizedNodeId.length === 0 || normalizedSessionId.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cached = screenStateByNodeId.get(normalizedNodeId);
|
||||
if (cached?.sessionId === normalizedSessionId) {
|
||||
screenStateByNodeId.delete(normalizedNodeId);
|
||||
}
|
||||
|
||||
if (
|
||||
invalidatedSessionIdByNodeId.get(normalizedNodeId) === normalizedSessionId
|
||||
) {
|
||||
invalidatedSessionIdByNodeId.delete(normalizedNodeId);
|
||||
}
|
||||
};
|
||||
|
||||
const invalidate = (nodeId: string, sessionId: string): void => {
|
||||
const normalizedNodeId = normalizeId(nodeId);
|
||||
const normalizedSessionId = normalizeId(sessionId);
|
||||
|
||||
if (normalizedNodeId.length === 0 || normalizedSessionId.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
screenStateByNodeId.delete(normalizedNodeId);
|
||||
invalidatedSessionIdByNodeId.set(normalizedNodeId, normalizedSessionId);
|
||||
};
|
||||
|
||||
const isInvalidated = (nodeId: string, sessionId: string): boolean => {
|
||||
const normalizedNodeId = normalizeId(nodeId);
|
||||
const normalizedSessionId = normalizeId(sessionId);
|
||||
|
||||
if (normalizedNodeId.length === 0 || normalizedSessionId.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
invalidatedSessionIdByNodeId.get(normalizedNodeId) === normalizedSessionId
|
||||
);
|
||||
};
|
||||
|
||||
const clearInvalidation = (nodeId: string, sessionId: string): void => {
|
||||
const normalizedNodeId = normalizeId(nodeId);
|
||||
const normalizedSessionId = normalizeId(sessionId);
|
||||
|
||||
if (normalizedNodeId.length === 0 || normalizedSessionId.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
invalidatedSessionIdByNodeId.get(normalizedNodeId) !== normalizedSessionId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
invalidatedSessionIdByNodeId.delete(normalizedNodeId);
|
||||
};
|
||||
|
||||
const clear = (): void => {
|
||||
screenStateByNodeId.clear();
|
||||
invalidatedSessionIdByNodeId.clear();
|
||||
};
|
||||
|
||||
return {
|
||||
clear,
|
||||
clearInvalidation,
|
||||
get,
|
||||
invalidate,
|
||||
isInvalidated,
|
||||
peek,
|
||||
remove,
|
||||
set
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeId(value: string): string {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function normalizeDimension(value: number, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0
|
||||
? Math.floor(value)
|
||||
: fallback;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
mergeTerminalScrollbackSnapshots,
|
||||
resolveTerminalScrollbackDelta,
|
||||
truncateTerminalScrollback
|
||||
} from "./scrollback.ts";
|
||||
import { resolveSuffixPrefixOverlap } from "./stringOverlap.ts";
|
||||
|
||||
test("resolveSuffixPrefixOverlap finds the longest suffix/prefix match", () => {
|
||||
assert.equal(resolveSuffixPrefixOverlap("abc123", "123def"), 3);
|
||||
assert.equal(resolveSuffixPrefixOverlap("abc", "def"), 0);
|
||||
assert.equal(resolveSuffixPrefixOverlap("", "def"), 0);
|
||||
});
|
||||
|
||||
test("resolveTerminalScrollbackDelta returns only newly appended output", () => {
|
||||
assert.equal(resolveTerminalScrollbackDelta("hello\nwor", "world\n"), "ld\n");
|
||||
assert.equal(resolveTerminalScrollbackDelta("same", "same"), "");
|
||||
assert.equal(resolveTerminalScrollbackDelta("", "first"), "first");
|
||||
});
|
||||
|
||||
test("mergeTerminalScrollbackSnapshots deduplicates overlapping snapshots", () => {
|
||||
assert.equal(
|
||||
mergeTerminalScrollbackSnapshots("alpha\nbeta\n", "beta\ngamma\n"),
|
||||
"alpha\nbeta\ngamma\n"
|
||||
);
|
||||
assert.equal(mergeTerminalScrollbackSnapshots("abc", "abcdef"), "abcdef");
|
||||
assert.equal(mergeTerminalScrollbackSnapshots("abcdef", "abc"), "abcdef");
|
||||
});
|
||||
|
||||
test("truncateTerminalScrollback keeps the newest content", () => {
|
||||
assert.equal(truncateTerminalScrollback("abcdef", { maxChars: 3 }), "def");
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { resolveSuffixPrefixOverlap } from "./stringOverlap.ts";
|
||||
|
||||
export const defaultMaxTerminalScrollbackChars = 400_000;
|
||||
|
||||
export interface TerminalScrollbackOptions {
|
||||
maxChars?: number;
|
||||
}
|
||||
|
||||
export function truncateTerminalScrollback(
|
||||
snapshot: string,
|
||||
options?: TerminalScrollbackOptions
|
||||
): string {
|
||||
const maxChars = normalizeMaxChars(options?.maxChars);
|
||||
if (snapshot.length <= maxChars) {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
return snapshot.slice(-maxChars);
|
||||
}
|
||||
|
||||
export function resolveTerminalScrollbackDelta(
|
||||
previous: string,
|
||||
next: string,
|
||||
options?: TerminalScrollbackOptions
|
||||
): string {
|
||||
const previousSnapshot = truncateTerminalScrollback(previous, options);
|
||||
const nextSnapshot = truncateTerminalScrollback(next, options);
|
||||
|
||||
if (previousSnapshot.length === 0) {
|
||||
return nextSnapshot;
|
||||
}
|
||||
|
||||
if (nextSnapshot.length === 0 || previousSnapshot === nextSnapshot) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (previousSnapshot.includes(nextSnapshot)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const overlap = resolveSuffixPrefixOverlap(previousSnapshot, nextSnapshot);
|
||||
return nextSnapshot.slice(overlap);
|
||||
}
|
||||
|
||||
export function mergeTerminalScrollbackSnapshots(
|
||||
persisted: string,
|
||||
live: string,
|
||||
options?: TerminalScrollbackOptions
|
||||
): string {
|
||||
const persistedSnapshot = truncateTerminalScrollback(persisted, options);
|
||||
const liveSnapshot = truncateTerminalScrollback(live, options);
|
||||
|
||||
if (persistedSnapshot.length === 0) {
|
||||
return liveSnapshot;
|
||||
}
|
||||
|
||||
if (liveSnapshot.length === 0) {
|
||||
return persistedSnapshot;
|
||||
}
|
||||
|
||||
if (persistedSnapshot === liveSnapshot) {
|
||||
return liveSnapshot;
|
||||
}
|
||||
|
||||
if (liveSnapshot.includes(persistedSnapshot)) {
|
||||
return liveSnapshot;
|
||||
}
|
||||
|
||||
if (persistedSnapshot.includes(liveSnapshot)) {
|
||||
return persistedSnapshot;
|
||||
}
|
||||
|
||||
const overlap = resolveSuffixPrefixOverlap(persistedSnapshot, liveSnapshot);
|
||||
return truncateTerminalScrollback(
|
||||
`${persistedSnapshot}${liveSnapshot.slice(overlap)}`,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeMaxChars(value: number | undefined): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0
|
||||
? Math.floor(value)
|
||||
: defaultMaxTerminalScrollbackChars;
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import type {
|
||||
TerminalNodeLimits,
|
||||
TerminalWriteEncoding
|
||||
} from "../contracts/index.ts";
|
||||
import type { TerminalNodeFeature } from "./feature.ts";
|
||||
import {
|
||||
createBufferedTerminalInputQueue,
|
||||
type BufferedTerminalInputQueue
|
||||
} from "./inputQueue.ts";
|
||||
import {
|
||||
createTerminalSessionRecovery,
|
||||
type TerminalSessionRecoveryHandle
|
||||
} from "./sessionControllerRecovery.ts";
|
||||
import { createTerminalSessionRecoveryDiagnostics } from "./sessionDiagnostics.ts";
|
||||
import {
|
||||
createTerminalSessionControllerStore,
|
||||
type TerminalSessionControllerState,
|
||||
type TerminalSessionControllerStore
|
||||
} from "./sessionControllerStore.ts";
|
||||
import {
|
||||
acquireTerminalSessionTransportRuntime,
|
||||
type TerminalSessionTransportRuntime
|
||||
} from "./sessionTransportRuntime.ts";
|
||||
|
||||
export type { TerminalSessionControllerState } from "./sessionControllerStore.ts";
|
||||
|
||||
export interface TerminalSessionController {
|
||||
getState(): TerminalSessionControllerState;
|
||||
retain(): void;
|
||||
release(): void;
|
||||
resize(input: { cols: number; rows: number }): Promise<void>;
|
||||
subscribe(listener: () => void): () => void;
|
||||
write(data: string, encoding?: TerminalWriteEncoding): void;
|
||||
}
|
||||
|
||||
interface TerminalSessionControllerEntry {
|
||||
context: TerminalSessionControllerContext;
|
||||
disposed: boolean;
|
||||
inputQueue: BufferedTerminalInputQueue;
|
||||
recovery: TerminalSessionRecoveryHandle;
|
||||
refCount: number;
|
||||
release(): void;
|
||||
retainTimer: ReturnType<typeof setTimeout> | null;
|
||||
runtimeWriteReady: boolean;
|
||||
startPromise: Promise<void> | null;
|
||||
store: TerminalSessionControllerStore;
|
||||
teardown(): void;
|
||||
transportRuntime: TerminalSessionTransportRuntime;
|
||||
}
|
||||
|
||||
interface TerminalSessionControllerContext {
|
||||
feature: TerminalNodeFeature;
|
||||
nodeId: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
const defaultControllerRetainMs = 5_000;
|
||||
const controllerRegistry = new Map<string, TerminalSessionControllerEntry>();
|
||||
|
||||
export function acquireTerminalSessionController(input: {
|
||||
feature: TerminalNodeFeature;
|
||||
nodeId: string;
|
||||
retainMs?: number;
|
||||
sessionId: string;
|
||||
}): TerminalSessionController {
|
||||
const entry =
|
||||
controllerRegistry.get(input.sessionId) ??
|
||||
createTerminalSessionControllerEntry({
|
||||
feature: input.feature,
|
||||
nodeId: input.nodeId,
|
||||
retainMs: input.retainMs ?? defaultControllerRetainMs,
|
||||
sessionId: input.sessionId
|
||||
});
|
||||
if (!controllerRegistry.has(input.sessionId)) {
|
||||
controllerRegistry.set(input.sessionId, entry);
|
||||
}
|
||||
|
||||
entry.context = {
|
||||
feature: input.feature,
|
||||
nodeId: input.nodeId,
|
||||
sessionId: input.sessionId
|
||||
};
|
||||
|
||||
return {
|
||||
getState() {
|
||||
return entry.store.getState();
|
||||
},
|
||||
retain() {
|
||||
entry.refCount += 1;
|
||||
if (entry.retainTimer !== null) {
|
||||
clearTimeout(entry.retainTimer);
|
||||
entry.retainTimer = null;
|
||||
}
|
||||
ensureRecoveryStarted(entry);
|
||||
},
|
||||
release() {
|
||||
entry.release();
|
||||
},
|
||||
resize({ cols, rows }) {
|
||||
return entry.context.feature.transport.resize({
|
||||
cols,
|
||||
rows,
|
||||
sessionId: entry.context.sessionId
|
||||
});
|
||||
},
|
||||
subscribe(listener) {
|
||||
return entry.store.subscribe(listener);
|
||||
},
|
||||
write(data, encoding = "utf8") {
|
||||
if (!entry.runtimeWriteReady) {
|
||||
entry.inputQueue.enqueue(data, encoding);
|
||||
ensureRecoveryStarted(entry);
|
||||
return;
|
||||
}
|
||||
void writeTerminalInput(entry, data, encoding);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createTerminalSessionControllerEntry(input: {
|
||||
feature: TerminalNodeFeature;
|
||||
nodeId: string;
|
||||
retainMs: number;
|
||||
sessionId: string;
|
||||
}) {
|
||||
const transportRuntime = acquireTerminalSessionTransportRuntime({
|
||||
sessionId: input.sessionId,
|
||||
transport: input.feature.transport
|
||||
});
|
||||
const inputQueue = createBufferedTerminalInputQueue();
|
||||
const store = createTerminalSessionControllerStore({
|
||||
maxScrollbackChars: resolveMaxScrollbackChars(input.feature.limits)
|
||||
});
|
||||
|
||||
const entry = {
|
||||
context: {
|
||||
feature: input.feature,
|
||||
nodeId: input.nodeId,
|
||||
sessionId: input.sessionId
|
||||
},
|
||||
disposed: false,
|
||||
inputQueue,
|
||||
recovery: null as unknown as TerminalSessionRecoveryHandle,
|
||||
refCount: 0,
|
||||
release: () => undefined,
|
||||
retainTimer: null,
|
||||
runtimeWriteReady: false,
|
||||
startPromise: null,
|
||||
store,
|
||||
teardown: () => undefined,
|
||||
transportRuntime
|
||||
} as TerminalSessionControllerEntry;
|
||||
|
||||
entry.release = () => {
|
||||
entry.refCount = Math.max(0, entry.refCount - 1);
|
||||
if (entry.refCount > 0 || entry.retainTimer !== null) {
|
||||
return;
|
||||
}
|
||||
entry.retainTimer = setTimeout(() => {
|
||||
entry.retainTimer = null;
|
||||
if (entry.refCount > 0) {
|
||||
return;
|
||||
}
|
||||
entry.teardown();
|
||||
controllerRegistry.delete(entry.context.sessionId);
|
||||
}, input.retainMs);
|
||||
};
|
||||
|
||||
entry.teardown = () => {
|
||||
if (entry.disposed) {
|
||||
return;
|
||||
}
|
||||
entry.disposed = true;
|
||||
inputQueue.reset();
|
||||
entry.runtimeWriteReady = false;
|
||||
entry.recovery.dispose();
|
||||
transportRuntime.release();
|
||||
store.clearListeners();
|
||||
};
|
||||
|
||||
entry.recovery = createTerminalSessionRecovery({
|
||||
diagnostics: createTerminalSessionRecoveryDiagnostics({
|
||||
diagnostics: input.feature.diagnostics,
|
||||
nodeId: input.nodeId,
|
||||
sessionId: input.sessionId
|
||||
}),
|
||||
inputQueue,
|
||||
onRecoverableDetach() {
|
||||
if (entry.disposed || entry.refCount === 0) {
|
||||
return;
|
||||
}
|
||||
ensureRecoveryStarted(entry);
|
||||
},
|
||||
onWriteReadyChange(ready) {
|
||||
if (entry.disposed) {
|
||||
return;
|
||||
}
|
||||
entry.runtimeWriteReady = ready;
|
||||
},
|
||||
replayGapMessage: input.feature.i18n.t("recovery.replayGap"),
|
||||
sessionId: input.sessionId,
|
||||
snapshotTruncatedMessage: input.feature.i18n.t(
|
||||
"recovery.snapshotTruncated"
|
||||
),
|
||||
store,
|
||||
transport: input.feature.transport,
|
||||
transportRuntime
|
||||
});
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
function ensureRecoveryStarted(entry: TerminalSessionControllerEntry) {
|
||||
if (
|
||||
entry.disposed ||
|
||||
entry.startPromise !== null ||
|
||||
entry.runtimeWriteReady
|
||||
) {
|
||||
return;
|
||||
}
|
||||
entry.startPromise = entry.recovery.start().finally(() => {
|
||||
entry.startPromise = null;
|
||||
});
|
||||
}
|
||||
|
||||
function resolveMaxScrollbackChars(limits: TerminalNodeLimits) {
|
||||
return Math.max(limits.maxScrollbackLines * 160, 400_000);
|
||||
}
|
||||
|
||||
function writeTerminalInput(
|
||||
entry: TerminalSessionControllerEntry,
|
||||
data: string,
|
||||
encoding: TerminalWriteEncoding
|
||||
) {
|
||||
return entry.context.feature.transport
|
||||
.write({
|
||||
data,
|
||||
encoding,
|
||||
provenance: "user",
|
||||
sessionId: entry.context.sessionId
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
entry.runtimeWriteReady = false;
|
||||
entry.store.setInputReady(false);
|
||||
entry.inputQueue.enqueue(data, encoding);
|
||||
ensureRecoveryStarted(entry);
|
||||
entry.context.feature.diagnostics.log("write-error", {
|
||||
nodeId: entry.context.nodeId,
|
||||
sessionId: entry.context.sessionId
|
||||
});
|
||||
entry.store.setSurfaceError(errorMessage(error));
|
||||
});
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import type { BufferedTerminalInputQueue } from "./inputQueue.ts";
|
||||
import { writeQueuedTerminalInput } from "./inputQueue.ts";
|
||||
import type { TerminalTransport } from "../contracts/index.ts";
|
||||
import type { TerminalSessionRecoveryDiagnostics } from "./sessionDiagnostics.ts";
|
||||
import type { TerminalSessionControllerStore } from "./sessionControllerStore.ts";
|
||||
import type { TerminalSessionTransportRuntime } from "./sessionTransportRuntime.ts";
|
||||
|
||||
export interface TerminalSessionRecoveryHandle {
|
||||
dispose(): void;
|
||||
start(): Promise<void>;
|
||||
}
|
||||
|
||||
export function createTerminalSessionRecovery(input: {
|
||||
diagnostics: TerminalSessionRecoveryDiagnostics;
|
||||
inputQueue: BufferedTerminalInputQueue;
|
||||
onRecoverableDetach: () => void;
|
||||
onWriteReadyChange: (ready: boolean) => void;
|
||||
replayGapMessage: string;
|
||||
sessionId: string;
|
||||
snapshotTruncatedMessage: string;
|
||||
store: TerminalSessionControllerStore;
|
||||
transport: TerminalTransport;
|
||||
transportRuntime: TerminalSessionTransportRuntime;
|
||||
}): TerminalSessionRecoveryHandle {
|
||||
let disposed = false;
|
||||
let hydrationReady = false;
|
||||
const hydrationReplayChunks: string[] = [];
|
||||
|
||||
const disposeData = input.transportRuntime.onData((event) => {
|
||||
if (disposed || event.sessionId !== input.sessionId) {
|
||||
return;
|
||||
}
|
||||
if (!hydrationReady) {
|
||||
hydrationReplayChunks.push(event.data);
|
||||
return;
|
||||
}
|
||||
input.store.appendRawOutput(event.data);
|
||||
});
|
||||
|
||||
const disposeState = input.transportRuntime.onState((event) => {
|
||||
if (disposed || event.sessionId !== input.sessionId) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof event.gapStartSeq === "number" &&
|
||||
typeof event.gapEndSeq === "number"
|
||||
) {
|
||||
input.diagnostics.hydrationGap({
|
||||
fromSeq: event.gapStartSeq,
|
||||
toSeq: event.gapEndSeq
|
||||
});
|
||||
input.store.setSurfaceError(input.replayGapMessage);
|
||||
return;
|
||||
}
|
||||
if (event.error) {
|
||||
input.store.setSurfaceError(event.error);
|
||||
}
|
||||
if (event.status === "detached") {
|
||||
input.onWriteReadyChange(false);
|
||||
input.store.setInputReady(false);
|
||||
input.onRecoverableDetach();
|
||||
return;
|
||||
}
|
||||
if (event.status === "exited") {
|
||||
input.onWriteReadyChange(false);
|
||||
input.store.setInputReady(false);
|
||||
}
|
||||
});
|
||||
|
||||
const disposeExit = input.transportRuntime.onExit((event) => {
|
||||
if (disposed || event.sessionId !== input.sessionId) {
|
||||
return;
|
||||
}
|
||||
input.onWriteReadyChange(false);
|
||||
input.store.setInputReady(false);
|
||||
});
|
||||
|
||||
const disposeMetadata = input.transportRuntime.onMetadata(() => undefined);
|
||||
|
||||
return {
|
||||
dispose() {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
hydrationReady = false;
|
||||
hydrationReplayChunks.length = 0;
|
||||
disposeData();
|
||||
disposeState();
|
||||
disposeExit();
|
||||
disposeMetadata();
|
||||
},
|
||||
async start() {
|
||||
input.diagnostics.hydrationStart();
|
||||
input.diagnostics.snapshotStart();
|
||||
|
||||
try {
|
||||
const snapshot = await input.transportRuntime.snapshot();
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
input.store.replaceRawOutput(snapshot.data);
|
||||
const snapshotState = input.store.getState();
|
||||
input.diagnostics.outputProjected({
|
||||
contentEpoch: snapshotState.contentEpoch,
|
||||
previewHead: previewTerminalOutput(snapshot.data, "head"),
|
||||
previewTail: previewTerminalOutput(snapshot.data, "tail"),
|
||||
rawBytes: snapshotState.rawOutput.length,
|
||||
source: "snapshot",
|
||||
writeBytes: snapshot.data.length
|
||||
});
|
||||
if (snapshot.truncated) {
|
||||
input.store.setSurfaceError(input.snapshotTruncatedMessage);
|
||||
} else {
|
||||
input.store.setSurfaceError(null);
|
||||
}
|
||||
input.diagnostics.snapshotComplete({
|
||||
toSeq: snapshot.toSeq ?? null,
|
||||
truncated: snapshot.truncated ?? false
|
||||
});
|
||||
input.diagnostics.attachStart(snapshot.toSeq ?? null);
|
||||
await input.transportRuntime.attach(snapshot.toSeq);
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
hydrationReady = true;
|
||||
const replayChunks = hydrationReplayChunks.splice(0);
|
||||
replayChunks.forEach((chunk) => {
|
||||
input.store.appendRawOutput(chunk);
|
||||
});
|
||||
if (replayChunks.length > 0) {
|
||||
const replayState = input.store.getState();
|
||||
input.diagnostics.outputProjected({
|
||||
contentEpoch: replayState.contentEpoch,
|
||||
previewHead: previewTerminalOutput(replayChunks.join(""), "head"),
|
||||
previewTail: previewTerminalOutput(replayChunks.join(""), "tail"),
|
||||
rawBytes: replayState.rawOutput.length,
|
||||
source: "replay",
|
||||
writeBytes: replayChunks.reduce(
|
||||
(total, chunk) => total + chunk.length,
|
||||
0
|
||||
)
|
||||
});
|
||||
}
|
||||
input.onWriteReadyChange(true);
|
||||
input.store.setInputReady(true);
|
||||
await writeQueuedTerminalInput({
|
||||
queue: input.inputQueue,
|
||||
sessionId: input.sessionId,
|
||||
transport: input.transport
|
||||
});
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
input.diagnostics.attachComplete();
|
||||
input.diagnostics.hydrationComplete(replayChunks.length);
|
||||
} catch (error) {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
input.diagnostics.attachError();
|
||||
input.store.setSurfaceError(errorMessage(error));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function previewTerminalOutput(
|
||||
value: string,
|
||||
side: "head" | "tail",
|
||||
maxChars = 48
|
||||
) {
|
||||
const slice =
|
||||
side === "head"
|
||||
? value.slice(0, maxChars)
|
||||
: value.slice(Math.max(0, value.length - maxChars));
|
||||
return slice
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\n", "\\n");
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { truncateTerminalScrollback } from "./scrollback.ts";
|
||||
|
||||
export interface TerminalSessionControllerState {
|
||||
contentEpoch: number;
|
||||
inputReady: boolean;
|
||||
rawOutput: string;
|
||||
surfaceError: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalSessionControllerStore {
|
||||
appendRawOutput(data: string): void;
|
||||
clearListeners(): void;
|
||||
getState(): TerminalSessionControllerState;
|
||||
replaceRawOutput(rawOutput: string): void;
|
||||
setInputReady(inputReady: boolean): void;
|
||||
setSurfaceError(surfaceError: string | null): void;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
const initialState: TerminalSessionControllerState = {
|
||||
contentEpoch: 0,
|
||||
inputReady: false,
|
||||
rawOutput: "",
|
||||
surfaceError: null
|
||||
};
|
||||
|
||||
export function createTerminalSessionControllerStore(input: {
|
||||
maxScrollbackChars: number;
|
||||
}): TerminalSessionControllerStore {
|
||||
let state = initialState;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
return {
|
||||
appendRawOutput(data) {
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
const nextOutput = truncateTerminalScrollback(
|
||||
`${state.rawOutput}${data}`,
|
||||
{
|
||||
maxChars: input.maxScrollbackChars
|
||||
}
|
||||
);
|
||||
if (nextOutput === state.rawOutput) {
|
||||
return;
|
||||
}
|
||||
state = {
|
||||
...state,
|
||||
rawOutput: nextOutput
|
||||
};
|
||||
emitState(listeners);
|
||||
},
|
||||
clearListeners() {
|
||||
listeners.clear();
|
||||
},
|
||||
getState() {
|
||||
return state;
|
||||
},
|
||||
replaceRawOutput(rawOutput) {
|
||||
state = {
|
||||
...state,
|
||||
contentEpoch: state.contentEpoch + 1,
|
||||
rawOutput: truncateTerminalScrollback(rawOutput, {
|
||||
maxChars: input.maxScrollbackChars
|
||||
})
|
||||
};
|
||||
emitState(listeners);
|
||||
},
|
||||
setInputReady(inputReady) {
|
||||
if (state.inputReady === inputReady) {
|
||||
return;
|
||||
}
|
||||
state = {
|
||||
...state,
|
||||
inputReady
|
||||
};
|
||||
emitState(listeners);
|
||||
},
|
||||
setSurfaceError(surfaceError) {
|
||||
if (state.surfaceError === surfaceError) {
|
||||
return;
|
||||
}
|
||||
state = {
|
||||
...state,
|
||||
surfaceError
|
||||
};
|
||||
emitState(listeners);
|
||||
},
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function emitState(listeners: Set<() => void>) {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { TerminalDiagnosticEvent } from "../contracts/index.ts";
|
||||
import {
|
||||
createTerminalCloseDiagnostics,
|
||||
createTerminalSessionRecoveryDiagnostics,
|
||||
createTerminalSurfaceDiagnostics
|
||||
} from "./sessionDiagnostics.ts";
|
||||
|
||||
test("terminal diagnostics helpers emit consistent close, surface, and recovery events", () => {
|
||||
const events: Array<{
|
||||
details: Record<string, string | number | boolean | null> | undefined;
|
||||
event: TerminalDiagnosticEvent;
|
||||
}> = [];
|
||||
const diagnostics = {
|
||||
log(
|
||||
event: TerminalDiagnosticEvent,
|
||||
details?: Record<string, string | number | boolean | null>
|
||||
) {
|
||||
events.push({ details, event });
|
||||
}
|
||||
};
|
||||
|
||||
const closeDiagnostics = createTerminalCloseDiagnostics({
|
||||
diagnostics,
|
||||
sessionId: "session-1"
|
||||
});
|
||||
const surfaceDiagnostics = createTerminalSurfaceDiagnostics({
|
||||
diagnostics,
|
||||
nodeId: "node-1",
|
||||
sessionId: "session-1"
|
||||
});
|
||||
const recoveryDiagnostics = createTerminalSessionRecoveryDiagnostics({
|
||||
diagnostics,
|
||||
nodeId: "node-1",
|
||||
sessionId: "session-1"
|
||||
});
|
||||
|
||||
closeDiagnostics.requested();
|
||||
closeDiagnostics.confirmed();
|
||||
surfaceDiagnostics.mount();
|
||||
surfaceDiagnostics.outputSync({
|
||||
contentEpoch: 1,
|
||||
nextCommittedBytes: 352,
|
||||
plan: "replace",
|
||||
previousCommittedBytes: 0,
|
||||
rawBytes: 352,
|
||||
writeBytes: 352
|
||||
});
|
||||
surfaceDiagnostics.outputWritten({
|
||||
bufferCursorX: 14,
|
||||
bufferCursorY: 5,
|
||||
bufferLength: 6,
|
||||
bytes: 352,
|
||||
canvasClientHeight: 480,
|
||||
canvasClientWidth: 1024,
|
||||
canvasCount: 2,
|
||||
cols: 105,
|
||||
containerClientHeight: 520,
|
||||
containerClientWidth: 1080,
|
||||
cursorLinePreview: "➜ 705aigc.com_nginx",
|
||||
firstLinePreview: "➜ 705aigc.com_nginx",
|
||||
helperChildCount: 1,
|
||||
mode: "replace",
|
||||
remainingChunkCount: 0,
|
||||
renderDimensionsReady: true,
|
||||
rowContainerChildCount: 30,
|
||||
rowContainerTextPreview: "➜ 705aigc.com_nginx",
|
||||
rows: 30,
|
||||
screenChildCount: 3,
|
||||
screenClientHeight: 480,
|
||||
screenClientWidth: 1024,
|
||||
screenDisplay: "block",
|
||||
screenOpacity: "1",
|
||||
screenVisibility: "visible",
|
||||
serializedBytes: 352,
|
||||
xtermClientHeight: 500,
|
||||
xtermClientWidth: 1040,
|
||||
xtermDisplay: "block",
|
||||
xtermOpacity: "1",
|
||||
xtermVisibility: "visible"
|
||||
});
|
||||
surfaceDiagnostics.resize({ cols: 120, rows: 40 });
|
||||
surfaceDiagnostics.dispose();
|
||||
recoveryDiagnostics.hydrationStart();
|
||||
recoveryDiagnostics.snapshotStart();
|
||||
recoveryDiagnostics.outputProjected({
|
||||
contentEpoch: 1,
|
||||
previewHead: "\\u001b]633;C\\u0007\\u001b[?2004h",
|
||||
previewTail: "➜ 705aigc.com_nginx ",
|
||||
rawBytes: 352,
|
||||
source: "snapshot",
|
||||
writeBytes: 352
|
||||
});
|
||||
recoveryDiagnostics.snapshotComplete({ toSeq: 9, truncated: false });
|
||||
recoveryDiagnostics.attachStart(9);
|
||||
recoveryDiagnostics.outputProjected({
|
||||
contentEpoch: 1,
|
||||
previewHead: "abc",
|
||||
previewTail: "xyz",
|
||||
rawBytes: 368,
|
||||
source: "replay",
|
||||
writeBytes: 16
|
||||
});
|
||||
recoveryDiagnostics.attachComplete();
|
||||
recoveryDiagnostics.hydrationComplete(2);
|
||||
recoveryDiagnostics.hydrationGap({ fromSeq: 8, toSeq: 9 });
|
||||
recoveryDiagnostics.attachError();
|
||||
|
||||
assert.deepEqual(events, [
|
||||
{ details: { sessionId: "session-1" }, event: "close-requested" },
|
||||
{ details: { sessionId: "session-1" }, event: "close-confirmed" },
|
||||
{
|
||||
details: { nodeId: "node-1", sessionId: "session-1" },
|
||||
event: "mount"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
contentEpoch: 1,
|
||||
nextCommittedBytes: 352,
|
||||
nodeId: "node-1",
|
||||
plan: "replace",
|
||||
previousCommittedBytes: 0,
|
||||
rawBytes: 352,
|
||||
sessionId: "session-1",
|
||||
writeBytes: 352
|
||||
},
|
||||
event: "surface-output-sync"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
bufferCursorX: 14,
|
||||
bufferCursorY: 5,
|
||||
bufferLength: 6,
|
||||
bytes: 352,
|
||||
canvasClientHeight: 480,
|
||||
canvasClientWidth: 1024,
|
||||
canvasCount: 2,
|
||||
cols: 105,
|
||||
containerClientHeight: 520,
|
||||
containerClientWidth: 1080,
|
||||
cursorLinePreview: "➜ 705aigc.com_nginx",
|
||||
firstLinePreview: "➜ 705aigc.com_nginx",
|
||||
helperChildCount: 1,
|
||||
mode: "replace",
|
||||
nodeId: "node-1",
|
||||
remainingChunkCount: 0,
|
||||
renderDimensionsReady: true,
|
||||
rowContainerChildCount: 30,
|
||||
rowContainerTextPreview: "➜ 705aigc.com_nginx",
|
||||
rows: 30,
|
||||
screenChildCount: 3,
|
||||
sessionId: "session-1",
|
||||
screenClientHeight: 480,
|
||||
screenClientWidth: 1024,
|
||||
screenDisplay: "block",
|
||||
screenOpacity: "1",
|
||||
screenVisibility: "visible",
|
||||
serializedBytes: 352,
|
||||
xtermClientHeight: 500,
|
||||
xtermClientWidth: 1040,
|
||||
xtermDisplay: "block",
|
||||
xtermOpacity: "1",
|
||||
xtermVisibility: "visible"
|
||||
},
|
||||
event: "surface-output-written"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
cols: 120,
|
||||
nodeId: "node-1",
|
||||
rows: 40,
|
||||
sessionId: "session-1"
|
||||
},
|
||||
event: "resize"
|
||||
},
|
||||
{
|
||||
details: { nodeId: "node-1", sessionId: "session-1" },
|
||||
event: "dispose"
|
||||
},
|
||||
{
|
||||
details: { nodeId: "node-1", sessionId: "session-1" },
|
||||
event: "hydration-start"
|
||||
},
|
||||
{
|
||||
details: { nodeId: "node-1", sessionId: "session-1" },
|
||||
event: "snapshot-start"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
contentEpoch: 1,
|
||||
nodeId: "node-1",
|
||||
previewHead: "\\u001b]633;C\\u0007\\u001b[?2004h",
|
||||
previewTail: "➜ 705aigc.com_nginx ",
|
||||
rawBytes: 352,
|
||||
sessionId: "session-1",
|
||||
source: "snapshot",
|
||||
writeBytes: 352
|
||||
},
|
||||
event: "output-projected"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
nodeId: "node-1",
|
||||
sessionId: "session-1",
|
||||
toSeq: 9,
|
||||
truncated: false
|
||||
},
|
||||
event: "snapshot-complete"
|
||||
},
|
||||
{
|
||||
details: { afterSeq: 9, nodeId: "node-1", sessionId: "session-1" },
|
||||
event: "attach-start"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
contentEpoch: 1,
|
||||
nodeId: "node-1",
|
||||
previewHead: "abc",
|
||||
previewTail: "xyz",
|
||||
rawBytes: 368,
|
||||
sessionId: "session-1",
|
||||
source: "replay",
|
||||
writeBytes: 16
|
||||
},
|
||||
event: "output-projected"
|
||||
},
|
||||
{
|
||||
details: { nodeId: "node-1", sessionId: "session-1" },
|
||||
event: "attach-complete"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
nodeId: "node-1",
|
||||
replayChunkCount: 2,
|
||||
sessionId: "session-1"
|
||||
},
|
||||
event: "hydration-complete"
|
||||
},
|
||||
{
|
||||
details: {
|
||||
fromSeq: 8,
|
||||
nodeId: "node-1",
|
||||
sessionId: "session-1",
|
||||
toSeq: 9
|
||||
},
|
||||
event: "hydration-gap"
|
||||
},
|
||||
{
|
||||
details: { nodeId: "node-1", sessionId: "session-1" },
|
||||
event: "attach-error"
|
||||
}
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
import type { TerminalDiagnostics } from "../contracts/index.ts";
|
||||
|
||||
export interface TerminalCloseDiagnostics {
|
||||
confirmed(): void;
|
||||
requested(): void;
|
||||
}
|
||||
|
||||
export interface TerminalSurfaceDiagnostics {
|
||||
dispose(): void;
|
||||
mount(): void;
|
||||
outputSync(input: {
|
||||
contentEpoch: number;
|
||||
nextCommittedBytes: number;
|
||||
plan: "append" | "replace" | "reset" | "skip";
|
||||
previousCommittedBytes: number;
|
||||
rawBytes: number;
|
||||
writeBytes: number;
|
||||
}): void;
|
||||
outputWritten(input: {
|
||||
bufferCursorX: number;
|
||||
bufferCursorY: number;
|
||||
bufferLength: number;
|
||||
bytes: number;
|
||||
canvasClientHeight: number;
|
||||
canvasClientWidth: number;
|
||||
canvasCount: number;
|
||||
cols: number;
|
||||
containerClientHeight: number;
|
||||
containerClientWidth: number;
|
||||
cursorLinePreview: string;
|
||||
firstLinePreview: string;
|
||||
helperChildCount: number;
|
||||
mode: "append" | "cache" | "replace" | "reset";
|
||||
remainingChunkCount: number;
|
||||
renderDimensionsReady: boolean;
|
||||
rowContainerChildCount: number;
|
||||
rowContainerTextPreview: string;
|
||||
rows: number;
|
||||
screenChildCount: number;
|
||||
screenClientHeight: number;
|
||||
screenClientWidth: number;
|
||||
screenDisplay: string;
|
||||
screenOpacity: string;
|
||||
screenVisibility: string;
|
||||
serializedBytes: number;
|
||||
xtermClientHeight: number;
|
||||
xtermClientWidth: number;
|
||||
xtermDisplay: string;
|
||||
xtermOpacity: string;
|
||||
xtermVisibility: string;
|
||||
}): void;
|
||||
resize(input: { cols: number; rows: number }): void;
|
||||
}
|
||||
|
||||
export interface TerminalSessionRecoveryDiagnostics {
|
||||
attachComplete(): void;
|
||||
attachError(): void;
|
||||
attachStart(afterSeq: number | null): void;
|
||||
hydrationComplete(replayChunkCount: number): void;
|
||||
hydrationGap(input: { fromSeq: number; toSeq: number }): void;
|
||||
hydrationStart(): void;
|
||||
outputProjected(input: {
|
||||
contentEpoch: number;
|
||||
previewHead: string;
|
||||
previewTail: string;
|
||||
rawBytes: number;
|
||||
source: "replay" | "snapshot";
|
||||
writeBytes: number;
|
||||
}): void;
|
||||
snapshotComplete(input: { toSeq: number | null; truncated: boolean }): void;
|
||||
snapshotStart(): void;
|
||||
}
|
||||
|
||||
export function createTerminalSurfaceDiagnostics(input: {
|
||||
diagnostics: TerminalDiagnostics;
|
||||
nodeId: string;
|
||||
sessionId: string;
|
||||
}): TerminalSurfaceDiagnostics {
|
||||
return {
|
||||
dispose() {
|
||||
input.diagnostics.log("dispose", resolveContext(input));
|
||||
},
|
||||
mount() {
|
||||
input.diagnostics.log("mount", resolveContext(input));
|
||||
},
|
||||
outputSync({
|
||||
contentEpoch,
|
||||
nextCommittedBytes,
|
||||
plan,
|
||||
previousCommittedBytes,
|
||||
rawBytes,
|
||||
writeBytes
|
||||
}) {
|
||||
input.diagnostics.log("surface-output-sync", {
|
||||
...resolveContext(input),
|
||||
contentEpoch,
|
||||
nextCommittedBytes,
|
||||
plan,
|
||||
previousCommittedBytes,
|
||||
rawBytes,
|
||||
writeBytes
|
||||
});
|
||||
},
|
||||
outputWritten({
|
||||
bufferCursorX,
|
||||
bufferCursorY,
|
||||
bufferLength,
|
||||
bytes,
|
||||
canvasClientHeight,
|
||||
canvasClientWidth,
|
||||
canvasCount,
|
||||
cols,
|
||||
containerClientHeight,
|
||||
containerClientWidth,
|
||||
cursorLinePreview,
|
||||
firstLinePreview,
|
||||
helperChildCount,
|
||||
mode,
|
||||
remainingChunkCount,
|
||||
renderDimensionsReady,
|
||||
rowContainerChildCount,
|
||||
rowContainerTextPreview,
|
||||
rows,
|
||||
screenChildCount,
|
||||
screenClientHeight,
|
||||
screenClientWidth,
|
||||
screenDisplay,
|
||||
screenOpacity,
|
||||
screenVisibility,
|
||||
serializedBytes,
|
||||
xtermClientHeight,
|
||||
xtermClientWidth,
|
||||
xtermDisplay,
|
||||
xtermOpacity,
|
||||
xtermVisibility
|
||||
}) {
|
||||
input.diagnostics.log("surface-output-written", {
|
||||
...resolveContext(input),
|
||||
bufferCursorX,
|
||||
bufferCursorY,
|
||||
bufferLength,
|
||||
bytes,
|
||||
canvasClientHeight,
|
||||
canvasClientWidth,
|
||||
canvasCount,
|
||||
cols,
|
||||
containerClientHeight,
|
||||
containerClientWidth,
|
||||
cursorLinePreview,
|
||||
firstLinePreview,
|
||||
helperChildCount,
|
||||
mode,
|
||||
remainingChunkCount,
|
||||
renderDimensionsReady,
|
||||
rowContainerChildCount,
|
||||
rowContainerTextPreview,
|
||||
rows,
|
||||
screenChildCount,
|
||||
screenClientHeight,
|
||||
screenClientWidth,
|
||||
screenDisplay,
|
||||
screenOpacity,
|
||||
screenVisibility,
|
||||
serializedBytes,
|
||||
xtermClientHeight,
|
||||
xtermClientWidth,
|
||||
xtermDisplay,
|
||||
xtermOpacity,
|
||||
xtermVisibility
|
||||
});
|
||||
},
|
||||
resize({ cols, rows }) {
|
||||
input.diagnostics.log("resize", {
|
||||
...resolveContext(input),
|
||||
cols,
|
||||
rows
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createTerminalCloseDiagnostics(input: {
|
||||
diagnostics: TerminalDiagnostics;
|
||||
sessionId: string;
|
||||
}): TerminalCloseDiagnostics {
|
||||
return {
|
||||
confirmed() {
|
||||
input.diagnostics.log("close-confirmed", {
|
||||
sessionId: input.sessionId
|
||||
});
|
||||
},
|
||||
requested() {
|
||||
input.diagnostics.log("close-requested", {
|
||||
sessionId: input.sessionId
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createTerminalSessionRecoveryDiagnostics(input: {
|
||||
diagnostics: TerminalDiagnostics;
|
||||
nodeId: string;
|
||||
sessionId: string;
|
||||
}): TerminalSessionRecoveryDiagnostics {
|
||||
return {
|
||||
attachComplete() {
|
||||
input.diagnostics.log("attach-complete", resolveContext(input));
|
||||
},
|
||||
attachError() {
|
||||
input.diagnostics.log("attach-error", resolveContext(input));
|
||||
},
|
||||
attachStart(afterSeq) {
|
||||
input.diagnostics.log("attach-start", {
|
||||
...resolveContext(input),
|
||||
afterSeq
|
||||
});
|
||||
},
|
||||
hydrationComplete(replayChunkCount) {
|
||||
input.diagnostics.log("hydration-complete", {
|
||||
...resolveContext(input),
|
||||
replayChunkCount
|
||||
});
|
||||
},
|
||||
hydrationGap({ fromSeq, toSeq }) {
|
||||
input.diagnostics.log("hydration-gap", {
|
||||
...resolveContext(input),
|
||||
fromSeq,
|
||||
toSeq
|
||||
});
|
||||
},
|
||||
hydrationStart() {
|
||||
input.diagnostics.log("hydration-start", resolveContext(input));
|
||||
},
|
||||
outputProjected({
|
||||
contentEpoch,
|
||||
previewHead,
|
||||
previewTail,
|
||||
rawBytes,
|
||||
source,
|
||||
writeBytes
|
||||
}) {
|
||||
input.diagnostics.log("output-projected", {
|
||||
...resolveContext(input),
|
||||
contentEpoch,
|
||||
previewHead,
|
||||
previewTail,
|
||||
rawBytes,
|
||||
source,
|
||||
writeBytes
|
||||
});
|
||||
},
|
||||
snapshotComplete({ toSeq, truncated }) {
|
||||
input.diagnostics.log("snapshot-complete", {
|
||||
...resolveContext(input),
|
||||
toSeq,
|
||||
truncated
|
||||
});
|
||||
},
|
||||
snapshotStart() {
|
||||
input.diagnostics.log("snapshot-start", resolveContext(input));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function resolveContext(input: { nodeId: string; sessionId: string }) {
|
||||
return {
|
||||
nodeId: input.nodeId,
|
||||
sessionId: input.sessionId
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { TerminalNodeExternalState } from "../contracts/index.ts";
|
||||
import {
|
||||
applyTerminalSessionStatusProjection,
|
||||
applyTerminalSessionTitleProjection,
|
||||
createTerminalSessionExitProjection,
|
||||
createTerminalSessionFailedProjection
|
||||
} from "./sessionProjection.ts";
|
||||
|
||||
const baseState: TerminalNodeExternalState = {
|
||||
createdAt: null,
|
||||
cwd: null,
|
||||
endedAt: null,
|
||||
host: null,
|
||||
lastError: null,
|
||||
profileId: null,
|
||||
runtimeKind: "local",
|
||||
sessionId: "session-1",
|
||||
status: "running",
|
||||
title: "Terminal",
|
||||
updatedAt: null
|
||||
};
|
||||
|
||||
test("applyTerminalSessionStatusProjection marks ended sessions once", () => {
|
||||
const exited = applyTerminalSessionStatusProjection(
|
||||
baseState,
|
||||
createTerminalSessionExitProjection(),
|
||||
() => "2026-05-25T00:00:00.000Z"
|
||||
);
|
||||
|
||||
assert.equal(exited.status, "exited");
|
||||
assert.equal(exited.endedAt, "2026-05-25T00:00:00.000Z");
|
||||
|
||||
const ignoredRestart = applyTerminalSessionStatusProjection(exited, {
|
||||
lastError: null,
|
||||
status: "running"
|
||||
});
|
||||
|
||||
assert.equal(ignoredRestart, exited);
|
||||
});
|
||||
|
||||
test("applyTerminalSessionStatusProjection records failure details", () => {
|
||||
const failed = applyTerminalSessionStatusProjection(
|
||||
baseState,
|
||||
createTerminalSessionFailedProjection("lost"),
|
||||
() => "2026-05-25T00:00:00.000Z"
|
||||
);
|
||||
|
||||
assert.equal(failed.status, "failed");
|
||||
assert.equal(failed.lastError, "lost");
|
||||
assert.equal(failed.endedAt, "2026-05-25T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("applyTerminalSessionTitleProjection updates only the title", () => {
|
||||
const renamed = applyTerminalSessionTitleProjection(baseState, "Build");
|
||||
|
||||
assert.equal(renamed.title, "Build");
|
||||
assert.equal(renamed.sessionId, baseState.sessionId);
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import type {
|
||||
TerminalNodeExternalState,
|
||||
TerminalSessionStatus
|
||||
} from "../contracts/index.ts";
|
||||
|
||||
export const terminalSessionLostMessage = "Terminal session was lost.";
|
||||
|
||||
export interface TerminalSessionStatusProjection {
|
||||
lastError: string | null;
|
||||
status: TerminalSessionStatus;
|
||||
}
|
||||
|
||||
export function createTerminalSessionExitProjection(): TerminalSessionStatusProjection {
|
||||
return {
|
||||
lastError: null,
|
||||
status: "exited"
|
||||
};
|
||||
}
|
||||
|
||||
export function createTerminalSessionFailedProjection(
|
||||
lastError = terminalSessionLostMessage
|
||||
): TerminalSessionStatusProjection {
|
||||
return {
|
||||
lastError,
|
||||
status: "failed"
|
||||
};
|
||||
}
|
||||
|
||||
export function applyTerminalSessionStatusProjection<
|
||||
THostMetadata extends Record<string, unknown> = Record<string, unknown>
|
||||
>(
|
||||
current: TerminalNodeExternalState<THostMetadata>,
|
||||
projection: TerminalSessionStatusProjection,
|
||||
now: () => string = () => new Date().toISOString()
|
||||
): TerminalNodeExternalState<THostMetadata> {
|
||||
if (
|
||||
current.endedAt &&
|
||||
isTerminalSessionEndedStatus(current.status) &&
|
||||
!isTerminalSessionEndedStatus(projection.status)
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return {
|
||||
...current,
|
||||
endedAt: isTerminalSessionEndedStatus(projection.status)
|
||||
? (current.endedAt ?? now())
|
||||
: current.endedAt,
|
||||
lastError: projection.lastError,
|
||||
status: projection.status
|
||||
};
|
||||
}
|
||||
|
||||
export function applyTerminalSessionTitleProjection<
|
||||
THostMetadata extends Record<string, unknown> = Record<string, unknown>
|
||||
>(
|
||||
current: TerminalNodeExternalState<THostMetadata>,
|
||||
title: string
|
||||
): TerminalNodeExternalState<THostMetadata> {
|
||||
return {
|
||||
...current,
|
||||
title
|
||||
};
|
||||
}
|
||||
|
||||
export function isTerminalSessionEndedStatus(
|
||||
status: TerminalSessionStatus
|
||||
): boolean {
|
||||
return status === "exited" || status === "failed";
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import type {
|
||||
TerminalDataEvent,
|
||||
TerminalExitEvent,
|
||||
TerminalMetadataEvent,
|
||||
TerminalSnapshot,
|
||||
TerminalStateEvent,
|
||||
TerminalTransport
|
||||
} from "../contracts/index.ts";
|
||||
import { createTerminalAttachmentController } from "./attachmentController.ts";
|
||||
|
||||
export interface TerminalSessionTransportRuntime {
|
||||
attach(afterSeq?: number): Promise<void>;
|
||||
onData(listener: (event: TerminalDataEvent) => void): () => void;
|
||||
onExit(listener: (event: TerminalExitEvent) => void): () => void;
|
||||
onMetadata(listener: (event: TerminalMetadataEvent) => void): () => void;
|
||||
onState(listener: (event: TerminalStateEvent) => void): () => void;
|
||||
release(): void;
|
||||
snapshot(): Promise<TerminalSnapshot>;
|
||||
}
|
||||
|
||||
interface TerminalSessionTransportRuntimeEntry {
|
||||
attach(afterSeq?: number): Promise<void>;
|
||||
dataBuffer: TerminalDataEvent[];
|
||||
dataListeners: Set<(event: TerminalDataEvent) => void>;
|
||||
detachGraceMs: number;
|
||||
detachTimer: ReturnType<typeof setTimeout> | null;
|
||||
exitBuffer: TerminalExitEvent[];
|
||||
exitListeners: Set<(event: TerminalExitEvent) => void>;
|
||||
metadataBuffer: TerminalMetadataEvent[];
|
||||
metadataListeners: Set<(event: TerminalMetadataEvent) => void>;
|
||||
refCount: number;
|
||||
release(): void;
|
||||
sessionId: string;
|
||||
snapshot(): Promise<TerminalSnapshot>;
|
||||
snapshotCache: TerminalSnapshot | null;
|
||||
snapshotPromise: Promise<TerminalSnapshot> | null;
|
||||
stateBuffer: TerminalStateEvent[];
|
||||
stateListeners: Set<(event: TerminalStateEvent) => void>;
|
||||
teardown(): void;
|
||||
}
|
||||
|
||||
const defaultDetachGraceMs = 200;
|
||||
const runtimeRegistry = new Map<string, TerminalSessionTransportRuntimeEntry>();
|
||||
let runtimeClientSequence = 0;
|
||||
|
||||
export function acquireTerminalSessionTransportRuntime(input: {
|
||||
detachGraceMs?: number;
|
||||
sessionId: string;
|
||||
transport: TerminalTransport;
|
||||
}): TerminalSessionTransportRuntime {
|
||||
const entry =
|
||||
runtimeRegistry.get(input.sessionId) ??
|
||||
createTerminalSessionTransportRuntimeEntry(input);
|
||||
if (!runtimeRegistry.has(input.sessionId)) {
|
||||
runtimeRegistry.set(input.sessionId, entry);
|
||||
}
|
||||
entry.refCount += 1;
|
||||
if (entry.detachTimer !== null) {
|
||||
clearTimeout(entry.detachTimer);
|
||||
entry.detachTimer = null;
|
||||
}
|
||||
|
||||
return {
|
||||
attach(afterSeq) {
|
||||
return entry.attach(afterSeq);
|
||||
},
|
||||
onData(listener) {
|
||||
entry.dataListeners.add(listener);
|
||||
flushBufferedEvents(entry.dataBuffer, listener);
|
||||
return () => {
|
||||
entry.dataListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
onExit(listener) {
|
||||
entry.exitListeners.add(listener);
|
||||
flushBufferedEvents(entry.exitBuffer, listener);
|
||||
return () => {
|
||||
entry.exitListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
onMetadata(listener) {
|
||||
entry.metadataListeners.add(listener);
|
||||
flushBufferedEvents(entry.metadataBuffer, listener);
|
||||
return () => {
|
||||
entry.metadataListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
onState(listener) {
|
||||
entry.stateListeners.add(listener);
|
||||
flushBufferedEvents(entry.stateBuffer, listener);
|
||||
return () => {
|
||||
entry.stateListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
release() {
|
||||
entry.release();
|
||||
},
|
||||
snapshot() {
|
||||
return entry.snapshot();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createTerminalSessionTransportRuntimeEntry(input: {
|
||||
detachGraceMs?: number;
|
||||
sessionId: string;
|
||||
transport: TerminalTransport;
|
||||
}): TerminalSessionTransportRuntimeEntry {
|
||||
const attachmentController = createTerminalAttachmentController({
|
||||
clientId: createTerminalTransportClientId(),
|
||||
sessionId: input.sessionId,
|
||||
transport: input.transport
|
||||
});
|
||||
|
||||
const entry: TerminalSessionTransportRuntimeEntry = {
|
||||
attach(afterSeq) {
|
||||
return attachmentController.attach(afterSeq);
|
||||
},
|
||||
dataBuffer: [],
|
||||
dataListeners: new Set(),
|
||||
detachGraceMs: input.detachGraceMs ?? defaultDetachGraceMs,
|
||||
detachTimer: null,
|
||||
exitBuffer: [],
|
||||
exitListeners: new Set(),
|
||||
metadataBuffer: [],
|
||||
metadataListeners: new Set(),
|
||||
refCount: 0,
|
||||
release() {
|
||||
entry.refCount = Math.max(0, entry.refCount - 1);
|
||||
if (entry.refCount > 0 || entry.detachTimer !== null) {
|
||||
return;
|
||||
}
|
||||
entry.detachTimer = setTimeout(() => {
|
||||
entry.detachTimer = null;
|
||||
if (entry.refCount > 0) {
|
||||
return;
|
||||
}
|
||||
void attachmentController.detach().finally(() => {
|
||||
entry.teardown();
|
||||
runtimeRegistry.delete(entry.sessionId);
|
||||
});
|
||||
}, entry.detachGraceMs);
|
||||
},
|
||||
sessionId: input.sessionId,
|
||||
snapshot() {
|
||||
if (entry.snapshotPromise) {
|
||||
return entry.snapshotPromise;
|
||||
}
|
||||
if (entry.snapshotCache) {
|
||||
return Promise.resolve(entry.snapshotCache);
|
||||
}
|
||||
entry.snapshotPromise = input.transport
|
||||
.snapshot({ sessionId: input.sessionId })
|
||||
.then((snapshot) => {
|
||||
entry.snapshotCache = snapshot;
|
||||
return snapshot;
|
||||
})
|
||||
.finally(() => {
|
||||
entry.snapshotPromise = null;
|
||||
});
|
||||
return entry.snapshotPromise;
|
||||
},
|
||||
snapshotCache: null,
|
||||
snapshotPromise: null,
|
||||
stateBuffer: [],
|
||||
stateListeners: new Set(),
|
||||
teardown() {
|
||||
disposeData();
|
||||
disposeState();
|
||||
disposeExit();
|
||||
disposeMetadata?.();
|
||||
entry.dataBuffer.length = 0;
|
||||
entry.exitBuffer.length = 0;
|
||||
entry.metadataBuffer.length = 0;
|
||||
entry.stateBuffer.length = 0;
|
||||
entry.snapshotCache = null;
|
||||
entry.snapshotPromise = null;
|
||||
}
|
||||
};
|
||||
|
||||
const disposeData = input.transport.onData((event) => {
|
||||
if (event.sessionId !== input.sessionId) {
|
||||
return;
|
||||
}
|
||||
entry.snapshotCache = null;
|
||||
dispatchOrBuffer(entry.dataListeners, entry.dataBuffer, event);
|
||||
});
|
||||
const disposeState = input.transport.onState((event) => {
|
||||
if (event.sessionId !== input.sessionId) {
|
||||
return;
|
||||
}
|
||||
if (event.status === "detached" || event.status === "exited") {
|
||||
attachmentController.markDetached();
|
||||
}
|
||||
if (
|
||||
typeof event.gapStartSeq === "number" ||
|
||||
typeof event.gapEndSeq === "number"
|
||||
) {
|
||||
entry.snapshotCache = null;
|
||||
}
|
||||
dispatchOrBuffer(entry.stateListeners, entry.stateBuffer, event);
|
||||
});
|
||||
const disposeExit = input.transport.onExit((event) => {
|
||||
if (event.sessionId !== input.sessionId) {
|
||||
return;
|
||||
}
|
||||
dispatchOrBuffer(entry.exitListeners, entry.exitBuffer, event);
|
||||
});
|
||||
const disposeMetadata = input.transport.onMetadata?.((event) => {
|
||||
if (event.sessionId !== input.sessionId) {
|
||||
return;
|
||||
}
|
||||
dispatchOrBuffer(entry.metadataListeners, entry.metadataBuffer, event);
|
||||
});
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
function createTerminalTransportClientId(): string {
|
||||
runtimeClientSequence += 1;
|
||||
return `terminal-runtime-${runtimeClientSequence}`;
|
||||
}
|
||||
|
||||
function dispatchOrBuffer<TEvent>(
|
||||
listeners: Set<(event: TEvent) => void>,
|
||||
buffer: TEvent[],
|
||||
event: TEvent
|
||||
) {
|
||||
if (listeners.size === 0) {
|
||||
buffer.push(event);
|
||||
return;
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
|
||||
function flushBufferedEvents<TEvent>(
|
||||
buffer: TEvent[],
|
||||
listener: (event: TEvent) => void
|
||||
) {
|
||||
if (buffer.length === 0) {
|
||||
return;
|
||||
}
|
||||
const pending = buffer.splice(0);
|
||||
for (const event of pending) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export function resolveSuffixPrefixOverlap(
|
||||
left: string,
|
||||
right: string
|
||||
): number {
|
||||
if (left.length === 0 || right.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const max = Math.min(left.length, right.length);
|
||||
const leftTail = left.slice(-max);
|
||||
const rightPrefix = right.slice(0, max);
|
||||
const combined = `${rightPrefix}\u0000${leftTail}`;
|
||||
const prefix = new Uint32Array(combined.length);
|
||||
let cursor = 0;
|
||||
|
||||
for (let index = 1; index < combined.length; index += 1) {
|
||||
while (cursor > 0 && combined[index] !== combined[cursor]) {
|
||||
cursor = prefix[cursor - 1] ?? 0;
|
||||
}
|
||||
|
||||
if (combined[index] === combined[cursor]) {
|
||||
cursor += 1;
|
||||
prefix[index] = cursor;
|
||||
}
|
||||
}
|
||||
|
||||
return prefix[combined.length - 1] ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export {
|
||||
createTerminalNodeI18nRuntime,
|
||||
terminalNodeI18nModule,
|
||||
terminalNodeI18nNamespace,
|
||||
terminalNodeI18nResources,
|
||||
type TerminalNodeI18nKey,
|
||||
type TerminalNodeI18nRuntime
|
||||
} from "./terminalNodeI18n.ts";
|
||||
@@ -0,0 +1,143 @@
|
||||
import {
|
||||
createI18nRuntime,
|
||||
createScopedI18nRuntime,
|
||||
createScopedLocaleObjectsI18nModuleManifest,
|
||||
type I18nDictionary,
|
||||
type I18nRuntime
|
||||
} from "@tutti-os/ui-i18n-runtime";
|
||||
|
||||
type TerminalNodeI18nLocale = "en" | "zh-CN";
|
||||
|
||||
export const terminalNodeI18nNamespace = "terminalNode";
|
||||
export const terminalNodeI18nModule =
|
||||
createScopedLocaleObjectsI18nModuleManifest({
|
||||
localeObjectByLocale: {
|
||||
en: "terminalNodeEn",
|
||||
"zh-CN": "terminalNodeZhCN"
|
||||
},
|
||||
name: "workspace-terminal",
|
||||
namespace: terminalNodeI18nNamespace,
|
||||
sourceRoot: "packages/workspace/terminal/src"
|
||||
});
|
||||
|
||||
const terminalNodeEn = {
|
||||
actions: {
|
||||
caseSensitive: "Case sensitive",
|
||||
close: "Close terminal",
|
||||
find: "Find",
|
||||
next: "Next match",
|
||||
previous: "Previous match",
|
||||
regex: "Regular expression"
|
||||
},
|
||||
closeGuard: {
|
||||
cancel: "Keep running",
|
||||
confirm: "Terminate",
|
||||
description:
|
||||
"This terminal still has running work. Terminating it will stop the session.",
|
||||
title: "Terminate terminal?"
|
||||
},
|
||||
dockLabel: "Terminal",
|
||||
emptySession: "No terminal session",
|
||||
findPlaceholder: "Search terminal",
|
||||
recovery: {
|
||||
replayGap:
|
||||
"Terminal output recovery skipped some history. New output will continue from the live session.",
|
||||
snapshotTruncated:
|
||||
"Terminal recovery snapshot was truncated. Earlier output is no longer available."
|
||||
},
|
||||
status: {
|
||||
created: "Created",
|
||||
detached: "Detached",
|
||||
exited: "Exited",
|
||||
failed: "Failed",
|
||||
running: "Running",
|
||||
starting: "Starting"
|
||||
},
|
||||
title: "Terminal"
|
||||
} as const satisfies I18nDictionary;
|
||||
|
||||
const terminalNodeZhCN = {
|
||||
actions: {
|
||||
caseSensitive: "区分大小写",
|
||||
close: "关闭终端",
|
||||
find: "查找",
|
||||
next: "下一个匹配项",
|
||||
previous: "上一个匹配项",
|
||||
regex: "正则表达式"
|
||||
},
|
||||
closeGuard: {
|
||||
cancel: "继续运行",
|
||||
confirm: "终止",
|
||||
description: "这个终端仍有任务在运行。终止会停止当前终端会话。",
|
||||
title: "终止终端?"
|
||||
},
|
||||
dockLabel: "终端",
|
||||
emptySession: "没有终端会话",
|
||||
findPlaceholder: "搜索终端",
|
||||
recovery: {
|
||||
replayGap: "终端恢复时跳过了一部分历史输出。新的输出会继续从当前会话接收。",
|
||||
snapshotTruncated: "终端恢复快照已被截断,更早的输出已经不可用。"
|
||||
},
|
||||
status: {
|
||||
created: "已创建",
|
||||
detached: "已断开",
|
||||
exited: "已退出",
|
||||
failed: "失败",
|
||||
running: "运行中",
|
||||
starting: "启动中"
|
||||
},
|
||||
title: "终端"
|
||||
} as const satisfies I18nDictionary;
|
||||
|
||||
export type TerminalNodeI18nKey =
|
||||
| "actions.caseSensitive"
|
||||
| "actions.close"
|
||||
| "actions.find"
|
||||
| "actions.next"
|
||||
| "actions.previous"
|
||||
| "actions.regex"
|
||||
| "closeGuard.cancel"
|
||||
| "closeGuard.confirm"
|
||||
| "closeGuard.description"
|
||||
| "closeGuard.title"
|
||||
| "dockLabel"
|
||||
| "emptySession"
|
||||
| "findPlaceholder"
|
||||
| "recovery.replayGap"
|
||||
| "recovery.snapshotTruncated"
|
||||
| "status.created"
|
||||
| "status.detached"
|
||||
| "status.exited"
|
||||
| "status.failed"
|
||||
| "status.running"
|
||||
| "status.starting"
|
||||
| "title";
|
||||
|
||||
export type TerminalNodeI18nRuntime = I18nRuntime<TerminalNodeI18nKey>;
|
||||
|
||||
const terminalNodeDefaults: Record<TerminalNodeI18nLocale, I18nDictionary> = {
|
||||
en: terminalNodeEn,
|
||||
"zh-CN": terminalNodeZhCN
|
||||
};
|
||||
|
||||
export const terminalNodeI18nResources = {
|
||||
en: {
|
||||
[terminalNodeI18nNamespace]: terminalNodeDefaults.en
|
||||
},
|
||||
"zh-CN": {
|
||||
[terminalNodeI18nNamespace]: terminalNodeDefaults["zh-CN"]
|
||||
}
|
||||
} as const satisfies Record<TerminalNodeI18nLocale, I18nDictionary>;
|
||||
|
||||
const defaultTerminalNodeI18n = createI18nRuntime({
|
||||
dictionaries: [terminalNodeI18nResources.en]
|
||||
});
|
||||
|
||||
export function createTerminalNodeI18nRuntime(
|
||||
runtime: I18nRuntime<string> | undefined
|
||||
): TerminalNodeI18nRuntime {
|
||||
return createScopedI18nRuntime<TerminalNodeI18nKey>(
|
||||
runtime ?? defaultTerminalNodeI18n,
|
||||
terminalNodeI18nNamespace
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export {
|
||||
closeTerminalSession,
|
||||
createTerminalNodeFeature,
|
||||
defaultTerminalNodeLimits,
|
||||
type TerminalCloseConfirmation,
|
||||
type TerminalCloseResult,
|
||||
type CreateTerminalNodeFeatureInput,
|
||||
type TerminalNodeFeature
|
||||
} from "./core/index.ts";
|
||||
@@ -0,0 +1,331 @@
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import type { CSSProperties } from "react";
|
||||
import type {
|
||||
TerminalPreviewSegmentStyle,
|
||||
TerminalPreviewSnapshot,
|
||||
TerminalTheme
|
||||
} from "../contracts/index.ts";
|
||||
|
||||
export interface TerminalDockPreviewProps {
|
||||
frame?: TerminalDockPreviewFrame | null;
|
||||
snapshot: TerminalPreviewSnapshot;
|
||||
theme?: TerminalTheme | null;
|
||||
viewport?: TerminalDockPreviewFrame | null;
|
||||
}
|
||||
|
||||
export interface TerminalDockPreviewFrame {
|
||||
height: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
interface TerminalDockPreviewStyle extends CSSProperties {
|
||||
"--workspace-terminal-dock-preview-background"?: string;
|
||||
"--workspace-terminal-dock-preview-foreground"?: string;
|
||||
"--workspace-terminal-dock-preview-scale"?: string;
|
||||
"--workspace-terminal-dock-preview-source-height"?: string;
|
||||
"--workspace-terminal-dock-preview-source-width"?: string;
|
||||
"--workspace-terminal-dock-preview-height"?: string;
|
||||
"--workspace-terminal-dock-preview-width"?: string;
|
||||
}
|
||||
|
||||
const terminalDockPreviewLineHeight = 1.35;
|
||||
const terminalDockPreviewCharacterWidth = 0.62;
|
||||
const terminalDockPreviewFontSize = 13;
|
||||
const terminalDockPreviewPadding = 16;
|
||||
|
||||
export function TerminalDockPreview({
|
||||
frame = null,
|
||||
snapshot,
|
||||
theme = null,
|
||||
viewport = null
|
||||
}: TerminalDockPreviewProps) {
|
||||
const containerRef = useRef<HTMLSpanElement | null>(null);
|
||||
const [layout, setLayout] = useState(() =>
|
||||
resolveTerminalDockPreviewLayout({
|
||||
availableSize: viewport,
|
||||
fitMode: viewport ? "cover" : "contain",
|
||||
frame,
|
||||
snapshot
|
||||
})
|
||||
);
|
||||
const style: TerminalDockPreviewStyle = {};
|
||||
if (theme?.background) {
|
||||
style["--workspace-terminal-dock-preview-background"] = theme.background;
|
||||
}
|
||||
if (theme?.foreground) {
|
||||
style["--workspace-terminal-dock-preview-foreground"] = theme.foreground;
|
||||
}
|
||||
if (layout.viewportWidth > 0 && layout.viewportHeight > 0) {
|
||||
style["--workspace-terminal-dock-preview-height"] =
|
||||
`${layout.viewportHeight}px`;
|
||||
style["--workspace-terminal-dock-preview-width"] =
|
||||
`${layout.viewportWidth}px`;
|
||||
style["--workspace-terminal-dock-preview-scale"] = String(layout.scale);
|
||||
style["--workspace-terminal-dock-preview-source-height"] =
|
||||
`${layout.sourceHeight}px`;
|
||||
style["--workspace-terminal-dock-preview-source-width"] =
|
||||
`${layout.sourceWidth}px`;
|
||||
}
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container || typeof ResizeObserver === "undefined") {
|
||||
return;
|
||||
}
|
||||
const updateFontSize = () => {
|
||||
const nextLayout = resolveTerminalDockPreviewLayout({
|
||||
availableSize:
|
||||
viewport ?? readTerminalDockPreviewAvailableSize(container),
|
||||
fitMode: viewport ? "cover" : "contain",
|
||||
frame,
|
||||
snapshot
|
||||
});
|
||||
setLayout((current) => {
|
||||
if (
|
||||
Math.abs(current.scale - nextLayout.scale) < 0.001 &&
|
||||
Math.abs(current.sourceHeight - nextLayout.sourceHeight) < 0.5 &&
|
||||
Math.abs(current.sourceWidth - nextLayout.sourceWidth) < 0.5 &&
|
||||
Math.abs(current.viewportHeight - nextLayout.viewportHeight) < 0.5 &&
|
||||
Math.abs(current.viewportWidth - nextLayout.viewportWidth) < 0.5
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
return nextLayout;
|
||||
});
|
||||
};
|
||||
updateFontSize();
|
||||
const observer = new ResizeObserver(updateFontSize);
|
||||
observer.observe(container);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [frame, snapshot.cols, snapshot.lines.length, viewport]);
|
||||
|
||||
return (
|
||||
<span
|
||||
className="workspace-terminal__dock-preview-frame"
|
||||
data-terminal-dock-preview=""
|
||||
ref={containerRef}
|
||||
style={style}
|
||||
>
|
||||
<span className="workspace-terminal__dock-preview-viewport">
|
||||
<span className="workspace-terminal__dock-preview">
|
||||
{snapshot.lines.map((line, index) => (
|
||||
<span className="workspace-terminal__dock-preview-line" key={index}>
|
||||
{line.segments.length > 0
|
||||
? line.segments.map((segment, segmentIndex) => (
|
||||
<span
|
||||
className="workspace-terminal__dock-preview-segment"
|
||||
key={segmentIndex}
|
||||
style={resolveTerminalDockPreviewSegmentStyle(
|
||||
segment.style
|
||||
)}
|
||||
>
|
||||
{segment.text}
|
||||
</span>
|
||||
))
|
||||
: " "}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function resolveTerminalDockPreviewLayout({
|
||||
availableSize,
|
||||
fitMode,
|
||||
frame,
|
||||
snapshot
|
||||
}: {
|
||||
availableSize: TerminalDockPreviewFrame | null;
|
||||
fitMode: "contain" | "cover";
|
||||
frame: TerminalDockPreviewFrame | null;
|
||||
snapshot: TerminalPreviewSnapshot;
|
||||
}) {
|
||||
const availableWidth = availableSize?.width ?? 0;
|
||||
const availableHeight = availableSize?.height ?? 0;
|
||||
const previewRatio = resolveTerminalDockPreviewRatio(frame, snapshot);
|
||||
const sourceSize = resolveTerminalDockPreviewSourceSize(frame, snapshot);
|
||||
const viewportSize =
|
||||
fitMode === "cover"
|
||||
? {
|
||||
height: availableHeight > 0 ? availableHeight : 0,
|
||||
width: availableWidth > 0 ? availableWidth : 0
|
||||
}
|
||||
: fitTerminalDockPreviewSize({
|
||||
availableHeight,
|
||||
availableWidth,
|
||||
ratio: previewRatio
|
||||
});
|
||||
const scale = resolveTerminalDockPreviewScale({
|
||||
availableHeight: viewportSize.height,
|
||||
availableWidth: viewportSize.width,
|
||||
fitMode,
|
||||
sourceHeight: sourceSize.height,
|
||||
sourceWidth: sourceSize.width
|
||||
});
|
||||
return {
|
||||
scale,
|
||||
sourceHeight: sourceSize.height,
|
||||
sourceWidth: sourceSize.width,
|
||||
viewportHeight: viewportSize.height,
|
||||
viewportWidth: viewportSize.width
|
||||
};
|
||||
}
|
||||
|
||||
function readTerminalDockPreviewAvailableSize(element: HTMLElement) {
|
||||
const computedStyle = window.getComputedStyle(element);
|
||||
const computedWidth = Number.parseFloat(computedStyle.width);
|
||||
const computedHeight = Number.parseFloat(computedStyle.height);
|
||||
if (
|
||||
Number.isFinite(computedWidth) &&
|
||||
computedWidth > 0 &&
|
||||
Number.isFinite(computedHeight) &&
|
||||
computedHeight > 0
|
||||
) {
|
||||
return {
|
||||
height: computedHeight,
|
||||
width: computedWidth
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
height: Math.max(0, element.clientHeight),
|
||||
width: Math.max(0, element.clientWidth)
|
||||
};
|
||||
}
|
||||
|
||||
function resolveTerminalDockPreviewRatio(
|
||||
frame: TerminalDockPreviewFrame | null,
|
||||
snapshot: TerminalPreviewSnapshot
|
||||
) {
|
||||
if (frame && frame.width > 0 && frame.height > 0) {
|
||||
return frame.width / frame.height;
|
||||
}
|
||||
const rowCount = Math.max(1, snapshot.lines.length);
|
||||
const colCount = Math.max(1, Math.min(snapshot.cols, 160));
|
||||
return (
|
||||
(colCount * terminalDockPreviewCharacterWidth) /
|
||||
(rowCount * terminalDockPreviewLineHeight)
|
||||
);
|
||||
}
|
||||
|
||||
function resolveTerminalDockPreviewSourceSize(
|
||||
frame: TerminalDockPreviewFrame | null,
|
||||
snapshot: TerminalPreviewSnapshot
|
||||
) {
|
||||
if (frame && frame.width > 0 && frame.height > 0) {
|
||||
return {
|
||||
height: frame.height,
|
||||
width: frame.width
|
||||
};
|
||||
}
|
||||
|
||||
const rowCount = Math.max(1, snapshot.lines.length);
|
||||
const colCount = Math.max(1, Math.min(snapshot.cols, 160));
|
||||
return {
|
||||
height:
|
||||
rowCount * terminalDockPreviewFontSize * terminalDockPreviewLineHeight +
|
||||
terminalDockPreviewPadding,
|
||||
width:
|
||||
colCount *
|
||||
terminalDockPreviewFontSize *
|
||||
terminalDockPreviewCharacterWidth +
|
||||
terminalDockPreviewPadding
|
||||
};
|
||||
}
|
||||
|
||||
function fitTerminalDockPreviewSize(input: {
|
||||
availableHeight: number;
|
||||
availableWidth: number;
|
||||
ratio: number;
|
||||
}) {
|
||||
if (
|
||||
input.availableHeight <= 0 ||
|
||||
input.availableWidth <= 0 ||
|
||||
!Number.isFinite(input.ratio) ||
|
||||
input.ratio <= 0
|
||||
) {
|
||||
return { height: 0, width: 0 };
|
||||
}
|
||||
|
||||
const widthFromFullHeight = input.availableHeight * input.ratio;
|
||||
const heightFromFullWidth = input.availableWidth / input.ratio;
|
||||
if (widthFromFullHeight <= input.availableWidth) {
|
||||
return {
|
||||
height: input.availableHeight,
|
||||
width: widthFromFullHeight
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
height: heightFromFullWidth,
|
||||
width: input.availableWidth
|
||||
};
|
||||
}
|
||||
|
||||
function resolveTerminalDockPreviewScale(input: {
|
||||
availableHeight: number;
|
||||
availableWidth: number;
|
||||
fitMode: "contain" | "cover";
|
||||
sourceHeight: number;
|
||||
sourceWidth: number;
|
||||
}) {
|
||||
if (
|
||||
input.availableHeight <= 0 ||
|
||||
input.availableWidth <= 0 ||
|
||||
input.sourceHeight <= 0 ||
|
||||
input.sourceWidth <= 0
|
||||
) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
const widthScale = input.availableWidth / input.sourceWidth;
|
||||
const heightScale = input.availableHeight / input.sourceHeight;
|
||||
return input.fitMode === "cover"
|
||||
? Math.max(widthScale, heightScale)
|
||||
: Math.min(widthScale, heightScale);
|
||||
}
|
||||
|
||||
function resolveTerminalDockPreviewSegmentStyle(
|
||||
segmentStyle: TerminalPreviewSegmentStyle | undefined
|
||||
): CSSProperties | undefined {
|
||||
if (!segmentStyle) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const style: CSSProperties = {};
|
||||
if (segmentStyle.background) {
|
||||
style.backgroundColor = segmentStyle.background;
|
||||
}
|
||||
if (segmentStyle.color) {
|
||||
style.color = segmentStyle.color;
|
||||
}
|
||||
if (segmentStyle.bold) {
|
||||
style.fontWeight = 700;
|
||||
}
|
||||
if (segmentStyle.dim) {
|
||||
style.opacity = 0.64;
|
||||
}
|
||||
if (segmentStyle.italic) {
|
||||
style.fontStyle = "italic";
|
||||
}
|
||||
|
||||
const decorations: string[] = [];
|
||||
if (segmentStyle.underline) {
|
||||
decorations.push("underline");
|
||||
}
|
||||
if (segmentStyle.strikethrough) {
|
||||
decorations.push("line-through");
|
||||
}
|
||||
if (segmentStyle.overline) {
|
||||
decorations.push("overline");
|
||||
}
|
||||
if (decorations.length > 0) {
|
||||
style.textDecorationLine = decorations.join(" ");
|
||||
}
|
||||
|
||||
return style;
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { useState } from "react";
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { Badge, StatusDot } from "@tutti-os/ui-system";
|
||||
import type {
|
||||
TerminalCloseGuardResult,
|
||||
TerminalHeaderAccessoryRenderer,
|
||||
TerminalNodeExternalState,
|
||||
TerminalPreviewChangeHandler,
|
||||
TerminalSessionStatus
|
||||
} from "../contracts/index.ts";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import { createTerminalCloseDiagnostics } from "../core/sessionDiagnostics.ts";
|
||||
import { isTerminalSessionEndedStatus } from "../core/index.ts";
|
||||
import { hasTerminalHeaderDefaultActions } from "./headerActions.ts";
|
||||
import { TerminalSurface } from "./TerminalSurface.tsx";
|
||||
|
||||
export interface TerminalNodeProps {
|
||||
children?: ReactNode;
|
||||
controllerLeaseRetainedExternally?: boolean;
|
||||
externalState?: TerminalNodeExternalState | null;
|
||||
feature: TerminalNodeFeature;
|
||||
headerAccessory?: TerminalHeaderAccessoryRenderer;
|
||||
nodeId: string;
|
||||
onFocusRequest?: () => void;
|
||||
onPreviewChange?: TerminalPreviewChangeHandler;
|
||||
sessionId?: string | null;
|
||||
showHeader?: boolean;
|
||||
}
|
||||
|
||||
export interface TerminalNodeHeaderProps extends HTMLAttributes<HTMLElement> {
|
||||
className?: string;
|
||||
defaultActions?: ReactNode;
|
||||
externalState?: TerminalNodeExternalState | null;
|
||||
feature: TerminalNodeFeature;
|
||||
headerAccessory?: TerminalHeaderAccessoryRenderer;
|
||||
onCloseRequest?: () => void;
|
||||
sessionId?: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalCloseGuardDialogProps {
|
||||
feature: TerminalNodeFeature;
|
||||
leaderCommand?: string | null;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
open: boolean;
|
||||
}
|
||||
|
||||
export function TerminalNode({
|
||||
children,
|
||||
controllerLeaseRetainedExternally = false,
|
||||
externalState = null,
|
||||
feature,
|
||||
headerAccessory,
|
||||
nodeId,
|
||||
onFocusRequest,
|
||||
onPreviewChange,
|
||||
sessionId,
|
||||
showHeader = true
|
||||
}: TerminalNodeProps) {
|
||||
const resolvedSessionId = sessionId ?? externalState?.sessionId ?? null;
|
||||
const status = externalState?.status ?? "created";
|
||||
|
||||
return (
|
||||
<section
|
||||
className="workspace-terminal"
|
||||
data-terminal-node={nodeId}
|
||||
data-terminal-session-id={resolvedSessionId ?? undefined}
|
||||
onClick={onFocusRequest}
|
||||
>
|
||||
{showHeader ? (
|
||||
<TerminalNodeHeader
|
||||
externalState={externalState}
|
||||
feature={feature}
|
||||
headerAccessory={headerAccessory}
|
||||
sessionId={resolvedSessionId}
|
||||
/>
|
||||
) : null}
|
||||
<div className="workspace-terminal__body">
|
||||
{children ??
|
||||
(resolvedSessionId ? (
|
||||
<TerminalSurface
|
||||
controllerLeaseRetainedExternally={
|
||||
controllerLeaseRetainedExternally
|
||||
}
|
||||
externalState={externalState}
|
||||
feature={feature}
|
||||
nodeId={nodeId}
|
||||
onPreviewChange={onPreviewChange}
|
||||
sessionId={resolvedSessionId}
|
||||
status={status}
|
||||
/>
|
||||
) : (
|
||||
<div className="workspace-terminal__placeholder">
|
||||
{feature.i18n.t("emptySession")}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function TerminalNodeHeader({
|
||||
className,
|
||||
defaultActions,
|
||||
externalState = null,
|
||||
feature,
|
||||
headerAccessory,
|
||||
onCloseRequest,
|
||||
sessionId,
|
||||
...headerProps
|
||||
}: TerminalNodeHeaderProps) {
|
||||
const status = externalState?.status ?? "created";
|
||||
const statusLabel = resolveTerminalStatusLabel(feature, status);
|
||||
const resolvedSessionId = sessionId ?? externalState?.sessionId ?? null;
|
||||
const hasDefaultActions = hasTerminalHeaderDefaultActions(defaultActions);
|
||||
const [pendingCloseGuard, setPendingCloseGuard] =
|
||||
useState<TerminalCloseGuardResult | null>(null);
|
||||
const [closeError, setCloseError] = useState<string | null>(null);
|
||||
const closeDiagnostics = resolvedSessionId
|
||||
? createTerminalCloseDiagnostics({
|
||||
diagnostics: feature.diagnostics,
|
||||
sessionId: resolvedSessionId
|
||||
})
|
||||
: null;
|
||||
|
||||
const closeTerminal = async (skipConfirmation: boolean) => {
|
||||
if (
|
||||
!resolvedSessionId ||
|
||||
isTerminalSessionEndedStatus(externalState?.status ?? "created")
|
||||
) {
|
||||
onCloseRequest?.();
|
||||
return;
|
||||
}
|
||||
|
||||
setCloseError(null);
|
||||
try {
|
||||
if (!skipConfirmation) {
|
||||
closeDiagnostics?.requested();
|
||||
const guard = await feature.closeGuard.check({
|
||||
sessionId: resolvedSessionId
|
||||
});
|
||||
if (guard.requiresConfirmation) {
|
||||
setPendingCloseGuard(guard);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await feature.launchService.terminate({ sessionId: resolvedSessionId });
|
||||
closeDiagnostics?.confirmed();
|
||||
setPendingCloseGuard(null);
|
||||
onCloseRequest?.();
|
||||
} catch (error) {
|
||||
setCloseError(errorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<header
|
||||
{...headerProps}
|
||||
className={joinClassName("workspace-terminal__header", className)}
|
||||
>
|
||||
{defaultActions}
|
||||
<div className="workspace-terminal__header-main">
|
||||
<span className="workspace-terminal__title">
|
||||
{externalState?.title?.trim() || feature.i18n.t("title")}
|
||||
</span>
|
||||
<Badge className="workspace-terminal__status-tag" variant="default">
|
||||
<StatusDot
|
||||
pulse={status === "running" || status === "starting"}
|
||||
size="xs"
|
||||
tone={resolveTerminalStatusTone(status)}
|
||||
/>
|
||||
{statusLabel}
|
||||
</Badge>
|
||||
</div>
|
||||
{headerAccessory?.({
|
||||
externalState,
|
||||
sessionId: resolvedSessionId
|
||||
})}
|
||||
<div
|
||||
className="workspace-terminal__actions"
|
||||
onDoubleClick={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
>
|
||||
{onCloseRequest && !hasDefaultActions ? (
|
||||
<button
|
||||
aria-label={feature.i18n.t("actions.close")}
|
||||
className="workspace-terminal__icon-button"
|
||||
onClick={() => {
|
||||
void closeTerminal(false);
|
||||
}}
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
x
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<TerminalCloseGuardDialog
|
||||
feature={feature}
|
||||
leaderCommand={pendingCloseGuard?.leaderCommand}
|
||||
onCancel={() => setPendingCloseGuard(null)}
|
||||
onConfirm={() => {
|
||||
void closeTerminal(true);
|
||||
}}
|
||||
open={Boolean(pendingCloseGuard)}
|
||||
/>
|
||||
{closeError ? (
|
||||
<div className="workspace-terminal__close-error" role="status">
|
||||
{closeError}
|
||||
</div>
|
||||
) : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export function TerminalCloseGuardDialog({
|
||||
feature,
|
||||
leaderCommand,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
open
|
||||
}: TerminalCloseGuardDialogProps) {
|
||||
if (!open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="workspace-terminal__close-guard" role="alertdialog">
|
||||
<h2>{feature.i18n.t("closeGuard.title")}</h2>
|
||||
<p>{feature.i18n.t("closeGuard.description")}</p>
|
||||
{leaderCommand ? <code>{leaderCommand}</code> : null}
|
||||
<div className="workspace-terminal__close-guard-actions">
|
||||
<button onClick={() => onCancel()} type="button">
|
||||
{feature.i18n.t("closeGuard.cancel")}
|
||||
</button>
|
||||
<button onClick={() => onConfirm()} type="button">
|
||||
{feature.i18n.t("closeGuard.confirm")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function resolveTerminalStatusLabel(
|
||||
feature: TerminalNodeFeature,
|
||||
status: TerminalSessionStatus
|
||||
): string {
|
||||
return feature.i18n.t(`status.${status}`);
|
||||
}
|
||||
|
||||
function resolveTerminalStatusTone(
|
||||
status: TerminalSessionStatus
|
||||
): "amber" | "blue" | "green" | "neutral" | "red" {
|
||||
switch (status) {
|
||||
case "running":
|
||||
case "starting":
|
||||
return "blue";
|
||||
case "exited":
|
||||
return "green";
|
||||
case "failed":
|
||||
return "red";
|
||||
case "detached":
|
||||
return "amber";
|
||||
case "created":
|
||||
return "neutral";
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function joinClassName(...values: Array<string | undefined>): string {
|
||||
return values.filter(Boolean).join(" ");
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { ILink, Terminal } from "@xterm/xterm";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import { createTerminalFileLinkProvider } from "./terminalFileLinkProvider.ts";
|
||||
|
||||
test("terminal file link provider resolves cwd from the latest getter value", async () => {
|
||||
let currentCwd = "/workspace/first";
|
||||
const openCalls: Array<Record<string, unknown>> = [];
|
||||
const provider = createTerminalFileLinkProvider({
|
||||
feature: {
|
||||
linkHandler: {
|
||||
open(target) {
|
||||
openCalls.push(target as Record<string, unknown>);
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
} as TerminalNodeFeature,
|
||||
getCwd: () => currentCwd,
|
||||
terminal: {
|
||||
buffer: {
|
||||
active: {
|
||||
getLine() {
|
||||
return {
|
||||
translateToString() {
|
||||
return "./src/app.ts:12:4";
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
} as unknown as Terminal
|
||||
});
|
||||
|
||||
const links = await new Promise<ILink[] | undefined>((resolve) => {
|
||||
provider.provideLinks(1, resolve);
|
||||
});
|
||||
|
||||
assert.ok(links);
|
||||
assert.equal(links.length, 1);
|
||||
|
||||
links[0]?.activate({} as MouseEvent, links[0]?.text ?? "");
|
||||
currentCwd = "/workspace/second";
|
||||
links[0]?.activate({} as MouseEvent, links[0]?.text ?? "");
|
||||
|
||||
assert.deepEqual(
|
||||
openCalls.map((call) => ({
|
||||
column: call.column,
|
||||
cwd: call.cwd,
|
||||
line: call.line,
|
||||
path: call.path
|
||||
})),
|
||||
[
|
||||
{
|
||||
column: 4,
|
||||
cwd: "/workspace/first",
|
||||
line: 12,
|
||||
path: "./src/app.ts"
|
||||
},
|
||||
{
|
||||
column: 4,
|
||||
cwd: "/workspace/second",
|
||||
line: 12,
|
||||
path: "./src/app.ts"
|
||||
}
|
||||
]
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { CSSProperties } from "react";
|
||||
import type {
|
||||
TerminalNodeExternalState,
|
||||
TerminalPreviewChangeHandler,
|
||||
TerminalSessionStatus
|
||||
} from "../contracts/index.ts";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import { createTerminalSurfaceDiagnostics } from "../core/sessionDiagnostics.ts";
|
||||
import { createTerminalSurfaceRuntime } from "./terminalSurfaceRuntime.ts";
|
||||
import { isTerminalFindShortcut } from "./terminalFindShortcut.ts";
|
||||
import { useTerminalFindController } from "./useTerminalFindController.ts";
|
||||
import { useTerminalSessionController } from "./useTerminalSessionController.ts";
|
||||
|
||||
export interface TerminalSurfaceProps {
|
||||
controllerLeaseRetainedExternally?: boolean;
|
||||
externalState: TerminalNodeExternalState | null;
|
||||
feature: TerminalNodeFeature;
|
||||
nodeId: string;
|
||||
onPreviewChange?: TerminalPreviewChangeHandler;
|
||||
sessionId: string;
|
||||
status: TerminalSessionStatus;
|
||||
}
|
||||
|
||||
export function TerminalSurface({
|
||||
controllerLeaseRetainedExternally = false,
|
||||
externalState,
|
||||
feature,
|
||||
nodeId,
|
||||
onPreviewChange,
|
||||
sessionId,
|
||||
status
|
||||
}: TerminalSurfaceProps) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const currentCwdRef = useRef<string | null>(externalState?.cwd ?? null);
|
||||
const featureRef = useRef(feature);
|
||||
const findInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const runtimeRef = useRef<ReturnType<
|
||||
typeof createTerminalSurfaceRuntime
|
||||
> | null>(null);
|
||||
const [interactionError, setInteractionError] = useState<string | null>(null);
|
||||
const { controller, state } = useTerminalSessionController({
|
||||
feature,
|
||||
nodeId,
|
||||
retainLease: !controllerLeaseRetainedExternally,
|
||||
sessionId
|
||||
});
|
||||
const find = useTerminalFindController({
|
||||
getRuntime: () => runtimeRef.current
|
||||
});
|
||||
const theme = useMemo(
|
||||
() =>
|
||||
feature.resolveTheme({
|
||||
runtimeKind: externalState?.runtimeKind ?? "local",
|
||||
sessionId,
|
||||
status
|
||||
}),
|
||||
[externalState?.runtimeKind, feature, sessionId, status]
|
||||
);
|
||||
const surfaceDiagnostics = useMemo(
|
||||
() =>
|
||||
createTerminalSurfaceDiagnostics({
|
||||
diagnostics: feature.diagnostics,
|
||||
nodeId,
|
||||
sessionId
|
||||
}),
|
||||
[feature.diagnostics, nodeId, sessionId]
|
||||
);
|
||||
const surfaceError = interactionError ?? state.surfaceError;
|
||||
|
||||
useEffect(() => {
|
||||
currentCwdRef.current = externalState?.cwd ?? null;
|
||||
}, [externalState?.cwd]);
|
||||
|
||||
useEffect(() => {
|
||||
featureRef.current = feature;
|
||||
}, [feature]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!find.state.open) {
|
||||
return;
|
||||
}
|
||||
const input = findInputRef.current;
|
||||
if (!input) {
|
||||
return;
|
||||
}
|
||||
input.focus();
|
||||
input.select();
|
||||
}, [find.state.open]);
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
|
||||
surfaceDiagnostics.mount();
|
||||
setInteractionError(null);
|
||||
|
||||
const runtime = createTerminalSurfaceRuntime({
|
||||
container,
|
||||
diagnostics: surfaceDiagnostics,
|
||||
feature: featureRef.current,
|
||||
getCwd: () => currentCwdRef.current,
|
||||
nodeId,
|
||||
onResize: ({ cols, rows }) => {
|
||||
surfaceDiagnostics.resize({ cols, rows });
|
||||
void controller.resize({ cols, rows });
|
||||
},
|
||||
onPreviewChange,
|
||||
onUserInput: (data, encoding) => {
|
||||
controller.write(data, encoding);
|
||||
},
|
||||
sessionId,
|
||||
theme
|
||||
});
|
||||
runtimeRef.current = runtime;
|
||||
runtime.syncOutput(state.rawOutput, state.contentEpoch);
|
||||
runtime.focus();
|
||||
|
||||
return () => {
|
||||
surfaceDiagnostics.dispose();
|
||||
runtime.dispose();
|
||||
if (runtimeRef.current === runtime) {
|
||||
runtimeRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [controller, nodeId, sessionId, surfaceDiagnostics]);
|
||||
|
||||
useEffect(() => {
|
||||
runtimeRef.current?.setTheme(theme);
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
runtimeRef.current?.syncOutput(state.rawOutput, state.contentEpoch);
|
||||
}, [state.contentEpoch, state.rawOutput]);
|
||||
|
||||
const writeInput = (data: string) => {
|
||||
controller.write(data);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="workspace-terminal__surface-shell"
|
||||
style={
|
||||
theme.background
|
||||
? ({
|
||||
"--workspace-terminal-background": theme.background
|
||||
} as CSSProperties)
|
||||
: undefined
|
||||
}
|
||||
onKeyDownCapture={(event) => {
|
||||
if (!isTerminalFindShortcut(event)) {
|
||||
if (event.key === "Escape" && find.state.open) {
|
||||
find.actions.close();
|
||||
runtimeRef.current?.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
find.actions.open();
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
if (feature.dropInput) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
if (!feature.dropInput) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
void Promise.resolve(
|
||||
feature.dropInput({
|
||||
cwd: externalState?.cwd ?? null,
|
||||
dataTransfer: event.dataTransfer,
|
||||
sessionId
|
||||
})
|
||||
)
|
||||
.then((input) => {
|
||||
if (input) {
|
||||
writeInput(input);
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => setInteractionError(errorMessage(error)));
|
||||
}}
|
||||
>
|
||||
{find.state.open ? (
|
||||
<form
|
||||
className="workspace-terminal__find"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
find.actions.onSubmit();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label={feature.i18n.t("findPlaceholder")}
|
||||
ref={findInputRef}
|
||||
onChange={(event) => {
|
||||
find.actions.onQueryChange(event.currentTarget.value);
|
||||
}}
|
||||
placeholder={feature.i18n.t("findPlaceholder")}
|
||||
type="search"
|
||||
value={find.state.query}
|
||||
/>
|
||||
<button
|
||||
className="workspace-terminal__find-toggle"
|
||||
aria-label={feature.i18n.t("actions.caseSensitive")}
|
||||
aria-pressed={find.state.caseSensitive}
|
||||
onClick={() => find.actions.toggleCaseSensitive()}
|
||||
type="button"
|
||||
>
|
||||
Aa
|
||||
</button>
|
||||
<button
|
||||
className="workspace-terminal__find-toggle"
|
||||
aria-label={feature.i18n.t("actions.regex")}
|
||||
aria-pressed={find.state.regex}
|
||||
onClick={() => find.actions.toggleRegex()}
|
||||
type="button"
|
||||
>
|
||||
.*
|
||||
</button>
|
||||
<button
|
||||
className="workspace-terminal__find-nav workspace-terminal__find-nav--previous"
|
||||
aria-label={feature.i18n.t("actions.previous")}
|
||||
onClick={() => find.actions.findPrevious()}
|
||||
type="button"
|
||||
/>
|
||||
<button
|
||||
className="workspace-terminal__find-nav workspace-terminal__find-nav--next"
|
||||
aria-label={feature.i18n.t("actions.next")}
|
||||
onClick={() => find.actions.findNext()}
|
||||
type="submit"
|
||||
/>
|
||||
</form>
|
||||
) : null}
|
||||
<div
|
||||
className="workspace-terminal__xterm"
|
||||
data-terminal-xterm=""
|
||||
ref={containerRef}
|
||||
/>
|
||||
{surfaceError ? (
|
||||
<div className="workspace-terminal__surface-error" role="status">
|
||||
{surfaceError}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export function hasTerminalHeaderDefaultActions(
|
||||
defaultActions: ReactNode
|
||||
): boolean {
|
||||
return defaultActions !== undefined && defaultActions !== null;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export {
|
||||
TerminalCloseGuardDialog,
|
||||
TerminalNode,
|
||||
TerminalNodeHeader,
|
||||
type TerminalCloseGuardDialogProps,
|
||||
type TerminalNodeHeaderProps,
|
||||
type TerminalNodeProps
|
||||
} from "./TerminalNode.tsx";
|
||||
export {
|
||||
TerminalDockPreview,
|
||||
type TerminalDockPreviewProps
|
||||
} from "./TerminalDockPreview.tsx";
|
||||
@@ -0,0 +1,110 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
resolveTerminalClipboardShortcut,
|
||||
type TerminalClipboardShortcutEvent
|
||||
} from "./terminalClipboardShortcuts.ts";
|
||||
|
||||
function createEvent(
|
||||
overrides: Partial<TerminalClipboardShortcutEvent> = {}
|
||||
): TerminalClipboardShortcutEvent {
|
||||
return {
|
||||
altKey: false,
|
||||
ctrlKey: true,
|
||||
key: "c",
|
||||
metaKey: false,
|
||||
repeat: false,
|
||||
shiftKey: false,
|
||||
type: "keydown",
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
test("copies a selection with Ctrl+C and preserves Ctrl+C as PTY input otherwise", () => {
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(createEvent(), {
|
||||
hasSelection: true,
|
||||
platform: "other"
|
||||
}),
|
||||
"copy"
|
||||
);
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(createEvent(), {
|
||||
hasSelection: false,
|
||||
platform: "other"
|
||||
}),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("pastes with Ctrl+V and Ctrl+Shift+V", () => {
|
||||
for (const shiftKey of [false, true]) {
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(createEvent({ key: "v", shiftKey }), {
|
||||
hasSelection: false,
|
||||
platform: "other"
|
||||
}),
|
||||
"paste"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("supports the Windows terminal Insert-key clipboard shortcuts", () => {
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(
|
||||
createEvent({ key: "Insert", shiftKey: true }),
|
||||
{
|
||||
hasSelection: false,
|
||||
platform: "other"
|
||||
}
|
||||
),
|
||||
"paste"
|
||||
);
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(createEvent({ key: "Insert" }), {
|
||||
hasSelection: true,
|
||||
platform: "other"
|
||||
}),
|
||||
"copy"
|
||||
);
|
||||
});
|
||||
|
||||
test("uses Command shortcuts on macOS and does not treat Control as Command", () => {
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(
|
||||
createEvent({ ctrlKey: false, key: "c", metaKey: true }),
|
||||
{ hasSelection: true, platform: "mac" }
|
||||
),
|
||||
"copy"
|
||||
);
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(
|
||||
createEvent({ ctrlKey: false, key: "v", metaKey: true }),
|
||||
{ hasSelection: false, platform: "mac" }
|
||||
),
|
||||
"paste"
|
||||
);
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(createEvent({ key: "v" }), {
|
||||
hasSelection: false,
|
||||
platform: "mac"
|
||||
}),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("ignores keyup, repeats, and Alt-modified shortcuts", () => {
|
||||
for (const overrides of [
|
||||
{ type: "keyup" },
|
||||
{ repeat: true },
|
||||
{ altKey: true }
|
||||
]) {
|
||||
assert.equal(
|
||||
resolveTerminalClipboardShortcut(createEvent(overrides), {
|
||||
hasSelection: true,
|
||||
platform: "other"
|
||||
}),
|
||||
null
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
export type TerminalClipboardShortcutAction = "copy" | "paste";
|
||||
|
||||
export type TerminalClipboardPlatform = "mac" | "other";
|
||||
|
||||
export interface TerminalClipboardShortcutEvent {
|
||||
altKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
key: string;
|
||||
metaKey: boolean;
|
||||
repeat?: boolean;
|
||||
shiftKey: boolean;
|
||||
type: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the platform shortcuts that xterm does not consistently handle in
|
||||
* an embedded Windows/Electron terminal. Ctrl/C copies a selection while
|
||||
* Ctrl/C without a selection remains the PTY interrupt sequence.
|
||||
*/
|
||||
export function resolveTerminalClipboardShortcut(
|
||||
event: TerminalClipboardShortcutEvent,
|
||||
input: {
|
||||
hasSelection: boolean;
|
||||
platform: TerminalClipboardPlatform;
|
||||
}
|
||||
): TerminalClipboardShortcutAction | null {
|
||||
if (event.type !== "keydown" || event.altKey || event.repeat) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const key = event.key.toLowerCase();
|
||||
if (input.platform === "mac" && !event.metaKey) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
input.platform !== "mac" &&
|
||||
!event.ctrlKey &&
|
||||
!(event.shiftKey && key === "insert")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (input.platform !== "mac" && event.shiftKey && key === "insert") {
|
||||
return "paste";
|
||||
}
|
||||
if (input.platform !== "mac" && event.ctrlKey && key === "insert") {
|
||||
return input.hasSelection ? "copy" : null;
|
||||
}
|
||||
if (key === "c" && input.hasSelection) {
|
||||
return "copy";
|
||||
}
|
||||
if (key === "v") {
|
||||
return "paste";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveTerminalClipboardPlatform(): TerminalClipboardPlatform {
|
||||
if (typeof navigator !== "undefined" && /Mac/i.test(navigator.platform)) {
|
||||
return "mac";
|
||||
}
|
||||
return "other";
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ILink, ILinkProvider, Terminal } from "@xterm/xterm";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import {
|
||||
detectTerminalFileLinks,
|
||||
toTerminalLinkTarget
|
||||
} from "../core/index.ts";
|
||||
|
||||
export function createTerminalFileLinkProvider(input: {
|
||||
feature: TerminalNodeFeature;
|
||||
getCwd: () => string | null;
|
||||
terminal: Terminal;
|
||||
}): ILinkProvider {
|
||||
return {
|
||||
provideLinks(bufferLineNumber, callback) {
|
||||
if (!input.feature.linkHandler) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const line = input.terminal.buffer.active.getLine(bufferLineNumber - 1);
|
||||
if (!line) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const text = line.translateToString(true);
|
||||
const links = detectTerminalFileLinks(text).map<ILink>((link) => ({
|
||||
activate: () => {
|
||||
void input.feature.linkHandler?.open({
|
||||
...toTerminalLinkTarget(link),
|
||||
cwd: input.getCwd()
|
||||
});
|
||||
},
|
||||
range: {
|
||||
end: {
|
||||
x: link.index + link.text.length,
|
||||
y: bufferLineNumber
|
||||
},
|
||||
start: {
|
||||
x: link.index + 1,
|
||||
y: bufferLineNumber
|
||||
}
|
||||
},
|
||||
text: link.text
|
||||
}));
|
||||
|
||||
callback(links.length > 0 ? links : undefined);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isTerminalFindShortcut } from "./terminalFindShortcut.ts";
|
||||
|
||||
test("terminal find shortcut accepts cmd+f and ctrl+f", () => {
|
||||
assert.equal(
|
||||
isTerminalFindShortcut({
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
key: "f",
|
||||
metaKey: true
|
||||
}),
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
isTerminalFindShortcut({
|
||||
altKey: false,
|
||||
ctrlKey: true,
|
||||
key: "F",
|
||||
metaKey: false
|
||||
}),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal find shortcut rejects unrelated modifier combinations", () => {
|
||||
assert.equal(
|
||||
isTerminalFindShortcut({
|
||||
altKey: true,
|
||||
ctrlKey: false,
|
||||
key: "f",
|
||||
metaKey: true
|
||||
}),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
isTerminalFindShortcut({
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
key: "f",
|
||||
metaKey: false
|
||||
}),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
isTerminalFindShortcut({
|
||||
altKey: false,
|
||||
ctrlKey: true,
|
||||
key: "g",
|
||||
metaKey: false
|
||||
}),
|
||||
false
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
export function isTerminalFindShortcut(
|
||||
event: Pick<KeyboardEvent, "altKey" | "ctrlKey" | "key" | "metaKey">
|
||||
): boolean {
|
||||
if (event.altKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(event.metaKey || event.ctrlKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return event.key.toLowerCase() === "f";
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
createTerminalImeInputGuard,
|
||||
type TerminalImeKeyEvent
|
||||
} from "./terminalImeInputGuard.ts";
|
||||
|
||||
test("terminal IME guard suppresses terminal input while composition is active", () => {
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "z" })), false);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: " " })), false);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "Enter" })), false);
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(keyEvent({ key: "ArrowDown" })),
|
||||
false
|
||||
);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "Shift" })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard allows regular input outside composition", () => {
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "a" })), true);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "Enter" })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard suppresses the key that commits composition", () => {
|
||||
let now = 1_000;
|
||||
const guard = createTerminalImeInputGuard({ now: () => now });
|
||||
const event = keyEvent({
|
||||
key: "Enter",
|
||||
preventDefault: () => undefined,
|
||||
stopPropagation: () => undefined
|
||||
});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(event), false);
|
||||
now += 100;
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "a" })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard prevents native input for post-composition commit keys", () => {
|
||||
let preventDefaultCalls = 0;
|
||||
let stopPropagationCalls = 0;
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(
|
||||
keyEvent({
|
||||
key: " ",
|
||||
preventDefault: () => {
|
||||
preventDefaultCalls += 1;
|
||||
},
|
||||
stopPropagation: () => {
|
||||
stopPropagationCalls += 1;
|
||||
}
|
||||
})
|
||||
),
|
||||
false
|
||||
);
|
||||
assert.equal(preventDefaultCalls, 1);
|
||||
assert.equal(stopPropagationCalls, 1);
|
||||
});
|
||||
|
||||
test("terminal IME guard keeps the post-composition window open for repeated native events", () => {
|
||||
let now = 1_000;
|
||||
const guard = createTerminalImeInputGuard({ now: () => now });
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: " " })), false);
|
||||
now += 10;
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: " " })), false);
|
||||
now += 100;
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: " " })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard does not prevent native input during active composition", () => {
|
||||
let preventDefaultCalls = 0;
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(
|
||||
keyEvent({
|
||||
key: "z",
|
||||
preventDefault: () => {
|
||||
preventDefaultCalls += 1;
|
||||
}
|
||||
})
|
||||
),
|
||||
false
|
||||
);
|
||||
assert.equal(preventDefaultCalls, 0);
|
||||
});
|
||||
|
||||
test("terminal IME guard does not suppress delayed input after composition", () => {
|
||||
let now = 1_000;
|
||||
const guard = createTerminalImeInputGuard({ now: () => now });
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
now += 100;
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "a" })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard lets genuine input through right after composition", () => {
|
||||
let preventDefaultCalls = 0;
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(
|
||||
keyEvent({
|
||||
key: "a",
|
||||
preventDefault: () => {
|
||||
preventDefaultCalls += 1;
|
||||
}
|
||||
})
|
||||
),
|
||||
true
|
||||
);
|
||||
assert.equal(preventDefaultCalls, 0);
|
||||
});
|
||||
|
||||
test("terminal IME guard passes IME process keys through after composition", () => {
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "Process" })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard suppresses candidate-selection digits after composition", () => {
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "2" })), false);
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(keyEvent({ key: "2", type: "keyup" })),
|
||||
true
|
||||
);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "2" })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard closes the suppression window on keyup", () => {
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "Enter" })), false);
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(keyEvent({ key: "Enter", type: "keyup" })),
|
||||
true
|
||||
);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "Enter" })), true);
|
||||
});
|
||||
|
||||
test("terminal IME guard keeps composition suppression across keyups", () => {
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(keyEvent({ key: "n", type: "keyup" })),
|
||||
true
|
||||
);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "n" })), false);
|
||||
});
|
||||
|
||||
test("terminal IME guard consumes post-composition state for shortcuts", () => {
|
||||
const guard = createTerminalImeInputGuard({});
|
||||
|
||||
guard.handleCompositionStart();
|
||||
guard.handleCompositionEnd();
|
||||
|
||||
assert.equal(
|
||||
guard.shouldProcessKeyEvent(keyEvent({ ctrlKey: true, key: "c" })),
|
||||
true
|
||||
);
|
||||
assert.equal(guard.shouldProcessKeyEvent(keyEvent({ key: "a" })), true);
|
||||
});
|
||||
|
||||
function keyEvent(
|
||||
overrides: Partial<TerminalImeKeyEvent>
|
||||
): TerminalImeKeyEvent {
|
||||
return {
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
isComposing: false,
|
||||
key: "a",
|
||||
metaKey: false,
|
||||
type: "keydown",
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
const postCompositionSuppressMs = 80;
|
||||
|
||||
export interface TerminalImeKeyEvent {
|
||||
altKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
isComposing: boolean;
|
||||
key: string;
|
||||
metaKey: boolean;
|
||||
preventDefault?: () => void;
|
||||
stopPropagation?: () => void;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface TerminalImeInputGuard {
|
||||
dispose(): void;
|
||||
handleCompositionEnd(): void;
|
||||
handleCompositionStart(): void;
|
||||
shouldProcessKeyEvent(event: TerminalImeKeyEvent): boolean;
|
||||
}
|
||||
|
||||
export function createTerminalImeInputGuard(input: {
|
||||
now?: () => number;
|
||||
textarea?: HTMLTextAreaElement;
|
||||
}): TerminalImeInputGuard {
|
||||
const now = input.now ?? (() => Date.now());
|
||||
let composing = false;
|
||||
let compositionEndedAt: number | null = null;
|
||||
|
||||
const guard: TerminalImeInputGuard = {
|
||||
dispose() {
|
||||
input.textarea?.removeEventListener(
|
||||
"compositionstart",
|
||||
guard.handleCompositionStart
|
||||
);
|
||||
input.textarea?.removeEventListener(
|
||||
"compositionend",
|
||||
guard.handleCompositionEnd
|
||||
);
|
||||
},
|
||||
handleCompositionEnd() {
|
||||
composing = false;
|
||||
compositionEndedAt = now();
|
||||
},
|
||||
handleCompositionStart() {
|
||||
composing = true;
|
||||
compositionEndedAt = null;
|
||||
},
|
||||
shouldProcessKeyEvent(event) {
|
||||
if (event.type === "keyup") {
|
||||
// Ghost commit-key events replay before the physical key is released,
|
||||
// so any keyup after compositionend means later keydowns are genuine.
|
||||
if (!composing) {
|
||||
compositionEndedAt = null;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!isKeyInputEvent(event)) {
|
||||
return true;
|
||||
}
|
||||
if (isModifierOnlyKey(event.key)) {
|
||||
return true;
|
||||
}
|
||||
if (composing || event.isComposing) {
|
||||
return false;
|
||||
}
|
||||
if (compositionEndedAt === null) {
|
||||
return true;
|
||||
}
|
||||
if (now() - compositionEndedAt > postCompositionSuppressMs) {
|
||||
compositionEndedAt = null;
|
||||
return true;
|
||||
}
|
||||
if (!isPlainKeyEvent(event)) {
|
||||
compositionEndedAt = null;
|
||||
return true;
|
||||
}
|
||||
if (!isCompositionCommitKey(event.key)) {
|
||||
// Letters, digits, and IME "Process" keydowns right after a commit are
|
||||
// new input, not commit-key ghosts; xterm must keep handling them so
|
||||
// keyCode 229 punctuation still reaches the PTY.
|
||||
compositionEndedAt = null;
|
||||
return true;
|
||||
}
|
||||
event.preventDefault?.();
|
||||
event.stopPropagation?.();
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
input.textarea?.addEventListener(
|
||||
"compositionstart",
|
||||
guard.handleCompositionStart
|
||||
);
|
||||
input.textarea?.addEventListener(
|
||||
"compositionend",
|
||||
guard.handleCompositionEnd
|
||||
);
|
||||
|
||||
return guard;
|
||||
}
|
||||
|
||||
function isKeyInputEvent(event: TerminalImeKeyEvent): boolean {
|
||||
return event.type === "keydown" || event.type === "keypress";
|
||||
}
|
||||
|
||||
function isPlainKeyEvent(event: TerminalImeKeyEvent): boolean {
|
||||
return !event.altKey && !event.ctrlKey && !event.metaKey;
|
||||
}
|
||||
|
||||
function isCompositionCommitKey(key: string): boolean {
|
||||
// Digits commit candidates too (数字键选词), so treat them as commit keys;
|
||||
// genuine digits typed after the commit key's keyup are unaffected because
|
||||
// the keyup already closed the suppression window.
|
||||
return (
|
||||
key === "Enter" ||
|
||||
key === "Escape" ||
|
||||
key === " " ||
|
||||
(key.length === 1 && key >= "0" && key <= "9")
|
||||
);
|
||||
}
|
||||
|
||||
function isModifierOnlyKey(key: string): boolean {
|
||||
return (
|
||||
key === "Alt" ||
|
||||
key === "AltGraph" ||
|
||||
key === "Control" ||
|
||||
key === "Meta" ||
|
||||
key === "Shift"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { resolveTerminalSurfaceOutputPlan } from "./terminalSurfaceOutputPlan.ts";
|
||||
|
||||
test("terminal surface output plan skips stale empty bootstrap over cached output", () => {
|
||||
assert.equal(
|
||||
resolveTerminalSurfaceOutputPlan({
|
||||
committedRawOutput: "cached output",
|
||||
contentEpoch: 0,
|
||||
nextContentEpoch: 0,
|
||||
rawOutput: ""
|
||||
}),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal surface output plan resets on content epoch changes", () => {
|
||||
assert.deepEqual(
|
||||
resolveTerminalSurfaceOutputPlan({
|
||||
committedRawOutput: "before",
|
||||
contentEpoch: 1,
|
||||
nextContentEpoch: 2,
|
||||
rawOutput: "after"
|
||||
}),
|
||||
{
|
||||
nextCommittedRawOutput: "after",
|
||||
nextContentEpoch: 2,
|
||||
reset: true,
|
||||
write: "after"
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal surface output plan appends only the delta for incremental output", () => {
|
||||
assert.deepEqual(
|
||||
resolveTerminalSurfaceOutputPlan({
|
||||
committedRawOutput: "hello",
|
||||
contentEpoch: 2,
|
||||
nextContentEpoch: 2,
|
||||
rawOutput: "hello world"
|
||||
}),
|
||||
{
|
||||
nextCommittedRawOutput: "hello world",
|
||||
nextContentEpoch: 2,
|
||||
reset: false,
|
||||
write: " world"
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal surface output plan falls back to reset when delta cannot be derived", () => {
|
||||
assert.deepEqual(
|
||||
resolveTerminalSurfaceOutputPlan({
|
||||
committedRawOutput: "alpha-beta",
|
||||
contentEpoch: 2,
|
||||
nextContentEpoch: 2,
|
||||
rawOutput: "beta"
|
||||
}),
|
||||
{
|
||||
nextCommittedRawOutput: "beta",
|
||||
nextContentEpoch: 2,
|
||||
reset: true,
|
||||
write: "beta"
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { resolveTerminalScrollbackDelta } from "../core/index.ts";
|
||||
|
||||
export interface TerminalSurfaceOutputPlanInput {
|
||||
committedRawOutput: string;
|
||||
contentEpoch: number;
|
||||
nextContentEpoch: number;
|
||||
rawOutput: string;
|
||||
}
|
||||
|
||||
export interface TerminalSurfaceOutputPlan {
|
||||
nextCommittedRawOutput: string;
|
||||
nextContentEpoch: number;
|
||||
reset: boolean;
|
||||
write: string | null;
|
||||
}
|
||||
|
||||
export function resolveTerminalSurfaceOutputPlan(
|
||||
input: TerminalSurfaceOutputPlanInput
|
||||
): TerminalSurfaceOutputPlan | null {
|
||||
if (
|
||||
input.nextContentEpoch === 0 &&
|
||||
input.rawOutput.length === 0 &&
|
||||
input.committedRawOutput.length > 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (input.nextContentEpoch !== input.contentEpoch) {
|
||||
if (input.rawOutput === input.committedRawOutput) {
|
||||
return {
|
||||
nextCommittedRawOutput: input.committedRawOutput,
|
||||
nextContentEpoch: input.nextContentEpoch,
|
||||
reset: false,
|
||||
write: null
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
nextCommittedRawOutput: input.rawOutput,
|
||||
nextContentEpoch: input.nextContentEpoch,
|
||||
reset: true,
|
||||
write: input.rawOutput || null
|
||||
};
|
||||
}
|
||||
|
||||
if (input.rawOutput === input.committedRawOutput) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const delta = resolveTerminalScrollbackDelta(
|
||||
input.committedRawOutput,
|
||||
input.rawOutput
|
||||
);
|
||||
|
||||
return {
|
||||
nextCommittedRawOutput: input.rawOutput,
|
||||
nextContentEpoch: input.nextContentEpoch,
|
||||
reset: !delta,
|
||||
write: delta || input.rawOutput || null
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { IBufferCell, Terminal } from "@xterm/xterm";
|
||||
import type { TerminalTheme } from "../contracts/index.ts";
|
||||
import { createTerminalPreviewSnapshot } from "./terminalSurfacePreview.ts";
|
||||
|
||||
const theme: TerminalTheme = {
|
||||
background: "#111111",
|
||||
foreground: "#eeeeee"
|
||||
};
|
||||
|
||||
type CellSpec = {
|
||||
bgColor?: number;
|
||||
bgDefault?: boolean;
|
||||
bgPalette?: boolean;
|
||||
bgRgb?: boolean;
|
||||
bold?: boolean;
|
||||
chars?: string;
|
||||
dim?: boolean;
|
||||
fgColor?: number;
|
||||
fgDefault?: boolean;
|
||||
fgPalette?: boolean;
|
||||
fgRgb?: boolean;
|
||||
inverse?: boolean;
|
||||
invisible?: boolean;
|
||||
italic?: boolean;
|
||||
overline?: boolean;
|
||||
strikethrough?: boolean;
|
||||
underline?: boolean;
|
||||
width?: number;
|
||||
};
|
||||
|
||||
function createCell(spec: CellSpec = {}): IBufferCell {
|
||||
return {
|
||||
getBgColor: () => spec.bgColor ?? 0,
|
||||
getChars: () => spec.chars ?? "",
|
||||
getFgColor: () => spec.fgColor ?? 0,
|
||||
getWidth: () => spec.width ?? 1,
|
||||
isBgDefault: () => spec.bgDefault ?? true,
|
||||
isBgPalette: () => spec.bgPalette ?? false,
|
||||
isBgRGB: () => spec.bgRgb ?? false,
|
||||
isBold: () => (spec.bold ? 1 : 0),
|
||||
isDim: () => (spec.dim ? 1 : 0),
|
||||
isFgDefault: () => spec.fgDefault ?? true,
|
||||
isFgPalette: () => spec.fgPalette ?? false,
|
||||
isFgRGB: () => spec.fgRgb ?? false,
|
||||
isInverse: () => (spec.inverse ? 1 : 0),
|
||||
isInvisible: () => (spec.invisible ? 1 : 0),
|
||||
isItalic: () => (spec.italic ? 1 : 0),
|
||||
isOverline: () => (spec.overline ? 1 : 0),
|
||||
isStrikethrough: () => (spec.strikethrough ? 1 : 0),
|
||||
isUnderline: () => (spec.underline ? 1 : 0)
|
||||
} as unknown as IBufferCell;
|
||||
}
|
||||
|
||||
function createTerminal(input: {
|
||||
cols?: number;
|
||||
cursorX?: number;
|
||||
cursorY?: number;
|
||||
rows?: number;
|
||||
viewportY?: number;
|
||||
lines: Array<Array<CellSpec | null>>;
|
||||
}): Terminal {
|
||||
const cols = input.cols ?? 8;
|
||||
const rows = input.rows ?? input.lines.length;
|
||||
const lineCells = input.lines.map((line) =>
|
||||
line.map((cell) => (cell ? createCell(cell) : null))
|
||||
);
|
||||
|
||||
return {
|
||||
cols,
|
||||
rows,
|
||||
options: {
|
||||
theme
|
||||
},
|
||||
buffer: {
|
||||
active: {
|
||||
cursorX: input.cursorX ?? 0,
|
||||
cursorY: input.cursorY ?? 0,
|
||||
viewportY: input.viewportY ?? 0,
|
||||
getNullCell: () => createCell(),
|
||||
getLine(row: number) {
|
||||
const cells = lineCells[row];
|
||||
if (!cells) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
getCell(column: number, destination?: IBufferCell) {
|
||||
const cell = cells[column];
|
||||
if (!cell) {
|
||||
return undefined;
|
||||
}
|
||||
if (destination) {
|
||||
Object.assign(destination, cell);
|
||||
return destination;
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
} as unknown as Terminal;
|
||||
}
|
||||
|
||||
function withoutTimestamp(
|
||||
snapshot: ReturnType<typeof createTerminalPreviewSnapshot>
|
||||
) {
|
||||
const { updatedAtUnixMs: _updatedAtUnixMs, ...rest } = snapshot;
|
||||
return rest;
|
||||
}
|
||||
|
||||
test("terminal surface preview projects blank lines as empty segments", () => {
|
||||
const snapshot = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
lines: [[{ chars: " " }, { chars: " " }, null]]
|
||||
})
|
||||
);
|
||||
|
||||
assert.deepEqual(withoutTimestamp(snapshot), {
|
||||
cols: 8,
|
||||
cursorX: 0,
|
||||
cursorY: 0,
|
||||
lines: [{ segments: [] }],
|
||||
revision: snapshot.revision,
|
||||
rows: 1
|
||||
});
|
||||
assert.equal(snapshot.lines[0]?.segments.length, 0);
|
||||
});
|
||||
|
||||
test("terminal surface preview groups adjacent cells with matching styles", () => {
|
||||
const snapshot = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
lines: [
|
||||
[
|
||||
{
|
||||
chars: "h",
|
||||
fgDefault: false,
|
||||
fgPalette: true,
|
||||
fgColor: 1
|
||||
},
|
||||
{
|
||||
chars: "i",
|
||||
fgDefault: false,
|
||||
fgPalette: true,
|
||||
fgColor: 1
|
||||
},
|
||||
{
|
||||
chars: "!",
|
||||
fgDefault: false,
|
||||
fgPalette: true,
|
||||
fgColor: 2
|
||||
}
|
||||
]
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
assert.deepEqual(snapshot.lines[0]?.segments, [
|
||||
{ style: { color: "#cc0000" }, text: "hi" },
|
||||
{ style: { color: "#4e9a06" }, text: "!" }
|
||||
]);
|
||||
});
|
||||
|
||||
test("terminal surface preview maps bold palette and inverse styles", () => {
|
||||
const snapshot = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
lines: [
|
||||
[
|
||||
{
|
||||
bold: true,
|
||||
chars: "A",
|
||||
fgDefault: false,
|
||||
fgPalette: true,
|
||||
fgColor: 1
|
||||
},
|
||||
{
|
||||
chars: "B",
|
||||
fgDefault: false,
|
||||
fgPalette: true,
|
||||
fgColor: 2,
|
||||
bgDefault: false,
|
||||
bgPalette: true,
|
||||
bgColor: 4,
|
||||
inverse: true
|
||||
}
|
||||
]
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
assert.deepEqual(snapshot.lines[0]?.segments, [
|
||||
{ style: { bold: true, color: "#ef2929" }, text: "A" },
|
||||
{
|
||||
style: {
|
||||
background: "#4e9a06",
|
||||
color: "#3465a4"
|
||||
},
|
||||
text: "B"
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test("terminal surface preview maps RGB colors to hex", () => {
|
||||
const snapshot = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
lines: [
|
||||
[
|
||||
{
|
||||
chars: "R",
|
||||
fgDefault: false,
|
||||
fgRgb: true,
|
||||
fgColor: 0x112233
|
||||
},
|
||||
{
|
||||
chars: "G",
|
||||
bgDefault: false,
|
||||
bgRgb: true,
|
||||
bgColor: 0xaabbcc
|
||||
}
|
||||
]
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
assert.deepEqual(snapshot.lines[0]?.segments, [
|
||||
{ style: { color: "#112233" }, text: "R" },
|
||||
{ style: { background: "#aabbcc" }, text: "G" }
|
||||
]);
|
||||
});
|
||||
|
||||
test("terminal surface preview handles wide and invisible cells", () => {
|
||||
const snapshot = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
lines: [
|
||||
[
|
||||
{
|
||||
chars: "中",
|
||||
width: 2
|
||||
},
|
||||
{
|
||||
chars: "",
|
||||
width: 0
|
||||
},
|
||||
{
|
||||
chars: "x",
|
||||
invisible: true,
|
||||
width: 1
|
||||
},
|
||||
{
|
||||
chars: "y"
|
||||
}
|
||||
]
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
// Wide cells contribute their glyph once; trailing width-0 cells are skipped.
|
||||
// Invisible cells become spaces and merge with adjacent default-styled text.
|
||||
assert.deepEqual(snapshot.lines[0]?.segments, [{ text: "中 y" }]);
|
||||
});
|
||||
|
||||
test("terminal surface preview trims trailing default-empty cells", () => {
|
||||
const snapshot = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
cols: 6,
|
||||
lines: [
|
||||
[
|
||||
{ chars: "a" },
|
||||
{ chars: " " },
|
||||
{ chars: " " },
|
||||
{ chars: " " },
|
||||
{ chars: " " },
|
||||
{ chars: " " }
|
||||
]
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
assert.deepEqual(snapshot.lines[0]?.segments, [{ text: "a" }]);
|
||||
});
|
||||
|
||||
test("terminal surface preview revisions change with content and cursor", () => {
|
||||
const base = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
cursorX: 0,
|
||||
cursorY: 0,
|
||||
lines: [[{ chars: "a" }]]
|
||||
})
|
||||
);
|
||||
const contentChanged = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
cursorX: 0,
|
||||
cursorY: 0,
|
||||
lines: [[{ chars: "b" }]]
|
||||
})
|
||||
);
|
||||
const cursorChanged = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
cursorX: 1,
|
||||
cursorY: 0,
|
||||
lines: [[{ chars: "a" }]]
|
||||
})
|
||||
);
|
||||
|
||||
assert.notEqual(base.revision, contentChanged.revision);
|
||||
assert.notEqual(base.revision, cursorChanged.revision);
|
||||
assert.match(base.revision, /^8\n1\n0\n0\n0\n/);
|
||||
});
|
||||
|
||||
test("terminal surface preview caps projected rows and columns", () => {
|
||||
const lines = Array.from({ length: 30 }, () =>
|
||||
Array.from({ length: 200 }, () => ({ chars: "x" as const }))
|
||||
);
|
||||
const snapshot = createTerminalPreviewSnapshot(
|
||||
createTerminal({
|
||||
cols: 200,
|
||||
rows: 30,
|
||||
lines
|
||||
})
|
||||
);
|
||||
|
||||
assert.equal(snapshot.lines.length, 24);
|
||||
assert.equal(
|
||||
snapshot.lines[0]?.segments.reduce(
|
||||
(total, segment) => total + segment.text.length,
|
||||
0
|
||||
),
|
||||
160
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import type { IBufferCell, IBufferLine, Terminal } from "@xterm/xterm";
|
||||
import type {
|
||||
TerminalPreviewLine,
|
||||
TerminalPreviewSegment,
|
||||
TerminalPreviewSegmentStyle,
|
||||
TerminalPreviewSnapshot,
|
||||
TerminalTheme
|
||||
} from "../contracts/index.ts";
|
||||
|
||||
const terminalPreviewMaxRows = 24;
|
||||
const terminalPreviewMaxCols = 160;
|
||||
const terminalPreviewAnsiColors = [
|
||||
"#2e3436",
|
||||
"#cc0000",
|
||||
"#4e9a06",
|
||||
"#c4a000",
|
||||
"#3465a4",
|
||||
"#75507b",
|
||||
"#06989a",
|
||||
"#d3d7cf",
|
||||
"#555753",
|
||||
"#ef2929",
|
||||
"#8ae234",
|
||||
"#fce94f",
|
||||
"#729fcf",
|
||||
"#ad7fa8",
|
||||
"#34e2e2",
|
||||
"#eeeeec"
|
||||
] as const;
|
||||
const terminalPreviewColorSteps = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
|
||||
|
||||
export function createTerminalPreviewSnapshot(
|
||||
terminal: Terminal
|
||||
): TerminalPreviewSnapshot {
|
||||
const buffer = terminal.buffer.active;
|
||||
const rowCount = Math.min(terminal.rows, terminalPreviewMaxRows);
|
||||
const colCount = Math.min(terminal.cols, terminalPreviewMaxCols);
|
||||
const viewportY = Math.max(0, buffer.viewportY);
|
||||
const theme = terminal.options.theme as TerminalTheme;
|
||||
const lines: TerminalPreviewLine[] = [];
|
||||
const scratchCell = buffer.getNullCell();
|
||||
|
||||
for (let index = 0; index < rowCount; index += 1) {
|
||||
lines.push(
|
||||
createTerminalPreviewLine({
|
||||
colCount,
|
||||
line: buffer.getLine(viewportY + index) ?? null,
|
||||
scratchCell,
|
||||
theme
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const revision = [
|
||||
terminal.cols,
|
||||
terminal.rows,
|
||||
buffer.cursorX,
|
||||
buffer.cursorY,
|
||||
viewportY,
|
||||
JSON.stringify(lines)
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
cols: terminal.cols,
|
||||
cursorX: buffer.cursorX,
|
||||
cursorY: buffer.cursorY,
|
||||
lines,
|
||||
revision,
|
||||
rows: terminal.rows,
|
||||
updatedAtUnixMs: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
function createTerminalPreviewLine(input: {
|
||||
colCount: number;
|
||||
line: IBufferLine | null;
|
||||
scratchCell: IBufferCell;
|
||||
theme: TerminalTheme;
|
||||
}): TerminalPreviewLine {
|
||||
const line = input.line;
|
||||
if (!line || input.colCount <= 0) {
|
||||
return { segments: [] };
|
||||
}
|
||||
|
||||
const segments: TerminalPreviewSegment[] = [];
|
||||
let currentStyle: TerminalPreviewSegmentStyle | undefined;
|
||||
let currentText = "";
|
||||
const lastColumn = resolveTerminalPreviewLastColumn({
|
||||
colCount: input.colCount,
|
||||
line,
|
||||
scratchCell: input.scratchCell,
|
||||
theme: input.theme
|
||||
});
|
||||
|
||||
for (let column = 0; column < lastColumn; column += 1) {
|
||||
const cell = line.getCell(column, input.scratchCell);
|
||||
if (!cell) {
|
||||
continue;
|
||||
}
|
||||
const width = cell.getWidth();
|
||||
if (width === 0) {
|
||||
continue;
|
||||
}
|
||||
const style = resolveTerminalPreviewCellStyle(cell, input.theme);
|
||||
const text = cell.isInvisible()
|
||||
? " ".repeat(Math.max(1, width))
|
||||
: cell.getChars() || " ".repeat(Math.max(1, width));
|
||||
|
||||
if (currentText && areTerminalPreviewStylesEqual(currentStyle, style)) {
|
||||
currentText += text;
|
||||
continue;
|
||||
}
|
||||
if (currentText) {
|
||||
segments.push(createTerminalPreviewSegment(currentText, currentStyle));
|
||||
}
|
||||
currentStyle = style;
|
||||
currentText = text;
|
||||
}
|
||||
|
||||
if (currentText) {
|
||||
segments.push(createTerminalPreviewSegment(currentText, currentStyle));
|
||||
}
|
||||
|
||||
return { segments };
|
||||
}
|
||||
|
||||
function createTerminalPreviewSegment(
|
||||
text: string,
|
||||
style: TerminalPreviewSegmentStyle | undefined
|
||||
): TerminalPreviewSegment {
|
||||
if (!style) {
|
||||
return { text };
|
||||
}
|
||||
return { style, text };
|
||||
}
|
||||
|
||||
function resolveTerminalPreviewLastColumn(input: {
|
||||
colCount: number;
|
||||
line: IBufferLine;
|
||||
scratchCell: IBufferCell;
|
||||
theme: TerminalTheme;
|
||||
}) {
|
||||
for (let column = input.colCount - 1; column >= 0; column -= 1) {
|
||||
const cell = input.line.getCell(column, input.scratchCell);
|
||||
if (!cell || cell.getWidth() === 0) {
|
||||
continue;
|
||||
}
|
||||
if (!isTerminalPreviewCellEmptyDefault(cell, input.theme)) {
|
||||
return column + 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function isTerminalPreviewCellEmptyDefault(
|
||||
cell: IBufferCell,
|
||||
theme: TerminalTheme
|
||||
) {
|
||||
const style = resolveTerminalPreviewCellStyle(cell, theme);
|
||||
return (cell.getChars() || " ") === " " && !style;
|
||||
}
|
||||
|
||||
function resolveTerminalPreviewCellStyle(
|
||||
cell: IBufferCell,
|
||||
theme: TerminalTheme
|
||||
): TerminalPreviewSegmentStyle | undefined {
|
||||
const style: TerminalPreviewSegmentStyle = {};
|
||||
const inverse = Boolean(cell.isInverse());
|
||||
const foreground = resolveTerminalPreviewColor(cell, "foreground", theme);
|
||||
const background = resolveTerminalPreviewColor(cell, "background", theme);
|
||||
const color = inverse ? (background ?? theme.background) : foreground;
|
||||
const backgroundColor = inverse
|
||||
? (foreground ?? theme.foreground)
|
||||
: background;
|
||||
|
||||
if (color) {
|
||||
style.color = color;
|
||||
}
|
||||
if (backgroundColor) {
|
||||
style.background = backgroundColor;
|
||||
}
|
||||
if (cell.isBold()) {
|
||||
style.bold = true;
|
||||
}
|
||||
if (cell.isDim()) {
|
||||
style.dim = true;
|
||||
}
|
||||
if (cell.isItalic()) {
|
||||
style.italic = true;
|
||||
}
|
||||
if (cell.isUnderline()) {
|
||||
style.underline = true;
|
||||
}
|
||||
if (cell.isStrikethrough()) {
|
||||
style.strikethrough = true;
|
||||
}
|
||||
if (cell.isOverline()) {
|
||||
style.overline = true;
|
||||
}
|
||||
|
||||
return Object.keys(style).length > 0 ? style : undefined;
|
||||
}
|
||||
|
||||
function resolveTerminalPreviewColor(
|
||||
cell: IBufferCell,
|
||||
channel: "background" | "foreground",
|
||||
theme: TerminalTheme
|
||||
) {
|
||||
const isDefault =
|
||||
channel === "foreground" ? cell.isFgDefault() : cell.isBgDefault();
|
||||
if (isDefault) {
|
||||
return undefined;
|
||||
}
|
||||
const isRgb = channel === "foreground" ? cell.isFgRGB() : cell.isBgRGB();
|
||||
const isPalette =
|
||||
channel === "foreground" ? cell.isFgPalette() : cell.isBgPalette();
|
||||
const rawColor =
|
||||
channel === "foreground" ? cell.getFgColor() : cell.getBgColor();
|
||||
|
||||
if (isRgb) {
|
||||
return terminalPreviewColorToHex(rawColor);
|
||||
}
|
||||
if (!isPalette) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const paletteIndex =
|
||||
channel === "foreground" && cell.isBold() && rawColor >= 0 && rawColor <= 7
|
||||
? rawColor + 8
|
||||
: rawColor;
|
||||
const paletteColor = resolveTerminalPreviewPaletteColor(paletteIndex);
|
||||
if (paletteColor) {
|
||||
return paletteColor;
|
||||
}
|
||||
return channel === "foreground" ? theme.foreground : theme.background;
|
||||
}
|
||||
|
||||
function resolveTerminalPreviewPaletteColor(index: number) {
|
||||
if (index >= 0 && index < terminalPreviewAnsiColors.length) {
|
||||
return terminalPreviewAnsiColors[index];
|
||||
}
|
||||
if (index >= 16 && index <= 231) {
|
||||
const offset = index - 16;
|
||||
const red = terminalPreviewColorSteps[Math.floor(offset / 36) % 6] ?? 0;
|
||||
const green = terminalPreviewColorSteps[Math.floor(offset / 6) % 6] ?? 0;
|
||||
const blue = terminalPreviewColorSteps[offset % 6] ?? 0;
|
||||
return terminalPreviewRgbToHex(red, green, blue);
|
||||
}
|
||||
if (index >= 232 && index <= 255) {
|
||||
const value = 8 + (index - 232) * 10;
|
||||
return terminalPreviewRgbToHex(value, value, value);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function terminalPreviewColorToHex(color: number) {
|
||||
return `#${color.toString(16).padStart(6, "0").slice(-6)}`;
|
||||
}
|
||||
|
||||
function terminalPreviewRgbToHex(red: number, green: number, blue: number) {
|
||||
return `#${[red, green, blue]
|
||||
.map((value) => value.toString(16).padStart(2, "0"))
|
||||
.join("")}`;
|
||||
}
|
||||
|
||||
function areTerminalPreviewStylesEqual(
|
||||
left: TerminalPreviewSegmentStyle | undefined,
|
||||
right: TerminalPreviewSegmentStyle | undefined
|
||||
) {
|
||||
if (left === right) {
|
||||
return true;
|
||||
}
|
||||
if (!left || !right) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
left.background === right.background &&
|
||||
left.bold === right.bold &&
|
||||
left.color === right.color &&
|
||||
left.dim === right.dim &&
|
||||
left.italic === right.italic &&
|
||||
left.overline === right.overline &&
|
||||
left.strikethrough === right.strikethrough &&
|
||||
left.underline === right.underline
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { resolveTerminalSurfaceResizePlan } from "./terminalSurfaceResizePlan.ts";
|
||||
|
||||
test("terminal surface resize plan emits the next size when dimensions change", () => {
|
||||
assert.deepEqual(
|
||||
resolveTerminalSurfaceResizePlan({
|
||||
lastSize: { cols: 80, rows: 24 },
|
||||
nextSize: { cols: 100, rows: 30 }
|
||||
}),
|
||||
{ cols: 100, rows: 30 }
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal surface resize plan skips duplicate dimensions", () => {
|
||||
assert.equal(
|
||||
resolveTerminalSurfaceResizePlan({
|
||||
lastSize: { cols: 100, rows: 30 },
|
||||
nextSize: { cols: 100, rows: 30 }
|
||||
}),
|
||||
null
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
export interface TerminalSurfaceSize {
|
||||
cols: number;
|
||||
rows: number;
|
||||
}
|
||||
|
||||
export function resolveTerminalSurfaceResizePlan(input: {
|
||||
lastSize: TerminalSurfaceSize | null;
|
||||
nextSize: TerminalSurfaceSize;
|
||||
}): TerminalSurfaceSize | null {
|
||||
if (
|
||||
input.lastSize?.cols === input.nextSize.cols &&
|
||||
input.lastSize.rows === input.nextSize.rows
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return input.nextSize;
|
||||
}
|
||||
@@ -0,0 +1,671 @@
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { SearchAddon } from "@xterm/addon-search";
|
||||
import { SerializeAddon } from "@xterm/addon-serialize";
|
||||
import { WebLinksAddon } from "@xterm/addon-web-links";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import type {
|
||||
TerminalPreviewChangeHandler,
|
||||
TerminalTheme,
|
||||
TerminalWriteEncoding
|
||||
} from "../contracts/index.ts";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import { createTerminalScreenStateCache } from "../core/index.ts";
|
||||
import type { TerminalSurfaceDiagnostics } from "../core/sessionDiagnostics.ts";
|
||||
import { createTerminalFileLinkProvider } from "./terminalFileLinkProvider.ts";
|
||||
import {
|
||||
resolveTerminalClipboardPlatform,
|
||||
resolveTerminalClipboardShortcut
|
||||
} from "./terminalClipboardShortcuts.ts";
|
||||
import { createTerminalImeInputGuard } from "./terminalImeInputGuard.ts";
|
||||
import { resolveTerminalSurfaceOutputPlan } from "./terminalSurfaceOutputPlan.ts";
|
||||
import { createTerminalPreviewSnapshot } from "./terminalSurfacePreview.ts";
|
||||
import { resolveTerminalSurfaceResizePlan } from "./terminalSurfaceResizePlan.ts";
|
||||
import { resolveTerminalSurfaceScreenCachePlan } from "./terminalSurfaceScreenCachePlan.ts";
|
||||
import { drainTerminalWriteBatch } from "./terminalWriteBatch.ts";
|
||||
import type { TerminalFindRuntime } from "./useTerminalFindController.ts";
|
||||
|
||||
const terminalScreenStateCache = createTerminalScreenStateCache();
|
||||
|
||||
export interface TerminalSurfaceRuntime extends TerminalFindRuntime {
|
||||
dispose(): void;
|
||||
focus(): void;
|
||||
setTheme(theme: TerminalTheme): void;
|
||||
syncOutput(rawOutput: string, contentEpoch: number): void;
|
||||
}
|
||||
|
||||
export function createTerminalSurfaceRuntime(input: {
|
||||
container: HTMLElement;
|
||||
diagnostics: TerminalSurfaceDiagnostics;
|
||||
feature: TerminalNodeFeature;
|
||||
getCwd: () => string | null;
|
||||
nodeId: string;
|
||||
onResize: (size: { cols: number; rows: number }) => void;
|
||||
onPreviewChange?: TerminalPreviewChangeHandler;
|
||||
onUserInput: (data: string, encoding?: TerminalWriteEncoding) => void;
|
||||
sessionId: string;
|
||||
theme: TerminalTheme;
|
||||
}): TerminalSurfaceRuntime {
|
||||
let contentEpoch = 0;
|
||||
let committedRawOutput = "";
|
||||
let initialLayoutFrame: number | null = null;
|
||||
let initialLayoutTimeout: number | null = null;
|
||||
let lastSize: { cols: number; rows: number } | null = null;
|
||||
let pendingRevealFinalizeFrame: number | null = null;
|
||||
let pendingRevealStartFrame: number | null = null;
|
||||
let pendingRevealWrite: {
|
||||
bytes: number;
|
||||
mode: "cache" | "replace";
|
||||
remainingChunkCount: number;
|
||||
} | null = null;
|
||||
let pendingWriteFrame: number | null = null;
|
||||
let pendingWriteChunks: string[] = [];
|
||||
let pendingRenderedWrite: {
|
||||
bytes: number;
|
||||
mode: "append" | "cache" | "replace";
|
||||
remainingChunkCount: number;
|
||||
} | null = null;
|
||||
let lastPreviewRevision: string | null = null;
|
||||
|
||||
const terminal = new Terminal({
|
||||
allowProposedApi: false,
|
||||
convertEol: true,
|
||||
cursorBlink: true,
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
||||
fontSize: 13,
|
||||
scrollback: input.feature.limits.maxScrollbackLines,
|
||||
theme: resolveXtermTheme(input.theme)
|
||||
});
|
||||
const fitAddon = new FitAddon();
|
||||
const searchAddon = new SearchAddon();
|
||||
const serializeAddon = new SerializeAddon();
|
||||
const webLinksAddon = new WebLinksAddon((_event, uri) => {
|
||||
void input.feature.linkHandler?.open({ url: uri });
|
||||
});
|
||||
terminal.loadAddon(fitAddon);
|
||||
terminal.loadAddon(searchAddon);
|
||||
terminal.loadAddon(serializeAddon);
|
||||
terminal.loadAddon(webLinksAddon);
|
||||
const fileLinkDisposable = terminal.registerLinkProvider(
|
||||
createTerminalFileLinkProvider({
|
||||
feature: input.feature,
|
||||
getCwd: input.getCwd,
|
||||
terminal
|
||||
})
|
||||
);
|
||||
terminal.open(input.container);
|
||||
const imeInputGuard = createTerminalImeInputGuard({
|
||||
textarea: terminal.textarea
|
||||
});
|
||||
const clipboardPlatform = resolveTerminalClipboardPlatform();
|
||||
terminal.attachCustomKeyEventHandler((event) => {
|
||||
const clipboardAction = resolveTerminalClipboardShortcut(event, {
|
||||
hasSelection: terminal.hasSelection(),
|
||||
platform: clipboardPlatform
|
||||
});
|
||||
if (clipboardAction === "copy") {
|
||||
const clipboard = getNavigatorClipboard();
|
||||
const selection = terminal.getSelection();
|
||||
if (!clipboard || !selection) {
|
||||
return imeInputGuard.shouldProcessKeyEvent(event);
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void clipboard
|
||||
.writeText(selection)
|
||||
.catch(() => copyTerminalTextFallback(selection, terminal));
|
||||
return false;
|
||||
}
|
||||
if (clipboardAction === "paste") {
|
||||
const clipboard = getNavigatorClipboard();
|
||||
if (!clipboard) {
|
||||
return imeInputGuard.shouldProcessKeyEvent(event);
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void clipboard
|
||||
.readText()
|
||||
.then((text) => {
|
||||
if (text) {
|
||||
terminal.paste(text);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return false;
|
||||
}
|
||||
return imeInputGuard.shouldProcessKeyEvent(event);
|
||||
});
|
||||
|
||||
const dataSubscription = terminal.onData((data) => {
|
||||
input.onUserInput(data);
|
||||
});
|
||||
const binarySubscription = terminal.onBinary((data) => {
|
||||
input.onUserInput(data, "binary");
|
||||
});
|
||||
const writeParsedSubscription =
|
||||
typeof terminal.onWriteParsed === "function"
|
||||
? terminal.onWriteParsed(() => {
|
||||
if (!pendingRenderedWrite) {
|
||||
refreshTerminalSurface();
|
||||
return;
|
||||
}
|
||||
const renderedWrite = pendingRenderedWrite;
|
||||
pendingRenderedWrite = null;
|
||||
if (
|
||||
renderedWrite.mode === "cache" ||
|
||||
renderedWrite.mode === "replace"
|
||||
) {
|
||||
scheduleHydratedReveal({
|
||||
bytes: renderedWrite.bytes,
|
||||
mode: renderedWrite.mode,
|
||||
remainingChunkCount: renderedWrite.remainingChunkCount
|
||||
});
|
||||
return;
|
||||
}
|
||||
refreshTerminalSurface();
|
||||
logSurfaceWrite(
|
||||
renderedWrite.mode,
|
||||
renderedWrite.bytes,
|
||||
renderedWrite.remainingChunkCount
|
||||
);
|
||||
})
|
||||
: { dispose: () => undefined };
|
||||
|
||||
const resizeTerminal = () => {
|
||||
try {
|
||||
fitAddon.fit();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const plan = resolveTerminalSurfaceResizePlan({
|
||||
lastSize,
|
||||
nextSize: { cols: terminal.cols, rows: terminal.rows }
|
||||
});
|
||||
if (!plan) {
|
||||
return;
|
||||
}
|
||||
lastSize = plan;
|
||||
input.onResize(plan);
|
||||
};
|
||||
|
||||
const resizeObserver =
|
||||
typeof ResizeObserver === "undefined"
|
||||
? null
|
||||
: new ResizeObserver(() => resizeTerminal());
|
||||
resizeObserver?.observe(input.container);
|
||||
scheduleInitialLayoutSync();
|
||||
|
||||
const cached = terminalScreenStateCache.get(input.nodeId, input.sessionId);
|
||||
if (cached) {
|
||||
terminal.write(cached.serialized, () => {
|
||||
queueRenderedWrite("cache", cached.serialized.length, 0);
|
||||
});
|
||||
committedRawOutput = cached.rawSnapshot;
|
||||
}
|
||||
|
||||
return {
|
||||
dispose() {
|
||||
resizeObserver?.disconnect();
|
||||
dataSubscription.dispose();
|
||||
binarySubscription.dispose();
|
||||
writeParsedSubscription.dispose();
|
||||
fileLinkDisposable.dispose();
|
||||
imeInputGuard.dispose();
|
||||
clearInitialLayoutSync();
|
||||
clearPendingReveal();
|
||||
const hasPendingWrites =
|
||||
pendingWriteFrame !== null || pendingWriteChunks.length > 0;
|
||||
const cachePlan = resolveTerminalSurfaceScreenCachePlan({
|
||||
hasPendingWrites,
|
||||
rawSnapshot: committedRawOutput,
|
||||
serialized: hasPendingWrites ? "" : serializeAddon.serialize()
|
||||
});
|
||||
if (cachePlan.action === "save") {
|
||||
terminalScreenStateCache.set(input.nodeId, {
|
||||
cols: terminal.cols,
|
||||
rawSnapshot: cachePlan.rawSnapshot,
|
||||
rows: terminal.rows,
|
||||
serialized: cachePlan.serialized,
|
||||
sessionId: input.sessionId
|
||||
});
|
||||
} else if (cachePlan.action === "remove") {
|
||||
terminalScreenStateCache.remove(input.nodeId, input.sessionId);
|
||||
}
|
||||
clearPendingWrites();
|
||||
emitTerminalPreviewSnapshot();
|
||||
terminal.dispose();
|
||||
},
|
||||
findNext(query, options) {
|
||||
searchAddon.findNext(query, options);
|
||||
},
|
||||
findPrevious(query, options) {
|
||||
searchAddon.findPrevious(query, options);
|
||||
},
|
||||
focus() {
|
||||
terminal.focus();
|
||||
resizeTerminal();
|
||||
},
|
||||
setTheme(theme) {
|
||||
terminal.options.theme = resolveXtermTheme(theme);
|
||||
emitTerminalPreviewSnapshot();
|
||||
},
|
||||
syncOutput(rawOutput, nextContentEpoch) {
|
||||
const plan = resolveTerminalSurfaceOutputPlan({
|
||||
committedRawOutput,
|
||||
contentEpoch,
|
||||
nextContentEpoch,
|
||||
rawOutput
|
||||
});
|
||||
input.diagnostics.outputSync({
|
||||
contentEpoch: nextContentEpoch,
|
||||
nextCommittedBytes:
|
||||
plan?.nextCommittedRawOutput.length ?? committedRawOutput.length,
|
||||
plan: resolveOutputSyncPlan(plan),
|
||||
previousCommittedBytes: committedRawOutput.length,
|
||||
rawBytes: rawOutput.length,
|
||||
writeBytes: plan?.write?.length ?? 0
|
||||
});
|
||||
if (!plan) {
|
||||
return;
|
||||
}
|
||||
contentEpoch = plan.nextContentEpoch;
|
||||
if (plan.reset && plan.write) {
|
||||
replaceTerminalView(plan.write, { reset: true });
|
||||
} else if (plan.reset) {
|
||||
resetTerminalView();
|
||||
}
|
||||
if (plan.write && !plan.reset) {
|
||||
writeToTerminal(plan.write);
|
||||
}
|
||||
committedRawOutput = plan.nextCommittedRawOutput;
|
||||
}
|
||||
};
|
||||
|
||||
function clearPendingWrites() {
|
||||
pendingWriteChunks = [];
|
||||
if (pendingWriteFrame === null) {
|
||||
return;
|
||||
}
|
||||
if (typeof cancelAnimationFrame === "function") {
|
||||
cancelAnimationFrame(pendingWriteFrame);
|
||||
} else {
|
||||
clearTimeout(pendingWriteFrame);
|
||||
}
|
||||
pendingWriteFrame = null;
|
||||
}
|
||||
|
||||
function clearInitialLayoutSync() {
|
||||
if (initialLayoutFrame !== null) {
|
||||
if (typeof cancelAnimationFrame === "function") {
|
||||
cancelAnimationFrame(initialLayoutFrame);
|
||||
} else {
|
||||
clearTimeout(initialLayoutFrame);
|
||||
}
|
||||
initialLayoutFrame = null;
|
||||
}
|
||||
if (initialLayoutTimeout !== null) {
|
||||
clearTimeout(initialLayoutTimeout);
|
||||
initialLayoutTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
function clearPendingReveal() {
|
||||
if (pendingRevealStartFrame !== null) {
|
||||
if (typeof cancelAnimationFrame === "function") {
|
||||
cancelAnimationFrame(pendingRevealStartFrame);
|
||||
} else {
|
||||
clearTimeout(pendingRevealStartFrame);
|
||||
}
|
||||
pendingRevealStartFrame = null;
|
||||
}
|
||||
if (pendingRevealFinalizeFrame !== null) {
|
||||
if (typeof cancelAnimationFrame === "function") {
|
||||
cancelAnimationFrame(pendingRevealFinalizeFrame);
|
||||
} else {
|
||||
clearTimeout(pendingRevealFinalizeFrame);
|
||||
}
|
||||
pendingRevealFinalizeFrame = null;
|
||||
}
|
||||
pendingRevealWrite = null;
|
||||
}
|
||||
|
||||
function flushPendingWrites() {
|
||||
pendingWriteFrame = null;
|
||||
const batch = drainTerminalWriteBatch(
|
||||
pendingWriteChunks,
|
||||
input.feature.limits.maxWriteBatchBytes
|
||||
);
|
||||
pendingWriteChunks = batch.remainingChunks;
|
||||
|
||||
if (!batch.nextWrite) {
|
||||
return;
|
||||
}
|
||||
terminal.write(batch.nextWrite, () => {
|
||||
queueRenderedWrite(
|
||||
"append",
|
||||
batch.nextWrite.length,
|
||||
pendingWriteChunks.length
|
||||
);
|
||||
if (pendingWriteChunks.length > 0) {
|
||||
requestWriteFlush();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function requestWriteFlush() {
|
||||
if (pendingWriteFrame !== null) {
|
||||
return;
|
||||
}
|
||||
if (typeof requestAnimationFrame === "function") {
|
||||
pendingWriteFrame = requestAnimationFrame(flushPendingWrites);
|
||||
return;
|
||||
}
|
||||
pendingWriteFrame = window.setTimeout(flushPendingWrites, 0);
|
||||
}
|
||||
|
||||
function resetTerminalView() {
|
||||
clearPendingReveal();
|
||||
clearPendingWrites();
|
||||
terminal.reset();
|
||||
refreshTerminalSurface();
|
||||
logSurfaceWrite("reset", 0, 0);
|
||||
}
|
||||
|
||||
function replaceTerminalView(
|
||||
data: string,
|
||||
options?: {
|
||||
reset?: boolean;
|
||||
}
|
||||
) {
|
||||
const transformed =
|
||||
input.feature.outputTransform?.({
|
||||
data,
|
||||
sessionId: input.sessionId
|
||||
}) ?? data;
|
||||
if (transformed == null || transformed === "") {
|
||||
return;
|
||||
}
|
||||
clearPendingReveal();
|
||||
clearPendingWrites();
|
||||
if (options?.reset) {
|
||||
terminal.reset();
|
||||
}
|
||||
terminal.write(transformed, () => {
|
||||
queueRenderedWrite("replace", transformed.length, 0);
|
||||
});
|
||||
}
|
||||
|
||||
function refreshTerminalSurface() {
|
||||
if (terminal.rows <= 0) {
|
||||
return;
|
||||
}
|
||||
terminal.refresh(0, terminal.rows - 1);
|
||||
emitTerminalPreviewSnapshot();
|
||||
}
|
||||
|
||||
function emitTerminalPreviewSnapshot() {
|
||||
if (!input.onPreviewChange || terminal.cols <= 0 || terminal.rows <= 0) {
|
||||
return;
|
||||
}
|
||||
const snapshot = createTerminalPreviewSnapshot(terminal);
|
||||
if (snapshot.revision === lastPreviewRevision) {
|
||||
return;
|
||||
}
|
||||
lastPreviewRevision = snapshot.revision;
|
||||
input.onPreviewChange({
|
||||
nodeId: input.nodeId,
|
||||
sessionId: input.sessionId,
|
||||
snapshot
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleInitialLayoutSync() {
|
||||
resizeTerminal();
|
||||
if (typeof requestAnimationFrame === "function") {
|
||||
initialLayoutFrame = requestAnimationFrame(() => {
|
||||
initialLayoutFrame = null;
|
||||
resizeTerminal();
|
||||
refreshTerminalSurface();
|
||||
});
|
||||
} else {
|
||||
initialLayoutFrame = window.setTimeout(() => {
|
||||
initialLayoutFrame = null;
|
||||
resizeTerminal();
|
||||
refreshTerminalSurface();
|
||||
}, 0);
|
||||
}
|
||||
initialLayoutTimeout = window.setTimeout(() => {
|
||||
initialLayoutTimeout = null;
|
||||
resizeTerminal();
|
||||
refreshTerminalSurface();
|
||||
}, 32);
|
||||
}
|
||||
|
||||
function scheduleTerminalWrite(data: string) {
|
||||
pendingWriteChunks.push(data);
|
||||
requestWriteFlush();
|
||||
}
|
||||
|
||||
function writeToTerminal(data: string) {
|
||||
const transformed =
|
||||
input.feature.outputTransform?.({
|
||||
data,
|
||||
sessionId: input.sessionId
|
||||
}) ?? data;
|
||||
if (transformed == null || transformed === "") {
|
||||
return;
|
||||
}
|
||||
scheduleTerminalWrite(transformed);
|
||||
}
|
||||
|
||||
function queueRenderedWrite(
|
||||
mode: "append" | "cache" | "replace",
|
||||
bytes: number,
|
||||
remainingChunkCount: number
|
||||
) {
|
||||
if (pendingRenderedWrite && pendingRenderedWrite.mode === mode) {
|
||||
pendingRenderedWrite = {
|
||||
bytes: pendingRenderedWrite.bytes + bytes,
|
||||
mode,
|
||||
remainingChunkCount
|
||||
};
|
||||
return;
|
||||
}
|
||||
pendingRenderedWrite = {
|
||||
bytes,
|
||||
mode,
|
||||
remainingChunkCount
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleHydratedReveal(write: {
|
||||
bytes: number;
|
||||
mode: "cache" | "replace";
|
||||
remainingChunkCount: number;
|
||||
}) {
|
||||
if (pendingRevealWrite) {
|
||||
pendingRevealWrite = {
|
||||
bytes: pendingRevealWrite.bytes + write.bytes,
|
||||
mode: write.mode,
|
||||
remainingChunkCount: write.remainingChunkCount
|
||||
};
|
||||
} else {
|
||||
pendingRevealWrite = write;
|
||||
}
|
||||
if (
|
||||
pendingRevealStartFrame !== null ||
|
||||
pendingRevealFinalizeFrame !== null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
pendingRevealStartFrame = requestTerminalFrame(() => {
|
||||
pendingRevealStartFrame = null;
|
||||
resizeTerminal();
|
||||
pendingRevealFinalizeFrame = requestTerminalFrame(() => {
|
||||
pendingRevealFinalizeFrame = null;
|
||||
refreshTerminalSurface();
|
||||
const revealWrite = pendingRevealWrite;
|
||||
pendingRevealWrite = null;
|
||||
if (!revealWrite) {
|
||||
return;
|
||||
}
|
||||
logSurfaceWrite(
|
||||
revealWrite.mode,
|
||||
revealWrite.bytes,
|
||||
revealWrite.remainingChunkCount
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function logSurfaceWrite(
|
||||
mode: "append" | "cache" | "replace" | "reset",
|
||||
bytes: number,
|
||||
remainingChunkCount: number
|
||||
) {
|
||||
const buffer = terminal.buffer.active;
|
||||
const xtermElement =
|
||||
input.container.querySelector(".xterm") instanceof HTMLElement
|
||||
? (input.container.querySelector(".xterm") as HTMLElement)
|
||||
: null;
|
||||
const screenElement =
|
||||
input.container.querySelector(".xterm-screen") instanceof HTMLElement
|
||||
? (input.container.querySelector(".xterm-screen") as HTMLElement)
|
||||
: null;
|
||||
const helperElement =
|
||||
input.container.querySelector(".xterm-helpers") instanceof HTMLElement
|
||||
? (input.container.querySelector(".xterm-helpers") as HTMLElement)
|
||||
: null;
|
||||
const rowContainerElement =
|
||||
input.container.querySelector(".xterm-rows") instanceof HTMLElement
|
||||
? (input.container.querySelector(".xterm-rows") as HTMLElement)
|
||||
: null;
|
||||
const firstCanvas =
|
||||
screenElement?.querySelector("canvas") instanceof HTMLCanvasElement
|
||||
? (screenElement.querySelector("canvas") as HTMLCanvasElement)
|
||||
: null;
|
||||
const firstLine = buffer.getLine(0)?.translateToString(true) ?? "";
|
||||
const cursorLine =
|
||||
buffer.getLine(buffer.cursorY)?.translateToString(true) ?? "";
|
||||
const xtermStyle = xtermElement
|
||||
? window.getComputedStyle(xtermElement)
|
||||
: null;
|
||||
const screenStyle = screenElement
|
||||
? window.getComputedStyle(screenElement)
|
||||
: null;
|
||||
const renderDimensions = resolveXtermRenderDimensions(terminal);
|
||||
input.diagnostics.outputWritten({
|
||||
bufferCursorX: buffer.cursorX,
|
||||
bufferCursorY: buffer.cursorY,
|
||||
bufferLength: buffer.length,
|
||||
bytes,
|
||||
canvasClientHeight: firstCanvas?.clientHeight ?? 0,
|
||||
canvasClientWidth: firstCanvas?.clientWidth ?? 0,
|
||||
canvasCount: screenElement?.querySelectorAll("canvas").length ?? 0,
|
||||
cols: terminal.cols,
|
||||
containerClientHeight: input.container.clientHeight,
|
||||
containerClientWidth: input.container.clientWidth,
|
||||
cursorLinePreview: previewTerminalLine(cursorLine),
|
||||
firstLinePreview: previewTerminalLine(firstLine),
|
||||
helperChildCount: helperElement?.childElementCount ?? 0,
|
||||
mode,
|
||||
remainingChunkCount,
|
||||
renderDimensionsReady: renderDimensions !== undefined,
|
||||
rowContainerChildCount: rowContainerElement?.childElementCount ?? 0,
|
||||
rowContainerTextPreview: previewTerminalLine(
|
||||
rowContainerElement?.textContent ?? ""
|
||||
),
|
||||
rows: terminal.rows,
|
||||
screenChildCount: screenElement?.childElementCount ?? 0,
|
||||
screenClientHeight: screenElement?.clientHeight ?? 0,
|
||||
screenClientWidth: screenElement?.clientWidth ?? 0,
|
||||
screenDisplay: screenStyle?.display ?? "",
|
||||
screenOpacity: screenStyle?.opacity ?? "",
|
||||
screenVisibility: screenStyle?.visibility ?? "",
|
||||
serializedBytes: serializeAddon.serialize().length,
|
||||
xtermClientHeight: xtermElement?.clientHeight ?? 0,
|
||||
xtermClientWidth: xtermElement?.clientWidth ?? 0,
|
||||
xtermDisplay: xtermStyle?.display ?? "",
|
||||
xtermOpacity: xtermStyle?.opacity ?? "",
|
||||
xtermVisibility: xtermStyle?.visibility ?? ""
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getNavigatorClipboard(): Clipboard | null {
|
||||
if (typeof navigator === "undefined") {
|
||||
return null;
|
||||
}
|
||||
return navigator.clipboard ?? null;
|
||||
}
|
||||
|
||||
function copyTerminalTextFallback(text: string, terminal: Terminal): void {
|
||||
const document = terminal.element?.ownerDocument;
|
||||
if (!document?.body) {
|
||||
return;
|
||||
}
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.value = text;
|
||||
textarea.setAttribute("readonly", "true");
|
||||
textarea.style.position = "fixed";
|
||||
textarea.style.opacity = "0";
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
try {
|
||||
document.execCommand("copy");
|
||||
} finally {
|
||||
textarea.remove();
|
||||
terminal.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function requestTerminalFrame(callback: () => void) {
|
||||
if (typeof requestAnimationFrame === "function") {
|
||||
return requestAnimationFrame(callback);
|
||||
}
|
||||
return window.setTimeout(callback, 0);
|
||||
}
|
||||
|
||||
function resolveOutputSyncPlan(
|
||||
plan: ReturnType<typeof resolveTerminalSurfaceOutputPlan>
|
||||
): "append" | "replace" | "reset" | "skip" {
|
||||
if (!plan) {
|
||||
return "skip";
|
||||
}
|
||||
if (plan.reset && plan.write) {
|
||||
return "replace";
|
||||
}
|
||||
if (plan.reset) {
|
||||
return "reset";
|
||||
}
|
||||
return "append";
|
||||
}
|
||||
|
||||
function resolveXtermRenderDimensions(terminal: Terminal): unknown {
|
||||
const core: unknown = Reflect.get(terminal, "_core");
|
||||
if (core == null || typeof core !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const renderService: unknown = Reflect.get(core, "_renderService");
|
||||
if (renderService == null || typeof renderService !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return Reflect.get(renderService, "dimensions");
|
||||
}
|
||||
|
||||
function previewTerminalLine(value: string, maxChars = 80) {
|
||||
return value
|
||||
.slice(0, maxChars)
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\n", "\\n");
|
||||
}
|
||||
|
||||
function resolveXtermTheme(theme: TerminalTheme) {
|
||||
return {
|
||||
background: theme.background,
|
||||
cursor: theme.cursor,
|
||||
foreground: theme.foreground,
|
||||
selectionBackground: theme.selectionBackground
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { resolveTerminalSurfaceScreenCachePlan } from "./terminalSurfaceScreenCachePlan.ts";
|
||||
|
||||
test("terminal surface screen cache plan saves serialized output when writes are settled", () => {
|
||||
assert.deepEqual(
|
||||
resolveTerminalSurfaceScreenCachePlan({
|
||||
hasPendingWrites: false,
|
||||
rawSnapshot: "raw",
|
||||
serialized: "serialized"
|
||||
}),
|
||||
{
|
||||
action: "save",
|
||||
rawSnapshot: "raw",
|
||||
serialized: "serialized"
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal surface screen cache plan removes stale cache when writes are still pending", () => {
|
||||
assert.deepEqual(
|
||||
resolveTerminalSurfaceScreenCachePlan({
|
||||
hasPendingWrites: true,
|
||||
rawSnapshot: "raw",
|
||||
serialized: ""
|
||||
}),
|
||||
{ action: "remove" }
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal surface screen cache plan skips empty settled snapshots", () => {
|
||||
assert.deepEqual(
|
||||
resolveTerminalSurfaceScreenCachePlan({
|
||||
hasPendingWrites: false,
|
||||
rawSnapshot: "raw",
|
||||
serialized: ""
|
||||
}),
|
||||
{ action: "skip" }
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
export type TerminalSurfaceScreenCachePlan =
|
||||
| { action: "remove" }
|
||||
| {
|
||||
action: "save";
|
||||
rawSnapshot: string;
|
||||
serialized: string;
|
||||
}
|
||||
| { action: "skip" };
|
||||
|
||||
export function resolveTerminalSurfaceScreenCachePlan(input: {
|
||||
hasPendingWrites: boolean;
|
||||
rawSnapshot: string;
|
||||
serialized: string;
|
||||
}): TerminalSurfaceScreenCachePlan {
|
||||
if (input.hasPendingWrites) {
|
||||
return {
|
||||
action: input.serialized ? "skip" : "remove"
|
||||
};
|
||||
}
|
||||
|
||||
if (!input.serialized) {
|
||||
return { action: "skip" };
|
||||
}
|
||||
|
||||
return {
|
||||
action: "save",
|
||||
rawSnapshot: input.rawSnapshot,
|
||||
serialized: input.serialized
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { drainTerminalWriteBatch } from "./terminalWriteBatch.ts";
|
||||
|
||||
test("terminal write batch drains whole chunks up to the limit", () => {
|
||||
assert.deepEqual(drainTerminalWriteBatch(["abc", "def", "ghi"], 6), {
|
||||
nextWrite: "abcdef",
|
||||
remainingChunks: ["ghi"]
|
||||
});
|
||||
});
|
||||
|
||||
test("terminal write batch splits oversized chunks and preserves the remainder", () => {
|
||||
assert.deepEqual(drainTerminalWriteBatch(["abcdef"], 4), {
|
||||
nextWrite: "abcd",
|
||||
remainingChunks: ["ef"]
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
export interface TerminalWriteBatch {
|
||||
nextWrite: string;
|
||||
remainingChunks: string[];
|
||||
}
|
||||
|
||||
export function drainTerminalWriteBatch(
|
||||
chunks: string[],
|
||||
maxBytes: number
|
||||
): TerminalWriteBatch {
|
||||
let remaining = maxBytes;
|
||||
let nextWrite = "";
|
||||
const remainingChunks = chunks.slice();
|
||||
|
||||
while (remaining > 0 && remainingChunks.length > 0) {
|
||||
const chunk = remainingChunks.shift() ?? "";
|
||||
if (chunk.length <= remaining) {
|
||||
nextWrite += chunk;
|
||||
remaining -= chunk.length;
|
||||
continue;
|
||||
}
|
||||
nextWrite += chunk.slice(0, remaining);
|
||||
remainingChunks.unshift(chunk.slice(remaining));
|
||||
remaining = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
nextWrite,
|
||||
remainingChunks
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState } from "react";
|
||||
|
||||
export interface TerminalFindRuntime {
|
||||
findNext(
|
||||
query: string,
|
||||
options: {
|
||||
caseSensitive: boolean;
|
||||
incremental?: boolean;
|
||||
regex: boolean;
|
||||
}
|
||||
): void;
|
||||
findPrevious(
|
||||
query: string,
|
||||
options: {
|
||||
caseSensitive: boolean;
|
||||
regex: boolean;
|
||||
}
|
||||
): void;
|
||||
}
|
||||
|
||||
export interface TerminalFindController {
|
||||
actions: {
|
||||
close(): void;
|
||||
findNext(): void;
|
||||
findPrevious(): void;
|
||||
open(): void;
|
||||
onQueryChange(query: string): void;
|
||||
onSubmit(): void;
|
||||
toggleCaseSensitive(): void;
|
||||
toggleOpen(): void;
|
||||
toggleRegex(): void;
|
||||
};
|
||||
state: {
|
||||
caseSensitive: boolean;
|
||||
open: boolean;
|
||||
query: string;
|
||||
regex: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export function useTerminalFindController(input: {
|
||||
getRuntime: () => TerminalFindRuntime | null;
|
||||
}): TerminalFindController {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [caseSensitive, setCaseSensitive] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [regex, setRegex] = useState(false);
|
||||
|
||||
const resolveFindOptions = () => ({
|
||||
caseSensitive,
|
||||
regex
|
||||
});
|
||||
|
||||
return {
|
||||
actions: {
|
||||
close() {
|
||||
setOpen(false);
|
||||
},
|
||||
findNext() {
|
||||
input.getRuntime()?.findNext(query, resolveFindOptions());
|
||||
},
|
||||
findPrevious() {
|
||||
input.getRuntime()?.findPrevious(query, resolveFindOptions());
|
||||
},
|
||||
open() {
|
||||
setOpen(true);
|
||||
},
|
||||
onQueryChange(nextQuery) {
|
||||
setQuery(nextQuery);
|
||||
if (!nextQuery) {
|
||||
return;
|
||||
}
|
||||
input.getRuntime()?.findNext(nextQuery, {
|
||||
...resolveFindOptions(),
|
||||
incremental: true
|
||||
});
|
||||
},
|
||||
onSubmit() {
|
||||
input.getRuntime()?.findNext(query, resolveFindOptions());
|
||||
},
|
||||
toggleCaseSensitive() {
|
||||
setCaseSensitive((enabled) => !enabled);
|
||||
},
|
||||
toggleOpen() {
|
||||
setOpen((enabled) => !enabled);
|
||||
},
|
||||
toggleRegex() {
|
||||
setRegex((enabled) => !enabled);
|
||||
}
|
||||
},
|
||||
state: {
|
||||
caseSensitive,
|
||||
open,
|
||||
query,
|
||||
regex
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useExternalStoreSnapshot } from "@tutti-os/ui-react-hooks";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import {
|
||||
acquireTerminalSessionController,
|
||||
type TerminalSessionControllerState
|
||||
} from "../core/sessionController.ts";
|
||||
|
||||
export function useTerminalSessionController(input: {
|
||||
feature: TerminalNodeFeature;
|
||||
nodeId: string;
|
||||
retainLease?: boolean;
|
||||
sessionId: string;
|
||||
}) {
|
||||
const controller = useMemo(
|
||||
() =>
|
||||
acquireTerminalSessionController({
|
||||
feature: input.feature,
|
||||
nodeId: input.nodeId,
|
||||
sessionId: input.sessionId
|
||||
}),
|
||||
[input.nodeId, input.sessionId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (input.retainLease === false) {
|
||||
return;
|
||||
}
|
||||
controller.retain();
|
||||
return () => {
|
||||
controller.release();
|
||||
};
|
||||
}, [controller, input.retainLease]);
|
||||
const state = useExternalStoreSnapshot<TerminalSessionControllerState>({
|
||||
getSnapshot() {
|
||||
return controller.getState();
|
||||
},
|
||||
subscribe(listener) {
|
||||
return controller.subscribe(listener);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
controller,
|
||||
state
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
@import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
.workbench-window-shell[data-workbench-node-type-id="workspace-terminal"]
|
||||
.workbench-window {
|
||||
box-shadow:
|
||||
var(--workbench-window-shadow),
|
||||
0 8px 24px var(--shadow-elevated);
|
||||
}
|
||||
|
||||
.workspace-terminal {
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
flex-direction: column;
|
||||
background: var(--tutti-surface, #111);
|
||||
color: var(--tutti-text, #f4f4f5);
|
||||
}
|
||||
|
||||
.workspace-terminal__header {
|
||||
display: flex;
|
||||
flex: none;
|
||||
height: var(--workbench-header-height);
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 12px;
|
||||
border-bottom: 1px solid var(--border-1);
|
||||
background: var(--background-panel);
|
||||
color: var(--text-primary);
|
||||
padding: 0 12px 0 16px;
|
||||
font-size: 13px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.workspace-terminal__header-main {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.workspace-terminal__title {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.workspace-terminal__status-tag {
|
||||
flex: none;
|
||||
padding-inline: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.workspace-terminal__actions {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.workspace-terminal__icon-button {
|
||||
display: grid;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
place-items: center;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.workspace-terminal__body {
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.workspace-terminal__surface-shell {
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.workspace-terminal__find {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
z-index: 2;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(150px, 210px) 30px 30px 34px 34px;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
max-width: min(352px, calc(100% - 20px));
|
||||
border: 1px solid rgb(255 255 255 / 10%);
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(180deg, rgb(39 39 42 / 94%), rgb(15 23 42 / 92%));
|
||||
box-shadow:
|
||||
0 12px 28px rgb(0 0 0 / 30%),
|
||||
inset 0 1px 0 rgb(255 255 255 / 7%);
|
||||
padding: 5px;
|
||||
backdrop-filter: blur(10px);
|
||||
animation: workspace-terminal__find-enter 140ms ease-out;
|
||||
}
|
||||
|
||||
.workspace-terminal__find input {
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
background: rgb(5 8 18 / 78%);
|
||||
color: rgb(244 244 245);
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
outline: none;
|
||||
padding: 0 11px;
|
||||
box-shadow: inset 0 1px 2px rgb(0 0 0 / 24%);
|
||||
}
|
||||
|
||||
.workspace-terminal__find input:focus {
|
||||
border-color: rgb(125 211 252 / 44%);
|
||||
box-shadow:
|
||||
inset 0 1px 2px rgb(0 0 0 / 24%),
|
||||
0 0 0 1px rgb(125 211 252 / 22%);
|
||||
}
|
||||
|
||||
.workspace-terminal__find button {
|
||||
display: grid;
|
||||
min-width: 30px;
|
||||
height: 28px;
|
||||
place-items: center;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
background: rgb(255 255 255 / 2%);
|
||||
color: rgb(244 244 245 / 82%);
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
padding: 0 8px;
|
||||
transition:
|
||||
background-color 120ms ease,
|
||||
border-color 120ms ease,
|
||||
color 120ms ease,
|
||||
transform 120ms ease;
|
||||
}
|
||||
|
||||
.workspace-terminal__find button:hover {
|
||||
background: rgb(255 255 255 / 7%);
|
||||
color: rgb(244 244 245);
|
||||
}
|
||||
|
||||
.workspace-terminal__find button:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
.workspace-terminal__find button[aria-pressed="true"] {
|
||||
border-color: rgb(125 211 252 / 18%);
|
||||
background: rgb(14 116 144 / 24%);
|
||||
color: rgb(224 242 254);
|
||||
}
|
||||
|
||||
.workspace-terminal__find button:focus-visible {
|
||||
border-color: rgb(125 211 252 / 42%);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.workspace-terminal__find-toggle {
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.workspace-terminal__find-nav {
|
||||
position: relative;
|
||||
min-width: 30px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.workspace-terminal__find-nav::before {
|
||||
content: "";
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-top: 1.5px solid currentColor;
|
||||
border-right: 1.5px solid currentColor;
|
||||
}
|
||||
|
||||
.workspace-terminal__find-nav--previous::before {
|
||||
transform: rotate(-135deg);
|
||||
}
|
||||
|
||||
.workspace-terminal__find-nav--next::before {
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
@keyframes workspace-terminal__find-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-4px) scale(0.985);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.workspace-terminal__xterm {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.workspace-terminal__xterm .xterm {
|
||||
height: 100%;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.workspace-terminal__xterm .xterm-viewport {
|
||||
background-color: var(
|
||||
--workspace-terminal-background,
|
||||
var(--tutti-surface, #111)
|
||||
);
|
||||
}
|
||||
|
||||
.workspace-terminal__surface-error {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
max-width: min(420px, calc(100% - 16px));
|
||||
border: 1px solid rgb(248 113 113 / 50%);
|
||||
border-radius: 6px;
|
||||
background: rgb(69 10 10 / 92%);
|
||||
color: rgb(254 226 226);
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.workspace-terminal__placeholder {
|
||||
display: grid;
|
||||
height: 100%;
|
||||
min-height: 160px;
|
||||
place-items: center;
|
||||
color: var(--tutti-text-muted, rgb(244 244 245 / 68%));
|
||||
}
|
||||
|
||||
.workspace-terminal__close-guard {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 4;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
gap: 12px;
|
||||
background: rgb(0 0 0 / 42%);
|
||||
}
|
||||
|
||||
.workspace-terminal__close-guard > h2,
|
||||
.workspace-terminal__close-guard > p,
|
||||
.workspace-terminal__close-guard > code,
|
||||
.workspace-terminal__close-guard-actions {
|
||||
width: min(360px, calc(100vw - 48px));
|
||||
}
|
||||
|
||||
.workspace-terminal__close-guard > h2 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.workspace-terminal__close-guard > p {
|
||||
margin: 0;
|
||||
color: var(--tutti-text-muted, rgb(244 244 245 / 68%));
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.workspace-terminal__close-guard > code {
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
background: rgb(0 0 0 / 32%);
|
||||
color: inherit;
|
||||
font-size: 11px;
|
||||
padding: 6px 8px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.workspace-terminal__close-guard-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.workspace-terminal__close-error {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
z-index: 5;
|
||||
max-width: min(420px, calc(100% - 16px));
|
||||
border: 1px solid rgb(248 113 113 / 50%);
|
||||
border-radius: 6px;
|
||||
background: rgb(69 10 10 / 92%);
|
||||
color: rgb(254 226 226);
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.workspace-terminal__dock-icon {
|
||||
font-family:
|
||||
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
|
||||
"Courier New", monospace;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.workspace-terminal__dock-preview-frame {
|
||||
display: grid;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
background: var(--workspace-terminal-dock-preview-background, #000);
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.workspace-terminal__dock-preview-viewport {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: var(--workspace-terminal-dock-preview-width, 100%);
|
||||
height: var(--workspace-terminal-dock-preview-height, 100%);
|
||||
overflow: hidden;
|
||||
background: var(--workspace-terminal-dock-preview-background, #000);
|
||||
}
|
||||
|
||||
.workspace-terminal__dock-preview {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
display: block;
|
||||
width: var(--workspace-terminal-dock-preview-source-width, 100%);
|
||||
height: var(--workspace-terminal-dock-preview-source-height, 100%);
|
||||
overflow: hidden;
|
||||
background: var(--workspace-terminal-dock-preview-background, #000);
|
||||
color: var(--workspace-terminal-dock-preview-foreground, #f4f4f5);
|
||||
font-family:
|
||||
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
|
||||
"Courier New", monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.35;
|
||||
padding: 8px;
|
||||
pointer-events: none;
|
||||
text-align: left;
|
||||
transform: translate(-50%, -50%)
|
||||
scale(var(--workspace-terminal-dock-preview-scale, 1));
|
||||
transform-origin: center;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.workspace-terminal__dock-preview-line {
|
||||
display: block;
|
||||
min-height: 1.35em;
|
||||
overflow: hidden;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.workspace-terminal__dock-preview-segment {
|
||||
white-space: pre;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { WorkbenchHostNodeBodyContext } from "@tutti-os/workbench-surface";
|
||||
import type {
|
||||
TerminalNodeExternalState,
|
||||
TerminalPreviewChangeHandler
|
||||
} from "../contracts/index.ts";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
|
||||
export interface TerminalWorkbenchBodyProps {
|
||||
externalState: TerminalNodeExternalState | null;
|
||||
feature: TerminalNodeFeature;
|
||||
nodeId: string;
|
||||
onFocusRequest?: () => void;
|
||||
onPreviewChange?: TerminalPreviewChangeHandler;
|
||||
sessionId: string | null;
|
||||
showHeader: boolean;
|
||||
}
|
||||
|
||||
export function resolveTerminalWorkbenchBodyProps({
|
||||
context,
|
||||
feature,
|
||||
onPreviewChange
|
||||
}: {
|
||||
context: WorkbenchHostNodeBodyContext<
|
||||
TerminalNodeExternalState | null,
|
||||
unknown
|
||||
>;
|
||||
feature: TerminalNodeFeature;
|
||||
onPreviewChange?: TerminalPreviewChangeHandler;
|
||||
}): TerminalWorkbenchBodyProps {
|
||||
// Keep this resolver narrower than TerminalNodeProps on purpose. The workbench
|
||||
// lease keeps the session alive while the node exists, but the mounted surface
|
||||
// must still retain the controller so snapshot hydration starts immediately.
|
||||
// Passing controllerLeaseRetainedExternally here makes a newly opened terminal
|
||||
// render blank until the first user input triggers controller.write().
|
||||
return {
|
||||
externalState: context.externalNodeState,
|
||||
feature,
|
||||
nodeId: context.node.id,
|
||||
onFocusRequest: context.isFocused ? undefined : () => context.focus(),
|
||||
onPreviewChange,
|
||||
sessionId: context.node.data.instanceKey ?? null,
|
||||
showHeader: false
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type {
|
||||
WorkbenchHostNodeBodyContext,
|
||||
WorkbenchHostNodeData
|
||||
} from "@tutti-os/workbench-surface";
|
||||
import type { TerminalNodeExternalState } from "../contracts/index.ts";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import { resolveTerminalWorkbenchBodyProps } from "./bodyProps.ts";
|
||||
import { resolveTerminalWindowCloseEffect } from "./windowCloseEffect.ts";
|
||||
|
||||
test("terminal workbench body lets the mounted surface retain its session", () => {
|
||||
const props = resolveTerminalWorkbenchBodyProps({
|
||||
context: createTerminalWorkbenchBodyTestContext({
|
||||
externalNodeState: null,
|
||||
sessionId: "session-1"
|
||||
}),
|
||||
feature: {
|
||||
i18n: {
|
||||
t(key: string) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
} as TerminalNodeFeature
|
||||
});
|
||||
|
||||
assert.equal("controllerLeaseRetainedExternally" in props, false);
|
||||
assert.equal(props.sessionId, "session-1");
|
||||
});
|
||||
|
||||
test("terminal workbench body forwards preview changes to the host", () => {
|
||||
const onPreviewChange = () => undefined;
|
||||
const props = resolveTerminalWorkbenchBodyProps({
|
||||
context: createTerminalWorkbenchBodyTestContext({
|
||||
externalNodeState: null,
|
||||
sessionId: "session-1"
|
||||
}),
|
||||
feature: {
|
||||
i18n: {
|
||||
t(key: string) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
} as TerminalNodeFeature,
|
||||
onPreviewChange
|
||||
});
|
||||
|
||||
assert.equal(props.onPreviewChange, onPreviewChange);
|
||||
});
|
||||
|
||||
function createTerminalWorkbenchBodyTestContext({
|
||||
externalNodeState,
|
||||
isFocused = true,
|
||||
sessionId = "session-1"
|
||||
}: {
|
||||
externalNodeState: TerminalNodeExternalState | null;
|
||||
isFocused?: boolean;
|
||||
sessionId?: string | null;
|
||||
}): WorkbenchHostNodeBodyContext<TerminalNodeExternalState | null, unknown> {
|
||||
const data: WorkbenchHostNodeData = {
|
||||
instanceId: sessionId ?? "terminal",
|
||||
instanceKey: sessionId,
|
||||
typeId: "workspace-terminal"
|
||||
};
|
||||
|
||||
return {
|
||||
activation: null,
|
||||
displayMode: "floating",
|
||||
externalNodeState,
|
||||
externalWorkspaceState: undefined,
|
||||
focus() {
|
||||
return undefined;
|
||||
},
|
||||
host: {
|
||||
activateNode() {},
|
||||
async collectWindowCloseEffects() {
|
||||
return [];
|
||||
},
|
||||
controller: null,
|
||||
dispose() {},
|
||||
focusNode() {},
|
||||
async launchNode() {
|
||||
return null;
|
||||
},
|
||||
async load() {},
|
||||
minimizeNode() {},
|
||||
reconcileProjectedNodes() {},
|
||||
requestNodeClose() {},
|
||||
setNodeRuntimeState() {},
|
||||
setSnapshotNodeState() {}
|
||||
} as unknown as WorkbenchHostNodeBodyContext<
|
||||
TerminalNodeExternalState | null,
|
||||
unknown
|
||||
>["host"],
|
||||
instanceId: data.instanceId,
|
||||
instanceKey: data.instanceKey,
|
||||
isDragging: false,
|
||||
isFocused,
|
||||
isResizing: false,
|
||||
isVisible: true,
|
||||
node: {
|
||||
data,
|
||||
displayMode: "floating",
|
||||
frame: {
|
||||
height: 520,
|
||||
width: 860,
|
||||
x: 260,
|
||||
y: 140
|
||||
},
|
||||
id: "workspace-terminal:session-1",
|
||||
isMinimized: false,
|
||||
kind: "window",
|
||||
restoreFrame: null,
|
||||
title: "Terminal"
|
||||
},
|
||||
setNodeRuntimeState() {
|
||||
return undefined;
|
||||
},
|
||||
setSnapshotNodeState() {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test("terminal workbench window close effect ignores idle running terminals", async () => {
|
||||
const effect = await resolveTerminalWindowCloseEffect({
|
||||
closeGuard: {
|
||||
async check() {
|
||||
return {
|
||||
reason: "not-running",
|
||||
requiresConfirmation: false,
|
||||
status: "running"
|
||||
};
|
||||
}
|
||||
},
|
||||
description:
|
||||
"This terminal still has running work. Terminating it will stop the session.",
|
||||
externalNodeState: {
|
||||
createdAt: null,
|
||||
cwd: null,
|
||||
endedAt: null,
|
||||
host: null,
|
||||
lastError: null,
|
||||
profileId: null,
|
||||
runtimeKind: "local",
|
||||
sessionId: "session-1",
|
||||
status: "running",
|
||||
title: "Terminal A",
|
||||
updatedAt: null
|
||||
},
|
||||
nodeId: "terminal:session-1",
|
||||
sessionId: "session-1",
|
||||
title: "Terminal A",
|
||||
typeId: "workspace-terminal"
|
||||
});
|
||||
|
||||
assert.equal(effect, null);
|
||||
});
|
||||
|
||||
test("terminal workbench window close effect keeps blocking terminals with foreground work", async () => {
|
||||
const effect = await resolveTerminalWindowCloseEffect({
|
||||
closeGuard: {
|
||||
async check() {
|
||||
return {
|
||||
leaderCommand: "npm run dev",
|
||||
reason: "foreground-process",
|
||||
requiresConfirmation: true,
|
||||
status: "running"
|
||||
};
|
||||
}
|
||||
},
|
||||
description:
|
||||
"This terminal still has running work. Terminating it will stop the session.",
|
||||
externalNodeState: {
|
||||
createdAt: null,
|
||||
cwd: null,
|
||||
endedAt: null,
|
||||
host: null,
|
||||
lastError: null,
|
||||
profileId: null,
|
||||
runtimeKind: "local",
|
||||
sessionId: "session-1",
|
||||
status: "running",
|
||||
title: "Terminal A",
|
||||
updatedAt: null
|
||||
},
|
||||
nodeId: "terminal:session-1",
|
||||
sessionId: "session-1",
|
||||
title: "Terminal A",
|
||||
typeId: "workspace-terminal"
|
||||
});
|
||||
|
||||
assert.deepEqual(effect, {
|
||||
description:
|
||||
"This terminal still has running work. Terminating it will stop the session.",
|
||||
nodeId: "terminal:session-1",
|
||||
title: "Terminal A",
|
||||
typeId: "workspace-terminal"
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,364 @@
|
||||
import { createElement, type PointerEvent, type ReactNode } from "react";
|
||||
import type {
|
||||
WorkbenchContribution,
|
||||
WorkbenchFrame,
|
||||
WorkbenchHostDockEntry,
|
||||
WorkbenchHostExternalStateSource,
|
||||
WorkbenchHostLaunchRequest,
|
||||
WorkbenchHostLaunchResult,
|
||||
WorkbenchHostNodeCloseDecision,
|
||||
WorkbenchHostNodeCloseRequest,
|
||||
WorkbenchHostNodeDefinition,
|
||||
WorkbenchHostNodeMinimizedDockCapability
|
||||
} from "@tutti-os/workbench-surface";
|
||||
import type {
|
||||
TerminalCloseGuardResult,
|
||||
TerminalHeaderAccessoryRenderer,
|
||||
TerminalLaunchInput,
|
||||
TerminalNodeExternalState,
|
||||
TerminalPreviewChangeHandler
|
||||
} from "../contracts/index.ts";
|
||||
import { closeTerminalSession } from "../core/index.ts";
|
||||
import type { TerminalNodeFeature } from "../core/feature.ts";
|
||||
import { acquireTerminalSessionController } from "../core/sessionController.ts";
|
||||
import { resolveTerminalWorkbenchBodyProps } from "./bodyProps.ts";
|
||||
import { resolveTerminalLaunchAnalyticsTrigger } from "./launchAnalytics.ts";
|
||||
import { resolveTerminalWindowCloseEffect } from "./windowCloseEffect.ts";
|
||||
import { TerminalNode, TerminalNodeHeader } from "../react/TerminalNode.tsx";
|
||||
|
||||
export interface TerminalWorkbenchIntent {
|
||||
cwd?: string | null;
|
||||
initialInput?: string | null;
|
||||
profileId?: string | null;
|
||||
}
|
||||
|
||||
type TerminalMinimizedPreviewProvider = Extract<
|
||||
WorkbenchHostNodeMinimizedDockCapability,
|
||||
{ kind: "component" }
|
||||
>["providePreview"];
|
||||
|
||||
export interface CreateTerminalWorkbenchNodeDefinitionInput {
|
||||
feature: TerminalNodeFeature;
|
||||
frame?: WorkbenchFrame;
|
||||
headerAccessory?: TerminalHeaderAccessoryRenderer;
|
||||
onPreviewChange?: TerminalPreviewChangeHandler;
|
||||
provideMinimizedPreview?: TerminalMinimizedPreviewProvider;
|
||||
title?: string;
|
||||
typeId?: string;
|
||||
}
|
||||
|
||||
export type TerminalWorkbenchLaunchInputResolver = (
|
||||
request: WorkbenchHostLaunchRequest
|
||||
) =>
|
||||
| Promise<Partial<Omit<TerminalLaunchInput, "reason" | "workspaceId">>>
|
||||
| Partial<Omit<TerminalLaunchInput, "reason" | "workspaceId">>;
|
||||
|
||||
export interface CreateTerminalWorkbenchLaunchHandlerInput {
|
||||
feature: TerminalNodeFeature;
|
||||
frame?: WorkbenchFrame;
|
||||
resolveLaunchInput?: TerminalWorkbenchLaunchInputResolver;
|
||||
typeId?: string;
|
||||
}
|
||||
|
||||
export interface CreateTerminalDockEntryInput {
|
||||
dockIcon?: ReactNode;
|
||||
feature: TerminalNodeFeature;
|
||||
id?: string;
|
||||
order?: number;
|
||||
sectionId?: string;
|
||||
typeId?: string;
|
||||
}
|
||||
|
||||
export interface TerminalWorkbenchContributionCloseFailure {
|
||||
error: unknown;
|
||||
sessionId: string;
|
||||
status?: TerminalNodeExternalState["status"];
|
||||
}
|
||||
|
||||
export interface CreateTerminalWorkbenchContributionInput {
|
||||
contributionId?: string;
|
||||
dockEntry?: Omit<CreateTerminalDockEntryInput, "feature">;
|
||||
externalStateSource?: WorkbenchHostExternalStateSource<
|
||||
TerminalNodeExternalState | null,
|
||||
unknown
|
||||
>;
|
||||
feature: TerminalNodeFeature;
|
||||
getTerminalState?: (sessionId: string) => TerminalNodeExternalState | null;
|
||||
node?: Omit<CreateTerminalWorkbenchNodeDefinitionInput, "feature">;
|
||||
onCloseFailure?: (failure: TerminalWorkbenchContributionCloseFailure) => void;
|
||||
onConfirmClose?: (
|
||||
guard: TerminalCloseGuardResult
|
||||
) => Promise<boolean> | boolean;
|
||||
resolveLaunchInput?: TerminalWorkbenchLaunchInputResolver;
|
||||
shouldCloseAfterCloseFailure?: (
|
||||
failure: TerminalWorkbenchContributionCloseFailure
|
||||
) => boolean;
|
||||
typeId?: string;
|
||||
}
|
||||
|
||||
export const defaultTerminalWorkbenchTypeId = "workspace-terminal";
|
||||
|
||||
const defaultTerminalNodeFrame: WorkbenchFrame = {
|
||||
height: 520,
|
||||
width: 860,
|
||||
x: 260,
|
||||
y: 140
|
||||
};
|
||||
|
||||
export function createTerminalWorkbenchNodeDefinition({
|
||||
feature,
|
||||
frame = defaultTerminalNodeFrame,
|
||||
headerAccessory,
|
||||
onPreviewChange,
|
||||
provideMinimizedPreview,
|
||||
title,
|
||||
typeId = defaultTerminalWorkbenchTypeId
|
||||
}: CreateTerminalWorkbenchNodeDefinitionInput): WorkbenchHostNodeDefinition<TerminalNodeExternalState> {
|
||||
return {
|
||||
frame,
|
||||
instance: {
|
||||
mode: "multi"
|
||||
},
|
||||
renderBody: (context) =>
|
||||
createElement(
|
||||
TerminalNode,
|
||||
resolveTerminalWorkbenchBodyProps({ context, feature, onPreviewChange })
|
||||
),
|
||||
createLease: ({ node }) => {
|
||||
const sessionId = node.data.instanceKey ?? null;
|
||||
if (!sessionId) {
|
||||
return null;
|
||||
}
|
||||
const controller = acquireTerminalSessionController({
|
||||
feature,
|
||||
nodeId: node.id,
|
||||
sessionId
|
||||
});
|
||||
controller.retain();
|
||||
return {
|
||||
release() {
|
||||
controller.release();
|
||||
}
|
||||
};
|
||||
},
|
||||
getWindowCloseEffect: ({ externalNodeState, node }) =>
|
||||
resolveTerminalWindowCloseEffect({
|
||||
closeGuard: feature.closeGuard,
|
||||
description: feature.i18n.t("closeGuard.description"),
|
||||
externalNodeState,
|
||||
nodeId: node.id,
|
||||
sessionId: node.data.instanceKey ?? null,
|
||||
title: node.title,
|
||||
typeId
|
||||
}),
|
||||
renderHeader: ({
|
||||
defaultActions,
|
||||
dragHandleProps,
|
||||
externalNodeState,
|
||||
isFocused,
|
||||
node,
|
||||
windowActions
|
||||
}) =>
|
||||
createElement(TerminalNodeHeader, {
|
||||
defaultActions,
|
||||
externalState: externalNodeState,
|
||||
feature,
|
||||
headerAccessory,
|
||||
onCloseRequest: () => windowActions.close(),
|
||||
sessionId: node.data.instanceKey ?? null,
|
||||
...dragHandleProps,
|
||||
onPointerDown: (event: PointerEvent<HTMLElement>) => {
|
||||
dragHandleProps.onPointerDown?.(event);
|
||||
if (!isFocused) {
|
||||
windowActions.focus();
|
||||
}
|
||||
}
|
||||
}),
|
||||
title: title ?? feature.i18n.t("title"),
|
||||
typeId,
|
||||
window: {
|
||||
closable: true,
|
||||
defaultOpen: false,
|
||||
minimizedDock: provideMinimizedPreview
|
||||
? {
|
||||
kind: "component",
|
||||
providePreview: provideMinimizedPreview
|
||||
}
|
||||
: undefined,
|
||||
minimizable: true,
|
||||
restoreOnLoad: true
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createTerminalDockEntry({
|
||||
dockIcon,
|
||||
feature,
|
||||
id,
|
||||
order,
|
||||
sectionId,
|
||||
typeId = defaultTerminalWorkbenchTypeId
|
||||
}: CreateTerminalDockEntryInput): WorkbenchHostDockEntry {
|
||||
return {
|
||||
allowNewWindowInDockPopup: false,
|
||||
icon: dockIcon ?? createElement(DefaultTerminalDockIcon),
|
||||
id: id ?? typeId,
|
||||
label: feature.i18n.t("dockLabel"),
|
||||
launchBehavior: "enabled",
|
||||
matchNode: (node) => node.data.typeId === typeId,
|
||||
order,
|
||||
resolvePopupItem: ({ node }) => {
|
||||
const subtitle = node.data.instanceKey ?? node.data.instanceId;
|
||||
return {
|
||||
revision: `${node.title}\n${subtitle}`,
|
||||
subtitle,
|
||||
title: node.title
|
||||
};
|
||||
},
|
||||
sectionId,
|
||||
typeId,
|
||||
visibility: "always"
|
||||
};
|
||||
}
|
||||
|
||||
export function createTerminalWorkbenchLaunchHandler({
|
||||
feature,
|
||||
frame = defaultTerminalNodeFrame,
|
||||
resolveLaunchInput,
|
||||
typeId = defaultTerminalWorkbenchTypeId
|
||||
}: CreateTerminalWorkbenchLaunchHandlerInput): (
|
||||
request: WorkbenchHostLaunchRequest
|
||||
) => Promise<WorkbenchHostLaunchResult | null> {
|
||||
return async (request) => {
|
||||
if (request.typeId !== typeId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolved = (await resolveLaunchInput?.(request)) ?? {};
|
||||
const descriptor = await feature.launchService.create({
|
||||
cwd: resolved.cwd,
|
||||
initialInput: resolved.initialInput,
|
||||
profileId: resolved.profileId,
|
||||
reason: request.reason === "dock" ? "dock" : "intent",
|
||||
workspaceId: request.workspaceId
|
||||
});
|
||||
|
||||
return {
|
||||
activation: {
|
||||
payload: {
|
||||
trigger: resolveTerminalLaunchAnalyticsTrigger(request)
|
||||
},
|
||||
type: "terminal-launch"
|
||||
},
|
||||
defaultFrame: frame,
|
||||
dockEntryId: request.dockEntryId ?? typeId,
|
||||
framePolicy: "cascade",
|
||||
instanceId: descriptor.sessionId,
|
||||
instanceKey: descriptor.sessionId,
|
||||
title: descriptor.title,
|
||||
typeId
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export function createTerminalWorkbenchContribution({
|
||||
contributionId,
|
||||
dockEntry,
|
||||
externalStateSource,
|
||||
feature,
|
||||
getTerminalState,
|
||||
node,
|
||||
onCloseFailure,
|
||||
onConfirmClose,
|
||||
resolveLaunchInput,
|
||||
shouldCloseAfterCloseFailure,
|
||||
typeId = defaultTerminalWorkbenchTypeId
|
||||
}: CreateTerminalWorkbenchContributionInput): WorkbenchContribution {
|
||||
return {
|
||||
dockEntries: [
|
||||
createTerminalDockEntry({
|
||||
...dockEntry,
|
||||
feature,
|
||||
typeId
|
||||
})
|
||||
],
|
||||
externalStateSource,
|
||||
id: contributionId ?? typeId,
|
||||
nodes: [
|
||||
createTerminalWorkbenchNodeDefinition({
|
||||
...node,
|
||||
feature,
|
||||
typeId
|
||||
})
|
||||
],
|
||||
onLaunchRequest: createTerminalWorkbenchLaunchHandler({
|
||||
feature,
|
||||
frame: node?.frame,
|
||||
resolveLaunchInput,
|
||||
typeId
|
||||
}),
|
||||
onNodeCloseRequest: onConfirmClose
|
||||
? (request) =>
|
||||
handleTerminalContributionNodeCloseRequest({
|
||||
feature,
|
||||
getTerminalState,
|
||||
onCloseFailure,
|
||||
onConfirmClose,
|
||||
request,
|
||||
shouldCloseAfterCloseFailure,
|
||||
typeId
|
||||
})
|
||||
: undefined
|
||||
};
|
||||
}
|
||||
|
||||
async function handleTerminalContributionNodeCloseRequest(input: {
|
||||
feature: TerminalNodeFeature;
|
||||
getTerminalState?: (sessionId: string) => TerminalNodeExternalState | null;
|
||||
onCloseFailure?: (failure: TerminalWorkbenchContributionCloseFailure) => void;
|
||||
onConfirmClose: (
|
||||
guard: TerminalCloseGuardResult
|
||||
) => Promise<boolean> | boolean;
|
||||
request: WorkbenchHostNodeCloseRequest;
|
||||
shouldCloseAfterCloseFailure?: (
|
||||
failure: TerminalWorkbenchContributionCloseFailure
|
||||
) => boolean;
|
||||
typeId: string;
|
||||
}): Promise<WorkbenchHostNodeCloseDecision | void> {
|
||||
if (input.request.typeId !== input.typeId) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sessionId = input.request.instanceKey ?? input.request.instanceId;
|
||||
const terminalState = input.getTerminalState?.(sessionId) ?? null;
|
||||
try {
|
||||
const result = await closeTerminalSession({
|
||||
confirm: input.onConfirmClose,
|
||||
feature: input.feature,
|
||||
sessionId,
|
||||
status: terminalState?.status
|
||||
});
|
||||
return result === "closed" ? "close" : "keep-open";
|
||||
} catch (error) {
|
||||
const failure = {
|
||||
error,
|
||||
sessionId,
|
||||
status: terminalState?.status
|
||||
};
|
||||
input.onCloseFailure?.(failure);
|
||||
return input.shouldCloseAfterCloseFailure?.(failure)
|
||||
? "close"
|
||||
: "keep-open";
|
||||
}
|
||||
}
|
||||
|
||||
function DefaultTerminalDockIcon() {
|
||||
return createElement(
|
||||
"span",
|
||||
{
|
||||
"aria-hidden": "true",
|
||||
className: "workspace-terminal__dock-icon"
|
||||
},
|
||||
">"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { WorkbenchHostLaunchRequest } from "@tutti-os/workbench-surface";
|
||||
import { resolveTerminalLaunchAnalyticsTrigger } from "./launchAnalytics.ts";
|
||||
|
||||
const requestContext = {
|
||||
layoutConstraints: {
|
||||
minHeight: 180,
|
||||
minWidth: 280,
|
||||
safeArea: {
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0
|
||||
},
|
||||
surfacePadding: 24
|
||||
},
|
||||
surfaceSize: {
|
||||
height: 720,
|
||||
width: 1280
|
||||
}
|
||||
} satisfies Pick<
|
||||
WorkbenchHostLaunchRequest,
|
||||
"layoutConstraints" | "surfaceSize"
|
||||
>;
|
||||
|
||||
test("terminal launch analytics trigger resolves from launch source", () => {
|
||||
const cases: Array<{
|
||||
expectedTrigger: string;
|
||||
request: WorkbenchHostLaunchRequest;
|
||||
}> = [
|
||||
{
|
||||
expectedTrigger: "dock",
|
||||
request: {
|
||||
dockEntryId: "workspace-terminal",
|
||||
...requestContext,
|
||||
reason: "dock",
|
||||
typeId: "workspace-terminal",
|
||||
workspaceId: "workspace-1"
|
||||
}
|
||||
},
|
||||
{
|
||||
expectedTrigger: "keyboard",
|
||||
request: {
|
||||
dockEntryId: "workspace-terminal",
|
||||
...requestContext,
|
||||
reason: "shortcut",
|
||||
typeId: "workspace-terminal",
|
||||
workspaceId: "workspace-1"
|
||||
}
|
||||
},
|
||||
{
|
||||
expectedTrigger: "launchpad",
|
||||
request: {
|
||||
dockEntryId: "workspace-terminal",
|
||||
...requestContext,
|
||||
payload: {},
|
||||
reason: "launchpad",
|
||||
typeId: "workspace-terminal",
|
||||
workspaceId: "workspace-1"
|
||||
}
|
||||
},
|
||||
{
|
||||
expectedTrigger: "agent_command",
|
||||
request: {
|
||||
...requestContext,
|
||||
payload: {
|
||||
initialInput: "pnpm test\n"
|
||||
},
|
||||
reason: "host",
|
||||
typeId: "workspace-terminal",
|
||||
workspaceId: "workspace-1"
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
for (const { expectedTrigger, request } of cases) {
|
||||
assert.equal(
|
||||
resolveTerminalLaunchAnalyticsTrigger(request),
|
||||
expectedTrigger
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { WorkbenchHostLaunchRequest } from "@tutti-os/workbench-surface";
|
||||
|
||||
export type TerminalLaunchAnalyticsTrigger =
|
||||
| "agent_command"
|
||||
| "dock"
|
||||
| "keyboard"
|
||||
| "launchpad";
|
||||
|
||||
export function resolveTerminalLaunchAnalyticsTrigger(
|
||||
request: WorkbenchHostLaunchRequest
|
||||
): TerminalLaunchAnalyticsTrigger {
|
||||
switch (request.reason) {
|
||||
case "dock":
|
||||
return "dock";
|
||||
case "launchpad":
|
||||
return "launchpad";
|
||||
case "shortcut":
|
||||
return "keyboard";
|
||||
case "host":
|
||||
return hasInitialInput(request.payload) ? "agent_command" : "launchpad";
|
||||
default:
|
||||
return "launchpad";
|
||||
}
|
||||
}
|
||||
|
||||
function hasInitialInput(payload: unknown): boolean {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
return false;
|
||||
}
|
||||
const typed = payload as { initialInput?: unknown };
|
||||
return (
|
||||
typeof typed.initialInput === "string" &&
|
||||
typed.initialInput.trim().length > 0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type {
|
||||
TerminalCloseGuardService,
|
||||
TerminalNodeExternalState
|
||||
} from "../contracts/index.ts";
|
||||
import { isTerminalSessionEndedStatus } from "../core/sessionProjection.ts";
|
||||
|
||||
export interface ResolveTerminalWindowCloseEffectInput {
|
||||
closeGuard: TerminalCloseGuardService;
|
||||
description: string;
|
||||
externalNodeState: TerminalNodeExternalState | null;
|
||||
nodeId: string;
|
||||
sessionId?: string | null;
|
||||
title: string;
|
||||
typeId: string;
|
||||
}
|
||||
|
||||
export async function resolveTerminalWindowCloseEffect({
|
||||
closeGuard,
|
||||
description,
|
||||
externalNodeState,
|
||||
nodeId,
|
||||
sessionId,
|
||||
title,
|
||||
typeId
|
||||
}: ResolveTerminalWindowCloseEffectInput) {
|
||||
const status = externalNodeState?.status ?? "created";
|
||||
if (status === "created" || isTerminalSessionEndedStatus(status)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedSessionId = sessionId ?? externalNodeState?.sessionId ?? null;
|
||||
if (resolvedSessionId) {
|
||||
try {
|
||||
const guard = await closeGuard.check({ sessionId: resolvedSessionId });
|
||||
if (
|
||||
!guard.requiresConfirmation ||
|
||||
guard.reason === "not-running" ||
|
||||
isTerminalSessionEndedStatus(guard.status)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to a conservative close effect when guard lookup fails.
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
description,
|
||||
nodeId,
|
||||
title: externalNodeState?.title?.trim() || title,
|
||||
typeId
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../../packages/configs/tsconfig/base.json",
|
||||
"compilerOptions": {
|
||||
"allowImportingTsExtensions": true,
|
||||
"jsx": "react-jsx",
|
||||
"types": ["node", "react", "react-dom"]
|
||||
},
|
||||
"include": ["src/**/*", "tsup.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: {
|
||||
index: "src/index.ts",
|
||||
"contracts/index": "src/contracts/index.ts",
|
||||
"i18n/index": "src/i18n/index.ts",
|
||||
"react/index": "src/react/index.ts",
|
||||
"workbench/index": "src/workbench/index.ts"
|
||||
},
|
||||
external: ["react", "react-dom"],
|
||||
format: ["esm"],
|
||||
sourcemap: true
|
||||
});
|
||||
Reference in new issue
Block a user