feat(terminal): show bell indicator until user interacts (#1068)

This commit is contained in:
Brennan Benson
2026-04-25 19:05:53 -07:00
committed by GitHub
parent ff70ac0814
commit 7c75e9a853
11 changed files with 510 additions and 177 deletions
@@ -130,6 +130,8 @@ export default function TerminalPane({
const clearTabPtyId = useAppStore((store) => store.clearTabPtyId)
const markWorktreeUnread = useAppStore((store) => store.markWorktreeUnread)
const markTerminalTabUnread = useAppStore((store) => store.markTerminalTabUnread)
const clearWorktreeUnread = useAppStore((store) => store.clearWorktreeUnread)
const clearTerminalTabUnread = useAppStore((store) => store.clearTerminalTabUnread)
const settings = useAppStore((store) => store.settings)
// Why: Windows is the only platform where bare right-click is repurposed as
// a paste gesture; on macOS/Linux the terminal still owns right-click for the
@@ -386,6 +388,8 @@ export default function TerminalPane({
updateTabPtyId,
markWorktreeUnread,
markTerminalTabUnread,
clearWorktreeUnread,
clearTerminalTabUnread,
dispatchNotification,
setCacheTimerStartedAt,
syncPanePtyLayoutBinding,
@@ -450,6 +454,8 @@ export default function TerminalPane({
updateTabPtyId,
markWorktreeUnread,
markTerminalTabUnread,
clearWorktreeUnread,
clearTerminalTabUnread,
dispatchNotification,
setCacheTimerStartedAt,
syncPanePtyLayoutBinding
@@ -465,6 +471,8 @@ export default function TerminalPane({
dispatchNotification,
markWorktreeUnread,
markTerminalTabUnread,
clearWorktreeUnread,
clearTerminalTabUnread,
onPtyExitRef,
setCacheTimerStartedAt,
setRuntimePaneTitle,
@@ -634,6 +642,37 @@ export default function TerminalPane({
}
}, [isActive])
// Why: a click inside the terminal container is a deliberate interaction
// with the pane — dismiss the bell indicator for this tab and worktree
// (ghostty "show until interact" semantics). onData already covers
// keystrokes; pointerdown covers the mouse path, including right-click
// and middle-click paste, which also count as engagement with the pane.
//
// This listener is intentionally NOT gated on `isActive`. In multi-group
// split layouts (TabGroupPanel), several TerminalPane instances are
// simultaneously visible but only ONE has `isActive=true` (the focused
// group's active pane). When the user clicks into a visible-but-inactive
// split pane, TabGroupPanel's wrapper `onPointerDown={commands.focusGroup}`
// fires first; focusGroup clears tab-level unread but does NOT call
// clearWorktreeUnread — so the worktree-level sidebar dot would linger
// until another interaction. Attaching this listener unconditionally lets
// the first click dismiss both dots BEFORE focusGroup re-renders the pane
// as active and the effect deps change.
useEffect(() => {
const container = containerRef.current
if (!container) {
return
}
const onPointerDown = (): void => {
clearTerminalTabUnread(tabId)
clearWorktreeUnread(worktreeId)
}
container.addEventListener('pointerdown', onPointerDown, { capture: true })
return () => {
container.removeEventListener('pointerdown', onPointerDown, { capture: true })
}
}, [tabId, worktreeId, clearTerminalTabUnread, clearWorktreeUnread])
// Sync the data-has-title attribute on pane containers when titles change,
// and reflow terminals so safeFit() sees the correct available height.
// useLayoutEffect (not useEffect) ensures the attribute and refit happen
@@ -23,6 +23,8 @@ export type PtyConnectionDeps = {
updateTabPtyId: (tabId: string, ptyId: string) => void
markWorktreeUnread: (worktreeId: string) => void
markTerminalTabUnread: (tabId: string) => void
clearWorktreeUnread: (worktreeId: string) => void
clearTerminalTabUnread: (tabId: string) => void
// Why: the renderer-side dispatcher only handles BEL-sourced notifications
// now. shared/types.ts keeps a wider NotificationEventSource union because
// main-process callers can still emit others (e.g. `'test'` for the
@@ -148,6 +148,8 @@ function createDeps(overrides: Record<string, unknown> = {}) {
updateTabPtyId: vi.fn(),
markWorktreeUnread: vi.fn(),
markTerminalTabUnread: vi.fn(),
clearWorktreeUnread: vi.fn(),
clearTerminalTabUnread: vi.fn(),
dispatchNotification: vi.fn(),
setCacheTimerStartedAt: vi.fn(),
syncPanePtyLayoutBinding: vi.fn(),
@@ -614,10 +616,11 @@ describe('connectPanePty', () => {
// Why: BEL (0x07) is the attention signal. connectPanePty wires an
// onBell handler that raises the worktree unread dot, the tab-level
// bell indicator, and an OS notification. The unread flags clear when
// the user activates the tab (bell auto-clears on focus). This test
// locks in the wiring: if onBell is ever accidentally dropped, unread
// marks stop working entirely.
// bell indicator, and an OS notification. Under the ghostty
// show-until-interact model, the unread flags clear when the user
// actually interacts with the pane — keystroke via xterm onData or
// pointerdown on the container (see TerminalPane.tsx). This test
// locks in the mark wiring; separate tests below cover the clear path.
it('wires onBell to raise worktree unread, tab unread, and OS notification', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
@@ -641,6 +644,112 @@ describe('connectPanePty', () => {
expect(deps.dispatchNotification).toHaveBeenCalledWith({ source: 'terminal-bell' })
})
// Why: show-until-interact — a real keystroke through xterm onData is the
// canonical "user is here" signal that dismisses the bell. Guarded by the
// replay and codex-stale checks (see separate tests) so synthetic xterm
// auto-replies and blocked stale input never count as interaction.
it('clears tab and worktree unread on real keystroke via onData', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as (data: string) => void)('a')
expect(deps.clearTerminalTabUnread).toHaveBeenCalledWith('tab-1')
expect(deps.clearWorktreeUnread).toHaveBeenCalledWith('wt-1')
expect(transport.sendInput).toHaveBeenCalledWith('a')
})
// Why: xterm auto-replies during replay must not masquerade as user
// interaction. If they did, a pane that BELed during its scrollback
// replay would instantly self-dismiss without the user ever seeing it.
it('does not clear unread when onData fires during replay', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const replayingPanesRef = { current: new Map<number, number>([[1, 1]]) }
const deps = createDeps({ replayingPanesRef })
connectPanePty(pane as never, manager as never, deps as never)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as (data: string) => void)('\x1b[?1;2c')
expect(deps.clearTerminalTabUnread).not.toHaveBeenCalled()
expect(deps.clearWorktreeUnread).not.toHaveBeenCalled()
})
// Why: symmetric to the replay guard — if the pane is stale-codex (pending
// account-switch restart), xterm onData bytes are either blocked synthetic
// input or keystrokes that would execute under the wrong account. Either
// way they must not count as user interaction and dismiss the bell. The
// production code also blocks the transport.sendInput call in this branch
// (see pty-connection.ts lines 275-277), so we assert that too.
it('does not clear unread when onData fires on a stale codex pane', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-codex-stale')
transportFactoryQueue.push(transport)
// isCodexPaneStale reads codexRestartNoticeByPtyId from the store, so
// trigger the stale branch by seeding a restart notice for the pane's PTY.
mockStoreState = {
...mockStoreState,
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', ptyId: 'pty-codex-stale' }]
},
ptyIdsByTabId: {
'tab-1': ['pty-codex-stale']
},
codexRestartNoticeByPtyId: {
'pty-codex-stale': { previousAccountLabel: 'A', nextAccountLabel: 'B' }
}
}
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as (data: string) => void)('a')
expect(deps.clearTerminalTabUnread).not.toHaveBeenCalled()
expect(deps.clearWorktreeUnread).not.toHaveBeenCalled()
// Stale-codex input is also blocked from reaching the transport.
expect(transport.sendInput).not.toHaveBeenCalled()
})
// Why: the working→idle transition is kept solely to drive Claude's
// prompt-cache timer. It MUST NOT raise attention — doing so would
// double-fire with the BEL path above (since Claude's "done" state is
@@ -275,6 +275,12 @@ export function connectPanePty(
if (isCodexPaneStale({ tabId: deps.tabId, panePtyId: currentPtyId })) {
return
}
// Why: a real keystroke into the terminal is the unambiguous "user is
// here" signal that dismisses the bell (ghostty "show until interact").
// Guarded by the replay and codex-stale checks above so synthetic xterm
// auto-replies never count as interaction.
deps.clearTerminalTabUnread(deps.tabId)
deps.clearWorktreeUnread(deps.worktreeId)
transport.sendInput(data)
})
@@ -94,6 +94,8 @@ type UseTerminalPaneLifecycleDeps = {
updateTabPtyId: (tabId: string, ptyId: string) => void
markWorktreeUnread: (worktreeId: string) => void
markTerminalTabUnread: (tabId: string) => void
clearWorktreeUnread: (worktreeId: string) => void
clearTerminalTabUnread: (tabId: string) => void
dispatchNotification: (event: { source: 'terminal-bell' }) => void
setCacheTimerStartedAt: (key: string, ts: number | null) => void
syncPanePtyLayoutBinding: (paneId: number, ptyId: string | null) => void
@@ -176,6 +178,8 @@ export function useTerminalPaneLifecycle({
updateTabPtyId,
markWorktreeUnread,
markTerminalTabUnread,
clearWorktreeUnread,
clearTerminalTabUnread,
dispatchNotification,
setCacheTimerStartedAt,
syncPanePtyLayoutBinding,
@@ -319,6 +323,8 @@ export function useTerminalPaneLifecycle({
updateTabPtyId,
markWorktreeUnread,
markTerminalTabUnread,
clearWorktreeUnread,
clearTerminalTabUnread,
dispatchNotification,
setCacheTimerStartedAt,
syncPanePtyLayoutBinding,
+46 -39
View File
@@ -440,42 +440,32 @@ describe('TabsSlice', () => {
})
})
// ─── markTerminalTabUnread (split-group guard) ───────────────────
// ─── markTerminalTabUnread ───────────────────────────────────────
//
// Regression guard for the split-group bell bug: when two groups are visible
// side-by-side, a bell in the active tab of a non-focused group must NOT
// mark that tab unread — the user can already see it. Before the fix,
// markTerminalTabUnread only checked the global activeTabId (the focused
// group's tab), so the non-focused but still-visible group's tab got a
// spurious bell.
// Ghostty "show until interact" model: BEL always marks the tab unread,
// including the currently-focused tab and the active tab of every visible
// split group. The indicator is cleared by user interaction (keystroke,
// click, focus-gain) via clearTerminalTabUnread — NOT by the mark path
// trying to guess whether the user already "sees" the tab.
describe('markTerminalTabUnread', () => {
it('suppresses marking when the tab is active in any visible group of the active worktree', () => {
it('marks the tab even when it is active in a visible split group of the active worktree', () => {
// Group A: the current worktree's root group, created implicitly by
// createUnifiedTab. Populate it with a terminal tab (tabA).
const tabA = store.getState().createUnifiedTab(WT, 'terminal')
const groupAId = store.getState().groupsByWorktree[WT][0].id
// Group B: split to the right of Group A, then populate with its own
// terminal tab and focus Group B so it becomes the globally-focused
// group — this is the condition under which the bug reproduces.
// terminal tab and focus Group B so tabA is visible-but-not-focused.
const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right')
if (!groupBId) {
throw new Error('createEmptySplitGroup returned null')
}
store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId })
store.getState().focusGroup(WT, groupBId)
// Mark the active worktree so markTerminalTabUnread's guard reaches the
// split-group branch (it early-returns otherwise).
store.setState({ activeWorktreeId: WT })
// Why: markTerminalTabUnread early-returns when no TerminalTab owns
// tabA.entityId in tabsByWorktree (owner-missing guard). Without this
// seed, the test would pass via that early-return rather than exercising
// the split-group visibility branch we are trying to cover. In
// production, every terminal unified tab has a backing legacy terminal
// tab (createTab calls createUnifiedTab with matching ids); mirror that
// invariant here so the guard under test is actually reached.
// Seed the backing legacy terminal tab so markTerminalTabUnread's
// owner-missing guard doesn't short-circuit.
store.setState({
tabsByWorktree: {
[WT]: [
@@ -493,18 +483,12 @@ describe('TabsSlice', () => {
}
})
// Sanity: Group A still has tabA as its active tab, and tabA is NOT the
// global activeTabId (Group B's tab is). Without the fix, the global
// check alone would let the mark through.
const groupA = store.getState().groupsByWorktree[WT].find((g) => g.id === groupAId)
expect(groupA?.activeTabId).toBe(tabA.id)
expect(store.getState().activeTabId).not.toBe(tabA.entityId)
// Fire a bell on Group A's terminal tab. It must be suppressed because
// Group A is still visible alongside Group B.
// Fire a bell on Group A's terminal tab. Under ghostty semantics the
// indicator must appear even though that tab is visible — only
// clearTerminalTabUnread (called from onData / pointerdown) dismisses it.
store.getState().markTerminalTabUnread(tabA.entityId)
expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBeUndefined()
expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBe(true)
})
it('does mark a tab that is not the active tab of any visible group', () => {
@@ -550,15 +534,10 @@ describe('TabsSlice', () => {
expect(store.getState().unreadTerminalTabs[tabA2.entityId]).toBe(true)
})
// Why: the active-surface guard must only suppress when the user is
// actually looking at the terminal. activeTabId remains pinned to the
// last terminal tab even when the user has switched to the editor or
// browser — in that case the terminal is offscreen and bells are
// legitimate unread signals.
//
// We scope this test to a worktree that is NOT the activeWorktreeId so
// the split-group visibility check short-circuits; the test subject is
// the activeTabType branch of the guard.
// Why: under the show-until-interact model, BEL fires unconditionally
// even when the user is looking at a non-terminal surface or the tab
// is globally active. This test pins that behavior for the "editor is
// on screen, terminal is offscreen" case — clearly a legitimate unread.
it('still marks the tab when the active surface is not terminal', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
// Point global active* at this tab (matches post-activate state) but
@@ -658,6 +637,34 @@ describe('TabsSlice', () => {
})
})
// ─── clearTerminalTabUnread ──────────────────────────────────────────
//
// Called on actual user interaction with a terminal pane (keystroke via
// xterm onData, or pointerdown on the container). Pins the dismissal half
// of the show-until-interact contract.
describe('clearTerminalTabUnread', () => {
it('removes the tab from unreadTerminalTabs', () => {
const tabId = 'bell-tab-1'
store.setState({
unreadTerminalTabs: { [tabId]: true as const, 'other-tab': true as const }
})
store.getState().clearTerminalTabUnread(tabId)
expect(store.getState().unreadTerminalTabs).toEqual({ 'other-tab': true })
})
it('is a reference-preserving no-op when the tab is not flagged', () => {
const initial = { 'other-tab': true as const }
store.setState({ unreadTerminalTabs: initial })
store.getState().clearTerminalTabUnread('bell-tab-1')
// Same reference => no-op. Downstream selectors must not re-render.
expect(store.getState().unreadTerminalTabs).toBe(initial)
})
})
// ─── focusGroup clears unread on focused group's terminal tab ─────────
//
// Regression guard: users clicking a group that already had its tab
+22 -28
View File
@@ -120,6 +120,11 @@ export type TerminalSlice = {
* group within the active worktree. A visible tab is already "seen",
* so a flag would never clear naturally. */
markTerminalTabUnread: (tabId: string) => void
/** Clear a tab's unread indicator. Called on user interaction with the
* pane (keystroke, click) — matches ghostty's "show until interact"
* model where the bell stays visible until the user engages with the
* surface that raised it. */
clearTerminalTabUnread: (tabId: string) => void
setTabCustomTitle: (tabId: string, title: string | null) => void
setTabColor: (tabId: string, color: string | null) => void
updateTabPtyId: (tabId: string, ptyId: string) => void
@@ -653,34 +658,12 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
if (!ownerTab) {
return
}
if (state.activeTabType === 'terminal' && state.activeTabId === tabId) {
return
}
// Why: in split-group layouts multiple groups are visible simultaneously,
// each with its own active terminal tab. The global activeTabId only
// reflects the focused group's tab. If an attention signal fires on a tab
// that is the active tab of a non-focused but still-visible group,
// marking it unread would show a spurious bell on a pane the user can
// already see.
//
// Why (activeTabType guard): this suppression only applies while the
// terminal surface is actually being rendered. When the user is viewing
// the editor or browser surface (activeTabType !== 'terminal'), terminal
// panes are not on-screen at all, so the "active tab in a visible group"
// premise breaks — the user cannot see the tab, and the completion
// signal is legitimate unread that must not be swallowed.
if (state.activeTabType === 'terminal' && state.activeWorktreeId) {
const groups = state.groupsByWorktree[state.activeWorktreeId] ?? []
const unifiedTabs = state.unifiedTabsByWorktree[state.activeWorktreeId] ?? []
for (const group of groups) {
if (group.activeTabId) {
const groupActiveTab = unifiedTabs.find((t) => t.id === group.activeTabId)
if (groupActiveTab?.contentType === 'terminal' && groupActiveTab.entityId === tabId) {
return
}
}
}
}
// Why: BEL must fire regardless of focus (ghostty semantics — "show
// until interact"). A BEL on the focused tab sets the indicator; real
// user interaction with the pane dismisses it. Keystroke/pointerdown
// routes through clearTerminalTabUnread (see pty-connection.ts and
// TerminalPane.tsx); tab/group activation clears unreadTerminalTabs
// directly in activateTab/focusGroup as a pre-existing side-effect.
set((s) => {
if (s.unreadTerminalTabs[tabId]) {
return s
@@ -689,6 +672,17 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
})
},
clearTerminalTabUnread: (tabId) => {
set((s) => {
if (!s.unreadTerminalTabs[tabId]) {
return s
}
const copy = { ...s.unreadTerminalTabs }
delete copy[tabId]
return { unreadTerminalTabs: copy }
})
},
setTabCustomTitle: (tabId, title) => {
set((s) => {
const next = { ...s.tabsByWorktree }
@@ -37,6 +37,10 @@ export type WorktreeSlice = {
clearWorktreeDeleteState: (worktreeId: string) => void
updateWorktreeMeta: (worktreeId: string, updates: Partial<WorktreeMeta>) => Promise<void>
markWorktreeUnread: (worktreeId: string) => void
/** Clear the worktree's unread dot. Called on user interaction with any
* terminal pane inside the worktree (keystroke, click) — matches
* ghostty's "show until interact" model. Persists isUnread=false. */
clearWorktreeUnread: (worktreeId: string) => void
bumpWorktreeActivity: (worktreeId: string) => void
setActiveWorktree: (worktreeId: string | null) => void
allWorktrees: () => Worktree[]
@@ -404,3 +404,70 @@ describe('removeWorktree state cleanup', () => {
expect(store.getState().editorDrafts).toBe(drafts)
})
})
// Why: ghostty "show until interact" model — BEL must raise the sidebar dot
// even on the active worktree, and only clearWorktreeUnread (called from the
// terminal pane on keystroke / pointerdown) dismisses it. Pins both halves
// of that contract.
describe('worktree unread (show-until-interact)', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('markWorktreeUnread sets isUnread even when the worktree is active', async () => {
const store = createTestStore()
const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' })
store.setState({
worktreesByRepo: { repo1: [wt] },
activeWorktreeId: wt.id
} as Partial<AppState>)
store.getState().markWorktreeUnread(wt.id)
const after = store.getState().worktreesByRepo.repo1[0]
expect(after.isUnread).toBe(true)
expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith(
expect.objectContaining({
worktreeId: wt.id,
updates: expect.objectContaining({ isUnread: true })
})
)
})
it('clearWorktreeUnread clears isUnread and persists the change', async () => {
const store = createTestStore()
const wt = makeWorktree({
id: 'repo1::/path/wt1',
repoId: 'repo1',
path: '/path/wt1',
isUnread: true
})
store.setState({
worktreesByRepo: { repo1: [wt] },
activeWorktreeId: wt.id
} as Partial<AppState>)
store.getState().clearWorktreeUnread(wt.id)
const after = store.getState().worktreesByRepo.repo1[0]
expect(after.isUnread).toBe(false)
expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith(
expect.objectContaining({
worktreeId: wt.id,
updates: { isUnread: false }
})
)
})
it('clearWorktreeUnread is a no-op when already cleared', () => {
const store = createTestStore()
const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' })
const initial = { repo1: [wt] }
store.setState({ worktreesByRepo: initial } as Partial<AppState>)
store.getState().clearWorktreeUnread(wt.id)
expect(store.getState().worktreesByRepo).toBe(initial)
expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled()
})
})
+36 -5
View File
@@ -333,11 +333,11 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
},
markWorktreeUnread: (worktreeId) => {
const activeWorktreeId = get().activeWorktreeId
if (activeWorktreeId === worktreeId) {
return
}
// Why: BEL must fire regardless of focus (ghostty semantics — "show
// until interact"). Interaction with a pane inside the worktree
// dismisses the dot via clearWorktreeUnread. Worktree activation via
// setActiveWorktree also clears isUnread as a side-effect; that path
// predates this PR and is unaffected here.
let shouldPersist = false
const now = Date.now()
set((s) => {
@@ -367,6 +367,37 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
})
},
clearWorktreeUnread: (worktreeId) => {
let shouldPersist = false
set((s) => {
const worktree = findWorktreeById(s.worktreesByRepo, worktreeId)
if (!worktree || !worktree.isUnread) {
// Why: return `s` (not `{}`) to preserve the exact object reference
// on no-op. This matches the sibling `clearTerminalTabUnread` in
// terminals.ts and avoids downstream selector churn on the hot path
// (called on every keystroke and pointerdown).
return s
}
shouldPersist = true
return {
worktreesByRepo: applyWorktreeUpdates(s.worktreesByRepo, worktreeId, {
isUnread: false
})
}
})
if (!shouldPersist) {
return
}
void window.api.worktrees
.updateMeta({ worktreeId, updates: { isUnread: false } })
.catch((err) => {
console.error('Failed to persist cleared unread worktree state:', err)
void get().fetchWorktrees(getRepoIdFromWorktreeId(worktreeId))
})
},
bumpWorktreeActivity: (worktreeId) => {
const now = Date.now()
set((s) => {
+169 -101
View File
@@ -58,7 +58,11 @@ async function activateTerminalTab(page: Page, tabId: string): Promise<void> {
}
async function emitBell(page: Page, ptyId: string): Promise<void> {
await execInTerminal(page, ptyId, `node -e "process.stdout.write('\\u0007')"`)
// Why: `tput bel` is the canonical way to emit BEL from the shell — this is
// the exact command the user will run to reproduce the attention path. Prefer
// it over `node -e` so the test exercises the same PTY byte stream a real
// user sees.
await execInTerminal(page, ptyId, `tput bel`)
}
async function getUnreadTerminalTabIds(page: Page): Promise<string[]> {
@@ -121,10 +125,11 @@ test.describe('Terminal attention', () => {
await expect(secondTabBell).toBeHidden()
})
// Why (visibility guard): markTerminalTabUnread skips the currently-active
// tab. A BEL arriving on the tab the user is already looking at must not
// leave a persistent indicator — there is nothing to "notify" about.
test('a BEL on the focused tab does not raise its own bell', async ({ orcaPage }) => {
// Why (show-until-interact): ghostty's model fires the bell even on the
// currently-focused tab — the user only dismisses it by actually engaging
// with the pane. This test proves the BEL on a focused tab is visible
// until a pointerdown on the terminal container clears it.
test('a BEL on the focused tab raises, then clears on click', async ({ orcaPage }) => {
await waitForSessionReady(orcaPage)
await waitForActiveWorktree(orcaPage)
await ensureTerminalVisible(orcaPage)
@@ -138,8 +143,8 @@ test.describe('Terminal attention', () => {
// Emit the BEL, then a deterministic OSC title marker. When the marker
// title lands, all prior PTY bytes (including the BEL) have been
// processed — we can then safely assert that the focused tab is not
// unread. This avoids the flaky fixed-timeout pattern.
// processed — we can then safely assert unread state without racing the
// async PTY pipeline.
await emitBell(orcaPage, activePtyId)
const MARKER_TITLE = 'focused-tab-bell-marker'
await execInTerminal(
@@ -167,7 +172,38 @@ test.describe('Terminal attention', () => {
)
.toBe(true)
expect((await getUnreadTerminalTabIds(orcaPage)).includes(activeTabId)).toBe(false)
// The focused tab is now unread — the bell persists until the user
// actually interacts with the pane.
expect((await getUnreadTerminalTabIds(orcaPage)).includes(activeTabId)).toBe(true)
const activeTabBell = orcaPage
.locator(
`[data-testid="sortable-tab"][data-tab-id="${activeTabId}"] [data-testid="tab-activity-bell"]`
)
.first()
await expect(activeTabBell).toBeVisible()
// A pointerdown inside the terminal container counts as interaction
// (matches the pointerdown handler added in TerminalPane.tsx). Drive it
// via the DOM so we exercise the real listener path rather than bypassing
// to the store action.
await orcaPage.evaluate((tabId) => {
const managers = window.__paneManagers
const manager = managers?.get(tabId)
const pane = manager?.getActivePane()
const container = pane?.container
if (!container) {
throw new Error('No active pane container to click')
}
container.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true }))
}, activeTabId)
await expect
.poll(async () => (await getUnreadTerminalTabIds(orcaPage)).includes(activeTabId), {
timeout: 5_000,
message: 'Unread state did not clear after interacting with the pane'
})
.toBe(false)
await expect(activeTabBell).toBeHidden()
})
// Why (restart regression guard): the original user-reported bug was that
@@ -205,108 +241,140 @@ test.describe('Terminal attention', () => {
await waitForActiveTerminalManager(orcaPage, 30_000)
// secondTabId is already active after createTerminalTab. Simulate what
// scrollback replay does: a DECSET 1004 byte landing in xterm. This is
// the exact byte Claude Code emits at startup, and the exact byte
// SerializeAddon captures in a post-restart scrollback dump. The
// post-replay reset in layout-serialization.ts should cancel it out —
// so this write, immediately followed by the reset, produces a terminal
// with mode 1004 off. We write while secondTabId has focus so the
// DECSET lands on the tab whose xterm we want to verify.
// scrollback replay does: a DECSET 1004 byte landing in xterm. Then
// install an onData spy so we can observe everything xterm emits from
// this point on — crucially, the focus escapes `\e[I` / `\e[O` that
// leak when mode 1004 is still enabled. The POST_REPLAY_MODE_RESET
// bundle should turn mode 1004 OFF; if it does, no focus escape is
// emitted on the next blur and the spy's buffer stays empty.
// Why: xterm's parser is async — bytes passed to `write()` are queued and
// consumed on a later tick. During the brief window when mode 1004 is
// enabled, xterm emits a synchronous focus-IN (`\e[I`) because the
// terminal is focused; that emission MUST NOT land in the spy or the
// assertion below will false-positive even when the post-replay reset
// worked correctly.
//
// We use xterm's `write(data, callback)` overload: the callback fires
// AFTER the parser has consumed that write. By installing the spy inside
// the callback for the POST_REPLAY_MODE_RESET write, we guarantee any
// transient focus escapes emitted while mode 1004 was briefly on have
// already fired before the spy exists. No fixed sleep needed.
await orcaPage.evaluate(
({ tabId, modeReset }) => {
({ tabId, modeReset }) =>
new Promise<void>((resolve, reject) => {
const managers = window.__paneManagers
const manager = managers?.get(tabId)
const pane = manager?.getActivePane()
if (!pane) {
reject(new Error('No active pane on restored tab'))
return
}
pane.terminal.write('\x1b[?1004h')
pane.terminal.write(modeReset, () => {
// Parser has consumed both the DECSET and the reset. Any focus
// escapes from the brief 1004-ON window have already been emitted
// (and dropped on the floor, since nothing was listening). Install
// the spy now to observe only post-reset output.
const recorded: string[] = []
;(window as unknown as { __XTERM_ONDATA_SPY__: string[] }).__XTERM_ONDATA_SPY__ =
recorded
const disposer = pane.terminal.onData((data) => {
recorded.push(data)
})
;(
window as unknown as { __XTERM_ONDATA_DISPOSE__?: () => void }
).__XTERM_ONDATA_DISPOSE__ = () => disposer.dispose()
resolve()
})
}),
{ tabId: secondTabId, modeReset: POST_REPLAY_MODE_RESET }
)
// Why (try/finally): the onData spy + disposer live on window globals on
// the shared renderer. If any assertion below throws, we still MUST tear
// down the spy so it doesn't leak into subsequent tests (which would see
// stale captured data and/or a dangling xterm onData subscription).
try {
// Trigger focus change away from secondTabId. If mode 1004 is still
// enabled, xterm will emit `\e[O` via onData — captured by the spy above.
// Also explicitly blur the xterm instance so the DOM focus actually moves
// (setActiveTab alone doesn't blur focus).
await activateTerminalTab(orcaPage, firstTabId)
await orcaPage.evaluate((tabId) => {
const managers = window.__paneManagers
const manager = managers?.get(tabId)
const pane = manager?.getActivePane()
if (!pane) {
return
}
pane.terminal.blur()
}, secondTabId)
// Why: flush xterm's output queue with a DA1 query — xterm replies via
// onData with `\e[?...c`. By the time the reply lands in the spy, any
// focus escape the blur handler would have emitted has also landed.
// This gives us a deterministic "all-prior-output-processed" signal
// without a fixed sleep (which expect.poll + .not.toMatch does NOT
// provide — expect.poll exits as soon as the assertion passes once,
// so .not.toMatch on an empty buffer would pass instantly at 0ms).
await orcaPage.evaluate((tabId) => {
const managers = window.__paneManagers
const manager = managers?.get(tabId)
const pane = manager?.getActivePane()
if (!pane) {
throw new Error('No active pane on restored tab')
}
// Enable focus reporting and then immediately apply the same reset
// the real scrollback-restore path applies. After this, mode 1004
// should be OFF.
pane.terminal.write('\x1b[?1004h')
pane.terminal.write(modeReset)
},
{ tabId: secondTabId, modeReset: POST_REPLAY_MODE_RESET }
)
pane.terminal.write('\x1b[c')
}, secondTabId)
// Now trigger a focus change. The DECSET happened while secondTabId was
// active; the subsequent focus change to firstTabId causes a focus-out
// on secondTabId's xterm. If POST_REPLAY_MODE_RESET failed to disable
// mode 1004, xterm would emit `\e[O` down secondTabId's PTY and zsh
// would ring the bell. Flush pending output with a marker OSC title
// and assert that no unread indicator appeared.
await activateTerminalTab(orcaPage, firstTabId)
await expect
.poll(
async () => {
const emitted = await orcaPage.evaluate(
() =>
(window as unknown as { __XTERM_ONDATA_SPY__: string[] | undefined })
.__XTERM_ONDATA_SPY__ ?? []
)
return emitted.join('')
},
{
timeout: 5_000,
message: 'DA1 reply never arrived — xterm onData spy did not receive data'
}
)
// eslint-disable-next-line no-control-regex -- intentional terminal escape sequence matching
.toMatch(/\x1b\[\?.*c/)
// Resolve secondTabId's PTY directly from the store. We can't use
// discoverActivePtyId here — firstTabId is the active tab now, so that
// helper would return the wrong PTY and the marker flush would not
// guarantee secondTabId's pending output has been drained.
// Why: waitForActiveTerminalManager only waits for the pane manager to
// have panes — it does NOT wait for updateTabPtyId to fire, which
// happens asynchronously after pty.spawn resolves in pty-connection.ts.
// Poll so we don't race the spawn callback on slow CI.
await expect
.poll(
async () =>
orcaPage.evaluate((targetTabId) => {
const store = window.__store
if (!store) {
return null
}
return store.getState().ptyIdsByTabId[targetTabId]?.[0] ?? null
}, secondTabId),
{
timeout: 10_000,
message: `No PTY registered for tab ${secondTabId}`
// By this point all prior xterm output has been observed. Read the
// final buffer once and assert no focus escape is present. Mode 1004
// reset succeeded iff no focus escapes are emitted — we assert on the
// precise byte-level mechanism the fix guards against (`\e[I` focus-in
// / `\e[O` focus-out), not the tab unread state, because under the
// show-until-interact model that state can be flipped by unrelated
// shell-startup BELs.
const emittedFromXterm = await orcaPage.evaluate(
() =>
(window as unknown as { __XTERM_ONDATA_SPY__: string[] | undefined })
.__XTERM_ONDATA_SPY__ ?? []
)
// Join before matching: individual chunks could split an escape
// across onData calls (unlikely but possible — e.g. if xterm
// flushes mid-escape).
// eslint-disable-next-line no-control-regex -- intentional terminal escape sequence matching
expect(emittedFromXterm.join('')).not.toMatch(/\x1b\[[IO]/)
} finally {
// Dispose the onData subscription and clear the globals so nothing leaks
// across tests on the shared renderer. Runs even if an assertion above
// failed.
await orcaPage.evaluate(() => {
const w = window as unknown as {
__XTERM_ONDATA_DISPOSE__?: () => void
__XTERM_ONDATA_SPY__?: string[]
}
)
.not.toBeNull()
const secondTabPtyId = await orcaPage.evaluate((targetTabId) => {
const store = window.__store
if (!store) {
throw new Error('window.__store is unavailable')
}
const pty = store.getState().ptyIdsByTabId[targetTabId]?.[0]
if (!pty) {
throw new Error(`No PTY found for tab ${targetTabId}`)
}
return pty
}, secondTabId)
const MARKER_TITLE = 'mode-reset-marker'
await execInTerminal(
orcaPage,
secondTabPtyId,
`node -e "process.stdout.write('\\u001b]0;${MARKER_TITLE}\\u0007')"`
)
await expect
.poll(
async () =>
orcaPage.evaluate((want) => {
const store = window.__store
if (!store) {
return false
}
return Object.values(store.getState().tabsByWorktree ?? {})
.flat()
.some((tab) => tab.title === want)
}, MARKER_TITLE),
{
timeout: 10_000,
message: 'Marker title did not land — byte stream may not have been flushed'
}
)
.toBe(true)
// By the time the marker arrives, any BEL that mode 1004 would have
// produced has also been processed. The tab should not be unread.
expect((await getUnreadTerminalTabIds(orcaPage)).includes(secondTabId)).toBe(false)
const secondTabBell = orcaPage
.locator(
`[data-testid="sortable-tab"][data-tab-id="${secondTabId}"] [data-testid="tab-activity-bell"]`
)
.first()
await expect(secondTabBell).toBeHidden()
w.__XTERM_ONDATA_DISPOSE__?.()
delete w.__XTERM_ONDATA_DISPOSE__
delete w.__XTERM_ONDATA_SPY__
})
}
})
})