diff --git a/bun.lock b/bun.lock index 2986619a88b7..6394521efa86 100644 --- a/bun.lock +++ b/bun.lock @@ -383,9 +383,6 @@ "@betteroffice/fonts": "0.4.0", "@betteroffice/pptx": "0.2.0", "@betteroffice/xlsx": "0.3.0", - "@dnd-kit/abstract": "0.5.0", - "@dnd-kit/dom": "0.5.0", - "@dnd-kit/solid": "0.5.0", "@effect/platform-node": "catalog:", "@kobalte/core": "catalog:", "@opencode/client": "workspace:*", @@ -411,6 +408,7 @@ "devDependencies": { "@happy-dom/global-registrator": "20.0.11", "@lydell/node-pty": "catalog:", + "@opencode/protocol": "workspace:*", "@tsconfig/node22": "catalog:", "@types/bun": "catalog:", "@types/node": "catalog:", diff --git a/packages/app/component-tests/terminal-focus.spec.ts b/packages/app/component-tests/terminal-focus.spec.ts deleted file mode 100644 index e2962676095c..000000000000 --- a/packages/app/component-tests/terminal-focus.spec.ts +++ /dev/null @@ -1,56 +0,0 @@ -import type { Page } from "@playwright/test" -import { expect, sourceURL, story } from "../../stories/playwright/story" - -const fixture = sourceURL(new URL("../../gui-plugins/src/terminal/terminal.fixture.tsx", import.meta.url)) - -const mountTerminal = async (page: Page, autoFocus: boolean) => { - await page.evaluate( - async (input) => { - const { mountTerminalFocus } = await import(input.fixture) - mountTerminalFocus({ autoFocus: input.autoFocus }) - }, - { fixture, autoFocus }, - ) - const root = page.getByTestId("terminal-focus-fixture") - await expect(root.locator('[data-component="terminal"] textarea')).toBeAttached() - // The terminal's deferred focus and restore run on timers queued when it opened; let them run first. - await page.evaluate( - () => new Promise((resolve) => setTimeout(() => setTimeout(() => requestAnimationFrame(() => resolve()), 0), 0)), - ) - - return root -} - -story.beforeEach(async ({ mount }) => { - // Any story loads the app styles; the fixture mounts the real terminal beside it. - await mount("ui-line-comment--editor") -}) - -story("a terminal opened with a focus request keeps focus after the request is consumed", async ({ page }) => { - const root = await mountTerminal(page, true) - - await expect(root.locator('[data-component="terminal"] textarea')).toBeFocused() -}) - -story("a terminal opened without a focus request leaves focus in the composer", async ({ page }) => { - const root = await mountTerminal(page, false) - - await expect(root.getByRole("textbox", { name: "Composer", exact: true })).toBeFocused() -}) - -story("disposing a terminal invalidates its retained quote anchor", async ({ page }) => { - await page.evaluate(async (fixture) => { - const { mountTerminalQuote } = await import(fixture) - await mountTerminalQuote() - }, fixture) - const root = page.getByTestId("terminal-quote-fixture") - await root.getByRole("button", { name: "Select output", exact: true }).click() - await page.getByRole("toolbar", { name: "quote.actions", exact: true }).getByRole("button").click() - await expect(root.getByLabel("Quoted output", { exact: true })).toHaveText("Retained terminal output") - await expect(root.getByLabel("Quote placement", { exact: true })).toHaveText("Source") - await root.getByRole("button", { name: "Dispose source", exact: true }).click() - - await expect(root.getByTestId("terminal-quote-source")).toHaveCount(0) - await expect(root.getByLabel("Quote placement", { exact: true })).toHaveText("Tile") - await expect(root.getByLabel("Quoted output", { exact: true })).toHaveText("Retained terminal output") -}) diff --git a/packages/app/component-tests/terminal.spec.ts b/packages/app/component-tests/terminal.spec.ts new file mode 100644 index 000000000000..d97e93bdf809 --- /dev/null +++ b/packages/app/component-tests/terminal.spec.ts @@ -0,0 +1,138 @@ +import type { Locator, Page, WebSocketRoute } from "@playwright/test" +import { expect, sourceURL, story } from "../../stories/playwright/story" + +const fixture = sourceURL(new URL("../../gui-plugins/src/terminal/terminal.fixture.tsx", import.meta.url)) + +// No page loads anything from this origin; the routes below answer its terminal API and socket. +const SERVER = "http://127.0.0.1:4599" + +const SIZE = { cols: 80, rows: 24 } + +type Frame = { type: number; data: string } + +/** + * A server with one terminal that already wrote `output`: it answers the snapshot and connect ticket, then speaks the + * persistent PTY socket protocol at `inputProtocol`. A missing `output` is a terminal the server no longer has. + */ +async function serveTerminal(page: Page, input: { ptyID: string; output?: string; inputProtocol?: 0 | 1 }) { + const frames: Frame[] = [] + const sockets: WebSocketRoute[] = [] + const tail = Buffer.byteLength(input.output ?? "") + + const info = { + id: input.ptyID, + title: "Terminal 1", + userTitle: null, + command: "bash", + args: [], + cwd: "C:/OpenCode/Terminal", + status: "running", + pid: 1, + sessionID: "ses_terminal", + foregroundProcess: null, + size: SIZE, + output: { head: 0, tail }, + } + + await page.route(`${SERVER}/api/experimental/persistent-pty/**`, (route) => { + const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "*" } + + if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers }) + + if (input.output === undefined) { + return route.fulfill({ + status: 404, + headers, + // SAFETY: the server's wire body for a terminal it does not have. + // oxlint-disable-next-line anti-slop-effect/no-manual-tagged-construction -- see SAFETY above + json: { _tag: "PtyNotFoundError", ptyID: input.ptyID, message: `PTY session not found: ${input.ptyID}` }, + }) + } + + if (route.request().url().endsWith("/snapshot")) { + const checkpoint = Buffer.from(input.output).toString("base64") + + return route.fulfill({ + headers, + json: { data: { info, text: input.output, checkpoint, cursor: { x: 0, y: 0 } } }, + }) + } + + return route.fulfill({ headers, json: { data: { ticket: "component-ticket", expires_in: 60 } } }) + }) + + // The socket mock patches the page's WebSocket when it loads, so this runs before the story mounts. + await page.routeWebSocket(new RegExp(`/api/experimental/persistent-pty/${input.ptyID}/connect`), (ws) => { + const url = new URL(ws.url()) + const attachmentID = url.searchParams.get("attachment_id") ?? "" + sockets.push(ws) + ws.onMessage((message) => { + const data = Buffer.from(message) + + frames.push({ type: data[0] ?? -1, data: data.subarray(5).toString() }) + }) + ws.send( + JSON.stringify({ + type: "attached", + attachmentID, + inputProtocol: input.inputProtocol ?? 1, + info, + role: "controller", + generation: 1, + replay: { requestedOffset: tail, availableOffset: 0, endOffset: tail, truncated: false }, + }), + ) + ws.send(JSON.stringify({ type: "replay_complete", endOffset: tail })) + }) + + return { frames, sockets } +} + +async function mountTerminal(page: Page, mount: (id: string) => Promise, ptyID: string) { + // Any story loads the app styles; the fixture mounts the pane beside it. + await mount("ui-line-comment--editor") + await page.evaluate( + async (input) => { + const { mountTerminal } = await import(input.fixture) + mountTerminal({ url: input.server, ptyID: input.ptyID }) + }, + { fixture, server: SERVER, ptyID }, + ) + + return page.getByTestId("terminal-fixture") +} + +story("does not send the emulator's own answers to terminal queries as input", async ({ page, mount }) => { + // Device status and attribute queries, in the restored screen and in live output. The daemon answers them. + const server = await serveTerminal(page, { ptyID: "pty_queries", output: "restored\x1b[6n\x1b[c\r\n" }) + const root = await mountTerminal(page, mount, "pty_queries") + + await expect.poll(() => server.sockets.length).toBe(1) + await expect.poll(() => server.frames.some((frame) => frame.type === 0)).toBe(true) + server.sockets[0]!.send(Buffer.from("live\x1b[6n\x1b[5n\x1b[c\r\n")) + + // Typed input lands after the output was written, so any answer would already have been sent. + await expect(root.locator("textarea")).toBeFocused() + await page.keyboard.type("x") + await expect.poll(() => server.frames.filter((frame) => frame.type === 1).length).toBeGreaterThan(0) + expect(server.frames.filter((frame) => frame.type === 1).map((frame) => frame.data)).toEqual(["x"]) +}) + +story("tells the user a server that predates the input protocol is too old", async ({ page, mount }) => { + await serveTerminal(page, { ptyID: "pty_old", output: "old server\r\n", inputProtocol: 0 }) + const root = await mountTerminal(page, mount, "pty_old") + + await expect( + root.getByText("This server is too old for terminals; update OpenCode on it", { exact: true }), + ).toBeVisible() + await expect(root.locator("[data-failures]")).toHaveAttribute("data-failures", "1") +}) + +story("says the connection failed when the terminal cannot be restored", async ({ page, mount }) => { + const server = await serveTerminal(page, { ptyID: "pty_missing" }) + const root = await mountTerminal(page, mount, "pty_missing") + + await expect(root.getByText("Terminal connection failed", { exact: true })).toBeVisible() + await expect(root.locator("[data-failures]")).toHaveAttribute("data-failures", "1") + expect(server.sockets).toEqual([]) +}) diff --git a/packages/app/e2e/performance/terminals/README.md b/packages/app/e2e/performance/terminals/README.md deleted file mode 100644 index 4b9fd6a05f9d..000000000000 --- a/packages/app/e2e/performance/terminals/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Native Terminal Benchmark - -Manual Windows benchmark. Run only in an isolated development worktree. It does -not connect to an OpenCode service, user profile, or database. - -Build from `packages/app` with -`bun x vite build --config e2e/performance/terminals/vite.config.ts`, then freeze -`dist` outside the repository. Set `PLAYWRIGHT_BUILD=1`, `PLAYWRIGHT_BASE_URL` to -an unused loopback URL, `TERMINAL_BUILD` to the frozen build, -`TERMINAL_ARTIFACTS` to an existing external directory, and `TERMINAL_RESULTS` -to an external result directory. Run: - -```sh -bun x playwright test --config e2e/performance/terminals/playwright.config.ts --repeat-each=20 -``` - -The runner owns its preview server and each test owns a PowerShell ConPTY process. -Session metadata is deterministic. Native output is forwarded through Playwright's -WebSocket fixture into the real production `Terminal`, writer, Ghostty WASM/canvas, -and serializer. No output is dropped, paused, or delayed. This is native terminal -plus production renderer evidence, not the production PTY backend or Electron IPC. - -The workload is 12,000 colored build/test log lines with file paths, durations, and -result descriptions. Cases separate visible output, the same output while hidden, -and closing the session tab after filling the configured scrollback. Ghostty -converts the app's 10,000-line setting to bytes at its initial 80-column width; -resizing reduces the effective row capacity. The report records actual retained -rows and the first retained fixture record rather than assuming 10,000 rows. Completion -requires the final marker in Ghostty and completion of its write callbacks, not -just WebSocket delivery. Teardown requires Home readiness and the final serialized -snapshot. Input, focus, resizing, and native process survival are checked. - -`probe.ts` is included only by this benchmark build. It observes actual writes, -renderer calls, and serialization. Chrome `TaskDuration` measures renderer task -time, not total process CPU or RAM. For attribution, set -`OPENCODE_PERFORMANCE_TRACE_DIR`; keep traced runs separate from clean timing. -`TERMINAL_DRAW_PROBE=1` separately counts actual canvas draws to verify hidden -rendering; do not mix these instrumented samples with clean timing. -Use `TERMINAL_REVISION` and `TERMINAL_BUNDLE` to identify frozen artifacts. -`TERMINAL_SCREENSHOTS` captures the visible result after timing. - -The benchmark has no machine-dependent performance thresholds. Keep raw logs, -snapshots, traces, and screenshots outside Git. Run heavy work through the -coordinator's exclusive gate when participating in a shared performance wave. diff --git a/packages/app/e2e/performance/terminals/playwright.config.ts b/packages/app/e2e/performance/terminals/playwright.config.ts deleted file mode 100644 index 46de831b0a72..000000000000 --- a/packages/app/e2e/performance/terminals/playwright.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { defineConfig } from "@playwright/test" -import config from "../../../playwright.config" - -export default defineConfig({ - ...config, - testDir: ".", - testIgnore: [], - testMatch: "terminal-benchmark.spec.ts", - workers: 1, - retries: 0, - timeout: 120_000, - outputDir: process.env.TERMINAL_RESULTS, - reporter: [["line"]], - webServer: { - command: `bun x vite preview --host 127.0.0.1 --port ${new URL(process.env.PLAYWRIGHT_BASE_URL!).port} --strictPort --outDir ${process.env.TERMINAL_BUILD}`, - url: process.env.PLAYWRIGHT_BASE_URL, - reuseExistingServer: false, - }, - use: { ...config.use, viewport: { width: 1440, height: 900 }, trace: "off", video: "off", serviceWorkers: "block" }, -}) diff --git a/packages/app/e2e/performance/terminals/probe.ts b/packages/app/e2e/performance/terminals/probe.ts deleted file mode 100644 index 5547a40d3565..000000000000 --- a/packages/app/e2e/performance/terminals/probe.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { Terminal } from "ghostty-web" -import { SerializeAddon } from "../../../../gui-plugins/src/terminal/serialize" - -export type TerminalProbe = { - term?: Terminal - writes: number - pending: number - bytes: number - renders: number - hiddenRenders: number - draws: number - hiddenDraws: number - serialized: { ms: number; bytes: number; value: string }[] -} - -declare global { - interface Window { - terminalProbe: TerminalProbe - } -} - -const probe: TerminalProbe = { - writes: 0, - pending: 0, - bytes: 0, - renders: 0, - hiddenRenders: 0, - draws: 0, - hiddenDraws: 0, - serialized: [], -} - -window.terminalProbe = probe - -const open = Terminal.prototype.open - -Terminal.prototype.open = function (element) { - probe.term = this - open.call(this, element) - // Ghostty does not expose render events. This benchmark-only wrapper observes its - // actual renderer; it does not alter scheduling, parsing, or drawing. - // SAFETY: ghostty-web keeps its renderer on this undeclared field; the probe only wraps its render method. - const renderer = (this as Terminal & { renderer: { render: (...args: unknown[]) => void } }).renderer - const render = renderer.render - let hidden = false - renderer.render = function (...args) { - probe.renders++ - hidden = !element.checkVisibility() - - if (hidden) probe.hiddenRenders++ - - return render.apply(this, args) - } - - if (new URL(location.href).searchParams.has("terminalDrawProbe")) { - const context = element.querySelector("canvas")!.getContext("2d")! - const draw = context.drawImage - context.drawImage = function (...args: unknown[]) { - probe.draws++ - - if (hidden) probe.hiddenDraws++ - draw.apply(this, args) - } - } -} - -const write = Terminal.prototype.write - -Terminal.prototype.write = function (data, done) { - probe.writes++ - probe.pending++ - probe.bytes += data instanceof Uint8Array ? data.byteLength : new TextEncoder().encode(data).byteLength - - return write.call(this, data, () => { - probe.pending-- - done?.() - }) -} - -const serialize = SerializeAddon.prototype.serialize - -SerializeAddon.prototype.serialize = function (options) { - const start = performance.now() - const value = serialize.call(this, options) - probe.serialized.push({ ms: performance.now() - start, bytes: new TextEncoder().encode(value).byteLength, value }) - - return value -} diff --git a/packages/app/e2e/performance/terminals/shell.ps1 b/packages/app/e2e/performance/terminals/shell.ps1 deleted file mode 100644 index b8457d0c654c..000000000000 --- a/packages/app/e2e/performance/terminals/shell.ps1 +++ /dev/null @@ -1,13 +0,0 @@ -param([Parameter(Mandatory = $true)][string]$Fixture) -$ErrorActionPreference = 'Stop' -[Console]::WriteLine('TERMINAL_FIXTURE_READY') -while ($null -ne ($command = [Console]::ReadLine())) { - if ($command -eq 'exit') { exit 0 } - if ($command -eq 'run') { - foreach ($line in [System.IO.File]::ReadLines($Fixture)) { - [Console]::WriteLine($line) - } - [Console]::WriteLine('TERMINAL_WORKLOAD_DONE') - } - if ($command -eq 'ping') { [Console]::WriteLine('TERMINAL_PROCESS_ALIVE') } -} diff --git a/packages/app/e2e/performance/terminals/terminal-benchmark.spec.ts b/packages/app/e2e/performance/terminals/terminal-benchmark.spec.ts deleted file mode 100644 index 6c148b26e5fe..000000000000 --- a/packages/app/e2e/performance/terminals/terminal-benchmark.spec.ts +++ /dev/null @@ -1,388 +0,0 @@ -import { createRequire } from "node:module" -import { mkdtemp, writeFile, rm } from "node:fs/promises" -import { tmpdir } from "node:os" -import path from "node:path" -import { fileURLToPath } from "node:url" -import type { Page } from "@playwright/test" -import { benchmark, benchmarkDiagnostics, expect } from "../benchmark" -import { mockOpenCodeServer } from "../../utils/mock-server" -import { expectSessionTitle } from "../../utils/waits" -import type {} from "./probe" - -// Use the same installed native PTY package as Core, with a fixture-owned process. -const native = createRequire(new URL("../../../../core/package.json", import.meta.url))("@lydell/node-pty") as { - spawn: ( - file: string, - args: string[], - options: { cols: number; rows: number; cwd: string }, - ) => { - pid: number - write: (data: string) => void - resize: (cols: number, rows: number) => void - kill: () => void - onData: (handler: (data: string) => void) => { dispose: () => void } - onExit: (handler: () => void) => { dispose: () => void } - } -} - -const sessionID = "ses_terminal_benchmark" - -const ptyID = "pty_terminal_benchmark" - -const title = "Terminal build output" - -const server = process.env.PLAYWRIGHT_BASE_URL! - -const href = `/server/${Buffer.from(server).toString("base64url")}/session/${sessionID}` - -const lines = Array.from({ length: 12_000 }, (_, i) => { - const unit = ["session/history", "session/runner", "project/discovery", "tool/shell", "provider/stream"][i % 5] - - return `\x1b[32mPASS\x1b[0m packages/core/test/${unit}-${String(i).padStart(5, "0")}.test.ts \x1b[2m[${10 + (i % 237)}ms]\x1b[0m validates ordered output and durable recovery` -}).join("\r\n") - -benchmark.use({ traceScope: "interaction", viewport: { width: 1440, height: 900 } }) - -for (const scenario of ["visible-output", "hidden-output", "full-scrollback-teardown"] as const) { - benchmark(scenario, async ({ page, report }, info) => { - const dir = await mkdtemp(path.join(process.env.TERMINAL_ARTIFACTS ?? tmpdir(), "terminal-fixture-")) - await writeFile(path.join(dir, "build.log"), lines) - - const pty = native.spawn( - "pwsh.exe", - [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-File", - fileURLToPath(new URL("./shell.ps1", import.meta.url)), - "-Fixture", - path.join(dir, "build.log"), - ], - { cols: 120, rows: 24, cwd: dir }, - ) - - const exited = new Promise((resolve) => pty.onExit(resolve)) - let output = "" - let connected = 0 - let closed = 0 - let send: ((data: string) => void) | undefined - - const listener = pty.onData((data) => { - output += data - send?.(data) - }) - - const sizes: { cols: number; rows: number }[] = [] - const removals: string[] = [] - - try { - if (process.env.TERMINAL_DRAW_PROBE) { - await page.addInitScript(() => { - const fill = CanvasRenderingContext2D.prototype.fillText - CanvasRenderingContext2D.prototype.fillText = function (...args: Parameters) { - if (this.canvas instanceof HTMLCanvasElement && this.canvas.closest('[data-component="terminal"]')) { - window.terminalProbe.draws++ - - if (!this.canvas.checkVisibility()) window.terminalProbe.hiddenDraws++ - } - - fill.apply(this, args) - } - }) - } - - const location = { directory: dir, project: { id: "proj_terminal_benchmark", directory: dir } } - - const data = { - id: ptyID, - title: "Terminal 1", - command: "pwsh.exe", - args: [], - cwd: dir, - status: "running", - pid: pty.pid, - } - - await mockOpenCodeServer(page, { - directory: dir, - project: { - id: location.project.id, - worktree: dir, - vcs: "git", - name: "terminal-benchmark", - time: { created: 1, updated: 1 }, - sandboxes: [], - }, - provider: { - all: [ - { - id: "opencode", - name: "OpenCode", - models: { test: { id: "test", name: "Test", limit: { context: 200_000 } } }, - }, - ], - connected: ["opencode"], - default: { providerID: "opencode", modelID: "test" }, - }, - sessions: [ - { - id: sessionID, - slug: sessionID, - projectID: location.project.id, - directory: dir, - title, - version: "dev", - time: { created: 1700000000000, updated: 1700000000000 }, - }, - ], - pageMessages: () => ({ items: [] }), - }) - await page.route("**/api/pty**", async (route) => { - if (route.request().method() === "DELETE") removals.push(route.request().url()) - const body = route.request().postDataJSON() - - if (body?.size) { - sizes.push(body.size) - pty.resize(body.size.cols, body.size.rows) - } - - return route.fulfill({ - status: 200, - contentType: "application/json", - body: JSON.stringify({ - location, - data: route.request().url().includes("connect-token") ? { ticket: "fixture", expires_in: 60 } : data, - }), - }) - }) - await page.routeWebSocket(new RegExp(`/api/pty/${ptyID}/connect`), (socket) => { - connected++ - send = (data) => socket.send(data) - socket.send(output.slice(Number(new URL(socket.url()).searchParams.get("cursor") ?? 0))) - socket.onMessage((data) => pty.write(String(data))) - socket.onClose(() => { - closed++ - send = undefined - }) - }) - await page.addInitScript( - ({ server, sessionID }) => { - localStorage.setItem("settings.v3", JSON.stringify({ general: { terminalPlacement: "bottom" } })) - localStorage.setItem( - "opencode.window.browser.dat:tabs", - JSON.stringify([{ type: "session", server, sessionId: sessionID }]), - ) - }, - { server, sessionID }, - ) - await page.goto( - `${href}${process.env.TERMINAL_DRAW_PROBE && scenario !== "full-scrollback-teardown" ? "?terminalDrawProbe" : ""}`, - ) - await expectSessionTitle(page, title) - await page.keyboard.press("Control+Backquote") - await waitForText(page, "TERMINAL_FIXTURE_READY") - const terminal = page.locator('[data-component="terminal"]') - await expect(terminal).toBeVisible() - await page.evaluate(() => document.fonts.ready.then(() => undefined)) - await expect - .poll(async () => { - const size = await page.evaluate(() => ({ - cols: window.terminalProbe.term!.cols, - rows: window.terminalProbe.term!.rows, - })) - - return sizes.at(-1)?.cols === size.cols && sizes.at(-1)?.rows === size.rows - }) - .toBe(true) - - if (scenario === "hidden-output") { - await page.keyboard.press("Control+Backquote") - await expect(terminal).toBeHidden() - } - - const cdp = await page.context().newCDPSession(page) - await cdp.send("Performance.enable") - const before = await cdp.send("Performance.getMetrics") - - const start = await page.evaluate(() => { - window.terminalProbe.renders = 0 - window.terminalProbe.hiddenRenders = 0 - window.terminalProbe.draws = 0 - window.terminalProbe.hiddenDraws = 0 - - return performance.now() - }) - - await benchmarkDiagnostics(page).startTrace() - // The producer is not throttled. The visible and hidden cases receive the same bytes. - pty.write("run\r") - await waitForText(page, "TERMINAL_WORKLOAD_DONE") - - const produced = await page.evaluate( - (start) => ({ - ms: performance.now() - start, - renders: window.terminalProbe.renders, - hiddenRenders: window.terminalProbe.hiddenRenders, - draws: window.terminalProbe.draws, - hiddenDraws: window.terminalProbe.hiddenDraws, - bytes: window.terminalProbe.bytes, - scrollback: window.terminalProbe.term!.getScrollbackLength(), - cols: window.terminalProbe.term!.cols, - rows: window.terminalProbe.term!.rows, - firstRecord: Number( - window.terminalProbe - .term!.buffer.normal.getLine(0) - ?.translateToString(true) - .match(/-(\d{5})\.test\.ts/)?.[1], - ), - }), - start, - ) - - const after = await cdp.send("Performance.getMetrics") - - const cpuMs = - (after.metrics.find((x) => x.name === "TaskDuration")!.value - - before.metrics.find((x) => x.name === "TaskDuration")!.value) * - 1000 - - let interaction: Record = {} - - if (scenario === "hidden-output") { - const start = await page.evaluate(() => performance.now()) - await page.keyboard.press("Control+Backquote") - await expect(terminal).toBeVisible() - await waitForText(page, "TERMINAL_WORKLOAD_DONE") - interaction = { returnMs: await page.evaluate((start) => performance.now() - start, start) } - } - - if (scenario === "full-scrollback-teardown") { - // Ghostty converts the configured line limit to bytes at the initial - // 80-column size. Resizing changes the effective retained row count. - expect(produced.scrollback).toBeGreaterThan(0) - expect(produced.firstRecord).toBeGreaterThan(0) - expect(produced.firstRecord).toBeLessThan(11_999) - const close = page.locator(`[data-titlebar-tab-slot]:has(a[href="${href}"]) [data-component="icon-button-v2"]`) - await expect(close).toBeVisible() - const cpuBefore = await cdp.send("Performance.getMetrics") - const start = await page.evaluate(() => performance.now()) - await close.click() - await expect(page).toHaveURL("/") - await expect(page.locator('[data-component="home-session-search"]')).toBeVisible() - await expect(page.locator('[data-component="home-session-search"] input')).toBeEditable() - await expect.poll(() => page.evaluate(() => window.terminalProbe.serialized.length)).toBe(1) - interaction = await page.evaluate( - (start) => ({ - homeReadyMs: performance.now() - start, - serializeMs: window.terminalProbe.serialized[0].ms, - serializedBytes: window.terminalProbe.serialized[0].bytes, - }), - start, - ) - const cpuAfter = await cdp.send("Performance.getMetrics") - interaction.teardownCpuMs = - (cpuAfter.metrics.find((x) => x.name === "TaskDuration")!.value - - cpuBefore.metrics.find((x) => x.name === "TaskDuration")!.value) * - 1000 - const snapshot = await page.evaluate(() => window.terminalProbe.serialized[0].value) - expect(Array.from(snapshot.matchAll(/-(\d{5})\.test\.ts/g), (match) => Number(match[1]))).toEqual( - Array.from({ length: 12_000 - produced.firstRecord }, (_, index) => produced.firstRecord + index), - ) - expect(snapshot).toContain("TERMINAL_WORKLOAD_DONE") - await writeFile( - path.join( - process.env.TERMINAL_ARTIFACTS ?? tmpdir(), - `${process.env.TERMINAL_BUNDLE}-${info.repeatEachIndex}.ansi`, - ), - snapshot, - ) - await expect(terminal).toHaveCount(0) - expect(closed).toBe(1) - // UI teardown must not terminate the native process. - pty.write("ping\r") - await expect.poll(() => output.includes("TERMINAL_PROCESS_ALIVE")).toBe(true) - } - - await benchmarkDiagnostics(page).stop() - expect(connected).toBe(1) - expect(removals).toEqual([]) - expect(sizes.length).toBeGreaterThan(0) - report( - { ...produced, cpuMs, ...interaction }, - { - revision: process.env.TERMINAL_REVISION, - bundle: process.env.TERMINAL_BUNDLE, - fixtureBytes: Buffer.byteLength(lines), - fixtureLines: 12_000, - transport: "Windows ConPTY -> Playwright WebSocket fixture -> production Terminal/writer/Ghostty", - scope: "Chromium renderer; not Electron total RAM or production backend IPC", - }, - ) - - if (scenario !== "full-scrollback-teardown") { - // Validate input, focus, and resize after both visible and hidden output. - await terminal.click() - await expect(terminal.locator("textarea")).toBeFocused() - await page.keyboard.type("ping") - await page.keyboard.press("Enter") - await waitForText(page, "TERMINAL_PROCESS_ALIVE") - const columns = await page.evaluate(() => window.terminalProbe.term!.cols) - await page.setViewportSize({ width: 1100, height: 800 }) - await expect.poll(() => page.evaluate(() => window.terminalProbe.term!.cols)).not.toBe(columns) - await expect - .poll(async () => sizes.at(-1)?.cols === (await page.evaluate(() => window.terminalProbe.term!.cols))) - .toBe(true) - expect(closed).toBe(0) - } - - if (process.env.TERMINAL_SCREENSHOTS && scenario !== "full-scrollback-teardown") { - await page.screenshot({ - path: path.join(process.env.TERMINAL_SCREENSHOTS, `${scenario}-${info.repeatEachIndex}.png`), - }) - } - } finally { - listener.dispose() - - try { - await benchmarkDiagnostics(page).stop() - // Stop fixture request handlers before killing their native resource. The - // app debounces PTY resize requests independently of the canvas resize. - await page.unrouteAll({ behavior: "wait" }) - await page.close() - } finally { - pty.kill() - await exited - await writeFile( - path.join( - process.env.TERMINAL_ARTIFACTS ?? tmpdir(), - `${process.env.TERMINAL_BUNDLE}-${scenario}-${info.repeatEachIndex}.native.log`, - ), - output, - ) - await rm(dir, { recursive: true, force: true }) - } - } - }) -} - -async function waitForText(page: Page, text: string) { - await expect - .poll(() => - page.evaluate((text) => { - const probe = window.terminalProbe - const term = probe?.term - - if (!term || probe.pending !== 0) return false - const buffer = term.buffer.active - - return Array.from( - { length: term.rows }, - (_, i) => buffer.getLine(buffer.length - term.rows + i)?.translateToString(true) ?? "", - ) - .join("\n") - .includes(text) - }, text), - ) - .toBe(true) -} diff --git a/packages/app/e2e/performance/terminals/vite.config.ts b/packages/app/e2e/performance/terminals/vite.config.ts deleted file mode 100644 index 02f17d0ce544..000000000000 --- a/packages/app/e2e/performance/terminals/vite.config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { mergeConfig } from "vite" -import config from "../../../vite.config" - -// The probe is included only in this manual benchmark build, never in the app build. -export default mergeConfig(config, { - plugins: [ - { - name: "terminal-benchmark-probe", - transformIndexHtml: { - order: "pre", - handler: () => [ - { tag: "script", attrs: { type: "module", src: "/e2e/performance/terminals/probe.ts" }, injectTo: "head" }, - ], - }, - }, - ], -}) diff --git a/packages/app/e2e/regression/mobile-session.spec.ts b/packages/app/e2e/regression/mobile-session.spec.ts index f5209a13b5cc..ec2b9156067a 100644 --- a/packages/app/e2e/regression/mobile-session.spec.ts +++ b/packages/app/e2e/regression/mobile-session.spec.ts @@ -16,11 +16,11 @@ async function openStress(page: Page, extra: SeedInput = {}) { } for (const position of ["top", "bottom"] as const) { - test(`mobile session tabs switch views and keep the terminal cached with ${position} navigation`, async ({ + test(`mobile session tabs switch views and work with ${position} navigation`, async ({ page, }) => { await page.setViewportSize({ width: 390, height: 844 }) - await mockStressTimeline(page, { fileList: () => [], pty: {} }) + await mockStressTimeline(page, { fileList: () => [] }) await openStress(page, { settings: { general: { mobileTitlebarPosition: position } }, }) @@ -157,29 +157,10 @@ for (const position of ["top", "bottom"] as const) { await more.click() await expect(views.getByRole("button", { name: "Files", exact: true })).toHaveAttribute("aria-pressed", "true") - await views.getByRole("button", { name: "Terminal", exact: true }).click() + await page.keyboard.press("Escape") await expect(views).toBeHidden() - const panel = page.locator("#terminal-panel") - await expect(panel.getByRole("tab", { name: /Terminal 1/ })).toBeVisible() - await expect(panel.locator('[data-component="terminal"]')).toBeVisible() - await expect(panel.locator("textarea")).toBeEditable() - await expect(panel).toHaveCount(1) - await panel.evaluate((element) => element.setAttribute("data-cache-probe", "original")) - await expect(composer).toBeHidden() - await tabs.getByRole("tab", { name: "Session", exact: true }).click() await expect(message).toBeVisible() - await expect(panel).toBeHidden() - await expect(panel).toHaveAttribute("data-cache-probe", "original") - - await page.keyboard.press("Control+Backquote") - await expect(picker).toHaveText("More...") - await expect(panel).toBeVisible() - await expect(panel).toHaveAttribute("data-cache-probe", "original") - await expect(panel.getByRole("tab", { name: /^Terminal/ })).toHaveCount(1) - - await tabs.getByRole("tab", { name: "Session", exact: true }).click() - await expect(panel).toBeHidden() // The view resets to Session whenever the routed session changes, including through Home. const trigger = page.locator('[data-slot="mobile-tabs-trigger"]') @@ -287,7 +268,7 @@ test("a narrow-screen palette pick keeps the view, and the side region shows the fileList: (path) => (path ? [] : [fileNode(fixture.directory, "README.md")]), fileContent: (path) => ({ type: "text", content: `contents:${path}` }), findFiles: ({ query }) => ("README.md".includes(query) ? [fileNode(fixture.directory, "README.md")] : []), - pty: {}, + persistentPty: {}, }) await openStress(page) await page.goto(sessionHref(fixture.targetID)) diff --git a/packages/app/e2e/regression/session-header.spec.ts b/packages/app/e2e/regression/session-header.spec.ts index f79134d14316..09e55d4859c5 100644 --- a/packages/app/e2e/regression/session-header.spec.ts +++ b/packages/app/e2e/regression/session-header.spec.ts @@ -407,10 +407,10 @@ test.describe("location", () => { await context.grantPermissions(["clipboard-read", "clipboard-write"]) await page.setViewportSize({ width: 1440, height: 900 }) - const { pty } = await openSession(page, { + const { persistentPty } = await openSession(page, { ...workspace, vcs: (directory) => ({ current: directory === worktree ? "feature/branch-menu" : "main", default: "main" }), - pty: {}, + persistentPty: {}, }) await expect(page.getByRole("button", { name: "More options", exact: true })).toBeVisible() @@ -430,9 +430,9 @@ test.describe("location", () => { await branch.click() await actions.getByRole("menuitem", { name: "Open in terminal", exact: true }).click() await expect(card).toBeHidden() - await expect.poll(() => pty.created.map((item) => item.cwd)).toEqual([worktree]) - await expect.poll(() => pty.sockets.length).toBe(1) - pty.send("$ pwd\r\n" + worktree + "\r\n") + await expect.poll(() => persistentPty.created.map((item) => item.cwd)).toEqual([worktree]) + await expect.poll(() => persistentPty.sockets.length).toBe(1) + persistentPty.output(persistentPty.created[0]!.id, "$ pwd\r\n" + worktree + "\r\n") const terminal = page.locator('[data-component="terminal"]') await expect(terminal).toHaveCSS("opacity", "1") await expect(terminal.locator("textarea")).toBeFocused() diff --git a/packages/app/e2e/regression/settings-wsl.spec.ts b/packages/app/e2e/regression/settings-wsl.spec.ts index e2ad34195c44..4106b438c232 100644 --- a/packages/app/e2e/regression/settings-wsl.spec.ts +++ b/packages/app/e2e/regression/settings-wsl.spec.ts @@ -95,48 +95,6 @@ test("adding an SSH server while the SSH plugin is down fails instead of connect await expect(dialog.getByRole("button", { name: "Add server", exact: true })).toBeEnabled() }) -test("an open session's terminal follows its WSL server to the endpoint it restarts on", async ({ page }) => { - const restarted = "http://127.0.0.1:4098" - const directory = "/home/ubuntu/project" - const wsl = session({ id: "ses_wsl", directory, title: "WSL session" }) - - const config = { - directory, - project: project({ id: "proj_wsl", directory }), - provider: NO_PROVIDER, - sessions: [wsl], - pageMessages: () => ({ items: [] }), - } - - const servers = await mockServers(page, { - [SERVER]: { ...config, sessions: [] }, - [REMOTE_SERVER]: { ...config, pty: { prefix: "pty_before" } }, - [restarted]: { ...config, pty: { prefix: "pty_after" } }, - }) - - const path = `/server/${base64Encode("wsl:Ubuntu")}/session/${wsl.id}` - await page.goto( - `/e2e/utils/settings-wsl.html?${new URLSearchParams({ server: SERVER, mode: "ready", wsl: REMOTE_SERVER, restart: restarted, path })}`, - ) - await expectSessionTitle(page, wsl.title) - await page.keyboard.press("Control+Backquote") - await expect.poll(() => servers[REMOTE_SERVER]!.pty.sockets.map((socket) => socket.id)).toEqual(["pty_before1"]) - - await page.keyboard.press("Control+,") - const settings = page.getByTestId("settings-screen") - await settings.getByRole("tab", { name: "Servers", exact: true }).click() - const connection = settings.getByRole("region", { name: "Ubuntu", exact: true }) - await connection.getByRole("button", { name: "Update OpenCode", exact: true }).click() - await expect(connection.getByRole("button", { name: "Update OpenCode", exact: true })).toHaveCount(0) - await settings.getByRole("button", { name: "Back to app" }).click() - await expectSessionTitle(page, wsl.title) - - // The tab and its open terminal outlive the restart. The stopped server no longer knows the terminal, so it is - // recreated on the restarted one. - await expect.poll(() => servers[restarted]!.pty.sockets.map((socket) => socket.id)).toEqual(["pty_after1"]) - expect(servers[REMOTE_SERVER]!.pty.sockets.map((socket) => socket.id)).toEqual(["pty_before1"]) -}) - test("WSL session and draft tabs outlive the plugin going away until the server is removed", async ({ page }) => { const directory = "/home/ubuntu/project" const wsl = session({ id: "ses_wsl_tabs", directory, title: "WSL tabs session" }) diff --git a/packages/app/e2e/regression/side-panels.spec.ts b/packages/app/e2e/regression/side-panels.spec.ts index 8507ad00044b..f734f1b3cb86 100644 --- a/packages/app/e2e/regression/side-panels.spec.ts +++ b/packages/app/e2e/regression/side-panels.spec.ts @@ -1,102 +1,8 @@ -import { expect, test, type Locator, type Page } from "@playwright/test" -import { tabKey } from "../utils/app" +import { expect, test, type Page } from "@playwright/test" import { fileDiff, openSession } from "../utils/workspace" import { openReviewLauncher } from "../utils/side-panel" -import { expectSessionTitle } from "../utils/waits" import { base64Encode } from "@opencode/util/encode" -test("review and terminal tabs follow the session tab and the terminal stays mounted", async ({ page }) => { - await page.setViewportSize({ width: 1440, height: 900 }) - const a = { id: "ses_side_a", title: "Alpha session" } - const b = { id: "ses_side_b", title: "Beta session" } - - const { directory, pty } = await openSession(page, { - name: "SidePanels", - sessions: [a, b], - pty: {}, - vcsDiff: Array.from({ length: 2_740 }, (_, index) => - fileDiff(`src/generated-${String(index).padStart(4, "0")}.ts`), - ), - seed: { panes: { [a.id]: { sessionWidth: 580 }, [b.id]: { sessionWidth: 520 } } }, - }) - - const chat = page.locator('[data-slot="session-chat-panel"]') - const review = page.locator('#review-panel [data-component="session-review-v2"]') - const terminal = page.locator('[data-component="terminal"]') - const reviewTab = page.locator("#session-side-panel-review-tab") - const terminalTab = page.locator("#review-panel").getByRole("tab", { name: "Terminal 1", exact: true }) - - const switchTab = async (title: string) => { - await page.locator("[data-titlebar-tab-slot]", { hasText: title }).click() - await expectSessionTitle(page, title) - } - - await page.getByRole("button", { name: "Toggle review" }).click() - await openReviewLauncher(page.locator("#review-panel")) - await expect(review).toBeVisible() - await expect(chat).toHaveCSS("width", "580px") - await expect(reviewTab).toHaveText("Files Changed 2740") - - // The terminal opens as a tab beside review in the same strip. - await page.keyboard.press("Control+Backquote") - await expect(terminalTab).toHaveAttribute("aria-selected", "true") - await expect(terminal).toBeVisible() - await expect(review).toBeHidden() - await expect.poll(() => pty.sockets.length).toBe(1) - await mark(terminal) - - await switchTab(b.title) - await expect(terminal).toBeHidden() - await expectMarked(terminal) - await page.getByRole("button", { name: "Toggle review" }).click() - await openReviewLauncher(page.locator("#review-panel")) - await expect(review).toBeVisible() - await expect(chat).toHaveCSS("width", "520px") - // The workspace's terminal reopens in this session's strip instead of starting another shell. - await page.keyboard.press("Control+Backquote") - await expect(terminalTab).toHaveAttribute("aria-selected", "true") - await expect(terminal).toBeVisible() - await expectMarked(terminal) - - await switchTab(a.title) - await expect(terminal).toBeVisible() - await expect(chat).toHaveCSS("width", "580px") - await expectMarked(terminal) - await reviewTab.click() - await expect(review).toBeVisible() - expect(pty.sockets).toHaveLength(1) - expect(pty.created).toHaveLength(1) - expect(pty.sockets[0]!.url.searchParams.get("location[directory]")).toBe(directory) - expect(pty.sockets[0]!.url.searchParams.get("ticket")).toBe("e2e-ticket") - expect(pty.tokens[0]?.headers["x-opencode-ticket"]).toBe("1") - - await terminalTab.click() - await expect(terminal).toBeVisible() - await expect - .poll(() => - page.evaluate( - (key) => JSON.parse(localStorage.getItem("opencode.window.browser.dat:tabs.panes") ?? "{}")[key]?.review, - tabKey(a.id), - ), - ) - .toBe(true) - await page.reload() - await expectSessionTitle(page, a.title) - await expect(terminalTab).toHaveAttribute("aria-selected", "true") - await expect(terminal).toBeVisible() - await expect(chat).toHaveCSS("width", "580px") - await reviewTab.click() - await expect(review).toBeVisible() - - const tree = page.locator('#review-panel [data-component="file-tree-v2"]') - await expect(tree.getByRole("treeitem", { name: "generated-0000.ts" })).toBeVisible() - expect(await tree.locator('[data-type="item"]').count()).toBeLessThanOrEqual(60) - const viewport = tree.locator("[data-file-tree-virtualized-scroll]") - await viewport.hover() - await page.mouse.wheel(0, 100_000) - await expect(tree.getByRole("treeitem", { name: "generated-2739.ts" })).toBeVisible() -}) - test("review content stays aligned with the side region in both directions", async ({ page }) => { await page.setViewportSize({ width: 1400, height: 900 }) @@ -260,15 +166,6 @@ test("tabs in a narrow side strip shrink to keep their close buttons, and a tab' await expect(side.getByRole("tab", { name: "b.md", exact: true })).toHaveCount(0) }) -// A DOM mark survives only while the same node stays mounted. -function mark(locator: Locator) { - return locator.evaluate((element) => element.setAttribute("data-e2e-mounted", "original")) -} - -function expectMarked(locator: Locator) { - return expect(locator).toHaveAttribute("data-e2e-mounted", "original") -} - async function expectTreeSentinel(page: Page) { const tree = page.locator('#review-panel [data-component="file-tree-v2"]') await expect(tree.getByRole("treeitem", { name: "action.yml" })).toBeVisible() diff --git a/packages/app/e2e/regression/terminal-input.spec.ts b/packages/app/e2e/regression/terminal-input.spec.ts deleted file mode 100644 index 5a69c2d885c8..000000000000 --- a/packages/app/e2e/regression/terminal-input.spec.ts +++ /dev/null @@ -1,341 +0,0 @@ -import { base64Encode, checksum } from "@opencode/util/encode" -import { expect, test, type Page } from "@playwright/test" -import { sessionHref } from "../utils/app" -import { mockWorkspace, openSession, type WorkspaceInput } from "../utils/workspace" -import { expectSessionTitle } from "../utils/waits" - -const workspace = { name: "TerminalInput", pty: {} } satisfies WorkspaceInput - -test.use({ viewport: { width: 1440, height: 900 } }) - -test("clears the terminal line with Command+Delete and suppresses printable Command chords", async ({ page }) => { - const { pty } = await openSession(page, workspace) - const terminal = page.locator('[data-component="terminal"]') - await page.keyboard.press("Control+Backquote") - await expect(terminal.locator("textarea")).toHaveCount(1) - await expect.poll(() => pty.sockets.length).toBe(1) - - await page.keyboard.press("Meta+k") - await page.keyboard.press("Meta+j") - await terminal.locator("textarea").evaluate((textarea) => { - const clipboardData = new DataTransfer() - clipboardData.setData("text/plain", "echo pasted") - textarea.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true })) - }) - await expect.poll(() => pty.sockets[0]!.input.join("")).toBe("echo pasted") - - await page.keyboard.press("Meta+Backspace") - await expect.poll(() => pty.sockets[0]!.input.join("")).toBe("echo pasted\x15") -}) - -test("a custom Close tab shortcut closes the focused terminal, not the session tab", async ({ page }) => { - const { session } = await openSession(page, { - ...workspace, - seed: { settings: { keybinds: { "tab.close": "mod+e" } } }, - }) - - const terminal = page.locator('[data-component="terminal"]') - await page.keyboard.press("Control+Backquote") - await expect(terminal.locator("textarea")).toHaveCount(1) - await expect.poll(() => terminal.evaluate((element) => element.contains(document.activeElement))).toBe(true) - - await page.keyboard.press("ControlOrMeta+e") - await expect(terminal).toHaveCount(0) - await expect(page).toHaveURL(sessionHref(session.id)) -}) - -test("reveals the terminal after its first output and hides the native caret", async ({ page }) => { - const { pty } = await openSession(page, workspace) - await page.keyboard.press("Control+Backquote") - const terminal = page.locator('[data-component="terminal"]') - await expect(terminal).toHaveAttribute("contenteditable", "true") - await expect(terminal).toHaveCSS("caret-color", "rgba(0, 0, 0, 0)") - await expect(terminal).toHaveCSS("opacity", "0") - await expect.poll(() => pty.sockets.length).toBe(1) - - pty.send("\x1b[?25h") - await expect(terminal).toHaveCSS("opacity", "0") - pty.send("ready") - await expect(terminal).toHaveCSS("opacity", "1") -}) - -test("quotes selected terminal output into the composer", async ({ page }) => { - const { pty, editor } = await openSession(page, workspace) - const terminal = page.locator('[data-component="terminal"]') - await page.keyboard.press("Control+Backquote") - await expect.poll(() => pty.sockets.length).toBe(1) - pty.send("$ bun run build\r\nerror: Cannot find module './config'\r\n") - await expect(terminal).toHaveCSS("opacity", "1") - - const canvas = terminal.locator("canvas").first() - const box = await canvas.boundingBox() - - if (!box) throw new Error("The terminal has no canvas") - // From the first output row's start to well into the second. - await page.mouse.move(box.x + 2, box.y + 4) - await page.mouse.down() - await page.mouse.move(box.x + 320, box.y + 26, { steps: 8 }) - await page.mouse.up() - - const toolbar = page.getByRole("toolbar", { name: "Quote selection" }) - await expect(toolbar).toBeVisible() - await toolbar.getByRole("button", { name: "Quote", exact: true }).click() - - const chips = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]') - await expect(chips).toHaveCount(1) - await expect(chips).toContainText("Terminal") - await expect(toolbar).toBeHidden() - const comment = page.locator('[data-component="composer-quote-comment"] textarea') - await expect(comment).toBeFocused() - await comment.fill("Investigate this output") - - const atTile = async () => { - const popover = await page.locator('[data-component="composer-quote-comment"]').boundingBox() - const tile = await chips.nth(0).boundingBox() - - return ( - popover && tile && Math.abs(popover.x - tile.x) < 1 && Math.abs(popover.y + popover.height - (tile.y - 8)) < 1 - ) - } - - await expect.poll(atTile).toBe(false) - // Cached terminals can hide without a write or grid resize; the unsaved editor still follows its tile. - await page.getByRole("button", { name: "Add tab", exact: true }).click() - await expect(terminal).toBeHidden() - await expect.poll(atTile).toBe(true) - await expect(comment).toHaveValue("Investigate this output") - await page.locator("#review-panel").getByRole("tab", { name: "Terminal 1", exact: true }).click() - await expect(terminal).toBeVisible() - await expect.poll(atTile).toBe(false) - await expect(comment).toHaveValue("Investigate this output") - - // Any output invalidates terminal row identity; the same draft stays open beside its composer tile. - pty.send(Array.from({ length: 80 }, (_, index) => `output row ${index}\r\n`).join("")) - await expect.poll(atTile).toBe(true) - await expect(comment).toHaveValue("Investigate this output") - await comment.fill("") - await comment.press("Enter") - await expect(comment).toHaveCount(0) - await expect(editor).toBeFocused() - - // The plugin's Alt path skips the editor too, and either quote can still be commented from its tile. - const next = await canvas.boundingBox() - - if (!next) throw new Error("The terminal has no canvas") - await page.mouse.move(next.x + 2, next.y + 4) - await page.mouse.down() - await page.mouse.move(next.x + 320, next.y + 26, { steps: 8 }) - await page.mouse.up() - await toolbar.getByRole("button", { name: "Quote", exact: true }).click({ modifiers: ["Alt"] }) - await expect(chips).toHaveCount(2) - await expect(comment).toHaveCount(0) - await expect(editor).toBeFocused() - await chips.nth(0).click() - await comment.fill("Why did the build fail?") - await comment.press("Enter") - await expect(chips.nth(0)).toContainText("Why did the build fail?") -}) - -test("routes typing to the composer unless the open terminal is focused", async ({ page }) => { - const { pty, editor } = await openSession(page, workspace) - const terminal = page.locator('[data-component="terminal"]') - await editor.click() - await expect(editor).toBeFocused() - await page.keyboard.press("Control+Backquote") - await expect(terminal).toBeVisible() - await expect.poll(() => terminal.evaluate((element) => element.contains(document.activeElement))).toBe(true) - - await page.keyboard.type("x") - await expect(editor).toHaveText("") - await expect.poll(() => pty.sockets.length).toBe(1) - pty.send("ready") - await expect(terminal).toHaveCSS("opacity", "1") - await page.evaluate(() => { - if (document.activeElement instanceof HTMLElement) document.activeElement.blur() - }) - await page.keyboard.type("a") - await expect(editor).toBeFocused() - await expect(editor).toHaveText("a") -}) - -for (const mount of ["cached", "explicit"] as const) { - test(`keeps newer composer focus while a ${mount} terminal finishes mounting`, async ({ page }) => { - const ghostty = Promise.withResolvers() - const release = Promise.withResolvers() - await page.route(/ghostty-web/, async (route) => { - ghostty.resolve() - await release.promise - await route.continue() - }) - const cached = { id: "pty_cached", title: "Terminal 1" } - - const { pty, sessions } = await mockWorkspace(page, { - ...workspace, - pty: mount === "cached" ? { initial: [cached] } : {}, - seed: mount === "cached" ? restoredTerminal(cached) : undefined, - }) - - await page.goto(sessionHref(sessions[0]!.id), { waitUntil: "commit" }) - await expectSessionTitle(page, "TerminalInput") - const editor = page.locator('[data-component="composer-editor"]') - const terminal = page.locator('[data-component="terminal"]') - - if (mount === "explicit") { - await expect(editor).toBeEditable() - await page.keyboard.press("Control+Backquote") - } - - await expect(terminal).toBeVisible() - await ghostty.promise - await editor.click() - await expect(editor).toBeFocused() - - release.resolve() - await expect(terminal.locator("textarea")).toHaveCount(1) - await expect.poll(() => pty.sockets.length).toBe(1) - pty.send("ready") - await expect(terminal).toHaveCSS("opacity", "1") - await expect(editor).toBeFocused() - - if (mount === "cached") expect(pty.created).toEqual([]) - }) -} - -test("reconnects the same terminal after a transient connection failure", async ({ page }) => { - const { pty } = await openSession(page, workspace) - let tickets = 0 - await page.route(/\/api\/pty\/[^/]+\/connect-token/, (route) => { - if (route.request().method() === "OPTIONS") return route.fallback() - tickets += 1 - - if (tickets !== 2) return route.fallback() - - return route.fulfill({ - status: 503, - headers: { "access-control-allow-origin": "*" }, - body: "Service Unavailable", - }) - }) - await page.keyboard.press("Control+Backquote") - const terminal = page.locator('[data-component="terminal"]') - await expect(terminal.locator("textarea")).toHaveCount(1) - await expect.poll(() => pty.sockets.length).toBe(1) - const id = pty.sockets[0]!.id - await terminal.evaluate((element) => element.setAttribute("data-connection-probe", "original")) - - await pty.sockets[0]!.close(1011, "Temporary disconnection") - await expect.poll(() => tickets).toBe(3) - await expect.poll(() => pty.sockets.length).toBe(2) - expect(pty.sockets[1]!.id).toBe(id) - expect(pty.rejected).toEqual([]) - await expect(terminal).toHaveAttribute("data-connection-probe", "original") - expect(pty.created.map((item) => item.id)).toEqual([id]) -}) - -test("opens terminals as side panel tabs from the + menu", async ({ page }) => { - const { editor, pty } = await openSession(page, workspace) - const panel = page.locator("#review-panel") - const terminal = page.locator('[data-component="terminal"]') - await page.keyboard.press("Control+Backquote") - await expect(panel.getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute("aria-selected", "true") - await expect(terminal.locator("textarea")).toHaveCount(1) - - const add = async () => { - await editor.click() - await expect(editor).toBeFocused() - await panel.getByRole("button", { name: "Add tab", exact: true }).click() - await panel.getByRole("button", { name: /^Terminal/ }).click() - } - - for (const number of [2, 3]) { - await add() - await expect(panel.getByRole("tab", { name: `Terminal ${number}`, exact: true })).toHaveAttribute( - "aria-selected", - "true", - ) - const active = page.locator(`#terminal-wrapper-pty_${number} [data-component="terminal"]`) - await expect.poll(() => active.evaluate((element) => element.contains(document.activeElement))).toBe(true) - } - - // Closing a tab closes its terminal, and the next one takes the lowest free number. - await closeTab(page, "pty_2") - await expect.poll(() => pty.removed).toEqual(["pty_2"]) - await expect(panel.getByRole("tab", { name: /^Terminal / })).toHaveText(["Terminal 1", "Terminal 3"]) - await add() - await expect(panel.getByRole("tab", { name: /^Terminal / })).toHaveText(["Terminal 1", "Terminal 3", "Terminal 2"]) - await expect(panel.getByRole("tab", { name: "Terminal 2", exact: true })).toHaveAttribute("aria-selected", "true") -}) - -test("focuses the terminal opened from the command palette", async ({ page }) => { - const { editor } = await openSession(page, workspace) - const terminal = page.locator('[data-component="terminal"]') - await editor.click() - await page.keyboard.press("ControlOrMeta+Shift+P") - const palette = page.getByRole("dialog") - const search = palette.getByRole("combobox") - await expect(search).toBeFocused() - await search.fill("Toggle terminal") - await expect(palette.getByRole("option", { name: /^Toggle terminal/ })).toHaveAttribute("aria-selected", "true") - - await search.press("Enter") - await expect(palette).toHaveCount(0) - await expect(terminal.locator("textarea")).toHaveCount(1) - await expect.poll(() => terminal.evaluate((element) => element.contains(document.activeElement))).toBe(true) -}) - -test("closing the last restored terminal does not create a hidden replacement", async ({ page }) => { - const cached = { id: "pty_cached", title: "Terminal 1" } - const { pty } = await openSession(page, { ...workspace, pty: { initial: [cached] }, seed: restoredTerminal(cached) }) - const panel = page.locator("#review-panel") - const tab = panel.getByRole("tab", { name: "Terminal 1", exact: true }) - - const terminal = page.locator('[data-component="terminal"]') - await expect(terminal.locator("textarea")).toHaveCount(1) - await expect.poll(() => pty.sockets.length).toBe(1) - expect(pty.created).toEqual([]) - - await closeTab(page, cached.id) - await expect(terminal).toBeHidden() - await expect.poll(() => pty.removed).toEqual([cached.id]) - expect(pty.created).toEqual([]) - - await page.keyboard.press("Control+Backquote") - await expect(terminal.locator("textarea")).toHaveCount(1) - await expect.poll(() => pty.created.map((item) => item.id)).toEqual(["pty_1"]) - await expect(tab).toHaveAttribute("aria-selected", "true") -}) - -// A terminal tab restored open in the side panel, with the terminal in the pre-plugin store, which the terminal -// plugin imports. -function restoredTerminal(pty: { id: string; title: string }) { - const key = `terminal:${pty.id}` - - return { - panes: { ses_terminalinput: { review: true } }, - storage: { - [legacyTerminalKey()]: { active: pty.id, all: [{ ...pty, titleNumber: 1 }] }, - "opencode.global.dat:layout": { - sessionTabs: { [`local\u0000${directory()}/ses_terminalinput`]: { all: [key], active: key } }, - }, - }, - } -} - -function closeTab(page: Page, id: string) { - return page - .locator(`#review-panel [data-value="terminal:${id}"]`) - .first() - .getByRole("button", { name: "Close tab", exact: true }) - .click() -} - -function directory() { - return base64Encode("C:/OpenCode/TerminalInput") -} - -function legacyTerminalKey() { - const dir = directory() - const head = dir.slice(0, 12).replace(/[^a-zA-Z0-9._-]/g, "-") - - return `opencode.workspace.${head}.${checksum(dir) ?? "0"}.dat:workspace:terminal` -} diff --git a/packages/app/e2e/regression/terminal.spec.ts b/packages/app/e2e/regression/terminal.spec.ts new file mode 100644 index 000000000000..524d24b14f59 --- /dev/null +++ b/packages/app/e2e/regression/terminal.spec.ts @@ -0,0 +1,523 @@ +import { expect, test, type Page } from "@playwright/test" +import { holdRoute } from "../utils/app" +import { terminalScreen, terminalText } from "../utils/terminal" +import { openSession } from "../utils/workspace" + +test.use({ viewport: { width: 1440, height: 900 } }) + +test.beforeEach(async ({ context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]) +}) + +const SESSION = "ses_terminals" + +test("restores a terminal from the server's snapshot after a reload", async ({ page }) => { + const output = "first-line\r\n" + + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_restore", sessionID: SESSION, title: "Build", output }] }, + }) + + const screen = terminalScreen(page, "pty_restore") + + await openSide(page) + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + await expect.poll(() => terminalText(page, screen)).toBe("first-line") + expect(persistentPty.sockets.map((socket) => socket.cursor)).toEqual([Buffer.byteLength(output)]) + + // Output the page never saw: only the server's snapshot can restore it. + const snapshot = await holdRoute(page, /\/api\/experimental\/persistent-pty\/pty_restore\/snapshot/) + await page.reload() + await snapshot.arrived + persistentPty.output("pty_restore", "while-away\r\n") + snapshot.release() + + await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toHaveAttribute("aria-selected", "true") + await expect.poll(() => terminalText(page, screen)).toBe("first-line\nwhile-away") + expect(persistentPty.sockets.map((socket) => socket.cursor)).toEqual([ + Buffer.byteLength(output), + Buffer.byteLength(output + "while-away\r\n"), + ]) +}) + +test("after a reload, the close shortcut closes the restored terminal", async ({ page }) => { + // Elsewhere Ctrl+W reaches the shell, so the terminal hands only macOS's Cmd+W to the app. + await page.addInitScript(() => Object.defineProperty(navigator, "platform", { get: () => "MacIntel" })) + + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { + initial: [ + { id: "pty_build", sessionID: SESSION, title: "Build" }, + { id: "pty_shell", sessionID: SESSION, title: "Shell" }, + ], + }, + }) + + await openSide(page) + await showTerminal(page, "Shell", "pty_shell") + + // The restored tab is selected before the server lists the session's terminals. + const list = await holdRoute(page, /\/api\/experimental\/session\/ses_terminals\/terminal(\?|$)/, { method: "GET" }) + await page.reload() + await list.arrived + list.release() + + await expect(side(page).getByRole("tab", { name: "Shell", exact: true })).toHaveAttribute("aria-selected", "true") + // The terminal connects once it has mounted, and only a mounted terminal takes a click. + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual(["pty_shell", "pty_shell"]) + await terminalScreen(page, "pty_shell").click() + await expect(terminalScreen(page, "pty_shell").locator("textarea")).toBeFocused() + await page.keyboard.press("Meta+W") + + await expect(side(page).getByRole("tab", { name: "Shell", exact: true })).toHaveCount(0) + await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toBeVisible() + expect(persistentPty.removed).toEqual(["pty_shell"]) +}) + +test("a terminal another client creates joins the strip without taking it over", async ({ page }) => { + const { persistentPty } = await openSession(page, { name: "Terminals", persistentPty: {} }) + + await openSide(page) + await expect(side(page).getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true") + persistentPty.add({ id: "pty_remote", sessionID: SESSION, title: "Remote shell", output: "from-elsewhere\r\n" }) + + const tab = side(page).getByRole("tab", { name: "Remote shell", exact: true }) + await expect(tab).toHaveAttribute("aria-selected", "false") + await expect(side(page).getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true") + expect(persistentPty.sockets).toHaveLength(0) + + await tab.click() + await expect.poll(() => terminalText(page, terminalScreen(page, "pty_remote"))).toBe("from-elsewhere") +}) + +test("a new terminal opens focused, takes control, and streams input and output", async ({ page }) => { + const { persistentPty } = await openSession(page, { name: "Terminals", persistentPty: {} }) + + await openSide(page) + await side(page) + .getByRole("button", { name: /^Terminal/ }) + .click() + + await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute( + "aria-selected", + "true", + ) + expect(persistentPty.created.map((info) => ({ title: info.title, cwd: info.cwd }))).toEqual([ + { title: "Terminal 1", cwd: "C:/OpenCode/Terminals" }, + ]) + const id = persistentPty.created[0]!.id + await expect(terminalScreen(page, id).locator("textarea")).toBeFocused() + await expect.poll(() => persistentPty.sockets.map((socket) => socket.takeover)).toEqual([true]) + const socket = persistentPty.sockets[0]! + await expect.poll(() => socket.frames.filter((frame) => frame.type === 0).length).toBeGreaterThan(0) + expect(persistentPty.controller(id)).toBe(socket.attachmentID) + + await page.keyboard.type("echo hi") + await expect + .poll(() => + socket.frames + .filter((frame) => frame.type === 1) + .map((frame) => frame.data) + .join(""), + ) + .toBe("echo hi") + + persistentPty.output(id, "hi\r\n") + await expect.poll(() => terminalText(page, terminalScreen(page, id))).toBe("hi") +}) + +test("the New terminal shortcut creates the next numbered terminal", async ({ page }) => { + const { persistentPty, editor } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_first", sessionID: SESSION, title: "Terminal 1" }] }, + }) + + await openSide(page) + await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toBeVisible() + await editor.click() + await page.keyboard.press("Control+Alt+T") + + await expect(side(page).getByRole("tab", { name: "Terminal 2", exact: true })).toHaveAttribute( + "aria-selected", + "true", + ) + expect(persistentPty.created.map((info) => info.title)).toEqual(["Terminal 2"]) + await expect(terminalScreen(page, persistentPty.created[0]!.id).locator("textarea")).toBeFocused() +}) + +test("another client's control ends at a click, which resizes the terminal to the pane", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_shared", sessionID: SESSION, title: "Shared" }] }, + }) + + await openSide(page) + await side(page).getByRole("tab", { name: "Shared", exact: true }).click() + await expect.poll(() => persistentPty.sockets.length).toBe(1) + const socket = persistentPty.sockets[0]! + await expect.poll(() => persistentPty.controller("pty_shared")).toBe(socket.attachmentID) + + // The other client controls the terminal at its own size. + persistentPty.takeControl("pty_shared") + persistentPty.resize("pty_shared", { cols: 40, rows: 10 }) + const sent = socket.frames.length + + await terminalScreen(page, "pty_shared").click() + await expect.poll(() => persistentPty.controller("pty_shared")).toBe(socket.attachmentID) + await expect.poll(() => socket.frames.length).toBeGreaterThan(sent) + const pane = () => paneSize(socket.frames.at(-1)!) + expect(socket.frames.slice(sent).map(paneSize)).not.toContainEqual({ cols: 40, rows: 10 }) + await expect.poll(() => persistentPty.terminals[0]!.size).toEqual(pane()) + + // While it controls the terminal, the pane's new size follows. + const before = pane() + await page.setViewportSize({ width: 1200, height: 600 }) + await expect.poll(() => pane().rows).toBeLessThan(before.rows) + await expect.poll(() => persistentPty.terminals[0]!.size).toEqual(pane()) +}) + +test("a terminal whose shell exits leaves the strip", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { + initial: [ + { id: "pty_build", sessionID: SESSION, title: "Build" }, + { id: "pty_shell", sessionID: SESSION, title: "Shell" }, + ], + }, + }) + + await openSide(page) + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual(["pty_build"]) + + persistentPty.exit("pty_build", 0) + await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toHaveCount(0) + await expect(side(page).getByRole("tab", { name: "Shell", exact: true })).toBeVisible() + await expect(page.getByText("Terminal disconnected", { exact: true })).toHaveCount(0) +}) + +test("a dropped connection says the terminal disconnected and keeps its tab", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_drop", sessionID: SESSION, title: "Build", output: "still-here\r\n" }] }, + }) + + await openSide(page) + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + const screen = terminalScreen(page, "pty_drop") + await expect.poll(() => terminalText(page, screen)).toBe("still-here") + + await persistentPty.close("pty_drop") + await expect(side(page).getByText("Terminal disconnected", { exact: true })).toBeVisible() + await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toHaveAttribute("aria-selected", "true") + expect(persistentPty.sockets).toHaveLength(1) + expect(await terminalText(page, screen)).toBe("still-here") +}) + +test("after a server restart, showing the terminal again restores it from a new snapshot", async ({ page }) => { + const output = "before-restart\r\n" + + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_handoff", sessionID: SESSION, title: "Build", output }] }, + }) + + await openSide(page) + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + const screen = terminalScreen(page, "pty_handoff") + await expect.poll(() => terminalText(page, screen)).toBe("before-restart") + + await persistentPty.restart() + await expect(side(page).getByText("Terminal disconnected", { exact: true })).toBeVisible() + // The adopted daemon kept the shell running. + persistentPty.output("pty_handoff", "after-restart\r\n") + + // Showing the tab again takes a new snapshot and reconnects. + await side(page).getByRole("button", { name: "Add tab", exact: true }).click() + await expect(side(page).getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true") + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + await expect.poll(() => terminalText(page, screen)).toBe("before-restart\nafter-restart") + await expect(side(page).getByText("Terminal disconnected", { exact: true })).toHaveCount(0) + expect(persistentPty.sockets.map((socket) => socket.cursor)).toEqual([ + Buffer.byteLength(output), + Buffer.byteLength(output + "after-restart\r\n"), + ]) +}) + +test("a server without persistent terminals offers no terminal commands", async ({ page }) => { + const { editor } = await openSession(page, { name: "Terminals", persistentPty: { capability: false } }) + + await openSide(page) + const launchers = side(page).getByRole("tabpanel", { name: "New tab", exact: true }) + await expect(launchers.getByRole("button", { name: /^Open file/ })).toBeVisible() + await expect(launchers.getByRole("button", { name: /^Terminal/ })).toHaveCount(0) + + await editor.click() + await page.keyboard.type("/") + await expect(page.getByRole("button", { name: /^\/open/ })).toBeVisible() + await expect(page.getByRole("button", { name: /^\/terminal/ })).toHaveCount(0) +}) + +test("selected terminal output quotes into the composer", async ({ page }) => { + await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_quote", sessionID: SESSION, title: "Build", output: "quote-me\r\n" }] }, + }) + + await openSide(page) + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + const screen = terminalScreen(page, "pty_quote") + await expect.poll(() => terminalText(page, screen)).toBe("quote-me") + + await page + .getByRole("toolbar", { name: "Quote selection", exact: true }) + .getByRole("button", { name: "Quote" }) + .click() + await expect(page.locator('[data-component="composer"]').getByText("quote-me")).toBeVisible() +}) + +test("renaming a terminal tab renames it on the server", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_named", sessionID: SESSION, title: "Terminal 1" }] }, + }) + + await openSide(page) + const strip = side(page).getByRole("tablist") + await showTerminal(page, "Terminal 1", "pty_named") + await strip.getByText("Terminal 1", { exact: true }).dblclick() + const field = strip.getByRole("textbox", { name: "Rename", exact: true }) + await expect(field).toBeFocused() + await field.fill("Dev server") + await field.press("Enter") + + await expect(strip.getByRole("tab", { name: "Dev server", exact: true })).toBeVisible() + expect(persistentPty.updates).toEqual([{ id: "pty_named", body: { title: "Dev server" } }]) + await expect.poll(() => persistentPty.terminals[0]!.title).toBe("Dev server") +}) + +test("a rename from another client relabels the tab", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_named", sessionID: SESSION, title: "Terminal 1" }] }, + }) + + await openSide(page) + await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toBeVisible() + persistentPty.rename("pty_named", "Logs") + await expect(side(page).getByRole("tab", { name: "Logs", exact: true })).toBeVisible() + await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toHaveCount(0) +}) + +test("clearing a terminal's name resets a renamed one and leaves a never-renamed one alone", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { + initial: [ + { id: "pty_plain", sessionID: SESSION, title: "Terminal 1" }, + { id: "pty_renamed", sessionID: SESSION, title: "Terminal 2", userTitle: "Deploy" }, + ], + }, + }) + + await openSide(page) + const strip = side(page).getByRole("tablist") + const field = strip.getByRole("textbox", { name: "Rename", exact: true }) + + await showTerminal(page, "Terminal 1", "pty_plain") + await strip.getByText("Terminal 1", { exact: true }).dblclick() + await expect(field).toBeFocused() + await field.fill("") + await field.press("Enter") + await expect(field).toHaveCount(0) + await expect(strip.getByRole("tab", { name: "Terminal 1", exact: true })).toBeVisible() + + await showTerminal(page, "Deploy", "pty_renamed") + await strip.getByText("Deploy", { exact: true }).dblclick() + await expect(field).toBeFocused() + await field.fill("") + await field.press("Enter") + + await expect(strip.getByRole("tab", { name: "Terminal 2", exact: true })).toBeVisible() + await expect(strip.getByRole("tab", { name: "Deploy", exact: true })).toHaveCount(0) + // The first clear sent nothing: the only update is the second. + expect(persistentPty.updates).toEqual([{ id: "pty_renamed", body: { title: null } }]) +}) + +test("a server whose terminal service cannot rename yet keeps the old name and says when it will", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { + renameSupported: false, + initial: [{ id: "pty_named", sessionID: SESSION, title: "Terminal 1" }], + }, + }) + + await openSide(page) + const strip = side(page).getByRole("tablist") + await showTerminal(page, "Terminal 1", "pty_named") + await strip.getByText("Terminal 1", { exact: true }).dblclick() + const field = strip.getByRole("textbox", { name: "Rename", exact: true }) + await expect(field).toBeFocused() + await field.fill("Dev server") + await field.press("Enter") + + await expect( + page.getByText("Terminal renaming will be available after OpenCode's terminal service restarts", { exact: true }), + ).toBeVisible() + await expect(strip.getByRole("tab", { name: "Terminal 1", exact: true })).toBeVisible() + await expect(strip.getByRole("tab", { name: "Dev server", exact: true })).toHaveCount(0) + expect(persistentPty.terminals[0]!.title).toBe("Terminal 1") +}) + +test.describe("narrow screens", () => { + test.use({ viewport: { width: 390, height: 844 } }) + + test("the Terminal view opens from More... and shows the session's terminal", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_mobile", sessionID: SESSION, title: "Build", output: "on-mobile\r\n" }] }, + }) + + const tabs = page.getByRole("tablist", { name: "Session view", exact: true }) + const views = page.getByRole("dialog", { name: "More options", exact: true }) + await tabs.getByRole("tab", { name: "More...", exact: true }).click() + await views.getByRole("button", { name: "Terminal", exact: true }).click() + await expect(views).toBeHidden() + + const panel = page.locator("#terminal-panel") + await expect(panel.getByRole("tab", { name: "Build", exact: true })).toHaveAttribute("aria-selected", "true") + await expect.poll(() => terminalText(page, terminalScreen(page, "pty_mobile"))).toBe("on-mobile") + expect(persistentPty.created).toEqual([]) + }) + + test("an empty session's Terminal view starts its first terminal", async ({ page }) => { + const { persistentPty } = await openSession(page, { name: "Terminals", persistentPty: {} }) + + await page.getByRole("tablist", { name: "Session view", exact: true }).getByRole("tab", { name: "More..." }).click() + await page + .getByRole("dialog", { name: "More options", exact: true }) + .getByRole("button", { name: "Terminal" }) + .click() + + const panel = page.locator("#terminal-panel") + await expect(panel.getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute("aria-selected", "true") + expect(persistentPty.created.map((info) => info.title)).toEqual(["Terminal 1"]) + await expect(terminalScreen(page, persistentPty.created[0]!.id).locator("textarea")).toBeEditable() + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual([persistentPty.created[0]!.id]) + }) + + test("double-clicking a terminal tab that is not selected yet starts renaming it", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { + initial: [ + { id: "pty_first", sessionID: SESSION, title: "Build" }, + { id: "pty_second", sessionID: SESSION, title: "Deploy" }, + ], + }, + }) + + await page.getByRole("tablist", { name: "Session view", exact: true }).getByRole("tab", { name: "More..." }).click() + await page + .getByRole("dialog", { name: "More options", exact: true }) + .getByRole("button", { name: "Terminal" }) + .click() + + const panel = page.locator("#terminal-panel") + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual(["pty_first"]) + const field = panel.getByRole("textbox", { name: "Rename", exact: true }) + await panel.getByText("Deploy", { exact: true }).dblclick() + await expect(field).toBeFocused() + // The terminal connects after it mounts and asks for focus. + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual(["pty_first", "pty_second"]) + await expect(field).toBeFocused() + }) + + test("Escape cancels a terminal rename and Enter renames once", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_mobile", sessionID: SESSION, title: "Build" }] }, + }) + + await page.getByRole("tablist", { name: "Session view", exact: true }).getByRole("tab", { name: "More..." }).click() + await page + .getByRole("dialog", { name: "More options", exact: true }) + .getByRole("button", { name: "Terminal" }) + .click() + + const panel = page.locator("#terminal-panel") + const field = panel.getByRole("textbox", { name: "Rename", exact: true }) + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual(["pty_mobile"]) + + await panel.getByText("Build", { exact: true }).dblclick() + await expect(field).toBeFocused() + await field.fill("Cancelled") + await field.press("Escape") + await expect(field).toHaveCount(0) + await expect(panel.getByRole("tab", { name: "Build", exact: true })).toBeVisible() + + await panel.getByText("Build", { exact: true }).dblclick() + await expect(field).toBeFocused() + await field.fill("Deploy") + await field.press("Enter") + await expect(panel.getByRole("tab", { name: "Deploy", exact: true })).toBeVisible() + expect(persistentPty.updates).toEqual([{ id: "pty_mobile", body: { title: "Deploy" } }]) + }) +}) + +// Selecting the tab mounts its terminal, which asks for focus; the rename field keeps it. +test("double-clicking a terminal tab that is not selected yet starts renaming it", async ({ page }) => { + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_named", sessionID: SESSION, title: "Terminal 1" }] }, + }) + + // The terminal mounts once ghostty-web loads, which here waits until the rename field has focus. + const ghostty = await holdRoute(page, /\/_assets\/ghostty-web-[^/]+\.js$/) + await openSide(page) + const strip = side(page).getByRole("tablist") + const field = strip.getByRole("textbox", { name: "Rename", exact: true }) + await strip.getByText("Terminal 1", { exact: true }).dblclick() + await expect(field).toBeFocused() + ghostty.release() + // The terminal connects after it mounts and asks for focus. + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual(["pty_named"]) + await expect(field).toBeFocused() +}) + +// The menu returns focus to the tab as it closes; choosing Rename moves it to the rename field. +test("a terminal tab's context menu starts renaming it", async ({ page }) => { + await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_named", sessionID: SESSION, title: "Terminal 1" }] }, + }) + + await openSide(page) + const strip = side(page).getByRole("tablist") + await showTerminal(page, "Terminal 1", "pty_named") + await strip.getByText("Terminal 1", { exact: true }).click({ button: "right" }) + await page.getByRole("menuitem", { name: "Rename", exact: true }).click() + await expect(strip.getByRole("textbox", { name: "Rename", exact: true })).toBeFocused() +}) + +function side(page: Page) { + return page.getByRole("complementary", { name: "Review and files", exact: true }) +} + +async function openSide(page: Page) { + await page.getByRole("button", { name: "Toggle review", exact: true }).click() + await expect(side(page)).toBeVisible() +} + +async function showTerminal(page: Page, title: string, ptyID: string) { + await side(page).getByRole("tab", { name: title, exact: true }).click() + await expect(terminalScreen(page, ptyID).locator("textarea")).toBeFocused() +} + +function paneSize(frame: { cols: number; rows: number }) { + return { cols: frame.cols, rows: frame.rows } +} diff --git a/packages/app/e2e/utils/mock-api.ts b/packages/app/e2e/utils/mock-api.ts index bdac71face9a..37ee25b02aca 100644 --- a/packages/app/e2e/utils/mock-api.ts +++ b/packages/app/e2e/utils/mock-api.ts @@ -94,8 +94,6 @@ export class MockUnsupported extends Schema.TaggedError()("Mock const Unsupported = MockUnsupported.pipe(HttpApiSchema.status(501)) -const PtyMissing = [MockNotFound.pipe(HttpApiSchema.status(404)), MockPtyNotFound.pipe(HttpApiSchema.status(404))] - const PersistentPtyUnavailable = MockServiceUnavailable.pipe(HttpApiSchema.status(503)) const PersistentPtyMissing = [MockPtyNotFound.pipe(HttpApiSchema.status(404)), PersistentPtyUnavailable] @@ -273,48 +271,6 @@ const Group = HttpApiGroup.make("mock") success: NoContent, }), ) - .add( - HttpApiEndpoint.get("ptyList", "/api/pty", { - success: Json, - error: MockNotFound.pipe(HttpApiSchema.status(404)), - }), - ) - .add( - HttpApiEndpoint.post("ptyCreate", "/api/pty", { - payload: Pty.CreateInput, - success: Json, - error: MockNotFound.pipe(HttpApiSchema.status(404)), - }), - ) - .add( - HttpApiEndpoint.get("ptyGet", "/api/pty/:ptyID", { - params: PtyParams, - success: Json, - error: PtyMissing, - }), - ) - .add( - HttpApiEndpoint.put("ptyUpdate", "/api/pty/:ptyID", { - params: PtyParams, - payload: Pty.UpdateInput, - success: Json, - error: PtyMissing, - }), - ) - .add( - HttpApiEndpoint.delete("ptyRemove", "/api/pty/:ptyID", { - params: PtyParams, - success: NoContent, - error: PtyMissing, - }), - ) - .add( - HttpApiEndpoint.post("ptyConnectToken", "/api/pty/:ptyID/connect-token", { - params: PtyParams, - success: Json, - error: PtyMissing, - }), - ) .add( HttpApiEndpoint.get("persistentPtyList", "/api/experimental/session/:sessionID/terminal", { params: SessionParams, @@ -402,6 +358,12 @@ const Group = HttpApiGroup.make("mock") success: NoContent, }), ) + .add( + HttpApiEndpoint.post("sessionView", "/api/session/:sessionID/view", { + params: SessionParams, + success: NoContent, + }), + ) .add( HttpApiEndpoint.post("sessionShell", "/api/session/:sessionID/shell", { params: SessionParams, diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index 900708d5f3ad..7f920e74e6e7 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -147,9 +147,6 @@ export interface MockServerConfig { generate?: (input: { sessionID: string; prompt: string }) => { text: string } | Promise<{ text: string }> onInboxChange?: (input: { sessionID: string; inboxID: string; action: "cancel" | "steer" | "queue" }) => void onBackground?: (input: { sessionID: string }) => void - // Serves `/api/pty*` and mock PTY WebSockets. Created IDs are the first unused `${prefix}` (prefix must start with "pty"). - // `directory` is the owning workspace (Location); `cwd` is the reported working directory (default: `directory`). - pty?: { prefix?: string; initial?: { id: string; title: string; directory?: string; cwd?: string }[] } // Serves the session-scoped persistent PTY routes and their connect WebSockets (`e2e/utils/persistent-pty.ts`). // Without it, those routes answer 503 like a server whose opencode-pty daemon cannot run. persistentPty?: MockPersistentPtyConfig @@ -161,38 +158,6 @@ export interface MockServerConfig { pairing?: { code: string; token: string } } -export type MockPtyInfo = { - id: string - title: string - command: string - args: string[] - cwd: string - status: "running" | "exited" - pid: number -} - -export type MockPtySocket = { - id: string - url: URL - input: string[] - closed: boolean - send(data: string): void - close(code: number, reason: string): Promise -} - -export type MockPty = { - list: MockPtyInfo[] - created: MockPtyInfo[] - removed: string[] - updates: { id: string; body: unknown }[] - tokens: { id: string; headers: Record; ticket: string }[] - sockets: MockPtySocket[] - // WebSockets closed with 1008 because the PTY, its workspace, or an unused issued ticket did not match. - rejected: { id: string; url: URL; reason: string }[] - // Writes output to the newest open socket, optionally for one PTY. - send(data: string, id?: string): void -} - // The page relays events as opaque values; benchmarks also push their own payloads. type MockStream = { push: (payloads: readonly unknown[]) => void } @@ -455,48 +420,13 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) { }) } - if (config.pty) { - const host = new URL(server).host - await page.routeWebSocket( - (url) => url.host === host && /^\/api\/pty\/[^/]+\/connect$/.test(url.pathname), - (ws) => { - const url = new URL(ws.url()) - const id = decodeURIComponent(url.pathname.split("/")[3]!) - const reason = transport.pty.admit(id, url) - - if (reason) { - transport.pty.rejected.push({ id, url, reason }) - - return ws.close({ code: 1008, reason }) - } - - const socket: MockPtySocket = { - id, - url, - input: [], - closed: false, - send: (data) => ws.send(data), - close: (code, reason) => ws.close({ code, reason }), - } - - ws.onMessage((message) => socket.input.push(message.toString())) - ws.onClose(() => { - socket.closed = true - }) - transport.pty.sockets.push(socket) - }, - ) - } - - if (config.persistentPty) { - const host = new URL(server).host - await page.routeWebSocket( - (url) => url.host === host && /^\/api\/experimental\/persistent-pty\/[^/]+\/connect$/.test(url.pathname), - (ws) => transport.persistentPty.connect(ws), - ) - } + const host = new URL(server).host + await page.routeWebSocket( + (url) => url.host === host && /^\/api\/experimental\/persistent-pty\/[^/]+\/connect$/.test(url.pathname), + (ws) => transport.persistentPty.connect(ws), + ) - return { server, pty: transport.pty, persistentPty: transport.persistentPty, push } + return { server, persistentPty: transport.persistentPty, push } } // Answers every Location-scoped request for `directory` as the server does once that folder is deleted. @@ -549,7 +479,7 @@ export async function mockServers(page: Page, servers: Record void = () => {}, ) { - const pty = createPty(config) const persistentPty = createPersistentPty({ config: config.persistentPty, directory: config.directory }, emit) const web = HttpRouter.toWebHandler( @@ -570,7 +499,6 @@ export function createMockServerHandler( cursors: new Map(), nextCursor: 0, sessionCreates: 0, - pty, persistentPty, emit, mcp: new Map(), @@ -582,7 +510,7 @@ export function createMockServerHandler( { disableLogger: true }, ) - return { ...web, pty, persistentPty } + return { ...web, persistentPty } } const corsHeaders = { @@ -627,91 +555,6 @@ function retryableDelivery(cause: unknown) { ].some((text) => message.includes(text)) } -const PTY_TICKET = "e2e-ticket" - -function createPty(config: MockServerConfig) { - const info = (id: string, title: string, cwd = config.directory): MockPtyInfo => ({ - id, - title, - command: "cmd.exe", - args: [], - cwd, - status: "running", - pid: 1, - }) - - // Core scopes PTYs by Location, which can differ from the process cwd, so ownership is kept apart from `cwd`. - const owners = new Map((config.pty?.initial ?? []).map((item) => [item.id, item.directory ?? config.directory])) - // Issued, not yet used connect tickets, each bound to one PTY and workspace. - const tickets: { id: string; directory: string; ticket: string }[] = [] - const issued = { count: 0 } - const owns = (item: MockPtyInfo, directory: string) => owners.get(item.id) === directory - - const pty: MockPty = { - list: (config.pty?.initial ?? []).map((item) => info(item.id, item.title, item.cwd ?? item.directory)), - created: [], - removed: [], - updates: [], - tokens: [], - sockets: [], - rejected: [], - send(data, id) { - const socket = pty.sockets.findLast((item) => !item.closed && (id === undefined || item.id === id)) - - if (!socket) throw new Error(`No open PTY socket${id ? ` for ${id}` : ""}`) - socket.send(data) - }, - } - - return Object.assign(pty, { - info, - // The first `${prefix}` no initial, created, or removed PTY has used. - allocate() { - const prefix = config.pty?.prefix ?? "pty_" - const used = new Set([...pty.list, ...pty.created].map((item) => item.id).concat(pty.removed)) - - const number = Array.from({ length: used.size + 1 }, (_, index) => index + 1).find( - (value) => !used.has(`${prefix}${value}`), - )! - - return { id: `${prefix}${number}`, number } - }, - add(created: MockPtyInfo, directory: string) { - owners.set(created.id, directory) - pty.created.push(created) - pty.list.push(created) - }, - find: (id: string, directory: string) => pty.list.find((item) => item.id === id && owns(item, directory)), - owned: (directory: string) => pty.list.filter((item) => owns(item, directory)), - // Unique per server; the first stays `e2e-ticket` so single-terminal specs can assert a fixed value. - issue(id: string, directory: string) { - issued.count += 1 - const ticket = issued.count === 1 ? PTY_TICKET : `${PTY_TICKET}-${issued.count}` - tickets.push({ id, directory, ticket }) - - return ticket - }, - // Returns why a connect URL is refused: the PTY must exist, belong to the requested workspace, and carry the exact - // unused ticket issued for that PTY and workspace. Admission consumes the ticket. - admit(id: string, url: URL) { - const found = pty.list.find((item) => item.id === id) - - if (!found) return "PTY not found" - const directory = url.searchParams.get("location[directory]") || config.directory - - if (!owns(found, directory)) return "PTY belongs to another workspace" - const ticket = url.searchParams.get("ticket") - - const index = tickets.findIndex( - (item) => item.id === id && item.directory === directory && item.ticket === ticket, - ) - - if (index < 0) return "No unused ticket was issued for this PTY" - tickets.splice(index, 1) - }, - }) -} - // Every directory this server's configuration names: its own, project and inventory worktrees, and session locations. function ownedDirectories(config: MockServerConfig) { const projects = [config.project, ...(config.projects ? resolve(config.projects) : [])].flatMap((item) => @@ -754,7 +597,6 @@ function mockHandlers( cursors: Map nextCursor: number sessionCreates: number - pty: ReturnType persistentPty: ReturnType emit: (events: MockServerEvent[]) => void // MCP status overrides by `\n`, and OAuth attempt creation times by attempt ID. @@ -766,27 +608,10 @@ function mockHandlers( const delay = config.messageDelay === undefined ? Effect.void : Effect.sleep(Duration.millis(config.messageDelay)) const configEntries = config.configEntries ?? [] - const ptyEnabled = Effect.suspend(() => - config.pty ? Effect.void : Effect.fail(new MockNotFound({ message: "PTY is not enabled for this mock server" })), - ) - - // PTYs are scoped to the workspace (`location[directory]`) they were created in, like the real server. - const findPty = (id: string, request: { url: string }) => - ptyEnabled.pipe( - Effect.andThen(() => - Effect.suspend(() => { - const directory = requestDirectory(config, request) - const found = state.pty.find(id, directory) - - return found - ? Effect.succeed(found) - : Effect.fail(new MockPtyNotFound({ ptyID: id, message: `PTY not found: ${id}` })) - }), - ), - ) - + // Without a persistent PTY config the mock is a server with a working daemon and no terminals, since the desktop + // lists a session's terminals whenever its side panel renders. const persistentPtyEnabled = Effect.suspend(() => - config.persistentPty && state.persistentPty.capability !== false + state.persistentPty.capability !== false ? Effect.void : Effect.fail(new MockServiceUnavailable({ message: "opencode-pty is not available", service: "opencode-pty" })), ) @@ -1222,68 +1047,6 @@ function mockHandlers( }), // Like the server, which also answers 204 for a shell that already ended. shellRemove: () => noContent, - ptyList: (ctx) => - ptyEnabled.pipe( - Effect.map(() => { - const directory = requestDirectory(config, ctx.request) - - return { location: location(config, directory), data: state.pty.owned(directory) } - }), - ), - ptyCreate: (ctx) => - ptyEnabled.pipe( - Effect.map(() => { - const next = state.pty.allocate() - const directory = requestDirectory(config, ctx.request) - - const created = state.pty.info( - next.id, - ctx.payload.title ?? `Terminal ${next.number}`, - ctx.payload.cwd ?? directory, - ) - - state.pty.add(created, directory) - - return { location: location(config, directory), data: created } - }), - ), - ptyGet: (ctx) => - findPty(ctx.params.ptyID, ctx.request).pipe( - Effect.map((data) => ({ location: location(config, requestDirectory(config, ctx.request)), data })), - ), - ptyUpdate: (ctx) => - findPty(ctx.params.ptyID, ctx.request).pipe( - Effect.map((found) => { - state.pty.updates.push({ id: found.id, body: ctx.payload }) - - if (ctx.payload.title) found.title = ctx.payload.title - - return { location: location(config, requestDirectory(config, ctx.request)), data: found } - }), - ), - ptyRemove: (ctx) => - findPty(ctx.params.ptyID, ctx.request).pipe( - Effect.map((found) => { - state.pty.removed.push(found.id) - state.pty.list.splice(state.pty.list.indexOf(found), 1) - - return HttpApiSchema.NoContent.make() - }), - ), - ptyConnectToken: (ctx) => - findPty(ctx.params.ptyID, ctx.request).pipe( - Effect.map((found) => { - const directory = requestDirectory(config, ctx.request) - const ticket = state.pty.issue(found.id, directory) - state.pty.tokens.push({ - id: found.id, - headers: Object.fromEntries(Object.entries(ctx.request.headers)), - ticket, - }) - - return { location: location(config, directory), data: { ticket, expires_in: 60 } } - }), - ), persistentPtyList: (ctx) => persistentPtyEnabled.pipe(Effect.map(() => ({ data: state.persistentPty.list(ctx.params.sessionID) }))), persistentPtyCreate: (ctx) => diff --git a/packages/app/e2e/utils/terminal.ts b/packages/app/e2e/utils/terminal.ts new file mode 100644 index 000000000000..ff1b699e8fa6 --- /dev/null +++ b/packages/app/e2e/utils/terminal.ts @@ -0,0 +1,31 @@ +import type { Locator, Page } from "@playwright/test" + +/** The screen of one terminal in the terminal panel; cached terminals of other tabs stay mounted but hidden. */ +export function terminalScreen(page: Page, ptyID: string) { + return page.locator(`#terminal-wrapper-${ptyID} [data-component="terminal"]`) +} + +/** + * The terminal's text as the user can copy it: drags across its canvas and copies with Ctrl+Shift+C. Needs the + * clipboard permissions. The drag is a pointerdown, so the terminal also takes control, as a click would. + */ +export async function terminalText(page: Page, screen: Locator) { + const box = await screen.locator("canvas").boundingBox() + + if (!box) throw new Error("The terminal has no canvas") + + // An empty selection copies nothing, so an earlier copy must not pass for the screen. + await page.evaluate(() => navigator.clipboard.writeText("")) + await page.mouse.move(box.x + 1, box.y + 1) + await page.mouse.down() + await page.mouse.move(box.x + box.width - 1, box.y + box.height - 1, { steps: 4 }) + await page.mouse.up() + await page.keyboard.press("Control+Shift+C") + const text = await page.evaluate(() => navigator.clipboard.readText()) + + return text + .split("\n") + .map((line) => line.trimEnd()) + .join("\n") + .trimEnd() +} diff --git a/packages/app/e2e/utils/timeline.ts b/packages/app/e2e/utils/timeline.ts index f001cbb0d989..5a8ae0fd5b89 100644 --- a/packages/app/e2e/utils/timeline.ts +++ b/packages/app/e2e/utils/timeline.ts @@ -125,7 +125,6 @@ type TimelineServerInput = Partial< | "fileList" | "fileContent" | "findFiles" - | "pty" | "keepalive" | "onPermissionReply" | "shellCommands" @@ -322,7 +321,7 @@ export async function setupTimeline( return { transport, - pty: mock.pty, + persistentPty: mock.persistentPty, send, async sendAll(sequence: { event: TimelineEvent; delay: number }[]) { for (const item of sequence) await send(item.event, item.delay) diff --git a/packages/app/e2e/utils/workspace.ts b/packages/app/e2e/utils/workspace.ts index cc3e86992b43..20109c6a216f 100644 --- a/packages/app/e2e/utils/workspace.ts +++ b/packages/app/e2e/utils/workspace.ts @@ -53,7 +53,7 @@ export async function mockWorkspace(page: Page, input: WorkspaceInput) { ...input.seed, }) - return { server: SERVER, directory, projectID, sessions, pty: mock.pty, push: mock.push } + return { server: SERVER, directory, projectID, sessions, persistentPty: mock.persistentPty, push: mock.push } } // Opens a session (default: the first) and waits until its composer accepts input. diff --git a/packages/app/src/runtime/server/client.test.ts b/packages/app/src/runtime/server/client.test.ts index 1089ce7e21c8..6312ba577bc4 100644 --- a/packages/app/src/runtime/server/client.test.ts +++ b/packages/app/src/runtime/server/client.test.ts @@ -86,9 +86,10 @@ describe("server event stream", () => { }) }) -test("rotates HTTP and PTY clients together", async () => { +test("rotates the HTTP client with the endpoint", async () => { const requests: Array<{ url: string; authorization: string | null }> = [] + // SAFETY: the transport only calls fetch with a request and init; `preconnect` and other statics are never read. const fetch = (async (input: string | URL | Request, init?: RequestInit) => { const request = input instanceof Request ? input : new Request(input, init) requests.push({ url: request.url, authorization: request.headers.get("authorization") }) @@ -106,8 +107,6 @@ test("rotates HTTP and PTY clients together", async () => { fetch, }) - const initialPty = transport.pty - await transport.api.server.info() const replacement = transport.update({ @@ -118,7 +117,6 @@ test("rotates HTTP and PTY clients together", async () => { await transport.api.server.info() expect(replacement).toBe(transport.api) - expect(transport.pty).not.toBe(initialPty) expect(transport.url).toBe("http://127.0.0.1:4200") expect(requests).toEqual([ { diff --git a/packages/app/src/runtime/server/client.tsx b/packages/app/src/runtime/server/client.tsx index a54a947f2a28..aa3a29fdaec9 100644 --- a/packages/app/src/runtime/server/client.tsx +++ b/packages/app/src/runtime/server/client.tsx @@ -1,5 +1,5 @@ import type { OpenCodeEvent } from "@opencode/client/promise" -import { createClientConnection, createPtyClient, type ClientConnectionStatus } from "@opencode/client/solid" +import { createClientConnection, type ClientConnectionStatus } from "@opencode/client/solid" import { createGlobalEmitter } from "@solid-primitives/event-bus" import { type Accessor, createEffect, on, onCleanup } from "solid-js" import { createApiForServer, type ServerApi } from "@/runtime/server/api" @@ -68,7 +68,6 @@ type ServerSDKBase = { http: ServerConnection.HttpBase api: ServerApi media: MediaCache - pty: ReturnType connection: { status: Accessor attempt: Accessor @@ -136,9 +135,6 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS return transport.api }, media, - get pty() { - return transport.pty - }, connection, event: events.event, } @@ -163,9 +159,9 @@ function sameEndpoint(a: ServerConnection.HttpBase, b: ServerConnection.HttpBase return a.url === b.url && a.password === b.password } -/** A server's HTTP and PTY clients, rebuilt when its endpoint changes. */ +/** A server's HTTP client, rebuilt when its endpoint changes. */ export interface ServerTransport { - /** Rebuilds the clients for a new endpoint and returns the new API client. */ + /** Rebuilds the client for a new endpoint and returns it. */ update(http: ServerConnection.HttpBase): ServerApi /** The current base URL. */ readonly url: string @@ -173,8 +169,6 @@ export interface ServerTransport { readonly http: ServerConnection.HttpBase /** The current API client. */ readonly api: ServerApi - /** The current PTY client. */ - readonly pty: ReturnType } export function createServerTransport(input: { @@ -184,12 +178,11 @@ export function createServerTransport(input: { const queue = createRequestQueue({ fetch: input.fetch ?? globalThis.fetch }) // Keeps the endpoint as plain values: a plugin's endpoint can be a store proxy that already reads the next password, - // and the clients built here keep the one they started with. + // and the client built here keeps the one it started with. const build = (input: ServerConnection.HttpBase) => { const http = { url: input.url, password: input.password } - const api = createApiForServer({ server: http, fetch: queue.fetch }) - return { http, api, pty: createPtyClient(api, { url: http.url }) } + return { http, api: createApiForServer({ server: http, fetch: queue.fetch }) } } const state = { current: build(input.http) } @@ -210,9 +203,6 @@ export function createServerTransport(input: { get api() { return state.current.api }, - get pty() { - return state.current.pty - }, } } diff --git a/packages/client/src/solid/pty.ts b/packages/client/src/solid/pty.ts index b911b114608b..117a70386ae9 100644 --- a/packages/client/src/solid/pty.ts +++ b/packages/client/src/solid/pty.ts @@ -1,6 +1,6 @@ import { PersistentPty } from "@opencode/schema/persistent-pty" import { Schema } from "effect" -import type { ExperimentalPersistentPtyConnectTokenInput, OpenCodeClient, PtyConnectTokenInput } from "../promise" +import type { ExperimentalPersistentPtyConnectTokenInput, OpenCodeClient } from "../promise" // Declares only the fields clients read, so servers can add or drop the rest without a client silently ignoring a // message it depends on. @@ -52,12 +52,6 @@ export type PtyClientOptions = { readonly openSocket?: (url: URL) => WebSocket } -export type PtyConnectInput = { - readonly ptyID: PtyConnectTokenInput["ptyID"] - readonly location?: PtyConnectTokenInput["location"] - readonly cursor?: number -} - export type PersistentPtyConnectInput = { readonly ptyID: ExperimentalPersistentPtyConnectTokenInput["ptyID"] readonly cursor: number @@ -65,29 +59,6 @@ export type PersistentPtyConnectInput = { readonly takeover?: boolean } -export function createPtyClient(api: OpenCodeClient, options: PtyClientOptions) { - return { - async connect(input: PtyConnectInput) { - const result = await api.pty.connect.token({ - ptyID: input.ptyID, - location: input.location, - "x-opencode-ticket": "1", - }) - const baseUrl = new URL(options.url) - if (!baseUrl.pathname.endsWith("/")) baseUrl.pathname += "/" - const url = new URL(`api/pty/${encodeURIComponent(input.ptyID)}/connect`, baseUrl) - if (input.location?.directory) url.searchParams.set("location[directory]", input.location.directory) - if (input.cursor !== undefined) url.searchParams.set("cursor", String(input.cursor)) - url.searchParams.set("ticket", result.data.ticket) - url.protocol = url.protocol === "https:" ? "wss:" : "ws:" - - const socket = options.openSocket?.(url) ?? new WebSocket(url) - socket.binaryType = "arraybuffer" - return socket - }, - } -} - export function createPersistentPtyClient(api: OpenCodeClient, options: PtyClientOptions) { return { async connect(input: PersistentPtyConnectInput) { diff --git a/packages/client/test/solid-pty.test.ts b/packages/client/test/solid-pty.test.ts index a5c7aa48f6ab..42e825e31088 100644 --- a/packages/client/test/solid-pty.test.ts +++ b/packages/client/test/solid-pty.test.ts @@ -1,9 +1,9 @@ import { describe, expect, test } from "bun:test" import { OpenCode } from "../src/promise" -import { createPersistentPtyClient, createPtyClient } from "../src/solid" +import { createPersistentPtyClient } from "../src/solid" -describe("createPtyClient", () => { - test("mints an authenticated ticket before opening the terminal socket", async () => { +describe("createPersistentPtyClient", () => { + test("mints an authenticated ticket before opening the persistent terminal socket", async () => { let request: Request | undefined let socketURL: URL | undefined const socket = { binaryType: "blob" } as unknown as WebSocket @@ -12,16 +12,10 @@ describe("createPtyClient", () => { headers: { Authorization: "Basic credential" }, fetch: async (input, init) => { request = input instanceof Request ? input : new Request(input, init) - return Response.json({ - location: { - directory: "/repo/worktree", - project: { id: "project_1", directory: "/repo", canonical: "/repo" }, - }, - data: { ticket: "ticket-1", expires_in: 60 }, - }) + return Response.json({ data: { ticket: "persistent-ticket", expires_in: 60 } }) }, }) - const pty = createPtyClient(api, { + const pty = createPersistentPtyClient(api, { url: "https://server.example", openSocket(url) { socketURL = url @@ -29,21 +23,13 @@ describe("createPtyClient", () => { }, }) - expect( - await pty.connect({ - ptyID: "pty_1", - location: { directory: "/repo/worktree" }, - cursor: 42, - }), - ).toBe(socket) + expect(await pty.connect({ ptyID: "pty_1", cursor: 42, attachmentID: "attachment_1", takeover: true })).toBe(socket) expect(request?.method).toBe("POST") - expect(request?.url).toBe( - "https://server.example/api/pty/pty_1/connect-token?location%5Bdirectory%5D=%2Frepo%2Fworktree", - ) + expect(request?.url).toBe("https://server.example/api/experimental/persistent-pty/pty_1/connect-token") expect(request?.headers.get("authorization")).toBe("Basic credential") expect(request?.headers.get("x-opencode-ticket")).toBe("1") expect(socketURL?.toString()).toBe( - "wss://server.example/api/pty/pty_1/connect?location%5Bdirectory%5D=%2Frepo%2Fworktree&cursor=42&ticket=ticket-1", + "wss://server.example/api/experimental/persistent-pty/pty_1/connect?ticket=persistent-ticket&cursor=42&attachment_id=attachment_1&takeover=true&input_protocol=1", ) expect(socket.binaryType).toBe("arraybuffer") }) @@ -54,7 +40,7 @@ describe("createPtyClient", () => { baseUrl: "http://localhost:4096", fetch: async () => new Response(null, { status: 401 }), }) - const pty = createPtyClient(api, { + const pty = createPersistentPtyClient(api, { url: "http://localhost:4096", openSocket() { opened = true @@ -62,68 +48,10 @@ describe("createPtyClient", () => { }, }) - await expect(pty.connect({ ptyID: "pty_1", location: { directory: "/repo" } })).rejects.toThrow() + await expect(pty.connect({ ptyID: "pty_1", cursor: 0, attachmentID: "attachment_1" })).rejects.toThrow() expect(opened).toBe(false) }) - test("keeps the server path prefix when opening the terminal socket", async () => { - let socketURL: URL | undefined - const api = OpenCode.make({ - baseUrl: "https://server.example/base", - fetch: async () => - Response.json({ - location: { - directory: "/repo", - project: { id: "project_1", directory: "/repo", canonical: "/repo" }, - }, - data: { ticket: "ticket-1", expires_in: 60 }, - }), - }) - const pty = createPtyClient(api, { - url: "https://server.example/base", - openSocket(url) { - socketURL = url - return { binaryType: "blob" } as unknown as WebSocket - }, - }) - - await pty.connect({ ptyID: "pty_1" }) - expect(socketURL?.toString()).toBe("wss://server.example/base/api/pty/pty_1/connect?ticket=ticket-1") - }) -}) - -describe("createPersistentPtyClient", () => { - test("mints an authenticated ticket before opening the persistent terminal socket", async () => { - let request: Request | undefined - let socketURL: URL | undefined - const socket = { binaryType: "blob" } as unknown as WebSocket - const api = OpenCode.make({ - baseUrl: "https://server.example", - headers: { Authorization: "Basic credential" }, - fetch: async (input, init) => { - request = input instanceof Request ? input : new Request(input, init) - return Response.json({ data: { ticket: "persistent-ticket", expires_in: 60 } }) - }, - }) - const pty = createPersistentPtyClient(api, { - url: "https://server.example", - openSocket(url) { - socketURL = url - return socket - }, - }) - - expect(await pty.connect({ ptyID: "pty_1", cursor: 42, attachmentID: "attachment_1", takeover: true })).toBe(socket) - expect(request?.method).toBe("POST") - expect(request?.url).toBe("https://server.example/api/experimental/persistent-pty/pty_1/connect-token") - expect(request?.headers.get("authorization")).toBe("Basic credential") - expect(request?.headers.get("x-opencode-ticket")).toBe("1") - expect(socketURL?.toString()).toBe( - "wss://server.example/api/experimental/persistent-pty/pty_1/connect?ticket=persistent-ticket&cursor=42&attachment_id=attachment_1&takeover=true&input_protocol=1", - ) - expect(socket.binaryType).toBe("arraybuffer") - }) - test("keeps the server path prefix when opening the persistent terminal socket", async () => { let socketURL: URL | undefined const api = OpenCode.make({ diff --git a/packages/gui-plugins/package.json b/packages/gui-plugins/package.json index 41d57a732801..fe87dbcd14d5 100644 --- a/packages/gui-plugins/package.json +++ b/packages/gui-plugins/package.json @@ -21,9 +21,6 @@ "@betteroffice/fonts": "0.4.0", "@betteroffice/pptx": "0.2.0", "@betteroffice/xlsx": "0.3.0", - "@dnd-kit/abstract": "0.5.0", - "@dnd-kit/dom": "0.5.0", - "@dnd-kit/solid": "0.5.0", "@effect/platform-node": "catalog:", "@kobalte/core": "catalog:", "@opencode/client": "workspace:*", @@ -49,6 +46,7 @@ "devDependencies": { "@happy-dom/global-registrator": "20.0.11", "@lydell/node-pty": "catalog:", + "@opencode/protocol": "workspace:*", "@tsconfig/node22": "catalog:", "@types/bun": "catalog:", "@types/node": "catalog:", diff --git a/packages/gui-plugins/src/terminal/connection.test.ts b/packages/gui-plugins/src/terminal/connection.test.ts new file mode 100644 index 000000000000..102b3dc79680 --- /dev/null +++ b/packages/gui-plugins/src/terminal/connection.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, test } from "bun:test" +import { persistentPtyFrame } from "@opencode/client/solid" +import { terminalConnection, type TerminalFailure } from "./connection" + +const info = { + id: "pty_1", + title: "zsh", + command: "/bin/zsh", + args: [], + cwd: "/repo", + status: "running", + pid: 42, + sessionID: "ses_1", + foregroundProcess: null, + size: { cols: 80, rows: 24 }, + output: { head: 0, tail: 128 }, +} + +const attached = (fields: { inputProtocol?: number } = {}) => + JSON.stringify({ + type: "attached", + inputProtocol: 1, + info, + role: "controller", + generation: 1, + replay: { requestedOffset: 128, availableOffset: 0, endOffset: 128, truncated: false }, + ...fields, + }) + +const replayComplete = JSON.stringify({ type: "replay_complete", endOffset: 128 }) + +const encode = (text: string) => new TextEncoder().encode(text) + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) + +// A terminal that finishes each write only when the test says so, like ghostty-web finishing on the next frame. +function setup(options: { reply?: string } = {}) { + const log: string[] = [] + const sent: Uint8Array[] = [] + const failures: TerminalFailure[] = [] + const pending: VoidFunction[] = [] + + const connection = terminalConnection({ + attachmentID: "attachment-1", + write: (data, done) => { + log.push(`write ${new TextDecoder().decode(data)}`) + + if (options.reply) connection.input(options.reply) + pending.push(done) + }, + resize: (size) => log.push(`resize ${size.cols}x${size.rows}`), + send: (frame) => sent.push(frame), + fail: (failure) => failures.push(failure), + }) + + const drain = async () => { + await settle() + + while (pending.length) { + pending.shift()?.() + await settle() + } + } + + return { connection, log, sent, failures, drain } +} + +describe("terminalConnection", () => { + test("writes output received before a resize at the old size, then resets to the resize checkpoint", async () => { + const terminal = setup() + terminal.connection.restore({ size: { cols: 80, rows: 24 }, checkpoint: btoa("restored") }) + terminal.connection.message(attached()) + terminal.connection.output(encode("before")) + terminal.connection.message( + JSON.stringify({ type: "resized", cols: 100, rows: 30, generation: 2, checkpoint: btoa("checkpoint") }), + ) + terminal.connection.output(encode(" after")) + await terminal.drain() + + expect(terminal.log).toEqual([ + "resize 80x24", + "write restored", + "resize 80x24", + "write before", + "resize 100x30", + "write \x1bccheckpoint after", + ]) + }) + + test("holds input until the replay is written, then sends it at the pane's size", async () => { + const terminal = setup() + terminal.connection.size({ cols: 120, rows: 40 }) + terminal.connection.restore({ size: { cols: 80, rows: 24 }, checkpoint: btoa("restored") }) + terminal.connection.message(attached()) + terminal.connection.input("ls\r") + terminal.connection.output(encode("replayed")) + terminal.connection.message(replayComplete) + await settle() + + expect(terminal.sent).toEqual([]) + + await terminal.drain() + + expect(terminal.sent).toEqual([persistentPtyFrame({ cols: 120, rows: 40 }, encode("ls\r"))]) + }) + + test("drops replies the terminal makes while writing output", async () => { + const terminal = setup({ reply: "\x1b[0n" }) + terminal.connection.size({ cols: 120, rows: 40 }) + terminal.connection.restore({ size: { cols: 80, rows: 24 }, checkpoint: btoa("\x1b[5n") }) + terminal.connection.message(attached()) + terminal.connection.message(replayComplete) + await terminal.drain() + terminal.connection.output(encode("\x1b[5n")) + await terminal.drain() + + expect(terminal.sent).toEqual([persistentPtyFrame({ cols: 120, rows: 40 })]) + + terminal.connection.input("a") + + expect(terminal.sent).toEqual([ + persistentPtyFrame({ cols: 120, rows: 40 }), + persistentPtyFrame({ cols: 120, rows: 40 }, encode("a")), + ]) + }) + + test("stops sending its size once another client takes control, until the user interacts again", async () => { + const terminal = setup() + terminal.connection.size({ cols: 120, rows: 40 }) + terminal.connection.restore({ size: { cols: 80, rows: 24 }, checkpoint: btoa("restored") }) + terminal.connection.message(attached()) + terminal.connection.message(replayComplete) + await terminal.drain() + terminal.connection.message( + JSON.stringify({ type: "controller_changed", attachmentID: "attachment-2", generation: 2 }), + ) + terminal.connection.size({ cols: 100, rows: 30 }) + + expect(terminal.sent).toEqual([persistentPtyFrame({ cols: 120, rows: 40 })]) + + terminal.connection.interact() + + expect(terminal.sent).toEqual([ + persistentPtyFrame({ cols: 120, rows: 40 }), + persistentPtyFrame({ cols: 100, rows: 30 }), + ]) + }) + + test("reports a disconnect when the socket closes, but not after the shell exited", () => { + const open = setup() + open.connection.message(attached()) + open.connection.close() + + expect(open.failures).toEqual(["disconnected"]) + + const exited = setup() + exited.connection.message(attached()) + exited.connection.message(JSON.stringify({ type: "exited", exitCode: 0, finalOffset: 256 })) + exited.connection.close() + + expect(exited.failures).toEqual([]) + }) + + test("reports a server that does not speak input protocol 1 as out of date", () => { + const terminal = setup() + terminal.connection.message(attached({ inputProtocol: undefined })) + + expect(terminal.failures).toEqual(["outdated"]) + }) +}) diff --git a/packages/gui-plugins/src/terminal/connection.ts b/packages/gui-plugins/src/terminal/connection.ts new file mode 100644 index 000000000000..1beec6fd9ce1 --- /dev/null +++ b/packages/gui-plugins/src/terminal/connection.ts @@ -0,0 +1,158 @@ +import { decodePersistentPtyMessage, persistentPtyFrame } from "@opencode/client/solid" +import { Option } from "effect" +import { terminalWriter } from "./writer" + +export type TerminalSize = { cols: number; rows: number } + +export type TerminalFailure = "disconnected" | "failed" | "outdated" + +// One attachment to a persistent PTY, following the TUI's terminal pane: the snapshot restores the screen, then +// socket output, canonical resizes and the end of the replay apply in order through one queue. Input goes live once +// the replay completes, and size frames take control at the pane's size. +export function terminalConnection(input: { + attachmentID: string + write: (data: Uint8Array, done: VoidFunction) => void + resize: (size: TerminalSize) => void + send: (frame: Uint8Array) => void + fail: (failure: TerminalFailure) => void +}) { + const encoder = new TextEncoder() + const pendingInput: Uint8Array[] = [] + let attached = false + let controller = false + let restored = false + let wantsControl = false + let exited = false + let failed = false + let writing = false + let canonical: TerminalSize | undefined + let desired: TerminalSize | undefined + + // ghostty-web answers device and color queries itself while writing and reports the replies as input. The daemon + // already answers them, and forwarding a reply would also take control from another client. + const output = terminalWriter((data, done) => { + writing = true + input.write(data, done) + writing = false + }) + + const send = (frame: Uint8Array) => { + if (attached && !failed) input.send(frame) + } + + const interact = () => { + if (!restored) { + wantsControl = true + + return + } + + if (desired) send(persistentPtyFrame(desired)) + } + + const sendInput = (data: Uint8Array) => { + if (!restored) { + pendingInput.push(data) + + return + } + + const size = desired ?? canonical + + if (size) send(persistentPtyFrame(size, data)) + } + + // The checkpoint is a binary string: one character per byte. + const resize = (size: TerminalSize, checkpoint?: string) => { + output.push(() => { + canonical = size + input.resize(size) + }) + + if (checkpoint !== undefined) output.push(Uint8Array.from(checkpoint, (char) => char.charCodeAt(0))) + } + + const fail = (failure: TerminalFailure) => { + if (failed) return + failed = true + input.fail(failure) + } + + const message = (text: string) => { + const decoded = decodePersistentPtyMessage(text) + + if (Option.isNone(decoded)) return + const next = decoded.value + + if (next.type === "attached") { + if (next.inputProtocol !== 1) { + fail("outdated") + + return + } + + resize(next.info.size) + controller = next.role === "controller" + attached = true + + return + } + + if (next.type === "resized") { + resize({ cols: next.cols, rows: next.rows }, `\x1bc${atob(next.checkpoint)}`) + + return + } + + if (next.type === "replay_complete") { + output.push(() => { + restored = true + const queued = pendingInput.splice(0) + queued.forEach(sendInput) + + if (!queued.length && (controller || wantsControl)) interact() + wantsControl = false + }) + + return + } + + if (next.type === "controller_changed") { + const previous = controller + controller = next.attachmentID === input.attachmentID + + if (controller && !previous && restored) interact() + + return + } + + if (next.type === "exited") exited = true + } + + return { + restore(snapshot: { size: TerminalSize; checkpoint: string }) { + resize(snapshot.size, atob(snapshot.checkpoint)) + }, + output(data: Uint8Array) { + output.push(data) + }, + message, + input(data: string) { + if (writing) return + sendInput(encoder.encode(data)) + }, + interact, + size(next: TerminalSize) { + if (desired?.cols === next.cols && desired.rows === next.rows) return + desired = next + + if (controller && restored) interact() + }, + close() { + if (!exited) fail("disconnected") + }, + error() { + fail("failed") + }, + } +} diff --git a/packages/gui-plugins/src/terminal/i18n/am.ts b/packages/gui-plugins/src/terminal/i18n/am.ts index 730c9cc727a5..8b75b5993dfe 100644 --- a/packages/gui-plugins/src/terminal/i18n/am.ts +++ b/packages/gui-plugins/src/terminal/i18n/am.ts @@ -6,8 +6,5 @@ export default { loading: "በመጫን ላይ ተርሚናል…", "title.numbered": "ተርሚናል {{number}}", close: "ተርሚናል ዝጋ", - "connectionLost.title": "ግንኙነቱ ተቋርጧል", - "connectionLost.abnormalClose": "WebSocket ባልተለመደ ሁኔታ ተዘግቷል፡ {{code}}", - "connectionLost.description": "የተርሚናል ግንኙነቱ ተቋርጧል። ይህ አገልጋዩ እንደገና ሲጀምር ሊከሰት ይችላል።", "tab.title": "ተርሚናል", } diff --git a/packages/gui-plugins/src/terminal/i18n/ar.ts b/packages/gui-plugins/src/terminal/i18n/ar.ts index 415b28c0e7b3..8ae511c47e95 100644 --- a/packages/gui-plugins/src/terminal/i18n/ar.ts +++ b/packages/gui-plugins/src/terminal/i18n/ar.ts @@ -6,8 +6,5 @@ export default { loading: "جارٍ تحميل المحطة الطرفية…", "title.numbered": "محطة طرفية {{number}}", close: "إغلاق المحطة الطرفية", - "connectionLost.title": "فقد الاتصال", - "connectionLost.abnormalClose": "تم إغلاق WebSocket بشكل غير طبيعي: {{code}}", - "connectionLost.description": "انقطع اتصال المحطة الطرفية. يمكن أن يحدث هذا عند إعادة تشغيل الخادم.", "tab.title": "محطة طرفية", } diff --git a/packages/gui-plugins/src/terminal/i18n/az.ts b/packages/gui-plugins/src/terminal/i18n/az.ts index b522ec601179..8eef33167da4 100644 --- a/packages/gui-plugins/src/terminal/i18n/az.ts +++ b/packages/gui-plugins/src/terminal/i18n/az.ts @@ -6,8 +6,5 @@ export default { loading: "Terminal yüklənir…", "title.numbered": "Terminal {{number}}", close: "Terminalı bağla", - "connectionLost.title": "Bağlantı kəsildi", - "connectionLost.abnormalClose": "WebSocket anormal bağlandı: {{code}}", - "connectionLost.description": "Terminal bağlantısı kəsildi. Bu server yenidən başladıqda baş verə bilər.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/bg.ts b/packages/gui-plugins/src/terminal/i18n/bg.ts index 5277daa81937..5d471466a76d 100644 --- a/packages/gui-plugins/src/terminal/i18n/bg.ts +++ b/packages/gui-plugins/src/terminal/i18n/bg.ts @@ -6,9 +6,5 @@ export default { loading: "Терминалът се зарежда…", "title.numbered": "Терминал {{number}}", close: "Затворете терминала", - "connectionLost.title": "Загубена връзка", - "connectionLost.abnormalClose": "WebSocket затворено необичайно: {{code}}", - "connectionLost.description": - "Терминалната връзка беше прекъсната. Това може да се случи, когато сървърът се рестартира.", "tab.title": "Терминал", } diff --git a/packages/gui-plugins/src/terminal/i18n/bn.ts b/packages/gui-plugins/src/terminal/i18n/bn.ts index b957a997904b..fbf4a2f3e34a 100644 --- a/packages/gui-plugins/src/terminal/i18n/bn.ts +++ b/packages/gui-plugins/src/terminal/i18n/bn.ts @@ -6,8 +6,5 @@ export default { loading: "টার্মিনাল লোড হচ্ছে…", "title.numbered": "টার্মিনাল {{number}}", close: "টার্মিনাল বন্ধ করুন", - "connectionLost.title": "সংযোগ হারিয়েছে", - "connectionLost.abnormalClose": "WebSocket অস্বাভাবিকভাবে বন্ধ: {{code}}", - "connectionLost.description": "টার্মিনাল সংযোগ বিঘ্নিত হয়েছে। সার্ভার পুনরায় চালু হলে এটি ঘটতে পারে।", "tab.title": "টার্মিনাল", } diff --git a/packages/gui-plugins/src/terminal/i18n/br.ts b/packages/gui-plugins/src/terminal/i18n/br.ts index 9bdd723c82f8..f7a916226696 100644 --- a/packages/gui-plugins/src/terminal/i18n/br.ts +++ b/packages/gui-plugins/src/terminal/i18n/br.ts @@ -6,9 +6,5 @@ export default { loading: "Carregando terminal…", "title.numbered": "Terminal {{number}}", close: "Fechar terminal", - "connectionLost.title": "Conexão perdida", - "connectionLost.abnormalClose": "WebSocket fechado anormalmente: {{code}}", - "connectionLost.description": - "A conexão do terminal foi interrompida. Isso pode acontecer quando o servidor reinicia.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/bs.ts b/packages/gui-plugins/src/terminal/i18n/bs.ts index d7fbcc5d177d..11e6e0dcd9b7 100644 --- a/packages/gui-plugins/src/terminal/i18n/bs.ts +++ b/packages/gui-plugins/src/terminal/i18n/bs.ts @@ -6,8 +6,5 @@ export default { loading: "Učitavanje terminala…", "title.numbered": "Terminal {{number}}", close: "Zatvori terminal", - "connectionLost.title": "Veza prekinuta", - "connectionLost.abnormalClose": "WebSocket zatvoren nenormalno: {{code}}", - "connectionLost.description": "Veza s terminalom je prekinuta. Ovo se može desiti kada se server ponovo pokrene.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/ca.ts b/packages/gui-plugins/src/terminal/i18n/ca.ts index 45dc556ca711..9774488ee4f5 100644 --- a/packages/gui-plugins/src/terminal/i18n/ca.ts +++ b/packages/gui-plugins/src/terminal/i18n/ca.ts @@ -6,9 +6,5 @@ export default { loading: "S'està carregant el terminal…", "title.numbered": "Terminal {{number}}", close: "Tanca la terminal", - "connectionLost.title": "Connexió perduda", - "connectionLost.abnormalClose": "WebSocket tancat anormalment: {{code}}", - "connectionLost.description": - "La connexió del terminal s'ha interromput. Això pot passar quan es reinicia el servidor.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/cs.ts b/packages/gui-plugins/src/terminal/i18n/cs.ts index c563f995e8ee..6c8396c07539 100644 --- a/packages/gui-plugins/src/terminal/i18n/cs.ts +++ b/packages/gui-plugins/src/terminal/i18n/cs.ts @@ -6,8 +6,5 @@ export default { loading: "Načítání terminálu…", "title.numbered": "Terminál {{number}}", close: "Zavřete terminál", - "connectionLost.title": "Připojení ztraceno", - "connectionLost.abnormalClose": "WebSocket abnormálně uzavřeno: {{code}}", - "connectionLost.description": "Spojení terminálu bylo přerušeno. To se může stát, když se server restartuje.", "tab.title": "Terminál", } diff --git a/packages/gui-plugins/src/terminal/i18n/da.ts b/packages/gui-plugins/src/terminal/i18n/da.ts index ed7bab1a9b06..ac449bd636df 100644 --- a/packages/gui-plugins/src/terminal/i18n/da.ts +++ b/packages/gui-plugins/src/terminal/i18n/da.ts @@ -6,8 +6,5 @@ export default { loading: "Indlæser terminal…", "title.numbered": "Terminal {{number}}", close: "Luk terminal", - "connectionLost.title": "Forbindelse mistet", - "connectionLost.abnormalClose": "WebSocket lukkede unormalt: {{code}}", - "connectionLost.description": "Terminalforbindelsen blev afbrudt. Dette kan ske, når serveren genstarter.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/de.ts b/packages/gui-plugins/src/terminal/i18n/de.ts index d4d1cbe0f499..7865c6f74438 100644 --- a/packages/gui-plugins/src/terminal/i18n/de.ts +++ b/packages/gui-plugins/src/terminal/i18n/de.ts @@ -6,9 +6,5 @@ export default { loading: "Terminal wird geladen…", "title.numbered": "Terminal {{number}}", close: "Terminal schließen", - "connectionLost.title": "Verbindung verloren", - "connectionLost.abnormalClose": "WebSocket unerwartet geschlossen: {{code}}", - "connectionLost.description": - "Die Terminalverbindung wurde unterbrochen. Das kann passieren, wenn der Server neu startet.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/dv.ts b/packages/gui-plugins/src/terminal/i18n/dv.ts index 92457305bbc1..7acbf9c6dbce 100644 --- a/packages/gui-plugins/src/terminal/i18n/dv.ts +++ b/packages/gui-plugins/src/terminal/i18n/dv.ts @@ -6,9 +6,5 @@ export default { loading: "ލޯޑިންގ ޓާމިނަލް…", "title.numbered": "ޓާމިނަލް ⁨{{number}}⁩ އެވެ", close: "ޓާމިނަލް ބަންދުކުރުން", - "connectionLost.title": "ގުޅުން ގެއްލިއްޖެއެވެ", - "connectionLost.abnormalClose": "WebSocket އާދަޔާ ހިލާފަށް ބަންދުވެފައި: ⁨{{code}}⁩", - "connectionLost.description": - "ޓާމިނަލް ކަނެކްޝަން މެދުކެނޑުނެވެ. މިއީ ސަރވަރ އަލުން ސްޓާޓް ކުރުމުން ދިމާވެދާނެ ކަމެކެވެ.", "tab.title": "ޓާމިނަލް އެވެ", } diff --git a/packages/gui-plugins/src/terminal/i18n/dz.ts b/packages/gui-plugins/src/terminal/i18n/dz.ts index 59a02a7a2b35..48811e86e03f 100644 --- a/packages/gui-plugins/src/terminal/i18n/dz.ts +++ b/packages/gui-plugins/src/terminal/i18n/dz.ts @@ -6,9 +6,5 @@ export default { loading: "ཊར་མི་ནཱལ་མངོན་གསལ་འབད་དོ་…", "title.numbered": "ཊར་མི་ནཱལ་ {{number}}།", close: "ཊར་མི་ནཱལ་ཁ་བསྡམས།", - "connectionLost.title": "མཐུད་ལམ་བརླག་སྟོར་ཞུགས་ཡོདཔ།", - "connectionLost.abnormalClose": "WebSocket སྤྱིར་བཏང་མེན་པར་ཁ་བསྡམས: {{code}}", - "connectionLost.description": - "ཊར་མི་ནཱལ་མཐུད་ལམ་འདི་ བར་ཆད་བྱུང་ནུག། སར་བར་འདི་ལོག་འགོ་བཙུགས་པའི་སྐབས་ལུ་འདི་འབྱུང་འོང་།", "tab.title": "ཊར་མི་ནཱལ།", } diff --git a/packages/gui-plugins/src/terminal/i18n/el.ts b/packages/gui-plugins/src/terminal/i18n/el.ts index 03253090a88b..7326bf8991be 100644 --- a/packages/gui-plugins/src/terminal/i18n/el.ts +++ b/packages/gui-plugins/src/terminal/i18n/el.ts @@ -6,9 +6,5 @@ export default { loading: "Φόρτωση τερματικού…", "title.numbered": "Τερματικό {{number}}", close: "Κλείσιμο τερματικού", - "connectionLost.title": "Η σύνδεση χάθηκε", - "connectionLost.abnormalClose": "WebSocket έκλεισε ασυνήθιστα: {{code}}", - "connectionLost.description": - "Η σύνδεση τερματικού διακόπηκε. Αυτό μπορεί να συμβεί κατά την επανεκκίνηση του διακομιστή.", "tab.title": "Τερματικό", } diff --git a/packages/gui-plugins/src/terminal/i18n/en.ts b/packages/gui-plugins/src/terminal/i18n/en.ts index 41883cfa3a7e..e58fe4643666 100644 --- a/packages/gui-plugins/src/terminal/i18n/en.ts +++ b/packages/gui-plugins/src/terminal/i18n/en.ts @@ -7,9 +7,13 @@ export default { loading: "Loading terminal…", "title.numbered": "Terminal {{number}}", close: "Close terminal", - "connectionLost.title": "Connection Lost", - "connectionLost.abnormalClose": "WebSocket closed abnormally: {{code}}", - "connectionLost.description": "The terminal connection was interrupted. This can happen when the server restarts.", + "create.failed": "Couldn't create a terminal", + "create.unsupported": "This server is too old for terminals. Update OpenCode on this server.", + "rename.failed": "Couldn't rename the terminal", + "rename.unsupported": "Terminal renaming will be available after OpenCode's terminal service restarts", + disconnected: "Terminal disconnected", + connectionFailed: "Terminal connection failed", + serverOutdated: "This server is too old for terminals; update OpenCode on it", "tab.title": "Terminal", "quote.actions": "Quote selection", "quote.add": "Quote", diff --git a/packages/gui-plugins/src/terminal/i18n/es.ts b/packages/gui-plugins/src/terminal/i18n/es.ts index a62b18e7f151..963bcd03b0b7 100644 --- a/packages/gui-plugins/src/terminal/i18n/es.ts +++ b/packages/gui-plugins/src/terminal/i18n/es.ts @@ -6,9 +6,5 @@ export default { loading: "Cargando terminal…", "title.numbered": "Terminal {{number}}", close: "Cerrar terminal", - "connectionLost.title": "Conexión perdida", - "connectionLost.abnormalClose": "WebSocket cerrado anormalmente: {{code}}", - "connectionLost.description": - "La conexión del terminal se interrumpió. Esto puede ocurrir cuando el servidor se reinicia.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/et.ts b/packages/gui-plugins/src/terminal/i18n/et.ts index 67f58f20ade1..650b01c27295 100644 --- a/packages/gui-plugins/src/terminal/i18n/et.ts +++ b/packages/gui-plugins/src/terminal/i18n/et.ts @@ -6,8 +6,5 @@ export default { loading: "Terminali laadimine…", "title.numbered": "Terminal {{number}}", close: "Sulgege terminal", - "connectionLost.title": "Ühendus katkes", - "connectionLost.abnormalClose": "WebSocket on ebatavaliselt suletud: {{code}}", - "connectionLost.description": "Terminali ühendus katkes. See võib juhtuda serveri taaskäivitamisel.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/fa.ts b/packages/gui-plugins/src/terminal/i18n/fa.ts index 55c3e1267649..a308c5f737ab 100644 --- a/packages/gui-plugins/src/terminal/i18n/fa.ts +++ b/packages/gui-plugins/src/terminal/i18n/fa.ts @@ -6,8 +6,5 @@ export default { loading: "در حال بارگیری ترمینال…", "title.numbered": "ترمینال {{number}}", close: "ترمینال را ببندید", - "connectionLost.title": "اتصال قطع شد", - "connectionLost.abnormalClose": "WebSocket به طور غیر عادی بسته شد: {{code}}", - "connectionLost.description": "اتصال ترمینال قطع شد. این ممکن است زمانی اتفاق بیفتد که سرور راه اندازی مجدد شود.", "tab.title": "ترمینال", } diff --git a/packages/gui-plugins/src/terminal/i18n/fi.ts b/packages/gui-plugins/src/terminal/i18n/fi.ts index 209a536b97b9..8c7d2a85d118 100644 --- a/packages/gui-plugins/src/terminal/i18n/fi.ts +++ b/packages/gui-plugins/src/terminal/i18n/fi.ts @@ -6,8 +6,5 @@ export default { loading: "Ladataan terminaalia…", "title.numbered": "Terminaali {{number}}", close: "Sulje terminaali", - "connectionLost.title": "Yhteys katkesi", - "connectionLost.abnormalClose": "WebSocket sulkeutui poikkeavasti: {{code}}", - "connectionLost.description": "Terminaaliyhteys katkesi. Näin voi tapahtua, kun palvelin käynnistyy uudelleen.", "tab.title": "Terminaali", } diff --git a/packages/gui-plugins/src/terminal/i18n/fo.ts b/packages/gui-plugins/src/terminal/i18n/fo.ts index c197091a35d3..fc91dad5ca8d 100644 --- a/packages/gui-plugins/src/terminal/i18n/fo.ts +++ b/packages/gui-plugins/src/terminal/i18n/fo.ts @@ -6,8 +6,5 @@ export default { loading: "Innlesingarterminal…", "title.numbered": "Terminur {{number}}", close: "Lat terminalin aftur", - "connectionLost.title": "Sambandið er mist", - "connectionLost.abnormalClose": "WebSocket lukkað óvanliga: {{code}}", - "connectionLost.description": "Terminalsambandið varð avbrotið. Hetta kann henda tá ambætarin byrjar aftur.", "tab.title": "Farstøð", } diff --git a/packages/gui-plugins/src/terminal/i18n/fr.ts b/packages/gui-plugins/src/terminal/i18n/fr.ts index c28583d47e27..f50eb9d84fb1 100644 --- a/packages/gui-plugins/src/terminal/i18n/fr.ts +++ b/packages/gui-plugins/src/terminal/i18n/fr.ts @@ -6,9 +6,5 @@ export default { loading: "Chargement du terminal…", "title.numbered": "Terminal {{number}}", close: "Fermer le terminal", - "connectionLost.title": "Connexion perdue", - "connectionLost.abnormalClose": "WebSocket fermé anormalement : {{code}}", - "connectionLost.description": - "La connexion au terminal a été interrompue. Cela peut arriver lorsque le serveur redémarre.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/he.ts b/packages/gui-plugins/src/terminal/i18n/he.ts index 7c8ea345a571..a8121e827966 100644 --- a/packages/gui-plugins/src/terminal/i18n/he.ts +++ b/packages/gui-plugins/src/terminal/i18n/he.ts @@ -6,8 +6,5 @@ export default { loading: "טוען מסוף…", "title.numbered": "מסוף {{number}}", close: "סגור את המסוף", - "connectionLost.title": "החיבור אבד", - "connectionLost.abnormalClose": "WebSocket נסגר בצורה לא תקינה: {{code}}", - "connectionLost.description": "החיבור למסוף נקטע. הדבר עשוי לקרות כשהשרת מופעל מחדש.", "tab.title": "מסוף", } diff --git a/packages/gui-plugins/src/terminal/i18n/hi.ts b/packages/gui-plugins/src/terminal/i18n/hi.ts index fd9ff8313fd5..2fbb5a7dac9d 100644 --- a/packages/gui-plugins/src/terminal/i18n/hi.ts +++ b/packages/gui-plugins/src/terminal/i18n/hi.ts @@ -6,8 +6,5 @@ export default { loading: "टर्मिनल लोड हो रहा है…", "title.numbered": "टर्मिनल {{number}}", close: "टर्मिनल बंद करें", - "connectionLost.title": "कनेक्शन टूट गया", - "connectionLost.abnormalClose": "WebSocket असामान्य रूप से बंद हुआ: {{code}}", - "connectionLost.description": "टर्मिनल कनेक्शन बाधित हो गया था। ऐसा तब हो सकता है जब सर्वर पुनरारंभ हो।", "tab.title": "टर्मिनल", } diff --git a/packages/gui-plugins/src/terminal/i18n/hr.ts b/packages/gui-plugins/src/terminal/i18n/hr.ts index 5e8e3168b5a9..e7858c3c4993 100644 --- a/packages/gui-plugins/src/terminal/i18n/hr.ts +++ b/packages/gui-plugins/src/terminal/i18n/hr.ts @@ -6,8 +6,5 @@ export default { loading: "Učitavanje terminala…", "title.numbered": "Terminal {{number}}", close: "Zatvori terminal", - "connectionLost.title": "Veza izgubljena", - "connectionLost.abnormalClose": "WebSocket nenormalno zatvoren: {{code}}", - "connectionLost.description": "Veza terminala je prekinuta. To se može dogoditi kada se poslužitelj ponovno pokrene.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/hu.ts b/packages/gui-plugins/src/terminal/i18n/hu.ts index 4944fcc67584..16ac9613b2b9 100644 --- a/packages/gui-plugins/src/terminal/i18n/hu.ts +++ b/packages/gui-plugins/src/terminal/i18n/hu.ts @@ -6,8 +6,5 @@ export default { loading: "Terminál betöltése…", "title.numbered": "Terminal {{number}}", close: "Zárja be a terminált", - "connectionLost.title": "Kapcsolat megszakadt", - "connectionLost.abnormalClose": "WebSocket rendellenesen zárva: {{code}}", - "connectionLost.description": "A terminál kapcsolat megszakadt. Ez akkor fordulhat elő, amikor a szerver újraindul.", "tab.title": "Terminál", } diff --git a/packages/gui-plugins/src/terminal/i18n/hy.ts b/packages/gui-plugins/src/terminal/i18n/hy.ts index 37ec1855833f..f2202cc84637 100644 --- a/packages/gui-plugins/src/terminal/i18n/hy.ts +++ b/packages/gui-plugins/src/terminal/i18n/hy.ts @@ -6,8 +6,5 @@ export default { loading: "Բեռնվում է տերմինալը…", "title.numbered": "Տերմինալ {{number}}", close: "Փակել տերմինալը", - "connectionLost.title": "Կապը կորցրած", - "connectionLost.abnormalClose": "WebSocket փակվել է աննորմալ՝ {{code}}", - "connectionLost.description": "տերմինալի կապն ընդհատվել է։ Դա կարող է տեղի ունենալ, երբ սերվերը վերագործարկվի:", "tab.title": "Տերմինալ", } diff --git a/packages/gui-plugins/src/terminal/i18n/id.ts b/packages/gui-plugins/src/terminal/i18n/id.ts index 29bdd72c0344..7cbd164c9300 100644 --- a/packages/gui-plugins/src/terminal/i18n/id.ts +++ b/packages/gui-plugins/src/terminal/i18n/id.ts @@ -6,8 +6,5 @@ export default { loading: "Memuat terminal…", "title.numbered": "Terminal {{number}}", close: "Tutup terminal", - "connectionLost.title": "Koneksi Terputus", - "connectionLost.abnormalClose": "WebSocket ditutup secara tidak normal: {{code}}", - "connectionLost.description": "Koneksi terminal terputus. Ini bisa terjadi saat server dimulai ulang.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/is.ts b/packages/gui-plugins/src/terminal/i18n/is.ts index 86f8bb90ebde..e37a1baba959 100644 --- a/packages/gui-plugins/src/terminal/i18n/is.ts +++ b/packages/gui-plugins/src/terminal/i18n/is.ts @@ -6,8 +6,5 @@ export default { loading: "Hleður útstöð…", "title.numbered": "Skjáhermir {{number}}", close: "Lokaðu flugstöðinni", - "connectionLost.title": "Tenging rofin", - "connectionLost.abnormalClose": "WebSocket lokað óeðlilega: {{code}}", - "connectionLost.description": "Tengingin var rofin. Þetta getur gerst þegar þjónninn endurræsir sig.", "tab.title": "Skel", } diff --git a/packages/gui-plugins/src/terminal/i18n/it.ts b/packages/gui-plugins/src/terminal/i18n/it.ts index 8a53e35da58e..e80ca9cbc4d1 100644 --- a/packages/gui-plugins/src/terminal/i18n/it.ts +++ b/packages/gui-plugins/src/terminal/i18n/it.ts @@ -6,9 +6,5 @@ export default { loading: "Caricamento terminale…", "title.numbered": "Terminale {{number}}", close: "Chiudi il terminale", - "connectionLost.title": "Connessione persa", - "connectionLost.abnormalClose": "WebSocket chiuso in modo anomalo: {{code}}", - "connectionLost.description": - "La connessione del terminale è stata interrotta. Ciò può verificarsi al riavvio del server.", "tab.title": "Terminale", } diff --git a/packages/gui-plugins/src/terminal/i18n/ja.ts b/packages/gui-plugins/src/terminal/i18n/ja.ts index 337e145a6ebf..e6fa3916e6a7 100644 --- a/packages/gui-plugins/src/terminal/i18n/ja.ts +++ b/packages/gui-plugins/src/terminal/i18n/ja.ts @@ -6,9 +6,5 @@ export default { loading: "ターミナルを読み込み中…", "title.numbered": "ターミナル {{number}}", close: "ターミナルを閉じる", - "connectionLost.title": "接続が失われました", - "connectionLost.abnormalClose": "WebSocket が異常終了しました: {{code}}", - "connectionLost.description": - "ターミナルの接続が中断されました。これはサーバーが再起動したときに発生することがあります。", "tab.title": "ターミナル", } diff --git a/packages/gui-plugins/src/terminal/i18n/ka.ts b/packages/gui-plugins/src/terminal/i18n/ka.ts index bdc49e855a3c..f94962ce48e4 100644 --- a/packages/gui-plugins/src/terminal/i18n/ka.ts +++ b/packages/gui-plugins/src/terminal/i18n/ka.ts @@ -6,8 +6,5 @@ export default { loading: "იტვირთება ტერმინალი…", "title.numbered": "ტერმინალი {{number}}", close: "ტერმინალის დახურვა", - "connectionLost.title": "კავშირი დაიკარგა", - "connectionLost.abnormalClose": "WebSocket დახურულია არანორმალურად: {{code}}", - "connectionLost.description": "ტერმინალის კავშირი შეწყდა. ეს შეიძლება მოხდეს სერვერის გადატვირთვისას.", "tab.title": "ტერმინალი", } diff --git a/packages/gui-plugins/src/terminal/i18n/km.ts b/packages/gui-plugins/src/terminal/i18n/km.ts index 35780fc40501..8ef9c51f670c 100644 --- a/packages/gui-plugins/src/terminal/i18n/km.ts +++ b/packages/gui-plugins/src/terminal/i18n/km.ts @@ -6,8 +6,5 @@ export default { loading: "កំពុងផ្ទុកស្ថានីយ…", "title.numbered": "ស្ថានីយ {{number}}", close: "បិទស្ថានីយ", - "connectionLost.title": "ការតភ្ជាប់បាត់", - "connectionLost.abnormalClose": "WebSocket បានបិទមិនធម្មតា៖ {{code}}", - "connectionLost.description": "ការតភ្ជាប់ស្ថានីយត្រូវបានរំខាន។ វាអាចកើតឡើងនៅពេលដែលម៉ាស៊ីនមេចាប់ផ្តើមឡើងវិញ។", "tab.title": "ស្ថានីយ", } diff --git a/packages/gui-plugins/src/terminal/i18n/ko.ts b/packages/gui-plugins/src/terminal/i18n/ko.ts index e12de2a6ee9c..83181935f42e 100644 --- a/packages/gui-plugins/src/terminal/i18n/ko.ts +++ b/packages/gui-plugins/src/terminal/i18n/ko.ts @@ -6,8 +6,5 @@ export default { loading: "터미널 로드 중…", "title.numbered": "터미널 {{number}}", close: "터미널 닫기", - "connectionLost.title": "연결 끊김", - "connectionLost.abnormalClose": "WebSocket이 비정상적으로 닫힘: {{code}}", - "connectionLost.description": "터미널 연결이 중단되었습니다. 서버가 재시작하면 이런 일이 발생할 수 있습니다.", "tab.title": "터미널", } diff --git a/packages/gui-plugins/src/terminal/i18n/lo.ts b/packages/gui-plugins/src/terminal/i18n/lo.ts index 02d4c09c507c..d11757d641ca 100644 --- a/packages/gui-plugins/src/terminal/i18n/lo.ts +++ b/packages/gui-plugins/src/terminal/i18n/lo.ts @@ -6,8 +6,5 @@ export default { loading: "ກຳລັງໂຫຼດເຄື່ອງໃຊ້…", "title.numbered": "ສະຖານີ {{number}}", close: "ປິດ terminal", - "connectionLost.title": "ສູນເສຍການເຊື່ອມຕໍ່", - "connectionLost.abnormalClose": "WebSocket ປິດຢ່າງຜິດປົກກະຕິ: {{code}}", - "connectionLost.description": "ການເຊື່ອມຕໍ່ຢູ່ປາຍຍອດຖືກຂັດຈັງຫວະ. ອັນນີ້ສາມາດເກີດຂຶ້ນໄດ້ເມື່ອເຊີບເວີຣີສະຕາດ.", "tab.title": "ສະຖານີ", } diff --git a/packages/gui-plugins/src/terminal/i18n/lt.ts b/packages/gui-plugins/src/terminal/i18n/lt.ts index 60e318e86ed1..ea4e0030ce64 100644 --- a/packages/gui-plugins/src/terminal/i18n/lt.ts +++ b/packages/gui-plugins/src/terminal/i18n/lt.ts @@ -6,8 +6,5 @@ export default { loading: "Įkeliamas terminalas…", "title.numbered": "Terminalas {{number}}", close: "Uždarykite terminalą", - "connectionLost.title": "Ryšys nutrūko", - "connectionLost.abnormalClose": "WebSocket neįprastai uždarytas: {{code}}", - "connectionLost.description": "Terminalo ryšys nutrūko. Tai gali atsitikti, kai serveris paleidžiamas iš naujo.", "tab.title": "Terminalas", } diff --git a/packages/gui-plugins/src/terminal/i18n/lv.ts b/packages/gui-plugins/src/terminal/i18n/lv.ts index 84e96f756d52..a344f0994797 100644 --- a/packages/gui-plugins/src/terminal/i18n/lv.ts +++ b/packages/gui-plugins/src/terminal/i18n/lv.ts @@ -6,8 +6,5 @@ export default { loading: "Ielādē termināli…", "title.numbered": "Terminālis {{number}}", close: "Aizvērt termināli", - "connectionLost.title": "Savienojums zudis", - "connectionLost.abnormalClose": "WebSocket savienojums neparasti pārtraukts: {{code}}", - "connectionLost.description": "Termināļa savienojums tika pārtraukts. Tas var notikt, ja serveris tiek restartēts.", "tab.title": "Terminālis", } diff --git a/packages/gui-plugins/src/terminal/i18n/mk.ts b/packages/gui-plugins/src/terminal/i18n/mk.ts index eae42855a8a0..016876488bc5 100644 --- a/packages/gui-plugins/src/terminal/i18n/mk.ts +++ b/packages/gui-plugins/src/terminal/i18n/mk.ts @@ -6,9 +6,5 @@ export default { loading: "Се вчитува терминал…", "title.numbered": "Терминал {{number}}", close: "Затворете го терминалот", - "connectionLost.title": "Изгубена врска", - "connectionLost.abnormalClose": "WebSocket затворено ненормално: {{code}}", - "connectionLost.description": - "Приклучувањето на терминалот беше прекинато. Ова може да се случи кога серверот се рестартира.", "tab.title": "Терминал", } diff --git a/packages/gui-plugins/src/terminal/i18n/mn.ts b/packages/gui-plugins/src/terminal/i18n/mn.ts index dde1fb3e92eb..cbbad49b798c 100644 --- a/packages/gui-plugins/src/terminal/i18n/mn.ts +++ b/packages/gui-plugins/src/terminal/i18n/mn.ts @@ -6,8 +6,5 @@ export default { loading: "Терминал ачаалж байна…", "title.numbered": "Терминал {{number}}", close: "Терминалыг хаах", - "connectionLost.title": "Холболт тасарсан", - "connectionLost.abnormalClose": "WebSocket хэвийн бус хаагдсан: {{code}}", - "connectionLost.description": "Терминалын холболт тасалдсан. Энэ нь серверийг дахин эхлүүлэх үед тохиолдож болно.", "tab.title": "Терминал", } diff --git a/packages/gui-plugins/src/terminal/i18n/ms.ts b/packages/gui-plugins/src/terminal/i18n/ms.ts index 00882b393738..ea2cd55be2b5 100644 --- a/packages/gui-plugins/src/terminal/i18n/ms.ts +++ b/packages/gui-plugins/src/terminal/i18n/ms.ts @@ -6,9 +6,5 @@ export default { loading: "Memuatkan terminal…", "title.numbered": "Terminal {{number}}", close: "Tutup terminal", - "connectionLost.title": "Sambungan Terputus", - "connectionLost.abnormalClose": "WebSocket ditutup secara tidak normal: {{code}}", - "connectionLost.description": - "Sambungan terminal telah terganggu. Ini boleh berlaku apabila pelayan dimulakan semula.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/my.ts b/packages/gui-plugins/src/terminal/i18n/my.ts index b0149a70ee25..a71d06b2c348 100644 --- a/packages/gui-plugins/src/terminal/i18n/my.ts +++ b/packages/gui-plugins/src/terminal/i18n/my.ts @@ -6,9 +6,5 @@ export default { loading: "Terminal ကို ဖွင့်နေသည်…", "title.numbered": "Terminal {{number}}", close: "Terminal ကို ပိတ်ပါ", - "connectionLost.title": "ချိတ်ဆက်မှု ပြတ်တောက်သွားသည်။", - "connectionLost.abnormalClose": "WebSocket ကို ပုံမှန်မဟုတ်စွာ ပိတ်ထားသည်- {{code}}", - "connectionLost.description": - "Terminal ချိတ်ဆက်မှု ပြတ်တောက်သွားသည်။ ဆာဗာ ပြန်လည်စတင်သည့်အခါ ၎င်းသည် ဖြစ်ပေါ်လာနိုင်သည်။", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/ne.ts b/packages/gui-plugins/src/terminal/i18n/ne.ts index 7e7ac5e7dd69..d91b02cee37a 100644 --- a/packages/gui-plugins/src/terminal/i18n/ne.ts +++ b/packages/gui-plugins/src/terminal/i18n/ne.ts @@ -6,8 +6,5 @@ export default { loading: "टर्मिनल लोड गर्दै…", "title.numbered": "टर्मिनल {{number}}", close: "टर्मिनल बन्द गर्नुहोस्", - "connectionLost.title": "जडान हरायो", - "connectionLost.abnormalClose": "WebSocket असामान्य रूपमा बन्द भयो: {{code}}", - "connectionLost.description": "टर्मिनल जडान अवरुद्ध भयो। सर्भर पुन: सुरु हुँदा यो हुन सक्छ।", "tab.title": "टर्मिनल", } diff --git a/packages/gui-plugins/src/terminal/i18n/nl.ts b/packages/gui-plugins/src/terminal/i18n/nl.ts index 72bdf023c35e..15ccbbee4419 100644 --- a/packages/gui-plugins/src/terminal/i18n/nl.ts +++ b/packages/gui-plugins/src/terminal/i18n/nl.ts @@ -6,9 +6,5 @@ export default { loading: "Terminal laden…", "title.numbered": "Terminal {{number}}", close: "Terminal sluiten", - "connectionLost.title": "Verbinding verloren", - "connectionLost.abnormalClose": "WebSocket abnormaal gesloten: {{code}}", - "connectionLost.description": - "De terminalverbinding is onderbroken. Dit kan gebeuren wanneer de server opnieuw wordt opgestart.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/no.ts b/packages/gui-plugins/src/terminal/i18n/no.ts index eb055f1abd6b..21c8e916b340 100644 --- a/packages/gui-plugins/src/terminal/i18n/no.ts +++ b/packages/gui-plugins/src/terminal/i18n/no.ts @@ -6,8 +6,5 @@ export default { loading: "Laster terminal…", "title.numbered": "Terminal {{number}}", close: "Lukk terminal", - "connectionLost.title": "Tilkobling mistet", - "connectionLost.abnormalClose": "WebSocket lukket unormalt: {{code}}", - "connectionLost.description": "Terminalforbindelsen ble avbrutt. Dette kan skje når serveren starter på nytt.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/pa.ts b/packages/gui-plugins/src/terminal/i18n/pa.ts index a9fa16a6f731..a7749611bedc 100644 --- a/packages/gui-plugins/src/terminal/i18n/pa.ts +++ b/packages/gui-plugins/src/terminal/i18n/pa.ts @@ -6,8 +6,5 @@ export default { loading: "ٹرمینل لوڈ ہو رہیا اے…", "title.numbered": "Terminal ⁨{{number}}⁩", close: "ٹرمینل بند کرو", - "connectionLost.title": "کنکشن گواچ گیا", - "connectionLost.abnormalClose": "WebSocket غیر معمولی طور تے بند کیتا گیا: ⁨{{code}}⁩", - "connectionLost.description": "ٹرمینل کنکشن وچ رکاوٹ پے گئی۔ ایہ اودوں ہو سکدا اے جدوں سرور دوبارہ شروع ہوندا اے۔", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/pl.ts b/packages/gui-plugins/src/terminal/i18n/pl.ts index ae0aa47fe9ff..4199d9ee5d51 100644 --- a/packages/gui-plugins/src/terminal/i18n/pl.ts +++ b/packages/gui-plugins/src/terminal/i18n/pl.ts @@ -6,9 +6,5 @@ export default { loading: "Ładowanie terminala…", "title.numbered": "Terminal {{number}}", close: "Zamknij terminal", - "connectionLost.title": "Utracono połączenie", - "connectionLost.abnormalClose": "WebSocket zamknięty nieprawidłowo: {{code}}", - "connectionLost.description": - "Połączenie z terminalem zostało przerwane. Może się to zdarzyć podczas ponownego uruchamiania serwera.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/ro.ts b/packages/gui-plugins/src/terminal/i18n/ro.ts index 92b35ed23b33..5bc9b24df502 100644 --- a/packages/gui-plugins/src/terminal/i18n/ro.ts +++ b/packages/gui-plugins/src/terminal/i18n/ro.ts @@ -6,9 +6,5 @@ export default { loading: "Se încarcă terminalul…", "title.numbered": "Terminal {{number}}", close: "Închide terminalul", - "connectionLost.title": "Conexiune pierdută", - "connectionLost.abnormalClose": "WebSocket s-a închis anormal: {{code}}", - "connectionLost.description": - "Conexiunea la terminal a fost întreruptă. Acest lucru poate apărea când serverul repornește.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/ru.ts b/packages/gui-plugins/src/terminal/i18n/ru.ts index 2519931953fa..1dceaf8c5adf 100644 --- a/packages/gui-plugins/src/terminal/i18n/ru.ts +++ b/packages/gui-plugins/src/terminal/i18n/ru.ts @@ -6,8 +6,5 @@ export default { loading: "Загрузка терминала…", "title.numbered": "Терминал {{number}}", close: "Закрыть терминал", - "connectionLost.title": "Соединение потеряно", - "connectionLost.abnormalClose": "WebSocket закрыт аварийно: {{code}}", - "connectionLost.description": "Соединение с терминалом прервано. Это может произойти при перезапуске сервера.", "tab.title": "Терминал", } diff --git a/packages/gui-plugins/src/terminal/i18n/si.ts b/packages/gui-plugins/src/terminal/i18n/si.ts index 0f19f81a2d73..cea7cb353b65 100644 --- a/packages/gui-plugins/src/terminal/i18n/si.ts +++ b/packages/gui-plugins/src/terminal/i18n/si.ts @@ -6,8 +6,5 @@ export default { loading: "පර්යන්තය පූරණය කරමින්…", "title.numbered": "පර්යන්තය {{number}}", close: "පර්යන්තය වසන්න", - "connectionLost.title": "සම්බන්ධතාවය නැති විය", - "connectionLost.abnormalClose": "WebSocket අසාමාන්‍ය ලෙස වසා ඇත: {{code}}", - "connectionLost.description": "පර්යන්ත සම්බන්ධතාවයට බාධා ඇති විය. සේවාදායකය නැවත ආරම්භ වන විට මෙය සිදු විය හැක.", "tab.title": "පර්යන්තය", } diff --git a/packages/gui-plugins/src/terminal/i18n/sk.ts b/packages/gui-plugins/src/terminal/i18n/sk.ts index 2b2ec30339f8..d555f49eed22 100644 --- a/packages/gui-plugins/src/terminal/i18n/sk.ts +++ b/packages/gui-plugins/src/terminal/i18n/sk.ts @@ -6,8 +6,5 @@ export default { loading: "Načítava sa terminál…", "title.numbered": "Terminál {{number}}", close: "Zavrieť terminál", - "connectionLost.title": "Pripojenie prerušené", - "connectionLost.abnormalClose": "WebSocket bol abnormálne ukončený: {{code}}", - "connectionLost.description": "Pripojenie terminálu bolo prerušené. Môže sa to stať pri reštarte servera.", "tab.title": "Terminál", } diff --git a/packages/gui-plugins/src/terminal/i18n/sl.ts b/packages/gui-plugins/src/terminal/i18n/sl.ts index 71e86e0cf7d0..3a4b3509323b 100644 --- a/packages/gui-plugins/src/terminal/i18n/sl.ts +++ b/packages/gui-plugins/src/terminal/i18n/sl.ts @@ -6,9 +6,5 @@ export default { loading: "Nalaganje terminala …", "title.numbered": "Terminal {{number}}", close: "Zapri terminal", - "connectionLost.title": "Povezava je prekinjena", - "connectionLost.abnormalClose": "WebSocket zaprt nenormalno: {{code}}", - "connectionLost.description": - "Povezava s terminalom je bila prekinjena. To se lahko zgodi, ko se strežnik znova zažene.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/sq.ts b/packages/gui-plugins/src/terminal/i18n/sq.ts index 3c4d1eaf9642..598e70529be8 100644 --- a/packages/gui-plugins/src/terminal/i18n/sq.ts +++ b/packages/gui-plugins/src/terminal/i18n/sq.ts @@ -6,8 +6,5 @@ export default { loading: "Po ngarkohet terminali…", "title.numbered": "Terminali {{number}}", close: "Mbyll terminalin", - "connectionLost.title": "Lidhja e humbur", - "connectionLost.abnormalClose": "WebSocket u mbyll anormalisht: {{code}}", - "connectionLost.description": "Lidhja e terminalit u ndërpre. Kjo mund të ndodhë kur serveri riniset.", "tab.title": "Terminali", } diff --git a/packages/gui-plugins/src/terminal/i18n/sr.ts b/packages/gui-plugins/src/terminal/i18n/sr.ts index 474495bb95c6..632024220cf8 100644 --- a/packages/gui-plugins/src/terminal/i18n/sr.ts +++ b/packages/gui-plugins/src/terminal/i18n/sr.ts @@ -6,8 +6,5 @@ export default { loading: "Учитавање терминала…", "title.numbered": "Терминал {{number}}", close: "Затвори терминал", - "connectionLost.title": "Веза је изгубљена", - "connectionLost.abnormalClose": "WebSocket затворен ненормално: {{code}}", - "connectionLost.description": "Терминална веза је прекинута. Ово се може десити када се сервер поново покрене.", "tab.title": "Терминал", } diff --git a/packages/gui-plugins/src/terminal/i18n/sv.ts b/packages/gui-plugins/src/terminal/i18n/sv.ts index c41aef3b0b35..48574a53d5ba 100644 --- a/packages/gui-plugins/src/terminal/i18n/sv.ts +++ b/packages/gui-plugins/src/terminal/i18n/sv.ts @@ -6,8 +6,5 @@ export default { loading: "Laddar terminal…", "title.numbered": "Terminal {{number}}", close: "Stäng terminalen", - "connectionLost.title": "Anslutning förlorad", - "connectionLost.abnormalClose": "WebSocket stängdes onormalt: {{code}}", - "connectionLost.description": "Terminalanslutningen avbröts. Detta kan hända när servern startar om.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/tg.ts b/packages/gui-plugins/src/terminal/i18n/tg.ts index cb73c4b22d57..980b6731b2bf 100644 --- a/packages/gui-plugins/src/terminal/i18n/tg.ts +++ b/packages/gui-plugins/src/terminal/i18n/tg.ts @@ -6,8 +6,5 @@ export default { loading: "Терминал бор карда мешавад…", "title.numbered": "Терминал {{number}}", close: "Терминалро пӯшед", - "connectionLost.title": "Пайвастшавӣ гум шуд", - "connectionLost.abnormalClose": "WebSocket ғайримуқаррарӣ баста шуд: {{code}}", - "connectionLost.description": "Пайвасти терминал қатъ шуд. Ин метавонад ҳангоми аз нав оғоз шудани сервер рӯй диҳад.", "tab.title": "Терминал", } diff --git a/packages/gui-plugins/src/terminal/i18n/th.ts b/packages/gui-plugins/src/terminal/i18n/th.ts index 038ecea9af95..8f72b275c63d 100644 --- a/packages/gui-plugins/src/terminal/i18n/th.ts +++ b/packages/gui-plugins/src/terminal/i18n/th.ts @@ -6,8 +6,5 @@ export default { loading: "กำลังโหลดเทอร์มินัล…", "title.numbered": "เทอร์มินัล {{number}}", close: "ปิดเทอร์มินัล", - "connectionLost.title": "การเชื่อมต่อขาดหาย", - "connectionLost.abnormalClose": "WebSocket ปิดอย่างผิดปกติ: {{code}}", - "connectionLost.description": "การเชื่อมต่อเทอร์มินัลถูกขัดจังหวะ อาจเกิดขึ้นเมื่อเซิร์ฟเวอร์รีสตาร์ท", "tab.title": "เทอร์มินัล", } diff --git a/packages/gui-plugins/src/terminal/i18n/tk.ts b/packages/gui-plugins/src/terminal/i18n/tk.ts index 04fe86fc0ca8..d6427503f77e 100644 --- a/packages/gui-plugins/src/terminal/i18n/tk.ts +++ b/packages/gui-plugins/src/terminal/i18n/tk.ts @@ -6,8 +6,5 @@ export default { loading: "Terminal ýüklenýär …", "title.numbered": "{{number}} terminaly", close: "Terminaly ýapyň", - "connectionLost.title": "Baglanyşyk ýitdi", - "connectionLost.abnormalClose": "WebSocket adatdan daşary ýapyldy: {{code}}", - "connectionLost.description": "Terminal birikmesi kesildi. Serwer täzeden başlanda bolup biler.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/tr.ts b/packages/gui-plugins/src/terminal/i18n/tr.ts index 3ccfd7789f57..f14cd4a971a3 100644 --- a/packages/gui-plugins/src/terminal/i18n/tr.ts +++ b/packages/gui-plugins/src/terminal/i18n/tr.ts @@ -6,8 +6,5 @@ export default { loading: "Terminal yükleniyor…", "title.numbered": "Terminal {{number}}", close: "Terminali kapat", - "connectionLost.title": "Bağlantı kesildi", - "connectionLost.abnormalClose": "WebSocket anormal şekilde kapandı: {{code}}", - "connectionLost.description": "Terminal bağlantısı kesildi. Bu durum sunucu yeniden başladığında oluşabilir.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/uk.ts b/packages/gui-plugins/src/terminal/i18n/uk.ts index 0edfc7d61622..4b1fde799fed 100644 --- a/packages/gui-plugins/src/terminal/i18n/uk.ts +++ b/packages/gui-plugins/src/terminal/i18n/uk.ts @@ -6,8 +6,5 @@ export default { loading: "Завантаження термінала…", "title.numbered": "Термінал {{number}}", close: "Закрити термінал", - "connectionLost.title": "З'єднання втрачено", - "connectionLost.abnormalClose": "WebSocket закрито аномально: {{code}}", - "connectionLost.description": "З'єднання з терміналом було перервано. Це може статися під час перезапуску сервера.", "tab.title": "Термінал", } diff --git a/packages/gui-plugins/src/terminal/i18n/ur.ts b/packages/gui-plugins/src/terminal/i18n/ur.ts index 9a67fc339d00..e2736437bcdc 100644 --- a/packages/gui-plugins/src/terminal/i18n/ur.ts +++ b/packages/gui-plugins/src/terminal/i18n/ur.ts @@ -6,8 +6,5 @@ export default { loading: "ٹرمینل لوڈ ہو رہا ہے…", "title.numbered": "ٹرمینل ⁨{{number}}⁩", close: "ٹرمینل بند کریں۔", - "connectionLost.title": "کنکشن ختم ہو گیا۔", - "connectionLost.abnormalClose": "WebSocket غیر معمولی طور پر بند ہوا: ⁨{{code}}⁩", - "connectionLost.description": "ٹرمینل کنکشن میں خلل پڑا۔ یہ سرور کے دوبارہ شروع ہونے پر ہوسکتا ہے۔", "tab.title": "ٹرمینل", } diff --git a/packages/gui-plugins/src/terminal/i18n/uz.ts b/packages/gui-plugins/src/terminal/i18n/uz.ts index 55b474765e35..ef24f6bfb82b 100644 --- a/packages/gui-plugins/src/terminal/i18n/uz.ts +++ b/packages/gui-plugins/src/terminal/i18n/uz.ts @@ -6,8 +6,5 @@ export default { loading: "Terminal yuklanmoqda…", "title.numbered": "{{number}} terminali", close: "Terminalni yoping", - "connectionLost.title": "Ulanish uzildi", - "connectionLost.abnormalClose": "WebSocket anormal tarzda yopildi: {{code}}", - "connectionLost.description": "Terminal aloqasi uzildi. Bu server qayta ishga tushirilganda sodir bo'lishi mumkin.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/vi.ts b/packages/gui-plugins/src/terminal/i18n/vi.ts index f958d7835378..513339a18eb8 100644 --- a/packages/gui-plugins/src/terminal/i18n/vi.ts +++ b/packages/gui-plugins/src/terminal/i18n/vi.ts @@ -6,8 +6,5 @@ export default { loading: "Đang tải terminal…", "title.numbered": "Terminal {{number}}", close: "Đóng terminal", - "connectionLost.title": "Mất kết nối", - "connectionLost.abnormalClose": "WebSocket đóng bất thường: {{code}}", - "connectionLost.description": "Kết nối terminal bị gián đoạn. Điều này có thể xảy ra khi máy chủ khởi động lại.", "tab.title": "Terminal", } diff --git a/packages/gui-plugins/src/terminal/i18n/zh.ts b/packages/gui-plugins/src/terminal/i18n/zh.ts index 427e0bbf429a..2ee2f8883612 100644 --- a/packages/gui-plugins/src/terminal/i18n/zh.ts +++ b/packages/gui-plugins/src/terminal/i18n/zh.ts @@ -6,8 +6,5 @@ export default { loading: "正在加载终端…", "title.numbered": "终端 {{number}}", close: "关闭终端", - "connectionLost.title": "连接已丢失", - "connectionLost.abnormalClose": "WebSocket 异常关闭:{{code}}", - "connectionLost.description": "终端连接已中断。这可能发生在服务器重启时。", "tab.title": "终端", } diff --git a/packages/gui-plugins/src/terminal/i18n/zht.ts b/packages/gui-plugins/src/terminal/i18n/zht.ts index a97abd53596d..1c69fca5cc32 100644 --- a/packages/gui-plugins/src/terminal/i18n/zht.ts +++ b/packages/gui-plugins/src/terminal/i18n/zht.ts @@ -6,8 +6,5 @@ export default { loading: "正在載入終端機…", "title.numbered": "終端機 {{number}}", close: "關閉終端機", - "connectionLost.title": "連線中斷", - "connectionLost.abnormalClose": "WebSocket 異常關閉:{{code}}", - "connectionLost.description": "終端機連線已中斷。這可能會在伺服器重新啟動時發生。", "tab.title": "終端機", } diff --git a/packages/gui-plugins/src/terminal/label.tsx b/packages/gui-plugins/src/terminal/label.tsx index 207fe3ffe175..40350f7dceae 100644 --- a/packages/gui-plugins/src/terminal/label.tsx +++ b/packages/gui-plugins/src/terminal/label.tsx @@ -4,11 +4,15 @@ import { Icon } from "@opencode/ui/icon" import { Menu } from "@opencode/ui/menu" import { usePlugin } from "@opencode/plugin/gui" -/** A terminal's side panel tab label: renamed by double-click or its context menu, which also closes it. */ +/** + * A terminal's side panel tab label: renamed by double-click or its context menu, which also closes it. Without + * `rename` the terminal cannot be renamed. + */ export function TerminalTabLabel(props: { label: string title: string - rename: (title: string) => void + /** Receives the edited title, or `null` for an emptied field; unchanged titles are the receiver's to skip. */ + rename?: (title: string | null) => void close: () => void }): JSX.Element { const plugin = usePlugin() @@ -18,6 +22,7 @@ export function TerminalTabLabel(props: { let renameRequested = false const edit = () => { + if (!props.rename) return setStore({ editing: true, title: props.title }) // A blur fired while the trigger releases focus would end the edit before it starts. @@ -31,9 +36,7 @@ export function TerminalTabLabel(props: { const save = () => { if (!store.editing) return - const value = store.title.trim() - - if (value && value !== props.title) props.rename(value) + props.rename?.(store.title.trim() || null) setStore("editing", false) } @@ -41,7 +44,8 @@ export function TerminalTabLabel(props: { if (frame !== undefined) cancelAnimationFrame(frame) }) - // The label renders inside the strip's tab trigger, so the field keeps its keys and pointer from the trigger. + // The label renders inside the strip's tab trigger, so the field keeps its keys, pointer and focus from the trigger: + // the tab list returns focus that enters it from outside to the trigger. const isolate = (event: Event) => event.stopPropagation() return ( @@ -82,6 +86,7 @@ export function TerminalTabLabel(props: { setStore("editing", false) }} onKeyUp={isolate} + onFocusIn={isolate} onPointerDown={isolate} onMouseDown={isolate} onClick={isolate} @@ -98,7 +103,9 @@ export function TerminalTabLabel(props: { edit() }} > - (renameRequested = true)}>{plugin.t("common.rename")} + (renameRequested = true)}> + {plugin.t("common.rename")} + props.close()}>{plugin.t("common.close")} diff --git a/packages/gui-plugins/src/terminal/model.test.ts b/packages/gui-plugins/src/terminal/model.test.ts index ecf8b57dca7e..8b412280fe46 100644 --- a/packages/gui-plugins/src/terminal/model.test.ts +++ b/packages/gui-plugins/src/terminal/model.test.ts @@ -1,63 +1,460 @@ -import { afterEach, describe, expect, test } from "bun:test" -import { createRoot } from "solid-js" -import type { ServerRef, Sessions, Storage } from "@opencode/plugin/gui" +import { describe, expect, test } from "bun:test" +import { createStore, produce } from "solid-js/store" +import { ClientError, type PersistentPtyInfo } from "@opencode/client" +import type { Layout, ServerRef, SessionRef, Storage, ToastOptions } from "@opencode/plugin/gui" +import { PtyFeatureUnsupportedError, ServiceUnavailableError } from "@opencode/protocol/errors" import { createTerminalModel } from "./model" -// SAFETY: the workspace model reads only these members when it loads and handles focus. -// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above -const storage = { - memory: (_key: string, options: { initial: unknown }) => [options.initial], - store: () => ({ value: { all: [] }, ready: () => true }), -} as unknown as Storage +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)) -// SAFETY: load reads only sessions.list and server.id. -// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above -const sessions = { list: () => [] } as unknown as Sessions +const info = (id: string, title: string, sessionID = "ses_1"): PersistentPtyInfo => ({ + id, + title, + userTitle: null, + command: "/bin/zsh", + args: [], + cwd: "/repo", + status: "running", + pid: 1, + sessionID, + foregroundProcess: null, + size: { cols: 80, rows: 24 }, + output: { head: 0, tail: 0 }, +}) -// SAFETY: load reads only sessions.list and server.id. -// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above -const server = { id: "server" } as unknown as ServerRef +// A server with persistent terminals: its own terminal list per session, and an event stream the test drives. +function fakeServer(options: { capabilities?: { persistentPty?: boolean } } = {}) { + const terminals = new Map() + const handlers = new Map void)[]>() -const cleanups: VoidFunction[] = [] + const calls: FakeCalls = { + list: 0, + create: [], + remove: [], + update: [], + } -afterEach(() => { - cleanups.splice(0).forEach((cleanup) => cleanup()) - document.body.replaceChildren() -}) + const state: FakeState = { capabilities: options.capabilities, directory: "/repo", created: 0 } + + const server = { + id: "http://server", + data: { + on: (type: string, handler: (event: { data: EventData }) => void) => { + handlers.set(type, [...(handlers.get(type) ?? []), handler]) + + return () => + handlers.set( + type, + (handlers.get(type) ?? []).filter((item) => item !== handler), + ) + }, + session: { get: (id: string) => ({ id, location: { directory: state.directory } }) }, + }, + client: { + server: { info: async () => ({ capabilities: state.capabilities }) }, + experimental: { + persistentPty: { + list: async (input: { sessionID: string }) => { + calls.list += 1 + await state.list + + if (state.listError) throw state.listError + + return [...(terminals.get(input.sessionID) ?? [])] + }, + create: async (input: { sessionID: string; title: string; cwd?: string }) => { + calls.create.push(input) + + if (state.createError) throw state.createError + + state.created += 1 + const created = info(`pty_new${state.created}`, input.title, input.sessionID) + terminals.set(input.sessionID, [...(terminals.get(input.sessionID) ?? []), created]) + + return created + }, + remove: async (input: { ptyID: string }) => { + calls.remove.push(input.ptyID) + terminals.forEach((list, sessionID) => + terminals.set( + sessionID, + list.filter((item) => item.id !== input.ptyID), + ), + ) + }, + update: async (input: { ptyID: string; title?: string | null }) => { + calls.update.push(input) + await state.update + + if (state.updateError) throw state.updateError + + const updated = [...terminals.values()].flat().find((item) => item.id === input.ptyID)! + const next = { ...updated, title: input.title ?? "zsh", userTitle: input.title ?? null } + terminals.set( + next.sessionID, + terminals.get(next.sessionID)!.map((item) => (item.id === next.id ? next : item)), + ) + + return next + }, + }, + }, + }, + } + + return { + // SAFETY: the model reads only `id`, `data` (on, session.get) and the client calls stubbed here. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above + ref: server as unknown as ServerRef, + terminals, + calls, + state, + emit(type: string, sessionID = "ses_1", terminal?: PersistentPtyInfo) { + handlers.get(type)?.forEach((handler) => handler({ data: { sessionID, terminal } })) + }, + } +} + +type FakeCalls = { list: number; create: unknown[]; remove: string[]; update: unknown[] } + +type FakeState = { + capabilities?: { persistentPty?: boolean } + directory: string + created: number + createError?: Error + listError?: Error + updateError?: Error + update?: Promise + list?: Promise +} + +type EventData = { sessionID: string; terminal?: PersistentPtyInfo } + +function setup(server: ReturnType) { + const stored = new Map() + const opened: { key: string; session: string; tab?: string }[] = [] + const toasts: ToastOptions[] = [] + const removed: { key: string; options: Parameters[1] }[] = [] + + const storage = { + memory(_key: string, options: { initial: T }) { + const [value, set] = createStore(options.initial) + + return [value, (mutate: (draft: T) => void) => set(produce(mutate))] as const + }, + store(_key: string, options: { initial: T }) { + const [value, set] = createStore({ value: options.initial }) + + return { + get value() { + return value.value + }, + ready: () => true, + set: (next: T) => set("value", next), + update: () => undefined, + } + }, + remove: (key: string, options: Parameters[1]) => void removed.push({ key, options }), + } -const workspace = () => - createRoot((dispose) => { - cleanups.push(dispose) + const layout: Pick = { + stored: (session) => stored.get(session.key) ?? [], + open(key, session, options) { + opened.push({ key, session: session.key, tab: options?.tab }) + stored.set(session.key, [...(stored.get(session.key) ?? []), key.slice("terminal:".length)]) + }, + } - return createTerminalModel({ storage, sessions }).load({ server, directory: "/workspace" }) + const model = createTerminalModel({ + // SAFETY: the model opens only `memory`, `store` and `remove`, which these stand-ins implement. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above + storage: storage as unknown as Storage, + layout, + toast: { show: (options) => (toasts.push(options), { dismiss: () => undefined }) }, + t: (key) => key, + tab: (id) => `terminal:${id}`, }) -const field = (parent: HTMLElement) => { - const input = document.createElement("input") - parent.append(input) + const session: SessionRef = { + key: `${server.ref.id}\nses_1`, + id: "ses_1", + tab: "tab_1", + server: server.ref, + pending: false, + location: { directory: "/repo" }, + } - return input + return { model, session, stored, opened, toasts, removed } } -describe("terminal focus requests", () => { - test("survive the side region focusing its selected tab while switching terminals", () => { - const side = document.createElement("div") - side.id = "review-panel" - document.body.append(side) - const terminal = workspace() +describe("terminal model", () => { + test("is ready only once the server answers the session's first list", async () => { + const server = fakeServer() + const list = Promise.withResolvers() + server.state.list = list.promise + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + const { model, session } = setup(server) - terminal.requestFocus("pty_2") - field(side).focus() + const terminal = model.load(session) + await flush() - expect(terminal.focusRequested("pty_2")).toBe(true) + // An empty list before the first answer would let the transient strip drop restored terminal tabs. + expect(terminal.ready()).toBe(false) + expect(terminal.all()).toEqual([]) + + list.resolve() + await flush() + + expect(terminal.ready()).toBe(true) + expect(terminal.all().map((item) => item.id)).toEqual(["pty_1"]) + }) + + test("mirrors the server's list on terminal events and reconnects", async () => { + const server = fakeServer() + server.terminals.set("ses_1", [info("pty_1", "Terminal 1"), info("pty_2", "Terminal 2")]) + const { model, session } = setup(server) + const terminal = model.load(session) + await flush() + + server.terminals.set("ses_1", [info("pty_2", "Terminal 2")]) + server.emit("persistent-pty.removed") + await flush() + + // The panel lists only terminals the model knows, so the removed terminal's tab leaves the strip. + expect(terminal.get("pty_1")).toBeUndefined() + expect(terminal.all().map((item) => item.id)).toEqual(["pty_2"]) + + // Terminals that changed while the event stream was down show up after it reconnects. + server.terminals.set("ses_1", [info("pty_2", "Terminal 2"), info("pty_3", "Terminal 3")]) + server.emit("server.connected") + await flush() + + expect(terminal.all().map((item) => item.id)).toEqual(["pty_2", "pty_3"]) + + // Another session's events leave this one alone. + const calls = server.calls.list + server.emit("persistent-pty.added", "ses_other") + await flush() + + expect(server.calls.list).toBe(calls) + }) + + test("adds terminals another client created to the end of the strip without selecting them", async () => { + const server = fakeServer() + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + const { model, session, stored, opened } = setup(server) + stored.set(session.key, ["pty_1"]) + const terminal = model.load(session) + await flush() + + expect(opened).toEqual([]) + + server.terminals.set("ses_1", [info("pty_1", "Terminal 1"), info("pty_tui", "Terminal")]) + server.emit("persistent-pty.added") + await flush() + + expect(terminal.all().map((item) => item.id)).toEqual(["pty_1", "pty_tui"]) + expect(opened).toEqual([{ key: "terminal:pty_tui", session: session.key, tab: "append" }]) }) - test("are cancelled when focus leaves the side region", () => { - const terminal = workspace() + test("hides terminals on servers without persistent terminal support until a reconnect reports it", async () => { + const server = fakeServer({ capabilities: { persistentPty: false } }) + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + const { model, session } = setup(server) + + const terminal = model.load(session) + await flush() + + expect(model.available(server.ref)).toBe(false) + expect(server.calls.list).toBe(0) + expect(terminal.ready()).toBe(false) + + // Servers that predate the capability omit it and still offer terminals. + server.state.capabilities = undefined + server.emit("server.connected") + await flush() + + expect(model.available(server.ref)).toBe(true) + expect(terminal.all().map((item) => item.id)).toEqual(["pty_1"]) + }) + + test("treats a server whose terminal daemon is unavailable like one without terminal support", async () => { + const server = fakeServer() + server.state.listError = new ServiceUnavailableError({ + message: "opencode-pty is not available", + service: "opencode-pty", + }) + const { model, session } = setup(server) + + const terminal = model.load(session) + await flush() + + expect(model.available(server.ref)).toBe(false) + expect(terminal.ready()).toBe(true) + expect(terminal.all()).toEqual([]) + + server.state.listError = undefined + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + server.emit("server.connected") + await flush() + + expect(model.available(server.ref)).toBe(true) + expect(terminal.all().map((item) => item.id)).toEqual(["pty_1"]) + }) + + test("creates the next unused default title in the session's current directory and selects it", async () => { + const server = fakeServer() + server.terminals.set("ses_1", [info("pty_1", "Terminal 1"), info("pty_3", "Terminal 3"), info("pty_x", "vim")]) + const { model, session } = setup(server) + const terminal = model.load(session) + await flush() + server.state.directory = "/repo/worktree" + + const id = await terminal.new() + + expect(server.calls.create).toEqual([ + { sessionID: "ses_1", args: [], cwd: "/repo/worktree", title: "Terminal 2", env: {} }, + ]) + expect(id).toBe("pty_new1") + expect(terminal.active()).toBe("pty_new1") + expect(terminal.get("pty_new1")?.title).toBe("Terminal 2") + }) + + test("tells the user to update a server too old for persistent terminals", async () => { + const server = fakeServer() + server.state.createError = new ClientError("UnexpectedStatus", { cause: { status: 404 }, detail: "404" }) + const { model, session, toasts } = setup(server) + const terminal = model.load(session) + await flush() + + expect(await terminal.new()).toBeUndefined() + expect(toasts).toEqual([{ variant: "error", title: "create.unsupported" }]) + }) + + test("closes a terminal on the server and drops it once the server no longer lists it", async () => { + const server = fakeServer() + server.terminals.set("ses_1", [info("pty_1", "Terminal 1"), info("pty_2", "Terminal 2")]) + const { model, session } = setup(server) + const terminal = model.load(session) + await flush() + terminal.select("pty_1") + + await terminal.close("pty_1") + + expect(server.calls.remove).toEqual(["pty_1"]) + expect(terminal.all().map((item) => item.id)).toEqual(["pty_2"]) + expect(terminal.active()).toBe("pty_2") + }) + + test("labels follow another client's rename from the updated event", async () => { + const server = fakeServer() + server.terminals.set("ses_1", [info("pty_1", "Terminal 1"), info("pty_2", "Terminal 2")]) + const { model, session } = setup(server) + const terminal = model.load(session) + await flush() + const calls = server.calls.list + + server.emit("persistent-pty.updated", "ses_1", { ...info("pty_2", "build"), userTitle: "build" }) + await flush() + + // The event carries the terminal, so the label changes without listing again. + expect(terminal.get("pty_2")).toMatchObject({ title: "build", userTitle: "build" }) + expect(terminal.get("pty_1")?.title).toBe("Terminal 1") + expect(server.calls.list).toBe(calls) + + // A terminal the list hasn't seen yet arrives with a refresh. + server.terminals.set("ses_1", [...server.terminals.get("ses_1")!, info("pty_3", "Terminal 3")]) + server.emit("persistent-pty.updated", "ses_1", info("pty_3", "Terminal 3")) + await flush() + + expect(terminal.all().map((item) => item.id)).toEqual(["pty_1", "pty_2", "pty_3"]) + }) + + test("renames a terminal on the server and shows the new title right away", async () => { + const server = fakeServer() + const update = Promise.withResolvers() + server.state.update = update.promise + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + const { model, session } = setup(server) + const terminal = model.load(session) + await flush() + + const renamed = terminal.rename("pty_1", "build") + + expect(terminal.get("pty_1")?.title).toBe("build") + + update.resolve() + await renamed + + expect(server.calls.update).toEqual([{ ptyID: "pty_1", title: "build" }]) + expect(terminal.get("pty_1")).toMatchObject({ title: "build", userTitle: "build" }) + }) + + test("sends nothing for the current title or for clearing a terminal never renamed", async () => { + const server = fakeServer() + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + const { model, session } = setup(server) + const terminal = model.load(session) + await flush() + + await terminal.rename("pty_1", "Terminal 1") + await terminal.rename("pty_1", null) + + expect(server.calls.update).toEqual([]) + }) + + test("clears a user title with null so the server's fallback title shows", async () => { + const server = fakeServer() + server.terminals.set("ses_1", [{ ...info("pty_1", "build"), userTitle: "build" }]) + const { model, session } = setup(server) + const terminal = model.load(session) + await flush() + + await terminal.rename("pty_1", null) + + expect(server.calls.update).toEqual([{ ptyID: "pty_1", title: null }]) + expect(terminal.get("pty_1")).toMatchObject({ title: "zsh", userTitle: null }) + }) + + test("tells the user renaming waits for the terminal service to restart and restores the title", async () => { + const server = fakeServer() + server.state.updateError = new PtyFeatureUnsupportedError({ feature: "rename", message: "rename unsupported" }) + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + const { model, session, toasts } = setup(server) + const terminal = model.load(session) + await flush() + + await terminal.rename("pty_1", "build") + + expect(toasts).toEqual([{ variant: "error", title: "rename.unsupported" }]) + expect(terminal.get("pty_1")).toMatchObject({ title: "Terminal 1", userTitle: null }) + }) + + test("shows other rename failures as a generic error", async () => { + const server = fakeServer() + server.state.updateError = new Error("boom") + server.terminals.set("ses_1", [info("pty_1", "Terminal 1")]) + const { model, session, toasts } = setup(server) + const terminal = model.load(session) + await flush() + + await terminal.rename("pty_1", "build") + + expect(toasts).toEqual([{ variant: "error", title: "rename.failed", description: "boom" }]) + expect(terminal.get("pty_1")?.title).toBe("Terminal 1") + }) - terminal.requestFocus("pty_2") - field(document.body).focus() + test("drops the terminals stored before they lived on the server", async () => { + const server = fakeServer() + const { model, session, removed } = setup(server) + model.load(session) + await flush() - expect(terminal.focusRequested("pty_2")).toBe(false) + expect(removed).toEqual([ + { + key: "terminals", + options: { scope: { server: server.ref.id, directory: "/repo" }, from: "workspace:terminal" }, + }, + ]) }) }) diff --git a/packages/gui-plugins/src/terminal/model.ts b/packages/gui-plugins/src/terminal/model.ts index 21660c8564e4..a4a9ee0c7afa 100644 --- a/packages/gui-plugins/src/terminal/model.ts +++ b/packages/gui-plugins/src/terminal/model.ts @@ -1,415 +1,432 @@ -import { batch, createMemo, createRoot, getOwner, onCleanup, untrack } from "solid-js" +import { createRoot, getOwner, runWithOwner, type Owner } from "solid-js" import { createStore } from "solid-js/store" +import { Predicate, Schema } from "effect" +import { + ClientError, + isPtyFeatureUnsupportedError, + isServiceUnavailableError, + type PersistentPtyInfo, +} from "@opencode/client" import { createKeyed, - type Mutable, - type Storage, + type Layout, + type Persisted, type ServerRef, - type MountedSession, - type Sessions, + type SessionRef, + type Storage, + type Toasts, } from "@opencode/plugin/gui" -import { MAX_TERMINAL_SESSIONS, numberFromTitle, TerminalState, terminalTab, type LocalPTY } from "./state" -import { defaultTitle } from "./title" - -const STORE = "terminals" +import { defaultTitle, titleNumber } from "./title" -// The raw key terminals used before plugins, in the same workspace storage file. -const LEGACY = "workspace:terminal" +// The keys terminals were stored under before they lived on the server. Their PTY ids no longer exist anywhere. +const LEGACY = { key: "terminals", from: "workspace:terminal" } -const HANDOFF_MAX = 40 +const Selected = Schema.Struct({ id: Schema.optional(Schema.String) }) export type TerminalModel = ReturnType -export type TerminalWorkspace = ReturnType +export type TerminalSession = ReturnType -type CacheEntry = { - value: TerminalWorkspace - dispose: VoidFunction -} - -type FocusRequest = { request: number; id?: string; pending: boolean } +type FocusRequest = { key: string; request: number; id?: string; pending: boolean } const importGhostty = () => import("ghostty-web").then(async (mod) => ({ mod, ghostty: await mod.Ghostty.load() })) /** The one ghostty-web load the window's terminals share; a failed load is retried by the next terminal. */ type Ghostty = { shared?: ReturnType } -const workspaceKey = (server: string, directory: string) => `${server}\0${directory}` +/** + * Mirrors each session's terminals from its server, like the TUI: the server's list is the only record of which + * terminals exist, refreshed on its terminal events and on every reconnect. Only the selected terminal per session is + * stored. + */ +export function createTerminalModel(input: { + storage: Storage + layout: Pick + toast: Pick + t: (key: string) => string + /** The panel key of a terminal's side panel tab. */ + tab: (ptyID: string) => string +}) { + const owner = getOwner() -const trimTerminal = (pty: Mutable) => { - if (!pty.buffer && pty.cursor === undefined && pty.scrollY === undefined) return + const [lists, setLists] = input.storage.memory<{ sessions: Record }>("lists", { + initial: { sessions: {} }, + }) - pty.buffer = undefined - pty.cursor = undefined - pty.scrollY = undefined -} + const [state, setState] = createStore<{ capabilities: Record; focus?: FocusRequest }>({ + capabilities: {}, + }) -export function createTerminalModel(input: { storage: Storage; sessions: Sessions }) { - const owner = getOwner() - const cache = new Map() - const [handoff] = input.storage.memory("handoff", { initial: { terminal: new Map() } }) + const sessions = new Map() + const handles = new Map>() + const selected = new Map>() + const sequence = new Map() + const watched = new Map() + const cleared = new Set() + const cleanups: VoidFunction[] = [] const ghostty: Ghostty = {} + const focus = { request: 0 } - const prune = () => { - while (cache.size > MAX_TERMINAL_SESSIONS) { - const first = cache.keys().next().value - - if (!first) return - - const entry = cache.get(first) + const available = (server: ServerRef) => { + watch(server) - entry?.dispose() - cache.delete(first) - } + return state.capabilities[server.id] !== false } - return { - load(session: Pick) { - // Terminals are workspace-scoped so tabs persist while switching sessions in the same directory. - const key = workspaceKey(session.server.id, session.directory) - const existing = cache.get(key) + const refresh = async (session: SessionRef) => { + const next = (sequence.get(session.key) ?? 0) + 1 - if (existing) { - cache.delete(key) - cache.set(key, existing) + sequence.set(session.key, next) + const list = await session.server.client.experimental.persistentPty.list({ sessionID: session.id }) - return existing.value - } + // A newer refresh started meanwhile; its answer wins. + if (sequence.get(session.key) !== next) return + setLists((draft) => void (draft.sessions[session.key] = list)) + dropLegacy(session) + // The strip shows only stored tabs, so terminals another client created join it at the end. + const stored = new Set(input.layout.stored(session)) - // A cached workspace keeps talking to its own server after the route moves on. - const server = - untrack(() => input.sessions.list()).find((ref) => ref.server.id === session.server.id)?.server ?? - session.server + list.forEach((info) => { + if (!stored.has(info.id)) input.layout.open(input.tab(info.id), session, { tab: "append" }) + }) + } - const directory = session.directory + // Replaces a listed terminal's info; a terminal the list doesn't have yet arrives with the next refresh. + const replace = (key: string, terminal: PersistentPtyInfo) => + setLists((draft) => { + const list = draft.sessions[key] + const index = list?.findIndex((info) => info.id === terminal.id) ?? -1 - const entry = createRoot( - (dispose) => ({ value: createWorkspace({ storage: input.storage, server, directory, key }), dispose }), - owner, - ) + if (list && index !== -1) draft.sessions[key] = list.with(index, terminal) + }) - cache.set(key, entry) - prune() + // A server whose terminal daemon can't run answers 503; like a server reporting no support, it offers no terminals + // until the next connection checks again. + const listed = (session: SessionRef) => + refresh(session).catch((error) => { + if (!isServiceUnavailableError(error)) return console.error("Failed to list terminals", error) + setState("capabilities", session.server.id, false) + setLists((draft) => void (draft.sessions[session.key] = [])) + }) - return entry.value - }, - ghostty() { - if (ghostty.shared) return ghostty.shared + const refreshQuietly = (session: SessionRef) => void listed(session) - ghostty.shared = importGhostty().catch((err) => { - ghostty.shared = undefined - throw err - }) + const refreshServer = (server: ServerRef) => + sessions.forEach((session) => { + if (session.server.id === server.id) refreshQuietly(session) + }) - return ghostty.shared - }, - handoff: { - set(key: string, value: string[]) { - const map = handoff.terminal + const sync = (server: ServerRef) => + void server.client.server + .info() + .then((info) => { + // Servers that predate the field omit it; they still offer terminals. + const supported = info.capabilities?.persistentPty !== false - map.delete(key) - map.set(key, value) + setState("capabilities", server.id, supported) - while (map.size > HANDOFF_MAX) { - const first = map.keys().next().value + if (supported) refreshServer(server) + }) + .catch((error) => console.error("Failed to read server terminal support", error)) - if (first === undefined) return + // A restarted server replaces its data under the same ref, so reads that track `server.data` subscribe again. + const watch = (server: ServerRef) => { + const data = server.data + const current = watched.get(server.id) - map.delete(first) - } - }, - get: (key: string) => handoff.terminal.get(key), - }, - remove(value: { readonly server: string; readonly directory: string }) { - cache.get(workspaceKey(value.server, value.directory))?.value.clear() - // Also drops terminals saved before plugins, which opening the store would otherwise import. - input.storage.remove(STORE, { scope: { server: value.server, directory: value.directory }, from: LEGACY }) - }, - dispose() { - for (const entry of cache.values()) { - entry.dispose() - } + if (current?.data === data) return + current?.stop() - cache.clear() - }, - } -} + const refreshSession = (sessionID: string) => { + const session = sessions.get(`${server.id}\n${sessionID}`) -function createWorkspace(input: { storage: Storage; server: ServerRef; directory: string; key: string }) { - const location = { directory: input.directory } + if (session && state.capabilities[server.id]) refreshQuietly(session) + } - const stored = input.storage.store(STORE, { - schema: TerminalState, - initial: { all: [] }, - scope: { server: input.server.id, directory: input.directory }, - from: LEGACY, - }) + // Subscriptions end with the owner they start under, and this runs from whichever computation first read the + // server, so they belong to the model. + const stops = runWithOwner(owner, () => [ + // The event stream opens with server.connected, so this runs for the first connection and every reconnect. + data.on("server.connected", () => sync(server)), + data.on("persistent-pty.added", (event) => refreshSession(event.data.sessionID)), + data.on("persistent-pty.removed", (event) => refreshSession(event.data.sessionID)), + data.on("persistent-pty.updated", (event) => { + const key = `${server.id}\n${event.data.sessionID}` - // Empty until the stored terminals load; changes made before then apply over them in order. - const all = createMemo(() => stored.value?.all ?? []) - const active = createMemo(() => stored.value?.active) - const [ui, setUi] = createStore<{ focus?: FocusRequest }>({}) - const focus = { request: 0 } + if (!lists.sessions[key]?.some((info) => info.id === event.data.terminal.id)) + return refreshSession(event.data.sessionID) - const requestFocus = (id?: string, pending = false) => { - focus.request += 1 - setUi("focus", { request: focus.request, id, pending }) + replace(key, event.data.terminal) + }), + ])! - return focus.request + watched.set(server.id, { data, stop: () => stops.forEach((stop) => stop()) }) + sync(server) } - const focusRequested = (id?: string) => { - if (!id) return false + const selection = (session: SessionRef) => { + const existing = selected.get(session.key) + + if (existing) return existing + + // Opened from reactive reads, so it belongs to the model rather than the computation that first asked. + const created = runWithOwner(owner, () => + input.storage.store("selected", { schema: Selected, initial: {}, scope: { session } }), + )! - if (!ui.focus || ui.focus.pending) return false + selected.set(session.key, created) - return !ui.focus.id || ui.focus.id === id + return created } - const consumeFocus = (id: string) => { - if (!focusRequested(id)) return + const requestFocus = (key: string, id?: string, pending = false) => { + focus.request += 1 + setState("focus", { key, request: focus.request, id, pending }) - setUi("focus", undefined) + return focus.request } const cancelFocus = (request?: number) => { - if (request !== undefined && ui.focus?.request !== request) return + if (request !== undefined && state.focus?.request !== request) return - setUi("focus", undefined) + setState("focus", undefined) } if (typeof document !== "undefined") { const cancelOnOutsideFocus = (event: FocusEvent) => { - if (!ui.focus) return + if (!state.focus) return if (!(event.target instanceof Element)) return - // The side region focuses its selected tab trigger or root while switching tabs; only focus leaving it cancels. - if (event.target.closest("#terminal-panel, #review-panel")) return + // The side region focuses its selected tab trigger or root while switching tabs; only focus leaving it, or + // entering a field in it such as a tab's rename field, cancels. + if (event.target.closest("#terminal-panel, #review-panel") && !(event.target instanceof HTMLInputElement)) return cancelFocus() } - document.addEventListener("focusin", cancelOnOutsideFocus) - onCleanup(() => document.removeEventListener("focusin", cancelOnOutsideFocus)) - } - - const pickNextTerminalNumber = () => { - const existingTitleNumbers = new Set( - all().flatMap((pty) => { - const direct = Number.isFinite(pty.titleNumber) && pty.titleNumber > 0 ? pty.titleNumber : undefined - - if (direct !== undefined) return [direct] - - const parsed = numberFromTitle(pty.title) - - if (parsed === undefined) return [] - - return [parsed] - }), - ) - - return ( - Array.from({ length: existingTitleNumbers.size + 1 }, (_, index) => index + 1).find( - (number) => !existingTitleNumbers.has(number), - ) ?? 1 - ) + // Capture phase: a tab's rename field stops its focusin from bubbling. + document.addEventListener("focusin", cancelOnOutsideFocus, true) + cleanups.push(() => document.removeEventListener("focusin", cancelOnOutsideFocus, true)) } - const removeExited = (id: string) => { - const list = all() - const index = list.findIndex((x) => x.id === id) + const handle = (initial: SessionRef) => { + const key = initial.key + // A removed workspace forgets its session, while a component may still hold the handle. + const session = () => sessions.get(key) ?? initial + const all = () => lists.sessions[key] ?? [] + const get = (id: string) => all().find((info) => info.id === id) - if (index === -1) return + const focusRequested = (id?: string) => { + if (!id || !state.focus || state.focus.pending || state.focus.key !== key) return false - const next = active() === id ? (index === 0 ? list[1]?.id : list[0]?.id) : active() - - stored.update((draft) => { - draft.active = next - draft.all.splice(index, 1) - }) - } - - // A restarted server replaces its data under the same ref, so the subscription follows it. - createKeyed( - () => input.server.data, - (data) => - onCleanup( - data.on("pty.exited", (event) => { - if (event.location?.directory !== input.directory) return - - removeExited(event.data.id) - }), - ), - ) - - const update = (pty: Partial & { id: string }) => { - const index = all().findIndex((x) => x.id === pty.id) - const previous = index >= 0 ? all()[index] : undefined - - if (index >= 0) { - stored.update((draft) => void Object.assign(draft.all[index], pty)) + return !state.focus.id || state.focus.id === id } - const doUpdate = async () => { - await input.server.client.pty.update({ - ptyID: pty.id, - location, - title: pty.title, - size: pty.cols && pty.rows ? { rows: pty.rows, cols: pty.cols } : undefined, - }) - } - - doUpdate().catch((error) => { - if (previous) { - const currentIndex = all().findIndex((item) => item.id === pty.id) - - if (currentIndex >= 0) stored.update((draft) => void Object.assign(draft.all[currentIndex], previous)) - } - - console.error("Failed to update terminal", error) - }) - } - - const clone = async (id: string) => { - const index = all().findIndex((x) => x.id === id) - const pty = all()[index] + return { + key, + server: () => session().server, + /** The server answered this session's first terminal list. */ + ready: () => lists.sessions[key] !== undefined, + /** The session's terminals, in the server's order. */ + all, + get, + /** The selected terminal, else the first one. */ + active() { + const id = selection(session()).value?.id + + return id && get(id) ? id : all()[0]?.id + }, + select(id: string) { + selection(session()).set({ id }) + }, + refresh: () => refresh(session()), + /** Creates a terminal and selects it; resolves its id, or undefined when the server refuses. */ + async new() { + const target = session() + const request = requestFocus(key, undefined, true) + + await settled(target, owner) + + // The next default title counts the terminals the server already has. + if (lists.sessions[key] === undefined) await refresh(target).catch(() => undefined) + + const used = new Set(all().flatMap((info) => titleNumber(info.title) ?? [])) + const number = Array.from({ length: used.size + 1 }, (_, index) => index + 1).find((n) => !used.has(n)) ?? 1 + + const info = await target.server.client.experimental.persistentPty + .create({ + sessionID: target.id, + args: [], + // A session that moved keeps its object; the server's record has the directory it runs in now. + cwd: target.server.data.session.get(target.id)?.location.directory ?? target.location?.directory, + title: defaultTitle(number), + env: {}, + }) + .catch((error) => { + cancelFocus(request) + + // A server without the persistent terminal routes answers with a status its API never declares for them. + const outdated = + error instanceof ClientError && + error.reason === "UnexpectedStatus" && + Predicate.hasProperty(error.cause, "status") && + (error.cause.status === 404 || error.cause.status === 405) + + input.toast.show( + outdated + ? { variant: "error", title: input.t("create.unsupported") } + : { + variant: "error", + title: input.t("create.failed"), + description: error instanceof Error ? error.message : String(error), + }, + ) - if (!pty) return + return undefined + }) - const data = await input.server.client.pty - .create({ location, title: pty.title }) - .then((result) => result.data) - .catch((error) => { - console.error("Failed to clone terminal", error) + if (!info) return undefined - return undefined - }) + await listed(target) + selection(target).set({ id: info.id }) - if (!data?.id) return - - const wasActive = active() === pty.id - - stored.update((draft) => { - Object.assign(draft.all[index], { - id: data.id, - tab: terminalTab(pty), - title: data.title ?? pty.title, - titleNumber: pty.titleNumber, - buffer: undefined, - cursor: undefined, - scrollY: undefined, - rows: undefined, - cols: undefined, - }) + if (state.focus?.request === request) setState("focus", { key, request, id: info.id, pending: false }) - if (wasActive) draft.active = data.id - }) + return info.id + }, + /** Removes the terminal on the server; its tab leaves once the server lists it no longer. */ + async close(id: string) { + const target = session() + + await target.server.client.experimental.persistentPty + .remove({ ptyID: id }) + .then(() => refresh(target)) + .catch((error) => console.error("Failed to close terminal", error)) + }, + /** + * Sets the terminal's title on the server; `null` clears it, so the shell's or the default title shows again. + * The current title, or clearing a terminal never renamed, sends nothing. + */ + async rename(id: string, title: string | null) { + const target = session() + const previous = get(id) + + if (!previous || title === previous.title || (title === null && previous.userTitle === null)) return + + // Only a new title is known before the server answers; a cleared one shows whatever the server falls back to. + if (title !== null) replace(key, { ...previous, title, userTitle: title }) + + await target.server.client.experimental.persistentPty + .update({ ptyID: id, title }) + .then((info) => replace(key, info)) + .catch((error) => { + // A newer title from the server stays. + if (title !== null && get(id)?.userTitle === title) replace(key, previous) + input.toast.show( + isPtyFeatureUnsupportedError(error) + ? { variant: "error", title: input.t("rename.unsupported") } + : { + variant: "error", + title: input.t("rename.failed"), + description: error instanceof Error ? error.message : String(error), + }, + ) + }) + }, + requestFocus(id?: string) { + requestFocus(key, id) + }, + focusRequested, + consumeFocus(id: string) { + if (focusRequested(id)) setState("focus", undefined) + }, + cancelFocus() { + if (state.focus?.key === key) cancelFocus() + }, + } } return { - key: input.key, - // An accessor, so storing the workspace in a Solid store never unwraps the host's server data. - server: () => input.server, - directory: input.directory, - ready: () => stored.ready(), - all, - active, - clear() { - stored.set({ active: undefined, all: [] }) - }, - /** Creates a terminal and makes it the active one; resolves its id, or undefined when the server refuses. */ - new() { - const nextNumber = pickNextTerminalNumber() - const focusRequest = requestFocus(undefined, true) + /** The server offers terminals. Servers that predate the capability count as offering them. */ + available, + /** The session's terminals; the first load lists them from its server. */ + load(session: SessionRef) { + sessions.set(session.key, session) + watch(session.server) - return input.server.client.pty - .create({ location, title: defaultTitle(nextNumber) }) - .then((result) => { - const id = result.data?.id + const existing = handles.get(session.key) - if (!id) { - cancelFocus(focusRequest) + if (existing) return existing - return undefined - } + const created = handle(session) - batch(() => { - stored.update((draft) => { - draft.all.push({ id, title: result.data?.title ?? defaultTitle(nextNumber), titleNumber: nextNumber }) - draft.active = id - }) + handles.set(session.key, created) - if (ui.focus?.request === focusRequest) { - setUi("focus", { request: focusRequest, id, pending: false }) - } - }) - - return id - }) - .catch((error) => { - cancelFocus(focusRequest) - console.error("Failed to create terminal", error) + // Until the server's support is known, the check that reads it lists every loaded session. + if (state.capabilities[session.server.id]) refreshQuietly(session) - return undefined - }) + return created }, - update, - trim(id: string) { - const index = all().findIndex((x) => x.id === id) - - if (index === -1) return + ghostty() { + if (ghostty.shared) return ghostty.shared - stored.update((draft) => { - trimTerminal(draft.all[index]) - }) - }, - trimAll() { - stored.update((draft) => { - draft.all.forEach(trimTerminal) + ghostty.shared = importGhostty().catch((err) => { + ghostty.shared = undefined + throw err }) + + return ghostty.shared }, - clone, - /** The terminal whose side panel tab has this id. */ - byTab: (tab: string) => all().find((pty) => terminalTab(pty) === tab), - open(id: string) { - stored.update((draft) => { - draft.active = id + /** Forgets the terminal lists of a removed workspace's sessions. */ + remove(value: { readonly server: string; readonly directory: string }) { + input.storage.remove(LEGACY.key, { scope: value, from: LEGACY.from }) + sessions.forEach((session, key) => { + if (session.server.id !== value.server || session.location?.directory !== value.directory) return + + setLists((draft) => void delete draft.sessions[key]) + sessions.delete(key) + handles.delete(key) + selected.delete(key) + sequence.delete(key) }) }, - requestFocus(id?: string) { - requestFocus(id) - }, - focusRequested, - consumeFocus, - cancelFocus() { - cancelFocus() + dispose() { + watched.forEach((entry) => entry.stop()) + watched.clear() + cleanups.forEach((cleanup) => cleanup()) }, - async close(id: string) { - const index = all().findIndex((f) => f.id === id) + } - if (index !== -1) { - stored.update((draft) => { - if (draft.active === id) { - draft.active = index > 0 ? draft.all[index - 1]?.id : draft.all[1]?.id - } + function dropLegacy(session: SessionRef) { + const directory = session.location?.directory - draft.all.splice(index, 1) - }) - } + if (!directory) return - await input.server.client.pty.remove({ ptyID: id, location }).catch((error) => { - console.error("Failed to close terminal", error) - }) - }, - move(id: string, to: number) { - const index = all().findIndex((f) => f.id === id) + const id = `${session.server.id}\0${directory}` - if (index === -1) return + if (cleared.has(id)) return - stored.update((draft) => { - draft.all.splice(to, 0, draft.all.splice(index, 1)[0]) - }) - }, + cleared.add(id) + input.storage.remove(LEGACY.key, { scope: { server: session.server.id, directory }, from: LEGACY.from }) } } + +/** Resolves once the server has created the session. */ +function settled(session: SessionRef, owner: Owner | null) { + if (!session.pending) return Promise.resolve() + + return new Promise((resolve) => + createRoot( + (dispose) => + createKeyed( + () => !session.pending, + () => { + dispose() + resolve() + }, + ), + owner, + ), + ) +} diff --git a/packages/gui-plugins/src/terminal/panel.tsx b/packages/gui-plugins/src/terminal/panel.tsx index 9e4e8a1bf044..decedc9b46f9 100644 --- a/packages/gui-plugins/src/terminal/panel.tsx +++ b/packages/gui-plugins/src/terminal/panel.tsx @@ -1,45 +1,37 @@ -import { For, Show, createMemo, onCleanup, onMount } from "solid-js" +import { For, Show, createMemo, onCleanup } from "solid-js" import { createStore } from "solid-js/store" -import { makeEventListener } from "@solid-primitives/event-listener" -import { DragDropProvider, PointerSensor } from "@dnd-kit/solid" -import { isSortable } from "@dnd-kit/solid/sortable" -import { Accessibility, AutoScroller, Feedback, PointerActivationConstraints } from "@dnd-kit/dom" -import { RestrictToHorizontalAxis } from "@dnd-kit/abstract/modifiers" -import { RestrictToElement } from "@dnd-kit/dom/modifiers" import { Tabs } from "@opencode/ui/tabs" import { IconButton } from "@opencode/ui/icon-button" import { Icon } from "@opencode/ui/icon" import { Tooltip } from "@opencode/ui/tooltip" import { Keybind } from "@opencode/ui/keybind" import { uuid } from "@opencode/util/uuid" -import { createKeyed, usePlugin, usePanel, type MountedSession, type SessionScreen } from "@opencode/plugin/gui" -import type { TerminalModel, TerminalWorkspace } from "./model" -import { terminalTab, type LocalPTY } from "./state" -import { SortableTerminalTab } from "./tab" +import { + createKeyed, + usePlugin, + usePanel, + type MountedSession, + type ServerRef, + type SessionScreen, +} from "@opencode/plugin/gui" +import type { TerminalModel } from "./model" +import { TerminalTab } from "./tab" import { Terminal } from "./terminal" -import { terminalTabLabel } from "./title" import { focusTerminalById } from "./focus" import type { TerminalQuoteTarget } from "./quote" -const MAX_CACHED_TERMINAL_WORKSPACES = 20 - -type CachedTerminalSurface = { - key: string - workspace: string - pty: LocalPTY - ops: TerminalWorkspace - focus: boolean -} - -type TerminalPanelState = { - recovered: Record - surfaces: CachedTerminalSurface[] - workspaces: string[] +type TerminalSurface = { + session: string + id: string + // The connection ended. Like the TUI, a terminal doesn't reconnect; showing it again mounts it anew. + failed?: boolean + // An accessor, so the store never wraps the host's server ref. + server: () => ServerRef } /** - * The terminals of the routed session's workspace. In the side region each terminal is its own strip tab and `tab` - * names the one to show; the narrow-screen view has no strip, so it lists the terminals in its own tabs. + * The routed session's terminals. In the side region each terminal is its own strip tab and `tab` names the one to + * show; the narrow-screen view has no strip, so it lists the terminals in its own tabs. */ export default function TerminalPanel(props: { model: TerminalModel @@ -51,12 +43,10 @@ export default function TerminalPanel(props: { const keybinds = plugin.keybinds const frame = usePanel() const terminal = createMemo(() => props.model.load(props.session)) - const workspaceKey = () => terminal().key const opened = frame.visible const present = frame.present const mobile = () => frame.placement() === "mobile" - const active = () => (mobile() ? terminal().active() : terminal().byTab(props.tab())?.id) - let tabList: HTMLDivElement | undefined + const active = () => (mobile() ? terminal().active() : terminal().get(props.tab())?.id) // Selected output quotes into the composer of the screen showing this panel. const quote: TerminalQuoteTarget = { @@ -77,37 +67,29 @@ export default function TerminalPanel(props: { onCleanup(() => terminal().cancelFocus()) - const [store, setStore] = createStore({ recovered: {}, surfaces: [], workspaces: [] }) + const [store, setStore] = createStore<{ surfaces: TerminalSurface[] }>({ surfaces: [] }) const newTerminalKeybind = createMemo(() => [...keybinds.keybind("terminal.new")]) - onMount(() => { - makeEventListener(document, "focusin", (event) => { - if (event.target instanceof Element && event.target.closest("#terminal-panel")) return - - setStore("surfaces", (surface) => surface.focus, "focus", false) - }) - }) - - // While the narrow-screen view shows, a workspace first observed empty gets its first terminal, once per workspace in - // a row. In the side region the user opens each terminal from the strip. + // While the narrow-screen view shows, a session first observed empty gets its first terminal, once per session in a + // row. In the side region the user opens each terminal from the strip. createKeyed( () => opened() && mobile(), () => { - const seen = { workspace: "" } + const seen = { session: "" } createKeyed( () => { - const workspace = terminal() + const session = terminal() - return workspace.ready() ? workspace : undefined + return session.ready() ? session : undefined }, - (workspace) => { - if (seen.workspace === workspace.key) return + (session) => { + if (seen.session === session.key) return - seen.workspace = workspace.key + seen.session = session.key - if (workspace.all().length === 0) void workspace.new() + if (session.all().length === 0) void session.new() }, ) }, @@ -125,39 +107,12 @@ export default function TerminalPanel(props: { if (!opened() || active() !== request.id || !terminal().focusRequested(request.id)) return focusTerminalById(request.id) - }), - ) - - // The titles outlive this instance: after a reload they show until the stored terminals load. - createKeyed( - () => { - if (!props.session.directory || !terminal().ready()) return + const input = document.getElementById(`terminal-wrapper-${request.id}`)?.querySelector("textarea") - return { - workspace: workspaceKey(), - titles: terminal() - .all() - .map((pty) => terminalTabLabel({ title: pty.title, titleNumber: pty.titleNumber, t: plugin.t })), - } - }, - (handoff) => props.model.handoff.set(handoff.workspace, handoff.titles), - { - // A terminal changing anything but its title keeps the titles. - equals: (previous, next) => - previous.workspace === next.workspace && - previous.titles.length === next.titles.length && - previous.titles.every((title, index) => title === next.titles[index]), - }, + if (input === document.activeElement) terminal().consumeFocus(request.id) + }), ) - const handoff = createMemo(() => { - const dir = props.session.directory - - if (!dir) return [] - - return props.model.handoff.get(workspaceKey()) ?? [] - }) - // Terminals whose tabs the user moved to another pane render there, so this pane lets their screens go. const elsewhere = createMemo( () => { @@ -170,117 +125,77 @@ export default function TerminalPanel(props: { { equals: (previous, next) => previous.size === next.size && [...next].every((id) => previous.has(id)) }, ) - // Keeps each shown terminal mounted for the workspaces shown last, so switching back keeps its screen and session. A - // terminal mounts, and connects, once it is shown, not while the panel only holds its tab hidden. + // Keeps each terminal the session showed mounted, so switching between its tabs keeps their screens. Like the TUI, + // another session takes a new snapshot when it shows again. A terminal mounts, and connects, once it is shown, not + // while the panel only holds its tab hidden. createKeyed( () => ({ - workspace: workspaceKey(), + session: terminal().key, ready: terminal().ready(), active: opened() ? active() : undefined, - ptys: terminal().all(), + terminals: terminal().all(), elsewhere: elsewhere(), }), (current) => { - if (!current.ready) return + if (!current.ready) return setStore("surfaces", []) - const ids = new Set(current.ptys.map((pty) => pty.id)) + const ids = new Set(current.terminals.map((info) => info.id)) const surfaces = store.surfaces.filter( (surface) => - surface.workspace !== current.workspace || - (ids.has(surface.pty.id) && !current.elsewhere.has(terminalTab(surface.pty))), + surface.session === current.session && + !(surface.failed && surface.id !== current.active) && + ids.has(surface.id) && + !current.elsewhere.has(surface.id), ) - const pty = current.ptys.find((item) => item.id === current.active) - const key = pty ? `${current.workspace}\0${pty.id}` : undefined - - if (pty && key && !surfaces.some((surface) => surface.key === key)) { - surfaces.push({ - key, - workspace: current.workspace, - pty, - ops: terminal(), - focus: terminal().focusRequested(pty.id), - }) + if (current.active && !surfaces.some((surface) => surface.id === current.active)) { + surfaces.push({ session: current.session, id: current.active, server: terminal().server }) } - const workspaces = [...store.workspaces.filter((item) => item !== current.workspace), current.workspace].slice( - -MAX_CACHED_TERMINAL_WORKSPACES, - ) - - const keep = new Set(workspaces) - - setStore({ surfaces: surfaces.filter((surface) => keep.has(surface.workspace)), workspaces }) + setStore("surfaces", surfaces) }, { equals: (previous, next) => - previous.workspace === next.workspace && + previous.session === next.session && previous.ready === next.ready && previous.active === next.active && - previous.ptys === next.ptys && + previous.terminals === next.terminals && previous.elsewhere === next.elsewhere, }, ) - const recoverTerminal = (key: string, id: string, clone: (id: string) => Promise) => { - if (store.recovered[key]) return - setStore("recovered", key, true) - void clone(id) - } - - const markTerminalConnected = (key: string, id: string, trim: (id: string) => void) => { - setStore("recovered", key, false) - trim(id) - const index = store.surfaces.findIndex((surface) => surface.key === key) - - if (!store.surfaces[index]?.focus) return - setStore("surfaces", index, "focus", false) - - if (!opened() || active() !== id) return - focusTerminalById(id) - terminal().consumeFocus(id) - } - - const handleTerminalDragEnd = () => { - const activeId = terminal().active() - - if (!activeId) return - requestAnimationFrame(() => { - if (terminal().active() !== activeId) return - focusTerminalById(activeId) - }) - } - const surfaces = () => (
{(surface) => (
terminal().select(surface.id)} + onPointerDown={() => terminal().select(surface.id)} classList={{ - hidden: !present() || surface.workspace !== workspaceKey() || surface.pty.id !== active(), + hidden: !present() || surface.session !== terminal().key || surface.id !== active(), }} > { - focusTerminalById(surface.pty.id) - terminal().consumeFocus(surface.pty.id) + autoFocus={terminal().focusRequested(surface.id)} + onAutoFocus={() => terminal().consumeFocus(surface.id)} + onFailure={() => { + const shown = opened() && surface.session === terminal().key && surface.id === active() + + const same = (item: TerminalSurface) => item.session === surface.session && item.id === surface.id + + if (shown) return setStore("surfaces", same, "failed", true) + + setStore("surfaces", (list) => list.filter((item) => !same(item))) }} class="!px-[14px]" - onConnect={() => - markTerminalConnected(surface.key, surface.pty.id, (terminalID) => surface.ops.trim(terminalID)) - } - onCleanup={(terminal) => surface.ops.update(terminal)} - onConnectError={() => - recoverTerminal(surface.key, surface.pty.id, (terminalID) => surface.ops.clone(terminalID)) - } />
)} @@ -291,97 +206,65 @@ export default function TerminalPanel(props: { return (
0} + when={terminal().ready()} fallback={ -
- -
- - {(title) => ( -
- {title} -
- )} -
-
-
-
{plugin.t("loading")}
+
+ {plugin.t("loading")}
} > - - event.target instanceof Element && - !!event.target.closest('[data-slot="tabs-trigger-close-button"], input, [contenteditable="true"]'), - }), - ]} - modifiers={[RestrictToHorizontalAxis, RestrictToElement.configure({ element: () => tabList ?? null })]} - plugins={(defaults) => [ - ...defaults.filter((plugin) => plugin !== Accessibility), - AutoScroller.configure({ acceleration: 8, threshold: { x: 0.05, y: 0 } }), - Feedback.configure({ dropAnimation: null }), - ]} - onDragEnd={(event) => { - const source = event.operation.source - - if (!event.canceled && isSortable(source) && source.initialIndex !== source.index) { - terminal().move(source.id.toString(), source.index) - } - - handleTerminalDragEnd() - }} - > -
- terminal().open(id)} - class="!h-full min-w-0 !flex-1" +
+ terminal().select(id)} + class="!h-full min-w-0 !flex-1" + > + { + const focused = document.activeElement + + if (event.target === focused) return + + if (focused instanceof HTMLInputElement && event.currentTarget.contains(focused)) focused.blur() + }} > - { - const focused = document.activeElement - - if (event.target === focused) return - - if (focused instanceof HTMLInputElement && event.currentTarget.contains(focused)) focused.blur() - }} - > - - {(pty, index) => } - -
- - {plugin.t("command.new")} - 0}> - - - - } - placement="bottom" - class="flex items-center" - > - } - variant="ghost" - onClick={() => void terminal().new()} - aria-label={plugin.t("command.new")} - /> - -
-
-
-
- {surfaces()} - + + {(info) => ( + void terminal().rename(info.id, title)} + /> + )} + +
+ + {plugin.t("command.new")} + 0}> + + + + } + placement="bottom" + class="flex items-center" + > + } + variant="ghost" + onClick={() => void terminal().new()} + aria-label={plugin.t("command.new")} + /> + +
+ +
+
+ {surfaces()}
diff --git a/packages/gui-plugins/src/terminal/props.ts b/packages/gui-plugins/src/terminal/props.ts new file mode 100644 index 000000000000..2256064dc17d --- /dev/null +++ b/packages/gui-plugins/src/terminal/props.ts @@ -0,0 +1,16 @@ +import type { ServerRef } from "@opencode/plugin/gui" +import type { TerminalModel } from "./model" +import type { TerminalQuoteTarget } from "./quote" + +export type TerminalProps = { + ptyID: string + server: ServerRef + ghostty: TerminalModel["ghostty"] + quote?: TerminalQuoteTarget + autoFocus?: boolean + onAutoFocus?: () => void + onSubmit?: () => void + /** The connection failed or closed; the pane shows why and stays until it unmounts. */ + onFailure?: () => void + class?: string +} diff --git a/packages/gui-plugins/src/terminal/renderer.tsx b/packages/gui-plugins/src/terminal/renderer.tsx index d9458dcebef9..9f7ea2a70514 100644 --- a/packages/gui-plugins/src/terminal/renderer.tsx +++ b/packages/gui-plugins/src/terminal/renderer.tsx @@ -1,4 +1,4 @@ -import { createMemo, lazy, on, onCleanup, Suspense } from "solid-js" +import { createMemo, lazy, onCleanup, Show, Suspense } from "solid-js" import { Icon } from "@opencode/ui/icon" import { Menu } from "@opencode/ui/menu" import { @@ -10,11 +10,11 @@ import { type MountedSession, type PanelTab, type Plugin, + type SessionRef, } from "@opencode/plugin/gui" import type Terminal from "./index" import { terminalToggleCommand } from "./index" -import { createTerminalModel, type TerminalWorkspace } from "./model" -import { terminalTab, type LocalPTY } from "./state" +import { createTerminalModel, type TerminalSession } from "./model" import { terminalTabLabel } from "./title" import { TerminalTabLabel } from "./label" import quoteStyles from "./quote.css?inline" @@ -23,31 +23,14 @@ import { onIdle, BuiltinCommand, BuiltinSlot } from "@opencode/plugin/gui/builti const setup: Plugin.Setup = (ctx) => { const sessions = ctx.sessions const layout = ctx.layout - const model = createTerminalModel({ storage: ctx.storage, sessions }) const key = (id: string) => `${ctx.id}:${id}` + const model = createTerminalModel({ storage: ctx.storage, layout, toast: ctx.toast, t: ctx.t, tab: key }) onCleanup(model.dispose) ctx.add(Style, quoteStyles) // The host withdraws the listener with the plugin. ctx.workspaces.on("remove", model.remove) - // The routed session's workspace stays loaded while no panel renders it, like the session route did. - const workspace = createMemo((previous) => { - const session = sessions.current() - - return session ? model.load(session) : previous - }) - - // The workspace each later route change leaves. - const left = createMemo( - on(workspace, (next, previous) => (previous && next !== previous ? previous : undefined), { defer: true }), - ) - - // A workspace the route leaves drops its restore buffers. - createKeyed(left, (previous) => previous.trimAll()) - - const routed = createMemo(() => !!sessions.current()) - const current = () => { const session = sessions.current() @@ -56,37 +39,35 @@ const setup: Plugin.Setup = (ctx) => { return { session, terminal: model.load(session) } } + // Servers without persistent terminals get no terminal commands, like the TUI. + const enabled = createMemo(() => { + const session = sessions.current() + + return !!session && model.available(session.server) + }) + // Opens a terminal's tab in the session's side panel and focuses it. - const show = (session: MountedSession, terminal: TerminalWorkspace, pty: LocalPTY) => { - terminal.open(pty.id) - terminal.requestFocus(pty.id) + const show = (session: MountedSession, terminal: TerminalSession, id: string) => { + terminal.select(id) + terminal.requestFocus(id) // A narrow screen shows the terminal view; a wide one adds the tab without replacing the preview tab. - layout.open(key(terminalTab(pty)), session, layout.narrow() ? undefined : { tab: "select" }) + layout.open(key(id), session, layout.narrow() ? undefined : { tab: "select" }) } - const create = (session: MountedSession, terminal: TerminalWorkspace) => + const create = (session: MountedSession, terminal: TerminalSession) => void terminal.new().then((id) => { - const pty = id ? terminal.all().find((item) => item.id === id) : undefined - - if (pty && !ctx.signal.aborted) show(session, terminal, pty) + if (id && !ctx.signal.aborted) show(session, terminal, id) }) - // Closes the tab, which closes its terminal; the narrow-screen view lists terminals without storing their tabs. - const close = (session: MountedSession, terminal: TerminalWorkspace, pty: LocalPTY) => { - layout.close(key(terminalTab(pty)), session) - - if (terminal.all().some((item) => item.id === pty.id)) void terminal.close(pty.id) - } - - const active = (terminal: TerminalWorkspace) => terminal.all().find((pty) => pty.id === terminal.active()) - ctx.add(BuiltinSlot, { at: "session.location.branch.menu", render: (input) => ( - create(input.session, model.load(input.session))}> - - {ctx.t("location.open")} - + + create(input.session, model.load(input.session))}> + + {ctx.t("location.open")} + + ), }) @@ -100,25 +81,25 @@ const setup: Plugin.Setup = (ctx) => { featured: true, slash: { name: "terminal", after: "open" }, editable: true, - enabled: routed(), + enabled: enabled(), run() { const target = current() if (!target) return - const pty = active(target.terminal) + const id = target.terminal.active() - if (!pty) return create(target.session, target.terminal) + if (!id) return create(target.session, target.terminal) // A visible tab hides with its pane; a narrow screen has no strip, so there the command only shows it. - if (!layout.narrow() && layout.state(key(terminalTab(pty)), target.session) === "visible") { + if (!layout.narrow() && layout.state(key(id), target.session) === "visible") { target.terminal.cancelFocus() - layout.hide(key(terminalTab(pty)), target.session) + layout.hide(key(id), target.session) return } - show(target.session, target.terminal, pty) + show(target.session, target.terminal, id) }, }), ) @@ -133,7 +114,7 @@ const setup: Plugin.Setup = (ctx) => { section: "terminal", bind: "ctrl+alt+t", editable: true, - enabled: routed(), + enabled: enabled(), run() { const target = current() @@ -153,30 +134,32 @@ const setup: Plugin.Setup = (ctx) => { follows: "tab.close", hidden: true, scope: '[data-component="terminal"]', - enabled: routed(), + enabled: enabled(), run() { const target = current() - const pty = target ? active(target.terminal) : undefined + const id = target?.terminal.active() - if (target && pty) close(target.session, target.terminal, pty) + if (target && id) void target.terminal.close(id) }, }), ) - ctx.add(MenuItem, { - menu: "session.panel", - id: "new", - get title() { - return ctx.t("tab.title") - }, - icon: "terminal", - keybind: "terminal.new", - order: 20, - run() { - const target = current() + ctx.add(MenuItem, (): MenuItem | undefined => { + if (!enabled()) return - if (target) create(target.session, target.terminal) - }, + return { + menu: "session.panel", + id: "new", + title: ctx.t("tab.title"), + icon: "terminal", + keybind: "terminal.new", + order: 20, + run() { + const target = current() + + if (target) create(target.session, target.terminal) + }, + } }) const TerminalPanel = lazy(() => import("./panel")) @@ -189,8 +172,7 @@ const setup: Plugin.Setup = (ctx) => { () => void TerminalPanel.preload(), ) - // Tab objects per session, workspace and terminal, reused so strip updates and session switches do not rebuild a - // trigger. + // Tab objects per session and terminal, reused so strip updates and session switches do not rebuild a trigger. const tabs = new Map>() // Drops the tab objects of sessions whose shell tab closed. @@ -199,40 +181,32 @@ const setup: Plugin.Setup = (ctx) => { () => { const keep = new Set([...sessions.list().map((session) => session.key), sessions.current()?.key]) tabs.forEach((_cache, cacheKey) => { - if (!keep.has(cacheKey.slice(0, cacheKey.indexOf("\0")))) tabs.delete(cacheKey) + if (!keep.has(cacheKey)) tabs.delete(cacheKey) }) }, ) - const tab = (workspace: Pick, id: string): PanelTab => { - const terminal = () => model.load(workspace) - const pty = () => terminal().byTab(id) - const label = () => terminalTabLabel({ title: pty()?.title, titleNumber: pty()?.titleNumber, t: ctx.t }) + const tab = (session: SessionRef, id: string): PanelTab => { + const terminal = () => model.load(session) + const info = () => terminal().get(id) + const label = () => terminalTabLabel({ title: info()?.title, t: ctx.t }) return { id, get title() { return label() }, - // Listed only to hold the restored selection until the workspace's stored terminals load. + // Listed only to hold the restored selection until the server lists the session's terminals. get hidden() { return !terminal().ready() }, group: "terminal", - label: (state) => ( + label: () => ( { - const current = pty() - - if (current) terminal().update({ id: current.id, title }) - }} - close={() => { - const current = pty() - - if (current) close(state.session, terminal(), current) - }} + title={info()?.title ?? ""} + rename={(title) => void terminal().rename(id, title)} + close={() => void terminal().close(id)} /> ), } @@ -241,7 +215,7 @@ const setup: Plugin.Setup = (ctx) => { ctx.add(Panel, { id: "main", region: "side", - // A tab whose terminal exited, or was closed from another session of the workspace, leaves the strip. + // A tab whose terminal the server no longer lists (closed here or elsewhere, or exited) leaves the strip. transient: true, mobile: { get title() { @@ -252,22 +226,19 @@ const setup: Plugin.Setup = (ctx) => { icon: "terminal", cached: true, }, - // One tab per terminal of the session's workspace; the strip shows those opened in this session. Listing the rest - // keeps their shared render, and so their shells' screens, mounted while another session of the workspace is - // routed. Until the workspace's terminals load, the stored tabs stay listed but hidden so restore keeps them. + // One tab per terminal of the session. Until the server lists them, the stored tabs stay listed but hidden so + // restore keeps them. list: (input) => { const terminal = model.load(input.session) - const ids = [...new Set([...input.open, ...terminal.all().map(terminalTab)])] + const ids = [...new Set([...input.open, ...terminal.all().map((info) => info.id)])] if (ids.length === 0) return [] - const workspace = { server: input.session.server, directory: input.session.directory } - const cacheKey = `${input.session.key}\0${terminal.key}` - const cache = tabs.get(cacheKey) ?? new Map() - tabs.set(cacheKey, cache) + const cache = tabs.get(input.session.key) ?? new Map() + tabs.set(input.session.key, cache) return ids.flatMap((id) => { - if (terminal.ready() && !terminal.byTab(id)) { + if (terminal.ready() && !terminal.get(id)) { cache.delete(id) return [] @@ -277,7 +248,7 @@ const setup: Plugin.Setup = (ctx) => { if (existing) return [existing] - const created = tab(workspace, id) + const created = tab(input.session, id) cache.set(id, created) return [created] @@ -290,27 +261,26 @@ const setup: Plugin.Setup = (ctx) => { ), close: (input) => { const terminal = model.load(input.session) - const pty = terminal.byTab(input.tab.id) - tabs.get(`${input.session.key}\0${terminal.key}`)?.delete(input.tab.id) + tabs.get(input.session.key)?.delete(input.tab.id) - if (pty) void terminal.close(pty.id) + if (terminal.get(input.tab.id)) void terminal.close(input.tab.id) }, + // Before the server lists the session's terminals, a restored tab is selected on trust; `active` honours the + // selection once it is listed. focus: (input) => { const terminal = model.load(input.session) - const pty = terminal.byTab(input.tab.id) - if (!pty) return + if (terminal.ready() && !terminal.get(input.tab.id)) return - terminal.open(pty.id) + terminal.select(input.tab.id) - if (!input.restored) terminal.requestFocus(pty.id) + if (!input.restored) terminal.requestFocus(input.tab.id) }, enter: (input) => { const terminal = model.load(input.session) - const pty = terminal.byTab(input.tab.id) - if (pty) terminal.requestFocus(pty.id) + if (!terminal.ready() || terminal.get(input.tab.id)) terminal.requestFocus(input.tab.id) }, }) } diff --git a/packages/gui-plugins/src/terminal/serialize.test.ts b/packages/gui-plugins/src/terminal/serialize.test.ts deleted file mode 100644 index 7cc7cef70c19..000000000000 --- a/packages/gui-plugins/src/terminal/serialize.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, test, expect, afterEach, spyOn } from "bun:test" -import { Terminal, Ghostty } from "ghostty-web" -import { SerializeAddon } from "./serialize" - -const ghostty = await Ghostty.load() - -const terminals: Terminal[] = [] - -afterEach(() => { - for (const term of terminals) { - term.dispose() - } - - terminals.length = 0 - document.body.innerHTML = "" -}) - -function createTerminal(cols = 80, rows = 24): { term: Terminal; addon: SerializeAddon; container: HTMLElement } { - const container = document.createElement("div") - document.body.appendChild(container) - - const term = new Terminal({ cols, rows, ghostty }) - const addon = new SerializeAddon() - term.loadAddon(addon) - term.open(container) - terminals.push(term) - - return { term, addon, container } -} - -function writeAndWait(term: Terminal, data: string): Promise { - return new Promise((resolve) => { - term.write(data, resolve) - }) -} - -describe("SerializeAddon", () => { - test("scrollback reads only the requested tail and restores the cursor on its screen row", async () => { - const { term, addon } = createTerminal(20, 5) - await writeAndWait(term, Array.from({ length: 30 }, (_, i) => `line ${i}`).join("\r\n")) - await writeAndWait(term, "\x1b[2A\x1b[3G") - expect(term.buffer.normal.length).toBe(30) - expect([term.buffer.normal.cursorX, term.buffer.normal.cursorY]).toEqual([2, 2]) - - const reads = spyOn(term.buffer.normal, "getLine") - const serialized = addon.serialize({ scrollback: 3 }) - expect(new Set(reads.mock.calls.map((args) => args[0]))).toEqual(new Set([22, 23, 24, 25, 26, 27, 28, 29])) - reads.mockRestore() - - const restored = createTerminal(20, 5) - await writeAndWait(restored.term, serialized) - expect(restored.term.getScrollbackLength()).toBe(3) - - for (let row = 0; row < 8; row++) { - expect(restored.term.buffer.normal.getLine(row)?.translateToString(true)).toBe(`line ${22 + row}`) - } - - expect([restored.term.buffer.normal.cursorX, restored.term.buffer.normal.cursorY]).toEqual([2, 2]) - }) - - test("preserves color scheme reporting mode", async () => { - const { term, addon } = createTerminal() - await writeAndWait(term, "\x1b[?2031h") - - expect(addon.serialize().startsWith("\x1b[?2031h")).toBe(true) - expect(addon.serialize({ excludeModes: true }).startsWith("\x1b[?2031h")).toBe(false) - }) - - test("round trip keeps text, alternate screen, and colors", async () => { - const prompt = createTerminal() - await writeAndWait( - prompt.term, - ["\x1b[1;32m❯\x1b[0m \x1b[34mcd\x1b[0m /some/path", "\x1b[1;32m❯\x1b[0m \x1b[34mls\x1b[0m -la", "total 42"].join( - "\r\n", - ), - ) - const text = await roundTrip(prompt) - expect(/\x1b\[\d+X/.test(text.serialized)).toBe(false) - expect([0, 1, 2].map((row) => text.restored.buffer.active.getLine(row)?.translateToString(true))).toEqual([ - "❯ cd /some/path", - "❯ ls -la", - "total 42", - ]) - - const alternate = createTerminal(20, 5) - await writeAndWait(alternate.term, "normal\r\n") - await writeAndWait(alternate.term, "\x1b[?1049h\x1b[HALT") - expect(alternate.term.buffer.active.type).toBe("alternate") - const screen = (await roundTrip(alternate)).restored.buffer.active - expect(screen.type).toBe("alternate") - expect(screen.getLine(0)?.translateToString(true)).toBe("ALT") - expect([0, 32]).toContain(screen.getLine(0)!.getCell(10)!.getCode()) - - const colors = createTerminal(40, 5) - await writeAndWait( - colors.term, - "\x1b[38;2;255;0;0mHello\x1b[0m \x1b[38;2;0;255;0mWorld\x1b[0m! ", - ) - const original = colors.term.buffer.active.getLine(0)! - const line = (await roundTrip(colors, { range: { start: 0, end: 0 } })).restored.buffer.active.getLine(0)! - expect([0, 6, 11].map((cell) => line.getCell(cell)!.getChars())).toEqual(["H", "W", "!"]) - expect([0, 6].map((cell) => line.getCell(cell)!.getFgColor())).toEqual( - [0, 6].map((cell) => original.getCell(cell)!.getFgColor()), - ) - }) -}) - -async function roundTrip( - source: ReturnType, - options?: Parameters[0], -) { - const serialized = source.addon.serialize(options) - const restored = createTerminal(source.term.cols, source.term.rows).term - await writeAndWait(restored, serialized) - - return { serialized, restored } -} diff --git a/packages/gui-plugins/src/terminal/serialize.ts b/packages/gui-plugins/src/terminal/serialize.ts deleted file mode 100644 index fa95557f968a..000000000000 --- a/packages/gui-plugins/src/terminal/serialize.ts +++ /dev/null @@ -1,622 +0,0 @@ -/** - * SerializeAddon - Serialize terminal buffer contents - * - * Port of xterm.js addon-serialize for ghostty-web. - * Enables serialization of terminal contents to a string that can - * be written back to restore terminal state. - * - * Usage: - * ```typescript - * const serializeAddon = new SerializeAddon(); - * term.loadAddon(serializeAddon); - * const content = serializeAddon.serialize(); - * ``` - */ - -import type { ITerminalAddon, ITerminalCore, IBufferRange } from "ghostty-web" - -// ============================================================================ -// Buffer Types (matching ghostty-web internal interfaces) -// ============================================================================ - -interface IBuffer { - readonly type: "normal" | "alternate" - readonly cursorX: number - readonly cursorY: number - readonly viewportY: number - readonly baseY: number - readonly length: number - getLine(y: number): IBufferLine | undefined - getNullCell(): IBufferCell -} - -interface IBufferLine { - readonly length: number - readonly isWrapped: boolean - getCell(x: number): IBufferCell | undefined - translateToString(trimRight?: boolean, startColumn?: number, endColumn?: number): string -} - -interface IBufferCell { - getChars(): string - getCode(): number - getWidth(): number - getFgColorMode(): number - getBgColorMode(): number - getFgColor(): number - getBgColor(): number - isBold(): number - isItalic(): number - isUnderline(): number - isStrikethrough(): number - isBlink(): number - isInverse(): number - isInvisible(): number - isFaint(): number - isDim(): boolean -} - -type TerminalBuffers = { - active?: IBuffer - normal?: IBuffer - alternate?: IBuffer -} - -const isRecord = (value: unknown): value is Record => { - return typeof value === "object" && value !== null -} - -const isBuffer = (value: unknown): value is IBuffer => { - if (!isRecord(value)) return false - - if (typeof value.length !== "number") return false - - if (typeof value.cursorX !== "number") return false - - if (typeof value.cursorY !== "number") return false - - if (typeof value.baseY !== "number") return false - - if (typeof value.viewportY !== "number") return false - - if (typeof value.getLine !== "function") return false - - if (typeof value.getNullCell !== "function") return false - - return true -} - -const getTerminalBuffers = (value: ITerminalCore): TerminalBuffers | undefined => { - if (!isRecord(value)) return - const raw = value.buffer - - if (!isRecord(raw)) return - const active = isBuffer(raw.active) ? raw.active : undefined - const normal = isBuffer(raw.normal) ? raw.normal : undefined - const alternate = isBuffer(raw.alternate) ? raw.alternate : undefined - - if (!active && !normal) return - - return { active, normal, alternate } -} - -const getTerminalMode = (value: ITerminalCore, mode: number) => { - if (!isRecord(value)) return false - const terminal = value.wasmTerm - - if (!isRecord(terminal) || typeof terminal.getMode !== "function") return false - - return terminal.getMode(mode) === true -} - -// ============================================================================ -// Types -// ============================================================================ - -export interface ISerializeOptions { - /** - * The row range to serialize. When an explicit range is specified, the cursor - * will get its final repositioning. - */ - range?: ISerializeRange - /** - * The number of rows in the scrollback buffer to serialize, starting from - * the bottom of the scrollback buffer. When not specified, all available - * rows in the scrollback buffer will be serialized. - */ - scrollback?: number - /** - * Whether to exclude the terminal modes from the serialization. - * Default: false - */ - excludeModes?: boolean - /** - * Whether to exclude the alt buffer from the serialization. - * Default: false - */ - excludeAltBuffer?: boolean -} - -export interface ISerializeRange { - /** - * The line to start serializing (inclusive). - */ - start: number - /** - * The line to end serializing (inclusive). - */ - end: number -} - -// ============================================================================ -// Helper Functions -// ============================================================================ - -function constrain(value: number, low: number, high: number): number { - return Math.max(low, Math.min(value, high)) -} - -function equalFg(cell1: IBufferCell, cell2: IBufferCell): boolean { - return cell1.getFgColorMode() === cell2.getFgColorMode() && cell1.getFgColor() === cell2.getFgColor() -} - -function equalBg(cell1: IBufferCell, cell2: IBufferCell): boolean { - return cell1.getBgColorMode() === cell2.getBgColorMode() && cell1.getBgColor() === cell2.getBgColor() -} - -function equalFlags(cell1: IBufferCell, cell2: IBufferCell): boolean { - return ( - !!cell1.isInverse() === !!cell2.isInverse() && - !!cell1.isBold() === !!cell2.isBold() && - !!cell1.isUnderline() === !!cell2.isUnderline() && - !!cell1.isBlink() === !!cell2.isBlink() && - !!cell1.isInvisible() === !!cell2.isInvisible() && - !!cell1.isItalic() === !!cell2.isItalic() && - !!cell1.isDim() === !!cell2.isDim() && - !!cell1.isStrikethrough() === !!cell2.isStrikethrough() - ) -} - -// ============================================================================ -// String Serialize Handler -// ============================================================================ - -class StringSerializeHandler { - private _rowIndex: number = 0 - private _allRows: string[] = [] - private _allRowSeparators: string[] = [] - private _currentRow: string = "" - private _nullCellCount: number = 0 - private _cursorStyle: IBufferCell - private _firstRow: number = 0 - private _lastContentCursorRow: number = 0 - - constructor( - private readonly _buffer: IBuffer, - private readonly _terminal: ITerminalCore, - ) { - this._cursorStyle = this._buffer.getNullCell() - } - - public serialize(range: IBufferRange, excludeFinalCursorPosition?: boolean): string { - let oldCell = this._buffer.getNullCell() - - const startRow = range.start.y - const endRow = range.end.y - const startColumn = range.start.x - const endColumn = range.end.x - - this._beforeSerialize(endRow - startRow + 1, startRow, endRow) - - for (let row = startRow; row <= endRow; row++) { - const line = this._buffer.getLine(row) - - if (line) { - const startLineColumn = row === range.start.y ? startColumn : 0 - const endLineColumn = Math.min(endColumn, line.length) - - for (let col = startLineColumn; col < endLineColumn; col++) { - const c = line.getCell(col) - - if (!c) { - continue - } - - this._nextCell(c, oldCell, row) - oldCell = c - } - } - - this._rowEnd(row, row === endRow) - } - - return this._serializeString(excludeFinalCursorPosition) - } - - private _beforeSerialize(rows: number, start: number, _end: number): void { - this._allRows = Array.from({ length: rows }) - this._allRowSeparators = Array.from({ length: rows }) - this._rowIndex = 0 - - this._currentRow = "" - this._nullCellCount = 0 - this._cursorStyle = this._buffer.getNullCell() - - this._lastContentCursorRow = start - this._firstRow = start - } - - protected _rowEnd(row: number, isLastRow: boolean): void { - let rowSeparator = "" - - const nextLine = isLastRow ? undefined : this._buffer.getLine(row + 1) - const wrapped = !!nextLine?.isWrapped - - if (this._nullCellCount > 0 && wrapped) { - this._currentRow += " ".repeat(this._nullCellCount) - } - - this._nullCellCount = 0 - - if (!isLastRow && !wrapped) { - rowSeparator = "\r\n" - } - - this._allRows[this._rowIndex] = this._currentRow - this._allRowSeparators[this._rowIndex++] = rowSeparator - this._currentRow = "" - this._nullCellCount = 0 - } - - private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): number[] { - const sgrSeq: number[] = [] - const fgChanged = !equalFg(cell, oldCell) - const bgChanged = !equalBg(cell, oldCell) - const flagsChanged = !equalFlags(cell, oldCell) - - if (fgChanged || bgChanged || flagsChanged) { - if (this._isAttributeDefault(cell)) { - if (!this._isAttributeDefault(oldCell)) { - sgrSeq.push(0) - } - } else { - if (flagsChanged) { - if (!!cell.isInverse() !== !!oldCell.isInverse()) { - sgrSeq.push(cell.isInverse() ? 7 : 27) - } - - if (!!cell.isBold() !== !!oldCell.isBold()) { - sgrSeq.push(cell.isBold() ? 1 : 22) - } - - if (!!cell.isUnderline() !== !!oldCell.isUnderline()) { - sgrSeq.push(cell.isUnderline() ? 4 : 24) - } - - if (!!cell.isBlink() !== !!oldCell.isBlink()) { - sgrSeq.push(cell.isBlink() ? 5 : 25) - } - - if (!!cell.isInvisible() !== !!oldCell.isInvisible()) { - sgrSeq.push(cell.isInvisible() ? 8 : 28) - } - - if (!!cell.isItalic() !== !!oldCell.isItalic()) { - sgrSeq.push(cell.isItalic() ? 3 : 23) - } - - if (!!cell.isDim() !== !!oldCell.isDim()) { - sgrSeq.push(cell.isDim() ? 2 : 22) - } - - if (!!cell.isStrikethrough() !== !!oldCell.isStrikethrough()) { - sgrSeq.push(cell.isStrikethrough() ? 9 : 29) - } - } - - if (fgChanged) { - const color = cell.getFgColor() - const mode = cell.getFgColorMode() - - if (mode === 2 || mode === 3 || mode === -1) { - sgrSeq.push(38, 2, (color >>> 16) & 0xff, (color >>> 8) & 0xff, color & 0xff) - } else if (mode === 1) { - // Palette - if (color >= 16) { - sgrSeq.push(38, 5, color) - } else { - sgrSeq.push(color & 8 ? 90 + (color & 7) : 30 + (color & 7)) - } - } else { - sgrSeq.push(39) - } - } - - if (bgChanged) { - const color = cell.getBgColor() - const mode = cell.getBgColorMode() - - if (mode === 2 || mode === 3 || mode === -1) { - sgrSeq.push(48, 2, (color >>> 16) & 0xff, (color >>> 8) & 0xff, color & 0xff) - } else if (mode === 1) { - // Palette - if (color >= 16) { - sgrSeq.push(48, 5, color) - } else { - sgrSeq.push(color & 8 ? 100 + (color & 7) : 40 + (color & 7)) - } - } else { - sgrSeq.push(49) - } - } - } - } - - return sgrSeq - } - - private _isAttributeDefault(cell: IBufferCell): boolean { - const mode = cell.getFgColorMode() - const bgMode = cell.getBgColorMode() - - if (mode === 0 && bgMode === 0) { - return ( - !cell.isBold() && - !cell.isItalic() && - !cell.isUnderline() && - !cell.isBlink() && - !cell.isInverse() && - !cell.isInvisible() && - !cell.isDim() && - !cell.isStrikethrough() - ) - } - - const fgColor = cell.getFgColor() - const bgColor = cell.getBgColor() - const nullCell = this._buffer.getNullCell() - const nullFg = nullCell.getFgColor() - const nullBg = nullCell.getBgColor() - - return ( - fgColor === nullFg && - bgColor === nullBg && - !cell.isBold() && - !cell.isItalic() && - !cell.isUnderline() && - !cell.isBlink() && - !cell.isInverse() && - !cell.isInvisible() && - !cell.isDim() && - !cell.isStrikethrough() - ) - } - - private _nextCell(cell: IBufferCell, _oldCell: IBufferCell, row: number): void { - const isPlaceHolderCell = cell.getWidth() === 0 - - if (isPlaceHolderCell) { - return - } - - const codepoint = cell.getCode() - const isInvalidCodepoint = codepoint > 0x10ffff || (codepoint >= 0xd800 && codepoint <= 0xdfff) - const isGarbage = isInvalidCodepoint || (codepoint >= 0xf000 && cell.getWidth() === 1) - const isEmptyCell = codepoint === 0 || cell.getChars() === "" || isGarbage - - const sgrSeq = this._diffStyle(cell, this._cursorStyle) - - const styleChanged = sgrSeq.length > 0 - - if (styleChanged) { - if (this._nullCellCount > 0) { - this._currentRow += " ".repeat(this._nullCellCount) - this._nullCellCount = 0 - } - - this._lastContentCursorRow = row - - this._currentRow += `\u001b[${sgrSeq.join(";")}m` - - // Ghostty cells are snapshots; rereading this cell copies the whole row again. - this._cursorStyle = cell - } - - if (isEmptyCell) { - this._nullCellCount += cell.getWidth() - } else { - if (this._nullCellCount > 0) { - this._currentRow += " ".repeat(this._nullCellCount) - this._nullCellCount = 0 - } - - this._currentRow += cell.getChars() - - this._lastContentCursorRow = row - } - } - - protected _serializeString(excludeFinalCursorPosition?: boolean): string { - let rowEnd = this._allRows.length - - if (this._buffer.length - this._firstRow <= this._terminal.rows) { - rowEnd = this._lastContentCursorRow + 1 - this._firstRow - } - - let content = "" - - for (let i = 0; i < rowEnd; i++) { - content += this._allRows[i] - - if (i + 1 < rowEnd) { - content += this._allRowSeparators[i] - } - } - - if (excludeFinalCursorPosition) return content - - // CUP addresses the screen and ghostty-web reports cursorY relative to the screen, so the - // serialized range start must not shift the row. The cursor line sits in the screen region - // at the bottom of the buffer, after any scrollback rows. - content += `\u001b[${this._buffer.cursorY + 1};${this._buffer.cursorX + 1}H` - - const line = this._buffer.getLine(this._buffer.length - this._terminal.rows + this._buffer.cursorY) - const cell = line?.getCell(this._buffer.cursorX) - - const style = (() => { - if (!cell) return this._buffer.getNullCell() - - if (cell.getWidth() !== 0) return cell - - if (this._buffer.cursorX > 0) return line?.getCell(this._buffer.cursorX - 1) ?? cell - - return cell - })() - - const sgrSeq = this._diffStyle(style, this._cursorStyle) - - if (sgrSeq.length) content += `\u001b[${sgrSeq.join(";")}m` - - return content - } -} - -// ============================================================================ -// SerializeAddon Class -// ============================================================================ - -export class SerializeAddon implements ITerminalAddon { - private _terminal?: ITerminalCore - - /** - * Activate the addon (called by Terminal.loadAddon) - */ - public activate(terminal: ITerminalCore): void { - this._terminal = terminal - } - - /** - * Dispose the addon and clean up resources - */ - public dispose(): void { - this._terminal = undefined - } - - /** - * Serializes terminal rows into a string that can be written back to the - * terminal to restore the state. The cursor will also be positioned to the - * correct cell. - * - * @param options Custom options to allow control over what gets serialized. - */ - public serialize(options?: ISerializeOptions): string { - if (!this._terminal) { - throw new Error("Cannot use addon until it has been loaded") - } - - const buffer = getTerminalBuffers(this._terminal) - - if (!buffer) { - return "" - } - - const normalBuffer = buffer.normal ?? buffer.active - const altBuffer = buffer.alternate - - if (!normalBuffer) { - return "" - } - - let content = !options?.excludeModes && getTerminalMode(this._terminal, 2031) ? "\u001b[?2031h" : "" - content += options?.range - ? this._serializeBufferByRange(normalBuffer, options.range, true) - : this._serializeBufferByScrollback(normalBuffer, options?.scrollback) - - if (!options?.excludeAltBuffer && buffer.active?.type === "alternate" && altBuffer) { - const alternateContent = this._serializeBufferByScrollback(altBuffer, undefined) - content += `\u001b[?1049h\u001b[H${alternateContent}` - } - - return content - } - - /** - * Serializes terminal content as plain text (no escape sequences) - * @param options Custom options to allow control over what gets serialized. - */ - public serializeAsText(options?: { scrollback?: number; trimWhitespace?: boolean }): string { - if (!this._terminal) { - throw new Error("Cannot use addon until it has been loaded") - } - - const buffer = getTerminalBuffers(this._terminal) - - if (!buffer) { - return "" - } - - const activeBuffer = buffer.active ?? buffer.normal - - if (!activeBuffer) { - return "" - } - - const maxRows = activeBuffer.length - const scrollback = options?.scrollback - const correctRows = scrollback === undefined ? maxRows : constrain(scrollback + this._terminal.rows, 0, maxRows) - - const startRow = maxRows - correctRows - const endRow = maxRows - 1 - const lines: string[] = [] - - for (let row = startRow; row <= endRow; row++) { - const line = activeBuffer.getLine(row) - - if (line) { - const text = line.translateToString(options?.trimWhitespace ?? true) - lines.push(text) - } - } - - // Trim trailing empty lines if requested - if (options?.trimWhitespace) { - while (lines.length > 0 && lines[lines.length - 1] === "") { - lines.pop() - } - } - - return lines.join("\n") - } - - private _serializeBufferByScrollback(buffer: IBuffer, scrollback?: number): string { - const maxRows = buffer.length - const rows = this._terminal?.rows ?? 24 - const correctRows = scrollback === undefined ? maxRows : constrain(scrollback + rows, 0, maxRows) - - return this._serializeBufferByRange( - buffer, - { - start: maxRows - correctRows, - end: maxRows - 1, - }, - false, - ) - } - - private _serializeBufferByRange( - buffer: IBuffer, - range: ISerializeRange, - excludeFinalCursorPosition: boolean, - ): string { - const handler = new StringSerializeHandler(buffer, this._terminal!) - const cols = this._terminal?.cols ?? 80 - - return handler.serialize( - { - start: { x: 0, y: range.start }, - end: { x: cols, y: range.end }, - }, - excludeFinalCursorPosition, - ) - } -} diff --git a/packages/gui-plugins/src/terminal/state.test.ts b/packages/gui-plugins/src/terminal/state.test.ts deleted file mode 100644 index 2833ac61f87b..000000000000 --- a/packages/gui-plugins/src/terminal/state.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Schema } from "effect" -import { TerminalState } from "./state" - -const decodeTerminalState = Schema.decodeUnknownSync(TerminalState) - -describe("TerminalState", () => { - test("drops invalid terminals and restores a valid active terminal", () => { - const decoded = decodeTerminalState({ - active: "missing", - all: [ - null, - { id: "one", title: "Terminal 2" }, - { id: "one", title: "duplicate", titleNumber: 9 }, - { id: "two", title: "logs", titleNumber: 4, rows: 24, cols: 80, buffer: "output", cursor: 12, scrollY: 3 }, - { title: "no-id" }, - ], - }) - - expect(decoded).toEqual({ - active: "one", - all: [ - { id: "one", title: "Terminal 2", titleNumber: 2 }, - { id: "two", title: "logs", titleNumber: 4, rows: 24, cols: 80, buffer: "output", cursor: 12, scrollY: 3 }, - ], - }) - const active = decodeTerminalState({ ...decoded, active: "two" }) - expect(active.active).toBe("two") - expect(decodeTerminalState(Schema.encodeSync(TerminalState)(active))).toEqual(active) - }) - - test("defaults missing and malformed fields without dropping usable terminals", () => { - expect(decodeTerminalState({})).toEqual({ active: undefined, all: [] }) - expect(decodeTerminalState({ active: 2, all: "invalid" })).toEqual({ active: undefined, all: [] }) - expect(decodeTerminalState({ all: [null, {}, { id: "" }, { id: 2 }] })).toEqual({ active: undefined, all: [] }) - expect( - decodeTerminalState({ - all: [ - { - id: "one", - title: "Terminal 3", - titleNumber: Infinity, - rows: "24", - cols: 80, - buffer: false, - cursor: NaN, - scrollY: 0, - }, - { id: "two", title: null, titleNumber: -1, buffer: "saved", cursor: 0 }, - ], - }), - ).toEqual({ - active: "one", - all: [ - { id: "one", title: "Terminal 3", titleNumber: 3, cols: 80, scrollY: 0 }, - { id: "two", title: "", titleNumber: 0, buffer: "saved", cursor: 0 }, - ], - }) - }) -}) diff --git a/packages/gui-plugins/src/terminal/state.ts b/packages/gui-plugins/src/terminal/state.ts deleted file mode 100644 index bbfffb2e6f6a..000000000000 --- a/packages/gui-plugins/src/terminal/state.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Effect, Option, Schema, SchemaGetter } from "effect" -import { titleNumber } from "./title" - -// Same recovery rules as the host's persistence schema helpers, so stored terminals decode as before. -function fallback>(schema: S, value: () => S["Type"]) { - const defaulted = Schema.withDecodingDefaultType(Effect.sync(value))(schema) - - return Schema.catchDecoding(() => Effect.sync(() => Option.some(value())))(defaulted) -} - -function optional>(schema: S) { - const field = Schema.optional(schema) - - return Schema.catchDecoding(() => Effect.succeed(Option.none()))(field) -} - -// Recover individual entries rather than discarding the whole collection. -function array>(schema: S) { - const decode = Schema.decodeUnknownOption(schema) - const encode = Schema.encodeSync(schema) - - return fallback( - Schema.Array(Schema.Unknown).pipe( - Schema.decodeTo(Schema.Array(Schema.toType(schema)), { - decode: SchemaGetter.transform((items) => items.flatMap((item) => Option.toArray(decode(item)))), - encode: SchemaGetter.transform((items) => items.map((item) => encode(item))), - }), - ), - () => [], - ) -} - -const PTY = Schema.Struct({ - id: Schema.NonEmptyString, - // The id of the terminal's side panel tab, once a clone gave the terminal a new server id. - tab: optional(Schema.NonEmptyString), - title: fallback(Schema.String, () => ""), - titleNumber: fallback(Schema.Finite, () => 0), - rows: optional(Schema.Finite), - cols: optional(Schema.Finite), - buffer: optional(Schema.String), - scrollY: optional(Schema.Finite), - cursor: optional(Schema.Finite), -}) - -export type LocalPTY = typeof PTY.Type - -export const MAX_TERMINAL_SESSIONS = 20 - -/** The id of a terminal's side panel tab: its first server id, which a clone after a server restart keeps. */ -export function terminalTab(pty: Pick) { - return pty.tab ?? pty.id -} - -export function numberFromTitle(title: string) { - return titleNumber(title, MAX_TERMINAL_SESSIONS) -} - -const State = Schema.Struct({ - active: optional(Schema.String), - all: array(PTY), -}) - -export const TerminalState = State.pipe( - Schema.decodeTo(Schema.toType(State), { - decode: SchemaGetter.transform((value) => { - const seen = new Set() - - const all = value.all.flatMap((pty) => { - if (seen.has(pty.id)) return [] - seen.add(pty.id) - - return [{ ...pty, titleNumber: pty.titleNumber > 0 ? pty.titleNumber : (numberFromTitle(pty.title) ?? 0) }] - }) - - return { - active: value.active && seen.has(value.active) ? value.active : all[0]?.id, - all, - } - }), - encode: SchemaGetter.transform((value) => value), - }), -) diff --git a/packages/gui-plugins/src/terminal/tab.tsx b/packages/gui-plugins/src/terminal/tab.tsx index b3906959e13b..f6ec1f66b535 100644 --- a/packages/gui-plugins/src/terminal/tab.tsx +++ b/packages/gui-plugins/src/terminal/tab.tsx @@ -1,31 +1,23 @@ import type { JSX } from "solid-js" import { Show, onCleanup } from "solid-js" import { createStore } from "solid-js/store" -import { useSortable } from "@dnd-kit/solid/sortable" +import type { PersistentPtyInfo } from "@opencode/client" import { Tabs } from "@opencode/ui/tabs" import { Menu } from "@opencode/ui/menu" import { usePlugin } from "@opencode/plugin/gui" -import type { TerminalWorkspace } from "./model" -import type { LocalPTY } from "./state" +import type { TerminalSession } from "./model" import { terminalTabLabel } from "./title" import { focusTerminalById } from "./focus" -export function SortableTerminalTab(props: { - terminal: LocalPTY - workspace: TerminalWorkspace - index: number +/** A terminal's tab in the narrow-screen view. Without `rename` the terminal cannot be renamed. */ +export function TerminalTab(props: { + terminal: PersistentPtyInfo + session: TerminalSession + /** Receives the edited title, or `null` for an emptied field; unchanged titles are the receiver's to skip. */ + rename?: (title: string | null) => void }): JSX.Element { const plugin = usePlugin() - const sortable = useSortable({ - get id() { - return props.terminal.id - }, - get index() { - return props.index - }, - }) - const [store, setStore] = createStore({ editing: false, title: props.terminal.title, @@ -34,23 +26,23 @@ export function SortableTerminalTab(props: { let input: HTMLInputElement | undefined let blurFrame: number | undefined + let editFrame: number | undefined let editRequested = false - const label = () => - terminalTabLabel({ title: props.terminal.title, titleNumber: props.terminal.titleNumber, t: plugin.t }) + const label = () => terminalTabLabel({ title: props.terminal.title, t: plugin.t }) - const close = () => void props.workspace.close(props.terminal.id) + const close = () => void props.session.close(props.terminal.id) const focus = () => { if (store.editing) return - props.workspace.requestFocus(props.terminal.id) - props.workspace.open(props.terminal.id) + props.session.requestFocus(props.terminal.id) + props.session.select(props.terminal.id) if (document.activeElement instanceof HTMLElement) document.activeElement.blur() focusTerminalById(props.terminal.id) const input = document.getElementById(`terminal-wrapper-${props.terminal.id}`)?.querySelector("textarea") - if (input === document.activeElement) props.workspace.consumeFocus(props.terminal.id) + if (input === document.activeElement) props.session.consumeFocus(props.terminal.id) } const edit = (e?: Event) => { @@ -59,6 +51,8 @@ export function SortableTerminalTab(props: { e.preventDefault() } + if (!props.rename) return + const editing = store.editing setStore("blurEnabled", false) @@ -79,15 +73,11 @@ export function SortableTerminalTab(props: { }) } + // Ending the edit unmounts the focused field, whose blur would save again, or save a cancelled title. const save = () => { - if (!store.blurEnabled) return - - const value = store.title.trim() - - if (value && value !== props.terminal.title) { - props.workspace.update({ id: props.terminal.id, title: value }) - } + if (!store.editing || !store.blurEnabled) return + props.rename?.(store.title.trim() || null) setStore("editing", false) } @@ -106,12 +96,13 @@ export function SortableTerminalTab(props: { } onCleanup(() => { - if (blurFrame === undefined) return - cancelAnimationFrame(blurFrame) + if (blurFrame !== undefined) cancelAnimationFrame(blurFrame) + + if (editFrame !== undefined) cancelAnimationFrame(editFrame) }) return ( -
+
setStore("title", e.currentTarget.value)} onBlur={save} @@ -162,10 +154,17 @@ export function SortableTerminalTab(props: { if (!editRequested) return e.preventDefault() editRequested = false - requestAnimationFrame(() => edit()) + + if (editFrame !== undefined) cancelAnimationFrame(editFrame) + editFrame = requestAnimationFrame(() => { + editFrame = undefined + edit() + }) }} > - (editRequested = true)}>{plugin.t("common.rename")} + (editRequested = true)}> + {plugin.t("common.rename")} + {plugin.t("common.close")} diff --git a/packages/gui-plugins/src/terminal/terminal.fixture.tsx b/packages/gui-plugins/src/terminal/terminal.fixture.tsx index 8185a28f096a..229fa8a53af4 100644 --- a/packages/gui-plugins/src/terminal/terminal.fixture.tsx +++ b/packages/gui-plugins/src/terminal/terminal.fixture.tsx @@ -1,163 +1,71 @@ +import { OpenCode } from "@opencode/client/promise" import { ThemeProvider } from "@opencode/ui/theme/context" -import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js" -import { createStore } from "solid-js/store" +import { createSignal } from "solid-js" import { render } from "solid-js/web" -import type { ComposerQuoteAnchor, Context, ServerRef } from "@opencode/plugin/gui" import { PluginContext } from "@opencode/plugin/gui/host" +import type { Context, ServerRef } from "@opencode/plugin/gui" +import en from "./i18n/en" +import type { TerminalModel } from "./model" import { Terminal } from "./terminal" -import { TerminalQuote } from "./quote" /** - * Mounts the real terminal beside a focused composer field, as the side panel does when the user opens a terminal while - * typing. The PTY connection never resolves, so only the mount and focus lifecycle runs. + * One terminal pane attached to `ptyID` on the server at `url`, with the real ghostty-web and connection. Mounted by + * `packages/app/component-tests/terminal.spec.ts`, which serves the server with the e2e persistent PTY mock. */ -export function mountTerminalFocus(input: { autoFocus: boolean }) { +export function mountTerminal(input: { url: string; ptyID: string }) { const host = document.createElement("div") - host.dataset.testid = "terminal-focus-fixture" - host.style.cssText = "display:flex;flex-direction:column;gap:8px;width:640px;height:360px" + host.dataset.testid = "terminal-fixture" + host.style.cssText = "position: fixed; inset: 40px auto auto 40px; width: 640px; height: 320px; z-index: 1000" document.body.append(host) - const composer = document.createElement("textarea") - composer.setAttribute("aria-label", "Composer") - host.append(composer) - composer.focus() + const [failures, setFailures] = createSignal(0) + const strings: Record = en - const surface = document.createElement("div") - surface.style.cssText = "position:relative;flex:1" - host.append(surface) + const fake = { + appearance: { font: () => "monospace" }, + keybinds: { matches: () => false }, + system: { openExternal() {} }, + desktop: undefined, + t: (key: string) => strings[key] ?? key, + } - // As the panel's focus request does, consuming the request turns autoFocus off. - const [requested, setRequested] = createSignal(input.autoFocus) + const server = { + id: input.url, + name: input.url, + url: input.url, + client: OpenCode.make({ baseUrl: input.url }), + local: true, + builtin: false, + compatible: true, + connected: true, + } - const plugin = fixturePlugin() + const ghostty: TerminalModel["ghostty"] = () => + import("ghostty-web").then(async (mod) => ({ mod, ghostty: await mod.Ghostty.load() })) - // SAFETY: the terminal reads only these server members; the PTY token never resolves, so it never connects. + // SAFETY: the terminal pane reads only the plugin members implemented above. // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above - const server = { - id: "fixture", - name: "fixture", - url: "http://127.0.0.1:1", - client: { pty: { connect: { token: () => new Promise(() => {}) } } }, - } as unknown as ServerRef + const plugin = fake as unknown as Context + // SAFETY: the terminal pane reads only the server's client and url, implemented above. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above + const ref = server as unknown as ServerRef - const dispose = render( + return render( () => ( - - import("ghostty-web").then(async (mod) => ({ mod, ghostty: await mod.Ghostty.load() })) - } - autoFocus={requested()} - onAutoFocus={() => setRequested(false)} - /> +
+ setFailures((value) => value + 1)} + /> +
), - surface, + host, ) - - return () => { - dispose() - host.remove() - } -} - -/** Keeps a memoized quote consumer alive after its terminal source's owner is disposed. */ -export async function mountTerminalQuote() { - const mod = await import("ghostty-web") - const ghostty = await mod.Ghostty.load() - const host = document.createElement("div") - host.dataset.testid = "terminal-quote-fixture" - host.style.cssText = - "position:fixed;inset:16px auto auto 16px;z-index:40;background:white;color:black;width:640px;height:440px;padding:16px;display:flex;flex-direction:column;gap:8px" - document.body.append(host) - - const plugin = fixturePlugin() - - const dispose = render(() => { - const [state, setState] = createStore<{ - mounted: boolean - anchor: ComposerQuoteAnchor | undefined - text: string - }>({ - mounted: true, - anchor: undefined, - text: "", - }) - - // Do not read `mounted`: the source must invalidate this retained memo itself during disposal. - const source = createMemo(() => state.anchor?.({ width: 320, height: 120 })) - - const Source = () => { - const [ready, setReady] = createSignal(false) - const container = document.createElement("div") - container.dataset.testid = "terminal-quote-source" - container.style.cssText = "position:relative;width:600px;height:240px" - const term = new mod.Terminal({ ghostty, cols: 60, rows: 10 }) - onMount(() => { - term.open(container) - term.write("Retained terminal output", () => setReady(true)) - }) - onCleanup(() => term.dispose()) - - return ( - <> - - {container} - - true, - add: (text, anchor) => setState({ text, anchor }), - }} - /> - - - ) - } - - return ( - - - - {source() ? "Source" : "Tile"} - {state.text} - - - - - - ) - }, host) - - return () => { - dispose() - host.remove() - } -} - -function fixturePlugin() { - // SAFETY: the terminal and quote toolbar read only these plugin members while they mount and focus. - // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above - return { - t: (key: string) => key, - appearance: { font: () => "monospace" }, - keybinds: { matches: () => false }, - system: { openExternal() {} }, - } as unknown as Context } diff --git a/packages/gui-plugins/src/terminal/terminal.tsx b/packages/gui-plugins/src/terminal/terminal.tsx index a467533e6201..b2aa99a9e215 100644 --- a/packages/gui-plugins/src/terminal/terminal.tsx +++ b/packages/gui-plugins/src/terminal/terminal.tsx @@ -3,41 +3,16 @@ import { useTheme } from "@opencode/ui/theme/context" import { resolveThemeVariant } from "@opencode/ui/theme/resolve" import { resolveThemeVariantV2 } from "@opencode/ui/theme/v2/resolve" import type { HexColor, ResolvedV2Theme } from "@opencode/ui/theme/types" -import { showToast } from "@opencode/ui/toast" -import { createPtyClient } from "@opencode/client/solid" +import { createPersistentPtyClient } from "@opencode/client/solid" import type { FitAddon, Terminal as Term } from "ghostty-web" -import { Option, Predicate, Schema } from "effect" -import { type ComponentProps, createMemo, createSignal, onCleanup, onMount, Show, splitProps } from "solid-js" -import { createKeyed, usePlugin, type ServerRef } from "@opencode/plugin/gui" -import type { TerminalModel } from "./model" -import type { LocalPTY } from "./state" -import { SerializeAddon } from "./serialize" +import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js" +import { createKeyed, usePlugin } from "@opencode/plugin/gui" +import { uuid } from "@opencode/util/uuid" +import { terminalConnection, type TerminalFailure } from "./connection" +import type { TerminalProps } from "./props" import { disposeIfDisposable, getHoveredLinkText, setOptionIfSupported } from "./runtime-adapters" import { consumeTerminalMetaKey, terminalKeyInput } from "./terminal-key-event" -import { terminalWriter } from "./writer" -import { TerminalQuote, type TerminalQuoteTarget } from "./quote" - -// Serialization on unmount is a synchronous O(rows x cols) walk on the main thread and the -// result is written to localStorage or desktop state for every terminal in the workspace. -// Persisting the most recent 2k scrollback rows keeps restore fidelity for the history users -// actually scroll back through while capping teardown cost and snapshot size; the live -// terminal keeps its full 10k scrollback while mounted. -const persistedScrollbackRows = 2_000 - -export interface TerminalProps extends ComponentProps<"div"> { - pty: LocalPTY - server: ServerRef - directory: string - ghostty: TerminalModel["ghostty"] - /** Where selected output can be quoted to. */ - quote?: TerminalQuoteTarget - autoFocus?: boolean - onAutoFocus?: () => void - onSubmit?: () => void - onCleanup?: (pty: Partial & { id: string }) => void - onConnect?: () => void - onConnectError?: (error: Error) => void -} +import { TerminalQuote } from "./quote" type TerminalColors = { background: string @@ -61,11 +36,6 @@ const DEFAULT_TERMINAL_COLORS = { }, } as const satisfies Record<"light" | "dark", TerminalColors> -// The server's binary control frames carry JSON such as the output cursor. -const ControlFrame = Schema.fromJsonString(Schema.Struct({ cursor: Schema.optional(Schema.Number) })) - -const decodeControlFrame = Schema.decodeUnknownOption(ControlFrame) - const isHexColor = (value: string): value is HexColor => value.startsWith("#") const debugTerminal = (...values: unknown[]) => { @@ -97,6 +67,7 @@ const useTerminalUiBindings = (input: { cleanups: VoidFunction[] handlePointerDown: () => void handleLinkClick: (event: MouseEvent) => void + handleFocus: () => void }) => { const handleCopy = (event: ClipboardEvent) => { const selection = input.term.getSelection() @@ -124,6 +95,7 @@ const useTerminalUiBindings = (input: { const handleTextareaFocus = () => { input.term.options.cursorBlink = true + input.handleFocus() } const handleTextareaBlur = () => { @@ -154,35 +126,6 @@ const useTerminalUiBindings = (input: { input.cleanups.push(() => input.term.textarea?.removeEventListener("blur", handleTextareaBlur)) } -const persistTerminal = (input: { - term: Term | undefined - addon: SerializeAddon | undefined - cursor: number - id: string - onCleanup?: (pty: Partial & { id: string }) => void -}) => { - if (!input.addon || !input.onCleanup || !input.term) return - - const buffer = (() => { - try { - return input.addon.serialize({ scrollback: persistedScrollbackRows }) - } catch { - debugTerminal("failed to serialize terminal buffer") - - return "" - } - })() - - input.onCleanup({ - id: input.id, - buffer, - cursor: input.cursor, - rows: input.term.rows, - cols: input.term.cols, - scrollY: input.term.getViewportY(), - }) -} - export const Terminal = (props: TerminalProps) => { const plugin = usePlugin() const appearance = plugin.appearance @@ -192,73 +135,70 @@ export const Terminal = (props: TerminalProps) => { const theme = useTheme() let container!: HTMLDivElement - const [local, others] = splitProps(props, [ - "pty", - "server", - "directory", - "ghostty", - "quote", - "class", - "classList", - "autoFocus", - "onAutoFocus", - "onConnect", - "onConnectError", - ]) - - // Intentional mount-time capture: the imperative xterm/WebSocket lifecycle needs stable values, and each - // cached surface belongs to one workspace. - const server = local.server - const directory = local.directory - const id = local.pty.id - const restore = local.pty.buffer ?? "" - const stored = { cols: local.pty.cols, rows: local.pty.rows } - - const restoreSize = - restore && - stored.cols !== undefined && - Number.isSafeInteger(stored.cols) && - stored.cols > 0 && - stored.rows !== undefined && - Number.isSafeInteger(stored.rows) && - stored.rows > 0 - ? { cols: stored.cols, rows: stored.rows } - : undefined - - const scrollY = local.pty.scrollY - let ws: WebSocket | undefined + // Intentional mount-time capture: each surface attaches to one terminal. + const ptyID = props.ptyID + const attachmentID = uuid() + let socket: WebSocket | undefined let term: Term | undefined - let serializeAddon: SerializeAddon - let fitAddon: FitAddon - let handleResize: () => void - let fitFrame: number | undefined + let fitAddon: FitAddon | undefined + let measureFrame: number | undefined let sizeTimer: ReturnType | undefined - let pendingSize: { cols: number; rows: number } | undefined - let lastSize: { cols: number; rows: number } | undefined + let measured = false + let revealed = false let disposed = false const cleanups: VoidFunction[] = [] - - const start = local.pty.cursor !== undefined && Number.isSafeInteger(local.pty.cursor) ? local.pty.cursor : undefined - - let cursor = start ?? 0 - let seek = start !== undefined ? start : restore ? -1 : 0 - let output: ReturnType | undefined - let drop: VoidFunction | undefined - let reconn: ReturnType | undefined - let tries = 0 - let revealed = false // The opened terminal, for the quote toolbar. const [opened, setOpened] = createSignal() const [written, setWritten] = createSignal(0) + const [failure, setFailure] = createSignal() const reveal = () => { if (revealed) return - - if (!serializeAddon.serializeAsText({ trimWhitespace: true })) return revealed = true container.style.opacity = "1" } + const connection = terminalConnection({ + attachmentID, + write: (data, done) => { + if (disposed || !term) { + done() + + return + } + + term.write(data, () => { + setWritten((value) => value + 1) + done() + }) + reveal() + }, + resize: (size) => { + if (!disposed) term?.resize(size.cols, size.rows) + }, + send: (frame) => { + if (socket?.readyState === WebSocket.OPEN) socket.send(frame) + }, + fail: (next) => { + if (disposed) return + setFailure(next) + reveal() + props.onFailure?.() + + if (next === "outdated") socket?.close(1000) + }, + }) + + const failureText = () => { + const current = failure() + + if (current === "disconnected") return plugin.t("disconnected") + + if (current === "failed") return plugin.t("connectionFailed") + + if (current === "outdated") return plugin.t("serverOutdated") + } + const cleanup = () => { if (!cleanups.length) return const fns = cleanups.splice(0).reverse() @@ -272,18 +212,6 @@ export const Terminal = (props: TerminalProps) => { } } - const pushSize = async (cols: number, rows: number) => { - return server.client.pty - .update({ - ptyID: id, - location: { directory }, - size: { cols, rows }, - }) - .catch((err) => { - debugTerminal("failed to sync terminal size", err) - }) - } - const getTerminalColors = (): TerminalColors => { const mode = theme.mode() === "dark" ? "dark" : "light" const fallback = DEFAULT_TERMINAL_COLORS[mode] @@ -313,56 +241,35 @@ export const Terminal = (props: TerminalProps) => { const terminalColors = createMemo(getTerminalColors) - const scheduleFit = () => { - if (disposed) return - - if (!fitAddon) return + // FitAddon.fit() would resize the emulator, which only ever takes the server's canonical size. The pane's size is + // what this attachment asks for when it controls the terminal; changes after the first are debounced. + const measure = () => { + if (disposed || !fitAddon) return - if (fitFrame !== undefined) return + if (measureFrame !== undefined) return - fitFrame = requestAnimationFrame(() => { - fitFrame = undefined + measureFrame = requestAnimationFrame(() => { + measureFrame = undefined if (disposed) return - fitAddon.fit() - }) - } - - const scheduleSize = (cols: number, rows: number) => { - if (disposed) return + const next = fitAddon?.proposeDimensions() - if (lastSize?.cols === cols && lastSize?.rows === rows) { - pendingSize = undefined - - if (sizeTimer !== undefined) clearTimeout(sizeTimer) - sizeTimer = undefined - - return - } - - pendingSize = { cols, rows } - - if (!lastSize) { - lastSize = pendingSize - void pushSize(cols, rows) - - return - } + if (!next) return - if (sizeTimer !== undefined) return - sizeTimer = setTimeout(() => { - sizeTimer = undefined - const next = pendingSize + if (!measured) { + measured = true + connection.size(next) - if (!next) return - pendingSize = undefined + return + } - if (disposed) return + if (sizeTimer !== undefined) clearTimeout(sizeTimer) + sizeTimer = setTimeout(() => { + sizeTimer = undefined - if (lastSize?.cols === next.cols && lastSize?.rows === next.rows) return - lastSize = next - void pushSize(next.cols, next.rows) - }, 100) + if (!disposed) connection.size(next) + }, 100) + }) } // The terminal follows the theme and font; it is created with the current ones, so changes before then wait. @@ -382,21 +289,33 @@ export const Terminal = (props: TerminalProps) => { if (!term) return setOptionIfSupported(term, "fontFamily", font) - scheduleFit() + measure() }, ) - // A new zoom refits; the first value finds no fit addon yet. + // A new zoom remeasures; the first value finds no fit addon yet. createKeyed( () => desktop?.zoom(), - () => scheduleFit(), + () => measure(), ) const focusTerminal = () => { const t = term if (!t) return - const focus = () => (t.textarea ? t.textarea.focus({ preventScroll: true }) : t.focus()) + + // A tab's rename field keeps focus, before and after a tick; it may take it before the terminal mounts. Other + // fields, such as the command palette that created the terminal, give focus to it. + const focus = () => { + const current = document.activeElement + + if (current instanceof HTMLInputElement && current.closest('[role="tablist"]')) return + + if (t.textarea) return t.textarea.focus({ preventScroll: true }) + + t.focus() + } + focus() setTimeout(focus, 0) } @@ -408,6 +327,7 @@ export const Terminal = (props: TerminalProps) => { activeElement.blur() } + connection.interact() focusTerminal() } @@ -431,9 +351,53 @@ export const Terminal = (props: TerminalProps) => { system.openExternal(text) } + const connect = async () => { + const server = props.server + const snapshot = await server.client.experimental.persistentPty.snapshot({ ptyID }) + + if (disposed) return + connection.restore({ size: snapshot.info.size, checkpoint: snapshot.checkpoint }) + + const next = await createPersistentPtyClient(server.client, { url: server.url }).connect({ + ptyID, + cursor: snapshot.info.output.tail, + attachmentID, + takeover: true, + }) + + if (disposed) { + next.close(1000) + + return + } + + socket = next + next.addEventListener("message", (event) => { + if (disposed) return + + if (event.data instanceof ArrayBuffer) { + connection.output(new Uint8Array(event.data)) + + return + } + + // The PTY client receives binary frames as ArrayBuffers, handled above; the rest are text. + connection.message(String(event.data)) + }) + next.addEventListener("error", (event) => { + if (disposed) return + debugTerminal("websocket error", event) + connection.error() + }) + // The removal event closes the tab separately; keep the terminal visible until then. + next.addEventListener("close", () => { + if (!disposed) connection.close() + }) + } + onMount(() => { const run = async () => { - const loaded = await local.ghostty() + const loaded = await props.ghostty() if (disposed) return @@ -443,8 +407,6 @@ export const Terminal = (props: TerminalProps) => { const t = new mod.Terminal({ cursorBlink: true, cursorStyle: "bar", - cols: restoreSize?.cols, - rows: restoreSize?.rows, fontSize: 14, fontFamily: appearance.font("mono"), allowTransparency: false, @@ -464,12 +426,6 @@ export const Terminal = (props: TerminalProps) => { term = t setOptionIfSupported(t, "colorScheme", theme.mode() === "dark" ? "dark" : "light") - output = terminalWriter((data, done) => - t.write(data, () => { - setWritten((value) => value + 1) - done?.() - }), - ) t.attachCustomKeyEventHandler((event) => { const key = event.key.toLowerCase() @@ -498,12 +454,9 @@ export const Terminal = (props: TerminalProps) => { }) const fit = new mod.FitAddon() - const serializer = new SerializeAddon() cleanups.push(() => disposeIfDisposable(fit)) - t.loadAddon(serializer) t.loadAddon(fit) fitAddon = fit - serializeAddon = serializer const active = document.activeElement t.open(container) @@ -513,15 +466,16 @@ export const Terminal = (props: TerminalProps) => { cleanups, handlePointerDown, handleLinkClick, + handleFocus: () => connection.interact(), }) setOpened(t) // onAutoFocus consumes the request, which flips autoFocus, so read it once. - const autoFocus = local.autoFocus === true + const autoFocus = props.autoFocus === true if (autoFocus) { focusTerminal() - local.onAutoFocus?.() + props.onAutoFocus?.() } if (!autoFocus) { @@ -540,20 +494,7 @@ export const Terminal = (props: TerminalProps) => { cleanups.push(() => clearTimeout(timer)) } - if (typeof document !== "undefined" && document.fonts) { - void document.fonts.ready.then(scheduleFit) - } - - const onResize = t.onResize((size) => { - scheduleSize(size.cols, size.rows) - }) - - cleanups.push(() => disposeIfDisposable(onResize)) - - const onData = t.onData((data) => { - if (ws?.readyState === WebSocket.OPEN) ws.send(data) - }) - + const onData = t.onData((data) => connection.input(data)) cleanups.push(() => disposeIfDisposable(onData)) const onKey = t.onKey((key) => { @@ -564,246 +505,36 @@ export const Terminal = (props: TerminalProps) => { cleanups.push(() => disposeIfDisposable(onKey)) - const startResize = () => { - fit.observeResize() - handleResize = scheduleFit - window.addEventListener("resize", handleResize) - cleanups.push(() => window.removeEventListener("resize", handleResize)) - } - - const write = (data: string) => - new Promise((resolve) => { - if (!output) { - resolve() - - return - } - - output.push(data) - output.flush(resolve) - }) - - if (restore && restoreSize) { - await write(restore) - reveal() - fit.fit() - scheduleSize(t.cols, t.rows) - - if (scrollY !== undefined) t.scrollToLine(scrollY) - startResize() - } else { - fit.fit() - scheduleSize(t.cols, t.rows) - - if (restore) { - await write(restore) - reveal() - - if (scrollY !== undefined) t.scrollToLine(scrollY) - } - - startResize() - } - - const once = { value: false } - const decoder = new TextDecoder() - - const fail = (err: Error) => { - if (disposed) return - - if (once.value) return - - once.value = true - local.onConnectError?.(err) - } - - const gone = async () => { - return server.client.pty - .get({ ptyID: id, location: { directory } }) - .then((result) => result.data.status === "exited") - .catch((err) => { - if (Predicate.isTagged(err, "PtyNotFoundError")) return true - - debugTerminal("failed to inspect terminal session", err) - - return false - }) - } - - const retry = (err: Error) => { - if (disposed) return - - if (reconn !== undefined) return - - const ms = Math.min(250 * 2 ** Math.min(tries, 4), 4_000) - reconn = setTimeout(async () => { - reconn = undefined - - if (disposed) return - - if (await gone()) { - if (disposed) return - fail(err) - - return - } - - if (disposed) return - tries += 1 - open() - }, ms) - } - - const open = async () => { - if (disposed) return - drop?.() - - const socket = await createPtyClient(server.client, { url: server.url }) - .connect({ - ptyID: id, - location: { directory }, - cursor: seek, - }) - .catch((err) => { - // A failed connection does not mean the PTY exited; retry checks its status first. - retry(err) - - return undefined - }) - - if (!socket || once.value) return - - if (disposed) { - socket.close(1000) + const observer = new ResizeObserver(measure) + observer.observe(container) + cleanups.push(() => observer.disconnect()) + window.addEventListener("resize", measure) + cleanups.push(() => window.removeEventListener("resize", measure)) - return - } - - ws = socket - - const handleOpen = () => { - if (disposed) return - tries = 0 - local.onConnect?.() - scheduleSize(t.cols, t.rows) - - if (t.getMode(2031)) t.write("\x1b[?996n") - } - - const handleMessage = (event: MessageEvent) => { - if (disposed) return - - if (event.data instanceof ArrayBuffer) { - const bytes = new Uint8Array(event.data) - - if (bytes[0] !== 0) return - const meta = decodeControlFrame(decoder.decode(bytes.subarray(1))) - - if (Option.isNone(meta)) { - debugTerminal("invalid websocket control frame") - - return - } - - const next = meta.value.cursor - - if (next !== undefined && Number.isSafeInteger(next) && next >= 0) { - cursor = next - seek = next - } - - return - } - - // The PTY client receives binary frames as ArrayBuffers, handled above; the rest are text. - const data = String(event.data) - - if (!data) return - output?.push(data) - - if (!revealed) output?.flush(reveal) - cursor += data.length - seek = cursor - } - - const handleError = (error: Event) => { - if (disposed) return - debugTerminal("websocket error", error) - } - - const stop = () => { - socket.removeEventListener("open", handleOpen) - socket.removeEventListener("message", handleMessage) - socket.removeEventListener("error", handleError) - socket.removeEventListener("close", handleClose) - - if (ws === socket) ws = undefined - - if (drop === stop) drop = undefined - - if (socket.readyState !== WebSocket.CLOSED && socket.readyState !== WebSocket.CLOSING) socket.close(1000) - } - - const handleClose = (event: CloseEvent) => { - if (ws === socket) ws = undefined - - if (drop === stop) drop = undefined - socket.removeEventListener("open", handleOpen) - socket.removeEventListener("message", handleMessage) - socket.removeEventListener("error", handleError) - socket.removeEventListener("close", handleClose) - - if (disposed) return - - if (event.code === 1000) return - retry(new Error(plugin.t("connectionLost.abnormalClose", { code: event.code }))) - } - - drop = stop - socket.addEventListener("open", handleOpen) - socket.addEventListener("message", handleMessage) - socket.addEventListener("error", handleError) - socket.addEventListener("close", handleClose) + if (typeof document !== "undefined" && document.fonts) { + void document.fonts.ready.then(measure) } - open() + measure() + await connect() } void run().catch((err) => { if (disposed) return - showToast({ - variant: "error", - title: plugin.t("connectionLost.title"), - description: err instanceof Error ? err.message : plugin.t("connectionLost.description"), - }) - local.onConnectError?.(err) + debugTerminal("failed to connect terminal", err) + connection.error() }) }) onCleanup(() => { disposed = true - if (fitFrame !== undefined) cancelAnimationFrame(fitFrame) + if (measureFrame !== undefined) cancelAnimationFrame(measureFrame) if (sizeTimer !== undefined) clearTimeout(sizeTimer) - if (reconn !== undefined) clearTimeout(reconn) - drop?.() - - if (ws && ws.readyState !== WebSocket.CLOSED && ws.readyState !== WebSocket.CLOSING) ws.close(1000) - - const finalize = () => { - persistTerminal({ term, addon: serializeAddon, cursor, id, onCleanup: props.onCleanup }) - cleanup() - } - - if (!output) { - finalize() - - return - } - - output.flush(finalize) + if (socket && socket.readyState !== WebSocket.CLOSED && socket.readyState !== WebSocket.CLOSING) socket.close(1000) + cleanup() }) return ( @@ -821,14 +552,22 @@ export const Terminal = (props: TerminalProps) => { opacity: 0, }} classList={{ - ...local.classList, "select-text": true, "size-full px-6 py-3 relative overflow-hidden": true, - [local.class ?? ""]: !!local.class, + [props.class ?? ""]: !!props.class, }} - {...others} /> - + + {(text) => ( +
+ {text()} +
+ )} +
+ {(target) => ( {(term) => } diff --git a/packages/gui-plugins/src/terminal/title.ts b/packages/gui-plugins/src/terminal/title.ts index 99a352a49b17..3327d1577bd7 100644 --- a/packages/gui-plugins/src/terminal/title.ts +++ b/packages/gui-plugins/src/terminal/title.ts @@ -1,5 +1,6 @@ const template = "Terminal {{number}}" +// Default titles, including those of releases that created them in the interface language. const numbered = [ template, "محطة طرفية {{number}}", @@ -9,34 +10,32 @@ const numbered = [ "เทอร์มินัล {{number}}", "终端 {{number}}", "終端機 {{number}}", -] +].map((text) => text.split("{{number}}")) export function defaultTitle(number: number) { return template.replace("{{number}}", String(number)) } -function isDefaultTitle(title: string, number: number) { - return numbered.some((text) => title === text.replace("{{number}}", String(number))) -} +/** The number of a default title such as "Terminal 2". */ +export function titleNumber(title: string) { + return numbered.flatMap(([before, after]) => { + if (!title.startsWith(before) || !title.endsWith(after)) return [] + + const digits = title.slice(before.length, title.length - after.length) -export function titleNumber(title: string, max: number) { - return Array.from({ length: max }, (_, idx) => idx + 1).find((number) => isDefaultTitle(title, number)) + return /^[1-9]\d*$/.test(digits) ? [Number(digits)] : [] + })[0] } +/** A terminal's label: a default title in the interface language, else the server's title. */ export const terminalTabLabel = (input: { title?: string - titleNumber?: number t: (key: string, vars?: Record) => string }) => { const title = input.title ?? "" - const number = input.titleNumber ?? 0 - const defaultTitle = Number.isFinite(number) && number > 0 && isDefaultTitle(title, number) - - if (title && !defaultTitle) return title - - if (number > 0) return input.t("title.numbered", { number }) + const number = titleNumber(title) - if (title) return title + if (number !== undefined) return input.t("title.numbered", { number }) - return input.t("tab.title") + return title || input.t("tab.title") } diff --git a/packages/gui-plugins/src/terminal/writer.test.ts b/packages/gui-plugins/src/terminal/writer.test.ts index 8e8604504fd6..6a2b5c5272b0 100644 --- a/packages/gui-plugins/src/terminal/writer.test.ts +++ b/packages/gui-plugins/src/terminal/writer.test.ts @@ -1,35 +1,49 @@ import { describe, expect, test } from "bun:test" import { terminalWriter } from "./writer" +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) + describe("terminalWriter", () => { - test("final flush preserves output queued behind an in-flight write", () => { - const scheduled: VoidFunction[] = [] - const completions: VoidFunction[] = [] - const events: string[] = [] - - const writer = terminalWriter( - (data, done) => { - events.push(data) - - if (done) completions.push(done) - }, - (flush) => scheduled.push(flush), - ) - - writer.push("build started\r\n") - scheduled.shift()?.() - writer.push("\x1b[32mPASS\x1b[0m ") - writer.push("session/history.test.ts\r\n") - writer.flush(() => events.push("persist and dispose")) - expect(events).toEqual(["build started\r\n"]) - completions.shift()?.() - scheduled.shift()?.() - expect(events).toEqual(["build started\r\n", "\x1b[32mPASS\x1b[0m session/history.test.ts\r\n"]) - completions.shift()?.() - expect(events).toEqual([ - "build started\r\n", - "\x1b[32mPASS\x1b[0m session/history.test.ts\r\n", - "persist and dispose", - ]) + test("writes queued bytes as one chunk and skips empty output", async () => { + const writes: string[] = [] + + const output = terminalWriter((data, done) => { + writes.push(new TextDecoder().decode(data)) + done() + }) + + output.push(new Uint8Array()) + await settle() + + expect(writes).toEqual([]) + + output.push(new TextEncoder().encode("one ")) + output.push(new Uint8Array()) + output.push(new TextEncoder().encode("two")) + await settle() + + expect(writes).toEqual(["one two"]) + }) + + test("runs a step only after the output before it is written, and before the output after it", async () => { + const log: string[] = [] + const pending: VoidFunction[] = [] + + const output = terminalWriter((data, done) => { + log.push(new TextDecoder().decode(data)) + pending.push(done) + }) + + output.push(new TextEncoder().encode("before")) + output.push(() => log.push("step")) + output.push(new TextEncoder().encode("after")) + await settle() + + expect(log).toEqual(["before"]) + + pending.shift()?.() + await settle() + + expect(log).toEqual(["before", "step", "after"]) }) }) diff --git a/packages/gui-plugins/src/terminal/writer.ts b/packages/gui-plugins/src/terminal/writer.ts index d58b0f3e47c0..e8e1ddf526ee 100644 --- a/packages/gui-plugins/src/terminal/writer.ts +++ b/packages/gui-plugins/src/terminal/writer.ts @@ -1,77 +1,62 @@ -export function terminalWriter( - write: (data: string, done?: VoidFunction) => void, - schedule: (flush: VoidFunction) => void = queueMicrotask, -) { - let chunks: string[] | undefined - let waits: VoidFunction[] | undefined +// Writes output and runs steps such as resizes in the order they were pushed. Consecutive output is written as one +// chunk, and nothing after it starts until the terminal reports that chunk done. +export function terminalWriter(write: (data: Uint8Array, done: VoidFunction) => void) { + const queue: (Uint8Array | VoidFunction)[] = [] let scheduled = false let writing = false - const settle = () => { - if (scheduled || writing || chunks?.length) return - const list = waits - - if (!list?.length) return - waits = undefined - - for (const fn of list) { - fn() - } + const wake = () => { + if (scheduled) return + scheduled = true + queueMicrotask(run) } const run = () => { - if (writing) return scheduled = false - const items = chunks - if (!items?.length) { - settle() + while (!writing && queue.length) { + const next = queue[0] - return - } - - chunks = undefined - writing = true - write(items.join(""), () => { - writing = false + if (!(next instanceof Uint8Array)) { + queue.shift() + next() - if (chunks?.length) { - if (scheduled) return - scheduled = true - schedule(run) - - return + continue } - settle() - }) - } + const end = queue.findIndex((item) => !(item instanceof Uint8Array)) - const push = (data: string) => { - if (!data) return + const chunks = queue + .splice(0, end === -1 ? queue.length : end) + .filter((item): item is Uint8Array => item instanceof Uint8Array) - if (chunks) chunks.push(data) - else chunks = [data] + writing = true + write(concat(chunks), () => { + writing = false - if (scheduled || writing) return - scheduled = true - schedule(run) + if (queue.length) wake() + }) + } } - const flush = (done?: VoidFunction) => { - if (!scheduled && !writing && !chunks?.length) { - done?.() + const push = (item: Uint8Array | VoidFunction) => { + if (item instanceof Uint8Array && !item.length) return + queue.push(item) - return - } + if (!writing) wake() + } - if (done) { - if (waits) waits.push(done) - else waits = [done] - } + return { push } +} - run() - } +function concat(chunks: Uint8Array[]) { + if (chunks.length === 1) return chunks[0] + const data = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0)) + chunks.reduce((offset, chunk) => { + data.set(chunk, offset) + + return offset + chunk.length + }, 0) - return { push, flush } + return data }