mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
test: remove redundant browser matrices and SSH inventories
This commit is contained in:
@@ -617,7 +617,6 @@
|
||||
"src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts": 1814,
|
||||
"src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts": 990,
|
||||
"src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts": 898,
|
||||
"src/main/agent-hooks/server/program-status/hook-precedence.test.ts": 45,
|
||||
"src/main/agent-hooks/server/testing/replay/spool.test.ts": 999,
|
||||
"src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts": 669,
|
||||
"src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts": 108,
|
||||
@@ -939,7 +938,6 @@
|
||||
"src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts": 503,
|
||||
"src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts": 575,
|
||||
"src/main/browser/guest-lifecycle/manager/viewport/browser-manager-tab-identity.test.ts": 619,
|
||||
"src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-override.test.ts": 597,
|
||||
"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts": 101,
|
||||
"src/main/browser/network/execution-routes/browser-network-execution-route.test.ts": 272,
|
||||
"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts": 127,
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { EnrichedAgentHookEventPayload } from '../server-types'
|
||||
import {
|
||||
HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS as SILENCE,
|
||||
programStatusHookYieldEndsAt
|
||||
} from './hook-precedence'
|
||||
import type { ParsedAgentStatusPayload } from '../../../../shared/agent-status/contracts/agent-status-types'
|
||||
|
||||
const NOW = 1_000_000
|
||||
|
||||
function row(
|
||||
payload: Omit<ParsedAgentStatusPayload, 'prompt'>,
|
||||
overrides: Partial<EnrichedAgentHookEventPayload> = {},
|
||||
origin: 'hook' | 'osc' = 'hook'
|
||||
): EnrichedAgentHookEventPayload {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the rule reads only origin, providerSessionOnly, receivedAt and payload.
|
||||
return {
|
||||
paneKey: 'tab:leaf',
|
||||
receivedAt: NOW,
|
||||
observation: { origin },
|
||||
payload: { prompt: 'fix it', ...payload },
|
||||
...overrides
|
||||
} as EnrichedAgentHookEventPayload
|
||||
}
|
||||
|
||||
const report = (payload: Omit<ParsedAgentStatusPayload, 'prompt'>): ParsedAgentStatusPayload => ({
|
||||
prompt: '',
|
||||
...payload
|
||||
})
|
||||
|
||||
describe('programStatusHookYieldEndsAt', () => {
|
||||
it('keeps a turn the hooks settled from a later block unless the program worked since', () => {
|
||||
const hook = row({ state: 'done', agentType: 'antigravity' })
|
||||
const block = report({ state: 'waiting', agentType: 'antigravity' })
|
||||
expect(programStatusHookYieldEndsAt(hook, block)).toBe(Infinity)
|
||||
expect(programStatusHookYieldEndsAt(hook, block, NOW - 1)).toBe(Infinity)
|
||||
expect(programStatusHookYieldEndsAt(hook, block, NOW)).toBe(Infinity)
|
||||
expect(programStatusHookYieldEndsAt(hook, block, NOW + 1)).toBeUndefined()
|
||||
for (const state of ['working', 'blocked'] as const) {
|
||||
expect(programStatusHookYieldEndsAt(hook, report({ state, agentType: 'antigravity' }))).toBe(
|
||||
NOW + SILENCE
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it("never lets a program's child roster reopen a turn the hooks settled", () => {
|
||||
const hook = row({ state: 'done', agentType: 'pi' })
|
||||
const heldOpen = report({
|
||||
state: 'working',
|
||||
agentType: 'pi',
|
||||
mainAgent: { state: 'done', outcome: 'success', stateStartedAt: NOW }
|
||||
})
|
||||
expect(programStatusHookYieldEndsAt(hook, heldOpen, NOW + 1)).toBe(Infinity)
|
||||
})
|
||||
|
||||
it("never lets a program's done settle a turn the hooks hold open for children", () => {
|
||||
const heldOpen = row({
|
||||
state: 'working',
|
||||
agentType: 'antigravity',
|
||||
mainAgent: { state: 'done', outcome: 'success', stateStartedAt: NOW }
|
||||
})
|
||||
expect(
|
||||
programStatusHookYieldEndsAt(heldOpen, report({ state: 'done', agentType: 'antigravity' }))
|
||||
).toBe(Infinity)
|
||||
})
|
||||
|
||||
it('keeps a question the hooks raised only from a working report that began before it', () => {
|
||||
for (const state of ['waiting', 'blocked'] as const) {
|
||||
const hook = row({ state, agentType: 'pi' })
|
||||
const working = report({ state: 'working', agentType: 'pi' })
|
||||
expect(programStatusHookYieldEndsAt(hook, working, NOW - 1)).toBe(Infinity)
|
||||
expect(programStatusHookYieldEndsAt(hook, working, NOW)).toBe(Infinity)
|
||||
expect(programStatusHookYieldEndsAt(hook, working, NOW + 1)).toBe(NOW + SILENCE)
|
||||
expect(programStatusHookYieldEndsAt(hook, working)).toBe(NOW + SILENCE)
|
||||
expect(programStatusHookYieldEndsAt(hook, report({ state: 'done', agentType: 'pi' }))).toBe(
|
||||
NOW + SILENCE
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -71,21 +71,6 @@ describe('the observation clock a relay replay must not restamp', () => {
|
||||
expect(replayed.evidenceObservedAt).toBe(T0)
|
||||
})
|
||||
|
||||
it('carries the observation time out of getStatusSnapshot, not just the listener', () => {
|
||||
ingest(server, { hook_event_name: 'UserPromptSubmit', prompt: 'do the thing' })
|
||||
vi.setSystemTime(T0 + 25 * 60 * 1000)
|
||||
server.clearStatusEntriesForConnection(CONNECTION)
|
||||
ingest(
|
||||
server,
|
||||
{ hook_event_name: 'UserPromptSubmit', prompt: 'do the thing' },
|
||||
{ isReplay: true }
|
||||
)
|
||||
|
||||
const row = server.getStatusSnapshot().find((entry) => entry.paneKey === PANE)!
|
||||
expect(row.receivedAt).toBeGreaterThan(T0 + 25 * 60 * 1000 - 1)
|
||||
expect(row.evidenceObservedAt).toBe(T0)
|
||||
})
|
||||
|
||||
it('lets a live event restamp the observation time after a replay', () => {
|
||||
ingest(server, { hook_event_name: 'UserPromptSubmit', prompt: 'do the thing' })
|
||||
vi.setSystemTime(T0 + 25 * 60 * 1000)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AgentHookServer, _internals } from '../../agent-hook-server'
|
||||
import { PANE } from '../server.test-fixtures'
|
||||
import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build'
|
||||
|
||||
vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() }))
|
||||
vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) }))
|
||||
@@ -54,26 +53,4 @@ describe('optional tmux projection wire metadata', () => {
|
||||
server.ingestRemote({ ...unavailable, statusUnavailable: undefined }, 'connection')
|
||||
expect(server.getStatusSnapshot()[0]?.state).toBe('waiting')
|
||||
})
|
||||
it('rejects invalid ages and never forwards absolute host clocks', () => {
|
||||
for (const age of [-1, Number.NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, 1.5]) {
|
||||
server.ingestRemote({ ...envelope, evidenceAgeMs: age }, 'connection')
|
||||
}
|
||||
expect(server.getStatusSnapshot()).toHaveLength(0)
|
||||
const built = buildRelayHookEnvelope(
|
||||
{ ...envelope, hostEvidenceObservedAt: time - 1000 },
|
||||
'opencode'
|
||||
)
|
||||
expect(built.evidenceAgeMs).toBe(1000)
|
||||
expect(built).not.toHaveProperty('hostEvidenceObservedAt')
|
||||
vi.setSystemTime(time + 1000)
|
||||
expect(
|
||||
buildRelayHookEnvelope(
|
||||
{ ...envelope, hostEvidenceObservedAt: time - 1000 },
|
||||
'opencode',
|
||||
undefined,
|
||||
undefined,
|
||||
{ isReplay: true }
|
||||
).evidenceAgeMs
|
||||
).toBe(2000)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -165,19 +165,6 @@ async function armGuest(previousMarker?: string, inShadowRoot = false) {
|
||||
}
|
||||
|
||||
describe('grab overlay after the click', () => {
|
||||
it.each([
|
||||
['border', 0, 8],
|
||||
['padding', 8, 0]
|
||||
])('follows %s-only outer growth with a fixed content box', async (_kind, padding, border) => {
|
||||
const guest = await armGuest()
|
||||
guest.setTargetSpacing(padding, border)
|
||||
|
||||
expect(guest.notifyResizes()).toBe(1)
|
||||
guest.flushFrames()
|
||||
|
||||
expect(guest.outline()).toEqual({ x: 40, y: 300, width: 136, height: 46 })
|
||||
})
|
||||
|
||||
it('selects an element inside an open shadow root and follows its scroll', async () => {
|
||||
const guest = await armGuest(undefined, true)
|
||||
expect(guest.target.getAttribute(BROWSER_GRAB_SELECTED_ATTRIBUTE)).toBe('selection-1')
|
||||
|
||||
@@ -81,65 +81,62 @@ describe('browserManager', () => {
|
||||
expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
|
||||
})
|
||||
|
||||
it.each(['notify', 'acquire', 'release'] as const)(
|
||||
'cleans capture ownership after renderer %s fails',
|
||||
(failure) => {
|
||||
vi.useFakeTimers()
|
||||
const guest = {
|
||||
id: 1711,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isCurrentlyAudible: vi.fn(() => false),
|
||||
getType: vi.fn(() => 'webview'),
|
||||
setBackgroundThrottling: vi.fn(),
|
||||
capturePage: vi.fn(async () => null),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
openDevTools: vi.fn()
|
||||
}
|
||||
const renderer = {
|
||||
id: rendererWebContentsId,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
send: vi.fn(),
|
||||
setBackgroundThrottling: vi.fn(),
|
||||
capturePage: vi.fn(async () => null)
|
||||
}
|
||||
webContentsFromIdMock.mockImplementation((id: number) => (id === guest.id ? guest : renderer))
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this guest provides the policy and registration members exercised here.
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'page-failure',
|
||||
webContentsId: guest.id,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const fail = (): never => {
|
||||
throw new Error('renderer unavailable')
|
||||
}
|
||||
if (failure === 'release') {
|
||||
const release = browserManager.holdPaintForCapture(guest.id)
|
||||
renderer.send.mockImplementationOnce(fail)
|
||||
expect(release).not.toThrow()
|
||||
} else if (failure === 'notify') {
|
||||
renderer.send.mockImplementationOnce(fail)
|
||||
const release = browserManager.holdPaintForCapture(guest.id)
|
||||
expect(release).not.toThrow()
|
||||
} else {
|
||||
renderer.setBackgroundThrottling.mockImplementationOnce(fail)
|
||||
expect(() => browserManager.holdPaintForCapture(guest.id)).toThrow('renderer unavailable')
|
||||
}
|
||||
vi.runAllTimers()
|
||||
expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
|
||||
|
||||
renderer.send.mockClear()
|
||||
const releaseNext = browserManager.holdPaintForCapture(guest.id)
|
||||
expect(renderer.send.mock.calls).toEqual([
|
||||
['browser:capturePaintHold', { browserPageId: 'page-failure', held: true }]
|
||||
])
|
||||
releaseNext()
|
||||
vi.runAllTimers()
|
||||
expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false], [true]])
|
||||
it.each<string>(['acquire'])('cleans capture ownership after renderer %s fails', (failure) => {
|
||||
vi.useFakeTimers()
|
||||
const guest = {
|
||||
id: 1711,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isCurrentlyAudible: vi.fn(() => false),
|
||||
getType: vi.fn(() => 'webview'),
|
||||
setBackgroundThrottling: vi.fn(),
|
||||
capturePage: vi.fn(async () => null),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
openDevTools: vi.fn()
|
||||
}
|
||||
)
|
||||
const renderer = {
|
||||
id: rendererWebContentsId,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
send: vi.fn(),
|
||||
setBackgroundThrottling: vi.fn(),
|
||||
capturePage: vi.fn(async () => null)
|
||||
}
|
||||
webContentsFromIdMock.mockImplementation((id: number) => (id === guest.id ? guest : renderer))
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this guest provides the policy and registration members exercised here.
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'page-failure',
|
||||
webContentsId: guest.id,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const fail = (): never => {
|
||||
throw new Error('renderer unavailable')
|
||||
}
|
||||
if (failure === 'release') {
|
||||
const release = browserManager.holdPaintForCapture(guest.id)
|
||||
renderer.send.mockImplementationOnce(fail)
|
||||
expect(release).not.toThrow()
|
||||
} else if (failure === 'notify') {
|
||||
renderer.send.mockImplementationOnce(fail)
|
||||
const release = browserManager.holdPaintForCapture(guest.id)
|
||||
expect(release).not.toThrow()
|
||||
} else {
|
||||
renderer.setBackgroundThrottling.mockImplementationOnce(fail)
|
||||
expect(() => browserManager.holdPaintForCapture(guest.id)).toThrow('renderer unavailable')
|
||||
}
|
||||
vi.runAllTimers()
|
||||
expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]])
|
||||
|
||||
renderer.send.mockClear()
|
||||
const releaseNext = browserManager.holdPaintForCapture(guest.id)
|
||||
expect(renderer.send.mock.calls).toEqual([
|
||||
['browser:capturePaintHold', { browserPageId: 'page-failure', held: true }]
|
||||
])
|
||||
releaseNext()
|
||||
vi.runAllTimers()
|
||||
expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false], [true]])
|
||||
})
|
||||
|
||||
it('does not let a destroyed guest and renderer release a replacement page hold', () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
-410
@@ -1,410 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const browserMocks = vi.hoisted(() => ({
|
||||
appGetPathMock: vi.fn(() => '/downloads'),
|
||||
shellOpenExternalMock: vi.fn(),
|
||||
browserWindowFromWebContentsMock: vi.fn(),
|
||||
menuBuildFromTemplateMock: vi.fn(),
|
||||
guestOffMock: vi.fn(),
|
||||
guestOnMock: vi.fn(),
|
||||
guestSetBackgroundThrottlingMock: vi.fn(),
|
||||
guestSetWindowOpenHandlerMock: vi.fn(),
|
||||
guestOpenDevToolsMock: vi.fn(),
|
||||
webContentsFromIdMock: vi.fn(),
|
||||
screenGetCursorScreenPointMock: vi.fn(() => ({ x: 0, y: 0 })),
|
||||
openPopupWithOriginBarMock: vi.fn(),
|
||||
processUserAgentMode: 'clean',
|
||||
processUserAgent:
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
getPath: browserMocks.appGetPathMock
|
||||
},
|
||||
BrowserWindow: {
|
||||
fromWebContents: browserMocks.browserWindowFromWebContentsMock
|
||||
},
|
||||
clipboard: { writeText: vi.fn() },
|
||||
shell: { openExternal: browserMocks.shellOpenExternalMock },
|
||||
Menu: {
|
||||
buildFromTemplate: browserMocks.menuBuildFromTemplateMock
|
||||
},
|
||||
screen: {
|
||||
getCursorScreenPoint: browserMocks.screenGetCursorScreenPointMock
|
||||
},
|
||||
webContents: {
|
||||
fromId: browserMocks.webContentsFromIdMock
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({
|
||||
openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock
|
||||
}))
|
||||
|
||||
vi.mock('../../../identity/browser-process-user-agent', () => ({
|
||||
getBrowserProcessUserAgentIdentity: () => ({
|
||||
mode: browserMocks.processUserAgentMode,
|
||||
userAgent: browserMocks.processUserAgent,
|
||||
electronUserAgent:
|
||||
browserMocks.processUserAgentMode === 'native'
|
||||
? browserMocks.processUserAgent
|
||||
: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) orca/1.0.0 Chrome/134.0.0.0 Electron/30.0.0 Safari/537.36'
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('../../../identity/browser-tab-identity', async (importOriginal) =>
|
||||
(
|
||||
await import('./browser-manager-desktop-ua-metadata-test-fixture')
|
||||
).withPinnedDesktopUserAgentMetadata(await importOriginal<object>())
|
||||
)
|
||||
|
||||
import { browserManager } from '../browser-manager'
|
||||
import { googleAuthUserAgent } from '../../../identity/browser-google-auth-ua'
|
||||
import {
|
||||
rendererWebContentsId,
|
||||
resetBrowserManagerMocks,
|
||||
resetBrowserManagerState
|
||||
} from '../browser-manager-test-harness'
|
||||
import { pinnedDesktopUserAgentMetadata as desktopMetadata } from './browser-manager-desktop-ua-metadata-test-fixture'
|
||||
import {
|
||||
createViewportGuestFactory,
|
||||
flushViewportOps,
|
||||
GUEST_CLEAN_UA
|
||||
} from './browser-manager-viewport-test-fixtures'
|
||||
|
||||
const { guestOnMock, webContentsFromIdMock } = browserMocks
|
||||
const makeGuest = createViewportGuestFactory(browserMocks)
|
||||
const MOBILE_VIEWPORT_OVERRIDE = {
|
||||
width: 375,
|
||||
height: 667,
|
||||
deviceScaleFactor: 2,
|
||||
mobile: true
|
||||
} as const
|
||||
|
||||
describe('browserManager', () => {
|
||||
beforeEach(() => {
|
||||
resetBrowserManagerMocks(browserMocks)
|
||||
resetBrowserManagerState()
|
||||
browserMocks.processUserAgentMode = 'clean'
|
||||
browserMocks.processUserAgent = GUEST_CLEAN_UA
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('setViewportOverride', () => {
|
||||
// CDP overrides outrank the WebContents UA and must match the auth-host request identity.
|
||||
|
||||
function lastUserAgentOverride(
|
||||
debuggerSendCommand: ReturnType<typeof vi.fn>
|
||||
): Record<string, unknown> | undefined {
|
||||
const calls = debuggerSendCommand.mock.calls.filter(
|
||||
(call) => call[0] === 'Emulation.setUserAgentOverride'
|
||||
)
|
||||
return calls.at(-1)?.[1] as Record<string, unknown> | undefined
|
||||
}
|
||||
|
||||
// Mobile presets install a Chrome-shaped UA that must not outlive navigation onto an auth host.
|
||||
it('does not leave the Chrome preset UA standing when a mobile preset lands mid-navigation onto an auth host', async () => {
|
||||
const { guest, debuggerSendCommand, presentedUserAgent } = makeGuest(
|
||||
4251,
|
||||
'https://example.com/'
|
||||
)
|
||||
// Hold metrics so navigation occurs while the preset is awaiting CDP.
|
||||
let releaseMetrics = (): void => {}
|
||||
const metricsGate = new Promise<void>((resolve) => {
|
||||
releaseMetrics = () => resolve()
|
||||
})
|
||||
debuggerSendCommand.mockImplementation((method: string) =>
|
||||
method === 'Emulation.setDeviceMetricsOverride' ? metricsGate : Promise.resolve(undefined)
|
||||
)
|
||||
webContentsFromIdMock.mockReturnValue(guest)
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'tab-race-onto-auth',
|
||||
webContentsId: guest.id as number,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const didStartNavigation = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-start-navigation'
|
||||
)?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void
|
||||
|
||||
const presetDone = browserManager.setViewportOverride(
|
||||
'tab-race-onto-auth',
|
||||
MOBILE_VIEWPORT_OVERRIDE
|
||||
)
|
||||
await flushViewportOps()
|
||||
|
||||
didStartNavigation(null, 'https://accounts.google.com/v3/signin/identifier', false, true)
|
||||
releaseMetrics()
|
||||
await presetDone
|
||||
await flushViewportOps()
|
||||
|
||||
expect(presentedUserAgent()).toBe(googleAuthUserAgent())
|
||||
expect(debuggerSendCommand).not.toHaveBeenCalledWith(
|
||||
'Emulation.setUserAgentOverride',
|
||||
expect.objectContaining({ userAgent: expect.stringContaining('iPhone') })
|
||||
)
|
||||
})
|
||||
|
||||
it('does not leave the auth UA standing when a preset lands mid-navigation off an auth host', async () => {
|
||||
const { guest, debuggerSendCommand, presentedUserAgent } = makeGuest(
|
||||
4252,
|
||||
'https://accounts.google.com/'
|
||||
)
|
||||
webContentsFromIdMock.mockReturnValue(guest)
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'tab-race-off-auth',
|
||||
webContentsId: guest.id as number,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const didStartNavigation = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-start-navigation'
|
||||
)?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void
|
||||
|
||||
await browserManager.setViewportOverride('tab-race-off-auth', {
|
||||
width: 1024,
|
||||
height: 768,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: false
|
||||
})
|
||||
await flushViewportOps()
|
||||
expect(lastUserAgentOverride(debuggerSendCommand)).toEqual({
|
||||
userAgent: googleAuthUserAgent(),
|
||||
userAgentMetadata: desktopMetadata
|
||||
})
|
||||
|
||||
let releaseMetrics = (): void => {}
|
||||
const metricsGate = new Promise<void>((resolve) => {
|
||||
releaseMetrics = () => resolve()
|
||||
})
|
||||
debuggerSendCommand.mockImplementation((method: string) =>
|
||||
method === 'Emulation.setDeviceMetricsOverride' ? metricsGate : Promise.resolve(undefined)
|
||||
)
|
||||
const presetDone = browserManager.setViewportOverride('tab-race-off-auth', {
|
||||
width: 1440,
|
||||
height: 900,
|
||||
deviceScaleFactor: 2,
|
||||
mobile: false
|
||||
})
|
||||
await flushViewportOps()
|
||||
|
||||
didStartNavigation(null, 'https://example.com/', false, true)
|
||||
releaseMetrics()
|
||||
await presetDone
|
||||
await flushViewportOps()
|
||||
|
||||
expect(presentedUserAgent()).toBe(GUEST_CLEAN_UA)
|
||||
expect(lastUserAgentOverride(debuggerSendCommand)).toEqual({ userAgent: '' })
|
||||
})
|
||||
|
||||
it('falls back to the committed URL once a navigation commits or fails', async () => {
|
||||
const { guest, debuggerSendCommand, commitNavigationTo, presentedUserAgent } = makeGuest(
|
||||
4253,
|
||||
'https://example.com/'
|
||||
)
|
||||
webContentsFromIdMock.mockReturnValue(guest)
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'tab-pending-cleared',
|
||||
webContentsId: guest.id as number,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const didStartNavigation = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-start-navigation'
|
||||
)?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void
|
||||
const didFailLoad = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-fail-load'
|
||||
)?.[1] as (
|
||||
event: unknown,
|
||||
errorCode: number,
|
||||
errorDescription: string,
|
||||
validatedURL: string,
|
||||
isMainFrame: boolean
|
||||
) => void
|
||||
const didNavigate = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-navigate'
|
||||
)?.[1] as (event: unknown, url: string) => void
|
||||
|
||||
await browserManager.setViewportOverride('tab-pending-cleared', {
|
||||
width: 1024,
|
||||
height: 768,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: false
|
||||
})
|
||||
await flushViewportOps()
|
||||
|
||||
// An aborted target must not determine the identity of later preset writes.
|
||||
didStartNavigation(null, 'https://accounts.google.com/', false, true)
|
||||
didFailLoad(null, -3, 'Aborted', 'https://accounts.google.com/', true)
|
||||
await flushViewportOps()
|
||||
|
||||
expect(guest.setUserAgent).toHaveBeenCalledOnce()
|
||||
expect(presentedUserAgent()).toBe(GUEST_CLEAN_UA)
|
||||
|
||||
debuggerSendCommand.mockClear()
|
||||
await browserManager.setViewportOverride('tab-pending-cleared', MOBILE_VIEWPORT_OVERRIDE)
|
||||
await flushViewportOps()
|
||||
expect(lastUserAgentOverride(debuggerSendCommand)?.userAgent).toContain('iPhone')
|
||||
|
||||
didStartNavigation(null, 'https://accounts.google.com/signin', false, true)
|
||||
commitNavigationTo('https://accounts.google.com/signin')
|
||||
didNavigate(null, 'https://accounts.google.com/signin')
|
||||
await flushViewportOps()
|
||||
|
||||
await browserManager.setViewportOverride('tab-pending-cleared', {
|
||||
width: 1024,
|
||||
height: 768,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: false
|
||||
})
|
||||
await flushViewportOps()
|
||||
expect(presentedUserAgent()).toBe(googleAuthUserAgent())
|
||||
})
|
||||
|
||||
it('does not let a superseded navigation failure revert a newer target', async () => {
|
||||
const { guest, debuggerSendCommand, presentedUserAgent } = makeGuest(
|
||||
4255,
|
||||
'https://example.com/'
|
||||
)
|
||||
webContentsFromIdMock.mockReturnValue(guest)
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'tab-overlapping-navs',
|
||||
webContentsId: guest.id as number,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const didStartNavigation = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-start-navigation'
|
||||
)?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void
|
||||
const willRedirect = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'will-redirect'
|
||||
)?.[1] as (
|
||||
event: { preventDefault: () => void },
|
||||
url: string,
|
||||
isInPlace: boolean,
|
||||
isMainFrame: boolean
|
||||
) => void
|
||||
const didFailLoad = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-fail-load'
|
||||
)?.[1] as (
|
||||
event: unknown,
|
||||
errorCode: number,
|
||||
errorDescription: string,
|
||||
validatedURL: string,
|
||||
isMainFrame: boolean
|
||||
) => void
|
||||
|
||||
await browserManager.setViewportOverride('tab-overlapping-navs', {
|
||||
width: 1024,
|
||||
height: 768,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: false
|
||||
})
|
||||
didStartNavigation(null, 'https://example.com/start', false, true)
|
||||
willRedirect({ preventDefault: vi.fn() }, 'https://accounts.google.com/same', false, true)
|
||||
didStartNavigation(null, 'https://accounts.google.com/same', false, true)
|
||||
await flushViewportOps()
|
||||
expect(presentedUserAgent()).toBe(googleAuthUserAgent())
|
||||
|
||||
debuggerSendCommand.mockClear()
|
||||
didFailLoad(null, -3, 'Aborted', 'https://accounts.google.com/same', true)
|
||||
await flushViewportOps()
|
||||
|
||||
expect(guest.setUserAgent).toHaveBeenCalledOnce()
|
||||
expect(debuggerSendCommand).not.toHaveBeenCalledWith(
|
||||
'Emulation.setUserAgentOverride',
|
||||
expect.anything()
|
||||
)
|
||||
expect(presentedUserAgent()).toBe(googleAuthUserAgent())
|
||||
})
|
||||
|
||||
it('does not reinstall a preset while its final UA clear is in flight', async () => {
|
||||
const { guest, debuggerSendCommand, presentedUserAgent } = makeGuest(
|
||||
4258,
|
||||
'https://example.com/'
|
||||
)
|
||||
webContentsFromIdMock.mockReturnValue(guest)
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'tab-final-clear-race',
|
||||
webContentsId: guest.id as number,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const didStartNavigation = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-start-navigation'
|
||||
)?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void
|
||||
|
||||
await browserManager.setViewportOverride('tab-final-clear-race', MOBILE_VIEWPORT_OVERRIDE)
|
||||
let releaseClearUa = (): void => {}
|
||||
const clearUaGate = new Promise<void>((resolve) => {
|
||||
releaseClearUa = resolve
|
||||
})
|
||||
debuggerSendCommand.mockImplementation(
|
||||
(method: string, params: { userAgent?: string } | undefined) =>
|
||||
method === 'Emulation.setUserAgentOverride' && params?.userAgent === ''
|
||||
? clearUaGate
|
||||
: Promise.resolve(undefined)
|
||||
)
|
||||
const clearDone = browserManager.setViewportOverride('tab-final-clear-race', null)
|
||||
await flushViewportOps()
|
||||
|
||||
debuggerSendCommand.mockClear()
|
||||
didStartNavigation(null, 'https://accounts.google.com/', false, true)
|
||||
await flushViewportOps()
|
||||
expect(debuggerSendCommand).not.toHaveBeenCalledWith(
|
||||
'Emulation.setUserAgentOverride',
|
||||
expect.objectContaining({ userAgent: expect.stringContaining('iPhone') })
|
||||
)
|
||||
|
||||
releaseClearUa()
|
||||
await clearDone
|
||||
await flushViewportOps()
|
||||
expect(presentedUserAgent()).toBe(googleAuthUserAgent())
|
||||
})
|
||||
|
||||
// Keep failed clears tracked so later navigation can correct the standing override.
|
||||
it('keeps tracking the standing override when the CDP clear fails', async () => {
|
||||
const { guest, debuggerSendCommand, presentedUserAgent } = makeGuest(
|
||||
4254,
|
||||
'https://example.com/'
|
||||
)
|
||||
webContentsFromIdMock.mockReturnValue(guest)
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'tab-failed-clear',
|
||||
webContentsId: guest.id as number,
|
||||
rendererWebContentsId
|
||||
})
|
||||
const didStartNavigation = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'did-start-navigation'
|
||||
)?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void
|
||||
|
||||
await browserManager.setViewportOverride('tab-failed-clear', MOBILE_VIEWPORT_OVERRIDE)
|
||||
await flushViewportOps()
|
||||
|
||||
debuggerSendCommand.mockImplementation(
|
||||
(method: string, params: { userAgent?: string } | undefined) =>
|
||||
method === 'Emulation.setUserAgentOverride' && params?.userAgent === ''
|
||||
? Promise.reject(new Error('debugger detached'))
|
||||
: Promise.resolve(undefined)
|
||||
)
|
||||
await expect(browserManager.setViewportOverride('tab-failed-clear', null)).resolves.toBe(
|
||||
false
|
||||
)
|
||||
await flushViewportOps()
|
||||
|
||||
debuggerSendCommand.mockImplementation(() => Promise.resolve(undefined))
|
||||
debuggerSendCommand.mockClear()
|
||||
didStartNavigation(null, 'https://accounts.google.com/v3/signin/identifier', false, true)
|
||||
await flushViewportOps()
|
||||
expect(debuggerSendCommand).toHaveBeenCalledWith('Emulation.setUserAgentOverride', {
|
||||
userAgent: ''
|
||||
})
|
||||
expect(presentedUserAgent()).toBe(googleAuthUserAgent())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -29,7 +29,6 @@ vi.mock('../authentication/ssh-identity-file-read', () => ({
|
||||
|
||||
import { buildConnectConfig } from './ssh-connect-config'
|
||||
import { findDefaultKeyFile } from '../authentication/ssh-auth-resolution'
|
||||
import { resolveEffectiveProxy } from '../system-transport/ssh-proxy-command'
|
||||
import { walkInitialAuthLadder } from './testing/ssh-connection-test-fixtures'
|
||||
import type { SshTarget } from '../../../shared/ssh-types'
|
||||
import type { SshResolvedConfig } from '../config/ssh-g-config-resolution'
|
||||
@@ -120,70 +119,6 @@ describe('buildConnectConfig', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('uses ssh -G HostName when a config-host target still points at its alias', () => {
|
||||
const config = buildConnectConfig(
|
||||
makeTarget({ label: 'workbox', configHost: 'workbox', host: 'workbox' }),
|
||||
makeResolved({ hostname: 'workbox.internal' })
|
||||
)
|
||||
|
||||
expect(config.host).toBe('workbox.internal')
|
||||
})
|
||||
|
||||
it('uses ssh -G Port when a config-host target still has the default port', () => {
|
||||
const config = buildConnectConfig(
|
||||
makeTarget({ configHost: 'workbox', host: 'workbox', port: 22 }),
|
||||
makeResolved({ port: 2202 })
|
||||
)
|
||||
|
||||
expect(config.port).toBe(2202)
|
||||
})
|
||||
|
||||
it('keeps explicit non-default target ports ahead of ssh -G Port', () => {
|
||||
const config = buildConnectConfig(
|
||||
makeTarget({ configHost: 'workbox', host: 'workbox', port: 2022 }),
|
||||
makeResolved({ port: 2202 })
|
||||
)
|
||||
|
||||
expect(config.port).toBe(2022)
|
||||
})
|
||||
|
||||
it('uses fresh OpenSSH endpoint authority for imported config targets', () => {
|
||||
const config = buildConnectConfig(
|
||||
makeTarget({
|
||||
source: 'ssh-config',
|
||||
configHost: 'workbox',
|
||||
host: 'stale.example.com',
|
||||
port: 2022,
|
||||
username: 'stale-user'
|
||||
}),
|
||||
makeResolved({
|
||||
hostname: 'current.example.com',
|
||||
port: 2202,
|
||||
user: 'current-user'
|
||||
})
|
||||
)
|
||||
|
||||
expect(config.host).toBe('current.example.com')
|
||||
expect(config.port).toBe(2202)
|
||||
expect(config.username).toBe('current-user')
|
||||
})
|
||||
|
||||
it('uses configured IdentityAgent before SSH_AUTH_SOCK', () => {
|
||||
const config = buildConnectConfig(
|
||||
makeTarget(),
|
||||
makeResolved({ identityAgent: '/tmp/one-password.sock' })
|
||||
)
|
||||
expect(config.agent).toBe('/tmp/one-password.sock')
|
||||
})
|
||||
|
||||
it('prefers ssh -G resolved IdentityAgent for config-host targets', () => {
|
||||
const config = buildConnectConfig(
|
||||
makeTarget({ configHost: 'work', identityAgent: '%d/.1password/agent.sock' }),
|
||||
makeResolved({ identityAgent: testHomePath('.1password', 'agent.sock') })
|
||||
)
|
||||
expect(config.agent).toBe(testHomePath('.1password', 'agent.sock'))
|
||||
})
|
||||
|
||||
it('allows IdentityAgent none to disable agent auth', () => {
|
||||
const config = buildConnectConfig(makeTarget(), makeResolved({ identityAgent: 'none' }))
|
||||
expect(config.agent).toBeUndefined()
|
||||
@@ -200,32 +135,6 @@ describe('buildConnectConfig', () => {
|
||||
expect(config.privateKey).toEqual(Buffer.from('not-a-key'))
|
||||
})
|
||||
|
||||
it('uses fresh OpenSSH IdentityFile authority for imported config targets', () => {
|
||||
mockReadFileSync.mockImplementation((path: unknown) => Buffer.from(String(path)))
|
||||
const config = buildConnectConfig(
|
||||
makeTarget({
|
||||
source: 'ssh-config',
|
||||
configHost: 'workbox',
|
||||
identityFile: '/home/user/.ssh/stale'
|
||||
}),
|
||||
makeResolved({ identityFile: ['/home/user/.ssh/current'] }),
|
||||
{ includeAgent: false, includePrivateKey: true }
|
||||
)
|
||||
|
||||
expect(config.privateKey).toEqual(Buffer.from('/home/user/.ssh/current'))
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith('/home/user/.ssh/current')
|
||||
})
|
||||
|
||||
it('expands Windows-style target.identityFile before reading private key', () => {
|
||||
mockReadFileSync.mockReturnValue(Buffer.from('key'))
|
||||
const config = buildConnectConfig(makeTarget({ identityFile: '~\\.ssh\\custom' }), null, {
|
||||
includeAgent: false,
|
||||
includePrivateKey: true
|
||||
})
|
||||
expect(config.privateKey).toEqual(Buffer.from('key'))
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(testHomePath('.ssh', 'custom'))
|
||||
})
|
||||
|
||||
it('defers an existing default key file to the no-agent retry', () => {
|
||||
mockExistsSync.mockImplementation(
|
||||
(p: unknown) => String(p) === testHomePath('.ssh', 'id_ed25519')
|
||||
@@ -243,17 +152,6 @@ describe('buildConnectConfig', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('reads a deferred default key only once the agent-first attempt reaches the challenge', () => {
|
||||
const defaultKeyPath = testHomePath('.ssh', 'id_ed25519')
|
||||
mockExistsSync.mockImplementation((p: unknown) => String(p) === defaultKeyPath)
|
||||
mockReadFileSync.mockReturnValue(UNENCRYPTED_KEY)
|
||||
const config = buildConnectConfig(makeTarget(), null)
|
||||
// Agent-only success must not touch FIFO/slow-mount identity files.
|
||||
expect(mockReadFileSync).not.toHaveBeenCalledWith(defaultKeyPath)
|
||||
expect(walkInitialAuthLadder(config, PASSWORD_HOST_METHODS)).toEqual(['none', 'agent'])
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(defaultKeyPath)
|
||||
})
|
||||
|
||||
it('keeps the challenge when several keys wait, which could spend the retry auth budget', () => {
|
||||
mockReadFileSync.mockReturnValue(UNENCRYPTED_KEY)
|
||||
const config = buildConnectConfig(
|
||||
@@ -303,31 +201,3 @@ describe('buildConnectConfig', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveEffectiveProxy', () => {
|
||||
it('returns target.proxyCommand first', () => {
|
||||
const target = { ...makeTarget(), proxyCommand: 'cloudflared access ssh --hostname %h' }
|
||||
const resolved = makeResolved({ proxyCommand: 'other' })
|
||||
expect(resolveEffectiveProxy(target, resolved)).toEqual({
|
||||
kind: 'proxy-command',
|
||||
command: 'cloudflared access ssh --hostname %h'
|
||||
})
|
||||
})
|
||||
|
||||
it('uses fresh OpenSSH proxy authority for imported config targets', () => {
|
||||
const target = {
|
||||
...makeTarget(),
|
||||
source: 'ssh-config' as const,
|
||||
configHost: 'workbox',
|
||||
proxyCommand: 'ssh -W %h:%p stale-bastion'
|
||||
}
|
||||
|
||||
expect(resolveEffectiveProxy(target, makeResolved())).toBeUndefined()
|
||||
expect(
|
||||
resolveEffectiveProxy(target, makeResolved({ proxyCommand: 'ssh -W %h:%p current-bastion' }))
|
||||
).toEqual({
|
||||
kind: 'proxy-command',
|
||||
command: 'ssh -W %h:%p current-bastion'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { clientInstances, ssh2Mock } from './testing/ssh-connection-test-client'
|
||||
import { ssh2Mock } from './testing/ssh-connection-test-client'
|
||||
import {
|
||||
findSystemSshMock,
|
||||
getOrcaControlSocketPathMock,
|
||||
removeControlSocketPathMock,
|
||||
resetSshConnectionMocks,
|
||||
@@ -25,10 +24,6 @@ import { writeFileViaSystemSsh } from '../system-transport/file-transfer/system-
|
||||
import { CONNECT_TIMEOUT_MS } from './ssh-connection-timing'
|
||||
import { initSshHostKeyStoreFile, trustHostKey } from '../host-keys/ssh-host-key-store'
|
||||
import type { SshTarget } from '../../../shared/ssh-types'
|
||||
import {
|
||||
createOpenSshPrivateKeyFixture,
|
||||
createOpenSshPublicKeyFixture
|
||||
} from '../authentication/testing/ssh-security-key-identity.test-fixture'
|
||||
|
||||
vi.mock('../authentication/ssh2-module-load', async () =>
|
||||
(await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule()
|
||||
@@ -190,92 +185,6 @@ describe('SshConnection', () => {
|
||||
expect(removeControlSocketPathMock).toHaveBeenCalledWith('/tmp/orca-ssh-501/stale-socket')
|
||||
})
|
||||
|
||||
it('uses system SSH before ssh2 parses a security-key private key', async () => {
|
||||
findSystemSshMock.mockReturnValue('/usr/bin/ssh')
|
||||
const directory = mkdtempSync(join(tmpdir(), 'orca-security-key-connect-'))
|
||||
const keyPath = join(directory, 'id_ed25519_sk')
|
||||
writeFileSync(
|
||||
keyPath,
|
||||
createOpenSshPrivateKeyFixture(['sk-ssh-ed25519@openssh.com'], { encrypted: true })
|
||||
)
|
||||
const conn = new SshConnection(createTarget({ identityFile: keyPath }), createCallbacks())
|
||||
|
||||
try {
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
expect(clientInstances).toHaveLength(0)
|
||||
expect(spawnSystemSshCommandMock).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('uses system SSH for an agent-backed security-key public identity', async () => {
|
||||
findSystemSshMock.mockReturnValue('/usr/bin/ssh')
|
||||
const directory = mkdtempSync(join(tmpdir(), 'orca-security-key-agent-connect-'))
|
||||
const identityPath = join(directory, 'id_ed25519_sk')
|
||||
writeFileSync(
|
||||
`${identityPath}.pub`,
|
||||
createOpenSshPublicKeyFixture('sk-ssh-ed25519@openssh.com')
|
||||
)
|
||||
const conn = new SshConnection(createTarget({ identityFile: identityPath }), createCallbacks())
|
||||
|
||||
try {
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
expect(clientInstances).toHaveLength(0)
|
||||
expect(spawnSystemSshCommandMock).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('falls back to system SSH when ssh2 hits a local network policy reachability error', async () => {
|
||||
ssh2Mock.connectBehavior = 'error'
|
||||
ssh2Mock.connectErrorMessage =
|
||||
'connect EHOSTUNREACH 192.168.0.210:22 - Local (192.168.0.2:52112)'
|
||||
ssh2Mock.connectErrorCode = 'EHOSTUNREACH'
|
||||
const conn = new SshConnection(
|
||||
createTarget({ host: '192.168.0.210', label: 'LAN Linux', username: 'hydra' }),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
expect(clientInstances).toHaveLength(1)
|
||||
expect(spawnSystemSshCommandMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ host: '192.168.0.210' }),
|
||||
'echo ORCA-SYSTEM-SSH-OK',
|
||||
{ wrapCommand: false }
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'Handshake failed: no matching host key format',
|
||||
'Handshake failed: no matching key exchange algorithm',
|
||||
'Handshake failed: no matching C->S cipher'
|
||||
])(
|
||||
'falls back to system SSH when ssh2 shares no algorithm with the host (%s)',
|
||||
async (message) => {
|
||||
ssh2Mock.connectBehavior = 'error'
|
||||
ssh2Mock.connectErrorMessage = message
|
||||
const conn = new SshConnection(
|
||||
createTarget({ host: 'cert.example.com', label: 'Cert host' }),
|
||||
createCallbacks()
|
||||
)
|
||||
|
||||
await conn.connect()
|
||||
|
||||
expect(conn.getState().status).toBe('connected')
|
||||
expect(conn.usesSystemSshTransport()).toBe(true)
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps a host pinned in the Orca key store on ssh2 when negotiation fails', async () => {
|
||||
const storeDir = mkdtempSync(join(tmpdir(), 'orca-ssh-pinned-store-'))
|
||||
try {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { PassThrough } from 'node:stream'
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child'
|
||||
|
||||
const { existsSyncMock, spawnMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn(),
|
||||
@@ -20,14 +19,12 @@ vi.mock('child_process', () => ({
|
||||
spawn: spawnMock
|
||||
}))
|
||||
|
||||
import { buildSshArgs } from './system-ssh-args'
|
||||
import { spawnSystemSshCommand } from './system-ssh-command'
|
||||
import {
|
||||
uploadDirectoryViaSystemSsh,
|
||||
writeFileViaSystemSsh
|
||||
} from './file-transfer/system-ssh-file-transfer'
|
||||
import type { SshTarget } from '../../../shared/ssh-types'
|
||||
import type { SystemSshResolvedConfig } from './ssh-control-socket'
|
||||
|
||||
const SYSTEM_SSH_PATH =
|
||||
process.platform === 'win32' ? 'C:\\Windows\\System32\\OpenSSH\\ssh.exe' : '/usr/bin/ssh'
|
||||
@@ -47,37 +44,6 @@ function createTarget(overrides?: Partial<SshTarget>): SshTarget {
|
||||
}
|
||||
}
|
||||
|
||||
function createResolvedConfig(
|
||||
overrides?: Partial<SystemSshResolvedConfig>
|
||||
): SystemSshResolvedConfig {
|
||||
return {
|
||||
hostname: 'example.com',
|
||||
port: 22,
|
||||
identityFile: [],
|
||||
forwardAgent: false,
|
||||
identitiesOnly: false,
|
||||
proxyUseFdpass: false,
|
||||
controlMaster: 'no',
|
||||
controlPersist: 'no',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function expectNoOrcaControlMasterArgs(args: string[]): void {
|
||||
expect(args).not.toContain('ControlMaster=auto')
|
||||
expect(args.some((arg) => arg.startsWith('ControlPath='))).toBe(false)
|
||||
expect(args).not.toContain('ControlPersist=300')
|
||||
}
|
||||
|
||||
function createEventedProcess() {
|
||||
const proc = createFakeSpawnedChild(12345)
|
||||
const stdin = Object.assign(proc.stdin, {
|
||||
write: vi.spyOn(proc.stdin, 'write'),
|
||||
end: vi.spyOn(proc.stdin, 'end')
|
||||
})
|
||||
return Object.assign(proc, { stdin })
|
||||
}
|
||||
|
||||
function createMockChildProcess(): EventEmitter & {
|
||||
stdin: PassThrough
|
||||
stdout: PassThrough
|
||||
@@ -110,159 +76,12 @@ function createMockChildProcess(): EventEmitter & {
|
||||
}
|
||||
|
||||
describe('spawnSystemSsh', () => {
|
||||
let mockProc: {
|
||||
stdin: {
|
||||
write: ReturnType<typeof vi.fn>
|
||||
end: ReturnType<typeof vi.fn>
|
||||
on: ReturnType<typeof vi.fn>
|
||||
}
|
||||
stdout: { on: ReturnType<typeof vi.fn> }
|
||||
stderr: { on: ReturnType<typeof vi.fn> }
|
||||
pid: number
|
||||
on: ReturnType<typeof vi.fn>
|
||||
kill: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
existsSyncMock.mockReset()
|
||||
spawnMock.mockReset()
|
||||
|
||||
mockProc = {
|
||||
stdin: { write: vi.fn(), end: vi.fn(), on: vi.fn() },
|
||||
stdout: { on: vi.fn() },
|
||||
stderr: { on: vi.fn() },
|
||||
pid: 12345,
|
||||
on: vi.fn(),
|
||||
kill: vi.fn()
|
||||
}
|
||||
spawnMock.mockReturnValue(mockProc)
|
||||
mockSystemSshExists()
|
||||
})
|
||||
|
||||
it('uses configHost without resolved field overrides so OpenSSH sees the Host block', () => {
|
||||
const args = buildSshArgs(
|
||||
createTarget({
|
||||
configHost: 'fdpass-host',
|
||||
host: 'resolved.example.com',
|
||||
port: 2222,
|
||||
username: 'deploy',
|
||||
identityFile: '/tmp/key',
|
||||
identityAgent: '/tmp/agent.sock',
|
||||
proxyCommand: 'ignored'
|
||||
})
|
||||
)
|
||||
|
||||
expect(args).toContain('fdpass-host')
|
||||
expect(args).not.toContain('deploy@fdpass-host')
|
||||
expect(args).not.toContain('resolved.example.com')
|
||||
expect(args).not.toContain('-p')
|
||||
expect(args).not.toContain('-i')
|
||||
expect(args).not.toContain('IdentityAgent=/tmp/agent.sock')
|
||||
expect(args).not.toContain('ProxyCommand=ignored')
|
||||
})
|
||||
|
||||
it('states the stored endpoint when no Host block claims the alias', () => {
|
||||
// #11746: Host * can retain a deleted alias's proxy, making it appear config-backed.
|
||||
const args = buildSshArgs(
|
||||
createTarget({
|
||||
source: 'ssh-config',
|
||||
configHost: 'prod',
|
||||
host: '10.0.0.5',
|
||||
port: 2222,
|
||||
username: 'deploy'
|
||||
}),
|
||||
{ aliasClaimedByConfig: false }
|
||||
)
|
||||
|
||||
expect(args).toContain('Hostname=10.0.0.5')
|
||||
expect(args.slice(args.indexOf('-p'))).toContain('2222')
|
||||
expect(args.slice(args.indexOf('-l'))).toContain('deploy')
|
||||
expect(args.at(-1)).toBe('prod')
|
||||
expect(args).not.toContain('deploy@prod')
|
||||
expect(args).not.toContain('-i')
|
||||
expect(args).not.toContain('-J')
|
||||
})
|
||||
|
||||
it('restricts Kerberos probes to non-interactive GSSAPI authentication', () => {
|
||||
spawnSystemSshCommand(
|
||||
createTarget({
|
||||
configHost: 'krb-host; touch /tmp/not-run',
|
||||
source: 'ssh-config',
|
||||
gssapiAuthentication: true
|
||||
}),
|
||||
'echo ready',
|
||||
{ gssapiOnly: true, wrapCommand: false }
|
||||
)
|
||||
|
||||
const args = spawnMock.mock.calls[0][1] as string[]
|
||||
expect(args).toEqual(
|
||||
expect.arrayContaining([
|
||||
'-o',
|
||||
'BatchMode=yes',
|
||||
'-o',
|
||||
'GSSAPIAuthentication=yes',
|
||||
'-o',
|
||||
'PreferredAuthentications=gssapi-with-mic'
|
||||
])
|
||||
)
|
||||
expect(args).not.toContain('BatchMode=no')
|
||||
const standaloneControlIdx = args.indexOf('-S')
|
||||
expect(standaloneControlIdx).toBeGreaterThan(-1)
|
||||
expect(args[standaloneControlIdx + 1]).toBe('none')
|
||||
expect(args.at(-2)).toBe('krb-host; touch /tmp/not-run')
|
||||
expect(args.at(-1)).toBe('echo ready')
|
||||
})
|
||||
|
||||
it('does not inject Orca ControlMaster flags when ssh config already owns muxing', () => {
|
||||
const args = buildSshArgs(createTarget({ configHost: 'workbox', source: 'ssh-config' }), {
|
||||
resolvedConfig: createResolvedConfig({
|
||||
controlMaster: 'auto',
|
||||
controlPath: '/Users/me/.ssh/cm/%r@%h:%p',
|
||||
controlPersist: '10m'
|
||||
})
|
||||
})
|
||||
|
||||
expectNoOrcaControlMasterArgs(args)
|
||||
expect(args).not.toContain('-S')
|
||||
expect(args).toContain('workbox')
|
||||
})
|
||||
|
||||
it('does not inject Orca ControlMaster flags for unresolved ssh-config targets', () => {
|
||||
const args = buildSshArgs(createTarget({ configHost: 'workbox', source: 'ssh-config' }))
|
||||
|
||||
expectNoOrcaControlMasterArgs(args)
|
||||
expect(args).not.toContain('-S')
|
||||
expect(args).toContain('workbox')
|
||||
})
|
||||
|
||||
it('forces standalone SSH when target connection reuse is disabled', () => {
|
||||
const args = buildSshArgs(createTarget({ systemSshConnectionReuse: false }))
|
||||
const standaloneControlIdx = args.indexOf('-S')
|
||||
|
||||
expect(standaloneControlIdx).toBeGreaterThan(-1)
|
||||
expect(args[standaloneControlIdx + 1]).toBe('none')
|
||||
expectNoOrcaControlMasterArgs(args)
|
||||
})
|
||||
|
||||
it('removes wrapped process listeners after command close', () => {
|
||||
const proc = createEventedProcess()
|
||||
spawnMock.mockReturnValue(proc)
|
||||
|
||||
const channel = spawnSystemSshCommand(createTarget(), 'echo hello')
|
||||
const onClose = vi.fn()
|
||||
channel.on('close', onClose)
|
||||
proc.emit('close', 0, null)
|
||||
|
||||
expect(onClose).toHaveBeenCalledWith(0, null)
|
||||
expect(proc.stdout.listenerCount('data')).toBe(0)
|
||||
expect(proc.stdout.listenerCount('end')).toBe(0)
|
||||
expect(proc.stdout.listenerCount('error')).toBe(0)
|
||||
expect(proc.stdin.listenerCount('error')).toBe(0)
|
||||
expect(proc.listenerCount('exit')).toBe(0)
|
||||
expect(proc.listenerCount('close')).toBe(0)
|
||||
expect(proc.listenerCount('error')).toBe(0)
|
||||
})
|
||||
|
||||
it('pauses command stdout under backpressure and resumes when the channel reads', async () => {
|
||||
const proc = createMockChildProcess()
|
||||
const pause = vi.spyOn(proc.stdout, 'pause')
|
||||
|
||||
@@ -105,56 +105,6 @@ describe('SshConnectionStore import route de-duplication', () => {
|
||||
loadUserSshConfigMock.mockReturnValue([])
|
||||
})
|
||||
|
||||
it('never matches a saved target whose own jump host conflicts with the one it inherits', async () => {
|
||||
mockStore.addSshTarget({
|
||||
id: 'ssh-own-jump',
|
||||
label: 'Own jump',
|
||||
configHost: 'saved-own-jump',
|
||||
host: '172.16.203.131',
|
||||
port: 22,
|
||||
username: 'chanmuzi',
|
||||
jumpHost: 'bastion-b',
|
||||
source: 'manual'
|
||||
})
|
||||
sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('via-a')])
|
||||
|
||||
expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1)
|
||||
})
|
||||
|
||||
// Saved from the picker when prod was 10.0.0.1; system ssh now follows the config to 10.0.0.9, ssh2 keeps 10.0.0.1.
|
||||
it('never matches a saved target whose host the two transports resolve differently', async () => {
|
||||
mockStore.addSshTarget({
|
||||
id: 'ssh-prod',
|
||||
label: 'prod',
|
||||
configHost: 'prod',
|
||||
host: '10.0.0.1',
|
||||
port: 22,
|
||||
username: 'chanmuzi',
|
||||
jumpHost: 'b',
|
||||
source: 'manual'
|
||||
})
|
||||
sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('old')])
|
||||
|
||||
expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1)
|
||||
})
|
||||
|
||||
// Its Host block is gone, so system ssh still dials the saved 192.0.2.10, not the name `fresh` points at.
|
||||
it('never matches a saved config target whose alias the config no longer claims', async () => {
|
||||
mockStore.addSshTarget({
|
||||
id: 'ssh-removed-block',
|
||||
label: 'removed-block',
|
||||
configHost: 'removed-block',
|
||||
host: '192.0.2.10',
|
||||
port: 22,
|
||||
username: 'chanmuzi',
|
||||
source: 'ssh-config'
|
||||
})
|
||||
unclaimedAliases.add('removed-block')
|
||||
sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('fresh')])
|
||||
|
||||
expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps a route match when this import itself updates the matched target', async () => {
|
||||
mockStore.addSshTarget({
|
||||
...configCandidate('moved'),
|
||||
@@ -202,18 +152,6 @@ describe('SshConnectionStore import route de-duplication', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('imports the same address behind a different jump host', async () => {
|
||||
sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('via-b')])
|
||||
|
||||
expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('falls back to alias-only when ssh -G fails, rather than guessing', async () => {
|
||||
sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('unresolvable')])
|
||||
|
||||
expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('lets Restore bring back a removed alias that shares a saved route, as its dialog promised', async () => {
|
||||
sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('aimp')])
|
||||
mockStore.addDeletedSshConfigAlias('aimp')
|
||||
@@ -221,11 +159,4 @@ describe('SshConnectionStore import route de-duplication', () => {
|
||||
expect((await sshStore.importFromSshConfig()).targets).toEqual([])
|
||||
expect((await sshStore.importFromSshConfig({ reAdopt: true })).targets).toHaveLength(1)
|
||||
})
|
||||
|
||||
// #15478's own config: without HostName, OpenSSH connects to the alias name, which only DNS ties to the IP.
|
||||
it('does not match a HostName-less alias to an IP target by name resolution', async () => {
|
||||
sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('aimp-no-hostname')])
|
||||
|
||||
expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
+249
-249
@@ -314,258 +314,258 @@ function startEditing(text: string): HTMLInputElement {
|
||||
return input
|
||||
}
|
||||
|
||||
describe.each([
|
||||
{ tree: 'in a plain tree', strict: false },
|
||||
{ tree: 'under StrictMode', strict: true }
|
||||
])('BrowserPane adoption keeps live address-bar chrome ($tree)', ({ strict }) => {
|
||||
let webview: ReturnType<typeof createWebview>
|
||||
let liveAttachment: { detached: boolean } | null = null
|
||||
describe.each([{ tree: 'under StrictMode', strict: true }])(
|
||||
'BrowserPane adoption keeps live address-bar chrome ($tree)',
|
||||
({ strict }) => {
|
||||
let webview: ReturnType<typeof createWebview>
|
||||
let liveAttachment: { detached: boolean } | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
strictMode = strict
|
||||
frameCallbacks = []
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
|
||||
frameCallbacks.push(callback)
|
||||
return frameCallbacks.length
|
||||
})
|
||||
vi.stubGlobal('cancelAnimationFrame', () => {})
|
||||
webview = createWebview()
|
||||
liveAttachment = null
|
||||
mocks.attach.mockReset().mockImplementation((_args: unknown, viewport: HTMLElement) => {
|
||||
// Model the real visible-attachment claim: a second attach before detach must fail so ordering errors stay observable.
|
||||
if (liveAttachment?.detached === false) {
|
||||
throw new Error('browser_client_page_renderer_visible_page_claimed')
|
||||
}
|
||||
viewport.appendChild(webview)
|
||||
const attachment = {
|
||||
webview,
|
||||
detached: false,
|
||||
detach: vi.fn(() => {
|
||||
attachment.detached = true
|
||||
webview.remove()
|
||||
}),
|
||||
nextMetadataRevision: vi.fn(() => 1)
|
||||
}
|
||||
liveAttachment = attachment
|
||||
return attachment
|
||||
})
|
||||
mocks.ensureRemotePage.mockClear()
|
||||
mocks.callRuntimeRpc.mockClear()
|
||||
installClientHostedPaneApi({
|
||||
ui: { onFocusBrowserAddressBar: () => () => {}, onShowBrowserHistory: () => () => {} }
|
||||
})
|
||||
useAppStore.setState({
|
||||
browserPagesByWorkspace: { [WORKSPACE_ID]: [browserPage()] },
|
||||
browserUrlHistory: [
|
||||
{
|
||||
url: 'https://example.internal/docs',
|
||||
normalizedUrl: 'example.internal/docs',
|
||||
title: 'Example docs',
|
||||
lastVisitedAt: Date.now(),
|
||||
visitCount: 3
|
||||
beforeEach(() => {
|
||||
strictMode = strict
|
||||
frameCallbacks = []
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
|
||||
frameCallbacks.push(callback)
|
||||
return frameCallbacks.length
|
||||
})
|
||||
vi.stubGlobal('cancelAnimationFrame', () => {})
|
||||
webview = createWebview()
|
||||
liveAttachment = null
|
||||
mocks.attach.mockReset().mockImplementation((_args: unknown, viewport: HTMLElement) => {
|
||||
// Model the real visible-attachment claim: a second attach before detach must fail so ordering errors stay observable.
|
||||
if (liveAttachment?.detached === false) {
|
||||
throw new Error('browser_client_page_renderer_visible_page_claimed')
|
||||
}
|
||||
],
|
||||
browserCertificateFailuresByPageId: {},
|
||||
pendingAddressBarFocusByPageId: {},
|
||||
pendingAddressBarFocusByTabId: {}
|
||||
})
|
||||
stageHandle()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
clearBrowserAddressBarEditSession(PAGE_ID)
|
||||
clearBrowserPageDeferredNavigation(PAGE_ID)
|
||||
vi.unstubAllGlobals()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('carries the draft, caret and open suggestions through the staged-to-client swap', () => {
|
||||
renderWorkspacePane()
|
||||
expect(screen.getByTestId('streamed-viewport')).not.toBeNull()
|
||||
|
||||
const staged = startEditing('example.int')
|
||||
act(() => staged.setSelectionRange(3, 7))
|
||||
expect(staged.getAttribute('aria-expanded')).toBe('true')
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
// The pane really did swap: the streamed viewport is gone and the guest is attached.
|
||||
expect(screen.queryByTestId('streamed-viewport')).toBeNull()
|
||||
expect(mocks.attach).toHaveBeenCalled()
|
||||
|
||||
const adopted = addressBar()
|
||||
expect(adopted.value).toBe('example.int')
|
||||
expect(document.activeElement).toBe(adopted)
|
||||
expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([3, 7])
|
||||
expect(adopted.getAttribute('aria-expanded')).toBe('true')
|
||||
expect(screen.getByRole('option', { name: /Example docs/ })).not.toBeNull()
|
||||
})
|
||||
|
||||
// Previewed URLs live in the input; carry the separate typed query too or Escape cannot restore it.
|
||||
it('carries the typed query behind a previewed suggestion through the swap', () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('example')
|
||||
act(() => {
|
||||
fireEvent.keyDown(staged, { key: 'ArrowDown' })
|
||||
})
|
||||
expect(staged.value).toBe('https://example.internal/docs')
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
const adopted = addressBar()
|
||||
expect(adopted.value).toBe('https://example.internal/docs')
|
||||
act(() => {
|
||||
fireEvent.keyDown(adopted, { key: 'Escape' })
|
||||
})
|
||||
expect(adopted.value).toBe('example')
|
||||
})
|
||||
|
||||
// Apply the saved caret once; retrying it after typing would move it backward or overwrite new text.
|
||||
it('leaves the caret where the user puts it while the grab is still retrying', () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('example.int')
|
||||
act(() => staged.setSelectionRange(3, 7))
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
|
||||
const adopted = addressBar()
|
||||
act(() => {
|
||||
fireEvent.change(adopted, { target: { value: 'example.internal/docs' } })
|
||||
})
|
||||
act(() => adopted.setSelectionRange(12, 12))
|
||||
// The frames the grab would have spent re-taking the bar all land after the user typed.
|
||||
act(() => flushFrames())
|
||||
|
||||
expect(adopted.value).toBe('example.internal/docs')
|
||||
expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([12, 12])
|
||||
})
|
||||
|
||||
// Steal focus after resume to exercise the grab’s caret restore; otherwise select-all retries can escape detection.
|
||||
|
||||
// An open list survives focus naturally; only a dismissed list proves dropdown state crosses the swap.
|
||||
|
||||
// Only same-commit swaps may reclaim focus; later worktree revisits must not resume old edits.
|
||||
it('does not resume an edit into a pane that mounts in a later task', async () => {
|
||||
renderWorkspacePane()
|
||||
startEditing('example.int')
|
||||
|
||||
cleanup()
|
||||
await act(async () => {})
|
||||
renderWorkspacePane()
|
||||
|
||||
const remounted = addressBar()
|
||||
expect(remounted.value).toBe('')
|
||||
expect(document.activeElement).not.toBe(remounted)
|
||||
})
|
||||
|
||||
// Generation changes reattach in place; edits must survive without remounting.
|
||||
|
||||
// Headless adoption stays streamed and must preserve the same live edit.
|
||||
|
||||
it('holds a URL submitted against the staged page and loads it once the guest attaches', () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('https://example.internal/deferred')
|
||||
act(() => {
|
||||
fireEvent.submit(staged.closest('form') ?? staged)
|
||||
viewport.appendChild(webview)
|
||||
const attachment = {
|
||||
webview,
|
||||
detached: false,
|
||||
detach: vi.fn(() => {
|
||||
attachment.detached = true
|
||||
webview.remove()
|
||||
}),
|
||||
nextMetadataRevision: vi.fn(() => 1)
|
||||
}
|
||||
liveAttachment = attachment
|
||||
return attachment
|
||||
})
|
||||
mocks.ensureRemotePage.mockClear()
|
||||
mocks.callRuntimeRpc.mockClear()
|
||||
installClientHostedPaneApi({
|
||||
ui: { onFocusBrowserAddressBar: () => () => {}, onShowBrowserHistory: () => () => {} }
|
||||
})
|
||||
useAppStore.setState({
|
||||
browserPagesByWorkspace: { [WORKSPACE_ID]: [browserPage()] },
|
||||
browserUrlHistory: [
|
||||
{
|
||||
url: 'https://example.internal/docs',
|
||||
normalizedUrl: 'example.internal/docs',
|
||||
title: 'Example docs',
|
||||
lastVisitedAt: Date.now(),
|
||||
visitCount: 3
|
||||
}
|
||||
],
|
||||
browserCertificateFailuresByPageId: {},
|
||||
pendingAddressBarFocusByPageId: {},
|
||||
pendingAddressBarFocusByTabId: {}
|
||||
})
|
||||
stageHandle()
|
||||
})
|
||||
|
||||
// tabShow before host minting returns browser_tab_not_found, which would close the staged tab.
|
||||
expect(mocks.ensureRemotePage).not.toHaveBeenCalled()
|
||||
expect(webview.loadURL).not.toHaveBeenCalled()
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
expect(webview.loadURL).toHaveBeenCalledWith('https://example.internal/deferred')
|
||||
})
|
||||
|
||||
// Only input identity exposes chrome remounts; save/resume can otherwise hide the repeated dropdown animation.
|
||||
|
||||
// Continuity alone passes if nothing happens; verify generation changes really reattach the guest.
|
||||
it('re-attaches the guest when a host restart bumps the page generation', () => {
|
||||
stageClientHostedHandle()
|
||||
renderWorkspacePane()
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
const bar = addressBar()
|
||||
const stale = mocks.attach.mock.results.at(-1)?.value as { detach: ReturnType<typeof vi.fn> }
|
||||
expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration)
|
||||
expect(attachedGenerations()).not.toContain(CLIENT_PLACEMENT.pageHostGeneration + 1)
|
||||
|
||||
act(() => adoptOntoClient(CLIENT_PLACEMENT.pageHostGeneration + 1))
|
||||
act(() => flushFrames())
|
||||
|
||||
// The host retires the previous generation’s guest; retaining it would leave an inert tag.
|
||||
expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration + 1)
|
||||
// Detach before attach or the visible-page claim strands the pane on the unavailable notice.
|
||||
expect(stale.detach.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
mocks.attach.mock.invocationCallOrder.at(-1) as number
|
||||
)
|
||||
expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull()
|
||||
expect(addressBar()).toBe(bar)
|
||||
})
|
||||
|
||||
// Do not consume a one-time tour before placement makes its controls usable.
|
||||
|
||||
// Live host status can override cached client placement and swap to streaming; retain edit-session recovery for this path.
|
||||
it('carries a live edit when a staged client-hosted page is adopted onto the server', () => {
|
||||
stageClientHostedHandle()
|
||||
renderWorkspacePane()
|
||||
expect(screen.queryByTestId('streamed-viewport')).toBeNull()
|
||||
|
||||
const staged = startEditing('fallback.internal')
|
||||
act(() => staged.setSelectionRange(4, 4))
|
||||
|
||||
act(() => adoptOntoServer())
|
||||
act(() => flushFrames())
|
||||
|
||||
// The pane really did fall back to the streamed one.
|
||||
expect(screen.getByTestId('streamed-viewport')).not.toBeNull()
|
||||
const adopted = addressBar()
|
||||
expect(adopted.value).toBe('fallback.internal')
|
||||
expect(document.activeElement).toBe(adopted)
|
||||
expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([4, 4])
|
||||
})
|
||||
|
||||
// Restored client-placed pages must await recovery locally; hosts reject server screencasts for them.
|
||||
it('mounts a restored client-hosted page on the client pane while the host recovers it', () => {
|
||||
restoreClientHostedHandle()
|
||||
renderWorkspacePane()
|
||||
|
||||
expect(screen.queryByTestId('streamed-viewport')).toBeNull()
|
||||
expect(mocks.ensureRemotePage).not.toHaveBeenCalled()
|
||||
// Recovery retains the ID but replaces its generation; attaching early would strand the pane.
|
||||
expect(mocks.attach).not.toHaveBeenCalled()
|
||||
expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull()
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
expect(mocks.attach).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('replays a URL held against the staged page when a headless host adopts it', async () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('https://example.internal/headless')
|
||||
act(() => {
|
||||
fireEvent.submit(staged.closest('form') ?? staged)
|
||||
})
|
||||
expect(mocks.ensureRemotePage).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
adoptOntoServer()
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
clearBrowserAddressBarEditSession(PAGE_ID)
|
||||
clearBrowserPageDeferredNavigation(PAGE_ID)
|
||||
vi.unstubAllGlobals()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
expect(mocks.ensureRemotePage).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.callRuntimeRpc).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ environmentId: ENVIRONMENT_ID }),
|
||||
'browser.goto',
|
||||
expect.objectContaining({ url: 'https://example.internal/headless' }),
|
||||
expect.anything()
|
||||
)
|
||||
})
|
||||
})
|
||||
it('carries the draft, caret and open suggestions through the staged-to-client swap', () => {
|
||||
renderWorkspacePane()
|
||||
expect(screen.getByTestId('streamed-viewport')).not.toBeNull()
|
||||
|
||||
const staged = startEditing('example.int')
|
||||
act(() => staged.setSelectionRange(3, 7))
|
||||
expect(staged.getAttribute('aria-expanded')).toBe('true')
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
// The pane really did swap: the streamed viewport is gone and the guest is attached.
|
||||
expect(screen.queryByTestId('streamed-viewport')).toBeNull()
|
||||
expect(mocks.attach).toHaveBeenCalled()
|
||||
|
||||
const adopted = addressBar()
|
||||
expect(adopted.value).toBe('example.int')
|
||||
expect(document.activeElement).toBe(adopted)
|
||||
expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([3, 7])
|
||||
expect(adopted.getAttribute('aria-expanded')).toBe('true')
|
||||
expect(screen.getByRole('option', { name: /Example docs/ })).not.toBeNull()
|
||||
})
|
||||
|
||||
// Previewed URLs live in the input; carry the separate typed query too or Escape cannot restore it.
|
||||
it('carries the typed query behind a previewed suggestion through the swap', () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('example')
|
||||
act(() => {
|
||||
fireEvent.keyDown(staged, { key: 'ArrowDown' })
|
||||
})
|
||||
expect(staged.value).toBe('https://example.internal/docs')
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
const adopted = addressBar()
|
||||
expect(adopted.value).toBe('https://example.internal/docs')
|
||||
act(() => {
|
||||
fireEvent.keyDown(adopted, { key: 'Escape' })
|
||||
})
|
||||
expect(adopted.value).toBe('example')
|
||||
})
|
||||
|
||||
// Apply the saved caret once; retrying it after typing would move it backward or overwrite new text.
|
||||
it('leaves the caret where the user puts it while the grab is still retrying', () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('example.int')
|
||||
act(() => staged.setSelectionRange(3, 7))
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
|
||||
const adopted = addressBar()
|
||||
act(() => {
|
||||
fireEvent.change(adopted, { target: { value: 'example.internal/docs' } })
|
||||
})
|
||||
act(() => adopted.setSelectionRange(12, 12))
|
||||
// The frames the grab would have spent re-taking the bar all land after the user typed.
|
||||
act(() => flushFrames())
|
||||
|
||||
expect(adopted.value).toBe('example.internal/docs')
|
||||
expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([12, 12])
|
||||
})
|
||||
|
||||
// Steal focus after resume to exercise the grab’s caret restore; otherwise select-all retries can escape detection.
|
||||
|
||||
// An open list survives focus naturally; only a dismissed list proves dropdown state crosses the swap.
|
||||
|
||||
// Only same-commit swaps may reclaim focus; later worktree revisits must not resume old edits.
|
||||
it('does not resume an edit into a pane that mounts in a later task', async () => {
|
||||
renderWorkspacePane()
|
||||
startEditing('example.int')
|
||||
|
||||
cleanup()
|
||||
await act(async () => {})
|
||||
renderWorkspacePane()
|
||||
|
||||
const remounted = addressBar()
|
||||
expect(remounted.value).toBe('')
|
||||
expect(document.activeElement).not.toBe(remounted)
|
||||
})
|
||||
|
||||
// Generation changes reattach in place; edits must survive without remounting.
|
||||
|
||||
// Headless adoption stays streamed and must preserve the same live edit.
|
||||
|
||||
it('holds a URL submitted against the staged page and loads it once the guest attaches', () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('https://example.internal/deferred')
|
||||
act(() => {
|
||||
fireEvent.submit(staged.closest('form') ?? staged)
|
||||
})
|
||||
|
||||
// tabShow before host minting returns browser_tab_not_found, which would close the staged tab.
|
||||
expect(mocks.ensureRemotePage).not.toHaveBeenCalled()
|
||||
expect(webview.loadURL).not.toHaveBeenCalled()
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
expect(webview.loadURL).toHaveBeenCalledWith('https://example.internal/deferred')
|
||||
})
|
||||
|
||||
// Only input identity exposes chrome remounts; save/resume can otherwise hide the repeated dropdown animation.
|
||||
|
||||
// Continuity alone passes if nothing happens; verify generation changes really reattach the guest.
|
||||
it('re-attaches the guest when a host restart bumps the page generation', () => {
|
||||
stageClientHostedHandle()
|
||||
renderWorkspacePane()
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
const bar = addressBar()
|
||||
const stale = mocks.attach.mock.results.at(-1)?.value as { detach: ReturnType<typeof vi.fn> }
|
||||
expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration)
|
||||
expect(attachedGenerations()).not.toContain(CLIENT_PLACEMENT.pageHostGeneration + 1)
|
||||
|
||||
act(() => adoptOntoClient(CLIENT_PLACEMENT.pageHostGeneration + 1))
|
||||
act(() => flushFrames())
|
||||
|
||||
// The host retires the previous generation’s guest; retaining it would leave an inert tag.
|
||||
expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration + 1)
|
||||
// Detach before attach or the visible-page claim strands the pane on the unavailable notice.
|
||||
expect(stale.detach.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
mocks.attach.mock.invocationCallOrder.at(-1) as number
|
||||
)
|
||||
expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull()
|
||||
expect(addressBar()).toBe(bar)
|
||||
})
|
||||
|
||||
// Do not consume a one-time tour before placement makes its controls usable.
|
||||
|
||||
// Live host status can override cached client placement and swap to streaming; retain edit-session recovery for this path.
|
||||
it('carries a live edit when a staged client-hosted page is adopted onto the server', () => {
|
||||
stageClientHostedHandle()
|
||||
renderWorkspacePane()
|
||||
expect(screen.queryByTestId('streamed-viewport')).toBeNull()
|
||||
|
||||
const staged = startEditing('fallback.internal')
|
||||
act(() => staged.setSelectionRange(4, 4))
|
||||
|
||||
act(() => adoptOntoServer())
|
||||
act(() => flushFrames())
|
||||
|
||||
// The pane really did fall back to the streamed one.
|
||||
expect(screen.getByTestId('streamed-viewport')).not.toBeNull()
|
||||
const adopted = addressBar()
|
||||
expect(adopted.value).toBe('fallback.internal')
|
||||
expect(document.activeElement).toBe(adopted)
|
||||
expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([4, 4])
|
||||
})
|
||||
|
||||
// Restored client-placed pages must await recovery locally; hosts reject server screencasts for them.
|
||||
it('mounts a restored client-hosted page on the client pane while the host recovers it', () => {
|
||||
restoreClientHostedHandle()
|
||||
renderWorkspacePane()
|
||||
|
||||
expect(screen.queryByTestId('streamed-viewport')).toBeNull()
|
||||
expect(mocks.ensureRemotePage).not.toHaveBeenCalled()
|
||||
// Recovery retains the ID but replaces its generation; attaching early would strand the pane.
|
||||
expect(mocks.attach).not.toHaveBeenCalled()
|
||||
expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull()
|
||||
|
||||
act(() => adoptOntoClient())
|
||||
act(() => flushFrames())
|
||||
|
||||
expect(mocks.attach).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('replays a URL held against the staged page when a headless host adopts it', async () => {
|
||||
renderWorkspacePane()
|
||||
const staged = startEditing('https://example.internal/headless')
|
||||
act(() => {
|
||||
fireEvent.submit(staged.closest('form') ?? staged)
|
||||
})
|
||||
expect(mocks.ensureRemotePage).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
adoptOntoServer()
|
||||
})
|
||||
|
||||
expect(mocks.ensureRemotePage).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.callRuntimeRpc).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ environmentId: ENVIRONMENT_ID }),
|
||||
'browser.goto',
|
||||
expect.objectContaining({ url: 'https://example.internal/headless' }),
|
||||
expect.anything()
|
||||
)
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user