mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
test: remove 292 low-value tests (#39673)
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
@@ -679,7 +679,6 @@
|
||||
2 test-no-wall-clock:src/main/ssh/orcad-exited-own-lock-windows.test.ts
|
||||
4 test-no-wall-clock:src/main/ssh/ssh-remote-commands.test.ts
|
||||
2 test-no-wall-clock:src/main/star-nag/service-direct-star.test.ts
|
||||
1 test-no-wall-clock:src/main/star-nag/service-force-show-races.test.ts
|
||||
3 test-no-wall-clock:src/main/star-nag/service-threshold-prompt.test.ts
|
||||
2 test-no-wall-clock:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts
|
||||
1 test-no-wall-clock:src/main/startup/login-shell-environment.test.ts
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -3147,7 +3147,6 @@
|
||||
"src/main/project-groups/nested-repo-discovery.test.ts": 394,
|
||||
"src/main/project-groups/nested-repo-import-target.test.ts": 58,
|
||||
"src/main/project-groups/nested-repo-import.test.ts": 55,
|
||||
"src/main/workspaces/execution-host/project-runtime-git-options.test.ts": 172,
|
||||
"src/main/workspaces/execution-host/project-runtime-git-router-store.test.ts": 1818,
|
||||
"src/main/workspaces/execution-host/project-runtime-git-router.test.ts": 192,
|
||||
"src/main/credentials/protected-secret-persistence-concurrency.test.ts": 68,
|
||||
@@ -3247,7 +3246,6 @@
|
||||
"src/main/workspaces/catalog/repo-git-username-enrichment.test.ts": 111,
|
||||
"src/main/repository-icons/repo-icon-autodetect.test.ts": 806,
|
||||
"src/main/repository-icons/repo-icon-file-detection.test.ts": 487,
|
||||
"src/main/workspaces/catalog/repo-worktrees.test.ts": 414,
|
||||
"src/main/ripgrep/bundled-ripgrep-path.test.ts": 78,
|
||||
"src/main/ripgrep/bundled-ripgrep-real.test.ts": 242,
|
||||
"src/main/ripgrep/bundled-ripgrep-text-search.test.ts": 707,
|
||||
@@ -4169,7 +4167,6 @@
|
||||
"src/main/runtime/workspaces/process-listing/worktree-ps-degraded-repo-scan.test.ts": 4596,
|
||||
"src/main/runtime/workspaces/process-listing/worktree-ps-host-scope.test.ts": 4104,
|
||||
"src/main/runtime/workspaces/process-listing/worktree-ps-unverifiable-terminals.test.ts": 4030,
|
||||
"src/main/runtime/workspaces/removal/worktree-rm-id-selector-path-spelling.test.ts": 4352,
|
||||
"src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts": 4756,
|
||||
"src/main/runtime/workspaces/catalog/worktree-scan-repeated-path.test.ts": 3834,
|
||||
"src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts": 419,
|
||||
@@ -4330,7 +4327,6 @@
|
||||
"src/main/ssh/connection/ssh-connection-file-transfer-session-lost.test.ts": 5247,
|
||||
"src/main/ssh/connection/ssh-connection-file-transfer.test.ts": 335,
|
||||
"src/main/ssh/connection/ssh-connection-generation.test.ts": 53,
|
||||
"src/main/ssh/connection/ssh-connection-github-probe.test.ts": 435,
|
||||
"src/main/ssh/connection/ssh-connection-gssapi-fallback.test.ts": 420,
|
||||
"src/main/ssh/connection/ssh-connection-host-key-pin-race.test.ts": 462,
|
||||
"src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts": 776,
|
||||
@@ -4410,7 +4406,6 @@
|
||||
"src/main/ssh/orcad-terminal-census-client.test.ts": 217,
|
||||
"src/main/ssh/orcad-tunneled-pairing.test.ts": 94,
|
||||
"src/main/ssh/orcad-unreachable-setup-release.test.ts": 2336,
|
||||
"src/main/ssh/orcad-update-admission-fence.test.ts": 397,
|
||||
"src/main/ssh/orcad-update-plan.test.ts": 642,
|
||||
"src/main/ssh/pinned-runtime-host-target.test.ts": 45,
|
||||
"src/main/ssh/plain-ssh-terminal/plain-ssh-terminal-args.test.ts": 49,
|
||||
@@ -4543,7 +4538,6 @@
|
||||
"src/main/startup/skill-share-deep-link-state.test.ts": 217,
|
||||
"src/main/startup/startup-diagnostics.test.ts": 39,
|
||||
"src/main/startup/windows-app-data-path.test.ts": 55,
|
||||
"src/main/startup/windows-install-dir-acl-probe.test.ts": 111,
|
||||
"src/main/startup/windows-install-dir-acl-recovery.test.ts": 614,
|
||||
"src/main/startup/windows-install-dir-acl-repair.win32.test.ts": 132,
|
||||
"src/main/startup/windows-install-dir-package-acl-grant.test.ts": 88,
|
||||
@@ -4562,7 +4556,6 @@
|
||||
"src/main/power/system-power-lifecycle.test.ts": 42,
|
||||
"src/main/power/system-resume-broadcast.test.ts": 67,
|
||||
"src/main/telemetry/burst-cap.test.ts": 177,
|
||||
"src/main/telemetry/chat-ui-launch-tip-cohort.test.ts": 235,
|
||||
"src/main/telemetry/classify-error.test.ts": 43,
|
||||
"src/main/telemetry/client-agent-dashboard-snapshot.test.ts": 201,
|
||||
"src/main/telemetry/client-deferred-start.test.ts": 8659,
|
||||
@@ -4622,7 +4615,6 @@
|
||||
"src/main/updater/updater.headless-serve-install.test.ts": 1744,
|
||||
"src/main/updater/updater.install-failure-cause.test.ts": 1595,
|
||||
"src/main/updater/updater.linux-externally-managed.test.ts": 1056,
|
||||
"src/main/updater/updater.linux-root-package-install.test.ts": 1741,
|
||||
"src/main/updater/mac-install/updater.mac-install.test.ts": 879,
|
||||
"src/main/updater/updater.nudge-campaign.test.ts": 1658,
|
||||
"src/main/updater/updater.prerelease-fallback.test.ts": 2731,
|
||||
@@ -4672,7 +4664,6 @@
|
||||
"src/main/window/createMainWindow-markdown-editor-focus.test.ts": 1084,
|
||||
"src/main/window/createMainWindow-recovery-reload-watchdog.test.ts": 1251,
|
||||
"src/main/window/createMainWindow-renderer-crash-recovery.test.ts": 1613,
|
||||
"src/main/window/createMainWindow-renderer-launch-failure.test.ts": 1242,
|
||||
"src/main/window/createMainWindow-startup-reveal.test.ts": 1185,
|
||||
"src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts": 2628,
|
||||
"src/main/window/createMainWindow-tray-minimize-close.test.ts": 1140,
|
||||
@@ -4702,7 +4693,6 @@
|
||||
"src/main/window/renderer-launch-failure-probe.test.ts": 60,
|
||||
"src/main/window/renderer-liveness-at-death.test.ts": 50,
|
||||
"src/main/window/renderer-publication-throttle.electron.test.ts": 5163,
|
||||
"src/main/window/renderer-recovery-prompt.test.ts": 120,
|
||||
"src/main/window/renderer-recovery-reload-watchdog.test.ts": 69,
|
||||
"src/main/window/runtime-renderer-notification-sender.test.ts": 54,
|
||||
"src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts": 100,
|
||||
@@ -6226,7 +6216,6 @@
|
||||
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts": 3927,
|
||||
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-output-side-effects.test.ts": 1128,
|
||||
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts": 683,
|
||||
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts": 724,
|
||||
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-reattach-admission.test.ts": 1636,
|
||||
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-recycled-pty-incarnation.test.ts": 787,
|
||||
"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-errors.test.ts": 1218,
|
||||
@@ -6582,7 +6571,6 @@
|
||||
"src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts": 1778,
|
||||
"src/renderer/src/hooks/useIssueMetadata.test.tsx": 344,
|
||||
"src/renderer/src/hooks/useMacTccAttributionSeveredNotice.test.tsx": 2358,
|
||||
"src/renderer/src/hooks/useMacosTccPromptNotice.test.tsx": 1989,
|
||||
"src/renderer/src/hooks/useMetadataListRequest.test.tsx": 266,
|
||||
"src/renderer/src/hooks/useModalReturnFocus.test.tsx": 1938,
|
||||
"src/renderer/src/hooks/usePrimarySelectionPaste.terminal-native-paste.test.tsx": 388,
|
||||
@@ -6689,7 +6677,6 @@
|
||||
"src/renderer/src/lib/code-editor-theme.test.ts": 101,
|
||||
"src/renderer/src/lib/code-host-error-copy.test.ts": 297,
|
||||
"src/renderer/src/lib/codex-pane-selection-lane.test.ts": 543,
|
||||
"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart-account-recheck.test.ts": 1758,
|
||||
"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart-shell-flap.test.ts": 1745,
|
||||
"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts": 2039,
|
||||
"src/renderer/src/lib/codex-stale-pane-account-identity.test.ts": 1823,
|
||||
@@ -6960,7 +6947,6 @@
|
||||
"src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts": 5258,
|
||||
"src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-lifecycle.test.ts": 2633,
|
||||
"src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-prompts.test.tsx": 4554,
|
||||
"src/renderer/src/lib/worktree-initial-terminal-seeding-twin-host.test.ts": 1862,
|
||||
"src/renderer/src/lib/worktree-live-terminal-surface-owners.test.ts": 266,
|
||||
"src/renderer/src/lib/worktree-operation-route-index.test.ts": 262,
|
||||
"src/renderer/src/lib/worktree-operation-route.test.ts": 342,
|
||||
@@ -7115,7 +7101,6 @@
|
||||
"src/renderer/src/store/github/repositories/wsl-stopped-distro-poll-refusal.test.ts": 696,
|
||||
"src/renderer/src/store/workspaces/host-isolation/host-twin-isolation.test.ts": 1889,
|
||||
"src/renderer/src/store/workspaces/host-isolation/host-twin-worktree-purge.test.ts": 1945,
|
||||
"src/renderer/src/store/plugins/appearance/plugin-icon-themes.test.ts": 365,
|
||||
"src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts": 435,
|
||||
"src/renderer/src/store/plugins/localization/plugin-language-packs.test.ts": 377,
|
||||
"src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts": 5216,
|
||||
|
||||
@@ -2,10 +2,9 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { committingSpawn } from './bind-first-pane.test-fixture'
|
||||
import './runtime-test-module-registration.spec'
|
||||
import { OrcaRuntimeService } from '../orca-runtime'
|
||||
import { createSideEffectRuntime } from './orca-runtime-test-scenario-builders.spec'
|
||||
import './orca-runtime-test-scenario-builders.spec'
|
||||
import type { RuntimeTerminalAgentStatusEvent } from '../terminal/output/terminal-agent-status-events'
|
||||
import {
|
||||
syncSinglePty,
|
||||
TEST_WORKTREE_PATH,
|
||||
expectStablePaneKeyEnv,
|
||||
store
|
||||
@@ -52,142 +51,6 @@ describe('OSC 7501 program status', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it("hands the store each chunk's facet before the rows that chunk publishes", async () => {
|
||||
const order: string[] = []
|
||||
const spawn = vi.fn().mockResolvedValue({ id: 'pty-order' })
|
||||
const runtime = new OrcaRuntimeService(store, undefined, {
|
||||
onTerminalAgentStatus: (event) => order.push(`status:${event.payload.state}`),
|
||||
onTerminalProgramStatusFacet: (event) => order.push(`facet:${event.facet?.state ?? 'none'}`)
|
||||
})
|
||||
runtime.setPtyController({
|
||||
spawn: committingSpawn(runtime, spawn),
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { command: 'brew', title: 'w' })
|
||||
|
||||
runtime.onPtyData('pty-order', '\x1b]7501;state=working:app=brew:progress=10\x1b\\', 1)
|
||||
runtime.onPtyData('pty-order', '\x1b]7501;state=done:app=brew\x1b\\', 2)
|
||||
|
||||
// Readers between status updates must never see done with a live facet.
|
||||
expect(order).toEqual(['facet:working', 'status:working', 'facet:done', 'status:done'])
|
||||
})
|
||||
|
||||
it('clears a live facet when its PTY exits but keeps a finished one', async () => {
|
||||
const facets: [string, string | null][] = []
|
||||
const spawn = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ id: 'pty-live' })
|
||||
.mockResolvedValueOnce({ id: 'pty-done' })
|
||||
const runtime = new OrcaRuntimeService(store, undefined, {
|
||||
onTerminalProgramStatusFacet: (event) =>
|
||||
facets.push([event.ptyId, event.facet?.state ?? null])
|
||||
})
|
||||
runtime.setPtyController({
|
||||
spawn: committingSpawn(runtime, spawn),
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { command: 'brew', title: 'a' })
|
||||
await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { command: 'brew', title: 'b' })
|
||||
|
||||
runtime.onPtyData('pty-live', '\x1b]7501;state=working:app=brew:progress=10\x1b\\', 1)
|
||||
runtime.onPtyData('pty-done', '\x1b]7501;state=done:app=brew\x1b\\', 1)
|
||||
await runtime.onPtyExit('pty-live', 0)
|
||||
await runtime.onPtyExit('pty-done', 0)
|
||||
|
||||
expect(facets).toEqual([
|
||||
['pty-live', 'working'],
|
||||
['pty-done', 'done'],
|
||||
['pty-live', null]
|
||||
])
|
||||
})
|
||||
|
||||
it("drives agent edges and the PTY's status from Claude's OSC 7501, not its glyph-less titles", () => {
|
||||
// Claude Code 2.1.302 drops title spinners after OSC 7501; only its program report distinguishes working from idle.
|
||||
const { runtime, batches } = createSideEffectRuntime()
|
||||
syncSinglePty(runtime)
|
||||
const osc7501 = (body: string) => `\x1b]7501;${body}\x1b\\`
|
||||
type PtyRecords = { ptysById: Map<string, { lastAgentStatus: string | null }> }
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own PTY record, which the public API does not expose.
|
||||
const records = runtime as unknown as PtyRecords
|
||||
const ptyStatus = () => records.ptysById.get('pty-1')?.lastAgentStatus
|
||||
|
||||
runtime.onPtyData('pty-1', `${osc7501('state=idle:app=claude-code')}\x1b]0;Claude Code\x07`, 1)
|
||||
expect(ptyStatus()).toBe('idle')
|
||||
runtime.onPtyData('pty-1', osc7501('state=working:app=claude-code'), 2)
|
||||
expect(ptyStatus()).toBe('working')
|
||||
runtime.onPtyData('pty-1', '\x1b]0;Fix the parser\x07', 3)
|
||||
expect(ptyStatus()).toBe('working')
|
||||
runtime.onPtyData('pty-1', osc7501('state=done:app=claude-code'), 4)
|
||||
expect(ptyStatus()).toBe('idle')
|
||||
|
||||
const edges = batches.flatMap((batch) =>
|
||||
batch.facts.filter((fact) => fact.kind === 'agent-working' || fact.kind === 'agent-idle')
|
||||
)
|
||||
expect(edges).toEqual([
|
||||
{ kind: 'agent-working' },
|
||||
{ kind: 'agent-idle', title: 'Fix the parser', status: 'idle' }
|
||||
])
|
||||
})
|
||||
|
||||
it("returns the PTY's status to its titles once the shell prompt follows a program's done", () => {
|
||||
const { runtime } = createSideEffectRuntime()
|
||||
syncSinglePty(runtime)
|
||||
const osc7501 = (body: string) => `\x1b]7501;${body}\x1b\\`
|
||||
type PtyRecords = {
|
||||
ptysById: Map<
|
||||
string,
|
||||
{ lastAgentStatus: string | null; lastExplicitAgentStatus?: { programAtRest?: boolean } }
|
||||
>
|
||||
}
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own PTY record, which the public API does not expose.
|
||||
const records = runtime as unknown as PtyRecords
|
||||
const pty = () => records.ptysById.get('pty-1')
|
||||
|
||||
runtime.onPtyData('pty-1', `\x1b]0;tf\x07${osc7501('state=done:app=terraform')}`, 1)
|
||||
expect(pty()?.lastAgentStatus).toBe('idle')
|
||||
expect(pty()?.lastExplicitAgentStatus?.programAtRest).toBe(true)
|
||||
runtime.onPtyData('pty-1', '\x1b]133;A\x07', 2)
|
||||
expect(pty()?.lastAgentStatus).toBeNull()
|
||||
expect(pty()?.lastExplicitAgentStatus?.programAtRest).toBeUndefined()
|
||||
runtime.onPtyData('pty-1', '\x1b]0;⠋ Gemini working\x07', 3)
|
||||
expect(pty()?.lastAgentStatus).toBe('working')
|
||||
})
|
||||
|
||||
it('re-classifies on an activity change without restamping the last title', () => {
|
||||
const { runtime } = createSideEffectRuntime()
|
||||
syncSinglePty(runtime)
|
||||
type PtyRecords = {
|
||||
ptysById: Map<string, { lastAgentStatus: string | null; lastOscTitleAt: number | null }>
|
||||
}
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own PTY record, which the public API does not expose.
|
||||
const records = runtime as unknown as PtyRecords
|
||||
const pty = () => records.ptysById.get('pty-1')
|
||||
|
||||
runtime.onPtyData('pty-1', '\x1b]0;Fix the parser\x07', 1)
|
||||
const titledAt = pty()?.lastOscTitleAt
|
||||
runtime.onPtyData('pty-1', '\x1b]7501;state=working:app=claude-code\x1b\\', 2)
|
||||
expect(pty()?.lastAgentStatus).toBe('working')
|
||||
expect(pty()?.lastOscTitleAt).toBe(titledAt)
|
||||
})
|
||||
|
||||
it("classifies a chunk's trailing glyph-less title by the program's activity for the prompt lifecycle", () => {
|
||||
const { runtime } = createSideEffectRuntime()
|
||||
syncSinglePty(runtime)
|
||||
type Lifecycle = { agentPromptLifecycleByPtyId: Map<string, { status: string | null }> }
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own lifecycle map, which the public API does not expose.
|
||||
const lifecycle = runtime as unknown as Lifecycle
|
||||
runtime.onPtyData(
|
||||
'pty-1',
|
||||
'\x1b]7501;state=working:app=claude-code\x1b\\\x1b]0;Fix the parser\x07',
|
||||
1
|
||||
)
|
||||
expect(lifecycle.agentPromptLifecycleByPtyId.get('pty-1')?.status).toBe('working')
|
||||
})
|
||||
|
||||
it('reports a lasting sign-in block as blocked instead of waiting out tui-idle (#37056, #28348)', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
onTestFinished(() => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import '../../../unused-default-rpc-methods.test-fixture'
|
||||
import './linear-agent-project-access.spec'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { RpcDispatcher } from '../../../dispatcher'
|
||||
import type { RpcRequest } from '../../../core'
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../../../../orca-runtime'
|
||||
import type * as LinearIssueMutationsModule from '../../../../../linear/linear-issue-mutations'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ createIssueForAgent: vi.fn() }))
|
||||
|
||||
vi.mock('../../../../../linear/linear-issue-mutations', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof LinearIssueMutationsModule>()),
|
||||
createIssueForAgent: mocks.createIssueForAgent
|
||||
}))
|
||||
|
||||
type LinearProjectResolverTester = {
|
||||
resolveLinearCreateProject(
|
||||
input: string,
|
||||
team: { id: string; workspaceId: string }
|
||||
): Promise<{
|
||||
id: string
|
||||
name: string
|
||||
}>
|
||||
readLinearProjectByIdForCreate(id: string, workspaceId: string): Promise<unknown>
|
||||
readLinearProjectsForCreate(query: string, workspaceId: string): Promise<unknown[]>
|
||||
readLinearProjectsByExactNameForCreate(name: string, workspaceId: string): Promise<unknown[]>
|
||||
}
|
||||
|
||||
type LinearCreateTester = LinearProjectResolverTester & {
|
||||
resolveLinearCreateTeam(
|
||||
teamInput: string | undefined,
|
||||
workspaceId: string | undefined,
|
||||
parent: unknown
|
||||
): Promise<{ id: string; key: string; name: string; workspaceId: string }>
|
||||
}
|
||||
|
||||
describe('Linear agent project access helpers', () => {
|
||||
it('resolves Linear projects by UUID before searching names', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const tester = runtime as unknown as LinearProjectResolverTester
|
||||
const readById = vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue({
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
name: 'Launch',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
} as never)
|
||||
const readByName = vi
|
||||
.spyOn(tester, 'readLinearProjectsForCreate')
|
||||
.mockResolvedValue([] as never)
|
||||
|
||||
await expect(
|
||||
tester.resolveLinearCreateProject('11111111-1111-4111-8111-111111111111', {
|
||||
id: 'team-1',
|
||||
workspaceId: 'workspace-1'
|
||||
})
|
||||
).resolves.toMatchObject({ id: '11111111-1111-4111-8111-111111111111' })
|
||||
expect(readById).toHaveBeenCalledWith(
|
||||
'11111111-1111-4111-8111-111111111111',
|
||||
'workspace-1',
|
||||
undefined
|
||||
)
|
||||
expect(readByName).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves Linear projects by trimmed case-insensitive exact name', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const tester = runtime as unknown as LinearProjectResolverTester
|
||||
vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never)
|
||||
const readByName = vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Launch',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
}
|
||||
] as never)
|
||||
const readExactName = vi
|
||||
.spyOn(tester, 'readLinearProjectsByExactNameForCreate')
|
||||
.mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Launch',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
}
|
||||
] as never)
|
||||
|
||||
await expect(
|
||||
tester.resolveLinearCreateProject(' launch ', { id: 'team-1', workspaceId: 'workspace-1' })
|
||||
).resolves.toMatchObject({ id: 'project-1' })
|
||||
expect(readByName).toHaveBeenCalledWith('launch', 'workspace-1', undefined)
|
||||
expect(readExactName).toHaveBeenCalledWith('launch', 'workspace-1', undefined)
|
||||
})
|
||||
|
||||
it('resolves Linear projects by URL slug without a paginated exact-name scan', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const tester = runtime as unknown as LinearProjectResolverTester
|
||||
vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never)
|
||||
vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
slugId: 'launch-d8f6c7e7',
|
||||
name: 'Launch',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
}
|
||||
] as never)
|
||||
const readExactName = vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate')
|
||||
|
||||
await expect(
|
||||
tester.resolveLinearCreateProject('LAUNCH-D8F6C7E7', {
|
||||
id: 'team-1',
|
||||
workspaceId: 'workspace-1'
|
||||
})
|
||||
).resolves.toMatchObject({ id: 'project-1' })
|
||||
expect(readExactName).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves same-named Linear projects by target team compatibility', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const tester = runtime as unknown as LinearProjectResolverTester
|
||||
vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never)
|
||||
vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([] as never)
|
||||
vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Launch',
|
||||
teams: [{ id: 'team-other', name: 'Other', key: 'OTH' }]
|
||||
},
|
||||
{
|
||||
id: 'project-2',
|
||||
name: 'launch',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
}
|
||||
] as never)
|
||||
|
||||
await expect(
|
||||
tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' })
|
||||
).resolves.toMatchObject({ id: 'project-2' })
|
||||
})
|
||||
|
||||
it('rejects ambiguous Linear project names with candidate ids', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const tester = runtime as unknown as LinearProjectResolverTester
|
||||
vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never)
|
||||
vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([] as never)
|
||||
vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Launch',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
},
|
||||
{
|
||||
id: 'project-2',
|
||||
name: 'launch',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
}
|
||||
] as never)
|
||||
|
||||
await expect(
|
||||
tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' })
|
||||
).rejects.toMatchObject({
|
||||
code: 'linear_invalid_project',
|
||||
data: {
|
||||
projects: [
|
||||
{ id: 'project-1', name: 'Launch' },
|
||||
{ id: 'project-2', name: 'launch' }
|
||||
]
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('fails closed when Linear project team membership cannot be verified', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const tester = runtime as unknown as LinearProjectResolverTester
|
||||
vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never)
|
||||
vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([] as never)
|
||||
vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Launch'
|
||||
}
|
||||
] as never)
|
||||
|
||||
await expect(
|
||||
tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' })
|
||||
).rejects.toMatchObject({
|
||||
code: 'linear_invalid_project',
|
||||
data: { project: { id: 'project-1', name: 'Launch', teams: [] } }
|
||||
})
|
||||
})
|
||||
|
||||
it('caps agent project lists globally and returns a narrow project DTO', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
vi.spyOn(runtime, 'linearListProjects').mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 'project-1',
|
||||
name: 'Launch',
|
||||
url: 'https://linear.app/acme/project/launch',
|
||||
workspaceId: 'workspace-1',
|
||||
workspaceName: 'Acme',
|
||||
content: 'internal notes',
|
||||
description: 'roadmap',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
},
|
||||
{
|
||||
id: 'project-2',
|
||||
name: 'Follow-up',
|
||||
workspaceId: 'workspace-2',
|
||||
workspaceName: 'Beta'
|
||||
}
|
||||
],
|
||||
hasMore: false
|
||||
} as never)
|
||||
|
||||
const result = await runtime.linearProjectListForAgents({ limit: 1, workspaceId: 'all' })
|
||||
|
||||
expect(result.projects).toHaveLength(1)
|
||||
expect(result.projects[0]).toMatchObject({
|
||||
id: 'project-1',
|
||||
name: 'Launch',
|
||||
url: 'https://linear.app/acme/project/launch',
|
||||
workspaceId: 'workspace-1',
|
||||
workspaceName: 'Acme',
|
||||
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
|
||||
})
|
||||
expect(result.projects[0]).not.toHaveProperty('content')
|
||||
expect(result.projects[0]).not.toHaveProperty('description')
|
||||
expect(result.meta).toMatchObject({ limit: 1, returned: 1, hasMore: true })
|
||||
})
|
||||
|
||||
it('passes the resolved project id into agent issue create', async () => {
|
||||
const createIssueForAgent = mocks.createIssueForAgent.mockReset().mockResolvedValue({
|
||||
id: 'issue-created',
|
||||
identifier: 'ENG-123',
|
||||
title: 'Follow up',
|
||||
url: 'https://linear.app/acme/issue/ENG-123',
|
||||
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
|
||||
state: null,
|
||||
parent: null,
|
||||
project: { id: 'project-1', name: 'Launch' }
|
||||
})
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const tester = runtime as unknown as LinearCreateTester
|
||||
vi.spyOn(tester, 'resolveLinearCreateTeam').mockResolvedValue({
|
||||
id: 'team-1',
|
||||
key: 'ENG',
|
||||
name: 'Engineering',
|
||||
workspaceId: 'workspace-1'
|
||||
})
|
||||
vi.spyOn(tester, 'resolveLinearCreateProject').mockResolvedValue({
|
||||
id: 'project-1',
|
||||
name: 'Launch'
|
||||
} as never)
|
||||
|
||||
const result = await runtime.linearIssueCreate({
|
||||
title: 'Follow up',
|
||||
teamInput: 'ENG',
|
||||
projectInput: 'Launch',
|
||||
writeId: '33333333-3333-4333-8333-333333333333'
|
||||
})
|
||||
|
||||
expect(result.issue.project).toMatchObject({ id: 'project-1', name: 'Launch' })
|
||||
expect(createIssueForAgent).toHaveBeenCalledWith(
|
||||
'team-1',
|
||||
'Follow up',
|
||||
undefined,
|
||||
'workspace-1',
|
||||
expect.objectContaining({
|
||||
id: '33333333-3333-4333-8333-333333333333',
|
||||
parentId: null,
|
||||
projectId: 'project-1'
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,252 +0,0 @@
|
||||
import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing'
|
||||
/** Preserve id/path spelling parity, while id remains ambiguous for same-host duplicate rows that path deduplicates. This resolver also deletes workspaces (#16243). */
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const electronMocks = vi.hoisted(() => {
|
||||
const ipcMain = {
|
||||
on: vi.fn(() => ipcMain),
|
||||
removeListener: vi.fn(() => ipcMain),
|
||||
emit: vi.fn(() => true)
|
||||
}
|
||||
return {
|
||||
BrowserWindow: { fromId: vi.fn((): unknown => null) },
|
||||
webContents: { fromId: vi.fn((): unknown => null) },
|
||||
ipcMain,
|
||||
app: { getPath: vi.fn(() => '/tmp'), isPackaged: false }
|
||||
}
|
||||
})
|
||||
vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => {
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeListingModule>()),
|
||||
listWorktreesStrict: listWorktreesStrictMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', () => electronMocks)
|
||||
|
||||
const listWorktreesStrictMock = vi.hoisted(() => vi.fn())
|
||||
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity'
|
||||
|
||||
const REPO_ID = 'repo-local'
|
||||
const REPO_PATH = '/srv/projects/app'
|
||||
const WORKTREE_PATH = '/srv/projects/workspaces/plugin-host'
|
||||
const CANONICAL_ID = `${REPO_ID}::${WORKTREE_PATH}`
|
||||
|
||||
const ID_SPELLINGS: [label: string, worktreePath: string, repoPath?: string][] = [
|
||||
['a trailing slash', `${WORKTREE_PATH}/`],
|
||||
['a doubled separator', '/srv/projects//workspaces/plugin-host'],
|
||||
['an NFD workspace name', '/srv/projects/workspaces/café-plugin'.normalize('NFD')],
|
||||
// #15598/#15616: a Windows registration records backslashes; git reports forward slashes.
|
||||
['a backslash Windows spelling', 'D:\\Agentic\\game2\\battle-core', 'D:/Agentic/game2']
|
||||
]
|
||||
|
||||
function scannedSpellingOf(storedPath: string): string {
|
||||
const slashed = /^[A-Za-z]:[\\/]/.test(storedPath) ? storedPath.replace(/\\/g, '/') : storedPath
|
||||
return slashed.normalize('NFC').replace(/\/+/g, '/').replace(/\/$/, '')
|
||||
}
|
||||
|
||||
/** One registered repo whose worktree meta is writable, so a delete's `forgetLocal` is observable. */
|
||||
function makeStore(repoPath: string = REPO_PATH) {
|
||||
const metaById: Record<string, Record<string, unknown>> = {}
|
||||
const store = {
|
||||
getRepo: (id: string) => store.getRepos().find((repo) => repo.id === id),
|
||||
getRepos: () => [
|
||||
{ id: REPO_ID, path: repoPath, displayName: 'app', badgeColor: 'blue', addedAt: 1 }
|
||||
],
|
||||
getAllWorktreeMeta: vi.fn(() => metaById),
|
||||
getWorktreeMeta: (id: string) => metaById[id],
|
||||
setWorktreeMeta: ({ id }: HostWorktreeTarget, meta: Record<string, unknown>) => {
|
||||
metaById[id] = { ...metaById[id], ...meta }
|
||||
return metaById[id]
|
||||
},
|
||||
removeWorktreeMeta: () => {},
|
||||
getAllWorktreeLineage: () => ({}),
|
||||
getAllWorkspaceLineage: () => ({}),
|
||||
removeWorktreeLineage: vi.fn(),
|
||||
removeWorkspaceLineage: vi.fn(),
|
||||
getGitHubCache: () => undefined as never,
|
||||
getSettings: () => ({
|
||||
workspaceDir: '/tmp/workspaces',
|
||||
nestWorkspaces: false,
|
||||
refreshLocalBaseRefOnWorktreeCreate: false,
|
||||
branchPrefix: 'none',
|
||||
branchPrefixCustom: ''
|
||||
}),
|
||||
getProjects: () => []
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
function scanReports(worktreePath: string, repoPath: string = REPO_PATH): void {
|
||||
listWorktreesStrictMock.mockResolvedValue([
|
||||
{ path: repoPath, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true },
|
||||
{ path: worktreePath, head: 'def', branch: 'feature', isBare: false, isMainWorktree: false }
|
||||
])
|
||||
}
|
||||
|
||||
type RemovalInternals = {
|
||||
resolveWorktreeRemovalTarget: (
|
||||
worktreeSelector: string,
|
||||
requiredHostId?: string
|
||||
) => Promise<{ id: string; repoId: string; path: string }>
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
listWorktreesStrictMock.mockReset()
|
||||
})
|
||||
|
||||
describe('worktree id selectors vs. the path spelling git reports (#16243)', () => {
|
||||
it.each(ID_SPELLINGS)(
|
||||
'resolves through the fleet path what `path:` resolves when the id carries %s',
|
||||
async (_label, storedPath, repoPath) => {
|
||||
scanReports(scannedSpellingOf(storedPath), repoPath)
|
||||
const runtime = new OrcaRuntimeService(makeStore(repoPath) as never)
|
||||
|
||||
const byPath = await runtime.showManagedWorktree(`path:${storedPath}`)
|
||||
await expect(
|
||||
runtime.showManagedWorktree(`id:${REPO_ID}::${storedPath}`)
|
||||
).resolves.toMatchObject({ id: byPath.id, path: byPath.path })
|
||||
}
|
||||
)
|
||||
|
||||
it.each(ID_SPELLINGS)(
|
||||
'resolves a host-qualified removal target when the id carries %s',
|
||||
async (_label, storedPath, repoPath) => {
|
||||
scanReports(scannedSpellingOf(storedPath), repoPath)
|
||||
const runtime = new OrcaRuntimeService(makeStore(repoPath) as never)
|
||||
const internals = runtime as unknown as RemovalInternals
|
||||
|
||||
await expect(
|
||||
internals.resolveWorktreeRemovalTarget(
|
||||
`id:${REPO_ID}::${storedPath}`,
|
||||
LOCAL_EXECUTION_HOST_ID
|
||||
)
|
||||
).resolves.toMatchObject({ repoId: REPO_ID, path: scannedSpellingOf(storedPath) })
|
||||
}
|
||||
)
|
||||
|
||||
it('still refuses an id whose path names a different workspace', async () => {
|
||||
scanReports(WORKTREE_PATH)
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
|
||||
await expect(
|
||||
runtime.showManagedWorktree(`id:${REPO_ID}::/srv/projects/workspaces/other-plugin`)
|
||||
).rejects.toThrow('selector_not_found')
|
||||
})
|
||||
|
||||
// STA-4343: matching across repo ids would delete a workspace the caller never confirmed.
|
||||
it('still refuses the same path under a different repo id', async () => {
|
||||
scanReports(WORKTREE_PATH)
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
|
||||
await expect(runtime.showManagedWorktree(`id:other-repo::${WORKTREE_PATH}/`)).rejects.toThrow(
|
||||
'selector_not_found'
|
||||
)
|
||||
})
|
||||
|
||||
it('still refuses a removal qualified to a host that does not own the repo id', async () => {
|
||||
scanReports(WORKTREE_PATH)
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
const internals = runtime as unknown as RemovalInternals
|
||||
|
||||
await expect(
|
||||
internals.resolveWorktreeRemovalTarget(`id:${CANONICAL_ID}/`, 'runtime:env-b')
|
||||
).rejects.toThrow('selector_not_found')
|
||||
})
|
||||
|
||||
it('keeps `id:` and `path:` agreeing on a dot segment neither canonicalizes', async () => {
|
||||
scanReports(WORKTREE_PATH)
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
const dotted = '/srv/projects/./workspaces/plugin-host'
|
||||
|
||||
await expect(runtime.showManagedWorktree(`path:${dotted}`)).rejects.toThrow(
|
||||
'selector_not_found'
|
||||
)
|
||||
await expect(runtime.showManagedWorktree(`id:${REPO_ID}::${dotted}`)).rejects.toThrow(
|
||||
'selector_not_found'
|
||||
)
|
||||
})
|
||||
|
||||
// Windows stores either slash spelling; the table above covers id folding, and these tests pin its limits (#15598/#15616).
|
||||
describe('Windows drive-letter spellings', () => {
|
||||
const WINDOWS_REPO = 'D:/Agentic/game2'
|
||||
const WINDOWS_WORKTREE = 'D:/Agentic/game2/battle-core'
|
||||
|
||||
it('folds drive-letter case only for Windows paths, never for a POSIX path', async () => {
|
||||
scanReports(WINDOWS_WORKTREE, WINDOWS_REPO)
|
||||
const windowsRuntime = new OrcaRuntimeService(makeStore(WINDOWS_REPO) as never)
|
||||
|
||||
// A Windows root is case-insensitive, as `path:` already treats it.
|
||||
await expect(
|
||||
windowsRuntime.showManagedWorktree(`id:${REPO_ID}::d:/agentic/game2/battle-core`)
|
||||
).resolves.toMatchObject({ path: WINDOWS_WORKTREE })
|
||||
|
||||
// A POSIX root is not: folding case there would merge distinct directories for a delete.
|
||||
scanReports(WORKTREE_PATH)
|
||||
const posixRuntime = new OrcaRuntimeService(makeStore() as never)
|
||||
|
||||
await expect(
|
||||
posixRuntime.showManagedWorktree(`id:${REPO_ID}::/SRV/projects/workspaces/plugin-host`)
|
||||
).rejects.toThrow('selector_not_found')
|
||||
})
|
||||
|
||||
it('does not fold a backslash inside a POSIX path, where it is a valid filename character', async () => {
|
||||
scanReports(WORKTREE_PATH)
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
|
||||
await expect(
|
||||
runtime.showManagedWorktree(`id:${REPO_ID}::/srv/projects\\workspaces\\plugin-host`)
|
||||
).rejects.toThrow('selector_not_found')
|
||||
})
|
||||
})
|
||||
|
||||
// Delete-capable id resolution must refuse duplicates even when path resolution deduplicates them.
|
||||
it('refuses a folded id when two same-repo rows spell one directory', async () => {
|
||||
listWorktreesStrictMock.mockResolvedValue([
|
||||
{ path: REPO_PATH, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true },
|
||||
{ path: WORKTREE_PATH, head: 'def', branch: 'feature', isBare: false, isMainWorktree: false },
|
||||
{
|
||||
path: '/srv/projects//workspaces/plugin-host',
|
||||
head: 'ghi',
|
||||
branch: 'feature-2',
|
||||
isBare: false,
|
||||
isMainWorktree: false
|
||||
}
|
||||
])
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
|
||||
await expect(runtime.showManagedWorktree(`id:${CANONICAL_ID}/`)).rejects.toThrow(
|
||||
'selector_ambiguous'
|
||||
)
|
||||
})
|
||||
|
||||
// Folder-workspace ids trim only a terminal slash; one before the instance suffix stays exact-only.
|
||||
it('keeps a folder-workspace id exact when a slash precedes the instance suffix', async () => {
|
||||
const instanceSuffix = '::workspace:123e4567-e89b-12d3-a456-426614174000'
|
||||
scanReports(WORKTREE_PATH)
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
|
||||
await expect(
|
||||
runtime.showManagedWorktree(`id:${REPO_ID}::${WORKTREE_PATH}/${instanceSuffix}`)
|
||||
).rejects.toThrow('selector_not_found')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['no repo boundary', 'not-an-id'],
|
||||
['an empty path', `${REPO_ID}::`]
|
||||
])('keeps exact matching for a malformed id with %s', async (_label, malformedId) => {
|
||||
scanReports(WORKTREE_PATH)
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
const internals = runtime as unknown as RemovalInternals
|
||||
|
||||
await expect(runtime.showManagedWorktree(`id:${malformedId}`)).rejects.toThrow(
|
||||
'selector_not_found'
|
||||
)
|
||||
await expect(
|
||||
internals.resolveWorktreeRemovalTarget(`id:${malformedId}`, LOCAL_EXECUTION_HOST_ID)
|
||||
).rejects.toThrow('selector_not_found')
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,6 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
readSkillDeleteRecoveryJournal,
|
||||
recoverSkillDeleteTransaction,
|
||||
skillDeleteJournalPath,
|
||||
writeSkillDeleteJournal,
|
||||
@@ -13,7 +12,7 @@ import {
|
||||
nativeSkillInstallFilesystem,
|
||||
type SkillInstallFilesystem
|
||||
} from '../skill-install-filesystem'
|
||||
import { writeSkillStateFile } from '../skill-install-provenance'
|
||||
import '../skill-install-provenance'
|
||||
import { skillDeleteStagedName } from './staging-names'
|
||||
|
||||
const roots: string[] = []
|
||||
@@ -58,72 +57,6 @@ async function exists(path: string): Promise<boolean> {
|
||||
return Boolean(await lstat(path).catch(() => null))
|
||||
}
|
||||
|
||||
describe('skill delete journal validation', () => {
|
||||
it('round-trips a valid journal', async () => {
|
||||
const { stateDirectory, root } = await fixture()
|
||||
const canonicalPath = join(root, 'demo')
|
||||
await writeSkillDeleteJournal(stateDirectory, journal(root, canonicalPath))
|
||||
expect(await readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).toMatchObject({
|
||||
operation: 'delete',
|
||||
phase: 'staged'
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when there is no journal', async () => {
|
||||
const { stateDirectory, root } = await fixture()
|
||||
expect(await readSkillDeleteRecoveryJournal(stateDirectory, join(root, 'demo'))).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses a move whose source escapes every allowed root', async () => {
|
||||
const { home, stateDirectory, root } = await fixture()
|
||||
const canonicalPath = join(root, 'demo')
|
||||
const escaped = join(home, 'elsewhere', 'demo')
|
||||
await writeSkillStateFile(
|
||||
skillDeleteJournalPath(stateDirectory, canonicalPath),
|
||||
journal(root, canonicalPath, {
|
||||
moves: [
|
||||
{
|
||||
sourcePath: escaped,
|
||||
stagedPath: join(home, 'elsewhere', skillDeleteStagedName('demo', 'id-1')),
|
||||
kind: 'canonical'
|
||||
}
|
||||
]
|
||||
})
|
||||
)
|
||||
await expect(readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).rejects.toThrow(
|
||||
'skill-delete-journal-invalid'
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses a staged path that is not our sibling naming convention', async () => {
|
||||
const { stateDirectory, root } = await fixture()
|
||||
const canonicalPath = join(root, 'demo')
|
||||
await writeSkillStateFile(
|
||||
skillDeleteJournalPath(stateDirectory, canonicalPath),
|
||||
journal(root, canonicalPath, {
|
||||
moves: [
|
||||
{ sourcePath: canonicalPath, stagedPath: join(root, 'demo.bak'), kind: 'canonical' }
|
||||
]
|
||||
})
|
||||
)
|
||||
await expect(readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).rejects.toThrow(
|
||||
'skill-delete-journal-invalid'
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses a movedCount larger than the move list', async () => {
|
||||
const { stateDirectory, root } = await fixture()
|
||||
const canonicalPath = join(root, 'demo')
|
||||
await writeSkillStateFile(
|
||||
skillDeleteJournalPath(stateDirectory, canonicalPath),
|
||||
journal(root, canonicalPath, { movedCount: 4 })
|
||||
)
|
||||
await expect(readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).rejects.toThrow(
|
||||
'skill-delete-journal-invalid'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('recoverSkillDeleteTransaction', () => {
|
||||
it('rolls a staged phase forward by removing the staged path', async () => {
|
||||
const { stateDirectory, root } = await fixture()
|
||||
@@ -173,21 +106,6 @@ describe('recoverSkillDeleteTransaction', () => {
|
||||
expect(await exists(skillDeleteJournalPath(stateDirectory, canonicalPath))).toBe(false)
|
||||
})
|
||||
|
||||
it('clears the journal when the recorded move was never performed', async () => {
|
||||
// Intent precedes rename: absent staged paths may never have moved and must not pin recovery forever.
|
||||
const { stateDirectory, root } = await fixture()
|
||||
const canonicalPath = join(root, 'demo')
|
||||
await mkdir(canonicalPath, { recursive: true })
|
||||
await writeSkillDeleteJournal(
|
||||
stateDirectory,
|
||||
journal(root, canonicalPath, { phase: 'staging' })
|
||||
)
|
||||
|
||||
await recoverSkillDeleteTransaction(stateDirectory, canonicalPath)
|
||||
expect(await exists(canonicalPath)).toBe(true)
|
||||
expect(await exists(skillDeleteJournalPath(stateDirectory, canonicalPath))).toBe(false)
|
||||
})
|
||||
|
||||
it('clears the journal on retry after an earlier pass already restored a move', async () => {
|
||||
const { home, stateDirectory, root } = await fixture()
|
||||
const canonicalPath = join(root, 'demo')
|
||||
@@ -220,45 +138,4 @@ describe('recoverSkillDeleteTransaction', () => {
|
||||
expect(await exists(canonicalPath)).toBe(true)
|
||||
expect(await exists(skillDeleteJournalPath(stateDirectory, canonicalPath))).toBe(false)
|
||||
})
|
||||
|
||||
it('restores canonical before alias-file, so no alias dangles mid-recovery', async () => {
|
||||
const { home, stateDirectory, root } = await fixture()
|
||||
const canonicalPath = join(root, 'demo')
|
||||
const aliasRoot = join(home, '.claude', 'skills', 'demo')
|
||||
await mkdir(aliasRoot, { recursive: true })
|
||||
const entry = journal(root, canonicalPath, {
|
||||
phase: 'staging',
|
||||
movedCount: 2,
|
||||
allowedRoots: [root, join(home, '.claude', 'skills')],
|
||||
// Reverse alias-first staging to restore canonical content before aliases.
|
||||
moves: [
|
||||
{
|
||||
sourcePath: join(aliasRoot, 'SKILL.md'),
|
||||
stagedPath: join(aliasRoot, skillDeleteStagedName('SKILL.md', 'id-2')),
|
||||
kind: 'alias-file'
|
||||
},
|
||||
{
|
||||
sourcePath: canonicalPath,
|
||||
stagedPath: join(root, skillDeleteStagedName('demo', 'id-1')),
|
||||
kind: 'canonical'
|
||||
}
|
||||
]
|
||||
})
|
||||
await mkdir(entry.moves[1].stagedPath, { recursive: true })
|
||||
await writeFile(entry.moves[0].stagedPath, 'link-stand-in')
|
||||
await writeSkillDeleteJournal(stateDirectory, entry)
|
||||
|
||||
const order: string[] = []
|
||||
await recoverSkillDeleteTransaction(stateDirectory, canonicalPath, {
|
||||
prepareExtractedSkill: async () => undefined,
|
||||
observeSkill: async () => {
|
||||
throw new Error('unused')
|
||||
},
|
||||
rename: async (_source, target) => {
|
||||
order.push(target)
|
||||
},
|
||||
remove: async () => undefined
|
||||
})
|
||||
expect(order).toEqual([canonicalPath, join(aliasRoot, 'SKILL.md')])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -99,16 +99,6 @@ describe('deleteSkills', () => {
|
||||
expect(await exists(join(aliasDirectory, 'notes.md'))).toBe(true)
|
||||
})
|
||||
|
||||
it('removes an emptied alias-file directory', async () => {
|
||||
const { home, stateDirectory, file } = await fixture()
|
||||
const aliasDirectory = join(home, '.codex', 'skills', 'demo')
|
||||
await mkdir(aliasDirectory, { recursive: true })
|
||||
await symlink(file, join(aliasDirectory, 'SKILL.md'))
|
||||
|
||||
await run(home, stateDirectory, await request(file))
|
||||
expect(await exists(aliasDirectory)).toBe(false)
|
||||
})
|
||||
|
||||
it('takes the lock an install of the same destination directory would take', async () => {
|
||||
const { home, stateDirectory, canonicalDirectory, file } = await fixture()
|
||||
// Use install's literal placement-directory lock key, never canonical-file realpath.
|
||||
|
||||
@@ -107,62 +107,6 @@ describe('skill provider placement reconciliation', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('creates a verified copy when a host-owned alias operation is denied', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-skill-placement-test-'))
|
||||
temporaryDirectories.push(root)
|
||||
const canonicalPath = join(root, 'canonical', 'private-skill')
|
||||
const providerRoot = join(root, 'provider')
|
||||
await mkdir(canonicalPath, { recursive: true })
|
||||
await writeFile(join(canonicalPath, 'SKILL.md'), 'private skill')
|
||||
const observed = await nativeSkillInstallFilesystem.observeSkill(canonicalPath)
|
||||
|
||||
const result = await reconcileSkillProviderPlacement({
|
||||
canonicalPath,
|
||||
skillName: 'private-skill',
|
||||
destination: { provider: 'claude', rootPath: providerRoot, readsCanonicalRoot: false },
|
||||
previousReceipt: null,
|
||||
packageDigest: observed.observedDigest,
|
||||
filesystem: {
|
||||
...nativeSkillInstallFilesystem,
|
||||
createAlias: async () => {
|
||||
throw new Error('injected-host-alias-denial')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ topology: 'independent-copy', status: 'installed' })
|
||||
expect(await readFile(join(providerRoot, 'private-skill', 'SKILL.md'), 'utf8')).toBe(
|
||||
'private skill'
|
||||
)
|
||||
})
|
||||
|
||||
it('uses host alias inspection when the client cannot stat the destination', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-skill-placement-test-'))
|
||||
temporaryDirectories.push(root)
|
||||
const canonicalPath = join(root, 'canonical', 'private-skill')
|
||||
const providerRoot = join(root, 'provider')
|
||||
await mkdir(canonicalPath, { recursive: true })
|
||||
await writeFile(join(canonicalPath, 'SKILL.md'), 'private skill')
|
||||
const observed = await nativeSkillInstallFilesystem.observeSkill(canonicalPath)
|
||||
const createAlias = vi.fn()
|
||||
|
||||
const result = await reconcileSkillProviderPlacement({
|
||||
canonicalPath,
|
||||
skillName: 'private-skill',
|
||||
destination: { provider: 'claude', rootPath: providerRoot, readsCanonicalRoot: false },
|
||||
previousReceipt: null,
|
||||
packageDigest: observed.observedDigest,
|
||||
filesystem: {
|
||||
...nativeSkillInstallFilesystem,
|
||||
createAlias,
|
||||
aliasTargets: async () => true
|
||||
}
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ topology: 'provider-alias', status: 'unchanged' })
|
||||
expect(createAlias).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates an owned copy even when host alias inspection returns false', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-skill-placement-test-'))
|
||||
temporaryDirectories.push(root)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { SkillScanCoalescer, SkillScanShedError } from './skill-scan-coalescer'
|
||||
import { SkillScanCoalescer } from './skill-scan-coalescer'
|
||||
|
||||
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
|
||||
let resolve!: (value: T) => void
|
||||
@@ -10,108 +10,6 @@ function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
|
||||
}
|
||||
|
||||
describe('SkillScanCoalescer', () => {
|
||||
it('collapses concurrent callers on one key into a single scan', async () => {
|
||||
const coalescer = new SkillScanCoalescer<number>(8)
|
||||
const gate = deferred<number>()
|
||||
let runs = 0
|
||||
const task = (): Promise<number> => {
|
||||
runs += 1
|
||||
return gate.promise
|
||||
}
|
||||
|
||||
const outcomes = Promise.all([
|
||||
coalescer.run('root', { ttlMs: 0 }, task),
|
||||
coalescer.run('root', { ttlMs: 0 }, task),
|
||||
coalescer.run('root', { ttlMs: 0 }, task)
|
||||
])
|
||||
gate.resolve(7)
|
||||
|
||||
expect((await outcomes).map((outcome) => outcome.value)).toEqual([7, 7, 7])
|
||||
expect((await outcomes).map((outcome) => outcome.cached)).toEqual([false, true, true])
|
||||
expect(runs).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps distinct keys isolated, including paths differing only by case', async () => {
|
||||
const coalescer = new SkillScanCoalescer<string>(8)
|
||||
const seen: string[] = []
|
||||
const run = (key: string): Promise<{ value: string }> =>
|
||||
coalescer.run(key, { ttlMs: 1_000 }, async () => {
|
||||
seen.push(key)
|
||||
return key
|
||||
})
|
||||
|
||||
const [lower, upper] = await Promise.all([run('/home/a/Skills'), run('/home/a/skills')])
|
||||
|
||||
expect(lower.value).toBe('/home/a/Skills')
|
||||
expect(upper.value).toBe('/home/a/skills')
|
||||
expect(seen).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('reuses a result inside the ttl and rescans after it lapses', async () => {
|
||||
let now = 1_000
|
||||
const coalescer = new SkillScanCoalescer<number>(8, () => now)
|
||||
let runs = 0
|
||||
const task = async (): Promise<number> => {
|
||||
runs += 1
|
||||
return runs
|
||||
}
|
||||
|
||||
expect((await coalescer.run('root', { ttlMs: 100 }, task)).cached).toBe(false)
|
||||
now = 1_050
|
||||
const cached = await coalescer.run('root', { ttlMs: 100 }, task)
|
||||
expect(cached).toEqual({ value: 1, cached: true })
|
||||
now = 1_101
|
||||
expect(await coalescer.run('root', { ttlMs: 100 }, task)).toEqual({ value: 2, cached: false })
|
||||
expect(runs).toBe(2)
|
||||
})
|
||||
|
||||
it('retains nothing when the ttl is zero', async () => {
|
||||
const coalescer = new SkillScanCoalescer<number>(8)
|
||||
let runs = 0
|
||||
const task = async (): Promise<number> => {
|
||||
runs += 1
|
||||
return runs
|
||||
}
|
||||
|
||||
await coalescer.run('root', { ttlMs: 0 }, task)
|
||||
await coalescer.run('root', { ttlMs: 0 }, task)
|
||||
|
||||
expect(runs).toBe(2)
|
||||
})
|
||||
|
||||
it('bypasses cached and in-flight results when refreshing', async () => {
|
||||
let now = 1_000
|
||||
const coalescer = new SkillScanCoalescer<number>(8, () => now)
|
||||
let runs = 0
|
||||
const task = async (): Promise<number> => {
|
||||
runs += 1
|
||||
return runs
|
||||
}
|
||||
|
||||
await coalescer.run('root', { ttlMs: 10_000 }, task)
|
||||
const refreshed = await coalescer.run('root', { ttlMs: 10_000, refresh: true }, task)
|
||||
|
||||
expect(refreshed).toEqual({ value: 2, cached: false })
|
||||
expect(await coalescer.run('root', { ttlMs: 10_000 }, task)).toEqual({ value: 2, cached: true })
|
||||
expect(runs).toBe(2)
|
||||
})
|
||||
|
||||
// Refresh fan-out needs per-key publish ownership; a global counter would cache only the last root.
|
||||
it('caches every key when a refresh fans out across roots', async () => {
|
||||
const coalescer = new SkillScanCoalescer<string>(64)
|
||||
const keys = ['root-a', 'root-b', 'root-c', 'root-d']
|
||||
|
||||
await Promise.all(
|
||||
keys.map((key) => coalescer.run(key, { ttlMs: 10_000, refresh: true }, async () => key))
|
||||
)
|
||||
const readBack = await Promise.all(
|
||||
keys.map((key) => coalescer.run(key, { ttlMs: 10_000 }, async () => 're-walked'))
|
||||
)
|
||||
|
||||
expect(readBack.map((outcome) => outcome.cached)).toEqual([true, true, true, true])
|
||||
expect(readBack.map((outcome) => outcome.value)).toEqual(keys)
|
||||
})
|
||||
|
||||
it('does not let a scan that started before a refresh publish its stale result', async () => {
|
||||
const coalescer = new SkillScanCoalescer<string>(8)
|
||||
const slowScan = deferred<string>()
|
||||
@@ -148,133 +46,4 @@ describe('SkillScanCoalescer', () => {
|
||||
cached: false
|
||||
})
|
||||
})
|
||||
|
||||
it('does not cache a failed scan', async () => {
|
||||
const coalescer = new SkillScanCoalescer<number>(8)
|
||||
let runs = 0
|
||||
|
||||
await expect(
|
||||
coalescer.run('root', { ttlMs: 10_000 }, async () => {
|
||||
runs += 1
|
||||
throw new Error('scan failed')
|
||||
})
|
||||
).rejects.toThrow('scan failed')
|
||||
expect(await coalescer.run('root', { ttlMs: 10_000 }, async () => 5)).toEqual({
|
||||
value: 5,
|
||||
cached: false
|
||||
})
|
||||
expect(runs).toBe(1)
|
||||
})
|
||||
|
||||
it('evicts the least recently used entry past the bound', async () => {
|
||||
let now = 1_000
|
||||
const coalescer = new SkillScanCoalescer<string>(2, () => now)
|
||||
const scan = (key: string): Promise<{ cached: boolean }> =>
|
||||
coalescer.run(key, { ttlMs: 10_000 }, async () => key)
|
||||
|
||||
await scan('a')
|
||||
await scan('b')
|
||||
expect((await scan('a')).cached).toBe(true)
|
||||
await scan('c')
|
||||
|
||||
expect((await scan('a')).cached).toBe(true)
|
||||
expect((await scan('b')).cached).toBe(false)
|
||||
})
|
||||
|
||||
// Use nonzero TTL to expose abandoned scans incorrectly publishing over replacements.
|
||||
it('stops joining a scan that never settles, and never lets it publish later', async () => {
|
||||
let now = 1_000
|
||||
const coalescer = new SkillScanCoalescer<number>(8, () => now)
|
||||
const wedged = deferred<number>()
|
||||
let runs = 0
|
||||
const task = (signal: AbortSignal): Promise<number> => {
|
||||
runs += 1
|
||||
// Model a stalled mount whose syscall never settles.
|
||||
return runs === 1
|
||||
? Promise.race([
|
||||
wedged.promise,
|
||||
new Promise<number>((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason))
|
||||
})
|
||||
])
|
||||
: Promise.resolve(runs)
|
||||
}
|
||||
|
||||
void coalescer.run('root', { ttlMs: 10_000 }, task).catch(() => undefined)
|
||||
now = 1_100
|
||||
const joined = coalescer.run('root', { ttlMs: 10_000 }, task)
|
||||
now = 40_000
|
||||
|
||||
expect(await coalescer.run('root', { ttlMs: 10_000 }, task)).toEqual({
|
||||
value: 2,
|
||||
cached: false
|
||||
})
|
||||
expect(runs).toBe(2)
|
||||
|
||||
// Abort releases abandoned-scan callers even if the mount never answers.
|
||||
await expect(joined).rejects.toThrow()
|
||||
wedged.resolve(99)
|
||||
expect(await coalescer.run('root', { ttlMs: 10_000 }, task)).toEqual({ value: 2, cached: true })
|
||||
})
|
||||
|
||||
it('aborts the scan it abandons so its walk stops doing filesystem work', async () => {
|
||||
let now = 1_000
|
||||
const coalescer = new SkillScanCoalescer<number>(8, () => now)
|
||||
const signals: AbortSignal[] = []
|
||||
const task = (signal: AbortSignal): Promise<number> => {
|
||||
signals.push(signal)
|
||||
return signals.length === 1 ? new Promise<number>(() => {}) : Promise.resolve(2)
|
||||
}
|
||||
|
||||
void coalescer.run('root', { ttlMs: 10_000 }, task).catch(() => undefined)
|
||||
expect(signals[0].aborted).toBe(false)
|
||||
now = 40_000
|
||||
await coalescer.run('root', { ttlMs: 10_000 }, task)
|
||||
|
||||
expect(signals[0].aborted).toBe(true)
|
||||
// The new owner must not be aborted with its predecessor.
|
||||
expect(signals[1].aborted).toBe(false)
|
||||
})
|
||||
|
||||
// Keep healthy superseded callers alive; publish ownership already prevents stale caching.
|
||||
it('does not abort the scan a refresh supersedes', async () => {
|
||||
const coalescer = new SkillScanCoalescer<string>(8)
|
||||
const slowScan = deferred<string>()
|
||||
const signals: AbortSignal[] = []
|
||||
|
||||
const inFlight = coalescer.run('root', { ttlMs: 10_000 }, (signal) => {
|
||||
signals.push(signal)
|
||||
return slowScan.promise
|
||||
})
|
||||
await coalescer.run('root', { ttlMs: 10_000, refresh: true }, async () => 'after-install')
|
||||
|
||||
expect(signals[0].aborted).toBe(false)
|
||||
slowScan.resolve('before-install')
|
||||
expect((await inFlight).value).toBe('before-install')
|
||||
})
|
||||
|
||||
// A stuck syscall cannot settle on abort; budget abandoned scans until actual completion.
|
||||
it('sheds a replacement once too many abandoned scans are still live', async () => {
|
||||
let now = 1_000
|
||||
const coalescer = new SkillScanCoalescer<number>(64, () => now)
|
||||
const task = (): Promise<number> => new Promise<number>(() => {})
|
||||
const keys = Array.from({ length: 17 }, (_unused, index) => `root-${index}`)
|
||||
|
||||
// Each stalled root spends abandonment budget when a caller seeks a replacement.
|
||||
for (const key of keys) {
|
||||
void coalescer.run(key, { ttlMs: 10_000 }, task).catch(() => undefined)
|
||||
}
|
||||
now = 40_000
|
||||
const shed: string[] = []
|
||||
for (const key of keys) {
|
||||
void coalescer.run(key, { ttlMs: 10_000 }, task).catch((error: unknown) => {
|
||||
if (error instanceof SkillScanShedError) {
|
||||
shed.push(key)
|
||||
}
|
||||
})
|
||||
}
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
expect(shed).toEqual(['root-16'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -213,23 +213,4 @@ describe('skill transaction startup recovery', () => {
|
||||
expect(await readFile(join(installed.canonicalPath, 'SKILL.md'), 'utf8')).toContain('# Keep')
|
||||
expect(await readSkillInstallReceipt(stateDirectory, installed.canonicalPath)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('bounds corrupt journal scanning and leaves unknown files untouched', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-skill-startup-bounds-test-'))
|
||||
roots.push(root)
|
||||
const stateDirectory = join(root, 'state')
|
||||
const journalDirectory = join(stateDirectory, 'journals')
|
||||
await mkdir(journalDirectory, { recursive: true })
|
||||
await Promise.all(
|
||||
Array.from({ length: 65 }, (_, index) =>
|
||||
writeFile(join(journalDirectory, `${String(index).padStart(2, '0')}.json`), '{}')
|
||||
)
|
||||
)
|
||||
|
||||
const report = await recoverPendingSkillTransactions(stateDirectory)
|
||||
|
||||
expect(report).toMatchObject({ scanned: 0, recovered: 0, truncated: true })
|
||||
expect(report.failures).toHaveLength(64)
|
||||
expect(await readFile(join(journalDirectory, '00.json'), 'utf8')).toBe('{}')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { resetSshConnectionMocks, spawnSystemSshCommandMock } from './ssh-connection-test-harness'
|
||||
import {
|
||||
createCallbacks,
|
||||
createFailingSystemCommandChannel,
|
||||
createResolvedConfig,
|
||||
createTarget
|
||||
} from './ssh-connection-test-fixtures'
|
||||
import { SshConnection } from './ssh-connection'
|
||||
import { resolveWithSshG } from '../config/ssh-g-config-resolution'
|
||||
|
||||
vi.mock('../ssh2-module-load', async () =>
|
||||
(await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule()
|
||||
)
|
||||
vi.mock('../system-transport/system-ssh-binary', async () =>
|
||||
(await import('./ssh-connection-test-harness')).createSystemSshBinaryModule()
|
||||
)
|
||||
vi.mock('../system-transport/system-ssh-args', async (importOriginal) =>
|
||||
(await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal())
|
||||
)
|
||||
vi.mock('../system-transport/system-ssh-command', async (importOriginal) =>
|
||||
(await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal())
|
||||
)
|
||||
vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) =>
|
||||
(await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks(
|
||||
await importOriginal()
|
||||
)
|
||||
)
|
||||
vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) =>
|
||||
(await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks(
|
||||
await importOriginal()
|
||||
)
|
||||
)
|
||||
vi.mock('../ssh-control-socket', async () =>
|
||||
(await import('./ssh-connection-test-harness')).createControlSocketModule()
|
||||
)
|
||||
vi.mock('../config/ssh-config-parser', async () =>
|
||||
(await import('./ssh-connection-test-harness')).createSshConfigParserModule()
|
||||
)
|
||||
vi.mock('../config/ssh-g-config-resolution', async (importOriginal) =>
|
||||
(await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks(
|
||||
await importOriginal()
|
||||
)
|
||||
)
|
||||
|
||||
describe('SshConnection', () => {
|
||||
beforeEach(() => {
|
||||
resetSshConnectionMocks()
|
||||
})
|
||||
|
||||
it('accepts GitHub restricted-shell SSH probes with resolved user fallback', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: 'git' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: undefined
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
})
|
||||
|
||||
it('uses fresh OpenSSH user for imported GitHub targets', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: 'git' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
source: 'ssh-config',
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'stale-user'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts GitHub restricted-shell SSH probes with resolved host and target username', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: undefined })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'git'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts ssh.github.com restricted-shell SSH probes', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'ssh.github.com', user: 'git' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'ssh.github.com',
|
||||
host: 'ssh.github.com',
|
||||
username: 'git'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts GitHub restricted-shell SSH probes with the real git:// advisory transcript', async () => {
|
||||
// Real 4-line stderr GitHub returns for an invalid command (issue #6988).
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: 'git' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(
|
||||
1,
|
||||
'Invalid command: echo ORCA-SYSTEM-SSH-OK\n' +
|
||||
' You appear to be using ssh to clone a git:// URL.\n' +
|
||||
' Make sure your core.gitProxy config option and the\n' +
|
||||
' GIT_PROXY_COMMAND environment variable are NOT set.'
|
||||
)
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'git'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts GitHub restricted-shell SSH probes when OpenSSH config resolution fails', async () => {
|
||||
vi.stubEnv('ORCA_SSH_FORCE_SYSTEM_TRANSPORT', '1')
|
||||
vi.mocked(resolveWithSshG).mockRejectedValueOnce(new Error('ssh -G failed'))
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'git'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects non-GitHub SSH probes with GitHub invalid-command text', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'gitlab.com', user: 'git' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'git'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)')
|
||||
expect(conn.usesSystemSshTransport()).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts GitHub restricted-shell SSH probes when target username overrides resolved user', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: 'deploy' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'git'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects GitHub restricted-shell SSH probes when target username overrides resolved git user', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: 'git' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'deploy'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)')
|
||||
expect(conn.usesSystemSshTransport()).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects GitHub restricted-shell SSH probes with extra stderr text', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: 'git' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(
|
||||
1,
|
||||
'remote: rejected\nInvalid command: echo ORCA-SYSTEM-SSH-OK\ntry again'
|
||||
)
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'git'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)')
|
||||
expect(conn.usesSystemSshTransport()).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects GitHub restricted-shell SSH probes for non-git users', async () => {
|
||||
vi.mocked(resolveWithSshG).mockResolvedValueOnce(
|
||||
createResolvedConfig({ hostname: 'github.com', user: 'deploy' })
|
||||
)
|
||||
spawnSystemSshCommandMock.mockImplementation(() =>
|
||||
createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK')
|
||||
)
|
||||
const conn = new SshConnection(
|
||||
createTarget({
|
||||
configHost: 'github.com',
|
||||
host: 'github.com',
|
||||
username: 'deploy'
|
||||
}),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)')
|
||||
expect(conn.usesSystemSshTransport()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Relay restarts reuse socket and pty-1 ids; identify panes by endpoint plus relay-reported incarnation. */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { toAppSshPtyId } from '../../../shared/ssh-pty-id'
|
||||
import '../../../shared/ssh-pty-id'
|
||||
import type { SshRemotePtyLease } from '../../../shared/ssh-types'
|
||||
import {
|
||||
ENDPOINT,
|
||||
@@ -110,144 +110,4 @@ describe('a relay restarted at the same socket', () => {
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(relay.shutdowns).toEqual([])
|
||||
})
|
||||
|
||||
it('ignores the restarted relay’s exit report until its listing shows the pane’s own shell', async () => {
|
||||
relay.incarnations.set('pty-1', 'inc-1')
|
||||
const subject = bridge({
|
||||
openClient: async () => {
|
||||
const client = fakeClient(relay)
|
||||
const list = client.list.bind(client)
|
||||
client.list = async () => {
|
||||
// The replacement's own pty-1 exits after the reconnect, before its listing lands.
|
||||
if (relay.clients.length > 1) {
|
||||
client.emitExit('pty-1', 9)
|
||||
}
|
||||
return list()
|
||||
}
|
||||
relay.clients.push(client)
|
||||
return client
|
||||
}
|
||||
})
|
||||
await subject.refresh()
|
||||
relay.clients[0].drop()
|
||||
relay.incarnations.set('pty-1', 'inc-2')
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(relay.clients).toHaveLength(2)
|
||||
expect(events.exits).toEqual([])
|
||||
expect(leases[0].state).toBe('detached')
|
||||
})
|
||||
|
||||
it('keeps the same relay’s exit report that raced its reconnect listing', async () => {
|
||||
relay.incarnations.set('pty-1', 'inc-1')
|
||||
const subject = bridge({
|
||||
openClient: async () => {
|
||||
const client = fakeClient(relay)
|
||||
const list = client.list.bind(client)
|
||||
client.list = async () => {
|
||||
const rows = await list()
|
||||
// The shell exits after the reconnected relay answered, before its listing lands.
|
||||
if (relay.clients.length > 1) {
|
||||
client.emitExit('pty-1', 3)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
relay.clients.push(client)
|
||||
return client
|
||||
}
|
||||
})
|
||||
await subject.refresh()
|
||||
relay.clients[0].drop()
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(events.exits).toEqual([PTY])
|
||||
expect(leases[0].state).toBe('terminated')
|
||||
expect(subject.snapshot()).toEqual([])
|
||||
})
|
||||
|
||||
it('takes an exit report on the connection that listed the pane, even after a refused attach', async () => {
|
||||
relay.incarnations.set('pty-1', 'inc-1')
|
||||
let exhaustive = true
|
||||
const subject = bridge({
|
||||
listEndpoints: async () => ({ kind: 'listed', endpoints: [ENDPOINT], exhaustive })
|
||||
})
|
||||
await subject.refresh()
|
||||
exhaustive = false
|
||||
relay.attachError = new Error('PTY busy')
|
||||
await expect(subject.attach(PTY)).resolves.toEqual({ status: 'unverifiable' })
|
||||
relay.clients[0].emitExit('pty-1', 4)
|
||||
expect(events.exits).toEqual([PTY])
|
||||
expect(leases[0].state).toBe('terminated')
|
||||
})
|
||||
|
||||
it('takes an exit report on the connection that listed the pane after a listing missed it', async () => {
|
||||
relay.incarnations.set('pty-1', 'inc-1')
|
||||
// A second pane keeps the connection open.
|
||||
leases = [lease(), lease({ ptyId: 'pty-2', tabId: 'tab-2', leafId: 'leaf-2' })]
|
||||
relay.ptys.add('pty-2')
|
||||
let exhaustive = true
|
||||
const subject = bridge({
|
||||
listEndpoints: async () => ({ kind: 'listed', endpoints: [ENDPOINT], exhaustive })
|
||||
})
|
||||
await subject.refresh()
|
||||
// The relay answers without the pane while the census is incomplete: not yet proof.
|
||||
exhaustive = false
|
||||
relay.ptys.delete('pty-1')
|
||||
await subject.refresh()
|
||||
expect(subject.snapshot()).toContainEqual(expect.objectContaining({ state: 'unverifiable' }))
|
||||
expect(relay.clients[0].closed).toBe(false)
|
||||
relay.clients[0].emitExit('pty-1', 6)
|
||||
expect(events.exits).toEqual([PTY])
|
||||
expect(leases[0].state).toBe('terminated')
|
||||
expect(leases[1].state).toBe('detached')
|
||||
})
|
||||
|
||||
it('reattaches the same shell when the relay lists its incarnation again', async () => {
|
||||
relay.incarnations.set('pty-1', 'inc-1')
|
||||
const subject = bridge()
|
||||
await subject.refresh()
|
||||
relay.clients[0].drop()
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(subject.snapshot()).toEqual([expect.objectContaining({ state: 'live' })])
|
||||
subject.write(PTY, 'ls\r')
|
||||
expect(relay.clients.at(-1)!.writes).toEqual(['ls\r'])
|
||||
})
|
||||
|
||||
it('keeps an epoch-scoped exit reported before the reconnect listing, even when incomplete', async () => {
|
||||
leases = [lease({ ptyId: 'pty2:epoch-a:1' })]
|
||||
relay.ptys = new Set(['pty2:epoch-a:1'])
|
||||
let exhaustive = true
|
||||
const subject = bridge({
|
||||
listEndpoints: async () => ({ kind: 'listed', endpoints: [ENDPOINT], exhaustive }),
|
||||
openClient: async () => {
|
||||
const client = fakeClient(relay)
|
||||
const list = client.list.bind(client)
|
||||
client.list = async () => {
|
||||
if (relay.clients.length > 1) {
|
||||
client.emitExit('pty2:epoch-a:1', 5)
|
||||
relay.ptys.clear()
|
||||
}
|
||||
return list()
|
||||
}
|
||||
relay.clients.push(client)
|
||||
return client
|
||||
}
|
||||
})
|
||||
await subject.refresh()
|
||||
exhaustive = false
|
||||
relay.clients[0].drop()
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(events.exits).toEqual([toAppSshPtyId(TARGET, 'pty2:epoch-a:1')])
|
||||
expect(leases[0].state).toBe('terminated')
|
||||
})
|
||||
|
||||
it('never binds an epoch-scoped id to a restart, whose ids carry a new epoch', async () => {
|
||||
leases = [lease({ ptyId: 'pty2:epoch-a:1' })]
|
||||
relay.ptys = new Set(['pty2:epoch-a:1'])
|
||||
const subject = bridge()
|
||||
await subject.refresh()
|
||||
relay.clients[0].drop()
|
||||
relay.ptys = new Set(['pty2:epoch-b:1'])
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
subject.write(toAppSshPtyId(TARGET, 'pty2:epoch-a:1'), 'ls\r')
|
||||
expect(relay.clients.flatMap((client) => client.writes)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
} from './orcad-migration-source-fence'
|
||||
import type { OrcadMigrationTerminalVerdict } from './orcad-migration-terminal-gate'
|
||||
import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims'
|
||||
import { createOrcadMigrationManifest } from './orcad-migration-manifest-export'
|
||||
import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../shared/orcad-migration/orcad-migration-manifest-validation'
|
||||
import './orcad-migration-manifest-export'
|
||||
import '../../shared/orcad-migration/orcad-migration-manifest-validation'
|
||||
|
||||
const TARGET: SshTarget = {
|
||||
id: 'ssh-prod',
|
||||
@@ -69,29 +69,6 @@ function setup(displayName = 'App') {
|
||||
}
|
||||
|
||||
describe('migration source fence', () => {
|
||||
it('journals, then fences, then flushes, all before returning', async () => {
|
||||
const harness = setup()
|
||||
const order: string[] = []
|
||||
const journalWrite = vi
|
||||
.spyOn(harness.claims, 'fenceForMigration')
|
||||
.mockImplementation((...args) => {
|
||||
order.push(
|
||||
listOrcadMigrationSourceCutovers(harness.userDataPath).length ? 'journal' : 'none'
|
||||
)
|
||||
order.push('fence')
|
||||
return SshTargetOrcadClaims.prototype.fenceForMigration.apply(harness.claims, args)
|
||||
})
|
||||
const flush = vi.spyOn(harness.claims, 'flush').mockImplementation(async () => {
|
||||
order.push(harness.target().orcadFence ? 'flush-after-fence' : 'flush-before-fence')
|
||||
})
|
||||
const result = await harness.fence()
|
||||
expect(result).toMatchObject({ outcome: 'fenced', resumed: false })
|
||||
expect(order).toEqual(['journal', 'fence', 'flush-after-fence'])
|
||||
expect(getManagedOrcadFenceEnvironmentId(harness.target())).toBe('env-1')
|
||||
journalWrite.mockRestore()
|
||||
flush.mockRestore()
|
||||
})
|
||||
|
||||
it('keeps the journal out of the profile, where an older build would strip it', async () => {
|
||||
const harness = setup()
|
||||
const result = await harness.fence()
|
||||
@@ -112,19 +89,6 @@ describe('migration source fence', () => {
|
||||
expect(onDisk?.manifest.payload.repositories.map((repo) => repo.id)).toEqual(['repo-1'])
|
||||
})
|
||||
|
||||
it('resumes the same migration instead of starting a second one', async () => {
|
||||
const harness = setup()
|
||||
const first = await harness.fence()
|
||||
const second = await harness.fence({
|
||||
terminalProof: { verdict: 'live', ptyIds: ['p'], reason: 'x' }
|
||||
})
|
||||
expect(second).toMatchObject({ outcome: 'fenced', resumed: true })
|
||||
expect(
|
||||
first.outcome === 'fenced' && second.outcome === 'fenced' && second.cutover.migrationId
|
||||
).toBe(first.outcome === 'fenced' && first.cutover.migrationId)
|
||||
expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('treats a fence whose journal was lost as unverifiable and never releases it', async () => {
|
||||
const harness = setup()
|
||||
await harness.fence()
|
||||
@@ -141,16 +105,6 @@ describe('migration source fence', () => {
|
||||
expect(getManagedOrcadFenceEnvironmentId(harness.target())).toBe('env-1')
|
||||
})
|
||||
|
||||
it('treats a journal whose fence an older build removed as stale, granting nothing', async () => {
|
||||
const harness = setup()
|
||||
await harness.fence()
|
||||
harness.store.updateSshTarget(TARGET.id, { orcadFence: undefined })
|
||||
expect(resolveOrcadMigrationFence(harness.userDataPath, harness.target()).state).toBe(
|
||||
'stale-journal'
|
||||
)
|
||||
await expect(harness.fence()).resolves.toMatchObject({ code: 'orcad_migration_stale_journal' })
|
||||
})
|
||||
|
||||
it('fails closed on an unreadable journal', async () => {
|
||||
const harness = setup()
|
||||
await harness.fence()
|
||||
@@ -168,33 +122,6 @@ describe('migration source fence', () => {
|
||||
await expect(harness.fence()).rejects.toThrow('stays fenced')
|
||||
})
|
||||
|
||||
it.each<[OrcadMigrationTerminalVerdict, string]>([
|
||||
[{ verdict: 'live', ptyIds: ['p'], reason: 'terminals run' }, 'live'],
|
||||
[{ verdict: 'unverifiable', ptyIds: ['p'], reason: 'relay silent' }, 'unverifiable']
|
||||
])('refuses before fencing when terminals are %j', async (terminalProof, verdict) => {
|
||||
const harness = setup()
|
||||
await expect(harness.fence({ terminalProof })).resolves.toMatchObject({
|
||||
outcome: 'refused',
|
||||
verdict
|
||||
})
|
||||
expect(harness.target().orcadFence).toBeUndefined()
|
||||
expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps a blocker it could not read unverifiable, never live', async () => {
|
||||
const harness = setup()
|
||||
vi.spyOn(harness.store, 'inspectOrcadMigrationUntransferredDependencies').mockImplementation(
|
||||
() => {
|
||||
throw new Error('census failed')
|
||||
}
|
||||
)
|
||||
await expect(harness.fence()).resolves.toMatchObject({
|
||||
outcome: 'refused',
|
||||
verdict: 'unverifiable',
|
||||
code: 'orcad_migration_preflight_blocked'
|
||||
})
|
||||
})
|
||||
|
||||
it('releases its own fence when a terminal appeared before the fence took hold', async () => {
|
||||
const harness = setup()
|
||||
const flush = vi.spyOn(harness.claims, 'flush').mockImplementation(async () => {
|
||||
@@ -209,21 +136,4 @@ describe('migration source fence', () => {
|
||||
expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([])
|
||||
flush.mockRestore()
|
||||
})
|
||||
|
||||
it('refuses, without a journal or fence, a manifest under the export cap that no request can carry', async () => {
|
||||
const probe = setup()
|
||||
const baseline = JSON.stringify(
|
||||
createOrcadMigrationManifest(probe.store, probe.target())
|
||||
).length
|
||||
// Under the export cap, over the sealed-frame request budget: stage, state and abort all refuse.
|
||||
const harness = setup('x'.repeat(MAX_ORCAD_MIGRATION_MANIFEST_BYTES - 200 - baseline))
|
||||
const manifestBytes = JSON.stringify(
|
||||
createOrcadMigrationManifest(harness.store, harness.target())
|
||||
).length
|
||||
expect(manifestBytes).toBeLessThanOrEqual(MAX_ORCAD_MIGRATION_MANIFEST_BYTES)
|
||||
|
||||
await expect(harness.fence()).rejects.toThrow(/\(orcad_migration_manifest_too_large\)$/)
|
||||
expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([])
|
||||
expect(harness.target().orcadFence).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,11 +2,11 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { Server } from 'node:net'
|
||||
import type { EventEmitter } from 'node:events'
|
||||
|
||||
import { PassThrough } from 'node:stream'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { OrcadStdioBridgeUnavailableError } from '../orcad/orcad-host-unavailable'
|
||||
import { checkOrcadStdioBridge, type OrcadStdioBridge } from './orcad-stdio-bridge'
|
||||
import '../orcad/orcad-host-unavailable'
|
||||
import './orcad-stdio-bridge'
|
||||
import {
|
||||
orcadPosixStdioBridgeCommand,
|
||||
type OrcadStdioBridgeMode
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
startEchoServer
|
||||
} from '../managed-server/lifecycle/orcad-stdio-bridge-test-channel'
|
||||
import { ORCAD_WINDOWS_HOST_SCRIPT } from '../managed-server/host-state/orcad-windows-host-script'
|
||||
import type { OrcadHostTransport } from './orcad-host-transport'
|
||||
|
||||
import type { RemoteCommandChannel } from '../managed-server/install/remote-install-transport'
|
||||
|
||||
const POSIX = process.platform !== 'win32'
|
||||
@@ -76,17 +76,6 @@ function posixHome(withRuntime: boolean): string {
|
||||
return home
|
||||
}
|
||||
|
||||
function connectionRunning(channel: () => RemoteCommandChannel): OrcadHostTransport {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check calls only exec.
|
||||
return { exec: async () => channel() } as unknown as OrcadHostTransport
|
||||
}
|
||||
|
||||
const posixBridge = (port: number): OrcadStdioBridge => ({
|
||||
command: orcadPosixStdioBridgeCommand(port),
|
||||
mode: 'raw',
|
||||
wrapCommand: true
|
||||
})
|
||||
|
||||
describe.runIf(POSIX)('the POSIX stdio bridge command', () => {
|
||||
it('pipes every byte to orcad and back on the store’s pinned Node', async () => {
|
||||
const home = posixHome(true)
|
||||
@@ -101,19 +90,6 @@ describe.runIf(POSIX)('the POSIX stdio bridge command', () => {
|
||||
expect((await roundTrip(channel, 'raw')).equals(PAYLOAD)).toBe(true)
|
||||
})
|
||||
|
||||
it('proves the bridge runs even when orcad refuses the dial', async () => {
|
||||
const closed = await startEchoServer()
|
||||
closed.server.close()
|
||||
const home = posixHome(true)
|
||||
const conn = connectionRunning(() =>
|
||||
spawnLocalBridgeChannel('/bin/sh', ['-c', posixBridge(closed.port).command], {
|
||||
...process.env,
|
||||
HOME: home
|
||||
})
|
||||
)
|
||||
await expect(checkOrcadStdioBridge(conn, posixBridge(closed.port))).resolves.toBe('running')
|
||||
})
|
||||
|
||||
it('runs on a machine home’s Node, skipping a store runtime that cannot start here', async () => {
|
||||
const home = posixHome(false)
|
||||
// Another machine's runtime on the shared home, e.g. built for another architecture.
|
||||
@@ -133,19 +109,6 @@ describe.runIf(POSIX)('the POSIX stdio bridge command', () => {
|
||||
)
|
||||
expect((await roundTrip(channel, 'raw')).equals(PAYLOAD)).toBe(true)
|
||||
})
|
||||
|
||||
it('reports a host with no pinned Node as one the bridge cannot run on', async () => {
|
||||
const home = posixHome(false)
|
||||
const conn = connectionRunning(() =>
|
||||
spawnLocalBridgeChannel('/bin/sh', ['-c', posixBridge(echo.port).command], {
|
||||
...process.env,
|
||||
HOME: home
|
||||
})
|
||||
)
|
||||
await expect(checkOrcadStdioBridge(conn, posixBridge(echo.port))).rejects.toBeInstanceOf(
|
||||
OrcadStdioBridgeUnavailableError
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the Windows host script’s stdio-bridge op', () => {
|
||||
@@ -183,79 +146,4 @@ describe('reading a bridge channel', () => {
|
||||
await new Promise((resolve) => decoder.on('end', resolve))
|
||||
expect(Buffer.concat(out)).toEqual(Buffer.from([0, 1, 0xff]))
|
||||
})
|
||||
|
||||
it('fails a channel that prints no sentinel within its bound', async () => {
|
||||
const decoder = new OrcadStdioBridgeDecoder('raw')
|
||||
const failed = new Promise((resolve) => decoder.on('error', resolve))
|
||||
decoder.write(Buffer.alloc(70 * 1024, 0x61))
|
||||
await expect(failed).resolves.toBeInstanceOf(Error)
|
||||
})
|
||||
})
|
||||
|
||||
function scriptedChannel(): RemoteCommandChannel & EventEmitter & { stderr: PassThrough } {
|
||||
const channel = Object.assign(new PassThrough(), {
|
||||
stderr: new PassThrough(),
|
||||
close: () => {}
|
||||
})
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check uses only the stream, `stderr`, `close`, and events.
|
||||
return channel as unknown as RemoteCommandChannel & EventEmitter & { stderr: PassThrough }
|
||||
}
|
||||
|
||||
describe('checking a bridge before the tunnel relies on it', () => {
|
||||
it('reads a channel lost without an exit status as unverifiable, never as unavailable', async () => {
|
||||
const channel = scriptedChannel()
|
||||
const check = checkOrcadStdioBridge(
|
||||
connectionRunning(() => channel),
|
||||
posixBridge(1)
|
||||
)
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
channel.emit('close')
|
||||
await expect(check).resolves.toBe('unverifiable')
|
||||
})
|
||||
|
||||
it('reads a silent bridge as unverifiable once the check times out', async () => {
|
||||
const channel = scriptedChannel()
|
||||
await expect(
|
||||
checkOrcadStdioBridge(
|
||||
connectionRunning(() => channel),
|
||||
posixBridge(1),
|
||||
20
|
||||
)
|
||||
).resolves.toBe('unverifiable')
|
||||
})
|
||||
|
||||
it('reads a reported exit with no sentinel as a host the bridge cannot run on', async () => {
|
||||
const channel = scriptedChannel()
|
||||
const check = checkOrcadStdioBridge(
|
||||
connectionRunning(() => channel),
|
||||
posixBridge(1)
|
||||
)
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
channel.stderr.write('node.exe is not recognized')
|
||||
channel.emit('exit', 9009)
|
||||
channel.emit('close')
|
||||
await expect(check).rejects.toThrow(/exit 9009: node.exe is not recognized/u)
|
||||
})
|
||||
|
||||
it('reads a script cut short with no sentinel as unverifiable, not a permanent refusal', async () => {
|
||||
const channel = scriptedChannel()
|
||||
const check = checkOrcadStdioBridge(
|
||||
connectionRunning(() => channel),
|
||||
posixBridge(1)
|
||||
)
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
channel.emit('exit', 1)
|
||||
channel.emit('close')
|
||||
await expect(check).resolves.toBe('unverifiable')
|
||||
})
|
||||
|
||||
it('reads an exec channel sshd would not open as unverifiable', async () => {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check calls only exec.
|
||||
const conn = {
|
||||
exec: async () => {
|
||||
throw new Error('open failed')
|
||||
}
|
||||
} as unknown as OrcadHostTransport
|
||||
await expect(checkOrcadStdioBridge(conn, posixBridge(1))).resolves.toBe('unverifiable')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,240 +0,0 @@
|
||||
// Final census holds admission closed through stop and reopens it if incumbent keeps serving.
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as ExecCommandModule from './remote-exec/remote-exec-command'
|
||||
import type * as RecordFile from '../managed-server/install/orcad-remote-record-file'
|
||||
import type * as InstallLock from '../managed-server/install/remote-install-lock'
|
||||
import type * as VersionedInstall from '../managed-server/install/remote-versioned-install'
|
||||
|
||||
vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof ExecCommandModule>()),
|
||||
execCommand: vi.fn()
|
||||
}))
|
||||
vi.mock('../../shared/shell/launch/shell-argument-quoting', () => ({
|
||||
quotePosixShell: (s: string) => `'${s}'`
|
||||
}))
|
||||
vi.mock('../managed-server/install/remote-install-lock', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof InstallLock>()),
|
||||
acquireInstallLock: vi.fn()
|
||||
}))
|
||||
vi.mock('../managed-server/install/orcad-remote-record-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof RecordFile>()),
|
||||
writeAtomicOrcadRemoteRecord: vi.fn()
|
||||
}))
|
||||
vi.mock('../managed-server/install/remote-versioned-install', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof VersionedInstall>()),
|
||||
readLocalFullVersion: () => '0.2.0+bb01'
|
||||
}))
|
||||
vi.mock('../managed-server/install/orcad-remote-install', () => ({ installOrcadBundle: vi.fn() }))
|
||||
vi.mock('../managed-server/install/orcad-remote-preflight', () => ({
|
||||
preflightInstalledOrcad: vi.fn(async () => ({}))
|
||||
}))
|
||||
vi.mock('./orcad-local-build-hash', () => ({
|
||||
computeLocalOrcadBuildHash: () => 'abc123def4567890'
|
||||
}))
|
||||
|
||||
import { execCommand } from './remote-exec/remote-exec-command'
|
||||
import { preflightInstalledOrcad } from '../managed-server/install/orcad-remote-preflight'
|
||||
import { PROTOCOL_VERSION } from '../daemon/protocol/daemon-protocol-version'
|
||||
import { acquireInstallLock } from '../managed-server/install/remote-install-lock'
|
||||
import { writeAtomicOrcadRemoteRecord } from '../managed-server/install/orcad-remote-record-file'
|
||||
import { deployOrcad } from './orcad-remote-deploy'
|
||||
import { getRemoteHostPlatform } from './ssh-remote-platform'
|
||||
import {
|
||||
ORCAD_UPDATE_ADMISSION_FENCE_MS,
|
||||
ORCAD_UPDATE_ADMISSION_STOP_BY_MS,
|
||||
type OrcadTerminalCensus
|
||||
} from '../../shared/orcad-terminal-census'
|
||||
|
||||
import {
|
||||
TerminalUpdateAdmission,
|
||||
TerminalUpdateAdmissionClosedError
|
||||
} from '../runtime/terminal/stop/terminal-update-admission'
|
||||
import {
|
||||
FakeOrcadHost,
|
||||
NEW,
|
||||
OLD
|
||||
} from '../managed-server/activation/orcad-activation-host-test-harness'
|
||||
|
||||
let host = FakeOrcadHost.deployedOld()
|
||||
let clockMs = Date.parse('2026-02-02T00:00:00.000Z')
|
||||
let admission = new TerminalUpdateAdmission(async () => [])
|
||||
|
||||
const IDLE = { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 3 }
|
||||
const LIVE = { liveSessions: 1, startedSinceActivation: 1, daemonProtocolVersion: 3 }
|
||||
const UNREAD = { liveSessions: null, startedSinceActivation: null, daemonProtocolVersion: null }
|
||||
|
||||
function deploy(
|
||||
recount: OrcadTerminalCensus | Error = IDLE,
|
||||
force?: boolean,
|
||||
census: OrcadTerminalCensus = IDLE
|
||||
) {
|
||||
const recountCensus = vi.fn(async () => {
|
||||
admission.close(ORCAD_UPDATE_ADMISSION_FENCE_MS)
|
||||
if (recount instanceof Error) {
|
||||
throw recount
|
||||
}
|
||||
return recount
|
||||
})
|
||||
const releaseIncumbentAdmission = vi.fn(async () => {
|
||||
admission.close(0)
|
||||
})
|
||||
const result = deployOrcad({
|
||||
conn: Object.create(null),
|
||||
host: getRemoteHostPlatform('linux-x64'),
|
||||
remoteHome: '/home/work',
|
||||
nodePath: '/usr/bin/node',
|
||||
userDataDir: '/home/work/.orca',
|
||||
bindHost: '127.0.0.1',
|
||||
port: 7777,
|
||||
readinessTimeoutMs: 50,
|
||||
sleep: async () => {},
|
||||
now: () => new Date(clockMs),
|
||||
localOrcadDir: '/local/out/orcad',
|
||||
target: 'linux-x64-glibc217',
|
||||
census,
|
||||
recountCensus,
|
||||
releaseIncumbentAdmission,
|
||||
...(force !== undefined ? { force } : {})
|
||||
})
|
||||
return { result, recountCensus, releaseIncumbentAdmission }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
host = FakeOrcadHost.deployedOld()
|
||||
clockMs = Date.parse('2026-02-02T00:00:00.000Z')
|
||||
admission = new TerminalUpdateAdmission(async () => [])
|
||||
vi.mocked(execCommand).mockImplementation(async (_conn, command) => host.exec(command))
|
||||
vi.mocked(acquireInstallLock).mockImplementation(async (_conn, _dir, _host, options) => {
|
||||
host.acquireFence(options)
|
||||
})
|
||||
vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) =>
|
||||
host.write(path, contents)
|
||||
)
|
||||
})
|
||||
|
||||
describe("an update's terminal admission fence", () => {
|
||||
it('refuses a terminal opened between the last census and the stop, then stops', async () => {
|
||||
const refusals: unknown[] = []
|
||||
vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => {
|
||||
// A user opens a terminal while the update records its transaction, after the recount.
|
||||
if (path.endsWith('transaction.json') && host.alive.has(OLD)) {
|
||||
refusals.push(await admission.admit(undefined).catch((error: unknown) => error))
|
||||
}
|
||||
host.write(path, contents)
|
||||
})
|
||||
const { result, releaseIncumbentAdmission } = deploy()
|
||||
|
||||
await expect(result).resolves.toMatchObject({ outcome: 'installed-and-activated' })
|
||||
expect(refusals[0]).toBeInstanceOf(TerminalUpdateAdmissionClosedError)
|
||||
expect([...host.alive]).toEqual([NEW])
|
||||
expect(releaseIncumbentAdmission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
[LIVE, false, 'orcad_update_terminals_running'],
|
||||
[{ ...LIVE, inProcessSessions: 1 }, true, 'orcad_update_ends_in_process_terminals'],
|
||||
[UNREAD, true, 'orcad_update_daemon_protocol_unverifiable'],
|
||||
[new Error('tunnel closed'), false, 'orcad_update_terminal_census_unavailable']
|
||||
])(
|
||||
'defers on a recount of %j and reopens admission (force: %s)',
|
||||
async (recount, force, code) => {
|
||||
const { result, recountCensus } = deploy(recount, force)
|
||||
|
||||
await expect(result).resolves.toMatchObject({ outcome: 'installed-not-activated', code })
|
||||
expect(recountCensus).toHaveBeenCalledTimes(1)
|
||||
expect([...host.alive]).toEqual([OLD])
|
||||
expect(host.commands.some((command) => command.includes('kill -TERM'))).toBe(false)
|
||||
// The incumbent keeps serving, so it takes terminals again now, not when the fence lapses.
|
||||
expect(admission.isClosed()).toBe(false)
|
||||
}
|
||||
)
|
||||
|
||||
it('reopens admission when the first mutation after the recount fails before any stop', async () => {
|
||||
vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => {
|
||||
if (path.endsWith('transaction.json')) {
|
||||
throw new Error('disk full')
|
||||
}
|
||||
host.write(path, contents)
|
||||
})
|
||||
const { result, releaseIncumbentAdmission } = deploy()
|
||||
|
||||
await expect(result).rejects.toThrow('disk full')
|
||||
expect([...host.alive]).toEqual([OLD])
|
||||
expect(releaseIncumbentAdmission).toHaveBeenCalledTimes(1)
|
||||
expect(admission.isClosed()).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['SIGNAL_FAILED', false],
|
||||
['STILL_RUNNING', true]
|
||||
])(
|
||||
'after a stop answering %s, reopens admission only if no stop can still land',
|
||||
async (answer, underway) => {
|
||||
vi.mocked(execCommand).mockImplementation(async (_conn, command) =>
|
||||
command.includes('kill -TERM') ? answer : host.exec(command)
|
||||
)
|
||||
const { result } = deploy()
|
||||
|
||||
await expect(result).resolves.toMatchObject({ code: 'orcad_outgoing_stop_incomplete' })
|
||||
expect(admission.isClosed()).toBe(underway)
|
||||
}
|
||||
)
|
||||
|
||||
it('stops nothing once the fence may have lapsed before the stop could be sent', async () => {
|
||||
vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => {
|
||||
if (path.endsWith('transaction.json')) {
|
||||
clockMs += ORCAD_UPDATE_ADMISSION_STOP_BY_MS + 1
|
||||
}
|
||||
host.write(path, contents)
|
||||
})
|
||||
const { result } = deploy()
|
||||
|
||||
await expect(result).resolves.toMatchObject({
|
||||
outcome: 'installed-not-activated',
|
||||
code: 'orcad_update_terminal_census_unavailable'
|
||||
})
|
||||
expect(host.commands.some((command) => command.includes('kill -TERM'))).toBe(false)
|
||||
expect([...host.alive]).toEqual([OLD])
|
||||
expect(admission.isClosed()).toBe(false)
|
||||
})
|
||||
|
||||
describe('on a host whose census cannot name mixed daemon generations', () => {
|
||||
const MIXED = { liveSessions: 2, startedSinceActivation: null, daemonProtocolVersion: null }
|
||||
const answer = (liveDaemonProtocols: number[]) => ({
|
||||
type: 'orca_profile_state_ready' as const,
|
||||
nonce: '00000000-0000-4000-8000-000000000000',
|
||||
runtime: 'node' as const,
|
||||
runtimeVersion: process.versions.node,
|
||||
artifactVersion: '0.2.0+abc123def456',
|
||||
sqliteVersion: '3.50.0',
|
||||
revision: 1,
|
||||
liveDaemonProtocols
|
||||
})
|
||||
|
||||
it('asks the candidate about the served data root and updates when it attaches every generation', async () => {
|
||||
vi.mocked(preflightInstalledOrcad).mockResolvedValueOnce(
|
||||
answer([PROTOCOL_VERSION - 1, PROTOCOL_VERSION])
|
||||
)
|
||||
const { result } = deploy(MIXED, true, MIXED)
|
||||
|
||||
await expect(result).resolves.toMatchObject({ outcome: 'installed-and-activated' })
|
||||
expect(preflightInstalledOrcad).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ probeDaemonsUnder: '/home/work/.orca' })
|
||||
)
|
||||
})
|
||||
|
||||
it('stops nothing when the candidate sees a generation it cannot attach', async () => {
|
||||
vi.mocked(preflightInstalledOrcad).mockResolvedValueOnce(
|
||||
answer([PROTOCOL_VERSION, PROTOCOL_VERSION + 1])
|
||||
)
|
||||
const { result } = deploy(MIXED, true, MIXED)
|
||||
|
||||
await expect(result).resolves.toMatchObject({
|
||||
outcome: 'installed-not-activated',
|
||||
code: 'orcad_update_strands_live_terminals'
|
||||
})
|
||||
expect([...host.alive]).toEqual([OLD])
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,12 +1,12 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { mkdtemp, mkdir, readdir, readlink, rm, writeFile } from 'node:fs/promises'
|
||||
import { mkdtemp, readdir, readlink, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, posix } from 'node:path'
|
||||
import type { SFTPWrapper, WriteStreamOptions } from 'ssh2'
|
||||
import { SFTP } from 'ssh2/lib/protocol/SFTP.js'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { uploadSshDirectory } from './connection/ssh-connection-file-transfers'
|
||||
import { uploadDirectory } from './sftp-upload'
|
||||
import './sftp-upload'
|
||||
|
||||
function uploadSession(options?: {
|
||||
stalledCloses?: boolean
|
||||
@@ -158,46 +158,6 @@ async function expectLocalFilesClosed(dir: string): Promise<void> {
|
||||
}
|
||||
|
||||
describe('directory upload pipeline', () => {
|
||||
it('overlaps four small files, preserves bytes, and creates parents before child writes', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'orca-sftp-pipeline-'))
|
||||
const fixture = uploadSession({ stalledCloses: true })
|
||||
const files = new Map<string, Buffer>()
|
||||
let upload: Promise<void> | undefined
|
||||
try {
|
||||
await mkdir(join(dir, 'nested'))
|
||||
for (let index = 0; index < 12; index++) {
|
||||
const path = index < 6 ? `${index}.bin` : `nested/${index}.bin`
|
||||
const contents = Buffer.alloc(1024 + index * 521, index)
|
||||
files.set(`/remote/${path}`, contents)
|
||||
await writeFile(join(dir, path), contents)
|
||||
}
|
||||
upload = uploadDirectory(fixture.sftp, dir, '/remote', dir, { exclusive: true })
|
||||
void upload.catch(() => {})
|
||||
await vi.waitFor(() => expect(fixture.closes.size).toBe(4))
|
||||
expect(fixture.opened).toHaveLength(4)
|
||||
fixture.releaseCloses()
|
||||
await upload
|
||||
|
||||
expect(fixture.peakHandles()).toBe(4)
|
||||
expect(fixture.peakWindow()).toBe(4 * 64 * 1024)
|
||||
expect(fixture.windows.size).toBe(0)
|
||||
expect(fixture.contents.size).toBe(files.size)
|
||||
for (const [path, expected] of files) {
|
||||
const pieces = fixture.contents.get(path)
|
||||
expect(pieces).toBeDefined()
|
||||
const actual = Buffer.concat(
|
||||
[...(pieces ?? [])].sort(([a], [b]) => a - b).map(([, chunk]) => chunk)
|
||||
)
|
||||
expect(actual.equals(expected)).toBe(true)
|
||||
}
|
||||
} finally {
|
||||
fixture.releaseCloses()
|
||||
fixture.sftp.emit('close')
|
||||
await upload?.catch(() => {})
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves the first write failure while closing a sibling stalled in CLOSE', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'orca-sftp-pipeline-'))
|
||||
const settings = { stalledCloses: true, heldWrite: '' }
|
||||
|
||||
@@ -2,8 +2,6 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import { parseKnownHosts } from './config/ssh-known-hosts'
|
||||
import {
|
||||
createHostKeyVerifier,
|
||||
getDefaultServerHostKeyAlgorithms,
|
||||
hostKeyFingerprintOf,
|
||||
orderServerHostKeyAlgorithms,
|
||||
type HostKeyVerifierDeps
|
||||
} from './ssh-host-key-verifier'
|
||||
@@ -54,10 +52,6 @@ describe('the ssh2 host key verifier', () => {
|
||||
expect(run({ entries }).accepted).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts a key our own store already holds', () => {
|
||||
expect(run({ isTrusted: () => 'match' }).accepted).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a changed key', () => {
|
||||
const entries = parseKnownHosts(`example.com ssh-ed25519 ${ED_B}`)
|
||||
expect(run({ entries }).accepted).toBe(false)
|
||||
@@ -95,77 +89,7 @@ describe('the ssh2 host key verifier', () => {
|
||||
expect(accepted).toBe(false)
|
||||
})
|
||||
|
||||
it('does not record a key for a superseded attempt', () => {
|
||||
const rememberHostKey = vi.fn()
|
||||
run({ isCurrentAttempt: () => false, rememberHostKey })
|
||||
expect(rememberHostKey).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
describe('remembering', () => {
|
||||
it('records a first-contact key', () => {
|
||||
const rememberHostKey = vi.fn()
|
||||
run({ rememberHostKey })
|
||||
expect(rememberHostKey).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
host: 'example.com',
|
||||
port: 22,
|
||||
keyType: 'ssh-ed25519',
|
||||
fingerprint: hostKeyFingerprintOf(blob(ED_A))
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a key we already know', { entries: parseKnownHosts(`example.com ssh-ed25519 ${ED_A}`) }],
|
||||
['a rejected key', { entries: parseKnownHosts(`example.com ssh-ed25519 ${ED_B}`) }],
|
||||
['an ephemeral runtime target', { policy: { kind: 'ephemeral' as const } }],
|
||||
['a lax StrictHostKeyChecking', { strictHostKeyChecking: 'no' }]
|
||||
])('does not record %s', (_label, overrides) => {
|
||||
const rememberHostKey = vi.fn()
|
||||
run({ ...overrides, rememberHostKey })
|
||||
expect(rememberHostKey).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('reports every decision for audit', () => {
|
||||
const onDecision = vi.fn()
|
||||
run({ onDecision })
|
||||
expect(onDecision).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ outcome: 'unknown', keyType: 'ssh-ed25519' })
|
||||
)
|
||||
})
|
||||
|
||||
describe('denials that bypass the policy', () => {
|
||||
// Report every denial so credential fallback cannot prompt against a host already refused.
|
||||
it('reports a denial for a key it could not read', () => {
|
||||
const onDecision = vi.fn()
|
||||
createHostKeyVerifier(deps({ onDecision }))(Buffer.alloc(2), () => {})
|
||||
expect(onDecision).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'reject',
|
||||
reason: expect.stringContaining('example.com')
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('reports a denial when a dependency throws', () => {
|
||||
const onDecision = vi.fn()
|
||||
run({
|
||||
onDecision,
|
||||
isTrusted: () => {
|
||||
throw new Error('store unreadable')
|
||||
}
|
||||
})
|
||||
expect(onDecision).toHaveBeenCalledWith(expect.objectContaining({ action: 'reject' }))
|
||||
})
|
||||
|
||||
// No parseable key means no fingerprint; bogus values must not replace the install-lock identity.
|
||||
it('reports no fingerprint for a key it could not read', () => {
|
||||
const onDecision = vi.fn()
|
||||
createHostKeyVerifier(deps({ onDecision }))(Buffer.alloc(2), () => {})
|
||||
expect(onDecision.mock.calls[0]?.[0]?.fingerprint).toBe('')
|
||||
})
|
||||
|
||||
// Reporting failure inside verifier catch must still deny, never escape and hang handshake.
|
||||
it('still denies when reporting the denial throws', () => {
|
||||
let accepted: boolean | undefined
|
||||
@@ -183,67 +107,12 @@ describe('the ssh2 host key verifier', () => {
|
||||
).not.toThrow()
|
||||
expect(accepted).toBe(false)
|
||||
})
|
||||
|
||||
// Superseded verifiers must not overwrite the live attempt's reported outcome.
|
||||
it('reports nothing once its attempt has been superseded', () => {
|
||||
const onDecision = vi.fn()
|
||||
run({ onDecision, isCurrentAttempt: () => false })
|
||||
expect(onDecision).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('the ssh2 default algorithm list', () => {
|
||||
const ssh2Constants = require('ssh2/lib/protocol/constants.js') as {
|
||||
DEFAULT_SERVER_HOST_KEY: string[]
|
||||
SUPPORTED_SERVER_HOST_KEY: string[]
|
||||
}
|
||||
|
||||
it('is read from ssh2, not guessed', () => {
|
||||
expect(getDefaultServerHostKeyAlgorithms()).toEqual(ssh2Constants.DEFAULT_SERVER_HOST_KEY)
|
||||
})
|
||||
|
||||
it('proposes nothing ssh2 would refuse', () => {
|
||||
for (const algorithm of getDefaultServerHostKeyAlgorithms() ?? []) {
|
||||
expect(ssh2Constants.SUPPORTED_SERVER_HOST_KEY).toContain(algorithm)
|
||||
}
|
||||
})
|
||||
|
||||
// Keep all RSA signature names so one known ssh-rsa key can be promoted under every negotiated algorithm.
|
||||
it('contains the RSA signature algorithms the ordering maps onto', () => {
|
||||
expect(getDefaultServerHostKeyAlgorithms() ?? []).toEqual(
|
||||
expect.arrayContaining(['ssh-rsa', 'rsa-sha2-256', 'rsa-sha2-512'])
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('host key algorithm ordering', () => {
|
||||
const supported = ['ssh-ed25519', 'rsa-sha2-512', 'ssh-rsa', 'ecdsa-sha2-nistp256']
|
||||
|
||||
// Lead with stored types so another algorithm cannot turn mismatch into first contact.
|
||||
it('leads with the types already known for the host', () => {
|
||||
const entries = parseKnownHosts(`example.com ssh-rsa ${RSA_A}`)
|
||||
const ordered = orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported)
|
||||
expect(ordered?.[0]).toMatch(/rsa/)
|
||||
expect(ordered?.indexOf('ssh-ed25519')).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('keeps every supported algorithm, only reordered', () => {
|
||||
const entries = parseKnownHosts(`example.com ssh-rsa ${RSA_A}`)
|
||||
const ordered = orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported)
|
||||
expect([...(ordered ?? [])].sort()).toEqual([...supported].sort())
|
||||
})
|
||||
|
||||
it('leaves the defaults alone for a host we know nothing about', () => {
|
||||
const entries = parseKnownHosts(`other.com ssh-rsa ${RSA_A}`)
|
||||
expect(orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('ignores a revoked entry when choosing what to lead with', () => {
|
||||
const entries = parseKnownHosts(`@revoked example.com ssh-rsa ${RSA_A}`)
|
||||
expect(orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported)).toBeUndefined()
|
||||
})
|
||||
|
||||
// One ssh-rsa key negotiates as rsa-sha2-512/256 or ssh-rsa; promote them together.
|
||||
it('promotes every RSA signature algorithm for a known ssh-rsa key', () => {
|
||||
const entries = parseKnownHosts(`example.com ssh-rsa ${RSA_A}`)
|
||||
@@ -251,17 +120,4 @@ describe('host key algorithm ordering', () => {
|
||||
expect(ordered?.slice(0, 2).sort()).toEqual(['rsa-sha2-512', 'ssh-rsa'])
|
||||
expect(ordered?.indexOf('ssh-ed25519')).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
// Store-only known types need the same proposal protection as known_hosts types.
|
||||
it('leads with a type known only from our own store', () => {
|
||||
const ordered = orderServerHostKeyAlgorithms([], 'example.com', 22, supported, ['ssh-rsa'])
|
||||
expect(ordered?.[0]).toMatch(/rsa/)
|
||||
expect(ordered?.indexOf('ssh-ed25519')).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('does not propose a type the transport does not support', () => {
|
||||
const entries = parseKnownHosts(`example.com ssh-ed25519 ${ED_A}`)
|
||||
const ordered = orderServerHostKeyAlgorithms(entries, 'example.com', 22, ['rsa-sha2-512'])
|
||||
expect(ordered).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -37,75 +37,6 @@ it.skipIf(process.platform === 'win32')(
|
||||
)
|
||||
|
||||
describe('wrapRemoteCommandForPosixShell', () => {
|
||||
it('emits one physical line without requiring a remote decoder binary', () => {
|
||||
const wrapped = wrapRemoteCommandForPosixShell("printf 'a\\n'\nprintf 'b\\n'")
|
||||
expect(wrapped).not.toContain('\n')
|
||||
expect(wrapped).toContain('printf %b "$@"')
|
||||
expect(wrapped).not.toContain('base64')
|
||||
})
|
||||
|
||||
it('does not expand long commands made only of parser-safe ASCII', () => {
|
||||
const command = `: #${'x'.repeat(7_000)}`
|
||||
expect(wrapRemoteCommandForPosixShell(command).length - command.length).toBeLessThan(200)
|
||||
})
|
||||
|
||||
it('does not octal-expand literal UTF-8 near SSH command-length limits', () => {
|
||||
const command = `: #${'☃'.repeat(7_000)}`
|
||||
expect(wrapRemoteCommandForPosixShell(command).length - command.length).toBeLessThan(200)
|
||||
})
|
||||
|
||||
it('does not octal-expand quoted shell metacharacters near command-length limits', () => {
|
||||
const command = `: #${'$"`'.repeat(2_000)}`
|
||||
expect(wrapRemoteCommandForPosixShell(command).length - command.length).toBeLessThan(200)
|
||||
})
|
||||
|
||||
it('measures the compression threshold in UTF-8 bytes', () => {
|
||||
const command = `: #${'☃'.repeat(3_000)}`
|
||||
const wrapped = wrapRemoteCommandForPosixShell(command)
|
||||
|
||||
expect(command.length).toBeLessThan(8_000)
|
||||
expect(Buffer.byteLength(command)).toBeGreaterThan(8_000)
|
||||
expect(Buffer.byteLength(wrapped)).toBeLessThan(8_000)
|
||||
expect(wrapped).not.toContain('\n')
|
||||
})
|
||||
|
||||
it('keeps the printf form when compression would make the request larger', () => {
|
||||
const alphabet = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32))
|
||||
.filter((character) => !['!', "'", '\\'].includes(character))
|
||||
.join('')
|
||||
const padding = Array.from({ length: 400 }, (_, i) =>
|
||||
Array.from(
|
||||
createHash('sha256').update(String(i)).digest(),
|
||||
(byte) => alphabet[byte % alphabet.length]
|
||||
).join('')
|
||||
).join('')
|
||||
const wrapped = wrapRemoteCommandForPosixShell(`: #${padding}`)
|
||||
|
||||
expect(wrapped).toContain('printf %b "$@"')
|
||||
expect(wrapped).not.toContain('base64')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'reconstructs multiline UTF-8 and shell metacharacters exactly',
|
||||
() => {
|
||||
const expected = "line one\nline 'two' \"$`\\ ! ☃\n"
|
||||
const command = `printf '%s' ${quotePosixShell(expected)}`
|
||||
const result = runThroughShell('/bin/sh', command)
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stderr).toBe('')
|
||||
expect(result.stdout).toBe(expected)
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32')('keeps stdin free for relay protocol bytes', () => {
|
||||
const command = 'IFS= read -r frame; printf \'frame:%s\' "$frame"'
|
||||
const result = runThroughShell('/bin/sh', command, 'rpc-payload\n')
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe('frame:rpc-payload')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'passes a long command through a gateway with a 10 KiB exec limit without consuming stdin',
|
||||
() => {
|
||||
@@ -127,15 +58,6 @@ describe('wrapRemoteCommandForPosixShell', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32')('preserves trailing newlines in a long command', () => {
|
||||
const command = `# ${'padding'.repeat(2_000)}\nprintf '%s' trailing\\\n`
|
||||
const result = runThroughShell('/bin/sh', command)
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stderr).toBe('')
|
||||
expect(result.stdout).toBe('trailing')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'reports a host without the decoders before running anything',
|
||||
() => {
|
||||
@@ -151,21 +73,6 @@ describe('wrapRemoteCommandForPosixShell', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'fails without running the script if the payload does not decode',
|
||||
() => {
|
||||
const bin = shimDir({ base64: "cat >/dev/null; printf 'not gzip'" })
|
||||
const command = `# ${'padding'.repeat(2_000)}\nprintf 'must not run'`
|
||||
const result = spawnSync('/bin/sh', ['-c', wrapRemoteCommandForPosixShell(command)], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ''}` }
|
||||
})
|
||||
|
||||
expect(result.status).not.toBe(0)
|
||||
expect(result.stdout).toBe('')
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'decodes with `base64 -D` where `-d` is refused, as on macOS before 13',
|
||||
() => {
|
||||
@@ -184,27 +91,6 @@ describe('wrapRemoteCommandForPosixShell', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it('sends a long command plain when asked to', () => {
|
||||
const wrapped = wrapRemoteCommandForPosixShell(`# ${'padding'.repeat(2_000)}`, {
|
||||
compress: false
|
||||
})
|
||||
expect(wrapped).toContain('printf %b "$@"')
|
||||
expect(wrapped).not.toContain('base64')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32' || !existsSync('/bin/tcsh'))(
|
||||
'keeps every login-shell word bounded for long metacharacter-heavy commands',
|
||||
() => {
|
||||
const expected = '$"`'.repeat(2_000)
|
||||
const command = `printf '%s' ${quotePosixShell(expected)}`
|
||||
const result = runThroughShell('/bin/tcsh', command)
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stderr).toBe('')
|
||||
expect(result.stdout).toBe(expected)
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32' || !existsSync('/bin/tcsh'))(
|
||||
'bounds login-shell words when the compressed payload spans multiple chunks',
|
||||
() => {
|
||||
@@ -221,31 +107,6 @@ describe('wrapRemoteCommandForPosixShell', () => {
|
||||
expect(result.stdout).toBe(expected)
|
||||
}
|
||||
)
|
||||
|
||||
for (const shell of [
|
||||
'/bin/sh',
|
||||
'/bin/bash',
|
||||
'/bin/dash',
|
||||
'/bin/zsh',
|
||||
'/bin/ksh',
|
||||
'/bin/csh',
|
||||
'/bin/tcsh',
|
||||
'/usr/bin/fish',
|
||||
'/usr/local/bin/fish',
|
||||
'/opt/homebrew/bin/fish'
|
||||
]) {
|
||||
it.skipIf(process.platform === 'win32' || !existsSync(shell)).each([1, 1_000])(
|
||||
`survives the real ${shell} parser with %i repetitions`,
|
||||
(repetitions) => {
|
||||
const expected = "first\nsecond '$`\\n\\\\ ! ☃\n".repeat(repetitions)
|
||||
const command = `printf '%s' ${quotePosixShell(expected)}`
|
||||
const result = runThroughShell(shell, command)
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stderr).toBe('')
|
||||
expect(result.stdout).toBe(expected)
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
function runThroughShell(shell: string, command: string, input?: string) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { STAR_NAG_INITIAL_THRESHOLD } from '../../shared/constants'
|
||||
import '../../shared/constants'
|
||||
import {
|
||||
createDeferred,
|
||||
createHarness,
|
||||
@@ -60,147 +60,6 @@ describe('StarNagService', () => {
|
||||
consoleInfoMock.mockRestore()
|
||||
})
|
||||
|
||||
it('allows force_show to bypass the persisted cooldown', () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
const { service } = createHarness({
|
||||
starNagDeferredUntil: Date.now() + 3 * 24 * 60 * 60 * 1000
|
||||
})
|
||||
|
||||
service.registerIpcHandlers()
|
||||
getIpcHandler('star-nag:forceShow')()
|
||||
|
||||
expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', {
|
||||
mode: 'gh',
|
||||
surface: 'card'
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the force_show source through exposure and dismissal', () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
const { service, ui } = createHarness()
|
||||
|
||||
service.registerIpcHandlers()
|
||||
getIpcHandler('star-nag:forceShow')()
|
||||
getIpcHandler('star-nag:dismiss')()
|
||||
|
||||
expect(consoleInfoMock).toHaveBeenNthCalledWith(1, {
|
||||
event: 'star_nag_shown',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'force_show'
|
||||
})
|
||||
expect(consoleInfoMock).toHaveBeenNthCalledWith(2, {
|
||||
event: 'star_nag_dismissed',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'force_show',
|
||||
next_threshold: STAR_NAG_INITIAL_THRESHOLD * 2
|
||||
})
|
||||
expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD * 2)
|
||||
})
|
||||
|
||||
it('does not log or block a later force_show when no window exists', () => {
|
||||
const { service } = createHarness()
|
||||
|
||||
service.registerIpcHandlers()
|
||||
const forceShow = getIpcHandler('star-nag:forceShow')
|
||||
forceShow()
|
||||
|
||||
expect(consoleInfoMock).not.toHaveBeenCalled()
|
||||
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
forceShow()
|
||||
|
||||
expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', {
|
||||
mode: 'gh',
|
||||
surface: 'card'
|
||||
})
|
||||
expect(consoleInfoMock).toHaveBeenCalledWith({
|
||||
event: 'star_nag_shown',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'force_show'
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps threshold source when force_show is requested during a successful threshold evaluation', async () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
const deferredStarCheck = createDeferred<boolean | null>()
|
||||
checkOrcaStarredMock.mockReturnValue(deferredStarCheck.promise)
|
||||
const { service, emitAgentStarted } = createHarness()
|
||||
|
||||
service.start()
|
||||
service.registerIpcHandlers()
|
||||
emitAgentStarted(45)
|
||||
getIpcHandler('star-nag:forceShow')()
|
||||
|
||||
expect(window.webContents.send).not.toHaveBeenCalled()
|
||||
expect(consoleInfoMock).not.toHaveBeenCalled()
|
||||
|
||||
deferredStarCheck.resolve(false)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(window.webContents.send).toHaveBeenCalledTimes(1)
|
||||
expect(consoleInfoMock).toHaveBeenCalledTimes(1)
|
||||
expect(consoleInfoMock).toHaveBeenCalledWith({
|
||||
event: 'star_nag_shown',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'threshold'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not replay a stale queued force_show after threshold delivery wins', async () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
const firstStarCheck = createDeferred<boolean | null>()
|
||||
checkOrcaStarredMock.mockReturnValueOnce(firstStarCheck.promise).mockResolvedValue(null)
|
||||
const { service, emitAgentStarted } = createHarness()
|
||||
|
||||
service.start()
|
||||
service.registerIpcHandlers()
|
||||
emitAgentStarted(45)
|
||||
getIpcHandler('star-nag:forceShow')()
|
||||
|
||||
firstStarCheck.resolve(false)
|
||||
await flushAsyncWork()
|
||||
getIpcHandler('star-nag:dismiss')()
|
||||
|
||||
emitAgentStarted(114)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(window.webContents.send).toHaveBeenCalledTimes(1)
|
||||
expect(consoleInfoMock.mock.calls).toEqual([
|
||||
[
|
||||
{
|
||||
event: 'star_nag_shown',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'threshold'
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
event: 'star_nag_dismissed',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'threshold',
|
||||
next_threshold: STAR_NAG_INITIAL_THRESHOLD * 2
|
||||
}
|
||||
]
|
||||
])
|
||||
})
|
||||
|
||||
it('does not show after completion wins an in-flight threshold evaluation', async () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
@@ -221,81 +80,4 @@ describe('StarNagService', () => {
|
||||
expect(window.webContents.send).not.toHaveBeenCalled()
|
||||
expect(consoleInfoMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps threshold source when an in-flight star check falls back to the browser', async () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
const deferredStarCheck = createDeferred<boolean | null>()
|
||||
checkOrcaStarredMock.mockReturnValue(deferredStarCheck.promise)
|
||||
const { service, emitAgentStarted } = createHarness()
|
||||
|
||||
service.start()
|
||||
service.registerIpcHandlers()
|
||||
emitAgentStarted(45)
|
||||
getIpcHandler('star-nag:forceShow')()
|
||||
|
||||
expect(window.webContents.send).not.toHaveBeenCalled()
|
||||
expect(consoleInfoMock).not.toHaveBeenCalled()
|
||||
|
||||
deferredStarCheck.resolve(null)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(window.webContents.send).toHaveBeenCalledTimes(1)
|
||||
expect(consoleInfoMock).toHaveBeenCalledTimes(1)
|
||||
expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', {
|
||||
mode: 'web',
|
||||
surface: 'card'
|
||||
})
|
||||
expect(consoleInfoMock).toHaveBeenCalledWith({
|
||||
event: 'star_nag_shown',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'threshold'
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores stray and duplicate dismissals without logging or advancing backoff', () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
const { service, store, ui } = createHarness()
|
||||
|
||||
service.registerIpcHandlers()
|
||||
const dismiss = getIpcHandler('star-nag:dismiss')
|
||||
dismiss()
|
||||
|
||||
expect(consoleInfoMock).not.toHaveBeenCalled()
|
||||
expect(store.updateUI).not.toHaveBeenCalled()
|
||||
expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD)
|
||||
|
||||
getIpcHandler('star-nag:forceShow')()
|
||||
dismiss()
|
||||
dismiss()
|
||||
|
||||
const dismissedLogs = consoleInfoMock.mock.calls.filter(
|
||||
([payload]) => (payload as { event?: string }).event === 'star_nag_dismissed'
|
||||
)
|
||||
expect(dismissedLogs).toHaveLength(1)
|
||||
expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD * 2)
|
||||
})
|
||||
|
||||
it('marks completion without adding duplicate success logging', () => {
|
||||
const window = createWindow()
|
||||
browserWindowMock.getAllWindows.mockReturnValue([window])
|
||||
const { service, ui } = createHarness()
|
||||
|
||||
service.registerIpcHandlers()
|
||||
getIpcHandler('star-nag:forceShow')()
|
||||
getIpcHandler('star-nag:complete')()
|
||||
|
||||
expect(ui.starNagCompleted).toBe(true)
|
||||
expect(consoleInfoMock).toHaveBeenCalledTimes(1)
|
||||
expect(consoleInfoMock).toHaveBeenCalledWith({
|
||||
event: 'star_nag_shown',
|
||||
app_version: '1.2.3',
|
||||
threshold: STAR_NAG_INITIAL_THRESHOLD,
|
||||
agents_since_baseline: 35,
|
||||
source: 'force_show'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
import { join } from 'node:path'
|
||||
import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
resetWindowsSecurityLoadForTests,
|
||||
setWindowsSecurityForTests
|
||||
} from '../../shared/windows-security-addon'
|
||||
import {
|
||||
probeWindowsInstallDirAcl,
|
||||
resetWindowsInstallDirAclProbeForTest,
|
||||
WINDOWS_INSTALL_DIR_ACL_BREADCRUMB,
|
||||
type WindowsInstallDirAclProbeOptions
|
||||
} from './windows-install-dir-acl-probe'
|
||||
import { isInstallDirAclPoisonVerdict } from './windows-install-dir-package-acl-repair'
|
||||
import {
|
||||
ALL_PACKAGES_ACE,
|
||||
installFakeDacls,
|
||||
ORPHAN_PACKAGE_ACE,
|
||||
RESTRICTED_PACKAGES_ACE
|
||||
} from './windows-install-dir-acl.test-fixture'
|
||||
|
||||
const INSTALL_DIR = 'C:\\Users\\neil\\AppData\\Local\\Programs\\orca'
|
||||
const ORPHAN = ORPHAN_PACKAGE_ACE
|
||||
const RESTRICTED_GRANT = RESTRICTED_PACKAGES_ACE
|
||||
|
||||
function probe(options: WindowsInstallDirAclProbeOptions = {}): Promise<Record<string, unknown>> {
|
||||
return new Promise((resolve) => {
|
||||
probeWindowsInstallDirAcl({
|
||||
platform: 'win32',
|
||||
installDir: INSTALL_DIR,
|
||||
fileExists: (path) => path.endsWith('ffmpeg.dll'),
|
||||
...options,
|
||||
recordBreadcrumb: (name, data) => {
|
||||
resolve({ ...(data as Record<string, unknown>), name })
|
||||
return undefined
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Every target returns the same ACE set on top of the system baseline. */
|
||||
function probeWith(...aces: string[]): Promise<Record<string, unknown>> {
|
||||
installFakeDacls(() => aces)
|
||||
return probe()
|
||||
}
|
||||
|
||||
describe('probeWindowsInstallDirAcl', () => {
|
||||
beforeEach(() => {
|
||||
resetWindowsInstallDirAclProbeForTest()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resetWindowsSecurityLoadForTests()
|
||||
})
|
||||
|
||||
it('reports a clean DACL as unpoisoned', async () => {
|
||||
installFakeDacls(() => [])
|
||||
const data = await probe()
|
||||
expect(data.name).toBe(WINDOWS_INSTALL_DIR_ACL_BREADCRUMB)
|
||||
expect(data.status).toBe('ok')
|
||||
expect(data.orphanPackageSidCount).toBe(0)
|
||||
expect(data.matchesPoisonSignature).toBe(false)
|
||||
})
|
||||
|
||||
it('flags an orphan package SID with no well-known grant', async () => {
|
||||
const data = await probeWith(ORPHAN)
|
||||
expect(data.matchesPoisonSignature).toBe(true)
|
||||
expect(data.orphanPackageSidCount).toBe(1)
|
||||
expect(data.orphanPackageSids).toBe('S-1-15-2-999-999-999')
|
||||
expect(data.hasWellKnownPackageGrant).toBe(false)
|
||||
})
|
||||
|
||||
it('clears the signature once the restricted package ACE grants access', async () => {
|
||||
const data = await probeWith(RESTRICTED_GRANT, ORPHAN)
|
||||
expect(data.hasWellKnownPackageGrant).toBe(true)
|
||||
expect(data.hasRestrictedPackageGrant).toBe(true)
|
||||
expect(data.orphanPackageSidCount).toBe(1)
|
||||
expect(data.matchesPoisonSignature).toBe(false)
|
||||
})
|
||||
|
||||
// Orphan plus ALL APPLICATION PACKAGES launched clean on Windows 10.0.26200/Electron 43.4.1; it must not match the reproduced poison.
|
||||
it.each([
|
||||
['the AC alias', ALL_PACKAGES_ACE],
|
||||
['the raw SID form', '(A;OICI;0x1200a9;;;S-1-15-2-1)']
|
||||
])('clears the signature when only ALL APPLICATION PACKAGES grants (%s)', async (_l, ace) => {
|
||||
const data = await probeWith(ace, ORPHAN)
|
||||
expect(data.hasWellKnownPackageGrant).toBe(true)
|
||||
expect(data.hasRestrictedPackageGrant).toBe(false)
|
||||
expect(data.matchesPoisonSignature).toBe(false)
|
||||
})
|
||||
|
||||
// Deny/inherit-only ACEs grant no access on this object and cannot satisfy the orphan.
|
||||
it.each([
|
||||
['deny', '(D;OICI;FA;;;AC)'],
|
||||
['inherit-only', '(A;OICIIO;GRGX;;;AC)'],
|
||||
['restricted deny', '(D;;FA;;;S-1-15-2-2)'],
|
||||
['restricted inherit-only', '(A;CIOIIO;GRGX;;;S-1-15-2-2)']
|
||||
])('does not let a %s well-known ACE satisfy an orphan', async (_label, ace) => {
|
||||
const data = await probeWith(ace, ORPHAN)
|
||||
expect(data.hasWellKnownPackageGrant).toBe(false)
|
||||
expect(data.hasRestrictedPackageGrant).toBe(false)
|
||||
expect(data.matchesPoisonSignature).toBe(true)
|
||||
})
|
||||
|
||||
it('does not let a grant on one target mask its absence on another', async () => {
|
||||
installFakeDacls((target) =>
|
||||
target.endsWith('ffmpeg.dll') ? [ORPHAN] : [RESTRICTED_GRANT, ORPHAN]
|
||||
)
|
||||
const data = await probe()
|
||||
expect(data.hasWellKnownPackageGrant).toBe(true)
|
||||
expect(data.matchesPoisonSignature).toBe(true)
|
||||
})
|
||||
|
||||
// SDDL SIDs stay stable across localized display names.
|
||||
it('reads a repaired tree as clean from SIDs alone', async () => {
|
||||
let verdict: CrashReportBreadcrumbData = {}
|
||||
installFakeDacls(() => [ORPHAN, RESTRICTED_GRANT])
|
||||
const data = await probe({
|
||||
onDone: (done) => (verdict = done)
|
||||
})
|
||||
expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false)
|
||||
expect(data.status).toBe('ok')
|
||||
expect(data.orphanPackageSidCount).toBe(1)
|
||||
expect(data.hasRestrictedPackageGrant).toBe(true)
|
||||
})
|
||||
|
||||
it('matches the well-known SIDs exactly, not by prefix', async () => {
|
||||
const data = await probeWith('(A;OICI;0x1200a9;;;S-1-15-2-1234567890)')
|
||||
expect(data.orphanPackageSidCount).toBe(1)
|
||||
expect(data.hasWellKnownPackageGrant).toBe(false)
|
||||
expect(data.matchesPoisonSignature).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores capability SIDs, which are a different family and harmless', async () => {
|
||||
const data = await probeWith('(A;;0x100020;;;S-1-15-3-65536-599108337-2355189375-1353122160)')
|
||||
expect(data.orphanPackageSidCount).toBe(0)
|
||||
expect(data.matchesPoisonSignature).toBe(false)
|
||||
})
|
||||
|
||||
it('probes a content file, not just the directory object', async () => {
|
||||
const fake = installFakeDacls(() => [ORPHAN])
|
||||
await probe()
|
||||
expect(fake.calls).toEqual([INSTALL_DIR, join(INSTALL_DIR, 'ffmpeg.dll')])
|
||||
})
|
||||
|
||||
// Real DACL-only SDDL from Windows 10.0.26200.
|
||||
it.each([
|
||||
[
|
||||
'a repaired module file',
|
||||
'D:AI(A;;0x1200a9;;;S-1-15-2-2)(A;;0x1200a9;;;S-1-15-2-999-999-999)' +
|
||||
'(A;ID;0x1200a9;;;S-1-15-2-999-999-999)(A;ID;FA;;;SY)(A;ID;FA;;;BA)' +
|
||||
'(A;ID;FA;;;S-1-5-21-432636774-4279371817-3971399515-1001)',
|
||||
false
|
||||
],
|
||||
[
|
||||
'a poisoned dir whose AC ACE denies',
|
||||
'D:AI(D;;0x100116;;;AC)(A;OICI;0x1200a9;;;S-1-15-2-999-999-999)' +
|
||||
'(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)' +
|
||||
'(A;OICIID;FA;;;S-1-5-21-432636774-4279371817-3971399515-1001)',
|
||||
true
|
||||
]
|
||||
])('reads a real captured DACL: %s', async (_label, saved, poisoned) => {
|
||||
installFakeDacls(() => saved)
|
||||
const data = await probe({
|
||||
fileExists: () => false
|
||||
})
|
||||
expect(data.orphanPackageSids).toBe('S-1-15-2-999-999-999')
|
||||
expect(data.matchesPoisonSignature).toBe(poisoned)
|
||||
})
|
||||
|
||||
it('keeps a conditional DACL unreadable instead of hiding a later package grant', async () => {
|
||||
const saved =
|
||||
'D:AI(A;OICI;0x1200a9;;;S-1-15-2-999-999-999)' +
|
||||
'(XA;OICI;FA;;;WD;(@User.Department == "Finance"))' +
|
||||
'(A;OICIID;0x1200a9;;;S-1-15-2-2)'
|
||||
let verdict: CrashReportBreadcrumbData = {}
|
||||
installFakeDacls(() => saved)
|
||||
const data = await probe({
|
||||
fileExists: () => false,
|
||||
onDone: (done) => (verdict = done)
|
||||
})
|
||||
expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' })
|
||||
expect(data.matchesPoisonSignature).toBeUndefined()
|
||||
expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false)
|
||||
})
|
||||
|
||||
// NULL DACL grants all access but proves no specific package grant.
|
||||
it('keeps a NULL DACL unreadable rather than reading it as clean', async () => {
|
||||
installFakeDacls(() => 'D:NO_ACCESS_CONTROL')
|
||||
const data = await probe({ fileExists: () => false })
|
||||
expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' })
|
||||
})
|
||||
|
||||
it('treats a read that fails as unreadable, never as a clean DACL', async () => {
|
||||
let verdict: CrashReportBreadcrumbData = {}
|
||||
installFakeDacls(() => null)
|
||||
const data = await probe({
|
||||
fileExists: () => false,
|
||||
onDone: (done) => (verdict = done)
|
||||
})
|
||||
expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' })
|
||||
expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not report malformed saved output as a clean DACL', async () => {
|
||||
installFakeDacls(() => 'orca')
|
||||
const data = await probe({
|
||||
fileExists: () => false
|
||||
})
|
||||
expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' })
|
||||
expect(data.matchesPoisonSignature).toBeUndefined()
|
||||
})
|
||||
|
||||
it('records a failure instead of throwing when no DACL can be read', async () => {
|
||||
installFakeDacls(() => null)
|
||||
const data = await probe()
|
||||
expect(data.status).toBe('failed')
|
||||
expect(data.reason).toBe('all-targets-unreadable')
|
||||
expect(data.matchesPoisonSignature).toBeUndefined()
|
||||
})
|
||||
|
||||
// Missing addon proves probe failure, never a healthy tree.
|
||||
it('records a failure, not a verdict, when the addon cannot load', async () => {
|
||||
setWindowsSecurityForTests(null)
|
||||
let verdict: CrashReportBreadcrumbData = {}
|
||||
const data = await probe({ onDone: (done) => (verdict = done) })
|
||||
expect(data.status).toBe('failed')
|
||||
expect(String(data.reason)).toContain('windows-security addon unavailable')
|
||||
expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['darwin', { platform: 'darwin' as NodeJS.Platform }],
|
||||
['serve mode', { platform: 'win32' as NodeJS.Platform, isServeMode: true }]
|
||||
])('does no work on %s', async (_label, options) => {
|
||||
const fake = installFakeDacls(() => [ORPHAN])
|
||||
const record = vi.fn()
|
||||
const fileExists = vi.fn(() => true)
|
||||
probeWindowsInstallDirAcl({
|
||||
installDir: INSTALL_DIR,
|
||||
fileExists,
|
||||
recordBreadcrumb: record,
|
||||
...options
|
||||
})
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
expect(fake.calls).toHaveLength(0)
|
||||
expect(fileExists).not.toHaveBeenCalled()
|
||||
expect(record).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs once per process', async () => {
|
||||
const fake = installFakeDacls(() => [ORPHAN])
|
||||
await probe()
|
||||
const before = fake.calls.length
|
||||
probeWindowsInstallDirAcl({ platform: 'win32', installDir: INSTALL_DIR })
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
expect(fake.calls).toHaveLength(before)
|
||||
})
|
||||
})
|
||||
@@ -1,258 +0,0 @@
|
||||
import * as crypto from 'node:crypto'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ChatUiLaunchTipVariant } from '../../shared/native-chat/chat-ui-launch-tip-audience'
|
||||
import type { TelemetrySettings } from '../../shared/telemetry-settings-types'
|
||||
import type { GlobalSettings } from '../../shared/global-settings-types'
|
||||
import type { Store } from '../persistence/loading-store/store'
|
||||
import {
|
||||
ensureChatUiLaunchTipCohort,
|
||||
isChatUiLaunchTipDeferredForConsent
|
||||
} from './chat-ui-launch-tip-cohort'
|
||||
import { experimentCohortProps } from './experiment-cohort-props'
|
||||
import { commonPropsSchema } from '../../shared/telemetry-events'
|
||||
import {
|
||||
BASE_COMMON,
|
||||
makeFakeSettings,
|
||||
restoreConsentEnv,
|
||||
stashAndClearConsentEnv
|
||||
} from './client-test-harness'
|
||||
|
||||
vi.mock('node:crypto', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof crypto>()),
|
||||
randomInt: vi.fn(() => 0)
|
||||
}))
|
||||
|
||||
function makeStore(
|
||||
telemetry: Partial<TelemetrySettings>,
|
||||
variant: ChatUiLaunchTipVariant = 'chat-ui-off',
|
||||
seen: string[] = [],
|
||||
preferences: Partial<GlobalSettings> = {}
|
||||
): Store {
|
||||
const settings = makeFakeSettings({
|
||||
optedIn: true,
|
||||
installId: 'install',
|
||||
existedBeforeTelemetryRelease: true,
|
||||
...telemetry
|
||||
})
|
||||
Object.assign(settings, preferences)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: supplies every Store method the cohort assignment reads or writes.
|
||||
return {
|
||||
getSettings: () => settings,
|
||||
getUI: () => ({ featureTipsSeenIds: seen }),
|
||||
getChatUiLaunchTipVariant: () => variant,
|
||||
updateSettings: vi.fn((updates: { telemetry: TelemetrySettings }) => {
|
||||
settings.telemetry = updates.telemetry
|
||||
})
|
||||
} as unknown as Store
|
||||
}
|
||||
|
||||
describe('ensureChatUiLaunchTipCohort', () => {
|
||||
let env: Record<string, string | undefined>
|
||||
beforeEach(() => {
|
||||
env = stashAndClearConsentEnv()
|
||||
vi.mocked(crypto.randomInt)
|
||||
.mockReset()
|
||||
.mockImplementation(() => 0)
|
||||
})
|
||||
afterEach(() => {
|
||||
restoreConsentEnv(env)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ draw: 3, cohort: 'control' },
|
||||
{ draw: 4, cohort: 'treatment' }
|
||||
])('assigns draw $draw to $cohort and keeps the frozen cohort', ({ draw, cohort }) => {
|
||||
vi.mocked(crypto.randomInt).mockImplementationOnce(() => draw)
|
||||
const store = makeStore({})
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort)
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort)
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipCohort).toBeUndefined()
|
||||
expect(store.getSettings().telemetry?.installId).toBe('install')
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ draw: 3, cohort: 'control', targeting: undefined, emphasis: undefined },
|
||||
{ draw: 4, cohort: 'treatment', targeting: { mode: 'all' }, emphasis: 'normal' }
|
||||
])(
|
||||
'expands an existing control to $cohort once at draw $draw',
|
||||
({ draw, cohort, targeting, emphasis }) => {
|
||||
vi.mocked(crypto.randomInt).mockImplementationOnce(() => draw)
|
||||
const store = makeStore({ chatUiLaunchTipCohort: 'control' })
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort)
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort)
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipTargeting).toEqual(targeting)
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipButtonEmphasis).toBe(emphasis)
|
||||
|
||||
vi.mocked(crypto.randomInt).mockImplementation(() => 6)
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort)
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort)
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipCohort).toBe('control')
|
||||
expect(experimentCohortProps(store)).toMatchObject({
|
||||
chat_ui_launch_tip_v1: 'control',
|
||||
chat_ui_launch_tip_rollout_v1: cohort
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
it('waits for consent before expanding an existing control', () => {
|
||||
const store = makeStore({ chatUiLaunchTipCohort: 'control', optedIn: false })
|
||||
vi.mocked(crypto.randomInt).mockImplementationOnce(() => 6)
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe('control')
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBeUndefined()
|
||||
|
||||
store.getSettings().telemetry!.optedIn = true
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment')
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipCohort).toBe('control')
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe('treatment')
|
||||
})
|
||||
|
||||
it.each([0, 1])('freezes button emphasis draw %s independently', (draw) => {
|
||||
vi.mocked(crypto.randomInt)
|
||||
.mockImplementationOnce(() => 7)
|
||||
.mockImplementationOnce(() => 0)
|
||||
.mockImplementationOnce(() => draw)
|
||||
const store = makeStore({})
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment')
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipButtonEmphasis).toBe(
|
||||
draw === 0 ? 'normal' : 'swapped'
|
||||
)
|
||||
ensureChatUiLaunchTipCohort(store)
|
||||
expect(store.updateSettings).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ variant: 'chat-ui-off', surface: 'terminal' },
|
||||
{ variant: 'chat-ui-off', surface: 'chat' },
|
||||
{ variant: 'chat-ui-on', surface: 'terminal' },
|
||||
{ variant: 'chat-ui-on', surface: 'chat' },
|
||||
{ variant: 'chat-ui-on', surface: undefined }
|
||||
] as const)(
|
||||
'targets the current $surface default for the frozen $variant audience and preserves enrollment',
|
||||
({ variant, surface }) => {
|
||||
for (const draw of [0, 1]) {
|
||||
vi.mocked(crypto.randomInt)
|
||||
.mockReset()
|
||||
.mockImplementationOnce(() => 8)
|
||||
.mockImplementationOnce(() => draw)
|
||||
const store = makeStore({}, variant, [], { agentDefaultSurface: surface })
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment')
|
||||
expect(crypto.randomInt).toHaveBeenNthCalledWith(1, 10)
|
||||
expect(crypto.randomInt).toHaveBeenNthCalledWith(2, 2)
|
||||
const targeting = store.getSettings().telemetry?.chatUiLaunchTipTargeting
|
||||
expect(targeting).toEqual(
|
||||
draw === 0 ? { mode: 'all' } : { mode: 'not-switched', eligible: surface !== 'chat' }
|
||||
)
|
||||
store.getSettings().agentDefaultSurface = surface === 'chat' ? 'terminal' : 'chat'
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment')
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipTargeting).toEqual(targeting)
|
||||
expect(store.getChatUiLaunchTipVariant()).toBe(variant)
|
||||
expect(store.updateSettings).toHaveBeenCalledTimes(1)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
{ variant: 'chat-ui-off', before: 'terminal', atEnrollment: 'chat', eligible: false },
|
||||
{ variant: 'chat-ui-on', before: 'chat', atEnrollment: 'terminal', eligible: true }
|
||||
] as const)(
|
||||
'uses the $atEnrollment default after consent delays enrollment for $variant',
|
||||
({ variant, before, atEnrollment, eligible }) => {
|
||||
vi.mocked(crypto.randomInt)
|
||||
.mockImplementationOnce(() => 8)
|
||||
.mockImplementationOnce(() => 1)
|
||||
const store = makeStore({ optedIn: null }, variant, [], { agentDefaultSurface: before })
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBeUndefined()
|
||||
expect(crypto.randomInt).not.toHaveBeenCalled()
|
||||
|
||||
store.getSettings().agentDefaultSurface = atEnrollment
|
||||
store.getSettings().telemetry!.optedIn = true
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment')
|
||||
expect(store.getSettings().telemetry?.chatUiLaunchTipTargeting).toEqual({
|
||||
mode: 'not-switched',
|
||||
eligible
|
||||
})
|
||||
expect(store.getChatUiLaunchTipVariant()).toBe(variant)
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
'treatment-center',
|
||||
'treatment',
|
||||
'treatment-live-switch',
|
||||
'treatment-swapped-buttons'
|
||||
] as const)('preserves existing %s assignments', (cohort) => {
|
||||
const store = makeStore({
|
||||
chatUiLaunchTipCohort: cohort
|
||||
})
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort)
|
||||
expect(crypto.randomInt).not.toHaveBeenCalled()
|
||||
expect(store.updateSettings).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ draw: 7, cohort: 'treatment' },
|
||||
{ draw: 8, cohort: 'treatment' },
|
||||
{ draw: 9, cohort: 'treatment' }
|
||||
])(
|
||||
'emits schema-valid targeting props immediately after $cohort enrollment',
|
||||
({ draw, cohort }) => {
|
||||
vi.mocked(crypto.randomInt)
|
||||
.mockImplementationOnce(() => draw)
|
||||
.mockImplementationOnce(() => 1)
|
||||
const store = makeStore({ onboardingLanguageCohort: 'treatment' })
|
||||
const props = experimentCohortProps(store)
|
||||
expect(props).toEqual({
|
||||
onboarding_language_v1: 'treatment',
|
||||
chat_ui_launch_tip_v1: undefined,
|
||||
chat_ui_launch_tip_rollout_v1: cohort,
|
||||
chat_ui_launch_tip_targeting_v1: 'not-switched',
|
||||
chat_ui_launch_tip_button_emphasis_v1: 'normal'
|
||||
})
|
||||
expect(commonPropsSchema.safeParse({ ...BASE_COMMON, ...props }).success).toBe(true)
|
||||
}
|
||||
)
|
||||
|
||||
it('ignores malformed targeting metadata rather than disabling all telemetry', () => {
|
||||
const store = makeStore({ chatUiLaunchTipCohort: 'treatment' })
|
||||
Object.assign(store.getSettings().telemetry!, { chatUiLaunchTipTargeting: { mode: 'invalid' } })
|
||||
const props = experimentCohortProps(store)
|
||||
expect(props.chat_ui_launch_tip_targeting_v1).toBeUndefined()
|
||||
expect(commonPropsSchema.safeParse({ ...BASE_COMMON, ...props }).success).toBe(true)
|
||||
})
|
||||
|
||||
it('holds the tip unenrolled while the banner is pending, then enrolls after acknowledgement', () => {
|
||||
const pending = makeStore({ optedIn: null })
|
||||
expect(ensureChatUiLaunchTipCohort(pending)).toBeUndefined()
|
||||
expect(isChatUiLaunchTipDeferredForConsent()).toBe(true)
|
||||
expect(pending.updateSettings).not.toHaveBeenCalled()
|
||||
|
||||
// Acknowledging the banner persists optedIn=true; the next launch enrolls the still-unseen tip.
|
||||
pending.getSettings().telemetry!.optedIn = true
|
||||
const cohort = ensureChatUiLaunchTipCohort(pending)
|
||||
expect(['control', 'treatment']).toContain(cohort)
|
||||
expect(isChatUiLaunchTipDeferredForConsent()).toBe(false)
|
||||
expect(pending.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort)
|
||||
})
|
||||
|
||||
it('releases a pending profile unenrolled after the banner is declined, so the tip shows as before', () => {
|
||||
const pending = makeStore({ optedIn: null })
|
||||
ensureChatUiLaunchTipCohort(pending)
|
||||
expect(isChatUiLaunchTipDeferredForConsent()).toBe(true)
|
||||
|
||||
pending.getSettings().telemetry!.optedIn = false
|
||||
expect(ensureChatUiLaunchTipCohort(pending)).toBeUndefined()
|
||||
expect(isChatUiLaunchTipDeferredForConsent()).toBe(false)
|
||||
expect(pending.updateSettings).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['outside the audience', makeStore({}, 'none')],
|
||||
['already shown the tip', makeStore({}, 'chat-ui-off', ['chat-ui-here'])],
|
||||
['opted out', makeStore({ optedIn: false })]
|
||||
])('leaves a profile %s unenrolled, so it keeps today’s behaviour', (_label, store) => {
|
||||
expect(ensureChatUiLaunchTipCohort(store)).toBeUndefined()
|
||||
expect(isChatUiLaunchTipDeferredForConsent()).toBe(false)
|
||||
expect(store.updateSettings).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -85,173 +85,6 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', ()
|
||||
await expectChildTerminated(child)
|
||||
})
|
||||
|
||||
it('passes prepared provider environment to local agent subprocesses', async () => {
|
||||
const listeners = new Map<string, (value: unknown) => void>()
|
||||
const child = {
|
||||
pid: 123,
|
||||
kill: vi.fn(),
|
||||
stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) },
|
||||
stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) },
|
||||
stdin: { end: vi.fn() },
|
||||
on: vi.fn((event, callback) => listeners.set(event, callback))
|
||||
}
|
||||
spawnMock.mockReturnValue(child as never)
|
||||
|
||||
const pending = generateCommitMessageFromContext(
|
||||
{
|
||||
branch: 'main',
|
||||
stagedSummary: 'M\tREADME.md',
|
||||
stagedPatch: '+hello'
|
||||
},
|
||||
{
|
||||
agentId: 'custom',
|
||||
model: '',
|
||||
customAgentCommand: 'orca-test-agent-nope'
|
||||
},
|
||||
{
|
||||
kind: 'local',
|
||||
cwd: '/repo',
|
||||
env: { ...process.env, CODEX_HOME: '/managed/codex-home' }
|
||||
}
|
||||
)
|
||||
|
||||
listeners.get('stdout:data')?.(Buffer.from('Add README note\n'))
|
||||
listeners.get('close')?.(0)
|
||||
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
success: true,
|
||||
message: 'Add README note'
|
||||
})
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'orca-test-agent-nope',
|
||||
[],
|
||||
expect.objectContaining({
|
||||
env: expect.objectContaining({ CODEX_HOME: '/managed/codex-home' })
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('routes WSL local commit generation through the selected distro login shell', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
process.env.ORCA_HOST_ONLY_SECRET = 'do-not-leak'
|
||||
const listeners = new Map<string, (value: unknown) => void>()
|
||||
const child = {
|
||||
pid: 123,
|
||||
kill: vi.fn(),
|
||||
stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) },
|
||||
stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) },
|
||||
stdin: { end: vi.fn() },
|
||||
on: vi.fn((event, callback) => listeners.set(event, callback))
|
||||
}
|
||||
spawnMock.mockReturnValue(child as never)
|
||||
|
||||
const pending = generateCommitMessageFromContext(
|
||||
{
|
||||
branch: 'main',
|
||||
stagedSummary: 'M\tREADME.md',
|
||||
stagedPatch: '+hello'
|
||||
},
|
||||
{
|
||||
agentId: 'custom',
|
||||
model: '',
|
||||
customAgentCommand: 'agent --mode fast'
|
||||
},
|
||||
{
|
||||
kind: 'local',
|
||||
cwd: 'C:\\repo',
|
||||
wslDistro: 'Ubuntu 24.04',
|
||||
env: { ...process.env, CODEX_HOME: '/home/tester/.codex' }
|
||||
}
|
||||
)
|
||||
|
||||
listeners.get('stdout:data')?.(Buffer.from('Update README\n'))
|
||||
listeners.get('close')?.(0)
|
||||
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
success: true,
|
||||
message: 'Update README'
|
||||
})
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'wsl.exe',
|
||||
['-d', 'Ubuntu 24.04', '--exec', 'sh', '-lc', expect.any(String)],
|
||||
expect.objectContaining({
|
||||
// #16463: explicit native cwd avoids inheriting a deletable WSL UNC worktree; guest cwd stays inside the command.
|
||||
cwd: expect.any(String),
|
||||
windowsHide: true,
|
||||
env: expect.objectContaining({ CODEX_HOME: '/home/tester/.codex' })
|
||||
})
|
||||
)
|
||||
const spawnEnv = spawnMock.mock.calls[0]?.[2]?.env as NodeJS.ProcessEnv
|
||||
expect(spawnEnv.ORCA_HOST_ONLY_SECRET).toBeUndefined()
|
||||
const shellCommand = spawnMock.mock.calls[0]?.[1]?.[5] as string
|
||||
expect(shellCommand).toContain('getent passwd')
|
||||
expect(shellCommand).toContain('exec "$_orca_wsl_shell" -ilc')
|
||||
expect(shellCommand).toContain('/mnt/c/repo')
|
||||
expect(shellCommand).toContain("'agent'")
|
||||
expect(shellCommand).toContain('--mode')
|
||||
expect(shellCommand).toContain('fast')
|
||||
})
|
||||
})
|
||||
|
||||
it('routes Windows batch-script agent commands through cmd.exe', async () => {
|
||||
const originalComSpec = process.env.ComSpec
|
||||
process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe'
|
||||
try {
|
||||
await withPlatform('win32', async () => {
|
||||
const listeners = new Map<string, (value: unknown) => void>()
|
||||
const child = {
|
||||
pid: 123,
|
||||
kill: vi.fn(),
|
||||
stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) },
|
||||
stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) },
|
||||
stdin: { end: vi.fn() },
|
||||
on: vi.fn((event, callback) => listeners.set(event, callback))
|
||||
}
|
||||
spawnMock.mockReturnValue(child as never)
|
||||
|
||||
const pending = generateCommitMessageFromContext(
|
||||
{
|
||||
branch: 'main',
|
||||
stagedSummary: 'M\tREADME.md',
|
||||
stagedPatch: '+hello'
|
||||
},
|
||||
{
|
||||
agentId: 'custom',
|
||||
model: '',
|
||||
customAgentCommand: 'C:/tools/agent.cmd'
|
||||
},
|
||||
{
|
||||
kind: 'local',
|
||||
cwd: 'C:\\repo'
|
||||
}
|
||||
)
|
||||
|
||||
listeners.get('stdout:data')?.(Buffer.from('Update README\n'))
|
||||
listeners.get('close')?.(0)
|
||||
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
success: true,
|
||||
message: 'Update README'
|
||||
})
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'C:\\Windows\\System32\\cmd.exe',
|
||||
['/d /v:off /s /c ""C:/tools/agent.cmd""'],
|
||||
expect.objectContaining({
|
||||
cwd: 'C:\\repo',
|
||||
windowsHide: true,
|
||||
windowsVerbatimArguments: true
|
||||
})
|
||||
)
|
||||
})
|
||||
} finally {
|
||||
if (originalComSpec === undefined) {
|
||||
delete process.env.ComSpec
|
||||
} else {
|
||||
process.env.ComSpec = originalComSpec
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects unsafe argv prompts for Windows batch-script agent commands', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
const result = await generateCommitMessageFromContext(
|
||||
|
||||
@@ -6,8 +6,8 @@ import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan'
|
||||
import { prepareSourceControlReadOnlyPlan } from './source-control-read-only-policy'
|
||||
import { stageLocalPromptFiles } from './source-control-prompt-files'
|
||||
import { runLocalPlanForAgent } from './source-control-local-generation'
|
||||
import { cancelLocalGeneration } from './source-control-generation-lanes'
|
||||
import './source-control-local-generation'
|
||||
import './source-control-generation-lanes'
|
||||
|
||||
const { probe } = vi.hoisted(() => ({ probe: vi.fn() }))
|
||||
vi.mock('./source-control-policy-probe', () => ({ runSourceControlPolicyProbe: probe }))
|
||||
@@ -37,56 +37,6 @@ const spawnAgent = vi.fn(() => {
|
||||
throw new Error('Unexpected semantic process')
|
||||
})
|
||||
|
||||
it('cancels during configuration admission without launching a semantic agent', async () => {
|
||||
const cwd = await directory()
|
||||
const entered = Promise.withResolvers<void>()
|
||||
probe.mockImplementation(({ signal }: { signal: AbortSignal }) => ({
|
||||
result: new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
entered.resolve()
|
||||
}),
|
||||
processClosed: Promise.resolve()
|
||||
}))
|
||||
const result = runLocalPlanForAgent({
|
||||
agentId: 'codex',
|
||||
plan: planned('codex'),
|
||||
target: { kind: 'local', cwd, env: { CODEX_HOME: cwd } },
|
||||
operation: 'conversation-name',
|
||||
spawnAgent
|
||||
})
|
||||
await entered.promise
|
||||
cancelLocalGeneration('conversation-name', cwd)
|
||||
await expect(result).resolves.toMatchObject({ success: false, canceled: true })
|
||||
expect(spawnAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps non-title helpers inside the enforced task policy', async () => {
|
||||
const cwd = await directory()
|
||||
for (const agentId of ['amp', 'muse', 'kimi'] as const) {
|
||||
const result = planCommitMessageGeneration(
|
||||
{
|
||||
agentId,
|
||||
model: agentId === 'amp' ? 'smart' : 'default',
|
||||
...(agentId === 'kimi' ? { agentArgs: '--agent custom' } : {})
|
||||
},
|
||||
'Name this chat'
|
||||
)
|
||||
if (!result.ok) {
|
||||
throw new Error(result.error)
|
||||
}
|
||||
await expect(
|
||||
runLocalPlanForAgent({
|
||||
agentId,
|
||||
plan: result.plan,
|
||||
target: { kind: 'local', cwd },
|
||||
operation: 'commit-message',
|
||||
spawnAgent
|
||||
})
|
||||
).resolves.toMatchObject({ success: false })
|
||||
}
|
||||
expect(spawnAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('disables every effective Codex MCP name, including dotted names, after recipe overrides', async () => {
|
||||
probe.mockReturnValue({
|
||||
result: Promise.resolve({
|
||||
@@ -225,68 +175,3 @@ it('composes agy session settings without losing existing read denies or selecte
|
||||
expect(policy.args).toContain('high')
|
||||
expect(await readFile(join(cwd, 'settings.json'), 'utf8')).not.toContain('write_file')
|
||||
})
|
||||
|
||||
it('refuses an agy build without session settings before sending the prompt', async () => {
|
||||
probe.mockReturnValue({
|
||||
result: Promise.resolve({
|
||||
stdout: '',
|
||||
stderr: ' --model Model to use\n --agent Agent profile\n'
|
||||
}),
|
||||
processClosed: Promise.resolve()
|
||||
})
|
||||
const cwd = await directory()
|
||||
await expect(
|
||||
runLocalPlanForAgent({
|
||||
agentId: 'antigravity',
|
||||
plan: planned('antigravity'),
|
||||
target: { kind: 'local', cwd },
|
||||
operation: 'commit-message',
|
||||
spawnAgent
|
||||
})
|
||||
).resolves.toMatchObject({ success: false })
|
||||
expect(spawnAgent).not.toHaveBeenCalled()
|
||||
expect(probe.mock.calls[0][0]).toMatchObject({ args: ['--help'], target: { cwd } })
|
||||
})
|
||||
|
||||
it('preserves valid selected Kimi history and named profiles for best-effort naming', async () => {
|
||||
for (const args of ['--agent review', '--session saved-chat', '--continue']) {
|
||||
const plan = planned('kimi', args)
|
||||
const prepared = await prepareSourceControlReadOnlyPlan({
|
||||
agentId: 'kimi',
|
||||
plan,
|
||||
operation: 'conversation-name',
|
||||
target: { kind: 'local', cwd: '/workspace' },
|
||||
signal: new AbortController().signal,
|
||||
spawnAgent
|
||||
}).result
|
||||
expect(prepared.args).toEqual(plan.args)
|
||||
expect(prepared.taskFiles).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('uses successful older agy help as capability evidence without swallowing a failed probe', async () => {
|
||||
probe.mockReturnValueOnce({
|
||||
result: Promise.resolve({ stdout: ' --sandbox Use a sandbox\n --model Model', stderr: '' }),
|
||||
processClosed: Promise.resolve()
|
||||
})
|
||||
const plan = planned('antigravity', '--agent review')
|
||||
const input = {
|
||||
agentId: 'antigravity',
|
||||
plan,
|
||||
operation: 'conversation-name' as const,
|
||||
target: { kind: 'local' as const, cwd: '/workspace' },
|
||||
signal: new AbortController().signal,
|
||||
spawnAgent
|
||||
}
|
||||
const prepared = await prepareSourceControlReadOnlyPlan(input).result
|
||||
expect(prepared.args).toContain('review')
|
||||
expect(prepared.args).toContain('--sandbox')
|
||||
expect(prepared.args).not.toContain('--settings')
|
||||
probe.mockReturnValueOnce({
|
||||
result: Promise.reject(new Error('Help could not start')),
|
||||
processClosed: Promise.resolve()
|
||||
})
|
||||
await expect(prepareSourceControlReadOnlyPlan(input).result).rejects.toThrow(
|
||||
'Help could not start'
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,267 +0,0 @@
|
||||
import type { getReleaseDownloadUrl } from './releases/updater-release-readiness'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import type * as UpdaterModule from './updater-service'
|
||||
import type { UpdateInstallMode } from './lifecycle/updater-state'
|
||||
import type { LinuxRootPackageType, UpdateStatus } from '../../shared/update-status-types'
|
||||
import { loadUpdaterModule, warmUpdaterModule } from './testing/updater-test-module-loader'
|
||||
import { updaterMainWindow } from './testing/updater-test-main-window'
|
||||
|
||||
const {
|
||||
browserWindowMock,
|
||||
nativeUpdaterMock,
|
||||
autoUpdaterMock,
|
||||
killAllPtyMock,
|
||||
getLinuxPackageTypeMock,
|
||||
getLinuxRootPackageTypeMock,
|
||||
recordUpdaterLifecycleMock,
|
||||
fetchNewerReleaseTagsMock,
|
||||
moduleFactories,
|
||||
resetUpdaterMocks
|
||||
} = await vi.hoisted(async () =>
|
||||
(await import('./testing/updater-test-harness')).createUpdaterMocks()
|
||||
)
|
||||
|
||||
vi.mock('electron', () => moduleFactories.electron())
|
||||
vi.mock('electron-updater', () => moduleFactories.electronUpdater())
|
||||
vi.mock('./electron-updater-loader', () => moduleFactories.electronUpdaterLoader())
|
||||
vi.mock('../ipc/pty/kill-all', () => moduleFactories.ptyKillAll())
|
||||
vi.mock('./linux-package/linux-update-package-type', () => moduleFactories.linuxUpdatePackageType())
|
||||
vi.mock('./updater-lifecycle-diagnostics', () => moduleFactories.updaterLifecycleDiagnostics())
|
||||
vi.mock('./releases/updater-changelog', () => moduleFactories.updaterChangelog())
|
||||
vi.mock('./nudges/nudge-campaign', () => moduleFactories.updaterNudge())
|
||||
vi.mock('./update-install-exit-watchdog', () => moduleFactories.updateInstallExitWatchdog())
|
||||
vi.mock('./releases/updater-prerelease-feed', () => moduleFactories.updaterPrereleaseFeed())
|
||||
vi.mock('./releases/updater-release-readiness', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
getReleaseDownloadUrl: (
|
||||
await vi.importMock<{
|
||||
getReleaseDownloadUrl: typeof getReleaseDownloadUrl
|
||||
}>('./releases/updater-prerelease-feed')
|
||||
).getReleaseDownloadUrl
|
||||
}))
|
||||
vi.mock('../local-builds/local-build-switch', () => moduleFactories.localBuildSwitch())
|
||||
vi.mock('../local-builds/local-build-feed-server', () => moduleFactories.localBuildFeedServer())
|
||||
|
||||
const packageSha512 = Buffer.alloc(64).toString('base64')
|
||||
|
||||
function downloadedEvent(packageType: LinuxRootPackageType): Record<string, unknown> {
|
||||
const fileName =
|
||||
packageType === 'deb' ? 'orca-ide_1.0.61_amd64.deb' : 'orca-ide-1.0.61.x86_64.rpm'
|
||||
return {
|
||||
version: '1.0.61',
|
||||
downloadedFile: join(tmpdir(), 'orca-updater', 'pending', fileName),
|
||||
files: [{ url: fileName, sha512: packageSha512 }]
|
||||
}
|
||||
}
|
||||
|
||||
warmUpdaterModule()
|
||||
|
||||
describe('updater Linux root packages', () => {
|
||||
beforeEach(() => {
|
||||
resetUpdaterMocks()
|
||||
})
|
||||
|
||||
async function startUpdater(
|
||||
packageType: LinuxRootPackageType | null,
|
||||
installMode: UpdateInstallMode = 'interactive'
|
||||
): Promise<{ send: ReturnType<typeof vi.fn>; updater: typeof UpdaterModule }> {
|
||||
getLinuxRootPackageTypeMock.mockReturnValue(packageType)
|
||||
vi.useFakeTimers()
|
||||
fetchNewerReleaseTagsMock.mockResolvedValue({ tags: ['v1.0.61'], state: 'ready' })
|
||||
autoUpdaterMock.checkForUpdates.mockImplementation(() => {
|
||||
autoUpdaterMock.emit('checking-for-update')
|
||||
queueMicrotask(() => autoUpdaterMock.emit('update-available', { version: '1.0.61' }))
|
||||
return Promise.resolve(undefined)
|
||||
})
|
||||
const send = vi.fn()
|
||||
const updater = await loadUpdaterModule()
|
||||
updater.setupAutoUpdater(updaterMainWindow(send), {
|
||||
getLastUpdateCheckAt: () => Date.now(),
|
||||
installMode
|
||||
})
|
||||
return { send, updater }
|
||||
}
|
||||
|
||||
function lastStatus(send: ReturnType<typeof vi.fn>): UpdateStatus | undefined {
|
||||
return send.mock.calls.findLast(([channel]) => channel === 'updater:status')?.[1]
|
||||
}
|
||||
|
||||
function markMacInstallerReady(): void {
|
||||
if (process.platform !== 'darwin') {
|
||||
return
|
||||
}
|
||||
const handler = nativeUpdaterMock.on.mock.calls.find(
|
||||
([eventName]) => eventName === 'update-downloaded'
|
||||
)?.[1] as (() => void) | undefined
|
||||
handler?.()
|
||||
}
|
||||
|
||||
async function reachDownloaded(
|
||||
updater: typeof UpdaterModule,
|
||||
event: Record<string, unknown>,
|
||||
markInstallerReady = false
|
||||
): Promise<void> {
|
||||
updater.checkForUpdatesFromMenu()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
autoUpdaterMock.downloadUpdate.mockResolvedValue([])
|
||||
updater.downloadUpdate()
|
||||
autoUpdaterMock.emit('update-downloaded', event)
|
||||
if (markInstallerReady) {
|
||||
markMacInstallerReady()
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
}
|
||||
|
||||
it.each(['deb', 'rpm'] as const)(
|
||||
'hands off %s installs without invoking the native updater',
|
||||
async (packageType) => {
|
||||
const openWindow = { removeAllListeners: vi.fn() }
|
||||
browserWindowMock.getAllWindows.mockReturnValue([openWindow] as never)
|
||||
const { send, updater } = await startUpdater(packageType)
|
||||
|
||||
await reachDownloaded(updater, downloadedEvent(packageType))
|
||||
|
||||
expect(lastStatus(send)).toEqual({
|
||||
state: 'error',
|
||||
message: 'Quit Orca before running the system package install command.',
|
||||
messageCode: 'linuxPackageManualInstall',
|
||||
recovery: {
|
||||
kind: 'linux-package-install',
|
||||
packageType,
|
||||
reason: 'manual-install-required',
|
||||
version: '1.0.61'
|
||||
}
|
||||
})
|
||||
|
||||
updater.quitAndInstall()
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
|
||||
expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled()
|
||||
expect(killAllPtyMock).not.toHaveBeenCalled()
|
||||
expect(openWindow.removeAllListeners).not.toHaveBeenCalled()
|
||||
expect(updater.isQuittingForUpdate()).toBe(false)
|
||||
expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted')
|
||||
expect(recordUpdaterLifecycleMock).toHaveBeenCalledWith(
|
||||
'linux_package_manual_install_required',
|
||||
{ packageType, version: '1.0.61' }
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
it('guards the native boundary even when no package artifact was retained', async () => {
|
||||
const { send, updater } = await startUpdater('deb')
|
||||
|
||||
updater.quitAndInstall()
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
|
||||
expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled()
|
||||
expect(killAllPtyMock).not.toHaveBeenCalled()
|
||||
expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted')
|
||||
})
|
||||
|
||||
it('preserves the normal AppImage install path when no root-package marker is present', async () => {
|
||||
const { send, updater } = await startUpdater(null)
|
||||
await reachDownloaded(
|
||||
updater,
|
||||
{
|
||||
version: '1.0.61',
|
||||
downloadedFile: join(tmpdir(), 'Orca-1.0.61.AppImage'),
|
||||
files: []
|
||||
},
|
||||
true
|
||||
)
|
||||
|
||||
updater.quitAndInstall()
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
|
||||
expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1)
|
||||
expect(killAllPtyMock).toHaveBeenCalledTimes(1)
|
||||
expect(send).not.toHaveBeenCalledWith('updater:quitAndInstallAborted')
|
||||
expect(
|
||||
send.mock.calls.some(
|
||||
([channel, status]) =>
|
||||
channel === 'updater:status' &&
|
||||
(status as UpdateStatus).state === 'error' &&
|
||||
(status as Extract<UpdateStatus, { state: 'error' }>).recovery?.kind ===
|
||||
'linux-package-install'
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['deb', 'rpm'] as const)(
|
||||
'disables install-on-quit and remote automatic control for %s builds',
|
||||
async (packageType) => {
|
||||
autoUpdaterMock.autoInstallOnAppQuit = true
|
||||
const { updater } = await startUpdater(packageType)
|
||||
|
||||
expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false)
|
||||
expect(updater.getRemoteServerUpdateSupport()).toEqual({
|
||||
installMode: 'interactive',
|
||||
automatic: false,
|
||||
reason: 'manual-service-update-required'
|
||||
})
|
||||
expect(() => updater.checkForRemoteServerUpdate('runtime-1')).toThrow(
|
||||
'remote_update_manual_required'
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps interactive install-on-quit and remote control for non-root packages', async () => {
|
||||
autoUpdaterMock.autoInstallOnAppQuit = false
|
||||
const { updater } = await startUpdater(null)
|
||||
|
||||
expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(true)
|
||||
expect(updater.getRemoteServerUpdateSupport()).toEqual({
|
||||
installMode: 'interactive',
|
||||
automatic: true,
|
||||
reason: 'available'
|
||||
})
|
||||
})
|
||||
|
||||
it('fails closed for an unusable packaged marker', async () => {
|
||||
getLinuxPackageTypeMock.mockReturnValue('unusable')
|
||||
getLinuxRootPackageTypeMock.mockReturnValue(null)
|
||||
autoUpdaterMock.autoInstallOnAppQuit = true
|
||||
const { send, updater } = await startUpdater(null)
|
||||
|
||||
expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false)
|
||||
expect(updater.getRemoteServerUpdateSupport()).toEqual({
|
||||
installMode: 'interactive',
|
||||
automatic: false,
|
||||
reason: 'manual-service-update-required'
|
||||
})
|
||||
|
||||
await reachDownloaded(updater, {
|
||||
version: '1.0.61',
|
||||
downloadedFile: join(tmpdir(), 'orca-updater', 'pending', 'orca-ide_1.0.61_amd64.deb'),
|
||||
files: [{ url: 'orca-ide_1.0.61_amd64.deb', sha512: packageSha512 }]
|
||||
})
|
||||
expect(lastStatus(send)).toEqual({
|
||||
state: 'error',
|
||||
message:
|
||||
'Orca could not verify the installed Linux package format, so it will not install this update automatically. Download the update from the official release page and install it manually.',
|
||||
messageCode: 'linuxPackageMarkerUnusable',
|
||||
version: '1.0.61',
|
||||
retryable: false
|
||||
})
|
||||
|
||||
updater.quitAndInstall()
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled()
|
||||
expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted')
|
||||
})
|
||||
|
||||
it('leaves headless serve installs supervisor-controlled', async () => {
|
||||
for (const installMode of [
|
||||
'supervised-headless-serve',
|
||||
'unsupported-headless-serve'
|
||||
] as const) {
|
||||
resetUpdaterMocks()
|
||||
autoUpdaterMock.autoInstallOnAppQuit = true
|
||||
await startUpdater(null, installMode)
|
||||
expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -3,10 +3,7 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
MIN_RESUMABLE_PREFIX_BYTES,
|
||||
jsonlPhysicalFileId,
|
||||
openJsonlFileReader,
|
||||
resolveJsonlFileCheckpoint,
|
||||
validateJsonlFileReader,
|
||||
type JsonlFileReader
|
||||
} from './jsonl-file-checkpoint'
|
||||
@@ -55,76 +52,6 @@ function positionalReadArgs(args: readonly unknown[]): [Buffer, number, number,
|
||||
}
|
||||
|
||||
describe('pinned small JSONL reader', () => {
|
||||
it('encodes large physical identifiers exactly and preserves numeric caller compatibility', () => {
|
||||
expect(jsonlPhysicalFileId({ dev: 1n, ino: 9_007_199_254_740_992n })).toBe('1:9007199254740992')
|
||||
expect(jsonlPhysicalFileId({ dev: 1n, ino: 9_007_199_254_740_993n })).toBe('1:9007199254740993')
|
||||
expect(jsonlPhysicalFileId({ dev: 3, ino: 4 })).toBe('3:4')
|
||||
expect(jsonlPhysicalFileId({ dev: 3, ino: 0 })).toBeNull()
|
||||
expect(jsonlPhysicalFileId({ dev: 3n, ino: 0n })).toBeNull()
|
||||
})
|
||||
|
||||
it.each([Number.NaN, Infinity, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])(
|
||||
'rejects an invalid persisted offset %s before attempting a range read',
|
||||
async (parsedBytes) => {
|
||||
await expect(
|
||||
resolveJsonlFileCheckpoint(filePath, {
|
||||
parsedBytes,
|
||||
headDigest: '4096:invalid',
|
||||
boundaryDigest: '4096:invalid',
|
||||
physicalFileId: null
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
}
|
||||
)
|
||||
|
||||
it('verifies an empty snapshot without creating a stream or issuing a read', async () => {
|
||||
const active = await openFixture('')
|
||||
const read = vi.spyOn(active.handle, 'read')
|
||||
const stream = vi.spyOn(active.handle, 'createReadStream')
|
||||
|
||||
expect(await collect(active)).toEqual([])
|
||||
expect(await validateJsonlFileReader(active)).toBe(true)
|
||||
expect(stream).not.toHaveBeenCalled()
|
||||
expect(read).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads and verifies all bytes twice without creating a stream', async () => {
|
||||
const contents = '会🙂\r\n\r\nnext\n尾🙂'
|
||||
const active = await openFixture(contents)
|
||||
const read = vi.spyOn(active.handle, 'read')
|
||||
const stream = vi.spyOn(active.handle, 'createReadStream')
|
||||
|
||||
expect(await collect(active)).toEqual([
|
||||
{ line: '会🙂', endOffset: Buffer.byteLength('会🙂\r\n'), terminated: true },
|
||||
{ line: '', endOffset: Buffer.byteLength('会🙂\r\n\r\n'), terminated: true },
|
||||
{ line: 'next', endOffset: Buffer.byteLength('会🙂\r\n\r\nnext\n'), terminated: true },
|
||||
{ line: '尾🙂', endOffset: Buffer.byteLength(contents), terminated: false }
|
||||
])
|
||||
expect(await validateJsonlFileReader(active)).toBe(true)
|
||||
expect(stream).not.toHaveBeenCalled()
|
||||
expect(read).toHaveBeenCalledTimes(2)
|
||||
expect(
|
||||
(await Promise.all(read.mock.results.map((result) => result.value))).map(
|
||||
(result) => result.bytesRead
|
||||
)
|
||||
).toEqual([Buffer.byteLength(contents), Buffer.byteLength(contents)])
|
||||
})
|
||||
|
||||
it('accounts for a skipped legacy prefix in the full snapshot proof', async () => {
|
||||
const contents = 'legacy会\r\nnew🙂\r\n'
|
||||
const active = await openFixture(contents)
|
||||
const offset = Buffer.byteLength('legacy会\r\n')
|
||||
const read = vi.spyOn(active.handle, 'read')
|
||||
|
||||
expect(await collect(active, offset)).toEqual([
|
||||
{ line: 'new🙂', endOffset: Buffer.byteLength(contents), terminated: true }
|
||||
])
|
||||
expect(await validateJsonlFileReader(active)).toBe(true)
|
||||
expect(active.streamBytes).toBe(Buffer.byteLength(contents) - offset)
|
||||
expect(active.snapshotBytes).toBe(Buffer.byteLength(contents))
|
||||
expect(read).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('accumulates short positional reads without exposing gaps or duplicate bytes', async () => {
|
||||
const contents = '会🙂\r\nnext\n終🙂'
|
||||
const active = await openFixture(contents)
|
||||
@@ -142,19 +69,6 @@ describe('pinned small JSONL reader', () => {
|
||||
expect(await validateJsonlFileReader(active)).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a stable premature EOF instead of publishing partial history', async () => {
|
||||
const active = await openFixture('one\ntwo\n')
|
||||
const read = active.handle.read.bind(active.handle)
|
||||
vi.spyOn(active.handle, 'read').mockImplementationOnce(async (...args) => {
|
||||
const result = await read(...args)
|
||||
return { ...result, bytesRead: 0 }
|
||||
})
|
||||
|
||||
await expect(collect(active)).rejects.toThrow(/snapshot read.*unchanged file boundary/)
|
||||
expect(active.streamBytes).toBe(0)
|
||||
expect(active.snapshotBytes).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects an unchanged EOF after a positive short read without yielding a partial line', async () => {
|
||||
const active = await openFixture('one\ntwo\n')
|
||||
const read = active.handle.read.bind(active.handle)
|
||||
@@ -235,19 +149,4 @@ describe('pinned small JSONL reader', () => {
|
||||
expect(await collect(active)).toEqual([])
|
||||
expect(await validateJsonlFileReader(active)).toBe(false)
|
||||
})
|
||||
|
||||
it('uses the bounded buffer at the crossover and streams larger snapshots', async () => {
|
||||
const active = await openFixture(`${'x'.repeat(MIN_RESUMABLE_PREFIX_BYTES - 1)}\n`)
|
||||
const stream = vi.spyOn(active.handle, 'createReadStream')
|
||||
await collect(active)
|
||||
expect(await validateJsonlFileReader(active)).toBe(true)
|
||||
expect(stream).not.toHaveBeenCalled()
|
||||
await active.handle.close()
|
||||
reader = undefined
|
||||
const large = await openFixture(`${'x'.repeat(MIN_RESUMABLE_PREFIX_BYTES)}\n`)
|
||||
const largeStream = vi.spyOn(large.handle, 'createReadStream')
|
||||
await collect(large)
|
||||
expect(await validateJsonlFileReader(large)).toBe(true)
|
||||
expect(largeStream).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
CLIPBOARD_IMAGE_MAX_PIXELS,
|
||||
CLIPBOARD_IMAGE_MAX_SOURCE_BYTES
|
||||
} from '../../shared/clipboard-image'
|
||||
import { CLIPBOARD_IMAGE_MAX_PIXELS } from '../../shared/clipboard-image'
|
||||
import { readWindowsClipboardImageFileAsPng } from './clipboard-windows-image-file'
|
||||
|
||||
function fileNameW(filePath: string): Buffer {
|
||||
@@ -25,36 +22,6 @@ function pngHeader(width = 10, height = 10): Buffer {
|
||||
return source
|
||||
}
|
||||
|
||||
function jpegHeader(width = 10, height = 10): Buffer {
|
||||
return Buffer.from([
|
||||
0xff,
|
||||
0xd8,
|
||||
0xff,
|
||||
0xe0,
|
||||
0x00,
|
||||
0x02,
|
||||
0xff,
|
||||
0xc2,
|
||||
0x00,
|
||||
0x07,
|
||||
0x08,
|
||||
height >> 8,
|
||||
height & 0xff,
|
||||
width >> 8,
|
||||
width & 0xff
|
||||
])
|
||||
}
|
||||
|
||||
function image(png = Buffer.from([4, 3, 2, 1])) {
|
||||
const decoded = {
|
||||
getSize: () => ({ height: 10, width: 10 }),
|
||||
isEmpty: () => false,
|
||||
resize: () => decoded,
|
||||
toPNG: () => png
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
function fileHandle(
|
||||
source: Buffer,
|
||||
options: { chunkSize?: number; isFile?: boolean; size?: number } = {}
|
||||
@@ -80,31 +47,6 @@ function fileHandle(
|
||||
}
|
||||
|
||||
describe('readWindowsClipboardImageFileAsPng', () => {
|
||||
it.each([
|
||||
'C:\\Users\\alice\\图片\\shot.PNG',
|
||||
'\\\\server\\share\\shot.jpeg',
|
||||
'\\\\?\\C:\\Users\\alice\\shot.jpg',
|
||||
'\\\\?\\UNC\\server\\share\\shot.png'
|
||||
])('decodes and converts a bounded FileNameW path: %s', async (filePath) => {
|
||||
const source = filePath.toLowerCase().endsWith('.png') ? pngHeader() : jpegHeader()
|
||||
const png = Buffer.from([9, 8, 7])
|
||||
const handle = fileHandle(source, { chunkSize: 3 })
|
||||
const openFile = vi.fn().mockResolvedValue(handle)
|
||||
const createImageFromBuffer = vi.fn(() => image(png) as never)
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats(filePath), {
|
||||
createImageFromBuffer,
|
||||
openFile
|
||||
})
|
||||
).resolves.toEqual(png)
|
||||
|
||||
expect(openFile).toHaveBeenCalledWith(filePath)
|
||||
expect(handle.read.mock.calls.length).toBeGreaterThan(1)
|
||||
expect(handle.close).toHaveBeenCalledOnce()
|
||||
expect(createImageFromBuffer).toHaveBeenCalledWith(source)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['empty', Buffer.alloc(0)],
|
||||
['odd byte count', Buffer.from([65, 0, 0])],
|
||||
@@ -133,95 +75,6 @@ describe('readWindowsClipboardImageFileAsPng', () => {
|
||||
expect(createImageFromBuffer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an Explorer multi-selection when FileNameW exposes only its first path', async () => {
|
||||
const openFile = vi.fn()
|
||||
const createImageFromBuffer = vi.fn()
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\one.png', 2), {
|
||||
createImageFromBuffer,
|
||||
openFile
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
|
||||
expect(openFile).not.toHaveBeenCalled()
|
||||
expect(createImageFromBuffer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores missing, inaccessible, and looping paths', async () => {
|
||||
for (const code of ['ENOENT', 'EACCES', 'ELOOP']) {
|
||||
const error = Object.assign(new Error(code), { code })
|
||||
const openFile = vi.fn().mockRejectedValue(error)
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\shot.png'), {
|
||||
createImageFromBuffer: vi.fn(),
|
||||
openFile
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('ignores directories and closes their handles', async () => {
|
||||
const handle = fileHandle(Buffer.alloc(0), { isFile: false })
|
||||
const createImageFromBuffer = vi.fn()
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\images.png'), {
|
||||
createImageFromBuffer,
|
||||
openFile: vi.fn().mockResolvedValue(handle)
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
|
||||
expect(handle.read).not.toHaveBeenCalled()
|
||||
expect(handle.close).toHaveBeenCalledOnce()
|
||||
expect(createImageFromBuffer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects oversized sources before reading or decoding', async () => {
|
||||
const handle = fileHandle(Buffer.alloc(0), {
|
||||
size: CLIPBOARD_IMAGE_MAX_SOURCE_BYTES + 1
|
||||
})
|
||||
const createImageFromBuffer = vi.fn()
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\huge.png'), {
|
||||
createImageFromBuffer,
|
||||
openFile: vi.fn().mockResolvedValue(handle)
|
||||
})
|
||||
).rejects.toThrow('Clipboard image is too large')
|
||||
|
||||
expect(handle.read).not.toHaveBeenCalled()
|
||||
expect(handle.close).toHaveBeenCalledOnce()
|
||||
expect(createImageFromBuffer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores a source that changes size after handle validation', async () => {
|
||||
const handle = fileHandle(Buffer.from('grew'), { size: 3 })
|
||||
const createImageFromBuffer = vi.fn()
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\changed.png'), {
|
||||
createImageFromBuffer,
|
||||
openFile: vi.fn().mockResolvedValue(handle)
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
|
||||
expect(handle.close).toHaveBeenCalledOnce()
|
||||
expect(createImageFromBuffer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores image bytes the native decoder cannot decode', async () => {
|
||||
const handle = fileHandle(Buffer.from('not-an-image'))
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\invalid.png'), {
|
||||
createImageFromBuffer: vi.fn(() => ({ isEmpty: () => true }) as never),
|
||||
openFile: vi.fn().mockResolvedValue(handle)
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('rejects oversized encoded dimensions before native decoding', async () => {
|
||||
const handle = fileHandle(pngHeader(CLIPBOARD_IMAGE_MAX_PIXELS + 1, 1))
|
||||
const createImageFromBuffer = vi.fn()
|
||||
@@ -236,49 +89,4 @@ describe('readWindowsClipboardImageFileAsPng', () => {
|
||||
expect(createImageFromBuffer).not.toHaveBeenCalled()
|
||||
expect(handle.close).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('bounds malformed JPEG marker scanning before native decoding', async () => {
|
||||
const source = Buffer.alloc(2 + 2 * 4097)
|
||||
source.set([0xff, 0xd8])
|
||||
for (let offset = 2; offset < source.byteLength; offset += 2) {
|
||||
source.set([0xff, 0x01], offset)
|
||||
}
|
||||
const createImageFromBuffer = vi.fn()
|
||||
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\marker-flood.jpg'), {
|
||||
createImageFromBuffer,
|
||||
openFile: vi.fn().mockResolvedValue(fileHandle(source))
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
|
||||
expect(createImageFromBuffer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('bounds decoded dimensions and converted PNG bytes', async () => {
|
||||
const oversizedDimensions = fileHandle(pngHeader())
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\wide.png'), {
|
||||
createImageFromBuffer: vi.fn(
|
||||
() =>
|
||||
({
|
||||
getSize: () => ({ height: 1, width: CLIPBOARD_IMAGE_MAX_PIXELS + 1 }),
|
||||
isEmpty: () => false,
|
||||
toPNG: vi.fn()
|
||||
}) as never
|
||||
),
|
||||
openFile: vi.fn().mockResolvedValue(oversizedDimensions)
|
||||
})
|
||||
).rejects.toThrow('Clipboard image is too large')
|
||||
|
||||
const oversizedPng = fileHandle(pngHeader())
|
||||
await expect(
|
||||
readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\expanded.png'), {
|
||||
createImageFromBuffer: vi.fn(
|
||||
() => image(Buffer.alloc(CLIPBOARD_IMAGE_MAX_SOURCE_BYTES + 1)) as never
|
||||
),
|
||||
openFile: vi.fn().mockResolvedValue(oversizedPng)
|
||||
})
|
||||
).rejects.toThrow('Clipboard image is too large')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('electron', async () =>
|
||||
(await import('./createMainWindow-test-harness')).electronModuleMock()
|
||||
)
|
||||
vi.mock('./macos-tahoe-release', async () =>
|
||||
(await import('./createMainWindow-test-harness')).macosTahoeReleaseMock()
|
||||
)
|
||||
vi.mock('./desktop-integration/app-icon', async () =>
|
||||
(await import('./createMainWindow-test-harness')).appIconMock()
|
||||
)
|
||||
vi.mock('../browser/browser-manager', async () =>
|
||||
(await import('./createMainWindow-test-harness')).browserManagerMock()
|
||||
)
|
||||
vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => {
|
||||
const harness = await import('./createMainWindow-test-harness')
|
||||
return {
|
||||
attachBrowserClientPageRenderer: harness.attachClientPageRendererMock,
|
||||
retireBrowserClientPageRenderer: harness.retireClientPageRendererMock
|
||||
}
|
||||
})
|
||||
|
||||
import { createMainWindow } from './createMainWindow'
|
||||
import type { CreateMainWindowOptions } from './main-window-contracts'
|
||||
import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-gone-classification'
|
||||
import {
|
||||
browserWindowMock,
|
||||
resetMainWindowMocks,
|
||||
withPlatform
|
||||
} from './createMainWindow-test-harness'
|
||||
import { RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS } from './renderer-launch-failure-backoff'
|
||||
|
||||
// macOS LAUNCH_RESULT_FAILURE: posix_spawn of the Renderer helper failed (field: EAGAIN, per-user process limit).
|
||||
const LAUNCH_FAILED: Electron.RenderProcessGoneDetails = { reason: 'launch-failed', exitCode: 1003 }
|
||||
const CRASHED: Electron.RenderProcessGoneDetails = { reason: 'crashed', exitCode: 5 }
|
||||
|
||||
/** Reproduce spawn refusal: launch-failed then ERR_FAILED before a document; the same WebContents loads once process headroom returns. */
|
||||
function createSpawnRefusingWindow(
|
||||
platform: NodeJS.Platform = 'darwin',
|
||||
failure: Electron.RenderProcessGoneDetails = LAUNCH_FAILED
|
||||
) {
|
||||
const handlers: Record<string, (...args: any[]) => void> = {}
|
||||
const spawn = { refused: true }
|
||||
const webContents = {
|
||||
id: 143,
|
||||
getURL: vi.fn(() => 'file:///opt/orca/renderer/index.html'),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
on: vi.fn((event: string, handler: (...args: any[]) => void) => {
|
||||
handlers[event] = handler
|
||||
}),
|
||||
setZoomLevel: vi.fn(),
|
||||
setBackgroundThrottling: vi.fn(),
|
||||
setWebRTCIPHandlingPolicy: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
send: vi.fn()
|
||||
}
|
||||
const load = vi.fn((): Promise<void> => {
|
||||
if (!spawn.refused) {
|
||||
queueMicrotask(() => handlers['did-finish-load']?.())
|
||||
return Promise.resolve()
|
||||
}
|
||||
queueMicrotask(() =>
|
||||
withPlatform(platform, () => handlers['render-process-gone']?.({}, failure))
|
||||
)
|
||||
return Promise.reject(
|
||||
new Error("ERR_FAILED (-2) loading 'file:///opt/orca/renderer/index.html'")
|
||||
)
|
||||
})
|
||||
browserWindowMock.mockImplementation(function () {
|
||||
return {
|
||||
webContents,
|
||||
on: vi.fn((event: string, handler: (...args: any[]) => void) => {
|
||||
handlers[event] = handler
|
||||
}),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMaximized: vi.fn(() => true),
|
||||
isFullScreen: vi.fn(() => false),
|
||||
getSize: vi.fn(() => [1200, 800]),
|
||||
setSize: vi.fn(),
|
||||
maximize: vi.fn(),
|
||||
show: vi.fn(),
|
||||
loadFile: load,
|
||||
loadURL: load
|
||||
}
|
||||
})
|
||||
return { handlers, load, spawn }
|
||||
}
|
||||
|
||||
function open(overrides: CreateMainWindowOptions = {}) {
|
||||
const onRendererRecoveryExhausted = vi.fn()
|
||||
const onRecoveryReloadOutcome = vi.fn()
|
||||
createMainWindow(null, {
|
||||
onRendererRecoveryExhausted,
|
||||
onRecoveryReloadOutcome,
|
||||
shouldRecoverRenderer: (details) =>
|
||||
shouldRecoverRendererAfterProcessGone({ reason: details.reason, expectedTeardown: 'none' }),
|
||||
...overrides
|
||||
})
|
||||
return { onRendererRecoveryExhausted, onRecoveryReloadOutcome }
|
||||
}
|
||||
|
||||
const BACKOFF_TOTAL_MS = RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.reduce((sum, ms) => sum + ms, 0)
|
||||
|
||||
describe('renderer launch-failed recovery', () => {
|
||||
beforeEach(() => {
|
||||
resetMainWindowMocks()
|
||||
vi.useFakeTimers()
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('recovers in place once spawn headroom returns, without any prompt', async () => {
|
||||
const { handlers, load, spawn } = createSpawnRefusingWindow()
|
||||
const { onRendererRecoveryExhausted, onRecoveryReloadOutcome } = open()
|
||||
// Reproduce process-table exhaustion lasting minutes.
|
||||
await vi.advanceTimersByTimeAsync(250 + 1_000 + 2_000 + 4_000 + 8_000 + 15_000)
|
||||
expect(load).toHaveBeenCalledTimes(7)
|
||||
spawn.refused = false
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000)
|
||||
expect(load).toHaveBeenCalledTimes(8)
|
||||
expect(onRecoveryReloadOutcome).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ status: 'loaded' })
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(5 * 60_000)
|
||||
expect(load).toHaveBeenCalledTimes(8)
|
||||
expect(onRendererRecoveryExhausted).not.toHaveBeenCalled()
|
||||
|
||||
// A loaded document resets the launch-failure backoff.
|
||||
spawn.refused = true
|
||||
handlers['render-process-gone']?.({}, LAUNCH_FAILED)
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
expect(load).toHaveBeenCalledTimes(9)
|
||||
})
|
||||
|
||||
it('prompts only after the ~2 minute schedule is spent, then a failed manual retry re-prompts', async () => {
|
||||
const { load } = createSpawnRefusingWindow()
|
||||
const { onRendererRecoveryExhausted } = open()
|
||||
await vi.advanceTimersByTimeAsync(BACKOFF_TOTAL_MS - 1)
|
||||
expect(onRendererRecoveryExhausted).not.toHaveBeenCalled()
|
||||
|
||||
// Prompt on the next recovery tick after the final retry fails.
|
||||
await vi.advanceTimersByTimeAsync(251)
|
||||
expect(BACKOFF_TOTAL_MS).toBeLessThanOrEqual(125_000)
|
||||
expect(load).toHaveBeenCalledTimes(1 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length)
|
||||
expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce()
|
||||
expect(onRendererRecoveryExhausted).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
details: LAUNCH_FAILED,
|
||||
cause: 'launch-failed',
|
||||
recentRecoveryCount: RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length
|
||||
})
|
||||
)
|
||||
|
||||
onRendererRecoveryExhausted.mock.calls[0]?.[0].retry()
|
||||
expect(load).toHaveBeenCalledTimes(2 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length)
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
expect(onRendererRecoveryExhausted).toHaveBeenCalledTimes(2)
|
||||
await vi.advanceTimersByTimeAsync(5 * 60_000)
|
||||
expect(load).toHaveBeenCalledTimes(2 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length)
|
||||
})
|
||||
|
||||
it('stops recovery when quitting during the long backoff', async () => {
|
||||
const { load } = createSpawnRefusingWindow()
|
||||
let quitting = false
|
||||
const { onRendererRecoveryExhausted } = open({ getIsQuitting: () => quitting })
|
||||
await vi.advanceTimersByTimeAsync(250 + 1_000 + 2_000 + 4_000)
|
||||
const loadsBeforeQuit = load.mock.calls.length
|
||||
quitting = true
|
||||
await vi.advanceTimersByTimeAsync(BACKOFF_TOTAL_MS * 2)
|
||||
expect(load).toHaveBeenCalledTimes(loadsBeforeQuit)
|
||||
expect(onRendererRecoveryExhausted).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not spend retry attempts on duplicate failure events', async () => {
|
||||
const { handlers, load } = createSpawnRefusingWindow()
|
||||
const { onRendererRecoveryExhausted } = open()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
handlers['render-process-gone']?.({}, LAUNCH_FAILED)
|
||||
handlers['render-process-gone']?.({}, LAUNCH_FAILED)
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
expect(load).toHaveBeenCalledTimes(2)
|
||||
await vi.advanceTimersByTimeAsync(999)
|
||||
expect(load).toHaveBeenCalledTimes(2)
|
||||
expect(onRendererRecoveryExhausted).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rides out a Windows sandbox CreateProcess refusal in place instead of prompting', async () => {
|
||||
// Windows SBOX_ERROR_CREATE_PROCESS; awin repro (job capped at 1 process for 5s) prompted after ~1s on the 750ms breaker.
|
||||
const { spawn } = createSpawnRefusingWindow('win32', {
|
||||
reason: 'launch-failed',
|
||||
exitCode: 18
|
||||
})
|
||||
const { onRendererRecoveryExhausted, onRecoveryReloadOutcome } = open()
|
||||
await vi.advanceTimersByTimeAsync(5_000)
|
||||
expect(onRendererRecoveryExhausted).not.toHaveBeenCalled()
|
||||
spawn.refused = false
|
||||
|
||||
await vi.advanceTimersByTimeAsync(4_000)
|
||||
expect(onRecoveryReloadOutcome).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ status: 'loaded' })
|
||||
)
|
||||
expect(onRendererRecoveryExhausted).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still prompts on Windows once a persistent CreateProcess refusal spends the schedule', async () => {
|
||||
const SANDBOX_REFUSED = { reason: 'launch-failed', exitCode: 18 } as const
|
||||
const { load } = createSpawnRefusingWindow('win32', SANDBOX_REFUSED)
|
||||
const { onRendererRecoveryExhausted } = open()
|
||||
await vi.advanceTimersByTimeAsync(BACKOFF_TOTAL_MS - 1)
|
||||
expect(onRendererRecoveryExhausted).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(251)
|
||||
expect(load).toHaveBeenCalledTimes(1 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length)
|
||||
expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce()
|
||||
expect(onRendererRecoveryExhausted).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
details: SANDBOX_REFUSED,
|
||||
cause: 'launch-failed',
|
||||
recentRecoveryCount: RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the crash-loop breaker for renderers that actually crash', async () => {
|
||||
const { handlers, load, spawn } = createSpawnRefusingWindow()
|
||||
spawn.refused = false
|
||||
const { onRendererRecoveryExhausted } = open()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
handlers['render-process-gone']?.({}, CRASHED)
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
}
|
||||
expect(load).toHaveBeenCalledTimes(4)
|
||||
expect(onRendererRecoveryExhausted).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ details: CRASHED, cause: 'crash-loop', recentRecoveryCount: 3 })
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -7,7 +7,7 @@ import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/
|
||||
import type { Store } from '../persistence/loading-store/store'
|
||||
import { resolveLocalFileRequestPath } from '../ipc/filesystem/access/local-file-access-resolution'
|
||||
import { readLocalFileContent } from '../ipc/filesystem/filesystem-file-content-inspection'
|
||||
import { isInsideNativeChatPasteFolder, restoreNativeChatPastes } from './native-chat-paste-files'
|
||||
import { restoreNativeChatPastes } from './native-chat-paste-files'
|
||||
|
||||
// A store with no projects: nothing but an access kind decides what a read may reach.
|
||||
const NO_PROJECTS: Store = Object.assign(Object.create(null), {
|
||||
@@ -30,46 +30,6 @@ async function chatImageReadable(target: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
describe('isInsideNativeChatPasteFolder', () => {
|
||||
const posixFolder = '/data/native-chat-pastes'
|
||||
const winFolder = 'C:\\Users\\Me\\AppData\\Roaming\\Orca\\native-chat-pastes'
|
||||
|
||||
it.each([
|
||||
['a file inside', `${posixFolder}/orca-paste-1.png`, true],
|
||||
['a name that only starts with dots', `${posixFolder}/..orca-paste-1.png`, true],
|
||||
['the folder itself', posixFolder, false],
|
||||
['the parent', '/data', false],
|
||||
['a sibling reached through ..', `${posixFolder}/../secret.png`, false],
|
||||
['a sibling folder sharing the prefix', '/data/native-chat-pastes-evil/x.png', false],
|
||||
['an unrelated absolute path', '/etc/passwd', false]
|
||||
])('posix: %s', (_label, target, inside) => {
|
||||
expect(isInsideNativeChatPasteFolder(posixFolder, target, path.posix, 'darwin')).toBe(inside)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a file inside', `${winFolder}\\orca-paste-1.png`, true],
|
||||
['a file inside in other letter case', `${winFolder.toLowerCase()}\\ORCA-PASTE-1.PNG`, true],
|
||||
['a \\\\?\\ prefixed file inside', `\\\\?\\${winFolder}\\orca-paste-1.png`, true],
|
||||
['another drive', 'D:\\native-chat-pastes\\orca-paste-1.png', false],
|
||||
['a \\\\?\\UNC share', '\\\\?\\UNC\\server\\share\\orca-paste-1.png', false],
|
||||
['a sibling reached through ..', `${winFolder}\\..\\secret.png`, false],
|
||||
['the folder itself', winFolder, false]
|
||||
])('win32: %s', (_label, target, inside) => {
|
||||
expect(isInsideNativeChatPasteFolder(winFolder, target, path.win32, 'win32')).toBe(inside)
|
||||
})
|
||||
|
||||
it('compares a \\\\?\\ prefixed folder like its plain form', () => {
|
||||
expect(
|
||||
isInsideNativeChatPasteFolder(
|
||||
`\\\\?\\${winFolder}`,
|
||||
`${winFolder}\\orca-paste-1.png`,
|
||||
path.win32,
|
||||
'win32'
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('native-chat paste folder on disk', () => {
|
||||
let root: string
|
||||
let folder: string
|
||||
@@ -117,16 +77,6 @@ describe('native-chat paste folder on disk', () => {
|
||||
await expect(restoreNativeChatPastes('not a list')).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('leaves a kept paste readable by the composer preview, with no grant', async () => {
|
||||
const kept = path.join(folder, 'orca-paste-1.png')
|
||||
writeFileSync(kept, 'png')
|
||||
await expect(restoreNativeChatPastes([kept])).resolves.toEqual([
|
||||
{ path: kept, kept: true, exists: true }
|
||||
])
|
||||
const readable = await resolveLocalFileRequestPath(kept, { kind: 'chat-image' }, NO_PROJECTS)
|
||||
await expect(readLocalFileContent(readable)).resolves.toMatchObject({ mimeType: 'image/png' })
|
||||
})
|
||||
|
||||
it('keeps a paste reached through a symlinked alias of the folder, as /var is of /private/var', async () => {
|
||||
const kept = path.join(folder, 'orca-paste-1.png')
|
||||
writeFileSync(kept, 'png')
|
||||
@@ -207,18 +157,4 @@ describe('native-chat paste folder on disk', () => {
|
||||
[{ path: path.join(folder, 'orca-paste-1.png'), kept: false, exists: false }]
|
||||
)
|
||||
})
|
||||
|
||||
it('reports nothing kept when the folder does not exist yet', async () => {
|
||||
rmSync(folder, { recursive: true })
|
||||
await expect(
|
||||
resolveLocalFileRequestPath(
|
||||
path.join(root, 'agent-session-attachments', 'upload', 'gone.png'),
|
||||
{ kind: 'chat-image' },
|
||||
NO_PROJECTS
|
||||
)
|
||||
).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
await expect(restoreNativeChatPastes([path.join(folder, 'orca-paste-1.png')])).resolves.toEqual(
|
||||
[{ path: path.join(folder, 'orca-paste-1.png'), kept: false, exists: false }]
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
import type { MessageBoxOptions, MessageBoxReturnValue } from 'electron'
|
||||
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mainI18n } from '../i18n/main-i18n'
|
||||
import type { InstallDirAclPoisonDiagnosis } from '../startup/windows-install-dir-acl-recovery'
|
||||
import {
|
||||
presentRendererRecoveryPrompt,
|
||||
type RendererRecoveryPromptDeps
|
||||
} from './renderer-recovery-prompt'
|
||||
|
||||
vi.mock('electron', () => ({ app: { getLocale: () => 'en-US' } }))
|
||||
|
||||
const POISON: InstallDirAclPoisonDiagnosis = {
|
||||
detail: "Windows permissions on Orca's install folder are blocking its own sandboxed processes.",
|
||||
commands: ['icacls "C:\\Orca" /grant "*S-1-15-2-2:(OI)(CI)(RX)"', 'icacls "C:\\Orca" /grant b']
|
||||
}
|
||||
|
||||
function harness(overrides: Partial<RendererRecoveryPromptDeps> & { responses?: number[] } = {}): {
|
||||
run: () => Promise<void>
|
||||
shown: MessageBoxOptions[]
|
||||
copied: string[]
|
||||
reload: ReturnType<typeof vi.fn>
|
||||
quit: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const { responses = [0], ...rest } = overrides
|
||||
const shown: MessageBoxOptions[] = []
|
||||
const copied: string[] = []
|
||||
const reload = vi.fn()
|
||||
const quit = vi.fn()
|
||||
const deps: RendererRecoveryPromptDeps = {
|
||||
recentRecoveryCount: 4,
|
||||
isQuitting: () => false,
|
||||
diagnose: () => null,
|
||||
showMessageBox: async (options: MessageBoxOptions): Promise<MessageBoxReturnValue> => {
|
||||
shown.push(options)
|
||||
return {
|
||||
response: responses[Math.min(shown.length - 1, responses.length - 1)],
|
||||
checkboxChecked: false
|
||||
}
|
||||
},
|
||||
copyToClipboard: (text) => copied.push(text),
|
||||
reload,
|
||||
quit,
|
||||
...rest
|
||||
}
|
||||
return { run: () => presentRendererRecoveryPrompt(deps), shown, copied, reload, quit }
|
||||
}
|
||||
|
||||
describe('presentRendererRecoveryPrompt', () => {
|
||||
beforeEach(async () => {
|
||||
await mainI18n.changeLanguage('en')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
mainI18n.removeResourceBundle('en', 'translation')
|
||||
})
|
||||
|
||||
it('interpolates the recovery count', async () => {
|
||||
const { run, shown } = harness({ recentRecoveryCount: 7 })
|
||||
await run()
|
||||
expect(shown[0].detail).toContain('Orca tried to recover 7 times in a row')
|
||||
expect(shown[0].detail).not.toContain('{{')
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ responses: [1, 0], reloads: 1, quits: 0 },
|
||||
{ responses: [1, 2], reloads: 0, quits: 1 }
|
||||
])(
|
||||
'dispatches translated buttons by response index: $responses',
|
||||
async ({ responses, reloads, quits }) => {
|
||||
mainI18n.addResourceBundle('en', 'translation', {
|
||||
rendererRecovery: { reload: 'Recharger', copyCommands: 'Copier', quit: 'Quitter' }
|
||||
})
|
||||
const { run, shown, copied, reload, quit } = harness({ diagnose: () => POISON, responses })
|
||||
await run()
|
||||
expect(shown[0].buttons).toEqual(['Recharger', 'Copier', 'Quitter'])
|
||||
expect(copied).toEqual([POISON.commands.join('\r\n')])
|
||||
expect(reload).toHaveBeenCalledTimes(reloads)
|
||||
expect(quit).toHaveBeenCalledTimes(quits)
|
||||
}
|
||||
)
|
||||
|
||||
it('offers reload and quit with the generic cause when nothing is diagnosed', async () => {
|
||||
const { run, shown, reload, quit } = harness({ responses: [0] })
|
||||
await run()
|
||||
expect(shown).toHaveLength(1)
|
||||
expect(shown[0].buttons).toEqual(['Reload', 'Quit'])
|
||||
// Escape retries; a window-modal recovery box must not quit the session.
|
||||
expect(shown[0].cancelId).toBe(0)
|
||||
expect(shown[0].detail).toContain('graphics-driver or installation problem')
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
expect(quit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('names the stalled reload instead of claiming a repeated crash', async () => {
|
||||
const { run, shown } = harness({ failure: 'reload-stalled', responses: [1] })
|
||||
await run()
|
||||
expect(shown[0].message).toContain('stopped responding while reloading')
|
||||
expect(shown[0].detail).toContain('never finished loading')
|
||||
expect(shown[0].detail).not.toContain('times in a row')
|
||||
})
|
||||
|
||||
it('says Windows is out of memory with the commit left, instead of blaming drivers', async () => {
|
||||
const { run, shown, reload } = harness({
|
||||
failure: 'low-commit',
|
||||
availableCommitMB: 60,
|
||||
responses: [0]
|
||||
})
|
||||
await run()
|
||||
expect(shown[0].message).toBe('Windows is out of memory.')
|
||||
expect(shown[0].detail).toContain('only 60 MB of memory left')
|
||||
expect(shown[0].detail).toContain('increase the Windows page file size')
|
||||
expect(shown[0].detail).not.toContain('graphics')
|
||||
expect(shown[0].buttons).toEqual(['Reload', 'Quit'])
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('omits Copy Commands on low commit, since its detail would not be shown', async () => {
|
||||
const { run, shown, quit, copied } = harness({
|
||||
failure: 'low-commit',
|
||||
availableCommitMB: 60,
|
||||
diagnose: () => POISON,
|
||||
responses: [1]
|
||||
})
|
||||
await run()
|
||||
expect(shown[0].buttons).toEqual(['Reload', 'Quit'])
|
||||
expect(copied).toEqual([])
|
||||
expect(quit).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('quits on the last button', async () => {
|
||||
const { run, reload, quit } = harness({ responses: [1] })
|
||||
await run()
|
||||
expect(quit).toHaveBeenCalledOnce()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('names the install-permission cause and keeps the driver hint', async () => {
|
||||
const { run, shown } = harness({ diagnose: () => POISON, responses: [0] })
|
||||
await run()
|
||||
expect(shown[0].buttons).toEqual(['Reload', 'Copy Commands', 'Quit'])
|
||||
expect(shown[0].cancelId).toBe(0)
|
||||
expect(shown[0].detail).toContain(POISON.detail)
|
||||
expect(shown[0].detail).toContain('graphics driver')
|
||||
})
|
||||
|
||||
// Copy must retain the dialog: blank windows have no other recovery surface.
|
||||
it('keeps the dialog up after copying the commands, then still reloads', async () => {
|
||||
const { run, shown, copied, reload, quit } = harness({
|
||||
diagnose: () => POISON,
|
||||
responses: [1, 1, 0]
|
||||
})
|
||||
await run()
|
||||
expect(copied).toEqual([POISON.commands.join('\r\n'), POISON.commands.join('\r\n')])
|
||||
expect(shown).toHaveLength(3)
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
expect(quit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('quits on the third button once the diagnosis adds one', async () => {
|
||||
const { run, quit, copied } = harness({ diagnose: () => POISON, responses: [2] })
|
||||
await run()
|
||||
expect(quit).toHaveBeenCalledOnce()
|
||||
expect(copied).toEqual([])
|
||||
})
|
||||
|
||||
it('shows nothing once the app is already quitting', async () => {
|
||||
const { run, shown } = harness({ isQuitting: () => true })
|
||||
await run()
|
||||
expect(shown).toEqual([])
|
||||
})
|
||||
|
||||
// Re-read asynchronous repair diagnosis each pass so settled repair replaces stale repairing copy.
|
||||
it('re-reads the diagnosis on every pass', async () => {
|
||||
const details = ['repairing now', 'repaired']
|
||||
let pass = 0
|
||||
const { run, shown } = harness({
|
||||
diagnose: () => ({ detail: details[Math.min(pass++, 1)], commands: POISON.commands }),
|
||||
responses: [1, 0]
|
||||
})
|
||||
await run()
|
||||
expect(shown[0].detail).toContain('repairing now')
|
||||
expect(shown[1].detail).toContain('repaired')
|
||||
})
|
||||
|
||||
describe('after a renderer launch failure', () => {
|
||||
it('names the process limit when the probe is refused with EAGAIN', async () => {
|
||||
const probeLaunchCapacity = vi.fn(async () => 'EAGAIN')
|
||||
const { run, shown, reload, quit } = harness({
|
||||
failure: 'launch-failed',
|
||||
recentRecoveryCount: 8,
|
||||
probeLaunchCapacity
|
||||
})
|
||||
await run()
|
||||
expect(probeLaunchCapacity).toHaveBeenCalledOnce()
|
||||
// No Restart: app.relaunch needs a free process slot too and silently fails without one.
|
||||
expect(shown[0].buttons).toEqual(['Try Again', 'Quit'])
|
||||
expect(shown[0].defaultId).toBe(0)
|
||||
expect(shown[0].cancelId).toBe(0)
|
||||
expect(shown[0].message).toContain("couldn't start the process")
|
||||
expect(shown[0].detail).toContain('retried 8 times')
|
||||
expect(shown[0].detail).toContain('process limit')
|
||||
expect(shown[0].detail).not.toMatch(/graphics|driver/i)
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
expect(quit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('drops the graphics-driver blame when the probe could spawn', async () => {
|
||||
const { run, shown, quit } = harness({
|
||||
failure: 'launch-failed',
|
||||
probeLaunchCapacity: async () => 'ok',
|
||||
responses: [1]
|
||||
})
|
||||
await run()
|
||||
expect(shown[0].detail).not.toContain('process limit')
|
||||
expect(shown[0].detail).not.toMatch(/graphics|driver/i)
|
||||
expect(shown[0].detail).toContain('Try Again')
|
||||
expect(quit).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('probes once even when Copy Commands re-shows the box', async () => {
|
||||
const probeLaunchCapacity = vi.fn(async () => 'ok')
|
||||
const { run, shown, reload } = harness({
|
||||
failure: 'launch-failed',
|
||||
diagnose: () => POISON,
|
||||
probeLaunchCapacity,
|
||||
responses: [1, 1, 0]
|
||||
})
|
||||
await run()
|
||||
expect(shown).toHaveLength(3)
|
||||
expect(probeLaunchCapacity).toHaveBeenCalledOnce()
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('shows nothing when the app starts quitting during the probe', async () => {
|
||||
let quitting = false
|
||||
const { run, shown, reload } = harness({
|
||||
failure: 'launch-failed',
|
||||
isQuitting: () => quitting,
|
||||
probeLaunchCapacity: async () => {
|
||||
quitting = true
|
||||
return 'EAGAIN'
|
||||
}
|
||||
})
|
||||
await run()
|
||||
expect(shown).toEqual([])
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not probe once the app is already quitting', async () => {
|
||||
const probeLaunchCapacity = vi.fn(async () => 'ok')
|
||||
const { run } = harness({
|
||||
failure: 'launch-failed',
|
||||
isQuitting: () => true,
|
||||
probeLaunchCapacity
|
||||
})
|
||||
await run()
|
||||
expect(probeLaunchCapacity).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the install-permission diagnosis and its copy button', async () => {
|
||||
const { run, shown } = harness({
|
||||
failure: 'launch-failed',
|
||||
diagnose: () => POISON,
|
||||
probeLaunchCapacity: async () => 'ok'
|
||||
})
|
||||
await run()
|
||||
expect(shown[0].buttons).toEqual(['Try Again', 'Copy Commands', 'Quit'])
|
||||
expect(shown[0].detail).toContain(POISON.detail)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,333 +0,0 @@
|
||||
import type * as WorktreeScanCacheModule from '../../git/worktrees/catalog/worktree-scan-cache'
|
||||
import type * as WorktreeListingModule from '../../git/worktrees/catalog/worktree-listing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { listWorktreeGraphMock, listWorktreesMock, listWorktreesStrictMock } = vi.hoisted(() => ({
|
||||
listWorktreeGraphMock: vi.fn(),
|
||||
listWorktreesMock: vi.fn(),
|
||||
listWorktreesStrictMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => {
|
||||
const facade = await getWorktreeOwnerMocks()
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeScanCacheModule>()),
|
||||
listWorktrees: facade.listWorktrees,
|
||||
listWorktreeGraph: facade.listWorktreeGraph,
|
||||
listWorktreesSharedStrictAllowingTrueEmpty: facade.listWorktreesSharedStrictAllowingTrueEmpty
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../git/worktrees/catalog/worktree-listing', async (importOriginal) => {
|
||||
const facade = await getWorktreeOwnerMocks()
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeListingModule>()),
|
||||
listWorktreesStrict: facade.listWorktreesStrict
|
||||
}
|
||||
})
|
||||
|
||||
const { getWorktreeOwnerMocks } = vi.hoisted(() => {
|
||||
function createWorktreeOwnerMocks() {
|
||||
return (() => ({
|
||||
listWorktreeGraph: listWorktreeGraphMock,
|
||||
listWorktrees: listWorktreesMock,
|
||||
listWorktreesStrict: listWorktreesStrictMock,
|
||||
listWorktreesSharedStrictAllowingTrueEmpty: listWorktreesStrictMock
|
||||
}))()
|
||||
}
|
||||
let fixture: ReturnType<typeof createWorktreeOwnerMocks> | undefined
|
||||
return { getWorktreeOwnerMocks: () => (fixture ??= createWorktreeOwnerMocks()) }
|
||||
})
|
||||
|
||||
import {
|
||||
createFolderWorktree,
|
||||
isRepoRoot,
|
||||
listLocalRepoWorktreesStrict,
|
||||
listRepoWorktreeGraph,
|
||||
listRepoWorktrees,
|
||||
listRepoWorktreesForDetectedScan
|
||||
} from './repo-worktrees'
|
||||
import { WorktreeCatalogUnavailableError } from '../../../shared/worktree/worktree-catalog-availability'
|
||||
|
||||
describe('repo-worktrees', () => {
|
||||
beforeEach(() => {
|
||||
listWorktreeGraphMock.mockReset()
|
||||
listWorktreesMock.mockReset()
|
||||
listWorktreesStrictMock.mockReset()
|
||||
})
|
||||
|
||||
it('creates a stable synthetic worktree for folder repos', () => {
|
||||
expect(
|
||||
createFolderWorktree({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/folder',
|
||||
displayName: 'folder',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'folder'
|
||||
})
|
||||
).toEqual({
|
||||
path: '/workspace/folder',
|
||||
head: '',
|
||||
branch: '',
|
||||
isBare: false,
|
||||
isMainWorktree: true
|
||||
})
|
||||
})
|
||||
|
||||
it('returns the synthetic folder worktree instead of shelling out to git', async () => {
|
||||
const result = await listRepoWorktrees({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/folder',
|
||||
displayName: 'folder',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'folder'
|
||||
})
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
path: '/workspace/folder',
|
||||
head: '',
|
||||
branch: '',
|
||||
isBare: false,
|
||||
isMainWorktree: true
|
||||
}
|
||||
])
|
||||
expect(listWorktreesMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns the synthetic folder worktree for strict local listing', async () => {
|
||||
const result = await listLocalRepoWorktreesStrict({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/folder',
|
||||
displayName: 'folder',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'folder'
|
||||
})
|
||||
|
||||
expect(result).toEqual([
|
||||
createFolderWorktree({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/folder',
|
||||
displayName: 'folder',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'folder'
|
||||
})
|
||||
])
|
||||
expect(listWorktreesStrictMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('delegates to git worktree listing for git repos', async () => {
|
||||
listWorktreesMock.mockResolvedValue([
|
||||
{ path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true }
|
||||
])
|
||||
const signal = new AbortController().signal
|
||||
|
||||
const result = await listRepoWorktrees(
|
||||
{
|
||||
id: 'repo-1',
|
||||
path: '/workspace/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'git'
|
||||
},
|
||||
{ signal }
|
||||
)
|
||||
|
||||
expect(listWorktreesMock).toHaveBeenCalledWith('/workspace/repo', { signal })
|
||||
expect(result).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('delegates to the graph listing without sparse annotation', async () => {
|
||||
listWorktreeGraphMock.mockResolvedValue([
|
||||
{ path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true }
|
||||
])
|
||||
|
||||
const result = await listRepoWorktreeGraph({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'git'
|
||||
})
|
||||
|
||||
expect(listWorktreeGraphMock).toHaveBeenCalledWith('/workspace/repo')
|
||||
expect(listWorktreesMock).not.toHaveBeenCalled()
|
||||
expect(result).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('returns the synthetic folder worktree from the graph listing', async () => {
|
||||
const result = await listRepoWorktreeGraph({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/folder',
|
||||
displayName: 'folder',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'folder'
|
||||
})
|
||||
|
||||
expect(listWorktreeGraphMock).not.toHaveBeenCalled()
|
||||
expect(result).toEqual([
|
||||
createFolderWorktree({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/folder',
|
||||
displayName: 'folder',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'folder'
|
||||
})
|
||||
])
|
||||
})
|
||||
|
||||
it('delegates strict local listing with the signal and WSL options', async () => {
|
||||
listWorktreesStrictMock.mockResolvedValue([
|
||||
{ path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true }
|
||||
])
|
||||
const signal = new AbortController().signal
|
||||
|
||||
const result = await listLocalRepoWorktreesStrict(
|
||||
{
|
||||
id: 'repo-1',
|
||||
path: '/workspace/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'git'
|
||||
},
|
||||
{ signal, wslDistro: 'Ubuntu' }
|
||||
)
|
||||
|
||||
expect(listWorktreesStrictMock).toHaveBeenCalledWith('/workspace/repo', {
|
||||
signal,
|
||||
wslDistro: 'Ubuntu'
|
||||
})
|
||||
expect(result).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rejects strict listing for remote repos', async () => {
|
||||
await expect(
|
||||
listLocalRepoWorktreesStrict({
|
||||
id: 'repo-1',
|
||||
path: '/workspace/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
connectionId: 'ssh-1',
|
||||
kind: 'git'
|
||||
})
|
||||
).rejects.toThrow('remote repository')
|
||||
expect(listWorktreesStrictMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
describe('rows that spell their owner only as executionHostId', () => {
|
||||
const sshOnlyRepo = {
|
||||
id: 'repo-1',
|
||||
path: '/srv/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'git' as const,
|
||||
executionHostId: 'ssh:host-a' as const
|
||||
}
|
||||
|
||||
it('never lists an ssh-owned row with local git', async () => {
|
||||
await expect(listRepoWorktrees(sshOnlyRepo)).rejects.toThrow(WorktreeCatalogUnavailableError)
|
||||
expect(listWorktreesMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps an ssh-owned root out of the local repo-root match', () => {
|
||||
expect(isRepoRoot([sshOnlyRepo], '/srv/repo')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects strict local listing for an ssh-owned row', async () => {
|
||||
await expect(listLocalRepoWorktreesStrict(sshOnlyRepo)).rejects.toThrow('remote repository')
|
||||
expect(listWorktreesStrictMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses to answer a runtime-owned row from a same-named local target', async () => {
|
||||
await expect(
|
||||
listRepoWorktrees({
|
||||
...sshOnlyRepo,
|
||||
executionHostId: 'runtime:env-7',
|
||||
connectionId: 'nested-target'
|
||||
})
|
||||
).rejects.toThrow(WorktreeCatalogUnavailableError)
|
||||
expect(listWorktreesMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports an unserved ssh host as unavailable from the graph listing, never as empty', async () => {
|
||||
await expect(listRepoWorktreeGraph(sshOnlyRepo)).rejects.toThrow(
|
||||
'SSH connection "host-a" is not connected'
|
||||
)
|
||||
await expect(listRepoWorktreeGraph(sshOnlyRepo)).rejects.toBeInstanceOf(
|
||||
WorktreeCatalogUnavailableError
|
||||
)
|
||||
expect(listWorktreeGraphMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a runtime-owned row as unavailable from the graph listing, never as empty', async () => {
|
||||
await expect(
|
||||
listRepoWorktreeGraph({
|
||||
...sshOnlyRepo,
|
||||
executionHostId: 'runtime:env-7',
|
||||
connectionId: 'nested-target'
|
||||
})
|
||||
).rejects.toThrow('host runtime:env-7 is not reachable from this process')
|
||||
expect(listWorktreeGraphMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('treats Windows repo root casing differences as the same local root', () => {
|
||||
const repos = [
|
||||
{
|
||||
id: 'repo-1',
|
||||
path: String.raw`C:\Repo`,
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
kind: 'git' as const
|
||||
}
|
||||
]
|
||||
|
||||
expect(isRepoRoot(repos, String.raw`c:\repo`)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps an upgraded linked folder locator in every local listing, including restart hydration', async () => {
|
||||
const repo = {
|
||||
id: 'folder',
|
||||
path: 'C:\\projects\\draft',
|
||||
displayName: 'draft',
|
||||
badgeColor: 'blue',
|
||||
addedAt: 0,
|
||||
kind: 'git' as const,
|
||||
folderUpgradeGitRootPath: 'C:/projects/draft'
|
||||
}
|
||||
const raw = [
|
||||
{ path: 'C:/projects/main', head: 'abc', branch: 'main', isBare: false, isMainWorktree: true },
|
||||
{
|
||||
path: 'C:/projects/draft',
|
||||
head: 'def',
|
||||
branch: 'draft',
|
||||
isBare: false,
|
||||
isMainWorktree: false
|
||||
}
|
||||
]
|
||||
listWorktreesMock.mockResolvedValue(raw)
|
||||
listWorktreeGraphMock.mockResolvedValue(raw)
|
||||
listWorktreesStrictMock.mockResolvedValue(raw)
|
||||
for (const list of [
|
||||
listRepoWorktrees,
|
||||
listRepoWorktreesForDetectedScan,
|
||||
listRepoWorktreeGraph,
|
||||
listLocalRepoWorktreesStrict
|
||||
]) {
|
||||
expect(await list(repo)).toEqual([raw[0], { ...raw[1], path: repo.path }])
|
||||
}
|
||||
expect(raw[1].path).toBe('C:/projects/draft')
|
||||
})
|
||||
@@ -1,276 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Store } from '../../persistence/loading-store/store'
|
||||
import type { Project } from '../../../shared/project-types'
|
||||
import type { Repo } from '../../../shared/repo-types'
|
||||
import {
|
||||
getLocalProjectGitExecOptions,
|
||||
getWorktreeCreatePrefetchGitOptions,
|
||||
getWorktreeMirrorDistro
|
||||
} from './project-runtime-git-options'
|
||||
import { resolveLocalProjectRuntimeForRepo } from './local-project-runtime-resolution'
|
||||
import { _resetWslCachesForTests, _setWslCachesForTests } from '../../wsl/discovery/distro-catalog'
|
||||
|
||||
function withPlatform<T>(platform: NodeJS.Platform, run: () => T): T {
|
||||
const originalPlatform = process.platform
|
||||
Object.defineProperty(process, 'platform', {
|
||||
configurable: true,
|
||||
value: platform
|
||||
})
|
||||
try {
|
||||
return run()
|
||||
} finally {
|
||||
Object.defineProperty(process, 'platform', {
|
||||
configurable: true,
|
||||
value: originalPlatform
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function makeRepo(overrides: Partial<Repo> = {}): Repo {
|
||||
return {
|
||||
id: 'repo-1',
|
||||
displayName: 'Repo',
|
||||
path: String.raw`C:\repo`,
|
||||
badgeColor: '#000000',
|
||||
addedAt: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
return {
|
||||
id: 'project-1',
|
||||
displayName: 'Project',
|
||||
badgeColor: '#000000',
|
||||
sourceRepoIds: ['repo-1'],
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function makeStore(
|
||||
project: Project,
|
||||
localWindowsRuntimeDefault: unknown = { kind: 'windows-host' }
|
||||
): Store {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: runtime resolution reads only getProjects and getSettings.
|
||||
return {
|
||||
getProjects: () => [project],
|
||||
getSettings: () => ({ localWindowsRuntimeDefault })
|
||||
} as unknown as Store
|
||||
}
|
||||
|
||||
describe('project runtime git options', () => {
|
||||
afterEach(() => {
|
||||
_resetWslCachesForTests()
|
||||
})
|
||||
|
||||
it('does not probe or repair WSL git routing before capability caches exist', () => {
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
const options = withPlatform('win32', () =>
|
||||
getLocalProjectGitExecOptions(makeStore(project), makeRepo())
|
||||
)
|
||||
|
||||
expect(options).toEqual({ cwd: String.raw`C:\repo`, wslDistro: 'Ubuntu' })
|
||||
})
|
||||
|
||||
it('keeps WSL Git for a drive project that inherits WSL and never chose Windows Git', () => {
|
||||
const store = makeStore(makeProject(), { kind: 'wsl', distro: 'Ubuntu' })
|
||||
|
||||
const options = withPlatform('win32', () => getLocalProjectGitExecOptions(store, makeRepo()))
|
||||
|
||||
expect(options).toEqual({ cwd: String.raw`C:\repo`, wslDistro: 'Ubuntu' })
|
||||
})
|
||||
|
||||
it('runs Windows Git for a WSL project converted to Windows Git', () => {
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' }
|
||||
})
|
||||
|
||||
const options = withPlatform('win32', () =>
|
||||
getLocalProjectGitExecOptions(makeStore(project), makeRepo())
|
||||
)
|
||||
|
||||
expect(options).toEqual({ cwd: String.raw`C:\repo` })
|
||||
})
|
||||
|
||||
it('returns repair state for missing cached WSL distro before local git execution', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Debian'] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
const runtime = withPlatform('win32', () =>
|
||||
resolveLocalProjectRuntimeForRepo(makeStore(project), makeRepo())
|
||||
)
|
||||
|
||||
expect(runtime).toEqual({
|
||||
status: 'repair-required',
|
||||
repair: {
|
||||
projectId: 'project-1',
|
||||
preferredRuntime: { kind: 'wsl', distro: 'Ubuntu' },
|
||||
reason: 'wsl-distro-missing',
|
||||
source: 'project-override',
|
||||
cacheKey: 'project-1:repair:wsl-distro-missing:Ubuntu'
|
||||
}
|
||||
})
|
||||
expect(() =>
|
||||
withPlatform('win32', () => getLocalProjectGitExecOptions(makeStore(project), makeRepo()))
|
||||
).toThrow('Project runtime requires repair before git execution: wsl-distro-missing')
|
||||
})
|
||||
|
||||
it('returns repair state for cached WSL unavailable before local git execution', () => {
|
||||
_setWslCachesForTests({ available: false, distros: [] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
expect(() =>
|
||||
withPlatform('win32', () => getLocalProjectGitExecOptions(makeStore(project), makeRepo()))
|
||||
).toThrow('Project runtime requires repair before git execution: wsl-unavailable')
|
||||
})
|
||||
|
||||
it('keeps project host override on host even when cached WSL is unavailable', () => {
|
||||
_setWslCachesForTests({ available: false, distros: [] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'windows-host' }
|
||||
})
|
||||
|
||||
const options = withPlatform('win32', () =>
|
||||
getLocalProjectGitExecOptions(makeStore(project), makeRepo())
|
||||
)
|
||||
|
||||
expect(options).toEqual({ cwd: String.raw`C:\repo` })
|
||||
})
|
||||
|
||||
it('does not apply local Windows runtime routing to SSH-owned repos', () => {
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
const runtime = withPlatform('win32', () =>
|
||||
resolveLocalProjectRuntimeForRepo(
|
||||
makeStore(project),
|
||||
makeRepo({ connectionId: null, executionHostId: 'ssh:target-1' })
|
||||
)
|
||||
)
|
||||
|
||||
expect(runtime).toBeUndefined()
|
||||
})
|
||||
|
||||
describe('getWorktreeMirrorDistro', () => {
|
||||
it('names the distro a resolved WSL project runs in', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Ubuntu'] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
expect(
|
||||
withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo()))
|
||||
).toBe('Ubuntu')
|
||||
})
|
||||
|
||||
it('names no distro for a project converted to Windows Git', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Ubuntu'] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' }
|
||||
})
|
||||
|
||||
expect(
|
||||
withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo()))
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('names no distro for a host-runtime project', () => {
|
||||
const project = makeProject({ localWindowsRuntimePreference: { kind: 'windows-host' } })
|
||||
|
||||
expect(
|
||||
withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo()))
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
// Worktree placement permits Windows fallback even when Git execution would require runtime repair.
|
||||
it('names no distro instead of throwing when the runtime needs repair', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Debian'] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
expect(
|
||||
withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo()))
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('names no distro when the store cannot resolve projects', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Ubuntu'] })
|
||||
|
||||
expect(withPlatform('win32', () => getWorktreeMirrorDistro({}, makeRepo()))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getWorktreeCreatePrefetchGitOptions', () => {
|
||||
it('routes the warm-up through the distro a resolved WSL project runs in', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Ubuntu'] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
expect(
|
||||
withPlatform('win32', () =>
|
||||
getWorktreeCreatePrefetchGitOptions(makeStore(project), makeRepo())
|
||||
)
|
||||
).toEqual({ wslDistro: 'Ubuntu' })
|
||||
})
|
||||
|
||||
// Speculative warmup must fall back to host Git instead of exposing a repair error.
|
||||
it('falls back to host git instead of throwing when the runtime needs repair', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Debian'] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
expect(
|
||||
withPlatform('win32', () =>
|
||||
getWorktreeCreatePrefetchGitOptions(makeStore(project), makeRepo())
|
||||
)
|
||||
).toEqual({})
|
||||
})
|
||||
|
||||
it('does not resolve a project runtime for folder workspaces', () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Ubuntu'] })
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
const store = makeStore(project)
|
||||
const getProjects = vi.fn(store.getProjects)
|
||||
|
||||
expect(
|
||||
withPlatform('win32', () =>
|
||||
getWorktreeCreatePrefetchGitOptions(
|
||||
{ ...store, getProjects } as unknown as Store,
|
||||
makeRepo({ kind: 'folder' })
|
||||
)
|
||||
)
|
||||
).toEqual({})
|
||||
expect(getProjects).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('does not apply local Windows runtime routing to runtime-owned repos', () => {
|
||||
const project = makeProject({
|
||||
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
const runtime = withPlatform('win32', () =>
|
||||
resolveLocalProjectRuntimeForRepo(
|
||||
makeStore(project),
|
||||
makeRepo({ connectionId: null, executionHostId: 'runtime:env-1' })
|
||||
)
|
||||
)
|
||||
|
||||
expect(runtime).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -15,12 +15,7 @@ import {
|
||||
ORCAD_WSL_HOLDER_BLOCKED_FILENAME,
|
||||
ORCAD_WSL_HOLDER_RELEASE_FILENAME
|
||||
} from '../../../shared/orcad-idle-exit'
|
||||
import {
|
||||
buildWslDistroHolderScript,
|
||||
WSL_DISTRO_HOLDER_BLOCKED_NAMES_MAX,
|
||||
WSL_DISTRO_HOLDER_IGNORED_PROCESS_NAMES,
|
||||
WSL_DISTRO_HOLDER_MARKER
|
||||
} from './wsl-distro-holder-command'
|
||||
import { buildWslDistroHolderScript, WSL_DISTRO_HOLDER_MARKER } from './wsl-distro-holder-command'
|
||||
|
||||
// The script runs inside the distro; any POSIX sh here exercises the same text. A fake /proc stands
|
||||
// in for the distro's, so the test runner's own processes never count as the user's work.
|
||||
@@ -127,13 +122,6 @@ async function holderWithRequest(options: { procReadable?: boolean; path?: strin
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('WSL distro holder script', () => {
|
||||
it('drops a request left from before it started: a client wants the distro now', async () => {
|
||||
writeFileSync(releasePath(), '999999\n')
|
||||
const { exited } = startHolder()
|
||||
expect(await within(2_500, exited)).toBe('running')
|
||||
expect(existsSync(releasePath())).toBe(false)
|
||||
})
|
||||
|
||||
it('waits for the requesting orcad to exit, then claims the request and ends', async () => {
|
||||
const holder = await startHolderReady()
|
||||
const orcad = track(spawn('/bin/sh', ['-c', 'sleep 30'], { stdio: 'ignore' }))
|
||||
@@ -175,43 +163,6 @@ describe.skipIf(process.platform === 'win32')('WSL distro holder script', () =>
|
||||
expect(await within(RELEASE_BOUND_MS, exited)).toBe(0)
|
||||
})
|
||||
|
||||
it('does not count session plumbing, zombies, other users or its own children', async () => {
|
||||
let pid = 5000
|
||||
for (const name of WSL_DISTRO_HOLDER_IGNORED_PROCESS_NAMES) {
|
||||
fakeProcess(pid++, { name })
|
||||
}
|
||||
fakeProcess(pid++, { state: 'Z (zombie)' })
|
||||
fakeProcess(pid++, { uid: me + 1 })
|
||||
const holder = await startHolderReady()
|
||||
fakeProcess(pid++, { name: 'sleep', ppid: holder.child.pid })
|
||||
const orcad = track(spawn('/bin/sh', ['-c', 'exit 0'], { stdio: 'ignore' }))
|
||||
await new Promise((resolve) => orcad.once('exit', resolve))
|
||||
writeFileSync(releasePath(), `${orcad.pid}\n`)
|
||||
expect(await within(RELEASE_BOUND_MS, holder.exited)).toBe(0)
|
||||
})
|
||||
|
||||
it('notes what keeps it holding, and clears the note once it releases', async () => {
|
||||
const job = fakeProcess(4242, { name: 'node' })
|
||||
const { exited } = await holderWithRequest()
|
||||
await expect.poll(() => existsSync(blockedPath()), { timeout: 5_000 }).toBe(true)
|
||||
expect(readFileSync(blockedPath(), 'utf8')).toBe('node\n')
|
||||
rmSync(job, { recursive: true })
|
||||
expect(await within(RELEASE_BOUND_MS, exited)).toBe(0)
|
||||
expect(existsSync(blockedPath())).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the note bounded however much the user runs', async () => {
|
||||
for (let pid = 6000; pid < 6000 + 3 * WSL_DISTRO_HOLDER_BLOCKED_NAMES_MAX; pid++) {
|
||||
fakeProcess(pid, { name: `job${pid}` })
|
||||
}
|
||||
const { exited } = await holderWithRequest()
|
||||
await expect.poll(() => existsSync(blockedPath()), { timeout: 5_000 }).toBe(true)
|
||||
expect(readFileSync(blockedPath(), 'utf8').trim().split(' ')).toHaveLength(
|
||||
WSL_DISTRO_HOLDER_BLOCKED_NAMES_MAX
|
||||
)
|
||||
expect(await within(1_500, exited)).toBe('running')
|
||||
})
|
||||
|
||||
it('fails closed when /proc cannot be read', async () => {
|
||||
const { exited } = await holderWithRequest({ procReadable: false })
|
||||
expect(await within(2_500, exited)).toBe('running')
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as VersionGc from '../../managed-server/lifecycle/orcad-managed-version-gc'
|
||||
import type * as RemoteVersionedInstall from '../../managed-server/install/remote-versioned-install'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
installed: new Set<string>(),
|
||||
record: vi.fn(),
|
||||
readiness: vi.fn(),
|
||||
pins: vi.fn(),
|
||||
inUse: vi.fn(async () => false),
|
||||
remove: vi.fn(),
|
||||
fenceHeld: false
|
||||
}))
|
||||
|
||||
vi.mock('../../managed-server/activation/orcad-activation-record-store', () => ({
|
||||
readOrcadActivationRecord: mocks.record
|
||||
}))
|
||||
vi.mock('../../managed-server/lifecycle/orcad-managed-version-gc', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof VersionGc>()),
|
||||
probeOrcadSlotReadiness: mocks.readiness
|
||||
}))
|
||||
vi.mock('../../ssh/orcad-gc-transaction-pins', () => ({ readOrcadGcTransactionPins: mocks.pins }))
|
||||
vi.mock('./wsl-orcad-slot-process-probe', () => ({ isWslOrcadSlotInUse: mocks.inUse }))
|
||||
// One activation fence per host: a second taker is told it is held, as the real lock does after its wait.
|
||||
vi.mock('../../managed-server/activation/orcad-activation-lock', () => ({
|
||||
withOrcadActivationLock: async <T>(_slot: unknown, run: () => Promise<T>, held: () => T) => {
|
||||
if (mocks.fenceHeld) {
|
||||
return held()
|
||||
}
|
||||
mocks.fenceHeld = true
|
||||
try {
|
||||
return await run()
|
||||
} finally {
|
||||
mocks.fenceHeld = false
|
||||
}
|
||||
}
|
||||
}))
|
||||
vi.mock('../../managed-server/install/remote-install-gc', () => ({
|
||||
removeRemoteInstallVersionDir: mocks.remove
|
||||
}))
|
||||
// The install itself runs for real against a host whose only state is which slots are complete.
|
||||
vi.mock('../../managed-server/install/remote-versioned-install', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof RemoteVersionedInstall>()),
|
||||
isRemoteInstallComplete: async (_conn: unknown, _model: unknown, dir: string) =>
|
||||
mocks.installed.has(dir),
|
||||
finalizeInstall: async (_conn: unknown, dir: string) => void mocks.installed.add(dir),
|
||||
abandonInstall: async () => true
|
||||
}))
|
||||
vi.mock('../../managed-server/install/remote-install-lock', () => ({
|
||||
acquireInstallLock: vi.fn(async () => {})
|
||||
}))
|
||||
vi.mock('../../managed-server/install/remote-install-transfers', () => ({
|
||||
uploadRemoteInstallDirectory: vi.fn(async () => {}),
|
||||
writeRemoteInstallFile: vi.fn(async () => {})
|
||||
}))
|
||||
vi.mock('../../managed-server/install/orcad-remote-node-runtime', () => ({
|
||||
ensureRemoteOrcadNodeRuntime: vi.fn(async () => {})
|
||||
}))
|
||||
vi.mock('../../ssh/remote-exec/remote-exec-command', () => ({
|
||||
execCommand: vi.fn(async () => ''),
|
||||
isUnconfirmedSshCommandTermination: () => false
|
||||
}))
|
||||
|
||||
import { removeFailedFreshWslOrcadInstall } from './wsl-orcad-failed-install-removal'
|
||||
import { withOrcadActivationLock } from '../../managed-server/activation/orcad-activation-lock'
|
||||
import { installOrcadBundle } from '../../managed-server/install/orcad-remote-install'
|
||||
import { uploadRemoteInstallDirectory } from '../../managed-server/install/remote-install-transfers'
|
||||
import {
|
||||
emptyOrcadActivationRecord,
|
||||
withActivatedVersion
|
||||
} from '../../managed-server/activation/orcad-activation-record'
|
||||
import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform'
|
||||
import type { OrcadDeployResult } from '../../ssh/orcad-remote-deploy'
|
||||
|
||||
const NEW = '1.6.0+bb01'
|
||||
const OLD = '1.5.0+aa01'
|
||||
const NEW_DIR = `/home/u/.orca-remote/orcad-${NEW}`
|
||||
const host = getRemoteHostPlatform('linux-x64')
|
||||
const slot = {
|
||||
conn: Object.create(null),
|
||||
host,
|
||||
remoteHome: '/home/u',
|
||||
nodePath: '/usr/bin/node',
|
||||
userDataDir: '/home/u/.orca',
|
||||
bindHost: '127.0.0.1',
|
||||
port: 6768
|
||||
}
|
||||
const failedFresh: OrcadDeployResult = {
|
||||
outcome: 'installed-not-activated',
|
||||
fullVersion: NEW,
|
||||
code: 'orcad_activation_daemon_degraded',
|
||||
reason: 'the candidate failed its readiness check',
|
||||
startCheckFailed: true,
|
||||
freshlyInstalled: true
|
||||
}
|
||||
|
||||
function install(): Promise<'uploaded' | 'reused'> {
|
||||
return installOrcadBundle(
|
||||
{
|
||||
...slot,
|
||||
localOrcadDir: '/local/orcad',
|
||||
target: 'linux-x64-glibc',
|
||||
nodeRuntimeArchive: async () => '/cache/node.tar.gz'
|
||||
},
|
||||
NEW,
|
||||
NEW_DIR
|
||||
)
|
||||
}
|
||||
|
||||
function daemon(state: 'live' | 'absent' | 'degraded', buildVersion = OLD) {
|
||||
return { health: { terminalDaemon: { state, buildVersion } } }
|
||||
}
|
||||
|
||||
describe('removeFailedFreshWslOrcadInstall', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.installed.clear()
|
||||
mocks.fenceHeld = false
|
||||
mocks.record.mockResolvedValue(
|
||||
withActivatedVersion(emptyOrcadActivationRecord(), OLD, null, new Date(0))
|
||||
)
|
||||
mocks.readiness.mockResolvedValue(daemon('live'))
|
||||
mocks.pins.mockResolvedValue({ state: 'pinned', dirNames: [] })
|
||||
mocks.remove.mockImplementation(async (_conn: unknown, _model: unknown, dir: string) =>
|
||||
mocks.installed.delete(dir)
|
||||
)
|
||||
})
|
||||
|
||||
it('removes a slot this connect uploaded once its candidate fails, so the retry uploads again', async () => {
|
||||
expect(await install()).toBe('uploaded')
|
||||
|
||||
await removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
|
||||
expect(mocks.remove).toHaveBeenCalledWith(slot.conn, expect.anything(), NEW_DIR, host, {
|
||||
isDirLive: expect.any(Function)
|
||||
})
|
||||
expect(mocks.installed.has(NEW_DIR)).toBe(false)
|
||||
expect(await install()).toBe('uploaded')
|
||||
expect(uploadRemoteInstallDirectory).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('checks and deletes under the activation fence, so a concurrent activator waits and re-uploads', async () => {
|
||||
await install()
|
||||
let resume = (): void => {}
|
||||
mocks.record.mockImplementationOnce(async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
resume = resolve
|
||||
})
|
||||
return emptyOrcadActivationRecord()
|
||||
})
|
||||
const removal = removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
await vi.waitFor(() => expect(mocks.record).toHaveBeenCalled())
|
||||
|
||||
// Another connect reaching activation between the check and the delete finds the fence held.
|
||||
const activator = await withOrcadActivationLock(
|
||||
slot,
|
||||
async () => 'launched',
|
||||
() => 'held'
|
||||
)
|
||||
expect(activator).toBe('held')
|
||||
resume()
|
||||
await removal
|
||||
|
||||
expect(mocks.pins).toHaveBeenCalledWith(slot, { callerHoldsFence: true })
|
||||
expect(mocks.installed.has(NEW_DIR)).toBe(false)
|
||||
expect(await install()).toBe('uploaded')
|
||||
})
|
||||
|
||||
it('keeps the copy when another activator already holds the fence', async () => {
|
||||
await install()
|
||||
mocks.fenceHeld = true
|
||||
|
||||
await removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
|
||||
expect(mocks.record).not.toHaveBeenCalled()
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
expect(await install()).toBe('reused')
|
||||
})
|
||||
|
||||
it('asks the slot process probe, which also sees a daemon the candidate left there', async () => {
|
||||
await removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
const [, , , , { isDirLive }] = mocks.remove.mock.calls[0]
|
||||
mocks.inUse.mockResolvedValueOnce(true)
|
||||
|
||||
await expect(isDirLive(NEW_DIR)).resolves.toBe(true)
|
||||
expect(mocks.inUse).toHaveBeenCalledWith(slot, NEW_DIR)
|
||||
})
|
||||
|
||||
it('also removes a failed first install, where nothing is active', async () => {
|
||||
mocks.record.mockResolvedValue(emptyOrcadActivationRecord())
|
||||
await install()
|
||||
|
||||
await removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
|
||||
expect(mocks.readiness).not.toHaveBeenCalled()
|
||||
expect(mocks.installed.has(NEW_DIR)).toBe(false)
|
||||
})
|
||||
|
||||
it('never touches a slot that was already installed before this connect', async () => {
|
||||
mocks.installed.add(NEW_DIR)
|
||||
expect(await install()).toBe('reused')
|
||||
|
||||
await removeFailedFreshWslOrcadInstall(slot, { ...failedFresh, freshlyInstalled: undefined })
|
||||
|
||||
expect(mocks.record).not.toHaveBeenCalled()
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
expect(await install()).toBe('reused')
|
||||
})
|
||||
|
||||
it('keeps a deferred update staged for later', async () => {
|
||||
await removeFailedFreshWslOrcadInstall(slot, { ...failedFresh, startCheckFailed: undefined })
|
||||
await removeFailedFreshWslOrcadInstall(slot, { outcome: 'already-active', fullVersion: NEW })
|
||||
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'is the active version',
|
||||
withActivatedVersion(emptyOrcadActivationRecord(), NEW, null, new Date(0))
|
||||
],
|
||||
[
|
||||
'is the rollback target',
|
||||
withActivatedVersion(
|
||||
withActivatedVersion(emptyOrcadActivationRecord(), NEW, null, new Date(0)),
|
||||
OLD,
|
||||
null,
|
||||
new Date(1)
|
||||
)
|
||||
]
|
||||
])('never removes a slot that %s', async (_label, record) => {
|
||||
mocks.record.mockResolvedValue(record)
|
||||
|
||||
await removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['runs a live terminal daemon from it', daemon('live', NEW)],
|
||||
['cannot name its terminal daemon build', daemon('degraded')]
|
||||
])('keeps the slot while the serving version %s', async (_label, readiness) => {
|
||||
mocks.readiness.mockResolvedValue(readiness)
|
||||
|
||||
await removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a held fence or unreadable journal', { state: 'keep-all' }],
|
||||
['a journaled activation', { state: 'pinned', dirNames: [`orcad-${NEW}`] }]
|
||||
])('keeps the slot that %s may still need', async (_label, pins) => {
|
||||
mocks.pins.mockResolvedValue(pins)
|
||||
|
||||
await removeFailedFreshWslOrcadInstall(slot, failedFresh)
|
||||
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves the failed connect to report its own reason when cleanup fails', async () => {
|
||||
mocks.readiness.mockRejectedValue(new Error('probe timed out'))
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
await expect(removeFailedFreshWslOrcadInstall(slot, failedFresh)).resolves.toBeUndefined()
|
||||
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
warn.mockRestore()
|
||||
})
|
||||
})
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { useRef } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { NativeChatFollowUpBehavior } from '../../../../../../shared/native-chat/input/native-chat-follow-up-behavior'
|
||||
import { NATIVE_CHAT_STEER_CHORD_HOLD_MS } from '../../../../../../shared/native-chat/input/use-native-chat-steer-chord-preview'
|
||||
import { useNativeChatSteerChordPreview } from './use-native-chat-steer-chord-preview'
|
||||
|
||||
vi.mock('../../pane/routing/native-chat-shortcut', () => ({ isMacPlatform: () => true }))
|
||||
|
||||
type Props = {
|
||||
alternateSend: NativeChatFollowUpBehavior | undefined
|
||||
hasDraft: boolean
|
||||
chordSteersHead: boolean
|
||||
steerHead: (() => boolean) | undefined
|
||||
send: () => void
|
||||
pickerOpen: boolean
|
||||
}
|
||||
|
||||
function Composer(props: Props): React.JSX.Element {
|
||||
const root = useRef<HTMLDivElement>(null)
|
||||
const { alternateSend, hasDraft, chordSteersHead, steerHead, send, pickerOpen } = props
|
||||
const { preview, runPreview } = useNativeChatSteerChordPreview(
|
||||
root,
|
||||
{ alternateSend, hasDraft, chordSteersHead },
|
||||
steerHead,
|
||||
send,
|
||||
pickerOpen
|
||||
)
|
||||
return (
|
||||
<div ref={root}>
|
||||
<textarea aria-label="composer" />
|
||||
<button type="button" data-preview={preview ?? ''} onClick={runPreview}>
|
||||
send
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
describe('useNativeChatSteerChordPreview', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.spyOn(document, 'hasFocus').mockReturnValue(true)
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function setup(overrides: Partial<Props> = {}) {
|
||||
const props: Props = {
|
||||
alternateSend: 'steer',
|
||||
hasDraft: false,
|
||||
chordSteersHead: true,
|
||||
steerHead: vi.fn(() => true),
|
||||
send: vi.fn(),
|
||||
pickerOpen: false,
|
||||
...overrides
|
||||
}
|
||||
const view = render(<Composer {...props} />)
|
||||
const field = view.getByLabelText('composer')
|
||||
const button = view.getByRole('button')
|
||||
const hold = () => {
|
||||
fireEvent.keyDown(field, { key: 'Meta' })
|
||||
act(() => vi.advanceTimersByTime(NATIVE_CHAT_STEER_CHORD_HOLD_MS))
|
||||
}
|
||||
return { props, view, field, button, hold, preview: () => button.dataset.preview }
|
||||
}
|
||||
|
||||
it('never flashes for a quick chord such as Cmd+C', () => {
|
||||
const { field, preview } = setup()
|
||||
fireEvent.keyDown(field, { key: 'Meta' })
|
||||
fireEvent.keyDown(field, { key: 'c', metaKey: true })
|
||||
act(() => vi.advanceTimersByTime(NATIVE_CHAT_STEER_CHORD_HOLD_MS * 2))
|
||||
expect(preview()).toBe('')
|
||||
})
|
||||
|
||||
it('releases when the window loses focus, since macOS drops the key-up after Cmd+Tab', () => {
|
||||
const { hold, preview } = setup()
|
||||
hold()
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event('blur'))
|
||||
})
|
||||
expect(preview()).toBe('')
|
||||
})
|
||||
|
||||
it('shows nothing while an IME composes, since the IME owns Enter then', () => {
|
||||
const { field, preview } = setup({ hasDraft: true })
|
||||
fireEvent.keyDown(field, { key: 'Meta', isComposing: true })
|
||||
act(() => vi.advanceTimersByTime(NATIVE_CHAT_STEER_CHORD_HOLD_MS))
|
||||
expect(preview()).toBe('')
|
||||
})
|
||||
|
||||
it('previews sending the head card after a Stop, when no turn runs to steer into', () => {
|
||||
const { props, button, hold, preview } = setup({ alternateSend: undefined })
|
||||
hold()
|
||||
expect(preview()).toBe('steer-queued')
|
||||
fireEvent.click(button)
|
||||
expect(props.steerHead).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { expect, it } from 'vitest'
|
||||
import { useNativeChatReaderReturn } from './use-native-chat-reader-return'
|
||||
|
||||
it('requires reader movement and rejects a geometry-only clamp', () => {
|
||||
const element = document.createElement('div')
|
||||
Object.defineProperties(element, {
|
||||
scrollTop: { value: 360, writable: true },
|
||||
clientHeight: { value: 600, writable: true },
|
||||
scrollHeight: { value: 1000, writable: true }
|
||||
})
|
||||
const previous = { current: { scrollTop: 360, clientHeight: 600, scrollHeight: 1000 } }
|
||||
const view = renderHook(() =>
|
||||
useNativeChatReaderReturn({ current: element }, { current: true }, previous)
|
||||
)
|
||||
const geometry = { scrollTop: 320, clientHeight: 680, scrollHeight: 1000 }
|
||||
expect(view.result.current.readerReturned(geometry, false)).toBe(false)
|
||||
view.result.current.recordReaderScroll()
|
||||
expect(view.result.current.readerReturned(geometry, false)).toBe(false)
|
||||
view.result.current.recordReaderScroll()
|
||||
expect(
|
||||
view.result.current.readerReturned(
|
||||
{ scrollTop: 400, clientHeight: 600, scrollHeight: 1000 },
|
||||
true
|
||||
)
|
||||
).toBe(false)
|
||||
expect(
|
||||
view.result.current.readerReturned(
|
||||
{ scrollTop: 400, clientHeight: 600, scrollHeight: 1000 },
|
||||
false
|
||||
)
|
||||
).toBe(false)
|
||||
view.unmount()
|
||||
})
|
||||
|
||||
it('rebases a continuing reader gesture across compensation without crediting a later clamp', () => {
|
||||
const element = document.createElement('div')
|
||||
Object.defineProperties(element, {
|
||||
scrollTop: { value: 1400, writable: true },
|
||||
clientHeight: { value: 600, writable: true },
|
||||
scrollHeight: { value: 2000, writable: true }
|
||||
})
|
||||
const following = { current: false }
|
||||
const previous = { current: { scrollTop: 1400, clientHeight: 600, scrollHeight: 2000 } }
|
||||
const view = renderHook(() =>
|
||||
useNativeChatReaderReturn({ current: element }, following, previous)
|
||||
)
|
||||
const observe = (scrollTop: number, scrollHeight: number, programmatic = false) =>
|
||||
view.result.current.readerReturned({ scrollTop, clientHeight: 600, scrollHeight }, programmatic)
|
||||
view.result.current.recordReaderScroll()
|
||||
expect(observe(1380, 2000)).toBe(false)
|
||||
expect(observe(1580, 2200, true)).toBe(false)
|
||||
following.current = true
|
||||
expect(observe(1540, 2140)).toBe(false)
|
||||
|
||||
// A scrollbar drag or touch momentum can continue without a second input callback.
|
||||
following.current = false
|
||||
view.result.current.observeVisibility(true, true)
|
||||
view.result.current.recordReaderScroll()
|
||||
expect(observe(1380, 2000)).toBe(false)
|
||||
expect(observe(1580, 2200, true)).toBe(false)
|
||||
expect(observe(1580, 2200, true)).toBe(false)
|
||||
expect(observe(1590, 2200)).toBe(false)
|
||||
following.current = true
|
||||
expect(observe(1600, 2200)).toBe(true)
|
||||
expect(observe(1600, 2200)).toBe(false)
|
||||
|
||||
// A smaller measured row is a known compensation, not an ambiguous browser clamp.
|
||||
following.current = false
|
||||
view.result.current.observeVisibility(true, true)
|
||||
view.result.current.recordReaderScroll()
|
||||
expect(observe(1380, 2000)).toBe(false)
|
||||
expect(observe(1260, 1880, true)).toBe(false)
|
||||
expect(observe(1270, 1880)).toBe(false)
|
||||
following.current = true
|
||||
expect(observe(1280, 1880)).toBe(true)
|
||||
view.unmount()
|
||||
})
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushAsyncTicks } from '../test-fixtures/pty-connection-test-async'
|
||||
import {
|
||||
createMockTransport,
|
||||
createPane,
|
||||
captureCallbackTerminalWrites,
|
||||
createManager,
|
||||
type MockTransport
|
||||
} from '../test-fixtures/pty-connection-test-pane-fixtures'
|
||||
import {
|
||||
buildPaneConnectionDeps,
|
||||
type PtyConnectionAgentTitleMocks,
|
||||
bindPaneAgentTitleMocks
|
||||
} from '../test-fixtures/pty-connection-test-deps'
|
||||
import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures'
|
||||
import type { StoreState } from '../test-fixtures/pty-connection-test-store-state'
|
||||
import {
|
||||
installTerminalTestGlobals,
|
||||
restoreTerminalTestGlobals
|
||||
} from '../test-fixtures/pty-connection-test-environment'
|
||||
|
||||
export function registerPtyConnectionStartupCwdFallbackNoticeTests(): void {
|
||||
let mockStoreState: StoreState
|
||||
let transportFactoryQueue: MockTransport[] = []
|
||||
let createdTransportOptions: Record<string, unknown>[] = []
|
||||
let storeSubscribers: ((state: StoreState) => void)[] = []
|
||||
|
||||
function createDeps(overrides: Record<string, unknown> = {}) {
|
||||
return buildPaneConnectionDeps(() => mockStoreState, overrides)
|
||||
}
|
||||
describe('connectPanePty', () => {
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
transportFactoryQueue = []
|
||||
createdTransportOptions = []
|
||||
storeSubscribers = []
|
||||
mockStoreState = createInitialStoreState(() => mockStoreState)
|
||||
bindPtyConnectionTestMocks({
|
||||
getState: () => mockStoreState,
|
||||
getTransportQueue: () => transportFactoryQueue,
|
||||
getTransportOptions: () => createdTransportOptions,
|
||||
getStoreSubscribers: () => storeSubscribers,
|
||||
setStoreSubscribers: (subscribers) => {
|
||||
storeSubscribers = subscribers
|
||||
}
|
||||
})
|
||||
await installTerminalTestGlobals()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await restoreTerminalTestGlobals()
|
||||
})
|
||||
|
||||
it('prints a terminal notice when the startup cwd fell back to the workspace root', async () => {
|
||||
const { connectPanePty } = await import('../connect-pane-pty')
|
||||
const { STARTUP_CWD_FALLBACK_NOTICE } =
|
||||
await import('../../../../../../shared/startup-cwd-fallback')
|
||||
const agentTitleMocks5 =
|
||||
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
|
||||
const transport = createMockTransport('pty-fallback')
|
||||
transport.connect.mockResolvedValueOnce({
|
||||
id: 'pty-fallback',
|
||||
startupCwdFallback: { kind: 'worktree', cwd: '/tmp/wt-1' }
|
||||
})
|
||||
transportFactoryQueue.push(transport)
|
||||
|
||||
mockStoreState = {
|
||||
...mockStoreState,
|
||||
tabsByWorktree: {
|
||||
'wt-1': [{ id: 'tab-1', ptyId: null }]
|
||||
}
|
||||
} as StoreState
|
||||
|
||||
const pane = createPane(2)
|
||||
const { writes } = captureCallbackTerminalWrites(pane)
|
||||
|
||||
connectPanePty(
|
||||
pane as never,
|
||||
createManager(2) as never,
|
||||
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks5)
|
||||
)
|
||||
await flushAsyncTicks()
|
||||
|
||||
expect(writes).toContain(STARTUP_CWD_FALLBACK_NOTICE)
|
||||
})
|
||||
})
|
||||
}
|
||||
-2
@@ -4,7 +4,6 @@ import { registerPtyConnectionPendingSpawnTests } from '../spawn/pty-connection-
|
||||
import { registerPtyConnectionFreshSpawnGuardsTests } from '../spawn/pty-connection-fresh-spawn-guards.spec'
|
||||
import { registerPtyConnectionSplitSpawnTests } from '../spawn/pty-connection-split-spawn.spec'
|
||||
import { registerPtyConnectionRuntimeOwnerSpawnRoutingTests } from '../host-ownership/pty-connection-runtime-owner-spawn-routing.spec'
|
||||
import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'
|
||||
import { registerPtyConnectionRestoredRuntimePaneBindingTests } from '../reattach/pty-connection-restored-runtime-pane-binding.spec'
|
||||
import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec'
|
||||
import {
|
||||
@@ -22,7 +21,6 @@ describe('pty-connection-fresh-spawn-guards', registerPtyConnectionFreshSpawnGua
|
||||
describe('pty-connection-split-spawn', registerPtyConnectionSplitSpawnTests)
|
||||
describe('pty-connection-runtime-owner-spawn-routing', () => {
|
||||
registerPtyConnectionRuntimeOwnerSpawnRoutingTests()
|
||||
registerPtyConnectionStartupCwdFallbackNoticeTests()
|
||||
registerPtyConnectionRestoredRuntimePaneBindingTests()
|
||||
registerPtyConnectionTerminalBellAttentionTests()
|
||||
})
|
||||
|
||||
-30
@@ -35,25 +35,6 @@ describe('pty model-restore channel routing', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('attaches the channel once and routes markers to the registered PTY handler', async () => {
|
||||
const { registerPtyModelRestoreNeededHandler } = await import('./pty-model-restore-channel')
|
||||
const handlerA = vi.fn()
|
||||
const handlerB = vi.fn()
|
||||
|
||||
registerPtyModelRestoreNeededHandler('pty-a', handlerA)
|
||||
registerPtyModelRestoreNeededHandler('pty-b', handlerB)
|
||||
expect(onModelRestoreNeeded).toHaveBeenCalledTimes(1)
|
||||
|
||||
channelCallback?.({ id: 'pty-a', reason: 'hidden-drop', markerSeq: 42 })
|
||||
expect(handlerA).toHaveBeenCalledWith({ id: 'pty-a', reason: 'hidden-drop', markerSeq: 42 })
|
||||
expect(handlerB).not.toHaveBeenCalled()
|
||||
|
||||
// Markers for PTYs without a registered handler are dropped silently.
|
||||
channelCallback?.({ id: 'pty-unknown', reason: 'pending-cap' })
|
||||
expect(handlerA).toHaveBeenCalledTimes(1)
|
||||
expect(handlerB).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lets a new registration replace a stale one without the stale unregister clobbering it', async () => {
|
||||
const { registerPtyModelRestoreNeededHandler } = await import('./pty-model-restore-channel')
|
||||
const staleHandler = vi.fn()
|
||||
@@ -68,15 +49,4 @@ describe('pty model-restore channel routing', () => {
|
||||
expect(staleHandler).not.toHaveBeenCalled()
|
||||
expect(liveHandler).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('stops routing after the live handler unregisters', async () => {
|
||||
const { registerPtyModelRestoreNeededHandler } = await import('./pty-model-restore-channel')
|
||||
const handler = vi.fn()
|
||||
|
||||
const unregister = registerPtyModelRestoreNeededHandler('pty-a', handler)
|
||||
unregister()
|
||||
|
||||
channelCallback?.({ id: 'pty-a', reason: 'hidden-drop' })
|
||||
expect(handler).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
-18
@@ -66,22 +66,4 @@ describe('pty-transport — coalesced OSC titles from Pi', () => {
|
||||
|
||||
transport.disconnect()
|
||||
})
|
||||
|
||||
it('surfaces working frames when many spinner frames arrive in one chunk', async () => {
|
||||
// Delayed renderer flushes can batch many spinner frames; all must retain observer order.
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const onTitleChange = vi.fn()
|
||||
const transport = createIpcPtyTransport({ onTitleChange })
|
||||
await transport.connect({ url: '', callbacks: {} })
|
||||
|
||||
const framesChars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
|
||||
const chunk = framesChars.map(workingFrame).join('body\r\n')
|
||||
onData?.({ id: 'pty-pi', data: chunk })
|
||||
await flushPtySideEffects()
|
||||
|
||||
const seen = onTitleChange.mock.calls.map((c) => c[0])
|
||||
expect(seen).toContain('⠋ π - cwd')
|
||||
|
||||
transport.disconnect()
|
||||
})
|
||||
})
|
||||
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
// Pi OSC spinner frames must reach onTitleChange in the normalized form used by worktree-card status, including after reattach.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const ESC = '\x1b'
|
||||
const BEL = '\x07'
|
||||
const workingFrame = (frame: string): string => `${ESC}]0;${frame} π - cwd${BEL}`
|
||||
const idleTitle = (): string => `${ESC}]0;π - cwd${BEL}`
|
||||
|
||||
function flushPtySideEffects(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0))
|
||||
}
|
||||
|
||||
describe('createIpcPtyTransport — Pi titlebar spinner signal', () => {
|
||||
const originalWindow = (globalThis as { window?: typeof window }).window
|
||||
let onData: ((payload: { id: string; data: string }) => void) | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
onData = null
|
||||
;(globalThis as { window: typeof window }).window = {
|
||||
...originalWindow,
|
||||
api: {
|
||||
...originalWindow?.api,
|
||||
pty: {
|
||||
...originalWindow?.api?.pty,
|
||||
spawn: vi.fn().mockResolvedValue({ id: 'pty-pi' }),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
kill: vi.fn(),
|
||||
onData: vi.fn((cb: (payload: { id: string; data: string }) => void) => {
|
||||
onData = cb
|
||||
return () => {}
|
||||
}),
|
||||
onReplay: vi.fn(() => () => {}),
|
||||
onExit: vi.fn(() => () => {})
|
||||
}
|
||||
}
|
||||
} as unknown as typeof window
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalWindow) {
|
||||
;(globalThis as { window: typeof window }).window = originalWindow
|
||||
} else {
|
||||
delete (globalThis as { window?: typeof window }).window
|
||||
}
|
||||
})
|
||||
|
||||
it('surfaces normalized working and idle labels across a spinner cycle', async () => {
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const onTitleChange = vi.fn()
|
||||
|
||||
const transport = createIpcPtyTransport({ onTitleChange })
|
||||
await transport.connect({ url: '', callbacks: {} })
|
||||
|
||||
// Deliver idle→working→idle as separate chunks, matching captured live-session ordering.
|
||||
onData?.({ id: 'pty-pi', data: idleTitle() })
|
||||
onData?.({ id: 'pty-pi', data: workingFrame('⠋') }) // ⠋
|
||||
onData?.({ id: 'pty-pi', data: workingFrame('⠙') }) // ⠙
|
||||
onData?.({ id: 'pty-pi', data: workingFrame('⠹') }) // ⠹
|
||||
onData?.({ id: 'pty-pi', data: idleTitle() })
|
||||
await flushPtySideEffects()
|
||||
|
||||
const normalized = onTitleChange.mock.calls.map((c) => c[0])
|
||||
// Require a normalized working frame so the store/card can observe the active turn.
|
||||
expect(normalized).toContain('⠋ π - cwd')
|
||||
expect(normalized).toContain('π - cwd')
|
||||
|
||||
transport.disconnect()
|
||||
})
|
||||
|
||||
it('surfaces working even when a single chunk contains multiple spinner frames', async () => {
|
||||
// Batched spinner chunks must surface working before agent_end; final-idle coalescing has dedicated ordered-frame coverage.
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const onTitleChange = vi.fn()
|
||||
|
||||
const transport = createIpcPtyTransport({ onTitleChange })
|
||||
await transport.connect({ url: '', callbacks: {} })
|
||||
|
||||
const coalescedWorking = `${workingFrame('⠋')}output\r\n${workingFrame('⠙')}`
|
||||
onData?.({ id: 'pty-pi', data: coalescedWorking })
|
||||
await flushPtySideEffects()
|
||||
|
||||
const calls = onTitleChange.mock.calls.map((c) => c[0])
|
||||
expect(calls).toContain('⠋ π - cwd')
|
||||
|
||||
transport.disconnect()
|
||||
})
|
||||
})
|
||||
-40
@@ -36,27 +36,6 @@ function withQueue(
|
||||
}
|
||||
|
||||
describe('PTY side-effect queue reentrant delivery', () => {
|
||||
it('keeps empty-tail coalescing observable during the apply callback', () => {
|
||||
let queue: PtyOutputSideEffectQueue
|
||||
const observed: string[] = []
|
||||
withQueue(
|
||||
(created) => {
|
||||
queue = created
|
||||
queue.enqueue(emptyEffect())
|
||||
queue.flush()
|
||||
expect(observed).toEqual(['none', 'stale-probe'])
|
||||
expect(queue.isDrained()).toBe(true)
|
||||
},
|
||||
(effect) => {
|
||||
observed.push(effect.titleScanEffect)
|
||||
if (observed.length === 1) {
|
||||
queue.enqueue(emptyEffect('stale-probe'))
|
||||
}
|
||||
observed.push(effect.titleScanEffect)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('delivers the same effect requeued after clear without releasing its new slot', () => {
|
||||
let queue: PtyOutputSideEffectQueue
|
||||
const delivered: string[] = []
|
||||
@@ -101,23 +80,4 @@ describe('PTY side-effect queue reentrant delivery', () => {
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves thrown apply errors and their existing empty-tail coalescing', () => {
|
||||
const failure = new Error('apply failed')
|
||||
let applied = 0
|
||||
withQueue(
|
||||
(queue) => {
|
||||
queue.enqueue(emptyEffect())
|
||||
expect(() => queue.flush()).toThrow(failure)
|
||||
queue.enqueue(emptyEffect('stale-probe'))
|
||||
queue.flush()
|
||||
expect(applied).toBe(1)
|
||||
expect(queue.isDrained()).toBe(true)
|
||||
},
|
||||
() => {
|
||||
applied += 1
|
||||
throw failure
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { getDefaultSettings } from '../../../shared/constants'
|
||||
import { UI_LANGUAGE_SPANISH } from '../../../shared/ui-language'
|
||||
import { useAppStore } from '@/store'
|
||||
import { usePluginLanguagePackStore } from '@/store/plugins/localization/plugin-language-packs'
|
||||
import { i18n } from '@/i18n/i18n'
|
||||
import { FULL_DISK_ACCESS_SETTINGS_TARGET_ID } from '@/lib/settings-navigation-types'
|
||||
|
||||
import { useMacosTccPromptNotice } from './useMacosTccPromptNotice'
|
||||
|
||||
type NoticeCallback = (payload: { promptCount: number }, acknowledge: () => void) => void
|
||||
|
||||
const subscribeToMacosTccPromptNotice = vi.hoisted(() =>
|
||||
vi.fn<(_: unknown, onNotice: NoticeCallback) => () => void>(() => vi.fn())
|
||||
)
|
||||
const toastWarning = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('./macos-tcc-prompt-notice-subscription', () => ({
|
||||
dismissMacosTccPromptNotice: vi.fn(),
|
||||
subscribeToMacosTccPromptNotice
|
||||
}))
|
||||
vi.mock('sonner', () => ({ toast: { warning: toastWarning } }))
|
||||
|
||||
const initialAppState = useAppStore.getInitialState()
|
||||
const initialPluginLanguagePackState = usePluginLanguagePackStore.getInitialState()
|
||||
let root: Root | null = null
|
||||
|
||||
function NoticeProbe(): null {
|
||||
useMacosTccPromptNotice()
|
||||
return null
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
useAppStore.setState(initialAppState, true)
|
||||
usePluginLanguagePackStore.setState(initialPluginLanguagePackState, true)
|
||||
subscribeToMacosTccPromptNotice.mockClear()
|
||||
toastWarning.mockClear()
|
||||
await i18n.changeLanguage('en')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => root?.unmount())
|
||||
root = null
|
||||
}
|
||||
useAppStore.setState(initialAppState, true)
|
||||
usePluginLanguagePackStore.setState(initialPluginLanguagePackState, true)
|
||||
})
|
||||
|
||||
it('waits for the persisted locale catalog before consuming the one-time notice', async () => {
|
||||
const container = document.createElement('div')
|
||||
root = createRoot(container)
|
||||
await act(async () => {
|
||||
root?.render(createElement(I18nextProvider, { i18n }, createElement(NoticeProbe)))
|
||||
})
|
||||
expect(subscribeToMacosTccPromptNotice).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
useAppStore.setState({
|
||||
settings: { ...getDefaultSettings('/tmp'), uiLanguage: UI_LANGUAGE_SPANISH }
|
||||
})
|
||||
})
|
||||
expect(subscribeToMacosTccPromptNotice).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
await i18n.changeLanguage('es')
|
||||
})
|
||||
expect(subscribeToMacosTccPromptNotice).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('acknowledges when opening Settings closes the notice', async () => {
|
||||
useAppStore.setState({
|
||||
settings: { ...getDefaultSettings('/tmp'), uiLanguage: 'en' }
|
||||
})
|
||||
const container = document.createElement('div')
|
||||
root = createRoot(container)
|
||||
await act(async () => {
|
||||
root?.render(createElement(I18nextProvider, { i18n }, createElement(NoticeProbe)))
|
||||
})
|
||||
const showNotice = subscribeToMacosTccPromptNotice.mock.calls[0]?.[1] as
|
||||
| NoticeCallback
|
||||
| undefined
|
||||
const acknowledge = vi.fn()
|
||||
|
||||
showNotice?.({ promptCount: 1 }, acknowledge)
|
||||
|
||||
const options = toastWarning.mock.calls[0]?.[1] as
|
||||
| { action?: { onClick: () => void } }
|
||||
| undefined
|
||||
options?.action?.onClick()
|
||||
expect(acknowledge).toHaveBeenCalledOnce()
|
||||
expect(useAppStore.getState().settingsNavigationTarget).toEqual({
|
||||
pane: 'developer-permissions',
|
||||
repoId: null,
|
||||
sectionId: FULL_DISK_ACCESS_SETTINGS_TARGET_ID
|
||||
})
|
||||
})
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { defaultScopeHost } from '@/lib/default-creation-host'
|
||||
|
||||
// Why: these cases model a switch made on the focused host, as the status bar does.
|
||||
const focusedOwner = () => defaultScopeHost(useAppStore.getState().settings)
|
||||
import { markLiveCodexSessionsForRestart } from './codex-session-restart'
|
||||
|
||||
const ACCOUNT_A = 'account-a@example.com'
|
||||
const ACCOUNT_B = 'account-b@example.com'
|
||||
const ACCOUNT_C = 'account-c@example.com'
|
||||
|
||||
/** Main's per-PTY record decides a recorded pane's notice, and the switch decides it when main cannot. */
|
||||
describe('Codex account switch recheck against main', () => {
|
||||
const listStalePanes = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
listStalePanes.mockReset().mockResolvedValue([])
|
||||
useAppStore.setState({
|
||||
settings: null,
|
||||
tabsByWorktree: {
|
||||
wt1: [
|
||||
{
|
||||
id: 'tab-1',
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'wt1',
|
||||
title: 'orca-1',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-1'] },
|
||||
pendingPaneAccountRestarts: {},
|
||||
codexRestartNoticeByPtyId: {}
|
||||
})
|
||||
vi.stubGlobal('window', {
|
||||
api: {
|
||||
pty: {
|
||||
inspectProcess: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ foregroundProcess: 'codex', hasChildProcesses: false }),
|
||||
confirmForegroundProcess: vi.fn().mockResolvedValue(null)
|
||||
},
|
||||
codexAccounts: {
|
||||
listRecordedPaneLanes: vi.fn().mockResolvedValue({ 'pty-1': 'host' }),
|
||||
listStalePanes
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('clears an open notice and its queued restart once main reports the pane current', async () => {
|
||||
useAppStore.getState().markCodexRestartNotices([
|
||||
{
|
||||
ptyId: 'pty-1',
|
||||
previousAccountLabel: ACCOUNT_A,
|
||||
nextAccountLabel: ACCOUNT_B,
|
||||
previousAccountId: 'account-a',
|
||||
nextAccountId: 'account-b'
|
||||
}
|
||||
])
|
||||
useAppStore.getState().queuePaneAccountRestarts(['pty-1'], 'codex')
|
||||
|
||||
await markLiveCodexSessionsForRestart({
|
||||
owner: focusedOwner(),
|
||||
previousAccountLabel: ACCOUNT_B,
|
||||
nextAccountLabel: ACCOUNT_C,
|
||||
previousAccountId: 'account-b',
|
||||
nextAccountId: 'account-c'
|
||||
})
|
||||
|
||||
expect(listStalePanes).toHaveBeenCalledWith({ ptyIds: ['pty-1'] })
|
||||
expect(useAppStore.getState().codexRestartNoticeByPtyId).toEqual({})
|
||||
expect(useAppStore.getState().pendingPaneAccountRestarts).toEqual({})
|
||||
})
|
||||
|
||||
it('falls back to the switch it was given when main cannot answer', async () => {
|
||||
listStalePanes.mockRejectedValue(new Error('ipc failed'))
|
||||
|
||||
await markLiveCodexSessionsForRestart({
|
||||
owner: focusedOwner(),
|
||||
previousAccountLabel: ACCOUNT_A,
|
||||
nextAccountLabel: ACCOUNT_B,
|
||||
previousAccountId: 'account-a',
|
||||
nextAccountId: 'account-b'
|
||||
})
|
||||
|
||||
expect(useAppStore.getState().codexRestartNoticeByPtyId['pty-1']).toEqual({
|
||||
previousAccountLabel: ACCOUNT_A,
|
||||
nextAccountLabel: ACCOUNT_B,
|
||||
previousAccountId: 'account-a',
|
||||
nextAccountId: 'account-b'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,84 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { pluginMonacoTokenRules } from '../plugin-monaco-token-rules'
|
||||
import { loadBuiltInMarkdownRules, withBuiltInMarkdownRules } from './markdown-monaco-theme-rules'
|
||||
|
||||
async function markdownRules(
|
||||
base: 'light' | 'dark',
|
||||
colors: Record<string, string>,
|
||||
tokenColors: Parameters<typeof pluginMonacoTokenRules>[0]
|
||||
) {
|
||||
const data = withBuiltInMarkdownRules(
|
||||
{
|
||||
base: base === 'dark' ? 'vs-dark' : 'vs',
|
||||
inherit: true,
|
||||
rules: pluginMonacoTokenRules(tokenColors, (value) => value),
|
||||
colors
|
||||
},
|
||||
await loadBuiltInMarkdownRules(base)
|
||||
)
|
||||
// Monaco applies rules in order, so the last one per token wins each setting.
|
||||
const byToken = new Map<string, { foreground?: string; fontStyle?: string }>()
|
||||
for (const { token, ...style } of data.rules) {
|
||||
byToken.set(token, { ...byToken.get(token), ...style })
|
||||
}
|
||||
return byToken
|
||||
}
|
||||
|
||||
describe('withBuiltInMarkdownRules', () => {
|
||||
it("keeps the theme's markdown colors and fills the rest from Dark+", async () => {
|
||||
const rules = await markdownRules(
|
||||
'dark',
|
||||
{ 'editor.background': '#0b0e14', 'editor.foreground': '#bfbdb6' },
|
||||
[
|
||||
{ scope: 'markup.heading', settings: { foreground: '#aad94c', fontStyle: 'bold' } },
|
||||
{ scope: 'entity.name', settings: { foreground: '#59c2ff' } },
|
||||
{ scope: 'markup.quote', settings: { foreground: '#95e6cb', fontStyle: 'italic' } }
|
||||
]
|
||||
)
|
||||
|
||||
expect(rules.get('md.markup.heading')).toEqual({ foreground: '#aad94c', fontStyle: 'bold' })
|
||||
// Heading text takes the theme's `entity.name` color and its heading's bold.
|
||||
expect(rules.get('md.entity.name.section.markdown')).toEqual({
|
||||
foreground: '#59c2ff',
|
||||
fontStyle: 'bold'
|
||||
})
|
||||
expect(rules.get('md.markup.quote')).toEqual({ foreground: '#95e6cb', fontStyle: 'italic' })
|
||||
expect(rules.get('md.markup.inline.raw')).toEqual({ foreground: '#ce9178' })
|
||||
expect(rules.get('md.meta.embedded')).toEqual({ foreground: '#bfbdb6' })
|
||||
})
|
||||
|
||||
it('colors heading text by a markup.heading descendant selector over plain entity.name', async () => {
|
||||
const rules = await markdownRules(
|
||||
'light',
|
||||
{ 'editor.background': '#ffffff', 'editor.foreground': '#1f2328' },
|
||||
[
|
||||
{ scope: 'entity.name', settings: { foreground: '#6f42c1' } },
|
||||
{
|
||||
scope: ['markup.heading', 'markup.heading entity.name'],
|
||||
settings: { foreground: '#005cc5', fontStyle: 'bold' }
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
expect(rules.get('md.entity.name.section.markdown')).toEqual({
|
||||
foreground: '#005cc5',
|
||||
fontStyle: 'bold'
|
||||
})
|
||||
})
|
||||
|
||||
it("paints Light+ plain text in the theme's foreground and drops unreadable fallbacks", async () => {
|
||||
const rules = await markdownRules(
|
||||
'light',
|
||||
{ 'editor.background': '#d2d2d2', 'editor.foreground': '#442244' },
|
||||
[]
|
||||
)
|
||||
|
||||
expect(rules.get('md.meta.embedded')).toEqual({ foreground: '#442244' })
|
||||
// Light+ regexp groups (#d16969) are 2.3:1 on this background.
|
||||
expect(rules.get('md.punctuation.definition.group.regexp')).toBeUndefined()
|
||||
expect(rules.get('md.entity.name.section.markdown')).toEqual({
|
||||
foreground: '#800000',
|
||||
fontStyle: 'bold'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,84 +0,0 @@
|
||||
// Resolve seeding by the create’s host when repo/path has a twin; desktop must not duplicate the paired server’s default tabs (ledger L277).
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type * as AgentStatusModule from '@/lib/agent-status'
|
||||
import type * as WebRuntimeSessionModule from '@/runtime/web-runtime-session-environment'
|
||||
import type { Repo } from '../../../shared/repo-types'
|
||||
import type { ExecutionHostId } from '../../../shared/execution-host'
|
||||
import { createTestStore } from '@/store/testing/app-store-test-fixture'
|
||||
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
|
||||
import { ensureWorktreeHasInitialTerminal } from '@/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding'
|
||||
import { applyCreatedWorktree } from '@/store/slices/worktrees/create/created-worktree-state-merge'
|
||||
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
|
||||
(
|
||||
await import('@/runtime/layout-apply-test-transport.test-fixture')
|
||||
).runtimeRpcClientWithLayoutApply(await importOriginal())
|
||||
)
|
||||
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
|
||||
vi.mock('@/lib/agent-status', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof AgentStatusModule>()
|
||||
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
|
||||
})
|
||||
vi.mock('@/runtime/web-runtime-session-environment', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof WebRuntimeSessionModule>()),
|
||||
// The paired server's session is up.
|
||||
isWebRuntimeSessionActive: (environmentId: string | null | undefined) => environmentId === 'env-1'
|
||||
}))
|
||||
|
||||
const SERVER: ExecutionHostId = 'runtime:env-1'
|
||||
const REPO_ID = 'repoP'
|
||||
const PATH = '/srv/proj/new-ws'
|
||||
const WT = `${REPO_ID}::${PATH}`
|
||||
const defaultTabs = {
|
||||
tabs: [
|
||||
{ title: 'A', command: 'echo a' },
|
||||
{ title: 'B', command: 'echo b' }
|
||||
],
|
||||
runCommands: true
|
||||
}
|
||||
const issueCommand = { command: 'echo issue' }
|
||||
const setup = { runnerScriptPath: `${PATH}/.orca/setup.sh`, envVars: {} }
|
||||
|
||||
function repo(executionHostId?: ExecutionHostId): Repo {
|
||||
return {
|
||||
id: REPO_ID,
|
||||
path: '/srv/proj',
|
||||
displayName: 'p',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
...(executionHostId ? { executionHostId } : {})
|
||||
}
|
||||
}
|
||||
|
||||
/** The server's create result merged the real way, then the background create's seeding. */
|
||||
function createOnServer(opts: { twin: boolean; passHost: boolean }) {
|
||||
const store = createTestStore()
|
||||
store.setState({
|
||||
repos: opts.twin ? [repo(), repo(SERVER)] : [repo(SERVER)],
|
||||
worktreesByRepo: opts.twin
|
||||
? { [REPO_ID]: [makeWorktree({ id: WT, repoId: REPO_ID, path: PATH, hostId: 'local' })] }
|
||||
: {}
|
||||
})
|
||||
applyCreatedWorktree(
|
||||
store.setState,
|
||||
REPO_ID,
|
||||
{ worktree: makeWorktree({ id: WT, repoId: REPO_ID, path: PATH }), defaultTabs },
|
||||
SERVER
|
||||
)
|
||||
ensureWorktreeHasInitialTerminal(
|
||||
store.getState(),
|
||||
WT,
|
||||
undefined,
|
||||
setup,
|
||||
issueCommand,
|
||||
defaultTabs,
|
||||
{ activateCreatedTabs: false, ...(opts.passHost ? { executionHostId: SERVER } : {}) }
|
||||
)
|
||||
return store.getState().tabsByWorktree[WT] ?? []
|
||||
}
|
||||
|
||||
describe('seeding a workspace a paired server created', () => {
|
||||
it('lays out no tabs of its own for a twin, given the host the create went to', () => {
|
||||
expect(createOnServer({ twin: true, passHost: true })).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,93 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { PluginChangeEvent } from '../../../../../shared/plugins/events/plugin-change-event'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
it('loads the selected icon theme and drops it when its plugin goes away', async () => {
|
||||
const metadata = {
|
||||
id: 'plugin:samples.icons/minimal',
|
||||
pluginKey: 'samples.icons',
|
||||
label: 'Minimal'
|
||||
}
|
||||
const theme = {
|
||||
...metadata,
|
||||
svgs: [
|
||||
'<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0h1" fill="currentColor"/></svg>',
|
||||
'<html/>'
|
||||
],
|
||||
icons: { folder: 0, file: 1 },
|
||||
fileNames: {},
|
||||
fileExtensions: {},
|
||||
folderNames: { src: 0, broken: 1 },
|
||||
folderNamesExpanded: { src: 0, broken: 1 }
|
||||
}
|
||||
let listed = [metadata]
|
||||
const listeners: ((event: PluginChangeEvent) => void)[] = []
|
||||
const loadIconTheme = vi.fn(async () => theme)
|
||||
vi.stubGlobal('api', {
|
||||
plugins: {
|
||||
listIconThemes: async () => listed,
|
||||
loadIconTheme,
|
||||
onChanged: (listener: (event: PluginChangeEvent) => void) => {
|
||||
listeners.push(listener)
|
||||
return () => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
const store = await import('./plugin-icon-themes')
|
||||
|
||||
renderHook(() => store.usePluginIconThemeActivation(metadata.id))
|
||||
// The unusable second SVG gets no rule, so its mappings fall back to the built-in icon.
|
||||
await waitFor(() =>
|
||||
expect(store.useActivePluginIconTheme.getState().theme).toEqual({
|
||||
icons: { folder: 0 },
|
||||
fileNames: {},
|
||||
fileExtensions: {},
|
||||
folderNames: { src: 0 },
|
||||
folderNamesExpanded: { src: 0 }
|
||||
})
|
||||
)
|
||||
|
||||
listed = []
|
||||
act(() => listeners.forEach((listener) => listener({ contentPacksChanged: true })))
|
||||
await waitFor(() => expect(store.useActivePluginIconTheme.getState().theme).toBeNull())
|
||||
expect(document.getElementById('orca-plugin-icon-theme')).toBeNull()
|
||||
})
|
||||
|
||||
it('drops the previous icons when the next selected theme fails to load', async () => {
|
||||
const working = { id: 'plugin:samples.icons/working', pluginKey: 'samples.icons', label: 'A' }
|
||||
const broken = { id: 'plugin:samples.icons/broken', pluginKey: 'samples.icons', label: 'B' }
|
||||
vi.stubGlobal('api', {
|
||||
plugins: {
|
||||
listIconThemes: async () => [working, broken],
|
||||
loadIconTheme: vi.fn(async (id: string) =>
|
||||
id === working.id
|
||||
? {
|
||||
...working,
|
||||
svgs: ['<svg xmlns="http://www.w3.org/2000/svg"><path fill="currentColor"/></svg>'],
|
||||
icons: { file: 0 },
|
||||
fileNames: {},
|
||||
fileExtensions: {},
|
||||
folderNames: {},
|
||||
folderNamesExpanded: {}
|
||||
}
|
||||
: null
|
||||
),
|
||||
onChanged: () => () => {}
|
||||
}
|
||||
})
|
||||
const store = await import('./plugin-icon-themes')
|
||||
|
||||
const { rerender } = renderHook(({ id }) => store.usePluginIconThemeActivation(id), {
|
||||
initialProps: { id: working.id }
|
||||
})
|
||||
await waitFor(() => expect(document.getElementById('orca-plugin-icon-theme')).not.toBeNull())
|
||||
rerender({ id: broken.id })
|
||||
await waitFor(() => expect(document.getElementById('orca-plugin-icon-theme')).toBeNull())
|
||||
expect(store.useActivePluginIconTheme.getState().theme).toBeNull()
|
||||
})
|
||||
@@ -1,113 +0,0 @@
|
||||
import type { StoreApi } from 'zustand/vanilla'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { AppState } from '../../../types'
|
||||
import type { BrowserTab } from '../../../../../../shared/browser-workspace-types'
|
||||
|
||||
import '../../../../i18n/i18n'
|
||||
import { createEditorTabsStore } from '../editor-slice-test-harness'
|
||||
import '@/runtime/layout-apply-test-transport.test-fixture'
|
||||
import '../../../../../../shared/layout-owner-switch'
|
||||
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
|
||||
(
|
||||
await import('@/runtime/layout-apply-test-transport.test-fixture')
|
||||
).runtimeRpcClientWithLayoutApply(await importOriginal())
|
||||
)
|
||||
|
||||
function createEditorStore(overrides?: Partial<AppState>): StoreApi<AppState> {
|
||||
const store = createEditorTabsStore()
|
||||
store.setState(overrides ?? {})
|
||||
return store
|
||||
}
|
||||
|
||||
function makeBrowserTab(id: string): BrowserTab {
|
||||
return {
|
||||
id,
|
||||
worktreeId: 'wt-1',
|
||||
url: 'about:blank',
|
||||
title: 'Browser',
|
||||
loading: false,
|
||||
faviconUrl: null,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
loadError: null,
|
||||
createdAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
describe('New Markdown — tab bar ordering with openFile', () => {
|
||||
it('does not create duplicate entries in tab order', () => {
|
||||
const store = createEditorStore({
|
||||
tabBarOrderByWorktree: { 'wt-1': [] }
|
||||
})
|
||||
|
||||
store.getState().openFile({
|
||||
filePath: '/repo/untitled.md',
|
||||
relativePath: 'untitled.md',
|
||||
worktreeId: 'wt-1',
|
||||
language: 'markdown',
|
||||
isUntitled: true,
|
||||
mode: 'edit'
|
||||
})
|
||||
store.getState().openFile({
|
||||
filePath: '/repo/untitled.md',
|
||||
relativePath: 'untitled.md',
|
||||
worktreeId: 'wt-1',
|
||||
language: 'markdown',
|
||||
isUntitled: true,
|
||||
mode: 'edit'
|
||||
})
|
||||
|
||||
const order = store.getState().tabBarOrderByWorktree['wt-1']
|
||||
const occurrences = order.filter((id: string) => id === '/repo/untitled.md')
|
||||
expect(occurrences).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not disturb existing tab positions when adding a file', () => {
|
||||
const store = createEditorStore({
|
||||
tabsByWorktree: {
|
||||
'wt-1': [
|
||||
{
|
||||
id: 't1',
|
||||
ptyId: null,
|
||||
worktreeId: 'wt-1',
|
||||
title: 'Term 1',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 0
|
||||
},
|
||||
{
|
||||
id: 't2',
|
||||
ptyId: null,
|
||||
worktreeId: 'wt-1',
|
||||
title: 'Term 2',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 1,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
browserTabsByWorktree: {
|
||||
'wt-1': [makeBrowserTab('b1'), makeBrowserTab('b2')]
|
||||
},
|
||||
tabBarOrderByWorktree: { 'wt-1': ['t1', 'b1', 't2', 'b2'] }
|
||||
})
|
||||
|
||||
store.getState().openFile({
|
||||
filePath: '/repo/untitled.md',
|
||||
relativePath: 'untitled.md',
|
||||
worktreeId: 'wt-1',
|
||||
language: 'markdown',
|
||||
isUntitled: true,
|
||||
mode: 'edit'
|
||||
})
|
||||
|
||||
const order = store.getState().tabBarOrderByWorktree['wt-1']
|
||||
expect(order.indexOf('t1')).toBeLessThan(order.indexOf('b1'))
|
||||
expect(order.indexOf('b1')).toBeLessThan(order.indexOf('t2'))
|
||||
expect(order.indexOf('t2')).toBeLessThan(order.indexOf('b2'))
|
||||
expect(order.at(-1)).toBe('/repo/untitled.md')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user