Files
apes-sidebar/tests/prefs.spec.ts
T
Menghuan1918 5ee81fb073 feat(clues): collect resources from files, Feishu and GitHub, adapted to DSH 0.2.2-rc.2
This lands the clue collection line on top of origin/dev (v0.32.1, DSH
0.2.2-rc.2). The 14 commits that carried it are squashed into this one
because every one of them overlapped upstream's own changes (version,
19 dictionaries, CHANGELOG), and each intermediate commit would have
failed to compile against rc.2's menu API. The pre-integration head is
kept at backup/clues-uiux-refresh-pre-rebase.

What the feature is:
- a Clues tab that reads local files, Feishu tasks/docs and GitHub
  issues/pulls through one source registry, with a scope row, shared
  search, filters, paging and stable [[dsh-clue:...]] references;
- one window host for detail, pack management, source configuration,
  new pack and sharing (preview and edit are separate paths: a read is
  never saved over);
- .cluepack export/import with per-row resolvability previews;
- a source runtime that owns dependency installs and connection
  authorization (gh, lark-cli device code) and only probes on an
  explicit read;
- the public betterSidebarClues service and the windows capability
  (features gains clues / windowHost).

Merged with upstream rather than over it:
- the settings section keeps upstream's start-page takeover group and
  this branch's clue sources group; navigation is now six groups;
- the dictionaries keep both sides' new keys (1211 each, verified equal
  across all 19), the external-plugin guide and CHANGELOG keep both
  histories, and service features list both capability sets.

Adapted to 0.2.2-rc.2:
- menu call sites use anchorPoint instead of getAnchorRect;
- the shared SelectMenu mounts the host menu only while open, because
  rc.2's Menu reads the DOM during render and broke server-rendered
  settings surfaces;
- the submenu flip workaround stays deleted (the host positions
  submenus now), pinned by an updated layout-css assertion.

Version 0.33.0 (three synced spots) with a new 未发布 / Unreleased
changelog section; package.json regains the ./clues export, lib/clues.js
and the uqr dependency that upstream never had.

Gates: typecheck, lint, 5410 unit tests, build, check:consumer-types and
the full mount lane (35 passed) against dsh 0.2.2-rc.2 in Chromium.
2026-11-24 16:43:26 +08:00

371 lines
16 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest'
import {
awaitBootDecision,
loadBootDecision,
loadExternalDisable,
loadPrefs,
type BootDecision,
type SidebarSettingsClient,
} from '../src/client/prefs.ts'
import { SIDEBAR_PREFS_DEFAULTS } from '../src/prefs-shared.ts'
/** A fake settings wire face whose settingsGet resolves to one raw value. */
const wire = (value: unknown): SidebarSettingsClient => ({
settingsGet: async () => ({ value, revision: 1 }),
settingsUpdate: async () => ({ value, revision: 2 }),
})
/** A fake wire carrying an explicit externalDisable flag. */
const wireWithDisable = (externalDisable: boolean): SidebarSettingsClient => ({
settingsGet: async () => ({ value: {}, revision: 1, externalDisable }),
settingsUpdate: async () => ({ value: {}, revision: 2 }),
})
const rejecting = (): SidebarSettingsClient => ({
settingsGet: async () => { throw new Error('route rejected') },
settingsUpdate: async () => { throw new Error('route rejected') },
})
describe('side card preferences', () => {
it('falls back to the defaults when the settings route rejects', async () => {
expect(await loadPrefs(rejecting())).toEqual(SIDEBAR_PREFS_DEFAULTS)
})
it('falls back to the defaults when the value is absent or malformed', async () => {
expect(await loadPrefs(wire(undefined))).toEqual(SIDEBAR_PREFS_DEFAULTS)
expect(await loadPrefs(wire('garbage'))).toEqual(SIDEBAR_PREFS_DEFAULTS)
})
it('parses a valid value', async () => {
expect(await loadPrefs(wire({ autoOpenSubagent: false, agentOpenTools: true })))
.toEqual({
autoOpenSubagent: false,
autoOpenJobs: true,
tasksViewMode: 'graph',
tasksAutoFoldSettled: true,
tasksAutoFoldBranches: true,
tasksAutoFoldIdle: true,
jobsAutoCollapse: true,
mobileNoAutoOpen: true,
mobileDefaultTree: true,
agentOpenTools: true,
editorExplorer: false,
editorGitGutter: true,
explorerExclude: ['.DS_Store', 'Thumbs.db'],
customCss: '',
htmlViewerNoSandbox: false,
htmlViewerDefaultUnsafe: false,
clueSourcesEnabled: {},
clueSourcesMentionEnabled: {},
cluePacksMentionEnabled: true,
tabsEnabled: {},
viewersEnabled: {},
pluginSettings: {},
guideRows: 6,
guideOrder: [],
guideHidden: {},
guideAlign: 'center',
guideTakeover: true,
})
})
it('falls back per-field when a stored field is malformed', async () => {
expect(await loadPrefs(wire({ autoOpenSubagent: 'no', agentOpenTools: 'yes' })))
.toEqual({
autoOpenSubagent: true,
autoOpenJobs: true,
tasksViewMode: 'graph',
tasksAutoFoldSettled: true,
tasksAutoFoldBranches: true,
tasksAutoFoldIdle: true,
jobsAutoCollapse: true,
mobileNoAutoOpen: true,
mobileDefaultTree: true,
agentOpenTools: false,
editorExplorer: false,
editorGitGutter: true,
explorerExclude: ['.DS_Store', 'Thumbs.db'],
customCss: '',
htmlViewerNoSandbox: false,
htmlViewerDefaultUnsafe: false,
clueSourcesEnabled: {},
clueSourcesMentionEnabled: {},
cluePacksMentionEnabled: true,
tabsEnabled: {},
viewersEnabled: {},
pluginSettings: {},
guideRows: 6,
guideOrder: [],
guideHidden: {},
guideAlign: 'center',
guideTakeover: true,
})
})
it('defaults autoOpenSubagent to true and the agent toggles to false when the stored value is absent or malformed', async () => {
expect(await loadPrefs(wire({})))
.toEqual({
autoOpenSubagent: true,
autoOpenJobs: true,
tasksViewMode: 'graph',
tasksAutoFoldSettled: true,
tasksAutoFoldBranches: true,
tasksAutoFoldIdle: true,
jobsAutoCollapse: true,
mobileNoAutoOpen: true,
mobileDefaultTree: true,
agentOpenTools: false,
editorExplorer: false,
editorGitGutter: true,
explorerExclude: ['.DS_Store', 'Thumbs.db'],
customCss: '',
htmlViewerNoSandbox: false,
htmlViewerDefaultUnsafe: false,
clueSourcesEnabled: {},
clueSourcesMentionEnabled: {},
cluePacksMentionEnabled: true,
tabsEnabled: {},
viewersEnabled: {},
pluginSettings: {},
guideRows: 6,
guideOrder: [],
guideHidden: {},
guideAlign: 'center',
guideTakeover: true,
})
expect((await loadPrefs(wire({ autoOpenSubagent: 1 }))).autoOpenSubagent)
.toBe(true)
// The sidebar-open tool is OFF by default; only an explicit true turns it on.
expect((await loadPrefs(wire({}))).agentOpenTools)
.toBe(false)
expect((await loadPrefs(wire({ agentOpenTools: 1 }))).agentOpenTools)
.toBe(false)
expect((await loadPrefs(wire({ agentOpenTools: true }))).agentOpenTools)
.toBe(true)
// The job auto-open is ON by default; only an explicit false turns it off.
expect((await loadPrefs(wire({ autoOpenJobs: 1 }))).autoOpenJobs)
.toBe(true)
expect((await loadPrefs(wire({ autoOpenJobs: false }))).autoOpenJobs)
.toBe(false)
})
it('defaults automatic task folding and jobs collapse to on and preserves explicit booleans', async () => {
for (const key of ['tasksAutoFoldSettled', 'tasksAutoFoldBranches', 'tasksAutoFoldIdle', 'jobsAutoCollapse'] as const) {
expect(SIDEBAR_PREFS_DEFAULTS[key], key).toBe(true)
for (const malformed of [undefined, null, 'false', 0, [], {}]) {
expect((await loadPrefs(wire({ [key]: malformed })))[key], key).toBe(true)
}
expect((await loadPrefs(wire({ [key]: false })))[key], key).toBe(false)
expect((await loadPrefs(wire({ [key]: true })))[key], key).toBe(true)
}
})
it('defaults both mobile adaptations to on; only an explicit false disarms one', async () => {
// Absent or malformed → ON: a phone is exactly the case these exist for,
// and each one only changes what happens on a NARROW viewport.
for (const key of ['mobileNoAutoOpen', 'mobileDefaultTree'] as const) {
expect((await loadPrefs(wire({})))[key]).toBe(true)
expect((await loadPrefs(wire({ [key]: 'yes' })))[key]).toBe(true)
expect((await loadPrefs(wire({ [key]: 1 })))[key]).toBe(true)
// Explicit booleans survive verbatim.
expect((await loadPrefs(wire({ [key]: false })))[key]).toBe(false)
expect((await loadPrefs(wire({ [key]: true })))[key]).toBe(true)
}
})
it('defaults explorerExclude to the stock junk list; only a valid string array overrides it', async () => {
// Absent or malformed → the stock list.
expect((await loadPrefs(wire({}))).explorerExclude).toEqual(['.DS_Store', 'Thumbs.db'])
expect((await loadPrefs(wire({ explorerExclude: 'node_modules' }))).explorerExclude).toEqual(['.DS_Store', 'Thumbs.db'])
expect((await loadPrefs(wire({ explorerExclude: { a: 1 } }))).explorerExclude).toEqual(['.DS_Store', 'Thumbs.db'])
// Non-string entries drop out; blanks drop out; entries trim.
expect((await loadPrefs(wire({ explorerExclude: ['node_modules', 42, ' *.log ', '', null] }))).explorerExclude)
.toEqual(['node_modules', '*.log'])
// An explicit empty array means "exclude nothing" and survives verbatim.
expect((await loadPrefs(wire({ explorerExclude: [] }))).explorerExclude).toEqual([])
})
it('defaults editorExplorer to false; only an explicit true enables the merged editor-explorer', async () => {
// Absent or malformed → off (separate file windows are the default).
expect((await loadPrefs(wire({}))).editorExplorer).toBe(false)
expect((await loadPrefs(wire({ editorExplorer: 'yes' }))).editorExplorer).toBe(false)
expect((await loadPrefs(wire({ editorExplorer: 1 }))).editorExplorer).toBe(false)
// Explicit booleans survive verbatim.
expect((await loadPrefs(wire({ editorExplorer: false }))).editorExplorer).toBe(false)
expect((await loadPrefs(wire({ editorExplorer: true }))).editorExplorer).toBe(true)
})
it('no longer exposes a workspaceFence pref (the containment guard is gone)', async () => {
// The field was retired together with the fence: whatever a stored
// document (or a legacy profile) still carries, the typed prefs the client
// consumes do not have it — there is nothing left to arm or disarm.
expect('workspaceFence' in await loadPrefs(wire({}))).toBe(false)
expect('workspaceFence' in await loadPrefs(wire({ workspaceFence: true }))).toBe(false)
expect('workspaceFence' in await loadPrefs(wire({ workspaceFence: false }))).toBe(false)
})
it('defaults customCss to the empty string; only a stored string survives', async () => {
// The custom-CSS escape hatch is inert until the user writes something.
expect((await loadPrefs(wire({}))).customCss).toBe('')
expect((await loadPrefs(wire({ customCss: 7 }))).customCss).toBe('')
expect((await loadPrefs(wire({ customCss: 'html { }' }))).customCss).toBe('html { }')
})
it('IGNORES the retired title-bar keys: a stored document that still carries them parses', async () => {
// The whole title-bar strip mechanism (and its four preference keys) was
// removed. A settings document written by an older version still carries
// them — the host schema is OPEN, so they resolve through it untouched
// (see plugin-shape.spec.ts), and this typed face is what makes them
// inert: parsePrefs builds its result from DECLARED fields only, so the
// retired keys never reach the client and never come back on a write.
const stored = {
titleBarScheme: 'preset',
titleBarPresetId: 'dsh-desktop',
titleBarCompat: true,
titleBarStripPx: 56,
}
const parsed = await loadPrefs(wire({ ...stored, agentOpenTools: true }))
expect(parsed).toEqual({ ...SIDEBAR_PREFS_DEFAULTS, agentOpenTools: true })
for (const key of Object.keys(stored)) {
expect(key in parsed, `${key} must not survive into the parsed prefs`).toBe(false)
}
// A malformed retired value is just as harmless (nothing reads it).
const junk = await loadPrefs(wire({ titleBarScheme: 42, titleBarStripPx: 'yes' }))
expect(junk).toEqual(SIDEBAR_PREFS_DEFAULTS)
})
it('validates the per-tab / per-viewer enable maps (absent keys mean enabled)', async () => {
// A non-object map falls back to {} (everything enabled).
expect((await loadPrefs(wire({ tabsEnabled: 'nope' }))).tabsEnabled).toEqual({})
expect((await loadPrefs(wire({ viewersEnabled: [1, 2] }))).viewersEnabled).toEqual({})
// Non-boolean entries are dropped; boolean entries survive verbatim.
const parsed = await loadPrefs(wire({
tabsEnabled: { git: false, explorer: true, bad: 'yes' },
viewersEnabled: { image: false, code: 1 },
}))
expect(parsed.tabsEnabled).toEqual({ git: false, explorer: true })
expect(parsed.viewersEnabled).toEqual({ image: false })
})
it('validates the start-page preferences: rows >= 1, a clean order, boolean visibility', async () => {
// Rows are a maximum, 1-based, and malformed/zero values fall back to 6.
expect((await loadPrefs(wire({}))).guideRows).toBe(6)
for (const bad of [undefined, null, 0, -1, 2.5, '4', NaN]) {
expect((await loadPrefs(wire({ guideRows: bad }))).guideRows).toBe(6)
}
expect((await loadPrefs(wire({ guideRows: 1 }))).guideRows).toBe(1)
expect((await loadPrefs(wire({ guideRows: 42 }))).guideRows).toBe(42)
// The order keeps first-seen order, trims, drops blanks/non-strings and dedupes.
expect((await loadPrefs(wire({ guideOrder: [' b ', 'a', 'b', '', 3] }))).guideOrder)
.toEqual(['b', 'a'])
expect((await loadPrefs(wire({ guideOrder: 'a' }))).guideOrder).toEqual([])
// Visibility is an open boolean map; absent means visible.
expect((await loadPrefs(wire({ guideHidden: { a: true, b: false, c: 'yes' } }))).guideHidden)
.toEqual({ a: true, b: false })
expect((await loadPrefs(wire({ guideHidden: [] }))).guideHidden).toEqual({})
// Vertical alignment: only the two known values survive.
expect((await loadPrefs(wire({ guideAlign: 'top' }))).guideAlign).toBe('top')
expect((await loadPrefs(wire({ guideAlign: 'center' }))).guideAlign).toBe('center')
expect((await loadPrefs(wire({ guideAlign: 'bottom' }))).guideAlign).toBe('center')
// Takeover is on by default; only an explicit false disarms it.
expect((await loadPrefs(wire({}))).guideTakeover).toBe(true)
expect((await loadPrefs(wire({ guideTakeover: 'no' }))).guideTakeover).toBe(true)
expect((await loadPrefs(wire({ guideTakeover: false }))).guideTakeover).toBe(false)
})
})
describe('external disable (aionui-panel provider choice)', () => {
it('reads true when the host reports the aionui provider active', async () => {
expect(await loadExternalDisable(wireWithDisable(true))).toBe(true)
})
it('reads false when the host reports no external disable', async () => {
expect(await loadExternalDisable(wireWithDisable(false))).toBe(false)
})
it('reads false when the flag is absent or the wire rejects', async () => {
expect(await loadExternalDisable(wire({}))).toBe(false)
expect(await loadExternalDisable(rejecting())).toBe(false)
})
})
describe('boot decision (one fetch for prefs + external disable)', () => {
it('answers both decisions from a single settingsGet call', async () => {
let calls = 0
const counting = (): SidebarSettingsClient => ({
settingsGet: async () => { calls += 1; return { value: { autoOpenSubagent: false, editorExplorer: true }, revision: 1, externalDisable: true } },
settingsUpdate: async () => ({ value: {}, revision: 2 }),
})
const decision = await loadBootDecision(counting())
expect(calls, 'the boot path must fetch the settings document exactly once').toBe(1)
expect(decision.suspended).toBe(true)
expect(decision.prefs.autoOpenSubagent).toBe(false)
})
it('falls back to the defaults + not suspended on any failure', async () => {
const decision = await loadBootDecision(rejecting())
expect(decision).toEqual({ prefs: SIDEBAR_PREFS_DEFAULTS, suspended: false })
})
it('reads suspended false when the flag is absent', async () => {
const decision = await loadBootDecision(wire({ customCss: 'html { }' }))
expect(decision.suspended).toBe(false)
expect(decision.prefs.customCss).toBe('html { }')
})
})
/** A promise plus its resolver, for a settings read that answers late. */
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve!: (value: T) => void
const promise = new Promise<T>((settle) => { resolve = settle })
return { promise, resolve }
}
describe('boot decision timeout (slow settings route)', () => {
afterEach(() => { vi.useRealTimers() })
it('adopts a prefs answer that lands after the first-paint budget', async () => {
vi.useFakeTimers()
const view = deferred<{ value?: unknown; revision?: number; externalDisable?: boolean }>()
const slow: SidebarSettingsClient = {
settingsGet: () => view.promise,
settingsUpdate: async () => ({ value: {}, revision: 2 }),
}
const late: BootDecision[] = []
const pending = awaitBootDecision(slow, (decision) => { late.push(decision) }, 2000)
await vi.advanceTimersByTimeAsync(2000)
expect(await pending, 'the boot path mounts on the defaults at the budget').toBeNull()
expect(late, 'no answer exists yet, so nothing is applied').toEqual([])
// The SAME read answers after the budget. The store's own
// settings/document-updated path only fires on a DOCUMENT change, so this
// continuation is the only way a disabled third-party tab type (or the
// external-disable flag) reaches the store on a slow boot (#1159).
view.resolve({
value: { tabsEnabled: { 'dsh-mnemon:memory': false }, customCss: 'html { }' },
revision: 1,
externalDisable: true,
})
await vi.advanceTimersByTimeAsync(0)
expect(late).toHaveLength(1)
expect(late[0]?.prefs.tabsEnabled).toEqual({ 'dsh-mnemon:memory': false })
expect(late[0]?.prefs.customCss).toBe('html { }')
expect(late[0]?.suspended).toBe(true)
})
it('never runs the late continuation when the answer wins the race', async () => {
vi.useFakeTimers()
const late = vi.fn()
const decision = await awaitBootDecision(wire({ customCss: 'html { }' }), late, 2000)
expect(decision?.prefs.customCss).toBe('html { }')
expect(decision?.suspended).toBe(false)
await vi.advanceTimersByTimeAsync(2000)
expect(late, 'an in-time answer must not be applied twice').not.toHaveBeenCalled()
})
})