/** * Sidebar crash tests — the failure modes behind issue #31 plus the store's * listener containment. * * 1. Layout-push leak: the layout-push effect writes * `--dsh-sidebar-height` on document.documentElement (the right column * belongs to DSH's native Sidebar, so no width is pushed). * Unmounting the Sidebar for ANY reason (error-boundary swap, plugin * disable, HMR) must clear it — otherwise layout.css keeps squeezing * `#root` with a stale margin and "the sidebar cannot be hidden" until a * full page reload. * * 2. Tab crash containment: a render error inside ONE tab's content must not * take down the whole sidebar. The per-tab boundary shows a strip inside * that tab's pane while the toggle cluster, the other tabs, and the panel * itself stay alive; the retry button recovers a transient crash. * * 3. Store listener containment: `service.subscribeState` is the store's own * `subscribe`, so a consumer plugin's listener runs inside `notify()` — * which runs inline in the mutating call site (the Sidebar's own mount * effect calls `store.setSession`). A throw escaping that loop lands in * the React commit phase, where the shell's ROOT RenderBoundary (index.tsx) * swaps the WHOLE sidebar for its error strip. One listener must not be * able to do that to the rest of the panel. * * Rendered with the REAL Sidebar shell + real store/service against a minimal * fake context (createRoot + act(), the repo's jsdom pattern). */ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' import { createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' // The act() environment flag (React 18.2 reads it before flushing effects). import { setupReactAct } from './test-utils.ts' setupReactAct() import { Sidebar } from '../src/client/Sidebar.tsx' import { createSidebarStore, setBottomHeight, toggleBottomPanel, type SidebarStore } from '../src/client/state.ts' import { createBetterSidebarService, type BetterSidebarService } from '../src/client/service.ts' import { t } from '../src/client/locales.ts' /** jsdom has no WebSocket; the agent-terminals push effect constructs one on mount. */ class FakeWebSocket { onmessage: ((event: { data: unknown }) => void) | null = null onclose: (() => void) | null = null onerror: (() => void) | null = null close = (): void => {} constructor(_url: string) {} } interface MountedSidebar { container: HTMLDivElement store: SidebarStore service: BetterSidebarService unmount: () => void } /** Roots still mounted when a test ends. `afterEach` unmounts them: wiping the * DOM without unmounting leaves every effect cleanup un-run, and the 1s * `session.phase` poller in `session-phase.ts` then outlives the test — it * fires after jsdom is gone, React reads a missing `window` and the whole run * is red on `Errors 1` even though every test passed. */ const mountedRoots: Array<() => void> = [] /** Intervals created while a test runs. `session-phase.ts` polls through * `setInterval`; a live id here after the roots are unmounted means some * effect leaked a timer (see `mountedRoots`). */ const liveIntervals = new Set>() /** Mount the real Sidebar shell against a minimal context (real store + service). */ /** Unique per-test session ids (see the comment inside). */ let sessionSeq = 0 function mountSidebar(): MountedSidebar { vi.stubGlobal('WebSocket', FakeWebSocket) // The real timers, wrapped so `afterEach` can prove nothing outlived the // test (vi.unstubAllGlobals restores both). const realSetInterval = globalThis.setInterval const realClearInterval = globalThis.clearInterval vi.stubGlobal('setInterval', ((handler: never, timeout?: number) => { const id = realSetInterval(handler, timeout) liveIntervals.add(id) return id }) as never) vi.stubGlobal('clearInterval', ((id: never) => { liveIntervals.delete(id) realClearInterval(id) }) as never) const container = document.createElement('div') document.body.append(container) const store = createSidebarStore() const service = createBetterSidebarService(store) // Unique session per test — the store persists per-session state to // localStorage (200ms debounce); a shared id lets a previous test's late // write leak into this store's setSession restore. const sessionId = `s1-${++sessionSeq}` store.setSession(sessionId) // useSyncExternalStore requires STABLE snapshots across calls (the real DSH // services return stable objects) — a fresh object per call loops forever. const localeSnapshot = { active: 'en' } const sessionsSnapshot = { // cwd present → api.sessionCwd is never called in these tests. byId: { [sessionId]: { cwd: '/tmp' } }, } // The conversation on screen is the native surface's mounted seat // (`ctx.sidebarRight.mounted`); the session-list snapshot never had a // current-session field, so the shell binds its per-session state to THIS. const mounted = { getSnapshot: () => sessionId, subscribe: () => () => {}, } const ctx = { locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot }, sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } }, betterSidebar: service, get: (name: string) => name === 'betterSidebar' ? service : name === 'sidebarRight' ? { mounted } : undefined, } const root: Root = createRoot(container) act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) }) // Idempotent: a test may unmount explicitly, and afterEach unmounts whatever // is left (calling React's unmount twice throws). let unmounted = false const unmount = (): void => { if (unmounted) return unmounted = true act(() => { root.unmount() }) container.remove() } mountedRoots.push(unmount) return { container, store, service, unmount } } afterEach(() => { // Unmount FIRST: that is what runs the effects' cleanups, and the cleanups // are what clear the pollers. Wiping the DOM instead (the old harness) left // them armed and reddened CI with `window is not defined`. for (const unmount of mountedRoots.splice(0).reverse()) unmount() const leaked = liveIntervals.size liveIntervals.clear() expect( leaked, 'every interval started by a test must be cleared before it ends — an armed one fires after jsdom is torn down', ).toBe(0) document.body.innerHTML = '' // Belt and braces: drop any persisted layout a pending 200ms debounce // write left behind between tests (unique session ids already isolate). localStorage.clear() vi.unstubAllGlobals() }) describe('test harness', () => { // The leak guard itself lives in `afterEach` (no interval may outlive a // test). A poll that never settles keeps the 1s `session.phase` interval // armed from mount to the end of the test — which is exactly the state the // old harness (wipe the DOM, never unmount) leaked past teardown: the timer // fired after jsdom was gone, React read a missing `window`, and an // all-green run went red on `Errors 1`. The assertion below proves the // armed state was really reached, so this test cannot pass vacuously. it('arms the session-phase poller, so afterEach has something to clear', () => { vi.stubGlobal('fetch', () => new Promise(() => {})) mountSidebar() expect( liveIntervals.size, 'the hanging route must leave the poller armed', ).toBeGreaterThan(0) }) }) describe('layout-push variable cleanup', () => { it('clears --dsh-sidebar-height when the sidebar unmounts (and never pushes a width)', () => { const { unmount } = mountSidebar() const htmlStyle = document.documentElement.style // A fresh session seeds the bottom workbench collapsed: the push is 0. expect(htmlStyle.getPropertyValue('--dsh-sidebar-height')).toBe('0px') // The right column is DSH's native Sidebar — this shell writes no width. expect(htmlStyle.getPropertyValue('--dsh-sidebar-width')).toBe('') // Any unmount (boundary swap, plugin disable, HMR) must release the push. unmount() expect(htmlStyle.getPropertyValue('--dsh-sidebar-height')).toBe('') }) it('a size change (release commit) re-applies the variable without removing it mid-commit', () => { const { store, unmount } = mountSidebar() const htmlStyle = document.documentElement.style const removeSpy = vi.spyOn(htmlStyle, 'removeProperty') // Simulate a drag release: the bottom panel opens and its height commits. act(() => { store.reduce(toggleBottomPanel) }) act(() => { store.reduce(s => setBottomHeight(s, 300)) }) expect(htmlStyle.getPropertyValue('--dsh-sidebar-height')).toBe('300px') // The commit must NOT have removed the variables at any point. React // runs every effect cleanup before every effect setup in a commit, so a // cleanup here would remove the variables before the draggingRef effect // (declared above the layout push) forces a layout in measureCenter // (getBoundingClientRect). That forced recalc resolves #root's // margin-right to the 0px fallback, caches it as the transition start // value, and measures centerRect too wide; once transitions re-enable on // release, the shell animates margin-right 0 → width — the "expand to // the full page then bounce back" flash. const removalProps = removeSpy.mock.calls .map(call => call[0] as string) .filter(prop => prop === '--dsh-sidebar-height') expect(removalProps).toHaveLength(0) // Only unmounting may remove it (issue #31). unmount() expect(removeSpy.mock.calls.some(call => call[0] === '--dsh-sidebar-height')).toBe(true) removeSpy.mockRestore() }) }) describe('tab crash containment', () => { it('a crashing tab shows an in-pane strip while the panel survives', () => { const { container, service, store } = mountSidebar() service.registerTab({ id: 'crash', title: 'Crash', component: () => { throw new Error('boom') }, }) act(() => { service.openTab({ type: 'crash', title: 'Crash' }) }) // The strip lives inside the tab's pane — the crash is contained. expect(container.textContent).toContain('boom') expect(container.textContent).toContain(t('terminalRetry')) // The workbench itself survived (no full-tree swap): the collapse control // is still there and the layout push is still live (the content open // expanded the panel). expect(container.querySelector(`[aria-label="${t('collapseBottomPanel')}"]`)).not.toBeNull() expect(document.documentElement.style.getPropertyValue('--dsh-sidebar-height')).toBe( `${store.getSnapshot().state!.bottomHeight}px`, ) }) it('the retry button recovers a tab whose crash has since been fixed', () => { // A PERSISTENT render error reaches the boundary strip (React 18.2 // auto-recovers transient throws — one bad render followed by a good // retry is swallowed as a recoverable error and never shows a strip). let shouldThrow = true const { container, service } = mountSidebar() service.registerTab({ id: 'crash-until-fixed', title: 'Crash until fixed', component: () => { if (shouldThrow) throw new Error('transient') return createElement('div', null, 'recovered') }, }) act(() => { service.openTab({ type: 'crash-until-fixed', title: 'Crash until fixed' }) }) expect(container.textContent).toContain('transient') const retry = [...container.querySelectorAll('button')] .find(button => button.textContent === t('terminalRetry')) expect(retry).toBeDefined() // The crash condition is gone (e.g. the data arrived): the retry button // remounts the tab's content and the strip clears. shouldThrow = false act(() => { retry!.click() }) expect(container.textContent).toContain('recovered') expect(container.textContent).not.toContain('transient') }) }) describe('store listener containment', () => { it('a throwing consumer listener cannot take the shell down', () => { const { container, service, store } = mountSidebar() const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) // A consumer plugin subscribes through the service's PUBLIC state seam // (subscribeState IS the store's subscribe) and throws while reading a // field this store no longer carries — the 0.19.0 shape that dropped the // right column's `splits` tree, i.e. a real third-party plugin's failure // mode rather than a synthetic one. const unsubscribe = service.subscribeState(() => { throw new Error('third-party listener boom') }) // The mutation drives notify() from inside act(); before the isolation // this call threw straight out of the store into the commit phase. expect(() => { act(() => { store.reduce(toggleBottomPanel) }) }).not.toThrow() // The shell is intact (the collapse control is still mounted) and the // mutation landed for everyone else. expect(container.textContent).not.toContain('dsh-better-sidebar:') expect(container.querySelector(`[aria-label="${t('collapseBottomPanel')}"]`)).not.toBeNull() expect(store.getSnapshot().state!.bottomOpen).toBe(true) // The crash is reported rather than swallowed silently. expect(errorSpy).toHaveBeenCalled() unsubscribe() errorSpy.mockRestore() }) })