Files
orca/src/main/ipc/filesystem-commit-message-generation.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

582 lines
20 KiB
TypeScript

import path from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
handlers,
store,
withPlatform,
WORKSPACE_DIR,
WORKTREE_FEATURE_PATH,
getStagedCommitContextMock,
resolveCommitMessageSettingsMock,
generateCommitMessageFromContextMock,
cancelGenerateCommitMessageLocalMock,
cancelGeneratePullRequestFieldsLocalMock,
getSshGitProviderMock,
resetFilesystemIpcMocks
} from './filesystem-test-harness'
vi.mock('electron', async () => (await import('./filesystem-test-harness')).electronMock)
vi.mock('fs/promises', async () => (await import('./filesystem-test-harness')).fsPromisesMock)
vi.mock(
'../wsl-unc-delete',
async () => (await import('./filesystem-test-harness')).wslUncDeleteMock
)
vi.mock(
'../crash-reporting/crash-breadcrumb-store',
async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock
)
vi.mock(
'../local-downloaded-folder-promotion',
async () => (await import('./filesystem-test-harness')).folderPromotionMock
)
vi.mock(
'../git/status',
async () => (await import('./filesystem-test-harness')).gitStatusModuleMock
)
vi.mock(
'../git/check-ignored-paths',
async () => (await import('./filesystem-test-harness')).gitIgnoredPathsMock
)
vi.mock('../git/worktree', async () => (await import('./filesystem-test-harness')).gitWorktreeMock)
vi.mock(
'../providers/ssh-filesystem-dispatch',
async () => (await import('./filesystem-test-harness')).sshFilesystemDispatchMock
)
vi.mock(
'../providers/ssh-git-dispatch',
async () => (await import('./filesystem-test-harness')).sshGitDispatchMock
)
vi.mock(
'../text-generation/commit-message-text-generation',
async () => (await import('./filesystem-test-harness')).textGenerationModuleMock
)
vi.mock(
'../text-generation/pull-request-context',
async () => (await import('./filesystem-test-harness')).pullRequestContextMock
)
vi.mock(
'../source-control/pull-request-template',
async () => (await import('./filesystem-test-harness')).pullRequestTemplateMock
)
vi.mock(
'../source-control/pull-request-linked-issue',
async () => (await import('./filesystem-test-harness')).pullRequestLinkedIssueMock
)
import { registerFilesystemHandlers } from './filesystem'
import { invalidateAuthorizedRootsCache } from './registered-worktree-roots-cache'
describe('registerFilesystemHandlers', () => {
beforeEach(() => {
resetFilesystemIpcMocks()
// Reset module-level auth cache so each test starts with a fresh dirty
// flag — prevents stale worktree data from a prior test's cache rebuild.
invalidateAuthorizedRootsCache()
})
it('generates a local commit message from main-process staged context', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' }
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({
success: true,
message: 'Update README'
})
registerFilesystemHandlers(store as never)
await expect(
handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH
})
).resolves.toEqual({ success: true, message: 'Update README' })
expect(getStagedCommitContextMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH, {
admissionTier: 'interactive'
})
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(context, params, {
kind: 'local',
cwd: WORKTREE_FEATURE_PATH
})
})
it('uses one-shot resolved params for local commit message generation', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const sourceControlAiResolvedParams = {
agentId: 'codex' as const,
model: 'gpt-5.5',
thinkingLevel: 'high',
customPrompt: 'Use Conventional Commits.'
}
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({
success: true,
message: 'feat: update readme'
})
registerFilesystemHandlers(store as never)
await expect(
handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH,
sourceControlAiResolvedParams
})
).resolves.toEqual({ success: true, message: 'feat: update readme' })
expect(resolveCommitMessageSettingsMock).not.toHaveBeenCalled()
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(
context,
sourceControlAiResolvedParams,
{
kind: 'local',
cwd: WORKTREE_FEATURE_PATH
}
)
})
it('prepares the selected Codex account home before local generation', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' }
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({
success: true,
message: 'Update README'
})
registerFilesystemHandlers(store as never, {
prepareForCodexLaunch: () => '/managed/codex-home'
})
await handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH
})
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(
context,
params,
expect.objectContaining({
kind: 'local',
cwd: WORKTREE_FEATURE_PATH,
env: expect.objectContaining({ CODEX_HOME: '/managed/codex-home' })
})
)
})
it('routes local WSL project commit-message generation through the project runtime target', async () => {
await withPlatform('win32', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' }
const prepareForCodexLaunch = vi.fn(() => '\\\\wsl.localhost\\Ubuntu\\home\\tester\\.codex')
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({
success: true,
message: 'Update README'
})
const wslStore = {
...store,
getRepos: () => [
{
id: 'repo-1',
path: WORKTREE_FEATURE_PATH,
displayName: 'repo',
badgeColor: '#000',
addedAt: 0
}
],
getProjects: () => [
{
id: 'project-1',
sourceRepoIds: ['repo-1'],
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
}
],
getSettings: () => ({
workspaceDir: WORKSPACE_DIR,
localWindowsRuntimeDefault: { kind: 'windows-host' }
})
}
registerFilesystemHandlers(wslStore as never, { prepareForCodexLaunch })
await handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH
})
expect(getStagedCommitContextMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH, {
admissionTier: 'interactive',
wslDistro: 'Ubuntu'
})
expect(prepareForCodexLaunch).toHaveBeenCalledWith({
runtime: 'wsl',
wslDistro: 'Ubuntu'
})
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(
context,
params,
expect.objectContaining({
kind: 'local',
cwd: WORKTREE_FEATURE_PATH,
wslDistro: 'Ubuntu',
env: expect.objectContaining({ CODEX_HOME: '/home/tester/.codex' })
})
)
})
})
it('enriches the local commit context with a validated worktree linked issue', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini' }
const worktreeId = `repo-1::${WORKTREE_FEATURE_PATH}`
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({ success: true, message: 'Update' })
const linkedStore = {
...store,
getWorktreeMeta: (id: string) => (id === worktreeId ? { linkedIssue: 123 } : undefined)
}
registerFilesystemHandlers(linkedStore as never)
await handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH,
worktreeId
})
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(
{ ...context, linkedIssue: 123 },
params,
expect.objectContaining({ kind: 'local' })
)
})
// Why: folder-repo instances keep `::workspace:<uuid>` on the meta key while the
// request path is the stripped cwd. A strip-before-lookup "cleanup" would still
// pass plain-id tests and silently lose enrichment on second workspaces.
it('enriches local commit context when the worktree id carries a folder-repo workspace suffix', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini' }
const instanceId = `repo-1::${WORKTREE_FEATURE_PATH}::workspace:${'0'.repeat(8)}-0000-0000-0000-${'0'.repeat(12)}`
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({ success: true, message: 'Update' })
const getWorktreeMeta = vi.fn((id: string) =>
id === instanceId ? { linkedIssue: 9 } : undefined
)
registerFilesystemHandlers({ ...store, getWorktreeMeta } as never)
await handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH,
worktreeId: instanceId
})
expect(getWorktreeMeta).toHaveBeenCalledWith(instanceId)
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(
{ ...context, linkedIssue: 9 },
params,
expect.objectContaining({ kind: 'local' })
)
})
// Why: the renderer derives worktreePath from worktreeId, so a mismatched pair
// models an independent caller (relay/CLI/future), not a stale renderer context.
it('ignores an independently supplied id that does not own the requested worktree path', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini' }
const getWorktreeMeta = vi.fn(() => ({ linkedIssue: 123 }))
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({ success: true, message: 'Update' })
registerFilesystemHandlers({ ...store, getWorktreeMeta } as never)
await handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH,
worktreeId: `repo-1::${path.resolve('/workspace/repo-other')}`
})
expect(getWorktreeMeta).not.toHaveBeenCalled()
// Why: without this the assertion below passes vacuously on an early return.
expect(generateCommitMessageFromContextMock.mock.calls).toHaveLength(1)
expect(generateCommitMessageFromContextMock.mock.calls[0]?.[0]).not.toHaveProperty(
'linkedIssue'
)
})
it('enriches the SSH commit context from host meta using the remote path', async () => {
const context = { branch: 'main', stagedSummary: 'A\tremote.txt', stagedPatch: '+remote' }
const params = { agentId: 'custom', model: '', customAgentCommand: 'agent' }
const worktreeId = 'repo-1::/remote/repo'
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getSshGitProviderMock.mockReturnValue({
getStagedCommitContext: vi.fn().mockResolvedValue(context),
executeCommitMessagePlan: vi.fn()
})
generateCommitMessageFromContextMock.mockResolvedValue({ success: true, message: 'Add file' })
const linkedStore = {
...store,
getWorktreeMeta: (id: string) => (id === worktreeId ? { linkedIssue: 77 } : undefined)
}
registerFilesystemHandlers(linkedStore as never)
await handlers.get('git:generateCommitMessage')!(null, {
worktreePath: '/remote/repo',
worktreeId,
connectionId: 'conn-1'
})
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(
{ ...context, linkedIssue: 77 },
params,
expect.objectContaining({ kind: 'remote' })
)
})
it('returns a sanitized error when local agent account preparation fails', async () => {
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' }
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
registerFilesystemHandlers(store as never, {
prepareForCodexLaunch: () => {
throw new Error('failed to read /Users/alice/.codex/auth.json')
}
})
await expect(
handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH
})
).resolves.toEqual({
success: false,
error: 'Failed to prepare the selected agent account for commit message generation.'
})
expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled()
})
it('prepares the selected Claude auth environment before local generation', async () => {
const previousAnthropicApiKey = process.env.ANTHROPIC_API_KEY
process.env.ANTHROPIC_API_KEY = 'do-not-leak-managed-auth-conflict'
const context = {
branch: 'feature/ai',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'claude', model: 'haiku' }
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getStagedCommitContextMock.mockResolvedValue(context)
generateCommitMessageFromContextMock.mockResolvedValue({
success: true,
message: 'Update README'
})
try {
registerFilesystemHandlers(store as never, {
prepareForClaudeLaunch: async () => ({
configDir: '/managed/claude',
envPatch: { CLAUDE_CONFIG_DIR: '/managed/claude' },
stripAuthEnv: true,
provenance: 'managed:account-1'
})
})
await handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH
})
const target = generateCommitMessageFromContextMock.mock.calls[0]?.[2] as
| { env?: NodeJS.ProcessEnv }
| undefined
expect(target?.env).toEqual(
expect.objectContaining({
CLAUDE_CONFIG_DIR: '/managed/claude'
})
)
expect(target?.env?.ANTHROPIC_API_KEY).toBeUndefined()
} finally {
if (previousAnthropicApiKey === undefined) {
delete process.env.ANTHROPIC_API_KEY
} else {
process.env.ANTHROPIC_API_KEY = previousAnthropicApiKey
}
}
})
it('generates an SSH commit message using remote staged context and relay execution', async () => {
const context = {
branch: 'main',
stagedSummary: 'A\tremote.txt',
stagedPatch: '+remote'
}
const params = { agentId: 'custom', model: '', customAgentCommand: 'agent' }
const executeCommitMessagePlan = vi.fn()
const prepareForCodexLaunch = vi.fn(() => '/managed/codex-home')
const prepareForClaudeLaunch = vi.fn()
resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params })
getSshGitProviderMock.mockReturnValue({
getStagedCommitContext: vi.fn().mockResolvedValue(context),
executeCommitMessagePlan
})
generateCommitMessageFromContextMock.mockResolvedValue({
success: true,
message: 'Add remote file'
})
registerFilesystemHandlers(store as never, {
prepareForCodexLaunch,
prepareForClaudeLaunch
})
await expect(
handlers.get('git:generateCommitMessage')!(null, {
worktreePath: '/remote/repo',
connectionId: 'conn-1'
})
).resolves.toEqual({ success: true, message: 'Add remote file' })
expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(
context,
params,
expect.objectContaining({
kind: 'remote',
cwd: '/remote/repo',
missingBinaryLocation: 'remote PATH'
})
)
const target = generateCommitMessageFromContextMock.mock.calls[0]?.[2]
await target.execute(
{ binary: 'agent', args: [], stdinPayload: null, label: 'agent' },
'/cwd',
1,
'commit-message'
)
expect(executeCommitMessagePlan).toHaveBeenCalledWith(
{ binary: 'agent', args: [], stdinPayload: null, label: 'agent' },
'/cwd',
1,
'commit-message'
)
expect(prepareForCodexLaunch).not.toHaveBeenCalled()
expect(prepareForClaudeLaunch).not.toHaveBeenCalled()
})
it('routes SSH generation cancellations to separate provider operations', async () => {
const cancelGenerateCommitMessage = vi.fn().mockResolvedValue(undefined)
getSshGitProviderMock.mockReturnValue({ cancelGenerateCommitMessage })
registerFilesystemHandlers(store as never)
await handlers.get('git:cancelGenerateCommitMessage')!(null, {
worktreePath: '/remote/repo',
connectionId: 'conn-1'
})
await handlers.get('git:cancelGeneratePullRequestFields')!(null, {
worktreePath: '/remote/repo',
connectionId: 'conn-1'
})
expect(cancelGenerateCommitMessage).toHaveBeenNthCalledWith(1, '/remote/repo', 'commit-message')
expect(cancelGenerateCommitMessage).toHaveBeenNthCalledWith(
2,
'/remote/repo',
'pull-request-fields'
)
expect(cancelGenerateCommitMessageLocalMock).not.toHaveBeenCalled()
expect(cancelGeneratePullRequestFieldsLocalMock).not.toHaveBeenCalled()
})
it('does not call the generator when no staged changes exist', async () => {
resolveCommitMessageSettingsMock.mockReturnValue({
ok: true,
params: { agentId: 'codex', model: 'gpt-5.4-mini' }
})
getStagedCommitContextMock.mockResolvedValue(null)
registerFilesystemHandlers(store as never)
await expect(
handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH
})
).resolves.toEqual({ success: false, error: 'No staged changes to summarize.' })
expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled()
})
it('sanitizes local staged-context read failures before returning to the renderer', async () => {
resolveCommitMessageSettingsMock.mockReturnValue({
ok: true,
params: { agentId: 'codex', model: 'gpt-5.4-mini' }
})
getStagedCommitContextMock.mockRejectedValue(new Error('fatal: /secret/repo failed'))
registerFilesystemHandlers(store as never)
await expect(
handlers.get('git:generateCommitMessage')!(null, {
worktreePath: WORKTREE_FEATURE_PATH
})
).resolves.toEqual({ success: false, error: 'Failed to read staged changes.' })
expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled()
})
it('sanitizes SSH staged-context read failures before returning to the renderer', async () => {
resolveCommitMessageSettingsMock.mockReturnValue({
ok: true,
params: { agentId: 'codex', model: 'gpt-5.4-mini' }
})
getSshGitProviderMock.mockReturnValue({
getStagedCommitContext: vi.fn().mockRejectedValue(new Error('fatal: /remote/secret failed'))
})
registerFilesystemHandlers(store as never)
await expect(
handlers.get('git:generateCommitMessage')!(null, {
worktreePath: '/remote/repo',
connectionId: 'conn-1'
})
).resolves.toEqual({ success: false, error: 'Failed to read staged changes.' })
expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled()
})
})