Fix parked browser wakeups and daemon PTY inspection (#4420)
This commit is contained in:
@@ -324,14 +324,22 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => {
|
||||
})
|
||||
|
||||
describe('hasChildProcesses / getForegroundProcess', () => {
|
||||
it('returns false for hasChildProcesses (stub)', async () => {
|
||||
it('returns false for shell foreground processes', async () => {
|
||||
const { id } = await adapter.spawn({ cols: 80, rows: 24 })
|
||||
vi.mocked(lastSubprocess.getForegroundProcess).mockReturnValue('bash')
|
||||
expect(await adapter.hasChildProcesses(id)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns null for getForegroundProcess (stub)', async () => {
|
||||
it('returns true for non-shell foreground processes', async () => {
|
||||
const { id } = await adapter.spawn({ cols: 80, rows: 24 })
|
||||
expect(await adapter.getForegroundProcess(id)).toBeNull()
|
||||
vi.mocked(lastSubprocess.getForegroundProcess).mockReturnValue('codex')
|
||||
expect(await adapter.hasChildProcesses(id)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns the foreground process', async () => {
|
||||
const { id } = await adapter.spawn({ cols: 80, rows: 24 })
|
||||
vi.mocked(lastSubprocess.getForegroundProcess).mockReturnValue('codex')
|
||||
expect(await adapter.getForegroundProcess(id)).toBe('codex')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type SessionInfo
|
||||
} from './types'
|
||||
import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types'
|
||||
import { isShellProcess } from '../../shared/agent-detection'
|
||||
|
||||
export type DaemonPtyAdapterOptions = {
|
||||
socketPath: string
|
||||
@@ -322,8 +323,11 @@ export class DaemonPtyAdapter implements IPtyProvider {
|
||||
// No flow control for daemon-backed terminals
|
||||
}
|
||||
|
||||
async hasChildProcesses(_id: string): Promise<boolean> {
|
||||
return false
|
||||
async hasChildProcesses(id: string): Promise<boolean> {
|
||||
const foregroundProcess = await this.getForegroundProcess(id)
|
||||
// Why: daemon-backed PTYs can host long-lived agents while the renderer is
|
||||
// detached. Cleanup prompts must not treat those sessions like idle shells.
|
||||
return foregroundProcess !== null && !isShellProcess(foregroundProcess)
|
||||
}
|
||||
|
||||
async getForegroundProcess(id: string): Promise<string | null> {
|
||||
|
||||
+3
-1
@@ -84,6 +84,7 @@ import { agentHookServer } from './agent-hooks/server'
|
||||
import { maybeAutoRenameBranchOnFirstWork } from './agent-hooks/first-work-branch-rename'
|
||||
import { setMigrationUnsupportedPtyListener } from './agent-hooks/migration-unsupported-pty-state'
|
||||
import {
|
||||
clearProviderPtyState,
|
||||
getPtyIdForPaneKey,
|
||||
registerPaneKeyTeardownListener,
|
||||
getLocalPtyProvider,
|
||||
@@ -1120,7 +1121,8 @@ app.whenReady().then(async () => {
|
||||
// to swap the in-process provider for the daemon-routed one. Capturing the
|
||||
// provider reference eagerly here would freeze the pre-daemon LocalPtyProvider
|
||||
// and defeat the teardown helper's prefix sweep (design §4.3 wire-up).
|
||||
getLocalProvider: () => getLocalPtyProvider()
|
||||
getLocalProvider: () => getLocalPtyProvider(),
|
||||
onPtyStopped: clearProviderPtyState
|
||||
})
|
||||
runtime = runtimeService
|
||||
automations = new AutomationService(store, { claudeUsage, codexUsage })
|
||||
|
||||
@@ -15,7 +15,8 @@ const {
|
||||
acceptDownloadMock,
|
||||
cancelDownloadMock,
|
||||
showSaveDialogMock,
|
||||
browserWindowFromWebContentsMock
|
||||
browserWindowFromWebContentsMock,
|
||||
webContentsFromIdMock
|
||||
} = vi.hoisted(() => ({
|
||||
removeHandlerMock: vi.fn(),
|
||||
handleMock: vi.fn(),
|
||||
@@ -30,7 +31,8 @@ const {
|
||||
acceptDownloadMock: vi.fn(),
|
||||
cancelDownloadMock: vi.fn(),
|
||||
showSaveDialogMock: vi.fn(),
|
||||
browserWindowFromWebContentsMock: vi.fn()
|
||||
browserWindowFromWebContentsMock: vi.fn(),
|
||||
webContentsFromIdMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
@@ -43,6 +45,9 @@ vi.mock('electron', () => ({
|
||||
ipcMain: {
|
||||
removeHandler: removeHandlerMock,
|
||||
handle: handleMock
|
||||
},
|
||||
webContents: {
|
||||
fromId: webContentsFromIdMock
|
||||
}
|
||||
}))
|
||||
|
||||
@@ -87,6 +92,8 @@ describe('registerBrowserHandlers', () => {
|
||||
cancelDownloadMock.mockReset()
|
||||
showSaveDialogMock.mockReset()
|
||||
browserWindowFromWebContentsMock.mockReset()
|
||||
webContentsFromIdMock.mockReset()
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => false })
|
||||
openDevToolsMock.mockResolvedValue(true)
|
||||
setAnnotationViewportBridgeMock.mockResolvedValue(true)
|
||||
setAgentBrowserBridgeRef(null)
|
||||
@@ -292,6 +299,54 @@ describe('registerBrowserHandlers', () => {
|
||||
await expect(waitForAnyTabRegistration(1000)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not resolve worktree registration waits from a stale registered guest', async () => {
|
||||
getWebContentsIdByTabIdMock.mockReturnValue(new Map([['page-1', 123]]))
|
||||
getWorktreeIdForTabMock.mockReturnValue('worktree-1')
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => true })
|
||||
|
||||
let resolved = false
|
||||
const wait = waitForWorktreeTabRegistration('worktree-1', 1000).then(() => {
|
||||
resolved = true
|
||||
})
|
||||
await Promise.resolve()
|
||||
|
||||
expect(resolved).toBe(false)
|
||||
|
||||
registerBrowserHandlers()
|
||||
const registerHandler = handleMock.mock.calls.find(
|
||||
([channel]) => channel === 'browser:registerGuest'
|
||||
)?.[1] as (
|
||||
event: { sender: Electron.WebContents },
|
||||
args: {
|
||||
browserPageId: string
|
||||
workspaceId: string
|
||||
worktreeId: string
|
||||
webContentsId: number
|
||||
}
|
||||
) => boolean
|
||||
|
||||
const result = registerHandler(
|
||||
{
|
||||
sender: {
|
||||
id: 91,
|
||||
isDestroyed: () => false,
|
||||
getType: () => 'window',
|
||||
getURL: () => 'file:///renderer/index.html'
|
||||
} as Electron.WebContents
|
||||
},
|
||||
{
|
||||
browserPageId: 'page-1',
|
||||
workspaceId: 'workspace-1',
|
||||
worktreeId: 'worktree-1',
|
||||
webContentsId: 456
|
||||
}
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
await expect(wait).resolves.toBeUndefined()
|
||||
expect(resolved).toBe(true)
|
||||
})
|
||||
|
||||
it('validates annotation viewport bridge requests before syncing to the guest', async () => {
|
||||
registerBrowserHandlers()
|
||||
|
||||
|
||||
+19
-6
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable max-lines -- Why: browser IPC handlers must be registered together so the
|
||||
trust boundary (isTrustedBrowserRenderer) and handler teardown stay consistent. */
|
||||
import { BrowserWindow, dialog, ipcMain } from 'electron'
|
||||
import { BrowserWindow, dialog, ipcMain, webContents } from 'electron'
|
||||
import { browserManager } from '../browser/browser-manager'
|
||||
import type { AgentBrowserBridge } from '../browser/agent-browser-bridge'
|
||||
import { browserSessionRegistry } from '../browser/browser-session-registry'
|
||||
@@ -75,9 +75,20 @@ function resolvePendingRegistrations(registrationResolvers: Set<() => void> | un
|
||||
}
|
||||
}
|
||||
|
||||
function isLiveBrowserWebContentsId(webContentsId: number | null | undefined): boolean {
|
||||
if (webContentsId == null) {
|
||||
return false
|
||||
}
|
||||
const guest = webContents.fromId(webContentsId)
|
||||
return Boolean(guest && !guest.isDestroyed())
|
||||
}
|
||||
|
||||
function hasRegisteredTabForWorktree(worktreeId: string): boolean {
|
||||
for (const browserPageId of browserManager.getWebContentsIdByTabId().keys()) {
|
||||
if (browserManager.getWorktreeIdForTab(browserPageId) === worktreeId) {
|
||||
for (const [browserPageId, webContentsId] of browserManager.getWebContentsIdByTabId()) {
|
||||
if (
|
||||
browserManager.getWorktreeIdForTab(browserPageId) === worktreeId &&
|
||||
isLiveBrowserWebContentsId(webContentsId)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -85,7 +96,7 @@ function hasRegisteredTabForWorktree(worktreeId: string): boolean {
|
||||
}
|
||||
|
||||
export function waitForTabRegistration(browserPageId: string, timeoutMs = 8_000): Promise<void> {
|
||||
if (browserManager.getGuestWebContentsId(browserPageId) !== null) {
|
||||
if (isLiveBrowserWebContentsId(browserManager.getGuestWebContentsId(browserPageId))) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
let registrationResolvers = pendingTabRegistrations.get(browserPageId)
|
||||
@@ -119,8 +130,10 @@ export function waitForWorktreeTabRegistration(
|
||||
}
|
||||
|
||||
export function waitForAnyTabRegistration(timeoutMs = 8_000): Promise<void> {
|
||||
if (browserManager.getWebContentsIdByTabId().size > 0) {
|
||||
return Promise.resolve()
|
||||
for (const webContentsId of browserManager.getWebContentsIdByTabId().values()) {
|
||||
if (isLiveBrowserWebContentsId(webContentsId)) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
}
|
||||
return waitForRegistrationSet(pendingAnyTabRegistrations, timeoutMs, () => {})
|
||||
}
|
||||
|
||||
@@ -190,16 +190,19 @@ vi.mock('../ports/advertised-url-watcher', () => ({
|
||||
}
|
||||
}))
|
||||
|
||||
const { killAllProcessesForWorktreeMock, getLocalPtyProviderMock } = vi.hoisted(() => ({
|
||||
killAllProcessesForWorktreeMock: vi.fn(),
|
||||
getLocalPtyProviderMock: vi.fn()
|
||||
}))
|
||||
const { killAllProcessesForWorktreeMock, clearProviderPtyStateMock, getLocalPtyProviderMock } =
|
||||
vi.hoisted(() => ({
|
||||
killAllProcessesForWorktreeMock: vi.fn(),
|
||||
clearProviderPtyStateMock: vi.fn(),
|
||||
getLocalPtyProviderMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../runtime/worktree-teardown', () => ({
|
||||
killAllProcessesForWorktree: killAllProcessesForWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('./pty', () => ({
|
||||
clearProviderPtyState: clearProviderPtyStateMock,
|
||||
getLocalPtyProvider: getLocalPtyProviderMock
|
||||
}))
|
||||
|
||||
@@ -290,6 +293,7 @@ describe('registerWorktreeHandlers', () => {
|
||||
store.getAllWorktreeLineage,
|
||||
store.removeWorktreeLineage,
|
||||
killAllProcessesForWorktreeMock,
|
||||
clearProviderPtyStateMock,
|
||||
getLocalPtyProviderMock,
|
||||
deleteWorktreeHistoryDirMock,
|
||||
advertisedUrlWatcherForgetWorktreeMock
|
||||
@@ -3574,7 +3578,8 @@ describe('registerWorktreeHandlers', () => {
|
||||
|
||||
expect(killAllProcessesForWorktreeMock).toHaveBeenCalledWith(worktreeId, {
|
||||
runtime: runtimeStub,
|
||||
localProvider: ptyProvider
|
||||
localProvider: ptyProvider,
|
||||
onPtyStopped: clearProviderPtyStateMock
|
||||
})
|
||||
expect(killAllProcessesForWorktreeMock.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
store.removeWorktreeMeta.mock.invocationCallOrder[0]
|
||||
@@ -4631,7 +4636,8 @@ describe('registerWorktreeHandlers', () => {
|
||||
expect(killAllProcessesForWorktreeMock).toHaveBeenCalledWith(
|
||||
'repo-1::/workspace/feature-wt',
|
||||
expect.objectContaining({
|
||||
localProvider: expect.anything()
|
||||
localProvider: expect.anything(),
|
||||
onPtyStopped: clearProviderPtyStateMock
|
||||
})
|
||||
)
|
||||
expect(removeWorktreeMock).toHaveBeenCalled()
|
||||
|
||||
@@ -76,7 +76,7 @@ import {
|
||||
} from './filesystem-auth'
|
||||
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
|
||||
import { killAllProcessesForWorktree } from '../runtime/worktree-teardown'
|
||||
import { getLocalPtyProvider } from './pty'
|
||||
import { clearProviderPtyState, getLocalPtyProvider } from './pty'
|
||||
import { removeWorktreeSymlinks } from './worktree-symlinks'
|
||||
import { track } from '../telemetry/client'
|
||||
import { getCohortAtEmit } from '../telemetry/cohort-classifier'
|
||||
@@ -1037,7 +1037,8 @@ export function registerWorktreeHandlers(
|
||||
// remove step to close shells; sweep PTYs before dropping metadata.
|
||||
await killAllProcessesForWorktree(args.worktreeId, {
|
||||
runtime,
|
||||
localProvider: getLocalPtyProvider()
|
||||
localProvider: getLocalPtyProvider(),
|
||||
onPtyStopped: clearProviderPtyState
|
||||
}).catch((err) => {
|
||||
console.warn(`[worktree-teardown] failed for ${args.worktreeId}:`, err)
|
||||
})
|
||||
@@ -1238,7 +1239,8 @@ export function registerWorktreeHandlers(
|
||||
// git-level removal so shells cannot keep the directory busy.
|
||||
await killAllProcessesForWorktree(args.worktreeId, {
|
||||
runtime,
|
||||
localProvider: getLocalPtyProvider()
|
||||
localProvider: getLocalPtyProvider(),
|
||||
onPtyStopped: clearProviderPtyState
|
||||
})
|
||||
.then((r) => {
|
||||
const total = r.runtimeStopped + r.providerStopped + r.registryStopped
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
/* eslint-disable max-lines -- Why: browser runtime command tests share one
|
||||
mocked BrowserManager/agent-browser bridge so page wake and registration
|
||||
ordering regressions stay in one boundary-focused suite. */
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentBrowserBridge } from '../browser/agent-browser-bridge'
|
||||
import type { RuntimeBrowserCommandHost } from './orca-runtime-browser'
|
||||
|
||||
const { webContentsFromIdMock, startBrowserScreencastMock, waitForWorktreeTabRegistrationMock } =
|
||||
vi.hoisted(() => ({
|
||||
webContentsFromIdMock: vi.fn(),
|
||||
startBrowserScreencastMock: vi.fn(),
|
||||
waitForWorktreeTabRegistrationMock: vi.fn()
|
||||
}))
|
||||
const {
|
||||
ipcMainOnMock,
|
||||
ipcMainRemoveListenerMock,
|
||||
webContentsFromIdMock,
|
||||
startBrowserScreencastMock,
|
||||
waitForTabRegistrationMock,
|
||||
waitForWorktreeTabRegistrationMock
|
||||
} = vi.hoisted(() => ({
|
||||
ipcMainOnMock: vi.fn(),
|
||||
ipcMainRemoveListenerMock: vi.fn(),
|
||||
webContentsFromIdMock: vi.fn(),
|
||||
startBrowserScreencastMock: vi.fn(),
|
||||
waitForTabRegistrationMock: vi.fn(),
|
||||
waitForWorktreeTabRegistrationMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
ipcMain: { on: vi.fn(), removeListener: vi.fn() },
|
||||
ipcMain: { on: ipcMainOnMock, removeListener: ipcMainRemoveListenerMock },
|
||||
webContents: { fromId: webContentsFromIdMock }
|
||||
}))
|
||||
|
||||
@@ -19,7 +31,7 @@ vi.mock('../browser/browser-screencast-stream', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('../ipc/browser', () => ({
|
||||
waitForTabRegistration: vi.fn(),
|
||||
waitForTabRegistration: waitForTabRegistrationMock,
|
||||
waitForWorktreeTabRegistration: waitForWorktreeTabRegistrationMock
|
||||
}))
|
||||
|
||||
@@ -62,8 +74,12 @@ function createHost(overrides: Partial<RuntimeBrowserCommandHost> = {}): Runtime
|
||||
|
||||
describe('RuntimeBrowserCommands browser screencast', () => {
|
||||
beforeEach(() => {
|
||||
ipcMainOnMock.mockReset()
|
||||
ipcMainRemoveListenerMock.mockReset()
|
||||
webContentsFromIdMock.mockReset()
|
||||
startBrowserScreencastMock.mockReset()
|
||||
waitForTabRegistrationMock.mockReset()
|
||||
waitForTabRegistrationMock.mockResolvedValue(undefined)
|
||||
waitForWorktreeTabRegistrationMock.mockReset()
|
||||
waitForWorktreeTabRegistrationMock.mockResolvedValue(undefined)
|
||||
})
|
||||
@@ -89,6 +105,28 @@ describe('RuntimeBrowserCommands browser screencast', () => {
|
||||
expect(bridge.tabList).toHaveBeenCalledWith('wt-1')
|
||||
})
|
||||
|
||||
it('re-wakes an explicit worktree when the only registered browser tab is stale', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => true })
|
||||
const send = vi.fn()
|
||||
const bridge = {
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-stale', 404]])),
|
||||
tabList: vi.fn(() => ({ tabs: [] }))
|
||||
} as unknown as AgentBrowserBridge
|
||||
const commands = new RuntimeBrowserCommands(
|
||||
createHost({
|
||||
getAgentBrowserBridge: () => bridge,
|
||||
getAuthoritativeWindow: vi.fn(() => ({ webContents: { send } }) as never)
|
||||
})
|
||||
)
|
||||
|
||||
await commands.browserTabList({ worktree: 'id:wt-1' })
|
||||
|
||||
expect(send).toHaveBeenCalledWith('browser:activateView', { worktreeId: 'wt-1' })
|
||||
expect(waitForWorktreeTabRegistrationMock).toHaveBeenCalledWith('wt-1')
|
||||
expect(bridge.tabList).toHaveBeenCalledWith('wt-1')
|
||||
})
|
||||
|
||||
it('waits for any browser registration after requesting a hidden mount without worktree scope', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
const send = vi.fn()
|
||||
@@ -110,6 +148,204 @@ describe('RuntimeBrowserCommands browser screencast', () => {
|
||||
expect(bridge.tabList).toHaveBeenCalledWith(undefined)
|
||||
})
|
||||
|
||||
it('creates the first explicit-worktree browser tab without waiting for an existing registration', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
const send = vi.fn((channel: string, data: { requestId: string }) => {
|
||||
expect(channel).toBe('browser:requestTabCreate')
|
||||
const handler = ipcMainOnMock.mock.calls.find(
|
||||
([eventName]) => eventName === 'browser:tabCreateReply'
|
||||
)?.[1] as
|
||||
| ((
|
||||
event: unknown,
|
||||
reply: { requestId: string; browserPageId?: string; error?: string }
|
||||
) => void)
|
||||
| undefined
|
||||
handler?.({} as never, { requestId: data.requestId, browserPageId: 'page-new' })
|
||||
})
|
||||
const bridge = {
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-new', 101]])),
|
||||
getActivePageId: vi.fn(() => 'page-new'),
|
||||
setActiveTab: vi.fn(),
|
||||
tabList: vi.fn(() => ({ tabs: [] }))
|
||||
} as unknown as AgentBrowserBridge
|
||||
const commands = new RuntimeBrowserCommands(
|
||||
createHost({
|
||||
getAgentBrowserBridge: () => bridge,
|
||||
getAvailableAuthoritativeWindow: vi.fn(() => ({}) as never),
|
||||
getAuthoritativeWindow: vi.fn(() => ({ webContents: { send } }) as never)
|
||||
})
|
||||
)
|
||||
|
||||
await expect(
|
||||
commands.browserTabCreate({ worktree: 'id:wt-1', url: 'about:blank' })
|
||||
).resolves.toEqual({ browserPageId: 'page-new' })
|
||||
|
||||
expect(waitForWorktreeTabRegistrationMock).not.toHaveBeenCalled()
|
||||
expect(send).toHaveBeenCalledWith(
|
||||
'browser:requestTabCreate',
|
||||
expect.objectContaining({ url: 'about:blank', worktreeId: 'wt-1' })
|
||||
)
|
||||
expect(waitForTabRegistrationMock).toHaveBeenCalledWith('page-new')
|
||||
expect(bridge.setActiveTab).toHaveBeenCalledWith(101, 'wt-1')
|
||||
})
|
||||
|
||||
it('wakes the requested page instead of the first worktree tab for page-scoped commands', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => true })
|
||||
const send = vi.fn()
|
||||
const snapshot = vi.fn(() => ({
|
||||
origin: 'about:blank',
|
||||
refs: {},
|
||||
snapshot: '(empty page)',
|
||||
browserPageId: 'page-target'
|
||||
}))
|
||||
const bridge = {
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-target', 101]])),
|
||||
getActivePageId: vi.fn(() => 'page-other'),
|
||||
snapshot
|
||||
} as unknown as AgentBrowserBridge
|
||||
const commands = new RuntimeBrowserCommands(
|
||||
createHost({
|
||||
getAgentBrowserBridge: () => bridge,
|
||||
getAuthoritativeWindow: vi.fn(() => ({ webContents: { send } }) as never)
|
||||
})
|
||||
)
|
||||
|
||||
await expect(
|
||||
commands.browserSnapshot({ worktree: 'id:wt-1', page: 'page-target' })
|
||||
).resolves.toEqual({
|
||||
origin: 'about:blank',
|
||||
refs: {},
|
||||
snapshot: '(empty page)',
|
||||
browserPageId: 'page-target'
|
||||
})
|
||||
|
||||
expect(send).toHaveBeenCalledWith('browser:activateView', {
|
||||
worktreeId: 'wt-1',
|
||||
browserPageId: 'page-target'
|
||||
})
|
||||
expect(waitForTabRegistrationMock).toHaveBeenCalledWith('page-target')
|
||||
expect(waitForWorktreeTabRegistrationMock).not.toHaveBeenCalled()
|
||||
expect(snapshot).toHaveBeenCalledWith('wt-1', 'page-target')
|
||||
})
|
||||
|
||||
it('wakes the requested page before showing page-scoped tab metadata', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => true })
|
||||
const send = vi.fn()
|
||||
const bridge = {
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-target', 101]])),
|
||||
getActivePageId: vi.fn(() => 'page-other'),
|
||||
tabList: vi.fn(() => ({
|
||||
tabs: [
|
||||
{
|
||||
browserPageId: 'page-target',
|
||||
index: 1,
|
||||
url: 'about:blank',
|
||||
title: 'Target',
|
||||
active: false
|
||||
}
|
||||
]
|
||||
}))
|
||||
} as unknown as AgentBrowserBridge
|
||||
const commands = new RuntimeBrowserCommands(
|
||||
createHost({
|
||||
getAgentBrowserBridge: () => bridge,
|
||||
getAuthoritativeWindow: vi.fn(() => ({ webContents: { send } }) as never)
|
||||
})
|
||||
)
|
||||
|
||||
const result = await commands.browserTabShow({ worktree: 'id:wt-1', page: 'page-target' })
|
||||
|
||||
expect(send).toHaveBeenCalledWith('browser:activateView', {
|
||||
worktreeId: 'wt-1',
|
||||
browserPageId: 'page-target'
|
||||
})
|
||||
expect(waitForTabRegistrationMock).toHaveBeenCalledWith('page-target')
|
||||
expect(waitForWorktreeTabRegistrationMock).not.toHaveBeenCalled()
|
||||
expect(result.tab.browserPageId).toBe('page-target')
|
||||
})
|
||||
|
||||
it('wakes the requested page before showing page-scoped profile metadata', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => true })
|
||||
const send = vi.fn()
|
||||
const bridge = {
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-target', 101]])),
|
||||
getActivePageId: vi.fn(() => 'page-other'),
|
||||
tabList: vi.fn(() => ({
|
||||
tabs: [
|
||||
{
|
||||
browserPageId: 'page-target',
|
||||
index: 1,
|
||||
url: 'about:blank',
|
||||
title: 'Target',
|
||||
active: false
|
||||
}
|
||||
]
|
||||
}))
|
||||
} as unknown as AgentBrowserBridge
|
||||
const commands = new RuntimeBrowserCommands(
|
||||
createHost({
|
||||
getAgentBrowserBridge: () => bridge,
|
||||
getAuthoritativeWindow: vi.fn(() => ({ webContents: { send } }) as never)
|
||||
})
|
||||
)
|
||||
|
||||
const result = await commands.browserTabProfileShow({
|
||||
worktree: 'id:wt-1',
|
||||
page: 'page-target'
|
||||
})
|
||||
|
||||
expect(send).toHaveBeenCalledWith('browser:activateView', {
|
||||
worktreeId: 'wt-1',
|
||||
browserPageId: 'page-target'
|
||||
})
|
||||
expect(waitForTabRegistrationMock).toHaveBeenCalledWith('page-target')
|
||||
expect(waitForWorktreeTabRegistrationMock).not.toHaveBeenCalled()
|
||||
expect(result.browserPageId).toBe('page-target')
|
||||
})
|
||||
|
||||
it('wakes the requested page before closing a page-scoped tab', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => true })
|
||||
const send = vi.fn((channel: string, data: { requestId?: string }) => {
|
||||
if (channel !== 'browser:requestTabClose') {
|
||||
return
|
||||
}
|
||||
const handler = ipcMainOnMock.mock.calls.find(
|
||||
([eventName]) => eventName === 'browser:tabCloseReply'
|
||||
)?.[1] as ((event: unknown, reply: { requestId: string; error?: string }) => void) | undefined
|
||||
handler?.({} as never, { requestId: data.requestId ?? '' })
|
||||
})
|
||||
const bridge = {
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-target', 101]])),
|
||||
getActivePageId: vi.fn(() => 'page-other'),
|
||||
getActiveWebContentsId: vi.fn(() => 101)
|
||||
} as unknown as AgentBrowserBridge
|
||||
const commands = new RuntimeBrowserCommands(
|
||||
createHost({
|
||||
getAgentBrowserBridge: () => bridge,
|
||||
getAuthoritativeWindow: vi.fn(() => ({ webContents: { send } }) as never)
|
||||
})
|
||||
)
|
||||
|
||||
await expect(
|
||||
commands.browserTabClose({ worktree: 'id:wt-1', page: 'page-target' })
|
||||
).resolves.toEqual({ closed: true })
|
||||
|
||||
expect(send).toHaveBeenCalledWith('browser:activateView', {
|
||||
worktreeId: 'wt-1',
|
||||
browserPageId: 'page-target'
|
||||
})
|
||||
expect(waitForTabRegistrationMock).toHaveBeenCalledWith('page-target')
|
||||
expect(waitForWorktreeTabRegistrationMock).not.toHaveBeenCalled()
|
||||
expect(send).toHaveBeenCalledWith(
|
||||
'browser:requestTabClose',
|
||||
expect.objectContaining({ tabId: 'page-target', worktreeId: 'wt-1' })
|
||||
)
|
||||
})
|
||||
|
||||
it('lets a new same-page stream take over an active stale stream', async () => {
|
||||
const { RuntimeBrowserCommands } = await import('./orca-runtime-browser')
|
||||
webContentsFromIdMock.mockReturnValue({ isDestroyed: () => false })
|
||||
|
||||
@@ -159,6 +159,32 @@ export class RuntimeBrowserCommands {
|
||||
return bridge
|
||||
}
|
||||
|
||||
private hasLiveRegisteredBrowserTab(
|
||||
bridge: AgentBrowserBridge,
|
||||
worktreeId: string | undefined
|
||||
): boolean {
|
||||
for (const [, webContentsId] of bridge.getRegisteredTabs(worktreeId)) {
|
||||
const guest = webContents.fromId(webContentsId)
|
||||
if (guest && !guest.isDestroyed()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private hasLiveRegisteredBrowserPage(
|
||||
bridge: AgentBrowserBridge,
|
||||
worktreeId: string | undefined,
|
||||
browserPageId: string
|
||||
): boolean {
|
||||
const webContentsId = bridge.getRegisteredTabs(worktreeId).get(browserPageId)
|
||||
if (webContentsId == null) {
|
||||
return false
|
||||
}
|
||||
const guest = webContents.fromId(webContentsId)
|
||||
return Boolean(guest && !guest.isDestroyed())
|
||||
}
|
||||
|
||||
// Why: the CLI sends worktree selectors (e.g. "path:/Users/...") but the
|
||||
// bridge stores worktreeIds in "repoId::path" format (from the renderer's
|
||||
// Zustand store). This helper resolves the selector to the store-compatible
|
||||
@@ -169,7 +195,7 @@ export class RuntimeBrowserCommands {
|
||||
// Without --worktree, we still need to activate the view so persisted tabs
|
||||
// become operable via registerGuest.
|
||||
const bridge = this.host.getAgentBrowserBridge()
|
||||
if (bridge && bridge.getRegisteredTabs().size === 0) {
|
||||
if (bridge && !this.hasLiveRegisteredBrowserTab(bridge, undefined)) {
|
||||
try {
|
||||
await this.ensureBrowserWorktreeActive(undefined)
|
||||
} catch {
|
||||
@@ -185,7 +211,7 @@ export class RuntimeBrowserCommands {
|
||||
// activation step remains best-effort because missing windows during tests
|
||||
// or startup should not erase the validated worktree target itself.
|
||||
const bridge = this.host.getAgentBrowserBridge()
|
||||
if (bridge && bridge.getRegisteredTabs(worktreeId).size === 0) {
|
||||
if (bridge && !this.hasLiveRegisteredBrowserTab(bridge, worktreeId)) {
|
||||
try {
|
||||
await this.ensureBrowserWorktreeActive(worktreeId)
|
||||
} catch {
|
||||
@@ -207,13 +233,23 @@ export class RuntimeBrowserCommands {
|
||||
}
|
||||
}
|
||||
|
||||
const worktreeId = params.worktree
|
||||
? (await this.host.resolveWorktreeSelector(params.worktree)).id
|
||||
: undefined
|
||||
const bridge = this.host.getAgentBrowserBridge()
|
||||
if (bridge && !this.hasLiveRegisteredBrowserPage(bridge, worktreeId, browserPageId)) {
|
||||
try {
|
||||
await this.ensureBrowserPageActive(worktreeId, browserPageId)
|
||||
} catch {
|
||||
// Fall through with the explicit page target so downstream routing
|
||||
// returns the existing clear "tab not found" error if wake fails.
|
||||
}
|
||||
}
|
||||
return {
|
||||
// Why: explicit browserPageId is already a stable tab identity, so we do
|
||||
// not auto-resolve cwd worktree scoping on top of it. Only honor an
|
||||
// explicit --worktree when the caller asked for that extra validation.
|
||||
worktreeId: params.worktree
|
||||
? await this.resolveBrowserWorktreeId(params.worktree)
|
||||
: undefined,
|
||||
worktreeId,
|
||||
browserPageId
|
||||
}
|
||||
}
|
||||
@@ -258,6 +294,18 @@ export class RuntimeBrowserCommands {
|
||||
await waitForWorktreeTabRegistration(worktreeId)
|
||||
}
|
||||
|
||||
private async ensureBrowserPageActive(
|
||||
worktreeId: string | undefined,
|
||||
browserPageId: string
|
||||
): Promise<void> {
|
||||
const win = this.host.getAuthoritativeWindow()
|
||||
win.webContents.send(
|
||||
'browser:activateView',
|
||||
worktreeId ? { worktreeId, browserPageId } : { browserPageId }
|
||||
)
|
||||
await waitForTabRegistration(browserPageId)
|
||||
}
|
||||
|
||||
// Why: agent-browser drives navigation via CDP, which bypasses Electron's
|
||||
// webview event system. The renderer's did-navigate / page-title-updated
|
||||
// listeners never fire, leaving the Zustand store (and thus the Orca UI's
|
||||
@@ -571,8 +619,8 @@ export class RuntimeBrowserCommands {
|
||||
}
|
||||
|
||||
async browserTabShow(params: { page: string; worktree?: string }): Promise<BrowserTabShowResult> {
|
||||
const worktreeId = await this.resolveBrowserWorktreeId(params.worktree)
|
||||
return { tab: this.describeBrowserTab(params.page, worktreeId) }
|
||||
const target = await this.resolveBrowserCommandTarget(params)
|
||||
return { tab: this.describeBrowserTab(params.page, target.worktreeId) }
|
||||
}
|
||||
|
||||
async browserTabCurrent(params: { worktree?: string }): Promise<BrowserTabCurrentResult> {
|
||||
@@ -1404,8 +1452,8 @@ export class RuntimeBrowserCommands {
|
||||
page: string
|
||||
worktree?: string
|
||||
}): Promise<BrowserTabProfileShowResult> {
|
||||
const worktreeId = await this.resolveBrowserWorktreeId(params.worktree)
|
||||
const tab = this.describeBrowserTab(params.page, worktreeId)
|
||||
const target = await this.resolveBrowserCommandTarget(params)
|
||||
const tab = this.describeBrowserTab(params.page, target.worktreeId)
|
||||
return {
|
||||
browserPageId: tab.browserPageId,
|
||||
worktreeId: tab.worktreeId ?? null,
|
||||
@@ -1545,7 +1593,12 @@ export class RuntimeBrowserCommands {
|
||||
worktree?: string
|
||||
}): Promise<{ closed: boolean }> {
|
||||
const bridge = this.requireAgentBrowserBridge()
|
||||
const worktreeId = await this.resolveBrowserWorktreeId(params.worktree)
|
||||
const pageTarget =
|
||||
typeof params.page === 'string' && params.page.length > 0
|
||||
? await this.resolveBrowserCommandTarget({ worktree: params.worktree, page: params.page })
|
||||
: null
|
||||
const worktreeId =
|
||||
pageTarget?.worktreeId ?? (await this.resolveBrowserWorktreeId(params.worktree))
|
||||
|
||||
let tabId: string | null = null
|
||||
if (typeof params.page === 'string' && params.page.length > 0) {
|
||||
@@ -1652,10 +1705,6 @@ export class RuntimeBrowserCommands {
|
||||
const win = this.host.getAuthoritativeWindow()
|
||||
const requestId = randomUUID()
|
||||
|
||||
if (worktreeId) {
|
||||
await this.ensureBrowserWorktreeActive(worktreeId)
|
||||
}
|
||||
|
||||
const browserPageId = await new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
ipcMain.removeListener('browser:tabCreateReply', handler)
|
||||
|
||||
@@ -65,6 +65,7 @@ const electronMocks = vi.hoisted(() => {
|
||||
}
|
||||
return {
|
||||
BrowserWindow: { fromId: vi.fn((_id: number): unknown => null) },
|
||||
webContents: { fromId: vi.fn((_id: number): unknown => null) },
|
||||
ipcMain,
|
||||
app: { getPath: vi.fn(() => '/tmp') }
|
||||
}
|
||||
@@ -338,6 +339,8 @@ afterEach(() => {
|
||||
advertisedUrlWatcher.clear()
|
||||
electronMocks.BrowserWindow.fromId.mockReset()
|
||||
electronMocks.BrowserWindow.fromId.mockReturnValue(null)
|
||||
electronMocks.webContents.fromId.mockReset()
|
||||
electronMocks.webContents.fromId.mockReturnValue(null)
|
||||
electronMocks.ipcMain.on.mockClear()
|
||||
electronMocks.ipcMain.removeListener.mockClear()
|
||||
electronMocks.ipcMain.emit.mockClear()
|
||||
@@ -10864,8 +10867,15 @@ describe('OrcaRuntimeService', () => {
|
||||
})
|
||||
|
||||
describe('browser page targeting', () => {
|
||||
function mockLiveBrowserGuest(): void {
|
||||
electronMocks.webContents.fromId.mockReturnValue({
|
||||
isDestroyed: () => false
|
||||
})
|
||||
}
|
||||
|
||||
it('passes explicit page ids through without resolving the current worktree', async () => {
|
||||
vi.mocked(listWorktrees).mockClear()
|
||||
mockLiveBrowserGuest()
|
||||
const runtime = createRuntime()
|
||||
const snapshotMock = vi.fn().mockResolvedValue({
|
||||
browserPageId: 'page-1',
|
||||
@@ -10876,7 +10886,8 @@ describe('OrcaRuntimeService', () => {
|
||||
})
|
||||
|
||||
runtime.setAgentBrowserBridge({
|
||||
snapshot: snapshotMock
|
||||
snapshot: snapshotMock,
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-1', 1]]))
|
||||
} as never)
|
||||
|
||||
const result = await runtime.browserSnapshot({ page: 'page-1' })
|
||||
@@ -10888,6 +10899,7 @@ describe('OrcaRuntimeService', () => {
|
||||
|
||||
it('resolves explicit worktree selectors when page ids are also provided', async () => {
|
||||
vi.mocked(listWorktrees).mockClear()
|
||||
mockLiveBrowserGuest()
|
||||
const runtime = createRuntime()
|
||||
const snapshotMock = vi.fn().mockResolvedValue({
|
||||
browserPageId: 'page-1',
|
||||
@@ -10911,6 +10923,7 @@ describe('OrcaRuntimeService', () => {
|
||||
})
|
||||
|
||||
it('routes tab switch and capture start by explicit page id', async () => {
|
||||
mockLiveBrowserGuest()
|
||||
const runtime = createRuntime()
|
||||
const tabSwitchMock = vi.fn().mockResolvedValue({
|
||||
switched: 2,
|
||||
@@ -10922,7 +10935,8 @@ describe('OrcaRuntimeService', () => {
|
||||
|
||||
runtime.setAgentBrowserBridge({
|
||||
tabSwitch: tabSwitchMock,
|
||||
captureStart: captureStartMock
|
||||
captureStart: captureStartMock,
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-2', 2]]))
|
||||
} as never)
|
||||
|
||||
await expect(runtime.browserTabSwitch({ page: 'page-2' })).resolves.toEqual({
|
||||
@@ -10937,13 +10951,17 @@ describe('OrcaRuntimeService', () => {
|
||||
})
|
||||
|
||||
it('accepts focus on tab switch without altering bridge args (focus is main-side concern)', async () => {
|
||||
mockLiveBrowserGuest()
|
||||
const runtime = createRuntime()
|
||||
const tabSwitchMock = vi.fn().mockResolvedValue({
|
||||
switched: 0,
|
||||
browserPageId: 'page-1'
|
||||
})
|
||||
|
||||
runtime.setAgentBrowserBridge({ tabSwitch: tabSwitchMock } as never)
|
||||
runtime.setAgentBrowserBridge({
|
||||
tabSwitch: tabSwitchMock,
|
||||
getRegisteredTabs: vi.fn(() => new Map([['page-1', 1]]))
|
||||
} as never)
|
||||
|
||||
await expect(runtime.browserTabSwitch({ page: 'page-1', focus: true })).resolves.toEqual({
|
||||
switched: 0,
|
||||
@@ -10956,6 +10974,7 @@ describe('OrcaRuntimeService', () => {
|
||||
|
||||
it('does not silently drop invalid explicit worktree selectors for page-targeted commands', async () => {
|
||||
vi.mocked(listWorktrees).mockResolvedValue(MOCK_GIT_WORKTREES)
|
||||
mockLiveBrowserGuest()
|
||||
const runtime = createRuntime()
|
||||
const snapshotMock = vi.fn()
|
||||
|
||||
@@ -10992,6 +11011,7 @@ describe('OrcaRuntimeService', () => {
|
||||
|
||||
it('rejects closing an unknown page id instead of treating it as success', async () => {
|
||||
vi.mocked(listWorktrees).mockResolvedValue(MOCK_GIT_WORKTREES)
|
||||
mockLiveBrowserGuest()
|
||||
const runtime = createRuntime()
|
||||
|
||||
runtime.setAgentBrowserBridge({
|
||||
@@ -11006,6 +11026,7 @@ describe('OrcaRuntimeService', () => {
|
||||
})
|
||||
|
||||
it('rejects closing a page outside the explicitly scoped worktree', async () => {
|
||||
mockLiveBrowserGuest()
|
||||
vi.mocked(listWorktrees).mockResolvedValue([
|
||||
...MOCK_GIT_WORKTREES,
|
||||
{
|
||||
@@ -11139,9 +11160,11 @@ describe('OrcaRuntimeService', () => {
|
||||
{ id: `${TEST_WORKTREE_ID}@@aaaaaaaa`, cwd: '/tmp', title: 'shell' }
|
||||
])
|
||||
let currentProvider: ReturnType<typeof createProviderStub> = preDaemonProvider
|
||||
const onPtyStopped = vi.fn()
|
||||
|
||||
const runtime = new OrcaRuntimeService(store, undefined, {
|
||||
getLocalProvider: () => currentProvider as never
|
||||
getLocalProvider: () => currentProvider as never,
|
||||
onPtyStopped
|
||||
})
|
||||
vi.mocked(removeWorktree).mockResolvedValue({})
|
||||
|
||||
@@ -11155,6 +11178,7 @@ describe('OrcaRuntimeService', () => {
|
||||
expect(postDaemonProvider.shutdown).toHaveBeenCalledWith(`${TEST_WORKTREE_ID}@@aaaaaaaa`, {
|
||||
immediate: true
|
||||
})
|
||||
expect(onPtyStopped).toHaveBeenCalledWith(`${TEST_WORKTREE_ID}@@aaaaaaaa`)
|
||||
// The pre-daemon provider must not have been consulted for the kill.
|
||||
expect(preDaemonProvider.shutdown).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -1419,6 +1419,7 @@ export class OrcaRuntimeService {
|
||||
private removeManagedWorktreeInFlight = new Map<string, RuntimeWorktreeRemovalInFlight>()
|
||||
private preservedBranchCleanupByWorktreeId = new Map<string, PreservedBranchCleanupTarget>()
|
||||
private readonly getLocalProviderFn: (() => IPtyProvider) | null
|
||||
private readonly onPtyStopped: ((ptyId: string) => void) | null
|
||||
private accountServices: RuntimeAccountServices | null = null
|
||||
private commitMessageAgentEnv: CommitMessageAgentEnvironmentResolvers | null = null
|
||||
private automationService: AutomationService | null = null
|
||||
@@ -1436,7 +1437,7 @@ export class OrcaRuntimeService {
|
||||
constructor(
|
||||
store: RuntimeStore | null = null,
|
||||
stats?: StatsCollector,
|
||||
deps?: { getLocalProvider?: () => IPtyProvider }
|
||||
deps?: { getLocalProvider?: () => IPtyProvider; onPtyStopped?: (ptyId: string) => void }
|
||||
) {
|
||||
this.store = store
|
||||
if (stats) {
|
||||
@@ -1450,6 +1451,7 @@ export class OrcaRuntimeService {
|
||||
// lazily via thunk so teardown always sees the currently-installed
|
||||
// provider (design §4.3 wire-up).
|
||||
this.getLocalProviderFn = deps?.getLocalProvider ?? null
|
||||
this.onPtyStopped = deps?.onPtyStopped ?? null
|
||||
}
|
||||
|
||||
getLocalProvider(): IPtyProvider | null {
|
||||
@@ -9241,7 +9243,8 @@ export class OrcaRuntimeService {
|
||||
// would otherwise be swept; tear them down before hiding the workspace.
|
||||
await killAllProcessesForWorktree(removalTarget.id, {
|
||||
runtime: this,
|
||||
localProvider
|
||||
localProvider,
|
||||
onPtyStopped: this.onPtyStopped ?? undefined
|
||||
}).catch((err) => {
|
||||
console.warn(`[worktree-teardown] failed for ${removalTarget.id}:`, err)
|
||||
})
|
||||
@@ -9417,7 +9420,8 @@ export class OrcaRuntimeService {
|
||||
// closes the headless-CLI leak for confirmed-removable worktrees.
|
||||
await killAllProcessesForWorktree(removalTarget.id, {
|
||||
runtime: this,
|
||||
localProvider
|
||||
localProvider,
|
||||
onPtyStopped: this.onPtyStopped ?? undefined
|
||||
})
|
||||
.then((r) => {
|
||||
const total = r.runtimeStopped + r.providerStopped + r.registryStopped
|
||||
|
||||
@@ -53,8 +53,9 @@ describe('killAllProcessesForWorktree', () => {
|
||||
{ ptyId: 'w1-registry-1', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 100 },
|
||||
{ ptyId: 'w2-registry-2', worktreeId: 'w2', sessionId: null, paneKey: null, pid: 101 }
|
||||
])
|
||||
const onPtyStopped = vi.fn()
|
||||
|
||||
const result = await killAllProcessesForWorktree('w1', { localProvider })
|
||||
const result = await killAllProcessesForWorktree('w1', { localProvider, onPtyStopped })
|
||||
|
||||
expect(result.runtimeStopped).toBe(0)
|
||||
expect(result.providerStopped).toBe(1)
|
||||
@@ -64,6 +65,10 @@ describe('killAllProcessesForWorktree', () => {
|
||||
expect(localProvider.shutdown).toHaveBeenCalledWith('w1-registry-1', { immediate: true })
|
||||
expect(localProvider.shutdown).not.toHaveBeenCalledWith('w2@@efef5678', { immediate: true })
|
||||
expect(localProvider.shutdown).not.toHaveBeenCalledWith('w2-registry-2', { immediate: true })
|
||||
expect(onPtyStopped).toHaveBeenCalledWith('w1@@abcd1234')
|
||||
expect(onPtyStopped).toHaveBeenCalledWith('w1-registry-1')
|
||||
expect(onPtyStopped).not.toHaveBeenCalledWith('w2@@efef5678')
|
||||
expect(onPtyStopped).not.toHaveBeenCalledWith('w2-registry-2')
|
||||
})
|
||||
|
||||
it('skips the daemon prefix sweep safely when the provider uses numeric ids', async () => {
|
||||
@@ -75,14 +80,16 @@ describe('killAllProcessesForWorktree', () => {
|
||||
listRegisteredPtysMock.mockReturnValue([
|
||||
{ ptyId: '1', worktreeId: 'w1', sessionId: null, paneKey: null, pid: 200 }
|
||||
])
|
||||
const onPtyStopped = vi.fn()
|
||||
|
||||
const result = await killAllProcessesForWorktree('w1', { localProvider })
|
||||
const result = await killAllProcessesForWorktree('w1', { localProvider, onPtyStopped })
|
||||
|
||||
// Prefix sweep must kill nothing; registry sweep must still fire.
|
||||
expect(result.providerStopped).toBe(0)
|
||||
expect(result.registryStopped).toBe(1)
|
||||
expect(localProvider.shutdown).toHaveBeenCalledWith('1', { immediate: true })
|
||||
expect(localProvider.shutdown).toHaveBeenCalledTimes(1)
|
||||
expect(onPtyStopped).toHaveBeenCalledWith('1')
|
||||
})
|
||||
|
||||
it('best-effort: swallows errors from listProcesses and shutdown', async () => {
|
||||
@@ -102,6 +109,21 @@ describe('killAllProcessesForWorktree', () => {
|
||||
expect(result.registryStopped).toBe(0)
|
||||
})
|
||||
|
||||
it('does not let cleanup hook failures abort teardown', async () => {
|
||||
const localProvider = createProviderStub(async () => [
|
||||
{ id: 'w1@@aaaa', cwd: '/tmp/w1', title: 'shell' }
|
||||
])
|
||||
listRegisteredPtysMock.mockReturnValue([])
|
||||
const onPtyStopped = vi.fn(() => {
|
||||
throw new Error('cleanup failed')
|
||||
})
|
||||
|
||||
const result = await killAllProcessesForWorktree('w1', { localProvider, onPtyStopped })
|
||||
|
||||
expect(result.providerStopped).toBe(1)
|
||||
expect(onPtyStopped).toHaveBeenCalledWith('w1@@aaaa')
|
||||
})
|
||||
|
||||
it('does not carry state between successive calls with distinct providers', async () => {
|
||||
// Guards against a future refactor that memoises provider or registry
|
||||
// reads inside the helper.
|
||||
|
||||
@@ -5,6 +5,7 @@ import { listRegisteredPtys } from '../memory/pty-registry'
|
||||
export type WorktreeTeardownDeps = {
|
||||
runtime?: OrcaRuntimeService
|
||||
localProvider: IPtyProvider
|
||||
onPtyStopped?: (ptyId: string) => void
|
||||
}
|
||||
|
||||
export type WorktreeTeardownResult = {
|
||||
@@ -50,13 +51,25 @@ export async function killAllProcessesForWorktree(
|
||||
result.runtimeStopped = r.stopped
|
||||
}
|
||||
|
||||
result.providerStopped = await sweepProviderByPrefix(worktreeId, deps.localProvider)
|
||||
result.registryStopped = await sweepRegistryForWorktree(worktreeId, deps.localProvider)
|
||||
result.providerStopped = await sweepProviderByPrefix(
|
||||
worktreeId,
|
||||
deps.localProvider,
|
||||
deps.onPtyStopped
|
||||
)
|
||||
result.registryStopped = await sweepRegistryForWorktree(
|
||||
worktreeId,
|
||||
deps.localProvider,
|
||||
deps.onPtyStopped
|
||||
)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
async function sweepProviderByPrefix(worktreeId: string, provider: IPtyProvider): Promise<number> {
|
||||
async function sweepProviderByPrefix(
|
||||
worktreeId: string,
|
||||
provider: IPtyProvider,
|
||||
onPtyStopped?: (ptyId: string) => void
|
||||
): Promise<number> {
|
||||
const prefix = `${worktreeId}@@`
|
||||
const sessions = await provider.listProcesses().catch(() => [])
|
||||
let killed = 0
|
||||
@@ -66,6 +79,7 @@ async function sweepProviderByPrefix(worktreeId: string, provider: IPtyProvider)
|
||||
}
|
||||
try {
|
||||
await provider.shutdown(s.id, { immediate: true })
|
||||
clearStoppedPtyState(s.id, onPtyStopped)
|
||||
killed += 1
|
||||
} catch {
|
||||
// Already dead, or the backend dropped the session — treat as success.
|
||||
@@ -77,13 +91,15 @@ async function sweepProviderByPrefix(worktreeId: string, provider: IPtyProvider)
|
||||
|
||||
async function sweepRegistryForWorktree(
|
||||
worktreeId: string,
|
||||
localProvider: IPtyProvider
|
||||
localProvider: IPtyProvider,
|
||||
onPtyStopped?: (ptyId: string) => void
|
||||
): Promise<number> {
|
||||
const entries = listRegisteredPtys().filter((r) => r.worktreeId === worktreeId)
|
||||
let killed = 0
|
||||
for (const entry of entries) {
|
||||
try {
|
||||
await localProvider.shutdown(entry.ptyId, { immediate: true })
|
||||
clearStoppedPtyState(entry.ptyId, onPtyStopped)
|
||||
killed += 1
|
||||
} catch {
|
||||
/* ignore — best-effort */
|
||||
@@ -91,3 +107,16 @@ async function sweepRegistryForWorktree(
|
||||
}
|
||||
return killed
|
||||
}
|
||||
|
||||
function clearStoppedPtyState(ptyId: string, onPtyStopped?: (ptyId: string) => void): void {
|
||||
if (!onPtyStopped) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Why: daemon shutdown does not always fan a local pty:exit event back
|
||||
// through pty.ts, but removed worktrees must immediately drop memory rows.
|
||||
onPtyStopped(ptyId)
|
||||
} catch {
|
||||
/* cleanup is best-effort and must not block git-level removal */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,7 +357,9 @@ export type BrowserApi = {
|
||||
onNavigationUpdate: (
|
||||
callback: (event: { browserPageId: string; url: string; title: string }) => void
|
||||
) => () => void
|
||||
onActivateView: (callback: (data: { worktreeId?: string }) => void) => () => void
|
||||
onActivateView: (
|
||||
callback: (data: { worktreeId?: string; browserPageId?: string }) => void
|
||||
) => () => void
|
||||
onPaneFocus: (
|
||||
callback: (data: { worktreeId: string | null; browserPageId: string }) => void
|
||||
) => () => void
|
||||
|
||||
@@ -1823,9 +1823,13 @@ const api = {
|
||||
return () => ipcRenderer.removeListener('browser:navigation-update', listener)
|
||||
},
|
||||
|
||||
onActivateView: (callback: (data: { worktreeId?: string }) => void): (() => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, data: { worktreeId?: string }) =>
|
||||
callback(data)
|
||||
onActivateView: (
|
||||
callback: (data: { worktreeId?: string; browserPageId?: string }) => void
|
||||
): (() => void) => {
|
||||
const listener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
data: { worktreeId?: string; browserPageId?: string }
|
||||
) => callback(data)
|
||||
ipcRenderer.on('browser:activateView', listener)
|
||||
return () => ipcRenderer.removeListener('browser:activateView', listener)
|
||||
},
|
||||
|
||||
@@ -211,6 +211,11 @@ describe('useIpcEvents browser tab create routing', () => {
|
||||
}) => void)
|
||||
| null
|
||||
} = { current: null }
|
||||
const activateViewListenerRef: {
|
||||
current:
|
||||
| ((data: { worktreeId?: string | null; browserPageId?: string | null }) => void)
|
||||
| null
|
||||
} = { current: null }
|
||||
const state = {
|
||||
setUpdateStatus: vi.fn(),
|
||||
fetchRepos: vi.fn(),
|
||||
@@ -242,10 +247,14 @@ describe('useIpcEvents browser tab create routing', () => {
|
||||
settings: { terminalFontSize: 13 },
|
||||
activeBrowserTabIdByWorktree: { 'wt-1': 'workspace-active' },
|
||||
browserTabsByWorktree: {
|
||||
'wt-1': [{ id: 'workspace-active', activePageId: 'page-active', pageIds: ['page-active'] }]
|
||||
'wt-1': [{ id: 'workspace-active', activePageId: 'page-active', pageIds: ['page-active'] }],
|
||||
'wt-2': [
|
||||
{ id: 'workspace-detached', activePageId: 'page-detached', pageIds: ['page-detached'] }
|
||||
]
|
||||
},
|
||||
browserPagesByWorkspace: {
|
||||
'workspace-active': [{ id: 'page-active', worktreeId: 'wt-1' }]
|
||||
'workspace-active': [{ id: 'page-active', worktreeId: 'wt-1' }],
|
||||
'workspace-detached': [{ id: 'page-detached', worktreeId: 'wt-2' }]
|
||||
},
|
||||
unifiedTabsByWorktree: {
|
||||
'wt-1': [
|
||||
@@ -377,7 +386,10 @@ describe('useIpcEvents browser tab create routing', () => {
|
||||
onGuestLoadFailed: () => () => {},
|
||||
onOpenLinkInOrcaTab: () => () => {},
|
||||
onNavigationUpdate: () => () => {},
|
||||
onActivateView: () => () => {},
|
||||
onActivateView: (listener: NonNullable<typeof activateViewListenerRef.current>) => {
|
||||
activateViewListenerRef.current = listener
|
||||
return () => {}
|
||||
},
|
||||
onPaneFocus: () => () => {}
|
||||
},
|
||||
rateLimits: {
|
||||
@@ -424,6 +436,16 @@ describe('useIpcEvents browser tab create routing', () => {
|
||||
})
|
||||
expect(dispatchEvent).toHaveBeenCalled()
|
||||
expect(releaseBrowserAutomationVisibility).not.toHaveBeenCalled()
|
||||
|
||||
acquireBrowserAutomationVisibility.mockClear()
|
||||
dispatchEvent.mockClear()
|
||||
|
||||
activateViewListenerRef.current?.({ browserPageId: 'page-detached' })
|
||||
|
||||
expect(acquireBrowserAutomationVisibility).toHaveBeenCalledWith('page-detached')
|
||||
expect(dispatchEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ detail: { worktreeId: 'wt-2' } })
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -129,12 +129,38 @@ function releaseBrowserAutomationBootstrapLease(browserPageId: string): void {
|
||||
browserAutomationBootstrapLeaseByPageId.delete(browserPageId)
|
||||
}
|
||||
|
||||
function findBrowserPageWorktreeId(store: AppState, browserPageId: string): string | null {
|
||||
for (const [worktreeId, browserTabs] of Object.entries(store.browserTabsByWorktree)) {
|
||||
for (const workspace of browserTabs) {
|
||||
if (
|
||||
workspace.id === browserPageId ||
|
||||
workspace.activePageId === browserPageId ||
|
||||
workspace.pageIds?.includes(browserPageId)
|
||||
) {
|
||||
return worktreeId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const pages of Object.values(store.browserPagesByWorkspace)) {
|
||||
const page = pages.find((candidate) => candidate.id === browserPageId)
|
||||
if (page) {
|
||||
return page.worktreeId
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function acquireBrowserAutomationBootstrapLease(
|
||||
worktreeId: string | null | undefined,
|
||||
browserPageId?: string | null
|
||||
): void {
|
||||
const store = useAppStore.getState()
|
||||
const targetWorktreeId = worktreeId ?? store.activeWorktreeId
|
||||
const targetWorktreeId =
|
||||
worktreeId ??
|
||||
(browserPageId ? findBrowserPageWorktreeId(store, browserPageId) : null) ??
|
||||
store.activeWorktreeId
|
||||
if (!targetWorktreeId) {
|
||||
return
|
||||
}
|
||||
@@ -1425,11 +1451,11 @@ export function useIpcEvents(): void {
|
||||
// has display != none. Main sends this before browser automation commands
|
||||
// so persisted hidden tabs mount without changing the user's active pane.
|
||||
unsubs.push(
|
||||
window.api.browser.onActivateView(({ worktreeId }) => {
|
||||
window.api.browser.onActivateView(({ worktreeId, browserPageId }) => {
|
||||
if (isRuntimeEnvironmentActive()) {
|
||||
return
|
||||
}
|
||||
acquireBrowserAutomationBootstrapLease(worktreeId)
|
||||
acquireBrowserAutomationBootstrapLease(worktreeId, browserPageId)
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user