fix(state): contain a throwing store listener instead of blanking the sidebar

`service.subscribeState` is the store's own `subscribe`, so a consumer
plugin's listener runs inside `notify()` — and `notify()` runs inline in
whatever call site mutated the store (`setSession` from the Sidebar's mount
effect, `reduce` from a click handler). A throw escaping that loop therefore
surfaces in the React commit phase, where the ROOT RenderBoundary in
index.tsx swaps the ENTIRE sidebar for its error strip.

Observed on a real install (DSH Desktop, this plugin 0.19.0 + a consumer
plugin): the consumer's listener still walked the right column's `splits`
tree, a field 0.19.0 dropped, so it threw "Cannot read properties of
undefined (reading 'kind')" from inside `notify()` and took the panel down
for every other plugin and for the user, with the sidebar stuck on the error
strip until a manual reload.

Isolate each listener with try/catch + console.error. React's own
useSyncExternalStore callback shares this loop, so the remaining subscribers
still receive the change and re-render.

Tests: two store-level cases (a throwing listener is contained and the rest
still get notified; later mutations still fan out) plus a shell-level case
that subscribes a throwing listener through the real service against the
real Sidebar. All three fail against the previous implementation.
This commit is contained in:
Jerryyyyy1 committed 2026-09-13 12:32:22 +08:00
1 parent 1fcf43ccbe
commit 7b61e1282b
4 files changed
+126 -4

No files matched your search

+4 -1
View File
@@ -657,7 +657,10 @@ interface BetterSidebarService {
/** 当前快照:激活 sessionId + 其状态(面板几何/打开的 tabs/展开集)+ prefs。
* session 未激活时 state/sessionId 为 undefined。 */
getSnapshot(): SidebarSnapshot
/** 订阅快照变化(会话切换/状态变更/prefs 写入);返回 disposer */
/** 订阅快照变化(会话切换/状态变更/prefs 写入);返回 disposer。
* listener 抛出的异常被逐个隔离并 `console.error`,既不中断其余监听器
* (含 React 自己的渲染订阅),也不会把整条侧栏换成错误条——所以
* listener 里读宿主 state 的字段仍请自己判空,别指望异常能当哨兵。 */
subscribeState(listener: () => void): () => void
/** 更新一个已打开 tab 的显示字段(title/path/meta);tab 不存在时 no-op */
updateTab(tabId: string, patch: { title?: string; path?: string; meta?: unknown }): void
+24 -1
View File
@@ -1235,8 +1235,31 @@ export class SidebarStore {
this.persistTimers.set(sessionId, timer)
}
/**
* Fan one store change out to every subscribed listener. A throwing
* listener is CONTAINED instead of aborting the loop.
*
* `service.subscribeState` hands this store's own `subscribe` to consumer
* plugins, and `notify()` runs inline in whatever call site mutated the
* store — `setSession` from the Sidebar's mount effect, `reduce` from a
* click handler. An exception escaping here therefore surfaces as a
* render/commit-phase error, and the shell's ROOT RenderBoundary swaps the
* ENTIRE sidebar for its error strip: one plugin misreading a field this
* store no longer carries (0.19.0 dropped the right column's `splits`
* tree) takes the panel down for every other plugin and for the user.
*
* Isolating per listener also keeps the remaining listeners running —
* React's own useSyncExternalStore callback shares this loop, so a crash
* in one subscriber no longer costs the healthy ones their re-render.
*/
private notify(): void {
for (const listener of [...this.listeners]) listener()
for (const listener of [...this.listeners]) {
try {
listener()
} catch (error) {
console.error('[dsh-better-sidebar] store listener error:', error)
}
}
}
}
+37 -1
View File
@@ -1,5 +1,6 @@
/**
* Sidebar crash tests — the two failure modes behind issue #31.
* 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
@@ -14,6 +15,14 @@
* 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).
*/
@@ -187,3 +196,30 @@ describe('tab crash containment', () => {
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()
})
})
+61 -1
View File
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
activateTab, allLeaves, BOTTOM_DEFAULT, BOTTOM_MIN, closeTab, CONVERSATION_MIN, createSidebarStore,
insertLeafAt, makeDefaultState, moveTab, moveTabToEdge, openDiffTab,
@@ -891,3 +891,63 @@ describe('URL reset escape hatch (issue #369)', () => {
expect(leaf.tabs.map(tab => tab.type)).toEqual([])
})
})
/**
* listener isolation. `service.subscribeState` is this store's own
* `subscribe`, so a consumer plugin's listener throws INSIDE notify() — and
* notify() runs inline in the mutating call site (setSession from the
* Sidebar's mount effect, reduce from a click handler). An escaping throw
* therefore lands in the React commit phase, where the shell's ROOT
* RenderBoundary swaps the whole sidebar for its error strip.
*/
describe('store listener isolation', () => {
// Same browser-global stubs as the blocks above: setSession → loadState
// reads window.location.search and localStorage.
beforeEach(() => {
const g = globalThis as Record<string, unknown>
g.window = { clearTimeout: () => {}, setTimeout: () => 0, innerWidth: 1024, innerHeight: 800, location: { search: '' } }
g.localStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {} }
})
afterEach(() => {
const g = globalThis as Record<string, unknown>
delete g.window
delete g.localStorage
})
it('contains a throwing listener and still delivers the change to the rest', () => {
const store = createSidebarStore()
const delivered: string[] = []
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
store.subscribe(() => {
delivered.push('throwing')
throw new Error('third-party listener boom')
})
store.subscribe(() => { delivered.push('healthy') })
// The mutation must not throw out of the store, and the throwing
// listener must not rob the healthy ones of their notification (React's
// own useSyncExternalStore callback shares this loop in the real shell).
expect(() => store.setSession('s1')).not.toThrow()
expect(delivered).toEqual(['throwing', 'healthy'])
// The mutation itself still landed.
expect(store.getSnapshot().sessionId).toBe('s1')
expect(store.getSnapshot().state).toBeDefined()
// The crash is reported, not swallowed silently.
expect(errorSpy).toHaveBeenCalled()
errorSpy.mockRestore()
})
it('keeps notifying every listener on later mutations (the loop recovers)', () => {
const store = createSidebarStore()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
let healthyCalls = 0
store.subscribe(() => { throw new Error('boom') })
store.subscribe(() => { healthyCalls += 1 })
store.setSession('s1')
const afterFirst = healthyCalls
// A later mutation notifies again: the throwing listener was neither
// dropped from the set nor left the loop half-iterated.
store.reduce(toggleBottomPanel)
expect(healthyCalls).toBe(afterFirst + 1)
errorSpy.mockRestore()
})
})