feat(tui): show recently closed tabs in new session menu

This commit is contained in:
Kit Langton
2026-09-29 03:35:31 -07:00
committed by GitHub
Unverified
parent b29dab3231
commit 7ef4a1a56e
6 changed files with 138 additions and 27 deletions
+37 -13
View File
@@ -43,6 +43,7 @@ import { TabPulse, unreadGlowIntensity } from "./tab-pulse"
import { tint } from "../theme/color"
import { SESSION_SIDEBAR_WIDTH, SESSION_TABS_COMPACT_BREAKPOINT } from "../ui/layout"
import { projectName } from "../util/project"
import { stringWidth } from "../util/string-width"
import { marqueeCycleWidth, marqueeOverflows, marqueeTextParts } from "../util/marquee"
import { useDialog } from "../ui/dialog"
import { useToast } from "../ui/toast"
@@ -112,6 +113,8 @@ export const EMPTY_SESSION_TAB_STATUS: SessionTabsStatus = {
export type SessionTabsController = Pick<ContextController, "tabs" | "current" | "select" | "close" | "move"> & {
newTab?: () => boolean
add?: () => void
recentlyClosed?: ContextController["recentlyClosed"]
reopen?: ContextController["reopen"]
detail?: (sessionID: string) => string | undefined
rename?: (sessionID: string) => void
search?: () => void
@@ -379,11 +382,12 @@ function TabContextMenu(props: { state: TabContextMenuState; tabs: SessionTabsCo
mode: "menu",
commands: [{ bind: "escape,ctrl+c", title: "Close tab menu", group: "Tabs", run: props.onClose }],
}))
const actions = createMemo(() => {
const actions = createMemo<Array<{ title: string; run?: () => void }>>(() => {
const sessionID = props.state.sessionID
const title = props.state.title
const closed = (props.tabs.recentlyClosed?.() ?? []).slice(0, 10)
return [
...(props.tabs.add ? [{ title: "New tab", run: () => props.tabs.add?.() }] : []),
...(sessionID && props.tabs.add ? [{ title: NEW_SESSION_TAB_TITLE, run: () => props.tabs.add?.() }] : []),
...(sessionID
? [
{
@@ -402,15 +406,32 @@ function TabContextMenu(props: { state: TabContextMenuState; tabs: SessionTabsCo
{ title: "Close", run: () => props.tabs.close(sessionID) },
]
: []),
...(!sessionID && props.tabs.reopen
? [
{ title: "Recently closed tabs" },
...closed.map((tab) => ({
title: tab.title || "Untitled session",
run: () => props.tabs.reopen?.(tab.sessionID),
})),
...(closed.length === 0 ? [{ title: "No recently closed tabs" }] : []),
]
: []),
]
})
const [selected, setSelected] = createSignal<number>()
const top = () => Math.max(0, Math.min(props.state.y + 1, dimensions().height - actions().length))
const left = () => Math.max(0, Math.min(props.state.x, dimensions().width - CONTEXT_MENU_WIDTH))
const width = () =>
Math.min(
dimensions().width,
Math.max(CONTEXT_MENU_WIDTH, ...actions().map((action) => Math.min(50, stringWidth(action.title) + 2))),
)
const height = () => Math.min(actions().length, dimensions().height)
const top = () => Math.max(0, Math.min(props.state.y + 1, dimensions().height - height()))
const left = () => Math.max(0, Math.min(props.state.x, dimensions().width - width()))
const run = (index: number) => {
const action = actions()[index]
if (!action?.run) return
props.onClose()
action?.run()
action.run()
}
return (
@@ -437,13 +458,14 @@ function TabContextMenu(props: { state: TabContextMenuState; tabs: SessionTabsCo
event.stopPropagation()
}}
>
<box
<scrollbox
position="absolute"
left={left()}
top={top()}
height={actions().length}
width={CONTEXT_MENU_WIDTH}
flexDirection="column"
height={height()}
width={width()}
scrollX={false}
scrollbarOptions={{ visible: false }}
backgroundColor={background()}
onMouseDown={(event) => {
if (event.button === RIGHT_MOUSE_BUTTON) props.onClose()
@@ -457,8 +479,10 @@ function TabContextMenu(props: { state: TabContextMenuState; tabs: SessionTabsCo
width="100%"
paddingLeft={1}
paddingRight={1}
backgroundColor={selected() === index() ? actionHovered() : undefined}
onMouseOver={() => setSelected(index())}
height={1}
flexShrink={0}
backgroundColor={action.run && selected() === index() ? actionHovered() : undefined}
onMouseOver={() => setSelected(action.run ? index() : undefined)}
onMouseOut={() => setSelected(undefined)}
onMouseUp={(event) => {
event.preventDefault()
@@ -467,13 +491,13 @@ function TabContextMenu(props: { state: TabContextMenuState; tabs: SessionTabsCo
run(index())
}}
>
<text fg={theme.text.base} selectable={false}>
<text fg={action.run ? theme.text.base : theme.text.muted} selectable={false} truncate>
{action.title}
</text>
</box>
)}
</For>
</box>
</scrollbox>
</box>
</Portal>
)
@@ -59,7 +59,7 @@ export type ClosedSessionTab = {
index: number
}
const CLOSED_SESSION_TAB_LIMIT = 10
const CLOSED_SESSION_TAB_LIMIT = 25
export function recordClosedSessionTab(
stack: readonly ClosedSessionTab[],
@@ -74,11 +74,14 @@ export function recordClosedSessionTab(
/**
* Pop the most recently closed tab that is not already open and restore it at its original
* position. Entries for already-open sessions are consumed so repeated reopens walk the stack.
* Selecting a session removes only its entry, preserving the rest of the closed history.
*/
export function reopenSessionTab(stack: readonly ClosedSessionTab[], tabs: readonly SessionTab[]) {
export function reopenSessionTab(stack: readonly ClosedSessionTab[], tabs: readonly SessionTab[], sessionID?: string) {
const remaining = [...stack]
while (remaining.length > 0) {
const entry = remaining.pop()!
const index = sessionID ? remaining.findIndex((entry) => entry.tab.sessionID === sessionID) : remaining.length - 1
if (index === -1) break
const [entry] = remaining.splice(index, 1)
if (tabs.some((tab) => tab.sessionID === entry.tab.sessionID)) continue
const next = [...tabs]
next.splice(Math.min(entry.index, tabs.length), 0, entry.tab)
+15 -6
View File
@@ -80,7 +80,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
const [promptPulses, setPromptPulses] = createSignal<Record<string, number>>({})
let history: SessionTabHistory = { entries: [], index: -1 }
// User-closed tabs eligible for reopening; in-memory like history, deleted sessions pruned.
let closedTabs: ClosedSessionTab[] = []
const [closedTabs, setClosedTabs] = createSignal<ClosedSessionTab[]>([])
// Storage mutations apply against the on-disk draft under a file lock, so
// a registration queued by the route effect can land AFTER a removal that
// ran while the write was still in flight — resurrecting a tab that was
@@ -317,7 +317,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
onCleanup(
event.on("session.deleted", (evt) => {
const target = root(evt.data.sessionID)
closedTabs = closedTabs.filter((entry) => entry.tab.sessionID !== target)
setClosedTabs((entries) => entries.filter((entry) => entry.tab.sessionID !== target))
remove(evt.data.sessionID, enabled())
}),
)
@@ -354,6 +354,15 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
tabs() {
return state().tabs
},
recentlyClosed() {
return closedTabs()
.filter((entry) => !state().tabs.some((tab) => tab.sessionID === entry.tab.sessionID))
.toReversed()
.map((entry) => ({
...entry.tab,
title: data.session.get(entry.tab.sessionID)?.title ?? entry.tab.title,
}))
},
newTab() {
return newTab()
},
@@ -420,13 +429,13 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
}
const index = state().tabs.findIndex((tab) => tab.sessionID === target)
const tab = state().tabs[index]
if (tab) closedTabs = recordClosedSessionTab(closedTabs, tab, index)
if (tab) setClosedTabs((entries) => recordClosedSessionTab(entries, tab, index))
remove(target, true)
},
reopen() {
reopen(sessionID?: string) {
if (!enabled()) return
const result = reopenSessionTab(closedTabs, state().tabs)
closedTabs = result.stack
const result = reopenSessionTab(closedTabs(), state().tabs, sessionID)
setClosedTabs(result.stack)
const tabs = result.tabs
if (!tabs || !result.sessionID) return
cancelledTabs.delete(result.sessionID)
@@ -35,6 +35,11 @@ for (const orientation of ["horizontal", "vertical"] as const) {
const [newTab, setNewTab] = createSignal(false)
const settings: Info = { tabs: { mode: "on" } }
const copied: string[] = []
const reopened: string[] = []
const [closed, setClosed] = createSignal([
{ sessionID: "closed-new", title: "Most recently closed" },
{ sessionID: "closed-old", title: "Earlier session" },
])
let config!: ReturnType<typeof useConfig>
let theme!: ReturnType<typeof useTheme>
function Colors() {
@@ -57,6 +62,12 @@ for (const orientation of ["horizontal", "vertical"] as const) {
},
close() {},
move() {},
add() {},
recentlyClosed: closed,
reopen(sessionID?: string) {
if (sessionID) reopened.push(sessionID)
setClosed((tabs) => tabs.filter((tab) => tab.sessionID !== sessionID))
},
detail: () => "project",
status: (sessionID: string) => (sessionID === "first" ? status() : EMPTY_SESSION_TAB_STATUS),
} satisfies SessionTabsController
@@ -205,17 +216,45 @@ for (const orientation of ["horizontal", "vertical"] as const) {
const column = rows[row]!.indexOf("First")
await app.mockMouse.click(column, row, MouseButton.RIGHT)
await app.waitForFrame((frame) => frame.includes("Rename"))
expect(app.captureCharFrame().split("\n")[row + 1]!.indexOf("Rename")).toBe(column + 1)
expect(app.captureCharFrame().split("\n")[row + 2]!.indexOf("Rename")).toBe(column + 1)
expect(app.captureCharFrame()).toContain("Copy session ID")
expect(app.captureCharFrame()).toContain("Close")
expect(app.captureCharFrame()).not.toContain("Keep open")
expect(active()).toBe("second")
await app.mockMouse.click(column + 1, row + 2)
await app.mockMouse.click(column + 1, row + 3)
expect(copied).toEqual(["first"])
await app.waitForFrame((frame) => !frame.includes("Rename"))
setNewTab(true)
await app.waitForFrame((frame) => frame.includes("+ New session"))
for (const width of [60, 35]) {
app.renderer.resize(width, 10)
await app.renderOnce()
const rows = app.captureCharFrame().split("\n")
const row = rows.findIndex((line) => line.includes("+ New session"))
await app.mockMouse.click(rows[row]!.indexOf("+ New session") + 2, row, MouseButton.RIGHT)
await app.waitForFrame((frame) => frame.includes("Recently closed tabs"))
expect(app.captureCharFrame()).not.toContain("New tab")
const menu = app.captureCharFrame().split("\n")
expect(menu.some((line) => line.trim() === "New session")).toBe(false)
const earlier = menu.findIndex((line) => line.includes("Earlier session"))
expect(earlier).toBeGreaterThan(menu.findIndex((line) => line.includes("Most recently closed")))
await app.mockMouse.click(menu[earlier]!.indexOf("Earlier session"), earlier)
expect(reopened.at(-1)).toBe("closed-old")
await app.waitForFrame((frame) => !frame.includes("Recently closed tabs"))
setClosed([
{ sessionID: "closed-new", title: "Most recently closed" },
{ sessionID: "closed-old", title: "Earlier session" },
])
}
app.renderer.resize(60, 20)
setClosed(Array.from({ length: 11 }, (_, index) => ({ sessionID: `closed-${index}`, title: `History ${index + 1}` })))
await app.renderOnce()
const historyRows = app.captureCharFrame().split("\n")
const newRow = historyRows.findIndex((line) => line.includes("+ New session"))
await app.mockMouse.click(historyRows[newRow]!.indexOf("+ New session") + 2, newRow, MouseButton.RIGHT)
await app.waitForFrame((frame) => frame.includes("History 10"))
expect(app.captureCharFrame()).not.toContain("History 11")
} finally {
app.renderer.destroy()
}
@@ -201,6 +201,20 @@ describe("session tabs", () => {
expect(reopenSessionTab([], tabs)).toEqual({ stack: [], tabs: undefined, sessionID: undefined })
})
test("reopens a selected closed tab without consuming newer entries", () => {
const stack = recordClosedSessionTab(recordClosedSessionTab([], { sessionID: "b" }, 1), { sessionID: "c" }, 2)
const result = reopenSessionTab(stack, [{ sessionID: "a" }], "b")
expect(result.sessionID).toBe("b")
expect(result.tabs).toEqual([{ sessionID: "a" }, { sessionID: "b" }])
expect(result.stack).toEqual([{ tab: { sessionID: "c" }, index: 2 }])
expect(reopenSessionTab(stack, [], "missing")).toEqual({ stack, tabs: undefined, sessionID: undefined })
expect(reopenSessionTab(stack, [{ sessionID: "b" }], "b")).toEqual({
stack: [{ tab: { sessionID: "c" }, index: 2 }],
tabs: undefined,
sessionID: undefined,
})
})
test("skips and consumes closed entries that are already open", () => {
const stack = [
{ tab: { sessionID: "a" }, index: 0 },
@@ -220,12 +234,12 @@ describe("session tabs", () => {
const reopened = reopenSessionTab(twice, [{ sessionID: "b" }])
expect(reopened.tabs).toEqual([{ sessionID: "b" }, { sessionID: "a" }])
const overflow = Array.from({ length: 12 }, (_, index) => ({ sessionID: String(index) })).reduce(
const overflow = Array.from({ length: 27 }, (_, index) => ({ sessionID: String(index) })).reduce(
(stack, tab, index) => recordClosedSessionTab(stack, tab, index),
twice,
)
expect(overflow).toHaveLength(10)
expect(overflow.at(-1)?.tab.sessionID).toBe("11")
expect(overflow).toHaveLength(25)
expect(overflow.at(-1)?.tab.sessionID).toBe("26")
expect(overflow[0]?.tab.sessionID).toBe("2")
})
@@ -323,6 +323,28 @@ test("keeps each visited session open", async () => {
}
})
test("lists closed tabs newest first and reopens a selected entry", async () => {
const setup = await renderSessionTabs("first", { persisted: ["first", "second", "third"] })
try {
await wait(() => setup.tabs.tabs().length === 3)
setup.tabs.close("second")
await wait(() => setup.tabs.tabs().length === 2)
setup.tabs.close("third")
await wait(() => setup.tabs.tabs().length === 1)
expect(setup.tabs.recentlyClosed().map((tab) => tab.sessionID)).toEqual(["third", "second"])
setup.tabs.reopen("second")
await wait(() => setup.tabs.tabs().some((tab) => tab.sessionID === "second"))
expect(setup.tabs.current()).toBe("second")
expect(setup.tabs.recentlyClosed().map((tab) => tab.sessionID)).toEqual(["third"])
setup.tabs.reopen()
await wait(() => setup.tabs.tabs().length === 3)
expect(setup.tabs.current()).toBe("third")
expect(setup.tabs.recentlyClosed()).toEqual([])
} finally {
await setup.destroy()
}
})
test("stores session tabs for the current working directory by default", async () => {
const setup = await renderSessionTabs("first")