feat(app): close side panel tabs to the right and make ⌘W/⌘⇧T side-panel aware (#62922)

This commit is contained in:
usrnk1
2026-11-09 21:43:57 +01:00
committed by GitHub
Unverified
parent f8fd7b0f3c
commit 85dc877ea4
20 changed files with 374 additions and 56 deletions
@@ -495,6 +495,7 @@ export function mountPanelWidths(input: { definitions: readonly Entry[]; active:
setActive: (key) => key && setActive(key),
close() {},
remap() {},
target() {},
}),
closed: createClosedTabs(),
open() {},
@@ -615,6 +616,7 @@ export function mountSessionRegion(input: {
setActive() {},
close() {},
remap() {},
target() {},
}),
closed: createClosedTabs(),
open() {},
@@ -221,7 +221,7 @@ test("New tabs stay when a launcher in another one opens a tab, or when the tab
await expect(toggle).toHaveAttribute("aria-expanded", "false")
})
test("tabs in a narrow side strip shrink to keep their close buttons, and a tab's menu closes the others", async ({
test("tabs in a narrow side strip shrink to keep their close buttons, and a tab's menu closes the others or those to its right", async ({
page,
}) => {
await page.setViewportSize({ width: 1000, height: 700 })
@@ -257,16 +257,53 @@ test("tabs in a narrow side strip shrink to keep their close buttons, and a tab'
expect(box.x + box.width).toBeLessThanOrEqual(end)
}
await side.getByRole("tab", { name: "b.md", exact: true }).click({ button: "right" })
await side.getByRole("tab", { name: files[1], exact: true }).click({ button: "right" })
await page.getByRole("menuitem", { name: "Close tabs to the right", exact: true }).click()
await expect(side.getByRole("tab")).toHaveText(["a.md", files[1]])
await side.getByRole("tab", { name: "a.md", exact: true }).click({ button: "right" })
await page.getByRole("menuitem", { name: "Close other tabs", exact: true }).click()
await expect(side.getByRole("tab")).toHaveCount(1)
await expect(side.getByRole("tab", { name: "b.md", exact: true })).toHaveAttribute("aria-selected", "true")
await expect(side.getByRole("tab", { name: "a.md", exact: true })).toHaveAttribute("aria-selected", "true")
// With nothing else to close, the menu offers only the tab itself.
await side.getByRole("tab", { name: "b.md", exact: true }).click({ button: "right" })
await side.getByRole("tab", { name: "a.md", exact: true }).click({ button: "right" })
await expect(page.getByRole("menuitem", { name: "Close other tabs", exact: true })).toBeDisabled()
await expect(page.getByRole("menuitem", { name: "Close tabs to the right", exact: true })).toBeDisabled()
await page.getByRole("menuitem", { name: "Close tab", exact: true }).click()
await expect(side.getByRole("tab", { name: "b.md", exact: true })).toHaveCount(0)
await expect(side.getByRole("tab", { name: "a.md", exact: true })).toHaveCount(0)
})
test("a reopened side tab returns to where it closed", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
const directory = "C:/OpenCode/ReopenPlace"
const key = `local\u0000${base64Encode(directory)}/ses_reopenplace`
const files = ["a.md", "b.md", "c.md"]
await openSession(page, {
name: "ReopenPlace",
fileList: () => [],
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
seed: {
panes: { ses_reopenplace: { review: true } },
storage: {
"opencode.global.dat:layout": {
sessionTabs: { [key]: { all: files.map((file) => `file://${file}`), active: "file://b.md" } },
},
},
},
})
const side = page.locator('[data-pane-content="side"]')
await expect(side.getByRole("tab", { name: "b.md", exact: true })).toHaveAttribute("aria-selected", "true")
await page.getByRole("textbox", { name: "Prompt", exact: true }).click()
await page.keyboard.press("ControlOrMeta+w")
await expect(side.getByRole("tab")).toHaveText(["a.md", "c.md"])
await page.keyboard.press("ControlOrMeta+Shift+t")
await expect(side.getByRole("tab")).toHaveText(["a.md", "b.md", "c.md"])
await expect(side.getByRole("tab", { name: "b.md", exact: true })).toHaveAttribute("aria-selected", "true")
})
async function expectTreeSentinel(page: Page) {
+96 -3
View File
@@ -1546,8 +1546,10 @@ test("tab shortcuts cycle side-panel tabs when the side panel is focused with mu
})
test("⌘W past the side panel's last tab keeps the session tab", async ({ page }) => {
const sessions = await emptySidePanel(page)
await page.clock.install()
const sessions = await emptySidePanel(page, () => holdClock(page))
await page.keyboard.press("ControlOrMeta+w")
await page.clock.resume()
// From the composer ⌘W closes the session tab, so only a swallowed press above leaves Beta to land on.
await page.getByRole("textbox", { name: "Prompt", exact: true }).click()
@@ -1556,6 +1558,35 @@ test("⌘W past the side panel's last tab keeps the session tab", async ({ page
await expect(sessions.alphaTab).toHaveCount(0)
})
test("⌘W past the side panel's last tab closes the session tab once ⌘W has rested", async ({ page }) => {
await page.clock.install()
const sessions = await emptySidePanel(page, () => holdClock(page))
// Each ⌘W within the rest is swallowed and restarts it, so the third lands 800ms after the panel closed.
await page.keyboard.press("ControlOrMeta+w")
await page.clock.runFor(400)
await page.keyboard.press("ControlOrMeta+w")
await page.clock.runFor(400)
await page.keyboard.press("ControlOrMeta+w")
await expect(sessions.alphaTab).toHaveCount(1)
await page.clock.runFor(600)
await page.clock.resume()
await page.keyboard.press("ControlOrMeta+w")
await expectPath(page, sessionHref(sessions.beta.id))
await expect(sessions.alphaTab).toHaveCount(0)
})
test("⌘⇧T brings back a side tab and opens the side panel it closed with", async ({ page }) => {
await emptySidePanel(page)
const panel = page.locator("#review-panel")
await page.getByRole("textbox", { name: "Prompt", exact: true }).click()
await page.keyboard.press("ControlOrMeta+Shift+t")
await expect(panel).toHaveAttribute("aria-hidden", "false")
await expect(panel.getByRole("tab", { selected: true })).toHaveCount(1)
})
test("⌘W past the side panel's last tab keeps the session tab when focus leaves the panel just after", async ({
page,
}) => {
@@ -1577,10 +1608,12 @@ test("⌘W past the side panel's last tab keeps the session tab when focus leave
observer.observe(document, { subtree: true, attributes: true, attributeFilter: ["aria-hidden"] })
})
const sessions = await emptySidePanel(page)
await page.clock.install()
const sessions = await emptySidePanel(page, () => holdClock(page))
const composer = page.getByRole("textbox", { name: "Prompt", exact: true })
await expect(composer).toBeFocused()
await page.keyboard.press("ControlOrMeta+w")
await page.clock.resume()
// Only a swallowed press above leaves Beta for this one to land on.
await composer.click()
@@ -1600,6 +1633,7 @@ test("⌘W closes the session tab again once the window loses focus after the si
test("⌘W in the side panel closes its last New tab with the panel, and only then the session tab", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
await page.clock.install()
const alpha = { id: "ses_side_new_alpha", title: "Side new alpha" }
const beta = { id: "ses_side_new_beta", title: "Side new beta" }
await openSession(page, { name: "SideCloseNewTab", sessions: [alpha, beta] })
@@ -1618,6 +1652,7 @@ test("⌘W in the side panel closes its last New tab with the panel, and only th
await panel.getByRole("button", { name: /^Open file/ }).focus()
// The New tab was the panel's last tab, so closing it closes the panel too, and focus goes back.
await holdClock(page)
await page.keyboard.press("ControlOrMeta+w")
await expect(newTab).toHaveCount(0)
await expect(toggle).toHaveAttribute("aria-expanded", "false")
@@ -1626,6 +1661,7 @@ test("⌘W in the side panel closes its last New tab with the panel, and only th
// One press too many closes nothing rather than the session.
await page.keyboard.press("ControlOrMeta+w")
await expect(alphaTab).toHaveCount(1)
await page.clock.resume()
await expectPath(page, sessionHref(alpha.id))
// With no panel open, ⌘W from the composer closes the session tab.
@@ -1778,8 +1814,64 @@ test("⌘W in a focused Context tab closes it, then the panel, and keeps the ses
await expectPath(page, sessionHref(alpha.id))
})
test("with the side panel open, ⌘W closes its tabs from anywhere, ⌥⌘W the session tab, and ⌘⇧T undoes them newest first", async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 900 })
const directory = "C:/OpenCode/SideCloseAnywhere"
const alpha = { id: "ses_side_anywhere_alpha", title: "Side anywhere alpha" }
const beta = { id: "ses_side_anywhere_beta", title: "Side anywhere beta" }
await openSession(page, {
name: "SideCloseAnywhere",
sessions: [alpha, beta],
fileList: (path) => (path ? [] : ["README.md"].map((file) => fileNode(directory, file))),
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
seed: {
panes: { [alpha.id]: { review: true }, [beta.id]: { review: true } },
storage: reviewTabs(directory, alpha.id),
},
})
const panel = page.locator("#review-panel")
const fileTab = panel.getByRole("tab", { name: "README.md", exact: true })
const composer = page.getByRole("textbox", { name: "Prompt", exact: true })
const sessionTab = (id: string) => page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(id)}"])`)
// ⌥⌘W closes Beta's session tab although its side panel holds a tab that ⌘W would close.
await sessionTab(beta.id).locator("a").click()
await expectPath(page, sessionHref(beta.id))
await expect(panel.getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true")
await composer.click()
await page.keyboard.press("ControlOrMeta+Alt+w")
await expect(sessionTab(beta.id)).toHaveCount(0)
await expectPath(page, sessionHref(alpha.id))
await openFileLauncher(panel)
await panel.getByRole("treeitem", { name: "README.md", exact: true }).click()
await expect(fileTab).toHaveAttribute("aria-selected", "true")
// From the composer, ⌘W closes the side tab, not the session tab.
await composer.click()
await page.keyboard.press("ControlOrMeta+w")
await expect(fileTab).toHaveCount(0)
await expect(sessionTab(alpha.id)).toHaveCount(1)
await expectPath(page, sessionHref(alpha.id))
// The side tab closed after Beta, so it comes back first, then Beta.
await page.keyboard.press("ControlOrMeta+Shift+t")
await expect(fileTab).toHaveAttribute("aria-selected", "true")
await expect(sessionTab(beta.id)).toHaveCount(0)
await page.keyboard.press("ControlOrMeta+Shift+t")
await expect(sessionTab(beta.id)).toHaveCount(1)
await expectPath(page, sessionHref(beta.id))
})
// Stops the clock `page.clock.install()` set up, so the ⌘W guard's rest after the panel empties only moves when the
// test moves it, however slow the runner.
const holdClock = (page: Page) => page.evaluate(() => Date.now()).then((now) => page.clock.pauseAt(now + 1_000))
// Closes Alpha's side tabs with ⌘W until the side panel empties and collapses, as an overshooting hand would.
async function emptySidePanel(page: Page) {
async function emptySidePanel(page: Page, beforeLastClose?: () => Promise<void>) {
await page.setViewportSize({ width: 1440, height: 900 })
const directory = "C:/OpenCode/SideCloseOvershoot"
const alpha = { id: "ses_side_close_alpha", title: "Side close alpha" }
@@ -1806,6 +1898,7 @@ async function emptySidePanel(page: Page) {
await page.keyboard.press("ControlOrMeta+w")
await expect(fileTab).toHaveCount(0)
await expect(reviewTab).toHaveAttribute("aria-selected", "true")
await beforeLastClose?.()
await page.keyboard.press("ControlOrMeta+w")
await expect(panel).toHaveAttribute("aria-hidden", "true")
+1
View File
@@ -80,6 +80,7 @@ export const dict = {
"command.file.open": "Open file",
"command.tab.close": "Close tab",
"command.tab.reopenClosed": "Reopen closed tab",
"command.tab.closeSession": "Close session tab",
"command.context.addSelection": "Add selection to context",
"command.context.addSelection.description": "Add selected lines from the current file",
"command.input.focus": "Focus input",
@@ -3,6 +3,7 @@ import { createStore } from "solid-js/store"
import { createEventListener } from "@solid-primitives/event-listener"
import type { Panel, PanelProps, SessionRef } from "@opencode/plugin/gui"
import { adjacentTabKey } from "@/shell/titlebar/tab-order"
import type { SessionPane } from "@/shell/state/session-tabs"
/** The most closed tabs a session keeps. */
export const CLOSED_TABS_LIMIT = 30
@@ -20,6 +21,9 @@ export type ClosedSideTab = {
readonly detail?: string
/** What the panel's `restore` needs. */
readonly data?: string
/** The pane it showed in and its position in the strip, where it reopens. */
readonly pane?: SessionPane
readonly index?: number
/** When it closed, in milliseconds since the epoch. */
readonly closed: number
}
+10 -3
View File
@@ -48,6 +48,7 @@ type Tabs = Accessor<{
setActive(tab: string | undefined): void
close(tab: string): void
remap(rewrite: (tab: string) => string): void
target(pane: SessionPane, plugin?: string, index?: number): void
}>
export type RegionEntry = {
@@ -470,8 +471,10 @@ export function createRegion(input: {
const entry = byKey().get(key)
const last = stored().length === 1 && stored()[0] === key
const closed = entry && closedEntry(key, entry.provider, panelInput(input.view, input.screen, { tab: entry.tab }))
const index = stored().indexOf(key)
if (closed) input.closed.push(input.view(), closed)
if (closed)
input.closed.push(input.view(), { ...closed, pane: paneOfKey(key), index: index === -1 ? undefined : index })
// New tabs left in the strip keep the region open.
batch(() => {
input.tabs().close(key)
@@ -496,14 +499,18 @@ export function createRegion(input: {
return input.closed.list(input.view()).filter((entry) => !!entry.file && !open.has(entry.key))
}),
/** Brings back the closed tab under `key`, or the newest one. */
reopen(key?: string) {
/** When the tab `reopen()` brings back closed. */
lastClosedTime: () => input.closed.list(input.view())[0]?.closed,
/** Brings back the closed tab under `key`, or the newest one, where it closed or in `pane`. */
reopen(key?: string, pane?: SessionPane) {
const entry = input.closed.take(input.view(), key)
if (!entry) return
const plugin = entry.key.slice(0, entry.key.indexOf(":"))
const provider = providers().find((item) => item.plugin === plugin)?.value
if (!stored().includes(entry.key)) input.tabs().target(pane ?? entry.pane ?? "side", plugin, entry.index)
if (!provider?.restore) return input.open(entry.key)
provider.restore({
session: input.view(),
@@ -209,10 +209,7 @@ export function PaneTabs(props: {
get entries() {
return props.region.recent()
},
onReopen: (key: string) => {
target(key)
props.region.reopen(key)
},
onReopen: (key: string) => props.region.reopen(key, props.pane.id),
}
const modifier = closedTabsModifier()
@@ -229,6 +226,15 @@ export function PaneTabs(props: {
}),
)
const after = createMemo(() => {
const keys = props.pane.keys()
const index = keys.indexOf(tabMenu.key)
if (index === -1) return []
return keys.slice(index + 1).filter((key) => closable().includes(key))
})
// Without a new tab item, "+" opens a host-owned new tab view listing the launchers, as ⌘T does inside the region.
const current = createMemo(() => props.region.shownNewTab(props.pane.id))
const add = () => props.region.openNewTab(props.pane.id)
@@ -389,6 +395,9 @@ export function PaneTabs(props: {
>
{language.t("session.tab.closeOthers")}
</Menu.Item>
<Menu.Item disabled={after().length === 0} onSelect={() => after().forEach(props.region.close)}>
{language.t(language.direction() === "rtl" ? "common.closeTabsToLeft" : "common.closeTabsToRight")}
</Menu.Item>
</Menu.Content>
</Menu.Portal>
</Menu>
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test"
import {
CLOSE_TAB_GUARD_QUIET_MS,
SESSION_DIALOG_LOAD_TIMEOUT_MS,
createCloseTabGuardState,
createSessionCommandsState,
@@ -194,7 +195,7 @@ describe("transitionCloseTabGuard", () => {
])
expect(armed?.state).toEqual({ status: "armed", attempt: 1, tabKey: "alpha", settling: true })
expect(armed?.effects).toEqual([{ type: "settle.schedule", attempt: 1 }])
expect(armed?.effects).toEqual([{ type: "settle.schedule", attempt: 1 }, { type: "quiet.schedule", attempt: 1, timeoutMs: CLOSE_TAB_GUARD_QUIET_MS }])
expect(focused?.state).toBe(armed!.state)
expect(selectCloseTabSwallowed(focused!.state)).toBe(true)
expect(settled?.state).toEqual({ status: "armed", attempt: 1, tabKey: "alpha", settling: false })
@@ -211,7 +212,7 @@ describe("transitionCloseTabGuard", () => {
expect(synced?.state).toBe(armed!.state)
expect(otherTab?.state).toEqual({ status: "disarmed", issued: 1 })
expect(otherTab?.effects).toEqual([{ type: "settle.cancel" }])
expect(otherTab?.effects).toEqual([{ type: "settle.cancel" }, { type: "quiet.cancel" }])
})
test("the panel reopening disarms the guard", () => {
@@ -229,12 +230,12 @@ describe("transitionCloseTabGuard", () => {
const [, , settled] = replayGuard([closedPanel, { type: "settle.completed", attempt: 1 }, event])
expect(settling?.state).toEqual({ status: "disarmed", issued: 1 })
expect(settling?.effects).toEqual([{ type: "settle.cancel" }])
expect(settling?.effects).toEqual([{ type: "settle.cancel" }, { type: "quiet.cancel" }])
expect(settled?.state).toEqual({ status: "disarmed", issued: 1 })
expect(settled?.effects).toEqual([])
expect(settled?.effects).toEqual([{ type: "quiet.cancel" }])
})
test("modifier keys and repeated ⌘W keep swallowing", () => {
test("modifier keys and repeated ⌘W keep swallowing, each ⌘W restarting the rest", () => {
const [armed, modifier, close] = replayGuard([
closedPanel,
{ type: "key.down", key: "Meta", matchesClose: false },
@@ -242,7 +243,22 @@ describe("transitionCloseTabGuard", () => {
])
expect(modifier?.state).toBe(armed!.state)
expect(modifier?.effects).toEqual([])
expect(close?.state).toBe(armed!.state)
expect(close?.effects).toEqual([{ type: "quiet.schedule", attempt: 1, timeoutMs: CLOSE_TAB_GUARD_QUIET_MS }])
})
test("once ⌘W rests, the next ⌘W closes the session tab again", () => {
const [, , stale, rested] = replayGuard([
closedPanel,
{ type: "key.down", key: "w", matchesClose: true },
{ type: "quiet.elapsed", attempt: 0 },
{ type: "quiet.elapsed", attempt: 1 },
])
expect(selectCloseTabSwallowed(stale!.state)).toBe(true)
expect(rested?.state).toEqual({ status: "disarmed", issued: 1 })
expect(selectCloseTabSwallowed(rested!.state)).toBe(false)
})
test("a close from the palette, or one that leaves the panel open, does not arm", () => {
@@ -255,7 +271,11 @@ describe("transitionCloseTabGuard", () => {
test("re-arming fences the previous frame, and a stale settle is dropped", () => {
const [, rearmed, stale] = replayGuard([closedPanel, closedPanel, { type: "settle.completed", attempt: 1 }])
expect(rearmed?.effects).toEqual([{ type: "settle.cancel" }, { type: "settle.schedule", attempt: 2 }])
expect(rearmed?.effects).toEqual([
{ type: "settle.cancel" },
{ type: "settle.schedule", attempt: 2 },
{ type: "quiet.schedule", attempt: 2, timeoutMs: CLOSE_TAB_GUARD_QUIET_MS },
])
expect(stale?.state).toBe(rearmed!.state)
})
@@ -269,6 +289,7 @@ describe("transitionCloseTabGuard", () => {
{ type: "key.down", key: "a", matchesClose: false },
{ type: "layout.synced", tabKey: "beta", sideOpened: true },
{ type: "settle.completed", attempt: 1 },
{ type: "quiet.elapsed", attempt: 1 },
]
events.forEach((event) => expect(transitionCloseTabGuard(disarmed, event).state).toBe(disarmed))
@@ -277,7 +298,7 @@ describe("transitionCloseTabGuard", () => {
test("disposing cancels a pending frame and ignores everything after", () => {
const [, disposed, late] = replayGuard([closedPanel, { type: "disposed" }, closedPanel])
expect(disposed?.effects).toEqual([{ type: "settle.cancel" }])
expect(disposed?.effects).toEqual([{ type: "settle.cancel" }, { type: "quiet.cancel" }])
expect(late?.state).toBe(disposed!.state)
expect(late?.effects).toEqual([])
})
+29 -7
View File
@@ -133,10 +133,15 @@ export function transitionSessionCommands(
// --- ⌘W after the side panel empties ---
// How long ⌘W must rest after the side panel closes before it closes the session tab.
export const CLOSE_TAB_GUARD_QUIET_MS = 500
/**
* ⌘W on the side panel's last tab closes the panel; one press too many would then close the session tab. While armed,
* ⌘W closes nothing, until the user moves on by clicking, focusing elsewhere, pressing another key, leaving the window,
* or switching session. `settling` covers the frame after arming, in which closing the panel may still move focus.
* ⌘W closes nothing, until ⌘W rests for `CLOSE_TAB_GUARD_QUIET_MS` or the user moves on by clicking, focusing
* elsewhere, pressing another key, leaving the window, or switching session. Each swallowed ⌘W restarts the rest, so
* mashing or holding it never reaches the session tab. `settling` covers the frame after arming, in which closing the
* panel may still move focus.
*/
export type CloseTabGuardState =
| { readonly status: "disarmed"; readonly issued: number }
@@ -156,6 +161,7 @@ export type CloseTabGuardEvent =
readonly sideOpened: boolean
}
| { readonly type: "settle.completed"; readonly attempt: number }
| { readonly type: "quiet.elapsed"; readonly attempt: number }
| { readonly type: "pointer.down" }
| { readonly type: "focus.in" }
| { readonly type: "window.blur" }
@@ -166,6 +172,8 @@ export type CloseTabGuardEvent =
export type CloseTabGuardEffect =
| { readonly type: "settle.schedule"; readonly attempt: number }
| { readonly type: "settle.cancel" }
| { readonly type: "quiet.schedule"; readonly attempt: number; readonly timeoutMs: number }
| { readonly type: "quiet.cancel" }
export type CloseTabGuardTransition = {
readonly state: CloseTabGuardState
@@ -183,7 +191,7 @@ const NO_GUARD_EFFECTS: readonly CloseTabGuardEffect[] = []
export function transitionCloseTabGuard(state: CloseTabGuardState, event: CloseTabGuardEvent): CloseTabGuardTransition {
if (state.status === "disposed") return { state, effects: NO_GUARD_EFFECTS }
if (event.type === "disposed") return { state: { status: "disposed" }, effects: settleCancel(state) }
if (event.type === "disposed") return { state: { status: "disposed" }, effects: cancelTimers(state) }
if (event.type === "close.completed") {
if (event.keybind && !event.sideOpened) {
@@ -191,7 +199,7 @@ export function transitionCloseTabGuard(state: CloseTabGuardState, event: CloseT
return {
state: { status: "armed", attempt, tabKey: event.tabKey, settling: true },
effects: [...settleCancel(state), { type: "settle.schedule", attempt }],
effects: [...settleCancel(state), { type: "settle.schedule", attempt }, quietSchedule(attempt)],
}
}
@@ -210,10 +218,16 @@ export function transitionCloseTabGuard(state: CloseTabGuardState, event: CloseT
// Focus the panel's own close moves, in this frame, is not the user moving on.
if (event.type === "focus.in" && state.settling) return { state, effects: NO_GUARD_EFFECTS }
if (event.type === "key.down" && (MODIFIER_KEYS.has(event.key) || event.matchesClose)) {
return { state, effects: NO_GUARD_EFFECTS }
if (event.type === "quiet.elapsed") {
if (event.attempt !== state.attempt) return { state, effects: NO_GUARD_EFFECTS }
return disarm(state)
}
if (event.type === "key.down" && event.matchesClose) return { state, effects: [quietSchedule(state.attempt)] }
if (event.type === "key.down" && MODIFIER_KEYS.has(event.key)) return { state, effects: NO_GUARD_EFFECTS }
// The panel closing is what armed the guard; only another session or the panel reopening moves on.
if (event.type === "layout.synced" && event.tabKey === state.tabKey && !event.sideOpened) {
return { state, effects: NO_GUARD_EFFECTS }
@@ -230,7 +244,15 @@ export function selectCloseTabSwallowed(state: CloseTabGuardState) {
function disarm(state: Exclude<CloseTabGuardState, { status: "disposed" }>): CloseTabGuardTransition {
if (state.status === "disarmed") return { state, effects: NO_GUARD_EFFECTS }
return { state: { status: "disarmed", issued: state.attempt }, effects: settleCancel(state) }
return { state: { status: "disarmed", issued: state.attempt }, effects: cancelTimers(state) }
}
function quietSchedule(attempt: number): CloseTabGuardEffect {
return { type: "quiet.schedule", attempt, timeoutMs: CLOSE_TAB_GUARD_QUIET_MS }
}
function cancelTimers(state: CloseTabGuardState): CloseTabGuardEffect[] {
return state.status === "armed" ? [...settleCancel(state), { type: "quiet.cancel" }] : []
}
function settleCancel(state: CloseTabGuardState): CloseTabGuardEffect[] {
@@ -19,6 +19,7 @@ import type { SessionRevert } from "@/session/revert"
import { usePluginClaims, usePluginScoped } from "@/runtime/plugin/commands"
import type { Region } from "@/runtime/plugin/panels"
import { sideTabShortcuts } from "@/runtime/plugin/closed-tabs"
import { useTabs } from "@/shell/tabs/tabs"
import {
createCloseTabGuardState,
createSessionCommandsState,
@@ -99,6 +100,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const exporter = useSessionExporter()
const pluginScoped = usePluginScoped()
const pluginClaims = usePluginClaims()
const tabs = useTabs()
// The file the selected side tab shows; other tabs have no line selection.
const activeFile = () => actions.region.selected()?.tab.file
@@ -113,18 +115,44 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
}
const inSide = actions.region.focus
// ⌘T and ⌘W inside the side region open and close its tabs, unless the focused panel binds the key itself there.
// ⌘T inside the side region opens one of its tabs, unless the focused panel binds the key itself there.
const sideKey = (event: KeyboardEvent) => inSide(event) && !pluginClaims(event)
// As in a browser, ⌘⇧T reopens whichever tab closed last, side or session.
const reopensSideTab = () => {
const side = actions.region.lastClosedTime()
if (side === undefined) return false
const session = tabs.lastClosedTime()
return session === undefined || side >= session
}
// ⌘W on the side panel's last tab, or on a panel with nothing left to close, closes the panel and moves focus out of
// it, where one press too many would close the session tab; the guard swallows that press.
const [closeGuard, setCloseGuard] = createSignal(createCloseTabGuardState())
let settleFrame: number | undefined
let quietTimer: ReturnType<typeof setTimeout> | undefined
const dispatchCloseGuard = (event: CloseTabGuardEvent) => {
const next = transitionCloseTabGuard(closeGuard(), event)
if (next.state !== closeGuard()) setCloseGuard(next.state)
next.effects.forEach((effect) => {
if (effect.type === "quiet.schedule" || effect.type === "quiet.cancel") {
clearTimeout(quietTimer)
quietTimer = undefined
if (effect.type === "quiet.cancel") return
const attempt = effect.attempt
quietTimer = setTimeout(() => {
quietTimer = undefined
dispatchCloseGuard({ type: "quiet.elapsed", attempt })
}, effect.timeoutMs)
return
}
if (settleFrame !== undefined) cancelAnimationFrame(settleFrame)
settleFrame = undefined
@@ -526,7 +554,8 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
keybind: "mod+w",
follows: "tab.close",
hidden: !tab,
when: (event) => (side ? sideKey(event) : selectCloseTabSwallowed(closeGuard())),
// While the side region is open, ⌘W closes its tabs wherever focus is.
when: (event) => (side ? !pluginClaims(event) : selectCloseTabSwallowed(closeGuard())),
onSelect: (source) => {
if (!side) return
closeTab()
@@ -547,13 +576,12 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
when: sideKey,
onSelect: openSideTab,
}),
// As in a browser: in the side panel, ⌘⇧T reopens a side tab rather than a session tab.
fileCommand({
id: "file.tab.reopen",
title: "",
keybind: settings.keybinds.get("tab.reopenClosed") ?? "mod+shift+t",
hidden: true,
when: inSide,
when: (event) => reopensSideTab() && !pluginClaims(event),
onSelect: () => actions.region.reopen(),
}),
cycle &&
+11 -2
View File
@@ -39,7 +39,13 @@ export type LayoutIntentEvent =
| { readonly type: "navigation.taken"; readonly attempt: number }
| { readonly type: "route.synced"; readonly route: LayoutRoute }
| { readonly type: "navigation.expired"; readonly attempt: number }
| { readonly type: "pane.targeted"; readonly session: string; readonly pane: SessionPane; readonly plugin?: string }
| {
readonly type: "pane.targeted"
readonly session: string
readonly pane: SessionPane
readonly plugin?: string
readonly index?: number
}
| { readonly type: "pane.consumed"; readonly session: string; readonly attempt: number }
| { readonly type: "pane.expired"; readonly session: string; readonly attempt: number }
| { readonly type: "sessions.pruned"; readonly keys: readonly string[] }
@@ -143,7 +149,10 @@ export function transitionLayoutIntent(state: LayoutIntentState, event: LayoutIn
state: {
...state,
nextAttempt: attempt + 1,
paneTargets: { ...state.paneTargets, [event.session]: { attempt, pane: event.pane, plugin: event.plugin } },
paneTargets: {
...state.paneTargets,
[event.session]: { attempt, pane: event.pane, plugin: event.plugin, index: event.index },
},
},
effects: [{ type: "pane-timer.start", session: event.session, attempt, timeoutMs: PANE_TARGET_TTL_MS }],
}
+8 -3
View File
@@ -133,6 +133,8 @@ const closedTabSchema = Schema.Struct({
file: Schema.optional(Schema.String),
detail: Schema.optional(Schema.String),
data: Schema.optional(Schema.String),
pane: Schema.optional(Schema.Literals(["side", "split", "bottom"])),
index: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
closed: Schema.Finite,
})
@@ -767,9 +769,12 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
if (!current?.all.includes(tab)) return
writeTabs(session, moveSessionTab(current, tab, pane, before))
},
/** Opens the next new tab a pane's "+" menu creates in `pane`; with `plugin`, only that plugin's tab. */
target(pane: SessionPane, plugin?: string) {
dispatchIntent({ type: "pane.targeted", session: key(), pane, plugin })
/**
* Opens the next new tab a pane's "+" menu creates in `pane`; with `plugin`, only that plugin's tab, and with
* `index`, at that position in the strip.
*/
target(pane: SessionPane, plugin?: string, index?: number) {
dispatchIntent({ type: "pane.targeted", session: key(), pane, plugin, index })
},
}
},
@@ -146,6 +146,22 @@ test.each<{ name: string; run: () => SessionTabs; expected: SessionTabs }>([
placeSessionTabs({ all: [A], active: A }, { all: [A, T1], active: T1 }, { pane: "bottom", plugin: "terminal" }),
expected: { all: [A, T1], active: T1, panes: { [T1]: "bottom" }, selected: { side: A, bottom: T1 } },
},
{
name: "a reopened tab's target puts it back where it closed",
run: () =>
placeSessionTabs(
{ all: [A, T1], active: A },
{ all: [A, T1, B], active: B },
{ pane: "side", plugin: "file", index: 1 },
),
expected: { all: [A, B, T1], active: B, selected: { side: B } },
},
{
name: "a reopened tab past the strip's end lands last",
run: () =>
placeSessionTabs({ all: [A], active: A }, { all: [A, B], active: B }, { pane: "side", plugin: "file", index: 5 }),
expected: { all: [A, B], active: B, selected: { side: B } },
},
])("$name", ({ run, expected }) => {
expect(run()).toEqual(expected)
})
+17 -3
View File
@@ -17,8 +17,11 @@ export type SessionTabState = {
preview?: string
}
/** Where a pane's "+" menu asked its next new tab to open; with `plugin`, only that plugin's tab. */
export type SessionPaneTarget = { readonly pane: SessionPane; readonly plugin?: string }
/**
* Where a pane's "+" menu asked its next new tab to open; with `plugin`, only that plugin's tab. With `index`, the tab
* lands at that position in the strip, as a reopened tab returns where it closed.
*/
export type SessionPaneTarget = { readonly pane: SessionPane; readonly plugin?: string; readonly index?: number }
export const sessionTabPane = (tabs: SessionTabs, tab: string): SessionPane => tabs.panes?.[tab] ?? "side"
@@ -87,13 +90,24 @@ export function placeSessionTabs(previous: SessionTabs, next: SessionTabs, targe
)
return {
all: next.all,
all: landAt(next.all, kept, target),
active: next.active,
panes: Object.keys(panes).length > 0 ? panes : undefined,
selected: Object.keys(selected).length > 0 ? selected : undefined,
}
}
// Moves the new tab `target` asked for to the target's index.
function landAt(all: string[], kept: ReadonlySet<string>, target: SessionPaneTarget | undefined) {
if (target?.index === undefined) return all
const landed = all.find((tab) => !kept.has(tab) && paneTargetMatches(target, tab))
if (landed === undefined) return all
const rest = all.filter((tab) => tab !== landed)
return [...rest.slice(0, target.index), landed, ...rest.slice(target.index)]
}
/**
* Moves `tab` into `pane` and selects it: before `before`, at the pane's start when `before` is a tab the strip does
* not store (a pinned one), or at the pane's end without `before`.
+8 -1
View File
@@ -10,7 +10,7 @@ const CLOSED_TAB_LIMIT = 100
export function pushClosedTab(stack: ClosedTab[], tab: Tab, index: number, info?: TabInfo): ClosedTab[] {
if (tab.type !== "session") return stack
const entry: ClosedTab = { tab: { ...tab }, index }
const entry: ClosedTab = { tab: { ...tab }, index, closed: Date.now() }
if (info) entry.info = { ...info }
@@ -55,6 +55,13 @@ export function takeClosedTab(stack: ClosedTab[], tabs: Tab[], target?: SessionT
return { stack: remaining }
}
// When the tab takeClosedTab would pop closed; tabs closed before times were recorded count as oldest.
export function latestClosedTime(stack: ClosedTab[], tabs: Tab[]) {
const entry = stack.findLast((item) => !isOpen(tabs, item.tab))
return entry ? (entry.closed ?? 0) : undefined
}
export function removeClosedTabs(stack: ClosedTab[], server: SessionTab["server"], sessionIDs: string[]) {
const removed = new Set(sessionIDs)
+1
View File
@@ -65,6 +65,7 @@ export const ClosedTab = Persistence.struct({
tab: SessionCodec,
index: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
info: Persistence.optional(Info),
closed: Persistence.optional(Schema.Finite),
})
export const Closed = Persistence.array(ClosedTab)
+26 -4
View File
@@ -1,7 +1,8 @@
import { describe, expect, test } from "bun:test"
import { afterEach, describe, expect, setSystemTime, test } from "bun:test"
import { createRoot, getOwner, onCleanup } from "solid-js"
import { createTabMemory } from "./memory"
import {
latestClosedTime,
listClosedTabs,
nextTabAfterClose,
pushClosedTab,
@@ -180,7 +181,11 @@ describe("tab memory", () => {
})
describe("closed tab stack", () => {
test("records session tabs with their index", () => {
afterEach(() => setSystemTime())
test("records session tabs with their index and close time", () => {
setSystemTime(1_000)
const stack = pushClosedTab([], sessionTab("a"), 2, {
title: "Alpha",
directory: "/project",
@@ -188,10 +193,25 @@ describe("closed tab stack", () => {
})
expect(stack).toEqual([
{ tab: sessionTab("a"), index: 2, info: { title: "Alpha", directory: "/project", prompted: true } },
{
tab: sessionTab("a"),
index: 2,
info: { title: "Alpha", directory: "/project", prompted: true },
closed: 1_000,
},
])
})
test("reports when the tab a reopen would take closed, counting untimed closes as oldest", () => {
setSystemTime(2_000)
const stack = pushClosedTab([{ tab: sessionTab("a"), index: 0 }], sessionTab("b"), 1)
expect(latestClosedTime(stack, [])).toBe(2_000)
expect(latestClosedTime(stack, [sessionTab("b")])).toBe(0)
expect(latestClosedTime(stack, [sessionTab("a"), sessionTab("b")])).toBeUndefined()
})
test("ignores draft tabs", () => {
const draft: Tab = { type: "draft", draftID: "d1", server, directory: "/tmp" }
@@ -210,6 +230,8 @@ describe("closed tab stack", () => {
})
test("keeps only the newest close record for a session", () => {
setSystemTime(3_000)
const stack = pushClosedTab(
pushClosedTab([], sessionTab("a"), 1, { title: "Old", directory: "/old", prompted: true }),
sessionTab("a"),
@@ -218,7 +240,7 @@ describe("closed tab stack", () => {
)
expect(stack).toEqual([
{ tab: sessionTab("a"), index: 3, info: { title: "New", directory: "/new", prompted: true } },
{ tab: sessionTab("a"), index: 3, info: { title: "New", directory: "/new", prompted: true }, closed: 3_000 },
])
})
+9 -1
View File
@@ -14,7 +14,14 @@ import { SessionTabsRemovedDetail } from "@/shell/titlebar/session-events"
import { sessionHref } from "@/shell/routes/session"
import { createTabMemory } from "./memory"
import { createSessionPreview } from "./preview"
import { nextTabAfterClose, pushClosedTab, removeClosedTabs, takeClosedTab, type ClosedTab } from "./closed"
import {
latestClosedTime,
nextTabAfterClose,
pushClosedTab,
removeClosedTabs,
takeClosedTab,
type ClosedTab,
} from "./closed"
import {
createDraftComposerState,
createMemoryComposerState,
@@ -638,6 +645,7 @@ export const { use: useTabs, provider: TabsProvider } = createSimpleContext({
})
entries.forEach((entry) => disposeTab(entry.tab))
},
lastClosedTime: () => latestClosedTime(closed, store),
reopenClosedTab(target?: SessionTab, options?: { append?: boolean }) {
dispatchHydration({ type: "closed.op", op: { kind: "reopen", target, options } })
},
+18 -9
View File
@@ -442,6 +442,16 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
command.register("tabs", () => {
const current = currentTab()
const closeCurrent = () => {
if (current === tabs.preview()) {
tabs.closePreview()
return
}
tabsStoreActions.closeTab(tabsStore.findIndex((tab) => current === tab))
}
return [
{
...newTabCommand,
@@ -456,15 +466,14 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
title: language.t("command.tab.close"),
keybind: "mod+w",
hidden: true,
onSelect: () => {
if (current === tabs.preview()) {
tabs.closePreview()
return
}
tabsStoreActions.closeTab(tabsStore.findIndex((tab) => current === tab))
},
onSelect: closeCurrent,
},
current && {
id: "tab.closeSession",
category: "tab",
title: language.t("command.tab.closeSession"),
keybind: "mod+alt+w",
onSelect: closeCurrent,
},
{
id: "tab.reopenClosed",
@@ -654,6 +654,8 @@ type StripTabs = {
setActive(tab: string | undefined): void
close(tab: string): void
remap(rewrite: (tab: string) => string): void
/** Where the next new tab lands; the fixture keeps every tab in the side pane, in open order. */
target(pane: "side" | "split" | "bottom", plugin?: string, index?: number): void
}
type PaneClient = IpcClient<(typeof BrowserPane)["spec"]>
@@ -1093,6 +1095,7 @@ export function mountBrowserRegion(input: RegionHost) {
if (next.length !== all.length || next.some((key, index) => key !== all[index])) setAll(view().key, next)
},
target() {},
}),
side: () => ({ opened: () => store.opened, toggle: () => setStore("opened", (opened) => !opened) }),
})