fix(app): keep terminal focus and tab renames on what the user chose (#61852)

This commit is contained in:
Luke Parker
2026-11-04 19:18:14 -06:00
committed by GitHub
Unverified
parent d3c9e758bb
commit fff729917e
11 changed files with 654 additions and 193 deletions
@@ -147,6 +147,47 @@ test("the New terminal shortcut creates the next numbered terminal", async ({ pa
await expect(terminalScreen(page, persistentPty.created[0]!.id).locator("textarea")).toBeFocused()
})
// Closing the palette returns focus to the composer while the terminal is still being created.
test("New terminal from the command palette opens the terminal focused", async ({ page }) => {
const { persistentPty, editor } = await openSession(page, { name: "Terminals", persistentPty: {} })
await editor.click()
await page.keyboard.press("Control+Shift+P")
const palette = page.getByRole("dialog")
const input = palette.getByRole("combobox")
await expect(input).toBeFocused()
await input.fill("New terminal")
await expect(palette.getByRole("option", { name: /^New terminal/ })).toHaveAttribute("aria-selected", "true")
await input.press("Enter")
await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute(
"aria-selected",
"true",
)
await expect(terminalScreen(page, persistentPty.created[0]!.id).locator("textarea")).toBeFocused()
})
test("a click into the composer while a new terminal is created keeps the focus there", async ({ page }) => {
const { persistentPty, editor } = await openSession(page, { name: "Terminals", persistentPty: {} })
const create = await holdRoute(page, /\/api\/experimental\/session\/ses_terminals\/terminal(\?|$)/, {
method: "POST",
})
await editor.click()
await page.keyboard.press("Control+Alt+T")
await create.arrived
await editor.click()
create.release()
await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute(
"aria-selected",
"true",
)
await expect.poll(() => persistentPty.sockets.length).toBe(1)
await expect(editor).toBeFocused()
})
test("another client's control ends at a click, which resizes the terminal to the pane", async ({ page }) => {
const { persistentPty } = await openSession(page, {
name: "Terminals",
@@ -0,0 +1,110 @@
import { describe, expect, test } from "bun:test"
import {
focusRequestToken,
initialFocusState,
isFocusRequested,
transitionFocus,
type FocusRequestEvent,
type FocusState,
} from "./focus-machine"
const replay = (events: readonly FocusRequestEvent[], state: FocusState = initialFocusState) =>
events.reduce(transitionFocus, state)
const pending = (overlay = false): FocusRequestEvent => ({ type: "request.pending", session: "ses_1", overlay })
const target = (id: string, overlay = false): FocusRequestEvent => ({
type: "request.target",
session: "ses_1",
id,
overlay,
})
const outside: FocusRequestEvent = { type: "focus.moved", into: "outside", leavingOverlay: false }
// The palette or menu that started the request returns focus to where it was opened from as it closes.
const restored: FocusRequestEvent = { type: "focus.moved", into: "outside", leavingOverlay: true }
describe("terminal focus machine", () => {
test("closing the palette or menu that created a terminal does not cancel its focus", () => {
const state = replay([pending(true), restored, { type: "pending.resolved", request: 1, id: "pty_1" }])
expect(isFocusRequested(state, "ses_1", "pty_1")).toBe(true)
// The terminal can also be created before the overlay returns focus.
const late = replay([pending(true), { type: "pending.resolved", request: 1, id: "pty_1" }, restored])
expect(isFocusRequested(late, "ses_1", "pty_1")).toBe(true)
})
test("only the overlay's one focus return is exempt; the user moving on cancels", () => {
expect(replay([pending(true), restored, outside])).toEqual({ status: "idle", request: 1 })
expect(replay([pending(true), restored, restored])).toEqual({ status: "idle", request: 1 })
expect(replay([pending(), restored])).toEqual({ status: "idle", request: 1 })
expect(replay([target("pty_1", true), { type: "pointer.outside" }])).toEqual({ status: "idle", request: 1 })
// A press outside cancels a terminal still being created, so it opens without taking focus.
const pressed = replay([
pending(),
{ type: "pointer.outside" },
{ type: "pending.resolved", request: 1, id: "pty_1" },
])
expect(isFocusRequested(pressed, "ses_1", "pty_1")).toBe(false)
})
test("focus moving within the panels keeps the request, unless it enters a field such as a rename", () => {
const panel = replay([target("pty_1"), { type: "focus.moved", into: "panel", leavingOverlay: false }])
expect(isFocusRequested(panel, "ses_1", "pty_1")).toBe(true)
expect(replay([target("pty_1", true), { type: "focus.moved", into: "field", leavingOverlay: true }])).toEqual({
status: "idle",
request: 1,
})
})
test("an answer for a request that was cancelled or replaced changes nothing", () => {
const cancelled = replay([pending(), { type: "cancelled", session: "ses_1" }])
const replaced = replay([pending(), target("pty_2")])
const answered = [cancelled, replaced]
answered.forEach((state) => {
expect(transitionFocus(state, { type: "pending.resolved", request: 1, id: "pty_1" })).toBe(state)
expect(transitionFocus(state, { type: "pending.failed", request: 1 })).toBe(state)
})
expect(replay([pending(), { type: "pending.failed", request: 1 }])).toEqual({ status: "idle", request: 1 })
})
test("asking again for the terminal already asked for keeps the request", () => {
const state = replay([target("pty_1", true)])
expect(transitionFocus(state, target("pty_1"))).toBe(state)
expect(focusRequestToken(transitionFocus(state, target("pty_1")), "ses_1", "pty_1")).toBe(1)
// A request from an overlay for the same terminal still gets its exemption.
const plain = replay([target("pty_1")])
expect(transitionFocus(plain, target("pty_1", true))).toEqual({
status: "target",
request: 1,
session: "ses_1",
id: "pty_1",
overlay: true,
})
expect(focusRequestToken(transitionFocus(plain, target("pty_2")), "ses_1", "pty_2")).toBe(2)
})
test("the terminal taking focus, or a cancel for its session, ends the request", () => {
const state = replay([target("pty_1")])
expect(transitionFocus(state, { type: "consumed", session: "ses_1", id: "pty_2" })).toBe(state)
expect(transitionFocus(state, { type: "consumed", session: "ses_1", id: "pty_1" })).toEqual({
status: "idle",
request: 1,
})
expect(transitionFocus(state, { type: "cancelled", session: "ses_2" })).toBe(state)
expect(transitionFocus(state, { type: "cancelled" })).toEqual({ status: "idle", request: 1 })
expect(transitionFocus(initialFocusState, outside)).toBe(initialFocusState)
})
})
@@ -0,0 +1,107 @@
/**
* The window's one terminal focus request. `pending` waits for a terminal being created; `target` waits for that
* terminal to show and take focus. `request` is the last request handed out, so an answer for an older one is stale.
* `overlay` marks a request started from a dialog or menu: closing it returns focus once, which does not cancel.
*/
export type FocusState =
| { readonly status: "idle"; readonly request: number }
| {
readonly status: "pending"
readonly request: number
readonly session: string
readonly overlay: boolean
}
| {
readonly status: "target"
readonly request: number
readonly session: string
readonly id: string
readonly overlay: boolean
}
export type FocusRequestEvent =
/** A terminal is being created and should take focus once it exists. */
| { readonly type: "request.pending"; readonly session: string; readonly overlay: boolean }
/** A terminal should take focus once it shows. */
| { readonly type: "request.target"; readonly session: string; readonly id: string; readonly overlay: boolean }
| { readonly type: "pending.resolved"; readonly request: number; readonly id: string }
| { readonly type: "pending.failed"; readonly request: number }
/** The terminal took focus. */
| { readonly type: "consumed"; readonly session: string; readonly id: string }
/**
* Focus moved: into the terminal or side panels (`panel`), into a field there such as a tab's rename field
* (`field`), or anywhere else (`outside`). `leavingOverlay` is true when it left a dialog or menu, or nothing.
*/
| { readonly type: "focus.moved"; readonly into: "panel" | "field" | "outside"; readonly leavingOverlay: boolean }
/** The user pressed outside the panels and every dialog or menu. */
| { readonly type: "pointer.outside" }
/** Drops the request, or only one for `session`. */
| { readonly type: "cancelled"; readonly session?: string }
export const initialFocusState: FocusState = { status: "idle", request: 0 }
/**
* The user moving on cancels a request: focus or a press outside the panels, or into a field in them. The one focus
* return of a closing dialog or menu that started the request does not.
*/
export function transitionFocus(state: FocusState, event: FocusRequestEvent): FocusState {
if (event.type === "request.pending")
return { status: "pending", request: state.request + 1, session: event.session, overlay: event.overlay }
if (event.type === "request.target") {
// Showing the tab asks again for the terminal already asked for; that keeps the request and its overlay.
if (state.status === "target" && state.session === event.session && state.id === event.id)
return event.overlay && !state.overlay ? { ...state, overlay: true } : state
return {
status: "target",
request: state.request + 1,
session: event.session,
id: event.id,
overlay: event.overlay,
}
}
if (event.type === "pending.resolved")
return state.status === "pending" && state.request === event.request
? { status: "target", request: state.request, session: state.session, id: event.id, overlay: state.overlay }
: state
if (event.type === "pending.failed")
return state.status === "pending" && state.request === event.request ? idle(state) : state
if (state.status === "idle") return state
if (event.type === "consumed")
return state.status === "target" && state.session === event.session && state.id === event.id ? idle(state) : state
if (event.type === "focus.moved") {
// The side region focuses its selected tab trigger or root while switching tabs.
if (event.into === "panel") return state
if (event.into === "outside" && state.overlay && event.leavingOverlay) return { ...state, overlay: false }
return idle(state)
}
if (event.type === "pointer.outside") return idle(state)
return event.session === undefined || event.session === state.session ? idle(state) : state
}
export function hasFocusRequest(state: FocusState) {
return state.status !== "idle"
}
export function isFocusRequested(state: FocusState, session: string, id: string) {
return state.status === "target" && state.session === session && state.id === id
}
/** The request asking `id` to take focus, so a focus attempt runs once per request. */
export function focusRequestToken(state: FocusState, session: string, id: string) {
return isFocusRequested(state, session, id) ? state.request : undefined
}
function idle(state: FocusState): FocusState {
return { status: "idle", request: state.request }
}
@@ -0,0 +1,93 @@
import { createSignal, onCleanup, untrack } from "solid-js"
import {
initialRenameState,
isRenaming,
renameDraft,
transitionRename,
type RenameEvent,
type RenameSource,
} from "./rename-machine"
/** The rename field while it is mounted, and the frame that arms it. */
type InlineRenameField = { input?: HTMLInputElement; frame?: number }
/** The inline rename of a terminal's tab, in the side panel strip and the narrow-screen view alike. */
export function createInlineRename(options: {
title: () => string
/** Receives the edited title, or `null` for an emptied field; without it the terminal cannot be renamed. */
rename: () => ((title: string | null) => void) | undefined
}) {
const [state, setState] = createSignal(initialRenameState)
const field: InlineRenameField = {}
onCleanup(disarm)
return {
editing: () => isRenaming(state()),
draft: () => renameDraft(state()),
ref(input: HTMLInputElement) {
field.input = input
},
start(source: RenameSource) {
dispatch({ type: "start", title: options.title(), source, enabled: options.rename() !== undefined })
},
change: (value: string) => dispatch({ type: "change", value }),
blur: () => dispatch({ type: "blur" }),
keydown(event: KeyboardEvent) {
if (event.key !== "Enter" && event.key !== "Escape") return
event.preventDefault()
dispatch({ type: event.key === "Enter" ? "submit" : "cancel" })
},
/** The tab's context menu closed: the field, not the trigger, takes focus while renaming. */
closeAutoFocus(event: Event) {
const current = untrack(state)
if (current.status === "idle") return
event.preventDefault()
if (current.status === "arming" && current.source === "menu") arm(current.attempt)
},
}
function dispatch(event: RenameEvent) {
const previous = untrack(state)
const next = transitionRename(previous, event)
if (next.state !== previous) setState(next.state)
next.effects.forEach((effect) => {
if (effect.type === "disarm") return disarm()
if (effect.type === "save") return options.rename()?.(effect.title)
// A menu pick arms once the menu has closed, from `closeAutoFocus`.
if (effect.source === "menu") return
field.input?.focus()
field.input?.select()
arm(effect.attempt)
})
}
// Next frame the field holds focus, so a blur ends the edit from then on.
function arm(attempt: number) {
disarm()
field.frame = requestAnimationFrame(() => {
field.frame = undefined
const current = untrack(state)
if (current.status !== "arming" || current.attempt !== attempt) return
if (field.input && document.activeElement !== field.input) {
field.input.focus()
if (!current.edited) field.input.select()
}
dispatch({ type: "armed", attempt })
})
}
function disarm() {
if (field.frame !== undefined) cancelAnimationFrame(field.frame)
field.frame = undefined
}
}
+13 -56
View File
@@ -1,8 +1,8 @@
import { Show, onCleanup, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
import { Show, type JSX } from "solid-js"
import { Icon } from "@opencode/ui/icon"
import { Menu } from "@opencode/ui/menu"
import { usePlugin } from "@opencode/plugin/gui"
import { createInlineRename } from "./inline-rename"
/**
* A terminal's side panel tab label: renamed by double-click or its context menu, which also closes it. Without
@@ -16,33 +16,7 @@ export function TerminalTabLabel(props: {
close: () => void
}): JSX.Element {
const plugin = usePlugin()
const [store, setStore] = createStore({ editing: false, title: "" })
let input: HTMLInputElement | undefined
let frame: number | undefined
let renameRequested = false
const edit = () => {
if (!props.rename) return
setStore({ editing: true, title: props.title })
// A blur fired while the trigger releases focus would end the edit before it starts.
if (frame !== undefined) cancelAnimationFrame(frame)
frame = requestAnimationFrame(() => {
frame = undefined
input?.focus()
input?.select()
})
}
const save = () => {
if (!store.editing) return
props.rename?.(store.title.trim() || null)
setStore("editing", false)
}
onCleanup(() => {
if (frame !== undefined) cancelAnimationFrame(frame)
})
const rename = createInlineRename({ title: () => props.title, rename: () => props.rename })
// The label renders inside the strip's tab trigger, so the field keeps its keys, pointer and focus from the trigger:
// the tab list returns focus that enters it from outside to the trigger.
@@ -55,35 +29,25 @@ export function TerminalTabLabel(props: {
<span
class="max-w-40 truncate"
data-slot="terminal-tab-title"
classList={{ invisible: store.editing }}
classList={{ invisible: rename.editing() }}
onDblClick={(event) => {
event.stopPropagation()
edit()
rename.start("pointer")
}}
>
{props.label}
</span>
<Show when={store.editing}>
<Show when={rename.editing()}>
<input
ref={input}
ref={rename.ref}
type="text"
aria-label={plugin.t("common.rename")}
value={store.title}
onInput={(event) => setStore("title", event.currentTarget.value)}
onBlur={save}
value={rename.draft()}
onInput={(event) => rename.change(event.currentTarget.value)}
onBlur={rename.blur}
onKeyDown={(event) => {
event.stopPropagation()
if (event.key === "Enter") {
event.preventDefault()
save()
return
}
if (event.key !== "Escape") return
event.preventDefault()
setStore("editing", false)
rename.keydown(event)
}}
onKeyUp={isolate}
onFocusIn={isolate}
@@ -95,15 +59,8 @@ export function TerminalTabLabel(props: {
</Show>
</Menu.Context.Trigger>
<Menu.Context.Portal>
<Menu.Context.Content
onCloseAutoFocus={(event) => {
if (!renameRequested) return
event.preventDefault()
renameRequested = false
edit()
}}
>
<Menu.Item disabled={!props.rename} onSelect={() => (renameRequested = true)}>
<Menu.Context.Content onCloseAutoFocus={rename.closeAutoFocus}>
<Menu.Item disabled={!props.rename} onSelect={() => rename.start("menu")}>
{plugin.t("common.rename")}
</Menu.Item>
<Menu.Item onSelect={() => props.close()}>{plugin.t("common.close")}</Menu.Item>
+58 -38
View File
@@ -1,5 +1,5 @@
import { createRoot, getOwner, runWithOwner, untrack, type Owner } from "solid-js"
import { createStore, unwrap } from "solid-js/store"
import { createRoot, createSignal, getOwner, runWithOwner, untrack, type Owner } from "solid-js"
import { unwrap } from "solid-js/store"
import { Predicate, Schema } from "effect"
import {
ClientError,
@@ -28,6 +28,14 @@ import {
type Event,
type State,
} from "./machine"
import {
focusRequestToken,
hasFocusRequest,
initialFocusState,
isFocusRequested,
transitionFocus,
type FocusRequestEvent,
} from "./focus-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" }
@@ -38,7 +46,9 @@ export type TerminalModel = ReturnType<typeof createTerminalModel>
export type TerminalSession = ReturnType<TerminalModel["load"]>
type FocusRequest = { key: string; request: number; id?: string; pending: boolean }
const PANELS = "#terminal-panel, #review-panel"
const OVERLAYS = '[role="dialog"], [role="menu"]'
const importGhostty = () => import("ghostty-web").then(async (mod) => ({ mod, ghostty: await mod.Ghostty.load() }))
@@ -66,7 +76,7 @@ export function createTerminalModel(input: {
initial: { servers: {} },
})
const [state, setState] = createStore<{ focus?: FocusRequest }>({})
const [focus, setFocus] = createSignal(initialFocusState)
const sessions = new Map<string, SessionRef>()
const handles = new Map<string, ReturnType<typeof handle>>()
@@ -75,7 +85,6 @@ export function createTerminalModel(input: {
const cleared = new Set<string>()
const cleanups: VoidFunction[] = []
const ghostty: Ghostty = {}
const focus = { request: 0 }
const serverState = (id: string) => machine.servers[id] ?? initialState
@@ -207,35 +216,45 @@ export function createTerminalModel(input: {
return created
}
const requestFocus = (key: string, id?: string, pending = false) => {
focus.request += 1
setState("focus", { key, request: focus.request, id, pending })
const dispatchFocus = (event: FocusRequestEvent) => {
const previous = untrack(focus)
const next = transitionFocus(previous, event)
return focus.request
if (next !== previous) setFocus(next)
return next
}
const cancelFocus = (request?: number) => {
if (request !== undefined && state.focus?.request !== request) return
setState("focus", undefined)
}
// A request from a palette or menu pick starts while the overlay still holds focus.
const overlay = () => typeof document !== "undefined" && inOverlay(document.activeElement)
if (typeof document !== "undefined") {
const cancelOnOutsideFocus = (event: FocusEvent) => {
if (!state.focus) return
const moved = (event: FocusEvent) => {
if (!hasFocusRequest(untrack(focus)) || !(event.target instanceof Element)) return
const panel = event.target.closest(PANELS) !== null
if (!(event.target instanceof Element)) return
dispatchFocus({
type: "focus.moved",
into: !panel ? "outside" : event.target instanceof HTMLInputElement ? "field" : "panel",
leavingOverlay: event.relatedTarget === null || inOverlay(event.relatedTarget),
})
}
// The side region focuses its selected tab trigger or root while switching tabs; only focus leaving it, or
// entering a field in it such as a tab's rename field, cancels.
if (event.target.closest("#terminal-panel, #review-panel") && !(event.target instanceof HTMLInputElement)) return
// A press where focus already is moves no focus, and still means the user moved on.
const pressed = (event: PointerEvent) => {
if (!hasFocusRequest(untrack(focus)) || !(event.target instanceof Element)) return
cancelFocus()
if (event.target.closest(PANELS) || inOverlay(event.target)) return
dispatchFocus({ type: "pointer.outside" })
}
// Capture phase: a tab's rename field stops its focusin from bubbling.
document.addEventListener("focusin", cancelOnOutsideFocus, true)
cleanups.push(() => document.removeEventListener("focusin", cancelOnOutsideFocus, true))
document.addEventListener("focusin", moved, true)
document.addEventListener("pointerdown", pressed, true)
cleanups.push(() => {
document.removeEventListener("focusin", moved, true)
document.removeEventListener("pointerdown", pressed, true)
})
}
const handle = (initial: SessionRef) => {
@@ -246,12 +265,6 @@ export function createTerminalModel(input: {
const all = () => viewItems(view())
const get = (id: string) => all().find((info) => info.id === id)
const focusRequested = (id?: string) => {
if (!id || !state.focus || state.focus.pending || state.focus.key !== key) return false
return !state.focus.id || state.focus.id === id
}
return {
key,
server: () => session().server,
@@ -276,7 +289,7 @@ export function createTerminalModel(input: {
/** Creates a terminal and selects it; resolves its id, or undefined when the server refuses. */
async new() {
const target = session()
const request = requestFocus(key, undefined, true)
const request = dispatchFocus({ type: "request.pending", session: key, overlay: overlay() }).request
await settled(target, owner)
@@ -299,7 +312,7 @@ export function createTerminalModel(input: {
env: {},
})
.catch((error) => {
cancelFocus(request)
dispatchFocus({ type: "pending.failed", request })
// A server without the persistent terminal routes answers with a status its API never declares for them.
const outdated =
@@ -325,8 +338,7 @@ export function createTerminalModel(input: {
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 })
dispatchFocus({ type: "pending.resolved", request, id: info.id })
return info.id
},
@@ -372,15 +384,18 @@ export function createTerminalModel(input: {
)
})
},
requestFocus(id?: string) {
requestFocus(key, id)
requestFocus(id: string) {
dispatchFocus({ type: "request.target", session: key, id, overlay: overlay() })
},
focusRequested,
/** The terminal should take focus once it shows. */
focusRequested: (id: string) => isFocusRequested(focus(), key, id),
/** The request asking the terminal to take focus, so each focus attempt runs once per request. */
focusRequest: (id: string) => focusRequestToken(focus(), key, id),
consumeFocus(id: string) {
if (focusRequested(id)) setState("focus", undefined)
dispatchFocus({ type: "consumed", session: key, id })
},
cancelFocus() {
if (state.focus?.key === key) cancelFocus()
dispatchFocus({ type: "cancelled", session: key })
},
}
}
@@ -426,6 +441,7 @@ export function createTerminalModel(input: {
sessions.delete(session.key)
handles.delete(session.key)
selected.delete(session.key)
dispatchFocus({ type: "cancelled", session: session.key })
})
const server = removed[0]?.server
@@ -454,6 +470,10 @@ export function createTerminalModel(input: {
}
}
function inOverlay(node: EventTarget | null) {
return node instanceof Element && node.closest(OVERLAYS) !== null
}
/** Resolves once the server has created the session. */
function settled(session: SessionRef, owner: Owner | null) {
if (!session.pending) return Promise.resolve()
+8 -6
View File
@@ -1,4 +1,4 @@
import { For, Match, Show, Switch, createMemo, onCleanup } from "solid-js"
import { For, Match, Show, Switch, createMemo, onCleanup, untrack } from "solid-js"
import { createStore } from "solid-js/store"
import { Button } from "@opencode/ui/button"
import { Tabs } from "@opencode/ui/tabs"
@@ -107,16 +107,18 @@ export default function TerminalPanel(props: {
() => {
const id = active()
return opened() && id && terminal().focusRequested(id) ? { id } : undefined
return opened() && id ? terminal().focusRequest(id) : undefined
},
(request) => {
const id = untrack(active)
const focusFrame = requestAnimationFrame(() => {
if (!opened() || active() !== request.id || !terminal().focusRequested(request.id)) return
if (!id || !opened() || active() !== id || terminal().focusRequest(id) !== request) return
focusTerminalById(request.id)
const input = document.getElementById(`terminal-wrapper-${request.id}`)?.querySelector("textarea")
focusTerminalById(id)
const input = document.getElementById(`terminal-wrapper-${id}`)?.querySelector("textarea")
if (input === document.activeElement) terminal().consumeFocus(request.id)
if (input === document.activeElement) terminal().consumeFocus(id)
})
onCleanup(() => cancelAnimationFrame(focusFrame))
@@ -0,0 +1,99 @@
import { describe, expect, test } from "bun:test"
import {
initialRenameState,
transitionRename,
type RenameEvent,
type RenameState,
type RenameTransition,
} from "./rename-machine"
const replay = (events: readonly RenameEvent[], state: RenameState = initialRenameState) =>
events.reduce<RenameTransition>((last, event) => transitionRename(last.state, event), { state, effects: [] })
const start = (source: "pointer" | "menu" = "pointer"): RenameEvent => ({
type: "start",
title: "Terminal 1",
source,
enabled: true,
})
describe("terminal rename machine", () => {
test("starting again while renaming keeps the edit, which still saves on blur", () => {
const editing = replay([start(), { type: "armed", attempt: 1 }, { type: "change", value: "Build" }]).state
// Before, a second double-click or menu Rename left blur and Enter ignored for good.
const again = transitionRename(editing, start("menu"))
expect(again.state).toBe(editing)
expect(again.effects).toEqual([])
expect(transitionRename(again.state, { type: "blur" })).toEqual({
state: { status: "idle", issued: 1 },
effects: [{ type: "save", title: "Build" }],
})
const arming = replay([start()]).state
expect(transitionRename(arming, start()).state).toBe(arming)
})
test("Enter before the field armed saves the typed title", () => {
const submitted = replay([start(), { type: "change", value: "Dev" }, { type: "submit" }])
// Before, Enter in the first frame was dropped.
expect(submitted).toEqual({
state: { status: "idle", issued: 1 },
effects: [{ type: "disarm" }, { type: "save", title: "Dev" }],
})
expect(transitionRename(submitted.state, { type: "armed", attempt: 1 }).state).toBe(submitted.state)
})
test("a blur while arming is ignored; once armed, blur saves once", () => {
const arming = replay([start()])
expect(arming.effects).toEqual([{ type: "arm", attempt: 1, source: "pointer" }])
expect(transitionRename(arming.state, { type: "blur" }).state).toBe(arming.state)
const saved = replay([{ type: "armed", attempt: 1 }, { type: "blur" }], arming.state)
expect(saved.effects).toEqual([{ type: "save", title: "Terminal 1" }])
// The field's blur as it unmounts finds nothing to save.
expect(transitionRename(saved.state, { type: "blur" })).toEqual({ state: saved.state, effects: [] })
})
test("Escape cancels without saving", () => {
const cancelled = replay([
start(),
{ type: "armed", attempt: 1 },
{ type: "change", value: "Temp" },
{ type: "cancel" },
])
expect(cancelled).toEqual({ state: { status: "idle", issued: 1 }, effects: [] })
expect(transitionRename(cancelled.state, { type: "blur" }).effects).toEqual([])
expect(replay([start("menu"), { type: "cancel" }]).effects).toEqual([{ type: "disarm" }])
})
test("an emptied field saves null, and a typed draft is kept from selection when the field arms", () => {
expect(
replay([start(), { type: "armed", attempt: 1 }, { type: "change", value: " " }, { type: "submit" }]).effects,
).toEqual([{ type: "save", title: null }])
expect(replay([start(), { type: "change", value: "Dev" }]).state).toMatchObject({ edited: true, draft: "Dev" })
})
test("a terminal that cannot be renamed, or an arm from an earlier attempt, changes nothing", () => {
const disabled = transitionRename(initialRenameState, {
type: "start",
title: "Terminal 1",
source: "pointer",
enabled: false,
})
expect(disabled.state).toBe(initialRenameState)
const second = replay([start(), { type: "cancel" }, start("menu")])
expect(second.effects).toEqual([{ type: "arm", attempt: 2, source: "menu" }])
expect(transitionRename(second.state, { type: "armed", attempt: 1 }).state).toBe(second.state)
})
})
@@ -0,0 +1,98 @@
/** What started a rename: a double-click on the title, or the tab's context menu. */
export type RenameSource = "pointer" | "menu"
/**
* A terminal tab's inline rename. `arming` shows the field while focus settles: the trigger or the closing menu still
* moves focus, so a blur then does not end the edit. `editing` saves on blur. `issued` is the last attempt handed out.
*/
export type RenameState =
| { readonly status: "idle"; readonly issued: number }
| {
readonly status: "arming"
readonly issued: number
readonly attempt: number
readonly source: RenameSource
readonly draft: string
/** The user typed before the field armed, so arming leaves their text unselected. */
readonly edited: boolean
}
| { readonly status: "editing"; readonly issued: number; readonly draft: string }
export type RenameEvent =
/** `enabled` is false for a terminal that cannot be renamed. */
| { readonly type: "start"; readonly title: string; readonly source: RenameSource; readonly enabled: boolean }
/** The field took focus after the attempt's frame. */
| { readonly type: "armed"; readonly attempt: number }
| { readonly type: "change"; readonly value: string }
/** Enter. */
| { readonly type: "submit" }
| { readonly type: "blur" }
/** Escape. */
| { readonly type: "cancel" }
export type RenameEffect =
/** Focus the field: a double-click at once and again next frame, a menu pick once the menu has closed. */
| { readonly type: "arm"; readonly attempt: number; readonly source: RenameSource }
| { readonly type: "disarm" }
/** `null` for an emptied field. */
| { readonly type: "save"; readonly title: string | null }
export type RenameTransition = { readonly state: RenameState; readonly effects: readonly RenameEffect[] }
export const initialRenameState: RenameState = { status: "idle", issued: 0 }
const NONE: readonly RenameEffect[] = []
const DISARM: readonly RenameEffect[] = [{ type: "disarm" }]
export function transitionRename(state: RenameState, event: RenameEvent): RenameTransition {
if (event.type === "start") {
// A rename already open keeps its field, its draft and its blur handling.
if (state.status !== "idle" || !event.enabled) return { state, effects: NONE }
const attempt = state.issued + 1
return {
state: { status: "arming", issued: attempt, attempt, source: event.source, draft: event.title, edited: false },
effects: [{ type: "arm", attempt, source: event.source }],
}
}
if (state.status === "idle") return { state, effects: NONE }
if (event.type === "armed")
return {
state:
state.status === "arming" && state.attempt === event.attempt
? { status: "editing", issued: state.issued, draft: state.draft }
: state,
effects: NONE,
}
if (event.type === "change") {
if (event.value === state.draft) return { state, effects: NONE }
return {
state:
state.status === "arming" ? { ...state, draft: event.value, edited: true } : { ...state, draft: event.value },
effects: NONE,
}
}
if (event.type === "blur" && state.status === "arming") return { state, effects: NONE }
const disarm = state.status === "arming" ? DISARM : NONE
const idle: RenameState = { status: "idle", issued: state.issued }
// Ending the edit unmounts the focused field, whose blur then finds nothing to save.
if (event.type === "cancel") return { state: idle, effects: disarm }
return { state: idle, effects: [...disarm, { type: "save", title: state.draft.trim() || null }] }
}
export function isRenaming(state: RenameState) {
return state.status !== "idle"
}
export function renameDraft(state: RenameState) {
return state.status === "idle" ? "" : state.draft
}
@@ -55,9 +55,16 @@ const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
layout.open(key(id), session, layout.narrow() ? undefined : { tab: "select" })
}
// `new` selects the terminal and asks it to take focus, unless the user moved on while it was created. Then opening
// its tab, which asks for focus again, gives that up.
const create = (session: MountedSession, terminal: TerminalSession) =>
void terminal.new().then((id) => {
if (id && !ctx.signal.aborted) show(session, terminal, id)
if (!id || ctx.signal.aborted) return
const focused = terminal.focusRequested(id)
layout.open(key(id), session, layout.narrow() ? undefined : { tab: "select" })
if (!focused) terminal.cancelFocus()
})
ctx.add(BuiltinSlot, {
+19 -92
View File
@@ -1,6 +1,5 @@
import type { JSX } from "solid-js"
import { Show, onCleanup } from "solid-js"
import { createStore } from "solid-js/store"
import { Show } from "solid-js"
import type { PersistentPtyInfo } from "@opencode/client"
import { Tabs } from "@opencode/ui/tabs"
import { Menu } from "@opencode/ui/menu"
@@ -8,6 +7,7 @@ import { usePlugin } from "@opencode/plugin/gui"
import type { TerminalSession } from "./model"
import { terminalTabLabel } from "./title"
import { focusTerminalById } from "./focus"
import { createInlineRename } from "./inline-rename"
/** A terminal's tab in the narrow-screen view. Without `rename` the terminal cannot be renamed. */
export function TerminalTab(props: {
@@ -18,23 +18,14 @@ export function TerminalTab(props: {
}): JSX.Element {
const plugin = usePlugin()
const [store, setStore] = createStore({
editing: false,
title: props.terminal.title,
blurEnabled: false,
})
let input: HTMLInputElement | undefined
let blurFrame: number | undefined
let editFrame: number | undefined
let editRequested = false
const rename = createInlineRename({ title: () => props.terminal.title, rename: () => props.rename })
const label = () => terminalTabLabel({ title: props.terminal.title, t: plugin.t })
const close = () => void props.session.close(props.terminal.id)
const focus = () => {
if (store.editing) return
if (rename.editing()) return
props.session.requestFocus(props.terminal.id)
props.session.select(props.terminal.id)
@@ -45,66 +36,10 @@ export function TerminalTab(props: {
if (input === document.activeElement) props.session.consumeFocus(props.terminal.id)
}
const edit = (e?: Event) => {
if (e) {
e.stopPropagation()
e.preventDefault()
}
if (!props.rename) return
const editing = store.editing
setStore("blurEnabled", false)
setStore("title", props.terminal.title)
setStore("editing", true)
// The input mounts with `editing`; a rename already in progress keeps its focus.
if (editing || !input) return
input.focus()
input.select()
if (blurFrame !== undefined) cancelAnimationFrame(blurFrame)
blurFrame = requestAnimationFrame(() => {
blurFrame = undefined
setStore("blurEnabled", true)
})
}
// Ending the edit unmounts the focused field, whose blur would save again, or save a cancelled title.
// The field renders inside the strip's tab trigger, so it keeps its keys, pointer and focus from the trigger: the
// tab list returns focus that enters it from outside to the trigger.
const isolate = (event: Event) => event.stopPropagation()
const save = () => {
if (!store.editing || !store.blurEnabled) return
props.rename?.(store.title.trim() || null)
setStore("editing", false)
}
const keydown = (e: KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault()
save()
return
}
if (e.key === "Escape") {
e.preventDefault()
setStore("editing", false)
}
}
onCleanup(() => {
if (blurFrame !== undefined) cancelAnimationFrame(blurFrame)
if (editFrame !== undefined) cancelAnimationFrame(editFrame)
})
return (
<div class="h-full flex items-center outline-none focus:outline-none focus-visible:outline-none">
<Menu.Context>
@@ -115,7 +50,7 @@ export function TerminalTab(props: {
// Switch on mousedown to shave the press-release delay off tab switches.
if (e.button !== 0) return
if (store.editing) return
if (rename.editing()) return
focus()
}}
onClick={(e) => {
@@ -130,24 +65,28 @@ export function TerminalTab(props: {
<span
class="truncate"
data-slot="terminal-tab-title"
onDblClick={edit}
classList={{ invisible: store.editing }}
onDblClick={(e) => {
e.stopPropagation()
e.preventDefault()
rename.start("pointer")
}}
classList={{ invisible: rename.editing() }}
>
{label()}
</span>
</Tabs.Trigger>
<Show when={store.editing}>
<Show when={rename.editing()}>
<div class="absolute inset-0 flex items-center bg-v2-background-bg-layer-01 z-10 pointer-events-auto rounded-[6px] shadow-[inset_0_0_0_0.5px_var(--v2-border-border-muted)] px-2">
<input
ref={input}
ref={rename.ref}
type="text"
aria-label={plugin.t("common.rename")}
value={store.title}
onInput={(e) => setStore("title", e.currentTarget.value)}
onBlur={save}
value={rename.draft()}
onInput={(e) => rename.change(e.currentTarget.value)}
onBlur={rename.blur}
onKeyDown={(e) => {
isolate(e)
keydown(e)
rename.keydown(e)
}}
onKeyUp={isolate}
onFocusIn={isolate}
@@ -160,20 +99,8 @@ export function TerminalTab(props: {
</Show>
</Menu.Context.Trigger>
<Menu.Context.Portal>
<Menu.Context.Content
onCloseAutoFocus={(e) => {
if (!editRequested) return
e.preventDefault()
editRequested = false
if (editFrame !== undefined) cancelAnimationFrame(editFrame)
editFrame = requestAnimationFrame(() => {
editFrame = undefined
edit()
})
}}
>
<Menu.Item disabled={!props.rename} onSelect={() => (editRequested = true)}>
<Menu.Context.Content onCloseAutoFocus={rename.closeAutoFocus}>
<Menu.Item disabled={!props.rename} onSelect={() => rename.start("menu")}>
{plugin.t("common.rename")}
</Menu.Item>
<Menu.Item onSelect={close}>{plugin.t("common.close")}</Menu.Item>