fix(app): let a custom Close tab shortcut close terminal and browser tabs (#58945)

Co-authored-by: vimtor <36263538+vimtor@users.noreply.github.com>
This commit is contained in:
opencode-agent[bot]
2026-10-25 10:47:03 +00:00
committed by GitHub
Unverified
parent a41d09bc78
commit 7a83c69fe1
9 changed files with 121 additions and 74 deletions
@@ -383,6 +383,18 @@ test("clearing project fields sends explicit removal values", async ({ page }) =
}
})
for (const own of [false, true]) {
test(`shortcuts list a command that shares Close tab only with its own shortcut: ${own}`, async ({ page }) => {
const { settings } = await open(page, {
seed: { settings: { keybinds: own ? { "terminal.close": "ctrl+alt+e" } : {} } },
})
await settings.getByRole("tab", { name: "Shortcuts", exact: true }).click()
await expect(settings.locator('[data-keybind-id="terminal.new"]')).toBeVisible()
await expect(settings.locator('[data-keybind-id="terminal.close"]')).toHaveText(own ? ["Ctrl+Alt+E"] : [])
})
}
test("the new session shortcut waits for a shortcut recording, then leaves settings", async ({ page }) => {
const { settings } = await open(page)
await settings.getByRole("tab", { name: "Shortcuts", exact: true }).click()
@@ -19,6 +19,22 @@ test("clears the terminal line with Command+Delete", async ({ page }) => {
await expect.poll(() => pty.sockets[0]!.input.join("")).toBe("\x15")
})
test("a custom Close tab shortcut closes the focused terminal, not the session tab", async ({ page }) => {
const { session } = await openSession(page, {
...workspace,
seed: { settings: { keybinds: { "tab.close": "mod+e" } } },
})
const terminal = page.locator('[data-component="terminal"]')
await page.keyboard.press("Control+Backquote")
await expect(terminal.locator("textarea")).toHaveCount(1)
await expect.poll(() => terminal.evaluate((element) => element.contains(document.activeElement))).toBe(true)
await page.keyboard.press("ControlOrMeta+e")
await expect(terminal).toHaveCount(0)
await expect(page).toHaveURL(sessionHref(session.id))
})
test("reveals the terminal after its first output and hides the native caret", async ({ page }) => {
const { pty } = await openSession(page, workspace)
await page.keyboard.press("Control+Backquote")
+25 -21
View File
@@ -17,27 +17,31 @@ export function ExtensionCommands() {
host
.items(Command)
.toSorted((a, b) => order(a.extension) - order(b.extension))
.map((item) => ({
id: `${item.extension}.${item.value.id}`,
title: item.value.title,
description: item.value.description,
category: item.value.group,
section: item.value.section,
keybind: item.value.bind,
slash: item.value.slash?.name,
slashArguments: item.value.slash?.arguments,
slashAfter: item.value.slash?.after,
suggested: item.value.suggested,
featured: item.value.featured,
disabled: item.value.enabled === false,
hidden: item.value.hidden,
editable: item.value.editable,
when: item.value.scope
? (event: KeyboardEvent) =>
event.target instanceof Element && !!event.target.closest(item.value.scope as string)
: undefined,
onSelect: (_source: unknown, input?: string) => item.value.run(input),
})),
.map((item) => {
const scope = item.value.scope
return {
id: `${item.extension}.${item.value.id}`,
title: item.value.title,
description: item.value.description,
category: item.value.group,
section: item.value.section,
keybind: item.value.bind,
follows: item.value.follows,
slash: item.value.slash?.name,
slashArguments: item.value.slash?.arguments,
slashAfter: item.value.slash?.after,
suggested: item.value.suggested,
featured: item.value.featured,
disabled: item.value.enabled === false,
hidden: item.value.hidden,
editable: item.value.editable,
when: scope
? (event: KeyboardEvent) => event.target instanceof Element && !!event.target.closest(scope)
: undefined,
onSelect: (_source, input) => item.value.run(input),
}
}),
)
return null
@@ -401,7 +401,8 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
fileCommand({
id: "file.close",
title: language.t("command.tab.close"),
keybind: settings.keybinds.get("tab.close") ?? "mod+w",
keybind: "mod+w",
follows: "tab.close",
when: (event) => !extensionScoped(event.target),
onSelect: closeTab,
}),
+15 -14
View File
@@ -4,6 +4,7 @@ import { makeEventListener } from "@solid-primitives/event-listener"
import { Button } from "@opencode/ui/button"
import { showToast } from "@/shell/notifications/toast"
import fuzzysort from "fuzzysort"
import { Predicate } from "effect"
import {
DEFAULT_PALETTE_KEYBIND,
formatKeybind,
@@ -18,7 +19,7 @@ import { SettingsList } from "@/settings/list"
import { SettingsSearchEmpty } from "@/settings/search-empty"
import { SettingsSearchField } from "@/settings/search-field"
const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
const PALETTE_ID = "command.palette"
@@ -141,20 +142,18 @@ function signatures(config: string | undefined) {
return sigs
}
function keybinds(value: unknown): KeybindMap {
if (!value || typeof value !== "object" || Array.isArray(value)) return {}
return value as KeybindMap
}
function listFor(command: Pick<CommandContext, "catalog" | "options">, map: KeybindMap, palette: string) {
const out = new Map<string, KeybindMeta>()
out.set(PALETTE_ID, { title: palette, group: "General" })
// A command that shares another's shortcut is set through that command, unless it already has its own.
const follower = (opt: { id: string; follows?: string }) => !!opt.follows && !Predicate.isString(map[opt.id])
for (const opt of command.catalog) {
if (opt.id.startsWith("suggested.")) continue
if (opt.hidden) continue
if (follower(opt)) continue
out.set(opt.id, { title: opt.title, group: groupFor(opt.id, opt.section) })
}
@@ -162,11 +161,13 @@ function listFor(command: Pick<CommandContext, "catalog" | "options">, map: Keyb
if (opt.id.startsWith("suggested.")) continue
if (opt.hidden) continue
if (follower(opt)) continue
out.set(opt.id, { title: opt.title, group: groupFor(opt.id, opt.section) })
}
for (const [id, value] of Object.entries(map)) {
if (typeof value !== "string") continue
if (!Predicate.isString(value)) continue
if (out.has(id)) continue
out.set(id, { title: id, group: groupFor(id) })
@@ -237,7 +238,7 @@ export function createKeybindSettingsController(
input: {
command: Pick<CommandContext, "catalog" | "options" | "keybinds">
settings: {
current: { keybinds: unknown }
current: { keybinds?: KeybindMap }
keybinds: Pick<SettingsContext["keybinds"], "get" | "set" | "resetAll">
}
target?: Document
@@ -245,8 +246,8 @@ export function createKeybindSettingsController(
},
language: Pick<LanguageContext, "locale" | "t"> = useLanguage(),
) {
const [store, setStore] = createStore({ active: null as string | null })
const overrides = createMemo(() => keybinds(input.settings.current.keybinds))
const [store, setStore] = createStore<{ active: string | null }>({ active: null })
const overrides = createMemo(() => input.settings.current.keybinds ?? {})
const list = createMemo(() => {
language.locale()
@@ -262,7 +263,7 @@ export function createKeybindSettingsController(
const custom = input.settings.keybinds.get(id)
if (typeof custom === "string") return custom
if (Predicate.isString(custom)) return custom
const live = input.command.options.find((item) => item.id === id)
@@ -368,7 +369,7 @@ export function createKeybindSettingsController(
stop()
}
const target = input.target ?? (typeof document === "object" ? document : undefined)
const target = input.target ?? (typeof document !== "undefined" ? document : undefined)
if (target) makeEventListener(target, "keydown", handle, { capture: true })
@@ -389,7 +390,7 @@ export function createKeybindSettingsController(
toggle,
},
settings: {
hasOverrides: () => Object.values(overrides()).some((value) => typeof value === "string"),
hasOverrides: () => Object.values(overrides()).some(Predicate.isString),
reset: () => {
stop()
input.settings.keybinds.resetAll()
+43 -38
View File
@@ -2,7 +2,7 @@ import { createSimpleContext } from "@opencode/ui/context"
import { useDialog } from "@opencode/ui/context/dialog"
import { type Accessor, batch, createEffect, createMemo, onCleanup, onMount, untrack } from "solid-js"
import { createStore, produce, reconcile } from "solid-js/store"
import { Schema } from "effect"
import { Predicate, Schema } from "effect"
import { Persistence } from "@/runtime/persistence/schema"
import { makeEventListener } from "@solid-primitives/event-listener"
import { useLanguage } from "@/runtime/i18n/language"
@@ -11,7 +11,7 @@ import { keybindRenames } from "@/settings/keybinds/migration"
import en from "@/runtime/i18n/en"
import { Persist, persisted } from "@/runtime/persistence/storage"
const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
const PALETTE_ID = "command.palette"
@@ -98,6 +98,8 @@ export interface CommandOption {
/** Section of Settings > Shortcuts. Host commands leave it unset and are placed by id prefix. */
section?: CommandSection
keybind?: KeybindConfig
/** Command id whose custom keybind this command takes; Settings > Shortcuts lists only that command. */
follows?: string
slash?: string
slashArguments?: boolean
/** Listed right after the option whose slash name this is, when one is registered. */
@@ -133,6 +135,7 @@ export const CommandCatalogItem = Persistence.struct({
category: Schema.optional(Schema.String),
section: Persistence.optional(CommandSection),
keybind: Schema.optional(Schema.String),
follows: Schema.optional(Schema.String),
slash: Schema.optional(Schema.String),
hidden: Schema.optional(Schema.Boolean),
})
@@ -262,39 +265,37 @@ function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) {
if (!kb.key) return parts
const keys: Record<string, string> = {
arrowup: "↑",
arrowdown: "↓",
arrowleft: "←",
arrowright: "→",
comma: ",",
plus: "+",
}
const keys = new Map<string, string>([
["arrowup", "↑"],
["arrowdown", "↓"],
["arrowleft", "←"],
["arrowright", "→"],
["comma", ","],
["plus", "+"],
])
const named: Record<string, KeyLabel> = {
backspace: "common.key.backspace",
delete: "common.key.delete",
end: "common.key.end",
enter: "common.key.enter",
esc: "common.key.esc",
escape: "common.key.esc",
home: "common.key.home",
insert: "common.key.insert",
pagedown: "common.key.pageDown",
pageup: "common.key.pageUp",
space: "common.key.space",
tab: "common.key.tab",
}
const named = new Map<string, KeyLabel>([
["backspace", "common.key.backspace"],
["delete", "common.key.delete"],
["end", "common.key.end"],
["enter", "common.key.enter"],
["esc", "common.key.esc"],
["escape", "common.key.esc"],
["home", "common.key.home"],
["insert", "common.key.insert"],
["pagedown", "common.key.pageDown"],
["pageup", "common.key.pageUp"],
["space", "common.key.space"],
["tab", "common.key.tab"],
])
const key = kb.key.toLowerCase()
const label = named.get(key)
const displayKey =
keys[key] ??
(named[key]
? keyText(named[key], t)
: key.length === 1
? key.toUpperCase()
: key.charAt(0).toUpperCase() + key.slice(1))
keys.get(key) ??
(label ? keyText(label, t) : key.length === 1 ? key.toUpperCase() : key.charAt(0).toUpperCase() + key.slice(1))
parts.push(displayKey)
@@ -335,8 +336,8 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const settings = useSettings()
const language = useLanguage()
const [store, setStore] = createStore({
registrations: [] as CommandRegistration[],
const [store, setStore] = createStore<{ registrations: CommandRegistration[]; suspendCount: number }>({
registrations: [],
suspendCount: 0,
})
@@ -344,8 +345,8 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const [catalog, setCatalog, _, catalogReady] = persisted(Persist.global("command.catalog.v1"), CommandCatalog, {})
const bind = (id: string, def: KeybindConfig | undefined) => {
const custom = settings.keybinds.get(actionId(id))
const bind = (id: string, def: KeybindConfig | undefined, follows?: string) => {
const custom = settings.keybinds.get(actionId(id)) ?? (follows ? settings.keybinds.get(follows) : undefined)
const config = custom ?? def
if (!config || config === "none") return
@@ -390,6 +391,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
category: opt.category,
section: opt.section,
keybind: opt.keybind,
follows: opt.follows,
slash: opt.slash,
}),
)
@@ -411,7 +413,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const options = createMemo(() => {
const resolved = registered().map((opt) => ({
...opt,
keybind: bind(opt.id, opt.keybind),
keybind: bind(opt.id, opt.keybind, opt.follows),
}))
const suggested = resolved.filter((x) => x.suggested && !x.disabled)
@@ -517,8 +519,8 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
function register(cb: () => CommandOption[]): void
function register(key: string, cb: () => CommandOption[]): void
function register(key: string | (() => CommandOption[]), cb?: () => CommandOption[]) {
const id = typeof key === "string" ? key : undefined
const next = typeof key === "function" ? key : cb
const id = Predicate.isString(key) ? key : undefined
const next = Predicate.isString(key) ? cb : key
if (!next) return
const options = createMemo(next)
@@ -540,7 +542,10 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
if (id === PALETTE_ID) return settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
const base = actionId(id)
return options().find((x) => actionId(x.id) === base)?.keybind ?? bind(base, catalog[base]?.keybind)
return (
options().find((x) => actionId(x.id) === base)?.keybind ??
bind(base, catalog[base]?.keybind, catalog[base]?.follows)
)
}
return {
@@ -99,6 +99,7 @@ const setup: Setup<typeof definition> = (ctx) => {
title: ctx.t("command.close"),
group: ctx.t("command.category.view"),
bind: "mod+w",
follows: "tab.close",
scope: "#browser-panel",
hidden: true,
editable: true,
@@ -31,6 +31,12 @@ export interface Command {
readonly section?: "general" | "session" | "navigation" | "model" | "terminal" | "prompt"
/** The default keybind, e.g. `mod+shift+t`. The user can change it in Settings > Shortcuts. */
readonly bind?: string
/**
* Published command id whose shortcut this command shares, e.g. `tab.close` for a command that closes a tab inside
* its `scope`. The command takes that command's custom shortcut, or `bind` while it has none, and Settings >
* Shortcuts lists only that command. Pair it with `scope`, so the shared shortcut reaches this command only there.
*/
readonly follows?: string
/** Also offers the command as a composer slash command. */
readonly slash?: {
/** The name after the slash, e.g. `open` for `/open`. */
@@ -102,6 +102,7 @@ const setup: Setup<typeof Terminal> = (ctx) => {
group: ctx.t("command.category"),
section: "terminal",
bind: "mod+w",
follows: "tab.close",
hidden: true,
scope: '[data-component="terminal"]',
enabled: routed(),