Files
orca/src/main/ipc/filesystem-watcher-large-batch.test.ts
T
Neil 7980ab9942 test: remove mock echoes and duplicate contracts that only reading finds (#23953)
* test: remove mock echoes and duplicate contracts that only reading finds

Two veins in one wave, both requiring the production path to be read rather than
pattern-matched.

Mock echoes (36 strongest candidates reviewed, 2 real): the flagged shape —
literals shared between a mock factory and an expect matcher — is almost always
a test feeding an input and asserting a transform. The two genuine echoes are in
`pty-management.test.ts`, where the handler returns
`getDaemonFolderAccessMismatch(identity)` verbatim, so asserting the mock's own
`evidence('allowed')` object and its `null` proved only the mock. One case's own
comment conceded the handler makes no decision. The branch-exercising cases in
that file stay.

Semantic sweep of 80 files no detector flagged, 27 junk cases removed. What it
found has no mechanical signature:
- a handler that is literally `() => getComputerUsePermissionStatus()`, so
  `resolves.toBe(result)` guarded nothing;
- "does not mutate a stale registration off Linux" whose refusal came from a
  DIFFERENT guard — `cli.ts` has no platform check, and the test's own mock made
  `resolveAppImageRuntimeIdentity` return null, which a sibling case already owns;
- "keeps probing a host that is still retained" asserting a no-op, because
  `retainScopes` only cancels queued probes and stores no state;
- two cases comparing against `referenceAllowedRoots`, a verbatim copy of the
  pre-change algorithm kept in the test file — expected values produced by the
  thing under test. The third such case stays: it calls the old algorithm to
  COUNT its work (100_000 containment checks vs 100), a real bound on the
  authorization hot path;
- a remote-folder refusal that came from the fake provider's own rejection
  message rather than any Orca guard;
- "advertises each capability once", where a duplicate entry is inert in
  production because membership is `includes`;
- an Antigravity `scaffold self-check` built on a hand-typed five-line screen —
  the exact fixture shape docs/reference/antigravity-readiness-evidence.md blames
  for five failed detector attempts — whose banner had already drifted to
  `Antigravity CLI 1.0.3` against a real captured `1.2.0`. The raw-capture
  provenance guard and the transcript checklist ratchet in that file stay.

No production file is touched and no test file is deleted.

* test: retire duplicate daemon and filesystem cases the sweep found

Continues the semantic sweep into src/main/ipc filesystem handlers and
src/main/daemon. 16 cases removed across 13 files; no production file touched.

The recurring shape is a case that reaches the same branch as its sibling by a
different-looking route:
- `parseArgs` is a flag-scanning loop, so "handles flags in any order" asserts the
  identical result object as the in-order case, and "throws with no args" lands on
  the same `Usage:` throw the two missing-flag cases already reach;
- an ENOENT case with "no code at all" and its sibling with a numeric transport
  code both fall through to the same `ENOENT_MESSAGE.test` branch;
- "establishes connection with hello handshake" and "receives stream events" are
  strict subsets of cases that require two matching authenticated sockets and a
  frame split inside a multibyte character.

Two were vacuous rather than duplicated: a fixture self-comparison asserting
`String.normalize` gives different NFC and NFD spellings, and a
`not.toThrow` batch case whose 200k events are truncated by
`MAX_BATCHED_WATCHER_EVENTS = 5_000` long before the argument spread it was
written to exercise.

One whole-file deletion was reversed: `freebuff-detection.test.ts` looked like a
table restatement, but the sibling detection test covers only dependency ordering
and platform gating, not freebuff/codebuff independence — and those two names
share a suffix, so it is the only guard against one shadowing the other.
2026-09-29 17:35:12 -07:00

150 lines
5.2 KiB
TypeScript

import { createWatcherSender } from './filesystem-watcher-test-sender'
import { join, resolve } from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { handleMock } = vi.hoisted(() => ({
handleMock: vi.fn()
}))
vi.mock('electron', () => ({
ipcMain: {
handle: handleMock
}
}))
vi.mock('fs/promises', () => ({
stat: vi.fn()
}))
vi.mock('@parcel/watcher', () => ({
subscribe: vi.fn()
}))
vi.mock('./filesystem-watcher-wsl', () => ({
createWslWatcher: vi.fn()
}))
vi.mock('../providers/ssh-filesystem-dispatch', () => ({
getSshFilesystemProvider: vi.fn(),
onSshFilesystemProviderRegistered: () => () => {}
}))
import { closeAllWatchers, registerFilesystemWatcherHandlers } from './filesystem-watcher'
import { stat } from 'node:fs/promises'
import { subscribe as subscribeParcelWatcher } from '@parcel/watcher'
import type { Event as WatcherEvent } from '@parcel/watcher'
import type { FsChangedPayload } from '../../shared/filesystem-entry-types'
import {
WATCH_BATCH_MAX_WAIT_MS,
WATCH_BATCH_TRAILING_MS
} from '../../shared/filesystem-watch-batch-window'
type HandlerMap = Record<string, (_event: unknown, args: unknown) => unknown>
describe('local filesystem watcher large batches', () => {
const handlers: HandlerMap = {}
beforeEach(async () => {
vi.useRealTimers()
handleMock.mockReset()
vi.mocked(stat).mockReset()
vi.mocked(subscribeParcelWatcher).mockReset()
for (const key of Object.keys(handlers)) {
delete handlers[key]
}
handleMock.mockImplementation((channel, handler) => {
handlers[channel] = handler
})
registerFilesystemWatcherHandlers()
await closeAllWatchers()
})
it('emits one overflow event for oversized native watcher batches', async () => {
vi.useFakeTimers()
vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as never)
let watcherCallback: ((err: Error | null, events: WatcherEvent[]) => void) | undefined
vi.mocked(subscribeParcelWatcher).mockImplementation(async (_root, callback) => {
watcherCallback = callback as typeof watcherCallback
return { unsubscribe: vi.fn() } as never
})
const worktreePath = resolve('/tmp/repo')
const sender = createWatcherSender(1)
await handlers['fs:watchWorktree']({ sender }, { worktreePath })
watcherCallback?.(
null,
Array.from({ length: 5_001 }, (_, index): WatcherEvent => ({
type: 'update',
path: join(worktreePath, `file-${index}.txt`)
}))
)
await vi.advanceTimersByTimeAsync(150)
expect(stat).toHaveBeenCalledTimes(1)
expect(sender.send).toHaveBeenCalledWith('fs:changed', {
worktreePath,
events: [{ kind: 'overflow', absolutePath: worktreePath }]
})
await closeAllWatchers()
vi.useRealTimers()
})
it('still coalesces a local burst on the shared trailing window', async () => {
vi.useFakeTimers()
vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as never)
let watcherCallback: ((err: Error | null, events: WatcherEvent[]) => void) | undefined
vi.mocked(subscribeParcelWatcher).mockImplementation(async (_root, callback) => {
watcherCallback = callback as typeof watcherCallback
return { unsubscribe: vi.fn() } as never
})
const worktreePath = resolve('/tmp/repo')
const filePath = join(worktreePath, 'a.ts')
const sender = createWatcherSender(1)
await handlers['fs:watchWorktree']({ sender }, { worktreePath })
watcherCallback?.(null, [{ type: 'update', path: filePath }])
watcherCallback?.(null, [{ type: 'update', path: filePath }])
await vi.advanceTimersByTimeAsync(WATCH_BATCH_TRAILING_MS - 1)
expect(sender.send).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1)
expect(sender.send).toHaveBeenCalledTimes(1)
expect(sender.send).toHaveBeenCalledWith('fs:changed', {
worktreePath,
events: [{ kind: 'update', absolutePath: filePath, isDirectory: true }]
})
await closeAllWatchers()
vi.useRealTimers()
})
it('still flushes a sustained local stream at the shared max wait', async () => {
vi.useFakeTimers()
vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as never)
let watcherCallback: ((err: Error | null, events: WatcherEvent[]) => void) | undefined
vi.mocked(subscribeParcelWatcher).mockImplementation(async (_root, callback) => {
watcherCallback = callback as typeof watcherCallback
return { unsubscribe: vi.fn() } as never
})
const worktreePath = resolve('/tmp/repo')
const sender = createWatcherSender(1)
await handlers['fs:watchWorktree']({ sender }, { worktreePath })
// Step under the trailing window so only the max wait can force a flush.
const step = 100
for (let elapsed = 0; elapsed <= WATCH_BATCH_MAX_WAIT_MS; elapsed += step) {
watcherCallback?.(null, [{ type: 'update', path: join(worktreePath, `f-${elapsed}.ts`) }])
if (elapsed < WATCH_BATCH_MAX_WAIT_MS) {
expect(sender.send).not.toHaveBeenCalled()
}
await vi.advanceTimersByTimeAsync(step)
}
expect(sender.send).toHaveBeenCalledTimes(1)
expect((sender.send.mock.calls[0][1] as FsChangedPayload).events).toHaveLength(6)
await closeAllWatchers()
vi.useRealTimers()
})
})