Files
apes-sidebar/tests/fs-watch.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

172 lines
7.1 KiB
TypeScript

/**
* Directory-watch spec: the file tree's live refresh rests on this module, so
* the tests use real directories and the real `fs.watch` rather than a stub —
* the debounce, the handle accounting and the error path are the behaviour
* being pinned.
*
* Timing note: `fs.watch` delivery is neither prompt nor one-to-one with the
* writes that caused it (macOS FSEvents batches on its own schedule, and a
* loaded machine stretches it further). The assertions below therefore pin
* the PROPERTIES the tree depends on — a change is reported, a burst is
* folded, an unwatched directory stays silent — instead of an exact event
* count, and every wait is given a budget far above the module's 150 ms
* debounce.
*/
import { describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { listDirectory } from '../src/fs-tree.ts'
import { createDirectoryWatchers, type DirectoryWatchEvent } from '../src/fs-watch.ts'
import { removeTree } from './temp-tree.ts'
/**
* Generous delivery budget: the module debounces at 150 ms, the OS adds its
* own latency. Kept under the suite-wide 30 s test timeout (22 s leaves room
* for the wait itself plus cleanup) but above the old 15 s: the vitest config
* already raised that clock because a STARVED worker lost this exact suite at
* 15000 ms, and this spec's own waitFor budget was overriding it on local
* full-suite runs. A genuinely silent watcher still fails, just with the real
* (never-delivered) verdict.
*/
const DELIVERY_TIMEOUT_MS = 22_000
/** Long enough for a second (tail) delivery to have surfaced, so "folded" means something. */
const SETTLE_MS = 1_000
/** One scratch tree with a directory to watch. */
const withScratch = (run: (dir: string) => Promise<void> | void): Promise<void> => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-watch-'))
const dir = join(root, 'watched')
mkdirSync(dir)
return Promise.resolve(run(dir)).finally(() => { removeTree(root) })
}
/** Sleep for a fixed window. */
const settle = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms))
/**
* macOS FSEvents needs a beat after `watch()` before it reports writes that
* happen immediately afterwards. Two full-suite runs on a loaded machine lost
* a positive-delivery case to a write that landed inside that window; the
* settle removes the startup race without weakening any assertion (a watcher
* that never reports still times out).
*/
const WATCH_SETTLE_MS = 300
describe('directory watchers', () => {
it('drops the level cache for a changed directory before it pushes', async () => {
await withScratch(async (dir) => {
const events: DirectoryWatchEvent[] = []
// Warm the listing cache with the pre-change level…
const before = await listDirectory(dir, 100)
expect(before.entries).toEqual([])
const watchers = createDirectoryWatchers(event => events.push(event), () => {})
try {
expect(watchers.add(dir)).toBe(true)
await settle(WATCH_SETTLE_MS)
writeFileSync(join(dir, 'new.txt'), 'x')
await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }, { timeout: DELIVERY_TIMEOUT_MS })
// …then the re-list the client is about to send must NOT be answered
// from that warm entry (the watcher invalidates before pushing).
const after = await listDirectory(dir, 100)
expect(after).not.toBe(before)
expect(after.entries.map(entry => entry.name)).toEqual(['new.txt'])
} finally {
watchers.close()
}
})
})
it('folds a burst of changes into a single notice', async () => {
await withScratch(async (dir) => {
const events: DirectoryWatchEvent[] = []
const watchers = createDirectoryWatchers(event => events.push(event), () => {})
try {
expect(watchers.add(dir)).toBe(true)
await settle(WATCH_SETTLE_MS)
// One save is several filesystem events; the tree re-lists the whole
// directory either way, so they must collapse. Twenty writes make the
// fold unambiguous even if the OS delivers one late tail batch.
for (let index = 0; index < 20; index++) writeFileSync(join(dir, `f${index}.txt`), 'x')
await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }, { timeout: DELIVERY_TIMEOUT_MS })
await settle(SETTLE_MS)
expect(events.length).toBeLessThanOrEqual(2)
for (const event of events) expect(event).toEqual({ dir })
} finally {
watchers.close()
}
})
})
it('stops reporting once a directory is unwatched or closed', async () => {
await withScratch(async (dir) => {
const events: DirectoryWatchEvent[] = []
const watchers = createDirectoryWatchers(event => events.push(event), () => {})
watchers.add(dir)
watchers.remove(dir)
// Removing twice is a no-op, never a throw.
watchers.remove(dir)
writeFileSync(join(dir, 'a.txt'), 'x')
// The waiting budget matches the positive case: a silent assertion is
// only meaningful if an event had ample time to arrive.
await settle(SETTLE_MS)
expect(events).toEqual([])
// Closing the whole set is idempotent too.
watchers.close()
watchers.close()
})
})
it('treats a repeat add as already-watched', async () => {
await withScratch(async (dir) => {
const events: DirectoryWatchEvent[] = []
const watchers = createDirectoryWatchers(event => events.push(event), () => {})
try {
expect(watchers.add(dir)).toBe(true)
// A second add must not install a second watcher — that would double
// every notice for the same directory.
expect(watchers.add(dir)).toBe(true)
await settle(WATCH_SETTLE_MS)
writeFileSync(join(dir, 'a.txt'), 'x')
await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }, { timeout: DELIVERY_TIMEOUT_MS })
await settle(SETTLE_MS)
expect(events.length).toBeLessThanOrEqual(2)
} finally {
watchers.close()
}
})
})
it('caps the handles one connection may hold', async () => {
await withScratch(async (dir) => {
const root = join(dir, '..')
const watchers = createDirectoryWatchers(() => {}, () => {})
try {
// The cap is 64: the first 64 directories are watched, the rest are
// refused rather than throwing, and a refusal evicts nothing.
let accepted = 0
for (let index = 0; index < 70; index++) {
const child = join(root, `child-${index}`)
mkdirSync(child)
if (watchers.add(child)) accepted += 1
}
expect(accepted).toBe(64)
} finally {
watchers.close()
}
})
})
it('reports an unwatchable directory instead of throwing', async () => {
const failures: string[] = []
const watchers = createDirectoryWatchers(() => {}, (dir) => { failures.push(dir) })
try {
const missing = join(tmpdir(), 'dsh-sidebar-watch-does-not-exist-42')
expect(watchers.add(missing)).toBe(false)
expect(failures).toEqual([missing])
} finally {
watchers.close()
}
})
})