fix(app): drive the terminal pane through one state machine (#61941)

This commit is contained in:
Luke Parker
2026-11-04 23:03:17 -06:00
committed by GitHub
Unverified
parent aa048bcb89
commit 5e76d6a9b1
4 changed files with 937 additions and 261 deletions
@@ -118,6 +118,16 @@ story("does not send the emulator's own answers to terminal queries as input", a
expect(server.frames.filter((frame) => frame.type === 1).map((frame) => frame.data)).toEqual(["x"])
})
story("shows a terminal that has written nothing yet and stays silent", async ({ page, mount }) => {
// An empty checkpoint and no output: nothing ever reaches the emulator.
const server = await serveTerminal(page, { ptyID: "pty_silent", output: "" })
const root = await mountTerminal(page, mount, "pty_silent")
await expect.poll(() => server.sockets.length).toBe(1)
await expect(root.locator('[data-component="terminal"]')).toHaveCSS("opacity", "1")
await expect(root.locator("[data-failures]")).toHaveAttribute("data-failures", "0")
})
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")
@@ -0,0 +1,329 @@
import { describe, expect, test } from "bun:test"
import {
createPaneDispatch,
GHOSTTY_LOAD_TIMEOUT_MS,
initialPaneState,
paneFailure,
paneRevealed,
paneTerm,
TERMINAL_CONNECT_TIMEOUT_MS,
TERMINAL_SIZE_DEBOUNCE_MS,
transitionPane,
type PaneEffect,
type PaneEvent,
type PaneState,
type PaneTransition,
} from "./pane-machine"
type Loaded = { readonly ghostty: string }
type Term = { readonly id: string }
const LOADED: Loaded = { ghostty: "wasm" }
const TERM: Term = { id: "term" }
const SIZE = { cols: 90, rows: 28 }
type Event = PaneEvent<Loaded, Term>
// Folds the events in order and returns the last transition.
const replay = (events: readonly Event[], state: PaneState<Term> = initialPaneState) =>
events.reduce<PaneTransition<Loaded, Term>>((last, event) => transitionPane(last.state, event), {
state,
effects: [],
})
const loading: Event[] = [{ type: "mounted" }]
const opening: Event[] = [...loading, { type: "ghostty.loaded", loaded: LOADED }]
const connecting: Event[] = [...opening, { type: "terminal.opened", term: TERM, initialSize: SIZE }]
const live: Event[] = [...connecting, { type: "socket.opened" }]
const sampled = (proposed: { cols: number; rows: number } | undefined): Event => ({ type: "measure.sampled", proposed })
describe("terminal pane machine", () => {
test("a silent terminal with an empty screen shows once its socket opens", () => {
const opened = replay(connecting)
expect(opened.state.status).toBe("connecting")
expect(paneRevealed(opened.state)).toBe(false)
// The snapshot's checkpoint is empty and the shell prints nothing: no write ever reaches the emulator.
const next = replay(live)
expect(next.state).toEqual({ status: "live", term: TERM, sizing: { seq: 0, size: SIZE, pending: undefined } })
expect(next.effects).toEqual([{ type: "cancel-phase-timer" }])
expect(paneRevealed(next.state)).toBe(true)
})
test("the restored screen shows before the socket opens", () => {
const written = replay([...connecting, { type: "screen.written" }])
expect(written.state.status).toBe("connecting")
expect(paneRevealed(written.state)).toBe(true)
expect(replay([{ type: "screen.written" }], written.state).state).toBe(written.state)
})
test("loads, opens, then connects at the first size", () => {
const mounted = replay(loading)
expect(mounted.state).toEqual({ status: "loading" })
expect(mounted.effects).toEqual([{ type: "load-ghostty", timeoutMs: GHOSTTY_LOAD_TIMEOUT_MS }])
const loaded = replay(opening)
expect(loaded.state).toEqual({ status: "opening" })
expect(loaded.effects).toEqual([{ type: "cancel-phase-timer" }, { type: "open-terminal", loaded: LOADED }])
// The size goes out before the connect starts, so the replay's end can take control at it.
const opened = replay(connecting)
expect(opened.effects).toEqual([
{ type: "apply-size", size: SIZE },
{ type: "start-connect", timeoutMs: TERMINAL_CONNECT_TIMEOUT_MS },
])
expect(paneTerm(opened.state)).toBe(TERM)
})
test("a failure stops the socket and the connect attempt, tells the panel once, and keeps the screen", () => {
const failed = replay([...live, { type: "connection.failed", failure: "failed" }])
expect(failed.state).toEqual({ status: "failed", failure: "failed", term: TERM })
expect(failed.effects).toEqual([{ type: "stop" }, { type: "notify-failure" }])
expect(paneRevealed(failed.state)).toBe(true)
expect(paneFailure(failed.state)).toBe("failed")
expect(paneTerm(failed.state)).toBe(TERM)
const late: Event[] = [
{ type: "connection.failed", failure: "disconnected" },
{ type: "socket.opened" },
{ type: "phase.timed-out", phase: "connecting" },
{ type: "measure.requested" },
sampled({ cols: 100, rows: 30 }),
{ type: "size.debounced", seq: 1 },
{ type: "screen.written" },
]
late.forEach((event) => {
const next = transitionPane(failed.state, event)
expect(next.state).toBe(failed.state)
expect(next.effects).toEqual([])
})
// A connect attempt that fails before its socket opens stops the same way.
const early = replay([...connecting, { type: "connection.failed", failure: "outdated" }])
expect(early.state).toEqual({ status: "failed", failure: "outdated", term: TERM })
expect(early.effects).toEqual([{ type: "stop" }, { type: "notify-failure" }])
})
test("loading and connecting time out into a failure", () => {
const loadTimeout = replay([...loading, { type: "phase.timed-out", phase: "loading" }])
expect(loadTimeout.state).toEqual({ status: "failed", failure: "failed", term: undefined })
expect(loadTimeout.effects).toEqual([{ type: "stop" }, { type: "notify-failure" }])
expect(paneRevealed(loadTimeout.state)).toBe(true)
// ghostty-web arriving after the timeout never builds an emulator.
const late = transitionPane(loadTimeout.state, { type: "ghostty.loaded", loaded: LOADED })
expect(late.state).toBe(loadTimeout.state)
expect(late.effects).toEqual([])
const connectTimeout = replay([...connecting, { type: "phase.timed-out", phase: "connecting" }])
expect(connectTimeout.state).toEqual({ status: "failed", failure: "failed", term: TERM })
expect(connectTimeout.effects).toEqual([{ type: "stop" }, { type: "notify-failure" }])
expect(transitionPane(connectTimeout.state, { type: "socket.opened" }).state).toBe(connectTimeout.state)
// A timer of an earlier phase that fires late is ignored.
const stale: [Event[], Event][] = [
[connecting, { type: "phase.timed-out", phase: "loading" }],
[live, { type: "phase.timed-out", phase: "loading" }],
[live, { type: "phase.timed-out", phase: "connecting" }],
[loading, { type: "phase.timed-out", phase: "connecting" }],
]
stale.forEach(([events, event]) => {
const state = replay(events).state
const next = transitionPane(state, event)
expect(next.state).toBe(state)
expect(next.effects).toEqual([])
})
})
test("a failed load or open shows the failure without a screen", () => {
const load = replay([...loading, { type: "ghostty.failed" }])
expect(load.state).toEqual({ status: "failed", failure: "failed", term: undefined })
expect(load.effects).toEqual([{ type: "stop" }, { type: "notify-failure" }])
// The emulator may have opened partway, so it is released.
const open = replay([...opening, { type: "connection.failed", failure: "failed" }])
expect(open.state).toEqual({ status: "failed", failure: "failed", term: undefined })
expect(open.effects).toEqual([{ type: "release" }, { type: "notify-failure" }])
expect(paneTerm(open.state)).toBeUndefined()
})
test("a pane hidden when it opened applies its first measurement at once", () => {
const opened = replay([...opening, { type: "terminal.opened", term: TERM, initialSize: undefined }])
expect(opened.effects).toEqual([{ type: "start-connect", timeoutMs: TERMINAL_CONNECT_TIMEOUT_MS }])
const requested = transitionPane(opened.state, { type: "measure.requested" })
expect(requested.state).toBe(opened.state)
expect(requested.effects).toEqual([{ type: "schedule-measure" }])
// Still hidden.
expect(transitionPane(opened.state, sampled(undefined)).state).toBe(opened.state)
const shown = transitionPane(opened.state, sampled(SIZE))
expect(shown.effects).toEqual([{ type: "apply-size", size: SIZE }])
expect(transitionPane(shown.state, sampled(SIZE))).toEqual({ state: shown.state, effects: [] })
})
test("a resize waits out the debounce, and hiding or bouncing back cancels it", () => {
const wider = { cols: 110, rows: 32 }
const resized = replay([...live, sampled(wider)])
expect(resized.effects).toEqual([{ type: "schedule-size-timer", seq: 1, delayMs: TERMINAL_SIZE_DEBOUNCE_MS }])
// The same pending size again keeps its timer.
expect(transitionPane(resized.state, sampled(wider))).toEqual({ state: resized.state, effects: [] })
const applied = transitionPane(resized.state, { type: "size.debounced", seq: 1 })
expect(applied.effects).toEqual([{ type: "apply-size", size: wider }])
expect(applied.state).toMatchObject({ sizing: { seq: 1, size: wider, pending: undefined } })
// The tab hides while the resize waits: nothing goes out, even when the timer fires.
const hidden = transitionPane(resized.state, sampled(undefined))
expect(hidden.effects).toEqual([{ type: "cancel-size-timer" }])
expect(transitionPane(hidden.state, { type: "size.debounced", seq: 1 })).toEqual({
state: hidden.state,
effects: [],
})
const bounced = transitionPane(resized.state, sampled(SIZE))
expect(bounced.effects).toEqual([{ type: "cancel-size-timer" }])
expect(transitionPane(bounced.state, { type: "size.debounced", seq: 1 }).effects).toEqual([])
})
test("only the last resize's timer applies", () => {
const wider = { cols: 110, rows: 32 }
const widest = { cols: 120, rows: 35 }
const resized = replay([...live, sampled(wider), sampled(widest), sampled(wider)])
expect(resized.effects).toEqual([{ type: "schedule-size-timer", seq: 3, delayMs: TERMINAL_SIZE_DEBOUNCE_MS }])
expect(transitionPane(resized.state, { type: "size.debounced", seq: 1 }).state).toBe(resized.state)
expect(transitionPane(resized.state, { type: "size.debounced", seq: 2 }).state).toBe(resized.state)
expect(transitionPane(resized.state, { type: "size.debounced", seq: 3 }).effects).toEqual([
{ type: "apply-size", size: wider },
])
})
test("measurement waits for the emulator and stops with the pane", () => {
const states = [
initialPaneState,
replay(loading).state,
replay(opening).state,
replay([...live, { type: "connection.failed", failure: "disconnected" }]).state,
replay([...live, { type: "disposed" }]).state,
]
states.forEach((state) => {
const next = transitionPane<Loaded, Term>(state, { type: "measure.requested" })
expect(next.state).toBe(state)
expect(next.effects).toEqual([])
})
})
test("unmounting from any phase releases everything and tells nobody", () => {
const phases: Event[][] = [
[],
loading,
opening,
connecting,
live,
[...live, { type: "connection.failed", failure: "failed" }],
]
phases.forEach((events) => {
const disposed = replay([...events, { type: "disposed" }])
expect(disposed.state).toEqual({ status: "disposed" })
expect(disposed.effects).toEqual(events.length === 0 ? [] : [{ type: "release" }])
expect(paneRevealed(disposed.state)).toBe(false)
const after: Event[] = [
{ type: "mounted" },
{ type: "ghostty.loaded", loaded: LOADED },
{ type: "ghostty.failed" },
{ type: "terminal.opened", term: TERM, initialSize: SIZE },
{ type: "socket.opened" },
{ type: "connection.failed", failure: "failed" },
{ type: "phase.timed-out", phase: "connecting" },
{ type: "disposed" },
]
after.forEach((event) => {
const next = transitionPane(disposed.state, event)
expect(next.state).toBe(disposed.state)
expect(next.effects).toEqual([])
})
})
})
test("the driver applies events an effect dispatches after the current one, and fails a throwing open", async () => {
const order: string[] = []
let current: PaneState<Term> = initialPaneState
const dispatch = createPaneDispatch<Loaded, Term>({
read: () => current,
write: (next) => {
order.push(`state:${next.status}`)
current = next
},
run: (effect: PaneEffect<Loaded>) => {
order.push(`effect:${effect.type}`)
if (effect.type === "load-ghostty") dispatch({ type: "ghostty.loaded", loaded: LOADED })
if (effect.type === "open-terminal") throw new Error("WebGL context lost")
},
})
dispatch({ type: "mounted" })
expect(order).toEqual([
"state:loading",
"effect:load-ghostty",
"state:opening",
"effect:cancel-phase-timer",
"effect:open-terminal",
])
await Promise.resolve()
await Promise.resolve()
expect(current).toEqual({ status: "failed", failure: "failed", term: undefined })
expect(order.slice(5)).toEqual(["state:failed", "effect:release", "effect:notify-failure"])
// The queue still advances.
dispatch({ type: "disposed" })
expect(current).toEqual({ status: "disposed" })
})
})
@@ -0,0 +1,286 @@
import type { TerminalFailure, TerminalSize } from "./connection"
/** How long loading ghostty-web and its WASM binary may take before the pane fails. */
export const GHOSTTY_LOAD_TIMEOUT_MS = 30_000
/** How long fetching the snapshot, minting the ticket and opening the socket may take before the pane fails. */
export const TERMINAL_CONNECT_TIMEOUT_MS = 15_000
/** How long a resize after the first measurement waits before the pane asks for it. */
export const TERMINAL_SIZE_DEBOUNCE_MS = 100
/**
* The size this attachment asks the PTY for. `size` is the last one asked for, undefined while the pane has not
* measured yet (it was hidden when it opened). `pending` waits out the resize debounce; `seq` names it, so an older
* timer is ignored.
*/
export type PaneSizing = {
readonly seq: number
readonly size: TerminalSize | undefined
readonly pending: TerminalSize | undefined
}
/**
* One `<Terminal>` mount, which attaches to one PTY once and only moves forward. `T` is the opened ghostty-web
* `Terminal`. `opening` builds the emulator; `connecting` restores the snapshot and opens the socket, and shows once
* it wrote the screen (`shown`). `failed` keeps the last screen, when there is one, under the reason until unmount.
*/
export type PaneState<T> =
| { readonly status: "idle" }
| { readonly status: "loading" }
| { readonly status: "opening" }
| { readonly status: "connecting"; readonly term: T; readonly sizing: PaneSizing; readonly shown: boolean }
| { readonly status: "live"; readonly term: T; readonly sizing: PaneSizing }
| { readonly status: "failed"; readonly failure: TerminalFailure; readonly term: T | undefined }
| { readonly status: "disposed" }
export type PaneEvent<L, T> =
| { readonly type: "mounted" }
| { readonly type: "ghostty.loaded"; readonly loaded: L }
| { readonly type: "ghostty.failed" }
/** The emulator opened in the pane; `initialSize` is its first measurement, undefined while the pane is hidden. */
| { readonly type: "terminal.opened"; readonly term: T; readonly initialSize: TerminalSize | undefined }
/** The emulator wrote output for the first time. */
| { readonly type: "screen.written" }
| { readonly type: "socket.opened" }
/** The emulator could not open, or the snapshot, ticket, socket or protocol check failed, or the socket closed. */
| { readonly type: "connection.failed"; readonly failure: TerminalFailure }
| { readonly type: "phase.timed-out"; readonly phase: "loading" | "connecting" }
/** The container, window, font or zoom changed, so the pane measures again on the next frame. */
| { readonly type: "measure.requested" }
/** The frame's measurement; undefined while the pane is hidden. */
| { readonly type: "measure.sampled"; readonly proposed: TerminalSize | undefined }
| { readonly type: "size.debounced"; readonly seq: number }
| { readonly type: "disposed" }
export type PaneEffect<L> =
/** Loads ghostty-web, and times out as `phase.timed-out` `loading`. */
| { readonly type: "load-ghostty"; readonly timeoutMs: number }
| { readonly type: "cancel-phase-timer" }
/** Builds and opens the emulator, then reports `terminal.opened` synchronously. */
| { readonly type: "open-terminal"; readonly loaded: L }
/** Restores the snapshot and opens the socket, and times out as `phase.timed-out` `connecting`. */
| { readonly type: "start-connect"; readonly timeoutMs: number }
| { readonly type: "apply-size"; readonly size: TerminalSize }
/** Measures on the next frame, unless a frame is already queued. */
| { readonly type: "schedule-measure" }
/** Replaces the resize debounce timer. */
| { readonly type: "schedule-size-timer"; readonly seq: number; readonly delayMs: number }
| { readonly type: "cancel-size-timer" }
/** Cancels the phase timer and measurement, aborts the connect attempt and closes its socket; keeps the emulator. */
| { readonly type: "stop" }
/** Tells the panel, once per mount, that this pane failed (`props.onFailure`). */
| { readonly type: "notify-failure" }
/** Stops, then disposes the emulator, its listeners and focus timers. */
| { readonly type: "release" }
export type PaneTransition<L, T> = {
readonly state: PaneState<T>
readonly effects: readonly PaneEffect<L>[]
}
const NONE: readonly never[] = []
const MEASURE: readonly PaneEffect<never>[] = [{ type: "schedule-measure" }]
const CANCEL_SIZE: readonly PaneEffect<never>[] = [{ type: "cancel-size-timer" }]
const FAIL: readonly PaneEffect<never>[] = [{ type: "stop" }, { type: "notify-failure" }]
const RELEASE_AND_FAIL: readonly PaneEffect<never>[] = [{ type: "release" }, { type: "notify-failure" }]
const RELEASE: readonly PaneEffect<never>[] = [{ type: "release" }]
export const initialPaneState: PaneState<never> = { status: "idle" }
/**
* The pane loads ghostty-web, opens the emulator, then restores the snapshot and opens the socket. It shows once it
* wrote the screen, the socket opened, or it failed, so a silent terminal with an empty screen still shows. Loading
* and connecting are bounded by a timeout. Failing stops everything in flight and tells the panel once; unmounting
* releases everything and tells nobody.
*/
export function transitionPane<L, T>(state: PaneState<T>, event: PaneEvent<L, T>): PaneTransition<L, T> {
if (state.status === "disposed") return { state, effects: NONE }
if (event.type === "disposed")
return { state: { status: "disposed" }, effects: state.status === "idle" ? NONE : RELEASE }
if (state.status === "idle") {
if (event.type !== "mounted") return { state, effects: NONE }
return { state: { status: "loading" }, effects: [{ type: "load-ghostty", timeoutMs: GHOSTTY_LOAD_TIMEOUT_MS }] }
}
if (state.status === "loading") {
if (event.type === "ghostty.loaded")
return {
state: { status: "opening" },
effects: [{ type: "cancel-phase-timer" }, { type: "open-terminal", loaded: event.loaded }],
}
if (event.type === "ghostty.failed" || (event.type === "phase.timed-out" && event.phase === "loading"))
return { state: failed<T>("failed", undefined), effects: FAIL }
return { state, effects: NONE }
}
if (state.status === "opening") {
if (event.type === "terminal.opened") {
const connect: PaneEffect<L> = { type: "start-connect", timeoutMs: TERMINAL_CONNECT_TIMEOUT_MS }
return {
state: {
status: "connecting",
term: event.term,
sizing: { seq: 0, size: event.initialSize, pending: undefined },
shown: false,
},
effects: event.initialSize ? [{ type: "apply-size", size: event.initialSize }, connect] : [connect],
}
}
// The emulator may have opened partway; nothing of it stays.
if (event.type === "connection.failed")
return { state: failed<T>(event.failure, undefined), effects: RELEASE_AND_FAIL }
return { state, effects: NONE }
}
if (state.status === "failed") return { state, effects: NONE }
if (event.type === "connection.failed") return { state: failed(event.failure, state.term), effects: FAIL }
if (event.type === "measure.requested") return { state, effects: MEASURE }
if (event.type === "measure.sampled") return sampled(state, event.proposed)
if (event.type === "size.debounced") {
const sizing = state.sizing
if (!sizing.pending || sizing.seq !== event.seq) return { state, effects: NONE }
return {
state: { ...state, sizing: { seq: sizing.seq, size: sizing.pending, pending: undefined } },
effects: [{ type: "apply-size", size: sizing.pending }],
}
}
if (state.status === "live") return { state, effects: NONE }
if (event.type === "screen.written")
return state.shown ? { state, effects: NONE } : { state: { ...state, shown: true }, effects: NONE }
if (event.type === "socket.opened")
return {
state: { status: "live", term: state.term, sizing: state.sizing },
effects: [{ type: "cancel-phase-timer" }],
}
if (event.type === "phase.timed-out" && event.phase === "connecting")
return { state: failed("failed", state.term), effects: FAIL }
return { state, effects: NONE }
}
/** Whether the pane shows; until then it is transparent, so an empty emulator never flashes before the screen. */
export function paneRevealed<T>(state: PaneState<T>) {
if (state.status === "connecting") return state.shown
return state.status === "live" || state.status === "failed"
}
/** Why the pane failed, for its banner. */
export function paneFailure<T>(state: PaneState<T>) {
return state.status === "failed" ? state.failure : undefined
}
/** The opened emulator, also after a failure so the last screen stays readable and selectable. */
export function paneTerm<T>(state: PaneState<T>) {
return state.status === "connecting" || state.status === "live" || state.status === "failed" ? state.term : undefined
}
/** The event a throwing effect reports, so the pane fails instead of waiting forever. */
export function paneEffectFailed<L>(effect: PaneEffect<L>): PaneEvent<L, never> | undefined {
if (effect.type === "load-ghostty") return { type: "ghostty.failed" }
if (effect.type === "open-terminal" || effect.type === "start-connect")
return { type: "connection.failed", failure: "failed" }
}
/**
* The pane's driver loop: applies one event at a time and runs its effects. An effect may dispatch synchronously; its
* event waits until the current one has applied. A throwing effect reports `paneEffectFailed(effect)`, and nothing
* that throws stalls the queue.
*/
export function createPaneDispatch<L, T>(driver: {
readonly read: () => PaneState<T>
readonly write: (state: PaneState<T>) => void
readonly run: (effect: PaneEffect<L>) => void
}) {
const queue: PaneEvent<L, T>[] = []
const apply = (event: PaneEvent<L, T>) => {
const next = transitionPane(driver.read(), event)
driver.write(next.state)
next.effects.forEach((effect) => {
void Promise.try(() => driver.run(effect)).catch((cause: unknown) => {
const failure = paneEffectFailed(effect)
if (!failure) throw cause
dispatch(failure)
})
})
}
const dispatch = (event: PaneEvent<L, T>) => {
queue.push(event)
if (queue.length > 1) return
while (queue.length > 0) {
void Promise.try(apply, queue[0])
queue.shift()
}
}
return dispatch
}
function failed<T>(failure: TerminalFailure, term: T | undefined): PaneState<T> {
return { status: "failed", failure, term }
}
function sampled<L, T>(
state: Extract<PaneState<T>, { status: "connecting" | "live" }>,
proposed: TerminalSize | undefined,
): PaneTransition<L, T> {
const sizing = state.sizing
// Hidden, or back at the size already asked for: a pending resize no longer applies.
if (!proposed || same(proposed, sizing.size)) {
if (!sizing.pending) return { state, effects: NONE }
return { state: { ...state, sizing: { ...sizing, pending: undefined } }, effects: CANCEL_SIZE }
}
// The first measurement applies at once; nothing is pending before it.
if (!sizing.size)
return {
state: { ...state, sizing: { seq: sizing.seq, size: proposed, pending: undefined } },
effects: [{ type: "apply-size", size: proposed }],
}
if (same(proposed, sizing.pending)) return { state, effects: NONE }
const seq = sizing.seq + 1
return {
state: { ...state, sizing: { seq, size: sizing.size, pending: proposed } },
effects: [{ type: "schedule-size-timer", seq, delayMs: TERMINAL_SIZE_DEBOUNCE_MS }],
}
}
function same(a: TerminalSize, b: TerminalSize | undefined) {
return a.cols === b?.cols && a.rows === b.rows
}
+312 -261
View File
@@ -5,10 +5,20 @@ import { resolveThemeVariantV2 } from "@opencode/ui/theme/v2/resolve"
import type { HexColor, ResolvedV2Theme } from "@opencode/ui/theme/types"
import { createPersistentPtyClient } from "@opencode/client/solid"
import type { FitAddon, Terminal as Term } from "ghostty-web"
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
import { createMemo, createSignal, onCleanup, onMount, Show, untrack } from "solid-js"
import { createKeyed, usePlugin } from "@opencode/plugin/gui"
import { uuid } from "@opencode/util/uuid"
import { terminalConnection, type TerminalFailure } from "./connection"
import { terminalConnection } from "./connection"
import {
createPaneDispatch,
initialPaneState,
paneFailure,
paneRevealed,
paneTerm,
type PaneEffect,
type PaneEvent,
type PaneState,
} from "./pane-machine"
import type { TerminalProps } from "./props"
import { disposeIfDisposable, getHoveredLinkText, setOptionIfSupported } from "./runtime-adapters"
import { consumeTerminalMetaKey, terminalKeyInput } from "./terminal-key-event"
@@ -36,13 +46,28 @@ const DEFAULT_TERMINAL_COLORS = {
},
} as const satisfies Record<"light" | "dark", TerminalColors>
const isHexColor = (value: string): value is HexColor => value.startsWith("#")
type Loaded = Awaited<ReturnType<TerminalProps["ghostty"]>>
const debugTerminal = (...values: unknown[]) => {
if (!import.meta.env.DEV) return
console.debug("[terminal]", ...values)
/**
* What the pane's effects hold between events; only `run` in `Terminal` changes them. `phaseTimer` bounds loading and
* connecting, `connect` aborts the connect attempt and detaches its socket's listeners, and `cleanups` dispose the
* emulator and its listeners.
*/
type PaneHandles = {
phaseTimer?: ReturnType<typeof setTimeout>
measureFrame?: number
sizeTimer?: ReturnType<typeof setTimeout>
focusTimer?: ReturnType<typeof setTimeout>
connect?: AbortController
socket?: WebSocket
fit?: FitAddon
cleanups: VoidFunction[]
}
const MEASURE_REQUESTED: PaneEvent<Loaded, Term> = { type: "measure.requested" }
const isHexColor = (value: string): value is HexColor => value.startsWith("#")
const resolveV2Token = (tokens: ResolvedV2Theme, key: string) => {
let current = tokens[key]
@@ -138,30 +163,25 @@ export const Terminal = (props: TerminalProps) => {
// 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 fitAddon: FitAddon | undefined
let measureFrame: number | undefined
let sizeTimer: ReturnType<typeof setTimeout> | undefined
let measured = false
let revealed = false
let disposed = false
const cleanups: VoidFunction[] = []
// The opened terminal, for the quote toolbar.
const [opened, setOpened] = createSignal<Term>()
const handles: PaneHandles = { cleanups: [] }
const [paneState, setPaneState] = createSignal<PaneState<Term>>(initialPaneState)
const [written, setWritten] = createSignal(0)
const [failure, setFailure] = createSignal<TerminalFailure>()
const reveal = () => {
if (revealed) return
revealed = true
container.style.opacity = "1"
}
const dispatch = createPaneDispatch<Loaded, Term>({
read: () => untrack(paneState),
write: (next) => setPaneState(next),
run,
})
const measure = () => dispatch(MEASURE_REQUESTED)
const connection = terminalConnection({
attachmentID,
write: (data, done) => {
if (disposed || !term) {
const current = untrack(paneState)
const term = paneTerm(current)
if (!term) {
done()
return
@@ -171,24 +191,22 @@ export const Terminal = (props: TerminalProps) => {
setWritten((value) => value + 1)
done()
})
reveal()
if (!paneRevealed(current)) dispatch({ type: "screen.written" })
},
resize: (size) => {
if (!disposed) term?.resize(size.cols, size.rows)
paneTerm(untrack(paneState))?.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)
if (handles.socket?.readyState === WebSocket.OPEN) handles.socket.send(frame)
},
fail: (reason) => dispatch({ type: "connection.failed", failure: reason }),
})
const revealed = createMemo(() => paneRevealed(paneState()))
const failure = createMemo(() => paneFailure(paneState()))
const opened = createMemo(() => paneTerm(paneState()))
const failureText = () => {
const current = failure()
@@ -199,19 +217,6 @@ export const Terminal = (props: TerminalProps) => {
if (current === "outdated") return plugin.t("serverOutdated")
}
const cleanup = () => {
if (!cleanups.length) return
const fns = cleanups.splice(0).reverse()
for (const fn of fns) {
try {
fn()
} catch (err) {
debugTerminal("cleanup failed", err)
}
}
}
const getTerminalColors = (): TerminalColors => {
const mode = theme.mode() === "dark" ? "dark" : "light"
const fallback = DEFAULT_TERMINAL_COLORS[mode]
@@ -241,51 +246,25 @@ export const Terminal = (props: TerminalProps) => {
const terminalColors = createMemo(getTerminalColors)
// 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 (measureFrame !== undefined) return
measureFrame = requestAnimationFrame(() => {
measureFrame = undefined
if (disposed) return
const next = fitAddon?.proposeDimensions()
if (!next) return
if (!measured) {
measured = true
connection.size(next)
return
}
if (sizeTimer !== undefined) clearTimeout(sizeTimer)
sizeTimer = setTimeout(() => {
sizeTimer = undefined
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.
createKeyed(
() => ({ colors: terminalColors(), mode: theme.mode() === "dark" ? "dark" : "light" }),
(current) => {
const term = paneTerm(untrack(paneState))
if (!term) return
setOptionIfSupported(term, "theme", current.colors)
setOptionIfSupported(term, "colorScheme", current.mode)
},
{ equals: (previous, next) => previous.colors === next.colors && previous.mode === next.mode },
)
createKeyed(
() => appearance.font("mono"),
(font) => {
const term = paneTerm(untrack(paneState))
if (!term) return
setOptionIfSupported(term, "fontFamily", font)
@@ -293,22 +272,16 @@ export const Terminal = (props: TerminalProps) => {
},
)
// A new zoom remeasures; the first value finds no fit addon yet.
// A new zoom remeasures; the pane ignores it until the terminal opened.
createKeyed(
() => desktop?.zoom(),
() => measure(),
)
const focusTerminal = () => {
const t = term
if (!t) return
const focusTerminal = (t: Term) => {
// 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 = () => {
if (disposed) return
const current = document.activeElement
if (current instanceof HTMLInputElement && current.closest('[role="tablist"]')) return
@@ -319,10 +292,11 @@ export const Terminal = (props: TerminalProps) => {
}
focus()
setTimeout(focus, 0)
clearTimeout(handles.focusTimer)
handles.focusTimer = setTimeout(focus, 0)
}
const handlePointerDown = () => {
const handlePointerDown = (t: Term) => {
const activeElement = document.activeElement
if (activeElement instanceof HTMLElement && activeElement !== container && !container.contains(activeElement)) {
@@ -330,20 +304,16 @@ export const Terminal = (props: TerminalProps) => {
}
connection.interact()
focusTerminal()
focusTerminal(t)
}
const handleLinkClick = (event: MouseEvent) => {
const handleLinkClick = (t: Term, event: MouseEvent) => {
if (!event.shiftKey && !event.ctrlKey && !event.metaKey) return
if (event.altKey) return
if (event.button !== 0) return
const t = term
if (!t) return
const text = getHoveredLinkText(t)
if (!text) return
@@ -353,191 +323,272 @@ export const Terminal = (props: TerminalProps) => {
system.openExternal(text)
}
const connect = async () => {
function run(effect: PaneEffect<Loaded>) {
if (effect.type === "load-ghostty") {
handles.phaseTimer = setTimeout(() => dispatch({ type: "phase.timed-out", phase: "loading" }), effect.timeoutMs)
void props.ghostty().then(
(loaded) => dispatch({ type: "ghostty.loaded", loaded }),
(cause: unknown) => {
if (import.meta.env.DEV) console.debug("[terminal] failed to load ghostty-web", cause)
dispatch({ type: "ghostty.failed" })
},
)
return
}
if (effect.type === "cancel-phase-timer") {
clearTimeout(handles.phaseTimer)
handles.phaseTimer = undefined
return
}
if (effect.type === "open-terminal") return open(effect.loaded)
if (effect.type === "start-connect") {
const controller = new AbortController()
handles.connect = controller
handles.phaseTimer = setTimeout(
() => dispatch({ type: "phase.timed-out", phase: "connecting" }),
effect.timeoutMs,
)
void connect(controller.signal).catch((cause: unknown) => {
if (controller.signal.aborted) return
if (import.meta.env.DEV) console.debug("[terminal] failed to connect terminal", cause)
connection.error()
})
return
}
if (effect.type === "apply-size") return connection.size(effect.size)
if (effect.type === "schedule-measure") {
if (handles.measureFrame !== undefined) return
handles.measureFrame = requestAnimationFrame(() => {
handles.measureFrame = undefined
dispatch({ type: "measure.sampled", proposed: handles.fit?.proposeDimensions() })
})
return
}
if (effect.type === "schedule-size-timer") {
clearTimeout(handles.sizeTimer)
handles.sizeTimer = setTimeout(() => {
handles.sizeTimer = undefined
dispatch({ type: "size.debounced", seq: effect.seq })
}, effect.delayMs)
return
}
if (effect.type === "cancel-size-timer") {
clearTimeout(handles.sizeTimer)
handles.sizeTimer = undefined
return
}
if (effect.type === "notify-failure") return props.onFailure?.()
stop()
if (effect.type === "stop") return
clearTimeout(handles.focusTimer)
handles.focusTimer = undefined
handles.fit = undefined
handles.cleanups
.splice(0)
.reverse()
.forEach((fn) => {
try {
fn()
} catch (err) {
if (import.meta.env.DEV) console.debug("[terminal] cleanup failed", err)
}
})
}
// Ends what is in flight: the phase timer, measurement, the connect attempt and its socket. The emulator stays.
function stop() {
clearTimeout(handles.phaseTimer)
handles.phaseTimer = undefined
if (handles.measureFrame !== undefined) cancelAnimationFrame(handles.measureFrame)
handles.measureFrame = undefined
clearTimeout(handles.sizeTimer)
handles.sizeTimer = undefined
// Aborting detaches the socket's listeners, so closing it reports nothing.
handles.connect?.abort()
handles.connect = undefined
const socket = handles.socket
handles.socket = undefined
if (socket?.readyState === WebSocket.CONNECTING || socket?.readyState === WebSocket.OPEN) socket.close(1000)
}
function open(loaded: Loaded) {
const mod = loaded.mod
const t = new mod.Terminal({
cursorBlink: true,
cursorStyle: "bar",
fontSize: 14,
fontFamily: appearance.font("mono"),
allowTransparency: false,
convertEol: false,
theme: terminalColors(),
scrollback: 10_000,
ghostty: loaded.ghostty,
})
handles.cleanups.push(() => t.dispose())
setOptionIfSupported(t, "colorScheme", theme.mode() === "dark" ? "dark" : "light")
t.attachCustomKeyEventHandler((event) => {
const key = event.key.toLowerCase()
const input = terminalKeyInput(event)
if (input) {
t.input(input, true)
return true
}
if (event.ctrlKey && event.shiftKey && !event.metaKey && key === "c") {
document.execCommand("copy")
return true
}
// allow for toggle terminal keybinds in parent
if (keybinds.matches("terminal.toggle", event)) return true
return consumeTerminalMetaKey(event, {
paste: () => void document.execCommand("paste"),
copy: () => t.hasSelection() && (document.execCommand("copy") || t.copySelection()),
})
})
const fit = new mod.FitAddon()
handles.cleanups.push(() => disposeIfDisposable(fit))
t.loadAddon(fit)
handles.fit = fit
const active = document.activeElement
t.open(container)
useTerminalUiBindings({
container,
term: t,
cleanups: handles.cleanups,
handlePointerDown: () => handlePointerDown(t),
handleLinkClick: (event) => handleLinkClick(t, event),
handleFocus: () => connection.interact(),
})
// onAutoFocus consumes the request, which flips autoFocus, so read it once, now that the terminal opened: the
// panel may cancel a request it made while mounting this pane.
const autoFocus = props.autoFocus === true
if (autoFocus) {
focusTerminal(t)
props.onAutoFocus?.()
}
if (!autoFocus) {
const restoreFocus = () => {
const current = document.activeElement
if (current !== container && !container.contains(current)) return
t.blur()
t.textarea?.blur()
if (active instanceof HTMLElement && active.isConnected) active.focus()
}
restoreFocus()
const timer = setTimeout(restoreFocus, 0)
handles.cleanups.push(() => clearTimeout(timer))
}
const onData = t.onData((data) => connection.input(data))
handles.cleanups.push(() => disposeIfDisposable(onData))
const onKey = t.onKey((key) => {
if (key.key == "Enter") {
props.onSubmit?.()
}
})
handles.cleanups.push(() => disposeIfDisposable(onKey))
// 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.
const observer = new ResizeObserver(measure)
observer.observe(container)
handles.cleanups.push(() => observer.disconnect())
window.addEventListener("resize", measure)
handles.cleanups.push(() => window.removeEventListener("resize", measure))
void document.fonts.ready.then(measure)
// The container is laid out once the emulator opened in it, so the first size goes out before the socket opens.
dispatch({ type: "terminal.opened", term: t, initialSize: fit.proposeDimensions() })
}
async function connect(signal: AbortSignal) {
const server = props.server
const snapshot = await server.client.experimental.persistentPty.snapshot({ ptyID })
if (disposed) return
if (signal.aborted) return
connection.restore({ size: snapshot.info.size, checkpoint: snapshot.checkpoint })
const next = await createPersistentPtyClient(server.client, { url: server.url }).connect({
const socket = await createPersistentPtyClient(server.client, { url: server.url }).connect({
ptyID,
cursor: snapshot.info.output.tail,
attachmentID,
takeover: true,
})
if (disposed) {
next.close(1000)
if (signal.aborted) {
socket.close(1000)
return
}
socket = next
next.addEventListener("message", (event) => {
if (disposed) return
handles.socket = socket
socket.addEventListener("open", () => dispatch({ type: "socket.opened" }), { signal })
socket.addEventListener(
"message",
(event) => {
if (event.data instanceof ArrayBuffer) {
connection.output(new Uint8Array(event.data))
if (event.data instanceof ArrayBuffer) {
connection.output(new Uint8Array(event.data))
return
}
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 PTY client receives binary frames as ArrayBuffers, handled above; the rest are text.
connection.message(String(event.data))
},
{ signal },
)
socket.addEventListener(
"error",
(event) => {
if (import.meta.env.DEV) console.debug("[terminal] websocket error", event)
connection.error()
},
{ signal },
)
// The removal event closes the tab separately; keep the terminal visible until then.
next.addEventListener("close", () => {
if (!disposed) connection.close()
})
socket.addEventListener("close", () => connection.close(), { signal })
}
onMount(() => {
const run = async () => {
const loaded = await props.ghostty()
if (disposed) return
const mod = loaded.mod
const g = loaded.ghostty
const t = new mod.Terminal({
cursorBlink: true,
cursorStyle: "bar",
fontSize: 14,
fontFamily: appearance.font("mono"),
allowTransparency: false,
convertEol: false,
theme: terminalColors(),
scrollback: 10_000,
ghostty: g,
})
cleanups.push(() => t.dispose())
if (disposed) {
cleanup()
return
}
term = t
setOptionIfSupported(t, "colorScheme", theme.mode() === "dark" ? "dark" : "light")
t.attachCustomKeyEventHandler((event) => {
const key = event.key.toLowerCase()
const input = terminalKeyInput(event)
if (input) {
t.input(input, true)
return true
}
if (event.ctrlKey && event.shiftKey && !event.metaKey && key === "c") {
document.execCommand("copy")
return true
}
// allow for toggle terminal keybinds in parent
if (keybinds.matches("terminal.toggle", event)) return true
return consumeTerminalMetaKey(event, {
paste: () => void document.execCommand("paste"),
copy: () => t.hasSelection() && (document.execCommand("copy") || t.copySelection()),
})
})
const fit = new mod.FitAddon()
cleanups.push(() => disposeIfDisposable(fit))
t.loadAddon(fit)
fitAddon = fit
const active = document.activeElement
t.open(container)
useTerminalUiBindings({
container,
term: t,
cleanups,
handlePointerDown,
handleLinkClick,
handleFocus: () => connection.interact(),
})
setOpened(t)
// onAutoFocus consumes the request, which flips autoFocus, so read it once.
const autoFocus = props.autoFocus === true
if (autoFocus) {
focusTerminal()
props.onAutoFocus?.()
}
if (!autoFocus) {
const restoreFocus = () => {
const current = document.activeElement
if (current !== container && !container.contains(current)) return
t.blur()
t.textarea?.blur()
if (active instanceof HTMLElement && active.isConnected) active.focus()
}
restoreFocus()
const timer = setTimeout(restoreFocus, 0)
cleanups.push(() => clearTimeout(timer))
}
const onData = t.onData((data) => connection.input(data))
cleanups.push(() => disposeIfDisposable(onData))
const onKey = t.onKey((key) => {
if (key.key == "Enter") {
props.onSubmit?.()
}
})
cleanups.push(() => disposeIfDisposable(onKey))
const observer = new ResizeObserver(measure)
observer.observe(container)
cleanups.push(() => observer.disconnect())
window.addEventListener("resize", measure)
cleanups.push(() => window.removeEventListener("resize", measure))
if (typeof document !== "undefined" && document.fonts) {
void document.fonts.ready.then(measure)
}
measure()
await connect()
}
void run().catch((err) => {
if (disposed) return
debugTerminal("failed to connect terminal", err)
connection.error()
})
})
onCleanup(() => {
disposed = true
if (measureFrame !== undefined) cancelAnimationFrame(measureFrame)
if (sizeTimer !== undefined) clearTimeout(sizeTimer)
if (socket && socket.readyState !== WebSocket.CLOSED && socket.readyState !== WebSocket.CLOSING) socket.close(1000)
cleanup()
})
onMount(() => dispatch({ type: "mounted" }))
onCleanup(() => dispatch({ type: "disposed" }))
return (
<>
@@ -551,7 +602,7 @@ export const Terminal = (props: TerminalProps) => {
"background-color": terminalColors().background,
"caret-color": "transparent",
"font-family": appearance.font("mono"),
opacity: 0,
opacity: revealed() ? 1 : 0,
}}
classList={{
"select-text": true,