fix(app): show failed terminal lists with retry and reject stale answers (#61650)

This commit is contained in:
Luke Parker 2026-11-04 10:44:53 -06:00 • committed by GitHub
parent b562a00d34
commit 0c441474bd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 971 additions and 184 deletions

View file

@ -217,6 +217,35 @@ test("a dropped connection says the terminal disconnected and keeps its tab", as
expect(await terminalText(page, screen)).toBe("still-here")
})
test("a terminal list that fails says why, and Try again lists the terminals", async ({ page }) => {
const { persistentPty } = await openSession(page, {
name: "Terminals",
persistentPty: { initial: [{ id: "pty_build", 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_build")
await expect.poll(() => terminalText(page, screen)).toBe("still-here")
// The restored session's list fails with an error other than the daemon's 503.
persistentPty.listFails = true
await page.reload()
const failure = side(page).getByRole("alert")
await expect(failure.getByText("Couldn't load terminals", { exact: true })).toBeVisible()
await expect(failure.getByText("UnexpectedStatus: 500", { exact: true })).toBeVisible()
// Without the list the restored tab has no title yet, but it shows and stays selected.
await expect(side(page).getByRole("tab", { name: "Terminal", exact: true })).toHaveAttribute("aria-selected", "true")
persistentPty.listFails = false
await failure.getByRole("button", { name: "Try again", exact: true }).click()
await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toHaveAttribute("aria-selected", "true")
await expect.poll(() => terminalText(page, screen)).toBe("still-here")
await expect(side(page).getByText("Couldn't load terminals", { exact: true })).toHaveCount(0)
})
test("after a server restart, showing the terminal again restores it from a new snapshot", async ({ page }) => {
const output = "before-restart\r\n"

View file

@ -277,7 +277,7 @@ const Group = HttpApiGroup.make("mock")
HttpApiEndpoint.get("persistentPtyList", "/api/experimental/session/:sessionID/terminal", {
params: SessionParams,
success: Json,
error: PersistentPtyUnavailable,
error: [PersistentPtyUnavailable, MockInternal.pipe(HttpApiSchema.status(500))],
}),
)
.add(

View file

@ -1047,7 +1047,13 @@ function mockHandlers(
// Like the server, which also answers 204 for a shell that already ended.
shellRemove: () => noContent,
persistentPtyList: (ctx) =>
persistentPtyEnabled.pipe(Effect.map(() => ({ data: state.persistentPty.list(ctx.params.sessionID) }))),
persistentPtyEnabled.pipe(
Effect.andThen(() =>
state.persistentPty.listFails
? Effect.fail(new MockInternal({ message: "Listing terminals failed" }))
: Effect.succeed({ data: state.persistentPty.list(ctx.params.sessionID) }),
),
),
persistentPtyCreate: (ctx) =>
persistentPtyEnabled.pipe(
Effect.map(() => {

View file

@ -108,6 +108,9 @@ export type MockPersistentPty = {
// Read by `/api/info`; tests may change both mid-test.
capability: boolean | undefined
renameSupported: boolean
// Whether listing a session's terminals answers 500, an error other than the daemon's 503. Starts false; tests may
// change it mid-test.
listFails: boolean
// Live terminals in creation order.
terminals: MockPersistentPtyInfo[]
created: MockPersistentPtyInfo[]
@ -336,6 +339,7 @@ export function createPersistentPty(
const pty: MockPersistentPty = {
capability: input.config?.capability,
renameSupported: input.config?.renameSupported ?? true,
listFails: false,
terminals: [],
created: [],
removed: [],

View file

@ -5,6 +5,8 @@ export default {
"command.new.description": "Create a new terminal tab",
"location.open": "Open in terminal",
loading: "Loading terminal…",
"list.failed": "Couldn't load terminals",
unavailable: "Terminals aren't available on this server",
"title.numbered": "Terminal {{number}}",
close: "Close terminal",
"create.failed": "Couldn't create a terminal",

View file

@ -0,0 +1,269 @@
import { describe, expect, test } from "bun:test"
import type { PersistentPtyInfo } from "@opencode/client"
import {
initialState,
serverAvailable,
sessionView,
tabHidden,
transition,
viewTabs,
type Event,
type State,
type Transition,
} from "./machine"
const info = (id: string, title = id): PersistentPtyInfo => ({
id,
title,
userTitle: null,
command: "/bin/zsh",
args: [],
cwd: "/repo",
status: "running",
pid: 1,
sessionID: "ses_1",
foregroundProcess: null,
size: { cols: 80, rows: 24 },
output: { head: 0, tail: 0 },
})
// Folds the events in order and returns the last transition.
const replay = (events: readonly Event[], state: State = initialState) =>
events.reduce<Transition>((last, event) => transition(last.state, event), { state, commands: [] })
// A supported server whose ses_1 listed pty_1 with attempt 2.
const listed = () =>
replay([
{ type: "server.connected" },
{ type: "session.loaded", sessionID: "ses_1" },
{ type: "capability.checked", attempt: 1, supported: true },
{ type: "list.loaded", sessionID: "ses_1", attempt: 2, items: [info("pty_1")] },
]).state
describe("terminal machine", () => {
test("a list that fails with an error other than 503 shows its error and its tabs, and retries on request", () => {
const failed = replay([
{ type: "session.loaded", sessionID: "ses_1" },
{ type: "capability.checked", attempt: 1, supported: true },
{ type: "list.failed", sessionID: "ses_1", attempt: 2, error: "boom" },
])
const view = sessionView(failed.state, "ses_1")
expect(view).toEqual({ type: "failed", error: "boom" })
expect(tabHidden(view)).toBe(false)
expect(viewTabs(view, ["pty_restored"])).toEqual(["pty_restored"])
expect(serverAvailable(failed.state)).toBe(true)
const retried = transition(failed.state, { type: "session.retry", sessionID: "ses_1" })
expect(sessionView(retried.state, "ses_1")).toEqual({ type: "loading" })
expect(retried.commands).toEqual([{ type: "load-list", sessionID: "ses_1", attempt: 3 }])
const loaded = transition(retried.state, {
type: "list.loaded",
sessionID: "ses_1",
attempt: 3,
items: [info("pty_1")],
})
expect(sessionView(loaded.state, "ses_1")).toEqual({ type: "ready", items: [info("pty_1")] })
expect(loaded.commands).toEqual([{ type: "sync-tabs", sessionID: "ses_1", items: [info("pty_1")] }])
})
test("loading a session again changes nothing, so reactive reads never retry a failed list", () => {
const loading = replay([
{ type: "session.loaded", sessionID: "ses_1" },
{ type: "capability.checked", attempt: 1, supported: true },
]).state
const failed = transition(loading, { type: "list.failed", sessionID: "ses_1", attempt: 2, error: "boom" }).state
const states = [loading, failed, listed()]
states.forEach((state) => {
const again = transition(state, { type: "session.loaded", sessionID: "ses_1" })
expect(again.state).toBe(state)
expect(again.commands).toEqual([])
})
// Retrying anything but a failed list repeats nothing.
expect(transition(loading, { type: "session.retry", sessionID: "ses_1" }).state).toBe(loading)
})
test("a support answer from before a reconnect is ignored", () => {
const rechecked = replay([
{ type: "server.connected" },
{ type: "session.loaded", sessionID: "ses_1" },
{ type: "server.connected" },
])
expect(rechecked.commands).toEqual([{ type: "check-capability", attempt: 2 }])
const stale = replay(
[
{ type: "capability.checked", attempt: 1, supported: false },
{ type: "capability.failed", attempt: 1, error: "offline" },
],
rechecked.state,
)
expect(stale.state).toBe(rechecked.state)
const supported = transition(rechecked.state, { type: "capability.checked", attempt: 2, supported: true })
expect(supported.state.status).toBe("supported")
expect(supported.commands).toEqual([{ type: "load-list", sessionID: "ses_1", attempt: 3 }])
})
test("only the latest list request settles a session", () => {
const refreshing = transition(listed(), { type: "session.refresh", sessionID: "ses_1" })
expect(refreshing.commands).toEqual([{ type: "load-list", sessionID: "ses_1", attempt: 3 }])
const newer = transition(refreshing.state, { type: "session.refresh", sessionID: "ses_1" })
const stale = replay(
[
{ type: "list.loaded", sessionID: "ses_1", attempt: 3, items: [] },
{ type: "list.failed", sessionID: "ses_1", attempt: 3, error: "old" },
{ type: "list.unavailable", sessionID: "ses_1", attempt: 3 },
],
newer.state,
)
expect(stale.state).toBe(newer.state)
expect(sessionView(newer.state, "ses_1")).toEqual({ type: "ready", items: [info("pty_1")] })
const settled = transition(newer.state, {
type: "list.loaded",
sessionID: "ses_1",
attempt: 4,
items: [info("pty_1"), info("pty_2")],
})
expect(sessionView(settled.state, "ses_1")).toEqual({ type: "ready", items: [info("pty_1"), info("pty_2")] })
})
test("a 503 for the latest request marks the server unavailable until a reconnect finds support", () => {
const loading = transition(listed(), { type: "session.refresh", sessionID: "ses_1" }).state
const unavailable = transition(loading, { type: "list.unavailable", sessionID: "ses_1", attempt: 3 }).state
const view = sessionView(unavailable, "ses_1")
expect(serverAvailable(unavailable)).toBe(false)
expect(view).toEqual({ type: "unsupported" })
expect(tabHidden(view)).toBe(true)
expect(viewTabs(view, ["pty_1"])).toEqual(["pty_1"])
const reconnected = transition(unavailable, { type: "server.connected" })
expect(reconnected.commands).toEqual([{ type: "check-capability", attempt: 4 }])
const supported = transition(reconnected.state, { type: "capability.checked", attempt: 4, supported: true })
expect(supported.commands).toEqual([{ type: "load-list", sessionID: "ses_1", attempt: 5 }])
})
test("a failed refresh keeps the terminals already shown", () => {
const refreshing = transition(listed(), { type: "session.refresh", sessionID: "ses_1" }).state
expect(sessionView(refreshing, "ses_1")).toEqual({ type: "ready", items: [info("pty_1")] })
const failed = transition(refreshing, { type: "list.failed", sessionID: "ses_1", attempt: 3, error: "boom" })
expect(sessionView(failed.state, "ses_1")).toEqual({ type: "ready", items: [info("pty_1")] })
})
test("a reconnect keeps listed terminals shown, drops answers from before it, and lists every session again", () => {
const supported = transition(listed(), { type: "session.loaded", sessionID: "ses_2" })
expect(supported.commands).toEqual([{ type: "load-list", sessionID: "ses_2", attempt: 3 }])
const rechecking = transition(supported.state, { type: "server.connected" })
expect(rechecking.commands).toEqual([{ type: "check-capability", attempt: 4 }])
expect(sessionView(rechecking.state, "ses_1")).toEqual({ type: "ready", items: [info("pty_1")] })
expect(sessionView(rechecking.state, "ses_2")).toEqual({ type: "loading" })
const late = transition(rechecking.state, { type: "list.unavailable", sessionID: "ses_2", attempt: 3 })
expect(late.state).toBe(rechecking.state)
const relisted = transition(rechecking.state, { type: "capability.checked", attempt: 4, supported: true })
expect(relisted.commands).toEqual([
{ type: "load-list", sessionID: "ses_1", attempt: 5 },
{ type: "load-list", sessionID: "ses_2", attempt: 6 },
])
expect(sessionView(relisted.state, "ses_1")).toEqual({ type: "ready", items: [info("pty_1")] })
})
test("a terminal update replaces a listed terminal and lists again for an unknown one", () => {
const state = listed()
const renamed = transition(state, {
type: "terminal.updated",
sessionID: "ses_1",
terminal: info("pty_1", "build"),
})
expect(renamed.commands).toEqual([])
expect(sessionView(renamed.state, "ses_1")).toEqual({ type: "ready", items: [info("pty_1", "build")] })
const unknown = transition(state, { type: "terminal.updated", sessionID: "ses_1", terminal: info("pty_9") })
expect(unknown.commands).toEqual([{ type: "load-list", sessionID: "ses_1", attempt: 3 }])
// A local change to a terminal the list doesn't have, or an update for a session never loaded, changes nothing.
expect(transition(state, { type: "terminal.replaced", sessionID: "ses_1", terminal: info("pty_9") }).state).toBe(
state,
)
expect(transition(state, { type: "terminal.updated", sessionID: "ses_9", terminal: info("pty_9") }).state).toBe(
state,
)
})
test("answers for a removed session are ignored", () => {
const loading = replay([
{ type: "session.loaded", sessionID: "ses_1" },
{ type: "capability.checked", attempt: 1, supported: true },
{ type: "sessions.removed", sessionIDs: ["ses_1"] },
]).state
const late = replay(
[
{ type: "list.loaded", sessionID: "ses_1", attempt: 2, items: [info("pty_1")] },
{ type: "list.unavailable", sessionID: "ses_1", attempt: 2 },
{ type: "list.failed", sessionID: "ses_1", attempt: 2, error: "boom" },
],
loading,
)
expect(late.state).toBe(loading)
// Loading it again takes a new attempt rather than reusing the abandoned one.
expect(transition(loading, { type: "session.loaded", sessionID: "ses_1" }).commands).toEqual([
{ type: "load-list", sessionID: "ses_1", attempt: 3 },
])
})
test("a failed support check shows its error with a retry that checks again", () => {
const failed = replay([
{ type: "server.connected" },
{ type: "session.loaded", sessionID: "ses_1" },
{ type: "capability.failed", attempt: 1, error: "offline" },
]).state
const view = sessionView(failed, "ses_1")
expect(view).toEqual({ type: "failed", error: "offline" })
expect(tabHidden(view)).toBe(false)
expect(serverAvailable(failed)).toBe(false)
const retried = transition(failed, { type: "session.retry", sessionID: "ses_1" })
expect(retried.commands).toEqual([{ type: "check-capability", attempt: 2 }])
expect(sessionView(retried.state, "ses_1")).toEqual({ type: "loading" })
})
})

View file

@ -0,0 +1,318 @@
import type { PersistentPtyInfo } from "@opencode/client"
/** A session's terminal list once the server offers terminals. */
export type List =
| { readonly status: "loading"; readonly attempt: number }
| { readonly status: "ready"; readonly items: readonly PersistentPtyInfo[] }
| { readonly status: "refreshing"; readonly items: readonly PersistentPtyInfo[]; readonly attempt: number }
| { readonly status: "failed"; readonly error: string }
/** A session's terminal list while the server's support is checked again: a known list stays shown. */
export type Held =
| { readonly status: "waiting" }
| { readonly status: "ready"; readonly items: readonly PersistentPtyInfo[] }
/**
* One server's terminal support and the terminal lists of its loaded sessions. Each request takes the server's next
* attempt number, so an answer whose attempt the state no longer holds is stale. `issued` is the last one handed out.
*/
export type State =
| { readonly status: "unknown" }
| { readonly status: "checking"; readonly attempt: number; readonly sessions: Readonly<Record<string, Held>> }
| { readonly status: "unsupported"; readonly issued: number; readonly sessions: readonly string[] }
| {
readonly status: "failed"
readonly issued: number
readonly sessions: readonly string[]
readonly error: string
}
| { readonly status: "supported"; readonly issued: number; readonly sessions: Readonly<Record<string, List>> }
export type Event =
/** The model started following the server, its event stream connected again, or a restarted server replaced it. */
| { readonly type: "server.connected" }
| { readonly type: "capability.checked"; readonly attempt: number; readonly supported: boolean }
| { readonly type: "capability.failed"; readonly attempt: number; readonly error: string }
| { readonly type: "session.loaded"; readonly sessionID: string }
/** The server reported a terminal change, or this client changed the session's terminals. */
| { readonly type: "session.refresh"; readonly sessionID: string }
/** The user asks to load the session's terminals again after a failure. */
| { readonly type: "session.retry"; readonly sessionID: string }
| {
readonly type: "list.loaded"
readonly sessionID: string
readonly attempt: number
readonly items: readonly PersistentPtyInfo[]
}
/** The list answered 503: the server's terminal daemon can't run. */
| { readonly type: "list.unavailable"; readonly sessionID: string; readonly attempt: number }
| { readonly type: "list.failed"; readonly sessionID: string; readonly attempt: number; readonly error: string }
/** The server sent a terminal's new info. */
| { readonly type: "terminal.updated"; readonly sessionID: string; readonly terminal: PersistentPtyInfo }
/** This client changed a listed terminal's info. */
| { readonly type: "terminal.replaced"; readonly sessionID: string; readonly terminal: PersistentPtyInfo }
| { readonly type: "sessions.removed"; readonly sessionIDs: readonly string[] }
export type Command =
| { readonly type: "check-capability"; readonly attempt: number }
| { readonly type: "load-list"; readonly sessionID: string; readonly attempt: number }
/** Adds the listed terminals the strip doesn't store yet, such as ones another client created. */
| { readonly type: "sync-tabs"; readonly sessionID: string; readonly items: readonly PersistentPtyInfo[] }
export type Transition = { readonly state: State; readonly commands: readonly Command[] }
/** What a session's terminal panel shows. */
export type View =
| { readonly type: "loading" }
| { readonly type: "unsupported" }
| { readonly type: "failed"; readonly error: string }
| { readonly type: "ready"; readonly items: readonly PersistentPtyInfo[] }
type Supported = Extract<State, { status: "supported" }>
export const initialState: State = { status: "unknown" }
const LOADING: View = { type: "loading" }
const UNSUPPORTED: View = { type: "unsupported" }
const NONE: readonly PersistentPtyInfo[] = []
export function transition(state: State, event: Event): Transition {
if (state.status === "unknown") return unknown(state, event)
if (state.status === "checking") return checking(state, event)
if (state.status === "supported") return supported(state, event)
return resting(state, event)
}
/** Servers that predate the capability report nothing and still offer terminals, until a check says otherwise. */
export function serverAvailable(state: State) {
return state.status !== "unsupported" && state.status !== "failed"
}
export function sessionView(state: State, sessionID: string): View {
if (state.status === "unknown") return LOADING
if (state.status === "unsupported") return UNSUPPORTED
if (state.status === "failed") return { type: "failed", error: state.error }
const session = state.sessions[sessionID]
if (!session || session.status === "waiting" || session.status === "loading") return LOADING
if (session.status === "failed") return { type: "failed", error: session.error }
return { type: "ready", items: session.items }
}
/** The listed terminals, in the server's order; none until the list is known. */
export function viewItems(current: View) {
return current.type === "ready" ? current.items : NONE
}
/**
* The strip's terminal tabs. Until the server lists the session's terminals the stored tabs stay, so restore keeps
* them; then the ones it no longer lists leave and the ones the strip doesn't store yet join at the end.
*/
export function viewTabs(current: View, open: readonly string[]) {
if (current.type !== "ready") return [...new Set(open)]
const live = new Set(current.items.map((info) => info.id))
return [...new Set([...open.filter((id) => live.has(id)), ...live])]
}
/** Stored tabs stay hidden while the panel has nothing to show for them. */
export function tabHidden(current: View) {
return current.type === "loading" || current.type === "unsupported"
}
/** A tab can be selected and focused unless the server's list leaves its terminal out. */
export function tabTargetable(current: View, id: string) {
return current.type !== "ready" || current.items.some((info) => info.id === id)
}
function unknown(state: State, event: Event): Transition {
if (event.type === "server.connected") return check(1, {})
if (event.type === "session.loaded") return check(1, { [event.sessionID]: { status: "waiting" } })
return unchanged(state)
}
function checking(state: Extract<State, { status: "checking" }>, event: Event): Transition {
if (event.type === "server.connected") return check(state.attempt + 1, state.sessions)
if (event.type === "capability.checked" && event.attempt === state.attempt) {
if (!event.supported)
return changed({ status: "unsupported", issued: state.attempt, sessions: Object.keys(state.sessions) })
// Every session lists again; a list it already had stays shown meanwhile.
const ids = Object.keys(state.sessions)
const sessions = Object.fromEntries(
ids.map((id, index): [string, List] => {
const held = state.sessions[id]
const attempt = state.attempt + 1 + index
if (held?.status === "ready") return [id, { status: "refreshing", items: held.items, attempt }]
return [id, { status: "loading", attempt }]
}),
)
return changed(
{ status: "supported", issued: state.attempt + ids.length, sessions },
ids.map((sessionID, index): Command => ({ type: "load-list", sessionID, attempt: state.attempt + 1 + index })),
)
}
if (event.type === "capability.failed" && event.attempt === state.attempt)
return changed({
status: "failed",
issued: state.attempt,
sessions: Object.keys(state.sessions),
error: event.error,
})
if (event.type === "session.loaded" && !state.sessions[event.sessionID])
return changed({ ...state, sessions: { ...state.sessions, [event.sessionID]: { status: "waiting" } } })
if (event.type === "terminal.updated" || event.type === "terminal.replaced") {
const held = state.sessions[event.sessionID]
if (held?.status !== "ready" || !listed(held.items, event.terminal.id)) return unchanged(state)
return changed({
...state,
sessions: {
...state.sessions,
[event.sessionID]: { status: "ready", items: replace(held.items, event.terminal) },
},
})
}
if (event.type === "sessions.removed" && event.sessionIDs.some((id) => id in state.sessions))
return changed({ ...state, sessions: omit(state.sessions, event.sessionIDs) })
return unchanged(state)
}
function resting(state: Extract<State, { status: "unsupported" | "failed" }>, event: Event): Transition {
if (event.type === "server.connected" || (event.type === "session.retry" && state.status === "failed"))
return check(
state.issued + 1,
Object.fromEntries(state.sessions.map((id): [string, Held] => [id, { status: "waiting" }])),
)
if (event.type === "session.loaded" && !state.sessions.includes(event.sessionID))
return changed({ ...state, sessions: [...state.sessions, event.sessionID] })
if (event.type === "sessions.removed" && state.sessions.some((id) => event.sessionIDs.includes(id)))
return changed({ ...state, sessions: state.sessions.filter((id) => !event.sessionIDs.includes(id)) })
return unchanged(state)
}
function supported(state: Supported, event: Event): Transition {
if (event.type === "server.connected")
return check(
state.issued + 1,
Object.fromEntries(
Object.entries(state.sessions).map(([id, list]): [string, Held] => {
if (list.status === "ready" || list.status === "refreshing")
return [id, { status: "ready", items: list.items }]
return [id, { status: "waiting" }]
}),
),
)
const list = "sessionID" in event ? state.sessions[event.sessionID] : undefined
if (event.type === "session.loaded") return list ? unchanged(state) : load(state, event.sessionID)
if (event.type === "session.refresh") return list ? load(state, event.sessionID) : unchanged(state)
// Retrying a list that isn't failed would only repeat a request.
if (event.type === "session.retry") return list?.status === "failed" ? load(state, event.sessionID) : unchanged(state)
if (event.type === "list.loaded" || event.type === "list.unavailable" || event.type === "list.failed") {
// Only the latest request for a session still loaded may settle it.
if (!list || (list.status !== "loading" && list.status !== "refreshing") || list.attempt !== event.attempt)
return unchanged(state)
if (event.type === "list.loaded")
return changed(put(state, event.sessionID, { status: "ready", items: event.items }), [
{ type: "sync-tabs", sessionID: event.sessionID, items: event.items },
])
// A server whose terminal daemon can't run offers no terminals until the next connection checks again.
if (event.type === "list.unavailable")
return changed({ status: "unsupported", issued: state.issued, sessions: Object.keys(state.sessions) })
// A failed refresh keeps the terminals already shown.
if (list.status === "refreshing")
return changed(put(state, event.sessionID, { status: "ready", items: list.items }))
return changed(put(state, event.sessionID, { status: "failed", error: event.error }))
}
if (event.type === "terminal.updated" || event.type === "terminal.replaced") {
if (!list) return unchanged(state)
if ((list.status === "ready" || list.status === "refreshing") && listed(list.items, event.terminal.id))
return changed(put(state, event.sessionID, { ...list, items: replace(list.items, event.terminal) }))
// A terminal the list doesn't have yet arrives with the next list; this client changes only listed ones.
return event.type === "terminal.updated" ? load(state, event.sessionID) : unchanged(state)
}
if (event.type === "sessions.removed" && event.sessionIDs.some((id) => id in state.sessions))
return changed({ ...state, sessions: omit(state.sessions, event.sessionIDs) })
return unchanged(state)
}
function load(state: Supported, sessionID: string): Transition {
const attempt = state.issued + 1
const list = state.sessions[sessionID]
const next =
list?.status === "ready" || list?.status === "refreshing"
? ({ status: "refreshing", items: list.items, attempt } satisfies List)
: ({ status: "loading", attempt } satisfies List)
return changed({ ...put(state, sessionID, next), issued: attempt }, [{ type: "load-list", sessionID, attempt }])
}
function check(attempt: number, sessions: Readonly<Record<string, Held>>): Transition {
return changed({ status: "checking", attempt, sessions }, [{ type: "check-capability", attempt }])
}
function put(state: Supported, sessionID: string, list: List): Supported {
return { ...state, sessions: { ...state.sessions, [sessionID]: list } }
}
function omit<T extends Held | List>(sessions: Readonly<Record<string, T>>, ids: readonly string[]) {
return Object.fromEntries(Object.entries(sessions).filter(([id]) => !ids.includes(id)))
}
function listed(list: readonly PersistentPtyInfo[], id: string) {
return list.some((info) => info.id === id)
}
function replace(list: readonly PersistentPtyInfo[], terminal: PersistentPtyInfo) {
return list.map((info) => (info.id === terminal.id ? terminal : info))
}
function changed(state: State, commands: readonly Command[] = []): Transition {
return { state, commands }
}
function unchanged(state: State): Transition {
return { state, commands: [] }
}

View file

@ -51,16 +51,26 @@ function fakeServer(options: { capabilities?: { persistentPty?: boolean } } = {}
session: { get: (id: string) => ({ id, location: { directory: state.directory } }) },
},
client: {
server: { info: async () => ({ capabilities: state.capabilities }) },
server: {
// Answers with the support the server had when asked, however late the answer arrives.
info: async () => {
const capabilities = state.capabilities
await state.info
return { capabilities }
},
},
experimental: {
persistentPty: {
// Answers with the terminals the server had when asked, or with the error it has when it answers.
list: async (input: { sessionID: string }) => {
calls.list += 1
const listed = [...(terminals.get(input.sessionID) ?? [])]
await state.list
if (state.listError) throw state.listError
return [...(terminals.get(input.sessionID) ?? [])]
return listed
},
create: async (input: { sessionID: string; title: string; cwd?: string }) => {
calls.create.push(input)
@ -126,6 +136,7 @@ type FakeState = {
updateError?: Error
update?: Promise<void>
list?: Promise<void>
info?: Promise<void>
}
type EventData = { sessionID: string; terminal?: PersistentPtyInfo }
@ -199,13 +210,15 @@ describe("terminal model", () => {
await flush()
// An empty list before the first answer would let the transient strip drop restored terminal tabs.
expect(terminal.ready()).toBe(false)
expect(terminal.view()).toEqual({ type: "loading" })
expect(terminal.all()).toEqual([])
expect(terminal.tabs(["pty_restored"])).toEqual(["pty_restored"])
list.resolve()
await flush()
expect(terminal.ready()).toBe(true)
expect(terminal.view().type).toBe("ready")
expect(terminal.tabs(["pty_restored"])).toEqual(["pty_1"])
expect(terminal.all().map((item) => item.id)).toEqual(["pty_1"])
})
@ -267,7 +280,7 @@ describe("terminal model", () => {
expect(model.available(server.ref)).toBe(false)
expect(server.calls.list).toBe(0)
expect(terminal.ready()).toBe(false)
expect(terminal.view()).toEqual({ type: "unsupported" })
// Servers that predate the capability omit it and still offer terminals.
server.state.capabilities = undefined
@ -290,7 +303,7 @@ describe("terminal model", () => {
await flush()
expect(model.available(server.ref)).toBe(false)
expect(terminal.ready()).toBe(true)
expect(terminal.view()).toEqual({ type: "unsupported" })
expect(terminal.all()).toEqual([])
server.state.listError = undefined
@ -302,6 +315,85 @@ describe("terminal model", () => {
expect(terminal.all().map((item) => item.id)).toEqual(["pty_1"])
})
test("shows a list that fails with an error other than 503 as failed until the user retries", async () => {
const server = fakeServer()
server.state.listError = new Error("boom")
server.terminals.set("ses_1", [info("pty_1", "Terminal 1")])
const { model, session } = setup(server)
const terminal = model.load(session)
await flush()
// It used to stay loading, with the restored tabs hidden, until a terminal event or a reconnect.
expect(terminal.view()).toEqual({ type: "failed", error: "boom" })
expect(terminal.tabs(["pty_restored"])).toEqual(["pty_restored"])
expect(model.available(server.ref)).toBe(true)
// Reading the session again doesn't retry by itself.
const calls = server.calls.list
model.load(session)
await flush()
expect(server.calls.list).toBe(calls)
server.state.listError = undefined
await terminal.retry()
expect(terminal.view().type).toBe("ready")
expect(terminal.all().map((item) => item.id)).toEqual(["pty_1"])
})
test("a late 503 from an older list leaves the newer list and the server's support alone", 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()
const slow = Promise.withResolvers<void>()
server.state.list = slow.promise
server.emit("persistent-pty.added")
server.state.list = undefined
server.terminals.set("ses_1", [info("pty_1", "Terminal 1"), info("pty_2", "Terminal 2")])
server.emit("persistent-pty.added")
await flush()
expect(terminal.all().map((item) => item.id)).toEqual(["pty_1", "pty_2"])
server.state.listError = new ServiceUnavailableError({
message: "opencode-pty is not available",
service: "opencode-pty",
})
slow.resolve()
await flush()
expect(model.available(server.ref)).toBe(true)
expect(terminal.all().map((item) => item.id)).toEqual(["pty_1", "pty_2"])
})
test("a late support answer from before a reconnect leaves the newer answer alone", async () => {
const server = fakeServer({ capabilities: { persistentPty: false } })
const slow = Promise.withResolvers<void>()
server.state.info = slow.promise
server.terminals.set("ses_1", [info("pty_1", "Terminal 1")])
const { model, session } = setup(server)
const terminal = model.load(session)
server.state.info = undefined
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"])
slow.resolve()
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")])

View file

@ -1,5 +1,5 @@
import { createRoot, getOwner, runWithOwner, type Owner } from "solid-js"
import { createStore } from "solid-js/store"
import { createRoot, getOwner, runWithOwner, untrack, type Owner } from "solid-js"
import { createStore, unwrap } from "solid-js/store"
import { Predicate, Schema } from "effect"
import {
ClientError,
@ -17,6 +17,17 @@ import {
type Toasts,
} from "@opencode/plugin/gui"
import { defaultTitle, titleNumber } from "./title"
import {
initialState,
serverAvailable,
sessionView,
transition,
viewItems,
viewTabs,
type Command,
type Event,
type State,
} from "./machine"
// 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" }
@ -37,7 +48,7 @@ type Ghostty = { shared?: ReturnType<typeof importGhostty> }
/**
* 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.
* stored. Each server's support and lists follow the machine in `./machine`; this runs its requests.
*/
export function createTerminalModel(input: {
storage: Storage
@ -48,90 +59,100 @@ export function createTerminalModel(input: {
tab: (ptyID: string) => string
}) {
const owner = getOwner()
const lifetime = new AbortController()
const [lists, setLists] = input.storage.memory<{ sessions: Record<string, readonly PersistentPtyInfo[]> }>("lists", {
initial: { sessions: {} },
// Survives plugin reloads, so restored terminals show at once; the first watch checks every server again.
const [machine, setMachine] = input.storage.memory<{ servers: Record<string, State> }>("servers", {
initial: { servers: {} },
})
const [state, setState] = createStore<{ capabilities: Record<string, boolean>; focus?: FocusRequest }>({
capabilities: {},
})
const [state, setState] = createStore<{ focus?: FocusRequest }>({})
const sessions = new Map<string, SessionRef>()
const handles = new Map<string, ReturnType<typeof handle>>()
const selected = new Map<string, Persisted<typeof Selected.Type>>()
const sequence = new Map<string, number>()
const watched = new Map<string, { data: ServerRef["data"]; stop: VoidFunction }>()
const cleared = new Set<string>()
const cleanups: VoidFunction[] = []
const ghostty: Ghostty = {}
const focus = { request: 0 }
const available = (server: ServerRef) => {
watch(server)
const serverState = (id: string) => machine.servers[id] ?? initialState
return state.capabilities[server.id] !== false
/** Resolves once the requests the event started have answered and their answers were dispatched. */
const dispatch = (server: ServerRef, event: Event): Promise<void> => {
if (lifetime.signal.aborted) return Promise.resolve()
// Reads from reactive computations, such as `load`, must not subscribe them to every state change.
const previous = untrack(() => unwrap(machine.servers[server.id])) ?? initialState
const next = transition(previous, event)
if (next.state !== previous) setMachine((draft) => void (draft.servers[server.id] = next.state))
return Promise.all(next.commands.map((command) => run(server, command))).then(() => undefined)
}
const refresh = async (session: SessionRef) => {
const next = (sequence.get(session.key) ?? 0) + 1
const run = (server: ServerRef, command: Command): Promise<void> => {
if (command.type === "check-capability")
return server.client.server.info().then(
// Servers that predate the field omit it; they still offer terminals.
(info) =>
dispatch(server, {
type: "capability.checked",
attempt: command.attempt,
supported: info.capabilities?.persistentPty !== false,
}),
(error) => {
console.error("Failed to read server terminal support", error)
sequence.set(session.key, next)
const list = await session.server.client.experimental.persistentPty.list({ sessionID: session.id })
return dispatch(server, {
type: "capability.failed",
attempt: command.attempt,
error: error instanceof Error ? error.message : String(error),
})
},
)
// A newer refresh started meanwhile; its answer wins.
if (sequence.get(session.key) !== next) return
setLists((draft) => void (draft.sessions[session.key] = list))
if (command.type === "load-list")
return server.client.experimental.persistentPty.list({ sessionID: command.sessionID }).then(
(items) =>
dispatch(server, { type: "list.loaded", sessionID: command.sessionID, attempt: command.attempt, items }),
(error) => {
if (isServiceUnavailableError(error))
return dispatch(server, {
type: "list.unavailable",
sessionID: command.sessionID,
attempt: command.attempt,
})
console.error("Failed to list terminals", error)
return dispatch(server, {
type: "list.failed",
sessionID: command.sessionID,
attempt: command.attempt,
error: error instanceof Error ? error.message : String(error),
})
},
)
const session = sessions.get(`${server.id}\n${command.sessionID}`)
if (!session) return Promise.resolve()
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))
list.forEach((info) => {
command.items.forEach((info) => {
if (!stored.has(info.id)) input.layout.open(input.tab(info.id), session, { tab: "append" })
})
return Promise.resolve()
}
// 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 available = (server: ServerRef) => {
watch(server)
if (list && index !== -1) draft.sessions[key] = list.with(index, terminal)
})
// 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] = []))
})
const refreshQuietly = (session: SessionRef) => void listed(session)
const refreshServer = (server: ServerRef) =>
sessions.forEach((session) => {
if (session.server.id === server.id) refreshQuietly(session)
})
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
setState("capabilities", server.id, supported)
if (supported) refreshServer(server)
})
.catch((error) => {
// Like the TUI: unknown support offers no terminals until the next connection checks again.
setState("capabilities", server.id, false)
console.error("Failed to read server terminal support", error)
})
return serverAvailable(serverState(server.id))
}
// A restarted server replaces its data under the same ref, so reads that track `server.data` subscribe again.
const watch = (server: ServerRef) => {
@ -141,31 +162,34 @@ export function createTerminalModel(input: {
if (current?.data === data) return
current?.stop()
const refreshSession = (sessionID: string) => {
const session = sessions.get(`${server.id}\n${sessionID}`)
if (session && state.capabilities[server.id]) refreshQuietly(session)
}
// 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}`
if (!lists.sessions[key]?.some((info) => info.id === event.data.terminal.id))
return refreshSession(event.data.sessionID)
replace(key, event.data.terminal)
}),
data.on("server.connected", () => void dispatch(server, { type: "server.connected" })),
data.on(
"persistent-pty.added",
(event) => void dispatch(server, { type: "session.refresh", sessionID: event.data.sessionID }),
),
data.on(
"persistent-pty.removed",
(event) => void dispatch(server, { type: "session.refresh", sessionID: event.data.sessionID }),
),
data.on(
"persistent-pty.updated",
(event) =>
void dispatch(server, {
type: "terminal.updated",
sessionID: event.data.sessionID,
terminal: event.data.terminal,
}),
),
])!
watched.set(server.id, { data, stop: () => stops.forEach((stop) => stop()) })
sync(server)
// Checks now rather than waiting for the stream: it may have connected already, and an answer a previous
// instance was waiting for never arrives here.
void dispatch(server, { type: "server.connected" })
}
const selection = (session: SessionRef) => {
@ -218,7 +242,8 @@ export function createTerminalModel(input: {
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 view = () => sessionView(serverState(initial.server.id), initial.id)
const all = () => viewItems(view())
const get = (id: string) => all().find((info) => info.id === id)
const focusRequested = (id?: string) => {
@ -230,11 +255,15 @@ export function createTerminalModel(input: {
return {
key,
server: () => session().server,
/** The server answered this session's first terminal list. */
ready: () => lists.sessions[key] !== undefined,
/** What the session's terminal panel shows: loading, failed, unsupported or the server's list. */
view,
/** The session's terminals, in the server's order. */
all,
get,
/** The strip's tab ids for the stored `open` ones. */
tabs: (open: readonly string[]) => viewTabs(view(), open),
/** Loads the session's terminals again after a failure. */
retry: () => dispatch(session().server, { type: "session.retry", sessionID: initial.id }),
/** The selected terminal, else the first one. */
active() {
const id = selection(session()).value?.id
@ -244,7 +273,6 @@ export function createTerminalModel(input: {
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()
@ -253,9 +281,12 @@ export function createTerminalModel(input: {
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 known =
view().type === "ready"
? all()
: await target.server.client.experimental.persistentPty.list({ sessionID: target.id }).catch(() => all())
const used = new Set(all().flatMap((info) => titleNumber(info.title) ?? []))
const used = new Set(known.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
@ -292,7 +323,7 @@ export function createTerminalModel(input: {
if (!info) return undefined
await listed(target)
await dispatch(target.server, { type: "session.refresh", sessionID: target.id })
selection(target).set({ id: info.id })
if (state.focus?.request === request) setState("focus", { key, request, id: info.id, pending: false })
@ -305,7 +336,7 @@ export function createTerminalModel(input: {
await target.server.client.experimental.persistentPty
.remove({ ptyID: id })
.then(() => refresh(target))
.then(() => dispatch(target.server, { type: "session.refresh", sessionID: target.id }))
.catch((error) => console.error("Failed to close terminal", error))
},
/**
@ -318,15 +349,18 @@ export function createTerminalModel(input: {
if (!previous || title === previous.title || (title === null && previous.userTitle === null)) return
const replace = (terminal: PersistentPtyInfo) =>
void dispatch(target.server, { type: "terminal.replaced", sessionID: target.id, terminal })
// 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 })
if (title !== null) replace({ ...previous, title, userTitle: title })
await target.server.client.experimental.persistentPty
.update({ ptyID: id, title })
.then((info) => replace(key, info))
.then(replace)
.catch((error) => {
// A newer title from the server stays.
if (title !== null && get(id)?.userTitle === title) replace(key, previous)
if (title !== null && get(id)?.userTitle === title) replace(previous)
input.toast.show(
isPtyFeatureUnsupportedError(error)
? { variant: "error", title: input.t("rename.unsupported") }
@ -358,6 +392,7 @@ export function createTerminalModel(input: {
load(session: SessionRef) {
sessions.set(session.key, session)
watch(session.server)
void dispatch(session.server, { type: "session.loaded", sessionID: session.id })
const existing = handles.get(session.key)
@ -367,9 +402,6 @@ export function createTerminalModel(input: {
handles.set(session.key, created)
// 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 created
},
ghostty() {
@ -385,17 +417,23 @@ export function createTerminalModel(input: {
/** 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)
const removed = [...sessions.values()].filter(
(session) => session.server.id === value.server && session.location?.directory === value.directory,
)
removed.forEach((session) => {
sessions.delete(session.key)
handles.delete(session.key)
selected.delete(session.key)
})
const server = removed[0]?.server
if (server) void dispatch(server, { type: "sessions.removed", sessionIDs: removed.map((session) => session.id) })
},
dispose() {
lifetime.abort()
watched.forEach((entry) => entry.stop())
watched.clear()
cleanups.forEach((cleanup) => cleanup())

View file

@ -1,5 +1,6 @@
import { For, Show, createMemo, onCleanup } from "solid-js"
import { For, Match, Show, Switch, createMemo, onCleanup } from "solid-js"
import { createStore } from "solid-js/store"
import { Button } from "@opencode/ui/button"
import { Tabs } from "@opencode/ui/tabs"
import { IconButton } from "@opencode/ui/icon-button"
import { Icon } from "@opencode/ui/icon"
@ -48,6 +49,12 @@ export default function TerminalPanel(props: {
const mobile = () => frame.placement() === "mobile"
const active = () => (mobile() ? terminal().active() : terminal().get(props.tab())?.id)
const failed = () => {
const view = terminal().view()
return view.type === "failed" ? view : undefined
}
// Selected output quotes into the composer of the screen showing this panel.
const quote: TerminalQuoteTarget = {
available: () => opened() && props.screen.composer.quotable(),
@ -82,7 +89,7 @@ export default function TerminalPanel(props: {
() => {
const session = terminal()
return session.ready() ? session : undefined
return session.view().type === "ready" ? session : undefined
},
(session) => {
if (seen.session === session.key) return
@ -134,7 +141,7 @@ export default function TerminalPanel(props: {
createKeyed(
() => ({
session: terminal().key,
ready: terminal().ready(),
ready: terminal().view().type === "ready",
active: opened() ? active() : undefined,
terminals: terminal().all(),
elsewhere: elsewhere(),
@ -208,68 +215,87 @@ export default function TerminalPanel(props: {
return (
<div id="terminal-panel" class="flex flex-col size-full">
<Show
when={terminal().ready()}
<Switch
fallback={
<div class="flex-1 flex items-center justify-center text-text-weak pointer-events-none">
{plugin.t("loading")}
</div>
}
>
<Show when={mobile()} fallback={surfaces()}>
<div class="h-[49px] shrink-0 flex border-b border-v2-border-border-base">
<Tabs
variant="panel"
value={terminal().active()}
onChange={(id) => terminal().select(id)}
class="!h-full min-w-0 !flex-1"
>
<Tabs.List
class="!border-b-0"
onPointerDown={(event: PointerEvent & { currentTarget: HTMLDivElement }) => {
const focused = document.activeElement
if (event.target === focused) return
if (focused instanceof HTMLInputElement && event.currentTarget.contains(focused)) focused.blur()
}}
>
<For each={terminal().all()}>
{(info) => (
<TerminalTab
terminal={info}
session={terminal()}
rename={(title) => void terminal().rename(info.id, title)}
/>
)}
</For>
<div class="h-full flex items-center justify-center">
<Tooltip
value={
<>
{plugin.t("command.new")}
<Show when={newTerminalKeybind().length > 0}>
<Keybind keys={newTerminalKeybind()} variant="neutral" />
</Show>
</>
}
placement="bottom"
class="flex items-center"
>
<IconButton
icon={<Icon name="plus-small" size="large" />}
variant="ghost"
onClick={() => void terminal().new()}
aria-label={plugin.t("command.new")}
/>
</Tooltip>
</div>
</Tabs.List>
</Tabs>
<Match when={failed()}>
{(view) => (
<div role="alert" class="flex-1 flex flex-col items-center justify-center gap-3 px-4 text-center">
<div class="flex flex-col gap-1">
<div class="text-13-regular text-text-strong">{plugin.t("list.failed")}</div>
<div class="text-12-regular text-text-weak break-words">{view().error}</div>
</div>
<Button size="small" variant="outline" onClick={() => void terminal().retry()}>
{plugin.t("common.retry")}
</Button>
</div>
)}
</Match>
<Match when={terminal().view().type === "unsupported"}>
<div class="flex-1 flex items-center justify-center px-4 text-center text-text-weak pointer-events-none">
{plugin.t("unavailable")}
</div>
{surfaces()}
</Show>
</Show>
</Match>
<Match when={terminal().view().type === "ready"}>
<Show when={mobile()} fallback={surfaces()}>
<div class="h-[49px] shrink-0 flex border-b border-v2-border-border-base">
<Tabs
variant="panel"
value={terminal().active()}
onChange={(id) => terminal().select(id)}
class="!h-full min-w-0 !flex-1"
>
<Tabs.List
class="!border-b-0"
onPointerDown={(event: PointerEvent & { currentTarget: HTMLDivElement }) => {
const focused = document.activeElement
if (event.target === focused) return
if (focused instanceof HTMLInputElement && event.currentTarget.contains(focused)) focused.blur()
}}
>
<For each={terminal().all()}>
{(info) => (
<TerminalTab
terminal={info}
session={terminal()}
rename={(title) => void terminal().rename(info.id, title)}
/>
)}
</For>
<div class="h-full flex items-center justify-center">
<Tooltip
value={
<>
{plugin.t("command.new")}
<Show when={newTerminalKeybind().length > 0}>
<Keybind keys={newTerminalKeybind()} variant="neutral" />
</Show>
</>
}
placement="bottom"
class="flex items-center"
>
<IconButton
icon={<Icon name="plus-small" size="large" />}
variant="ghost"
onClick={() => void terminal().new()}
aria-label={plugin.t("command.new")}
/>
</Tooltip>
</div>
</Tabs.List>
</Tabs>
</div>
{surfaces()}
</Show>
</Match>
</Switch>
</div>
)
}

View file

@ -15,6 +15,7 @@ import {
import type Terminal from "./index"
import { terminalToggleCommand } from "./index"
import { createTerminalModel, type TerminalSession } from "./model"
import { tabHidden, tabTargetable } from "./machine"
import { terminalTabLabel } from "./title"
import { TerminalTabLabel } from "./label"
import quoteStyles from "./quote.css?inline"
@ -196,16 +197,18 @@ const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
get title() {
return label()
},
// Listed only to hold the restored selection until the server lists the session's terminals.
// Listed only to hold the restored selection until the panel has something to show for it: the server's list,
// or why it failed.
get hidden() {
return !terminal().ready()
return tabHidden(terminal().view())
},
group: "terminal",
label: () => (
<TerminalTabLabel
label={label()}
title={info()?.title ?? ""}
rename={(title) => void terminal().rename(id, title)}
// A tab shown for a list that failed has no terminal to rename yet.
rename={info() ? (title) => void terminal().rename(id, title) : undefined}
close={() => void terminal().close(id)}
/>
),
@ -226,32 +229,32 @@ const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
icon: "terminal",
cached: true,
},
// One tab per terminal of the session. Until the server lists them, 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 (hidden while
// loading) so restore keeps them.
list: (input) => {
const terminal = model.load(input.session)
const ids = [...new Set([...input.open, ...terminal.all().map((info) => info.id)])]
const ids = model.load(input.session).tabs(input.open)
if (ids.length === 0) return []
if (ids.length === 0) {
tabs.delete(input.session.key)
return []
}
const cache = tabs.get(input.session.key) ?? new Map<string, PanelTab>()
tabs.set(input.session.key, cache)
cache.forEach((_tab, id) => {
if (!ids.includes(id)) cache.delete(id)
})
return ids.flatMap((id) => {
if (terminal.ready() && !terminal.get(id)) {
cache.delete(id)
return []
}
return ids.map((id) => {
const existing = cache.get(id)
if (existing) return [existing]
if (existing) return existing
const created = tab(input.session, id)
cache.set(id, created)
return [created]
return created
})
},
render: (props) => (
@ -271,7 +274,7 @@ const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
focus: (input) => {
const terminal = model.load(input.session)
if (terminal.ready() && !terminal.get(input.tab.id)) return
if (!tabTargetable(terminal.view(), input.tab.id)) return
terminal.select(input.tab.id)
@ -280,7 +283,7 @@ const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
enter: (input) => {
const terminal = model.load(input.session)
if (!terminal.ready() || terminal.get(input.tab.id)) terminal.requestFocus(input.tab.id)
if (tabTargetable(terminal.view(), input.tab.id)) terminal.requestFocus(input.tab.id)
},
})
}