From dfbfec3e3b6d52b31dc6cc0c39a15a5b66d1498a Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 16:11:57 -0800 Subject: [PATCH 01/52] test: remove low-value compatibility and stream cases (#42202) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../testing/daemon-async-io-probe.test.ts | 4 +- .../daemon-stream-binary-negotiation.test.ts | 2 +- .../transport/framing/testing/ndjson.test.ts | 6 - .../daemon-stream-data-batcher.test.ts | 50 ------ .../rich-markdown-terminal-path-paste.test.ts | 2 - ...ll-request-auto-merge-availability.test.ts | 12 -- .../sleeping-sweep-retention.test.ts | 9 - .../old-client-method-translation.test.ts | 128 -------------- ...old-client-pane-layout-translation.test.ts | 127 -------------- ...old-client-session-tabs-projection.test.ts | 166 ------------------ 10 files changed, 2 insertions(+), 504 deletions(-) delete mode 100644 src/shared/workspace-layout/old-client/old-client-method-translation.test.ts delete mode 100644 src/shared/workspace-layout/old-client/old-client-pane-layout-translation.test.ts delete mode 100644 src/shared/workspace-layout/old-client/old-client-session-tabs-projection.test.ts diff --git a/src/main/daemon/health/testing/daemon-async-io-probe.test.ts b/src/main/daemon/health/testing/daemon-async-io-probe.test.ts index 6878f76aa3f..7c698fe83aa 100644 --- a/src/main/daemon/health/testing/daemon-async-io-probe.test.ts +++ b/src/main/daemon/health/testing/daemon-async-io-probe.test.ts @@ -21,9 +21,7 @@ describe('daemon asynchronous I/O progress', () => { expect(probe.check()).toBe(first) await vi.advanceTimersByTimeAsync(DAEMON_ASYNC_IO_TIMEOUT_MS) expect(await first).toEqual({ state: 'stalled', pendingMs: DAEMON_ASYNC_IO_TIMEOUT_MS }) - for (let i = 0; i < 100; i++) { - expect(await probe.check()).toEqual(await first) - } + expect(await probe.check()).toEqual(await first) expect(start).toHaveBeenCalledTimes(1) expect(vi.getTimerCount()).toBe(0) }) diff --git a/src/main/daemon/transport/framing/testing/daemon-stream-binary-negotiation.test.ts b/src/main/daemon/transport/framing/testing/daemon-stream-binary-negotiation.test.ts index 2615de05d35..2e0b5a12768 100644 --- a/src/main/daemon/transport/framing/testing/daemon-stream-binary-negotiation.test.ts +++ b/src/main/daemon/transport/framing/testing/daemon-stream-binary-negotiation.test.ts @@ -169,7 +169,7 @@ describe('daemon stream framing negotiation', () => { return new Promise((resolve) => fakeDaemon!.listen(socketPath, resolve)) } - it.each([39, 41, 44])( + it.each([39])( 'falls back to NDJSON against a v%i daemon and keeps an event that shares the hello read', async (protocolVersion) => { let requested: string | undefined diff --git a/src/main/daemon/transport/framing/testing/ndjson.test.ts b/src/main/daemon/transport/framing/testing/ndjson.test.ts index f4e4c92a01f..17f224eaef0 100644 --- a/src/main/daemon/transport/framing/testing/ndjson.test.ts +++ b/src/main/daemon/transport/framing/testing/ndjson.test.ts @@ -7,12 +7,6 @@ import { } from '../../../../../shared/main-process-ndjson-framer' describe('encodeNdjson', () => { - it('accepts the exact line-byte limit and rejects one byte more', () => { - const emptyBytes = Buffer.byteLength(JSON.stringify({ data: '' }), 'utf8') - expect(encodeNdjson({ data: 'abc' }, emptyBytes + 3)).toBe('{"data":"abc"}\n') - expect(() => encodeNdjson({ data: 'abcd' }, emptyBytes + 3)).toThrow(NdjsonLineTooLongError) - }) - it('measures multibyte payloads in UTF-8 bytes, not characters', () => { const emptyBytes = Buffer.byteLength(JSON.stringify({ data: '' }), 'utf8') expect(encodeNdjson({ data: '🐙' }, emptyBytes + 4)).toBe('{"data":"🐙"}\n') diff --git a/src/main/daemon/transport/stream/testing/daemon-stream-data-batcher.test.ts b/src/main/daemon/transport/stream/testing/daemon-stream-data-batcher.test.ts index a451e174534..51f41675e7e 100644 --- a/src/main/daemon/transport/stream/testing/daemon-stream-data-batcher.test.ts +++ b/src/main/daemon/transport/stream/testing/daemon-stream-data-batcher.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { Socket } from 'node:net' import { DaemonStreamDataBatcher } from '../daemon-stream-data-batcher' -import { createNdjsonParser } from '../../../../../shared/main-process-ndjson-framer' function createBatcher(options?: ConstructorParameters[1]) { const streamSocket = { @@ -60,27 +59,6 @@ describe('DaemonStreamDataBatcher', () => { } }) - it('holds bulk output while the socket buffer is deep and resumes on the next flush', () => { - vi.useFakeTimers() - try { - const { batcher, streamSocket } = createBatcher() - const bulk = 'x'.repeat(64 * 1024) - - streamSocket.writableLength = 128 * 1024 - batcher.enqueue('client-1', 'session-bulk', bulk) - vi.advanceTimersByTime(2) - expect(nonSentinelWrites(streamSocket)).toHaveLength(0) - expect(batcher.queuedCharsForClient('client-1')).toBe(bulk.length) - - streamSocket.writableLength = 0 - batcher.flush('client-1') - expect(writtenData(streamSocket)).toBe(bulk) - expect(batcher.queuedCharsForClient('client-1')).toBe(0) - } finally { - vi.useRealTimers() - } - }) - it('lets a small session write through the gate while a flooding session holds (per-session fairness)', () => { vi.useFakeTimers() try { @@ -356,32 +334,4 @@ describe('DaemonStreamDataBatcher', () => { vi.useRealTimers() } }) - - it('writes large stream data as parser-sized NDJSON events', () => { - vi.useFakeTimers() - try { - const maxLineBytes = 256 - const { batcher, streamSocket } = createBatcher({ maxLineBytes }) - const data = 'x'.repeat(maxLineBytes * 3) - const onMessage = vi.fn() - const onError = vi.fn() - const parser = createNdjsonParser(onMessage, onError, { maxLineBytes }) - - batcher.enqueue('client-1', 'session-1', data) - vi.advanceTimersByTime(2) - for (const [line] of streamSocket.write.mock.calls) { - parser.feed(String(line)) - } - - expect(onError).not.toHaveBeenCalled() - expect(onMessage).toHaveBeenCalled() - expect( - onMessage.mock.calls - .map(([message]) => (message as { payload?: { data?: string } }).payload?.data ?? '') - .join('') - ).toBe(data) - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts index d0cf373a07a..a94ec47d8c1 100644 --- a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts @@ -6,7 +6,6 @@ describe('shouldPasteTerminalWindowsPathAsPlainText', () => { it.each([ 'Read C:\\Users\\My Project\\README.md before editing.', 'Review \\\\build-server\\Team Docs\\README.md with the release notes.', - 'Open \\\\server\\README.md before editing.', 'Open C:\\Users\\My Project\\README.md.', '"path": "C:\\\\Users\\\\My Project\\\\README.md"' ])('detects the linked basename in %s', (plainText) => { @@ -21,7 +20,6 @@ describe('shouldPasteTerminalWindowsPathAsPlainText', () => { it.each([ 'Open C:\\Users\\README.md.backup before editing.', 'Open C:\\Users\\README.md,backup before editing.', - 'Open C:\\Users\\NOTES.txt and review README.md before editing.', 'Open C:\\docs\\notes.txt and /README.md before editing.', 'Install to C:/Tools then read docs/README.md before editing.' ])('does not match a different basename in %s', (plainText) => { diff --git a/src/shared/github/pull-requests/merge/pull-request-auto-merge-availability.test.ts b/src/shared/github/pull-requests/merge/pull-request-auto-merge-availability.test.ts index 9f1d3d9ada2..cfc2789e5e3 100644 --- a/src/shared/github/pull-requests/merge/pull-request-auto-merge-availability.test.ts +++ b/src/shared/github/pull-requests/merge/pull-request-auto-merge-availability.test.ts @@ -17,18 +17,6 @@ function pr( } describe('github PR auto-merge availability', () => { - it.each([undefined, null, 'UNKNOWN', 'FUTURE_STATUS'])( - 'does not infer an auto-merge requirement from unresolved status %s', - (mergeStateStatus) => { - const item = pr({ mergeable: 'UNKNOWN', mergeStateStatus }) - expect(canShowGitHubPRAutoMergeControl(item)).toBe(false) - } - ) - - it('does not offer auto-merge for directly mergeable PRs with only optional checks pending', () => { - expect(canShowGitHubPRAutoMergeControl(pr())).toBe(false) - }) - it('offers auto-merge for requirement-blocked PRs', () => { expect( canShowGitHubPRAutoMergeControl( diff --git a/src/shared/sidebar-list/selection/sleeping-sweep-retention.test.ts b/src/shared/sidebar-list/selection/sleeping-sweep-retention.test.ts index 50a52c7b179..795636f0a0b 100644 --- a/src/shared/sidebar-list/selection/sleeping-sweep-retention.test.ts +++ b/src/shared/sidebar-list/selection/sleeping-sweep-retention.test.ts @@ -48,15 +48,6 @@ describe('sleeping sweep retention', () => { expect(after.nextExpiryInMs).toBeNull() }) - it('is idempotent across a double-invoked render at the same instant', () => { - const state = createSleepingSweepRetentionState() - runPass(state, ['wt-a'], 1_000) - runPass(state, [], 2_000) - const second = runPass(state, [], 2_000) - - expect([...second.retainedIds]).toEqual(['wt-a']) - }) - it('drops grace state for a workspace that leaves the candidate set', () => { const state = createSleepingSweepRetentionState() runPass(state, ['wt-a'], 1_000) diff --git a/src/shared/workspace-layout/old-client/old-client-method-translation.test.ts b/src/shared/workspace-layout/old-client/old-client-method-translation.test.ts deleted file mode 100644 index 33ae07992a7..00000000000 --- a/src/shared/workspace-layout/old-client/old-client-method-translation.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { MoveTab } from '../../rpc-contract/session-tabs/session-tabs-schemas-params' -import { TerminalCreateParams } from '../../rpc-contract/terminal/terminal-unary-params' -import { translateSessionTabMove, translateTerminalCreate } from './old-client-method-translation' -import './old-client-pane-layout-translation' -import './old-client-session-row-ids' -import { projectSessionTabs } from './old-client-session-tabs-projection' -import '../workspace-layout-commands' -import { build, testContext, WS } from '../commands/workspace-layout-command.test-fixture' - -import type { WorkspaceLayoutModel } from '../workspace-layout-model' - -const NEW_LEAF = '99999999-9999-4999-8999-999999999999' -const NO_VIEW = { groups: {}, panes: {}, editorDrafts: {} } -const NO_FACTS = { tabLabels: {}, terminalRows: {}, browserTabs: {} } - -/** Two terminal tabs and a browser tab in one group; the second terminal tab is pinned. */ -function setup() { - const ctx = testContext() - const { model, results } = build(ctx, [ - { type: 'createTerminalTab', workspace: WS }, - { type: 'createTerminalTab', workspace: WS }, - { type: 'openBrowserTab', workspace: WS } - ]) - const [first, second, browser] = results - const pinned = build( - ctx, - [{ type: 'setTabProps', workspace: WS, tabId: second!.tabId!, isPinned: true }], - model - ) - return { - ctx, - model: pinned.model, - tabA: first!.tabId!, - leafA: first!.leafId!, - tabB: second!.tabId!, - leafB: second!.leafId!, - browser: browser!.tabId! - } -} - -/** Parse terminal.create as an older desktop pane transport sends it. */ -function createParams(fields: { tabId?: string; leafId?: string; title?: string }) { - return TerminalCreateParams.parse({ - worktree: `id:${WS}`, - focus: false, - presentation: 'background', - ...fields - }) -} - -describe('translateTerminalCreate', () => { - it('refuses a pane id another tab holds, and a tab id that is not a terminal', () => { - const { model, tabA, leafB, browser } = setup() - expect( - translateTerminalCreate(model, WS, createParams({ tabId: tabA, leafId: leafB })) - ).toEqual({ - ok: false, - code: 'invalid_params' - }) - expect( - translateTerminalCreate(model, WS, createParams({ tabId: 'tab-new', leafId: leafB })) - ).toEqual({ ok: false, code: 'invalid_params' }) - expect( - translateTerminalCreate(model, WS, createParams({ tabId: browser, leafId: NEW_LEAF })) - ).toEqual({ ok: false, code: 'invalid_params' }) - }) -}) - -describe('session.tabs.move translation', () => { - /** Translate against the snapshot the client saw, matching the handler. */ - function move(model: WorkspaceLayoutModel, params: Record) { - const workspace = model.workspaces[WS]! - const shown = projectSessionTabs(WS, workspace, NO_VIEW, NO_FACTS, false) - return translateSessionTabMove(WS, workspace, shown, MoveTab.parse({ worktree: WS, ...params })) - } - - it.each([ - ['a partial order', (ids: string[]) => ids.slice(1)], - ['a repeated tab', (ids: string[]) => [ids[0]!, ids[0]!, ids[1]!]], - ['an unknown tab', (ids: string[]) => [...ids.slice(0, 2), 'gone']] - ])('refuses %s with invalid_tab_order, as today', (_, edit) => { - const { model } = setup() - const group = model.workspaces[WS]!.groups[0]! - expect( - move(model, { - tabId: group.tabOrder[0], - targetGroupId: group.id, - kind: 'reorder', - tabOrder: edit(group.tabOrder) - }) - ).toEqual({ ok: false, code: 'invalid_tab_order' }) - }) - - it("refuses a tab outside the reordered group and an unknown group with today's codes", () => { - const { ctx, model, tabA, tabB } = setup() - const sourceGroup = model.workspaces[WS]!.groups[0]!.id - const splitOff = build( - ctx, - [ - { - type: 'splitGroup', - workspace: WS, - tabId: tabB, - besideGroupId: sourceGroup, - direction: 'right' - } - ], - model - ) - const target = splitOff.results[0]!.groupId! - expect( - move(splitOff.model, { - tabId: tabA, - targetGroupId: target, - kind: 'reorder', - tabOrder: [tabB] - }) - ).toEqual({ ok: false, code: 'invalid_tab_order' }) - expect(move(model, { tabId: tabA, targetGroupId: 'gone', kind: 'move-to-group' })).toEqual({ - ok: false, - code: 'target_group_not_found' - }) - expect( - move(model, { tabId: 'gone', targetGroupId: sourceGroup, kind: 'move-to-group' }) - ).toEqual({ ok: false, code: 'tab_not_found' }) - }) -}) diff --git a/src/shared/workspace-layout/old-client/old-client-pane-layout-translation.test.ts b/src/shared/workspace-layout/old-client/old-client-pane-layout-translation.test.ts deleted file mode 100644 index 01386cb6d4c..00000000000 --- a/src/shared/workspace-layout/old-client/old-client-pane-layout-translation.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { UpdatePaneLayout } from '../../rpc-contract/session-tabs/session-tabs-schemas-params' -import type { TerminalPaneLayoutNode } from '../terminal-tab-types' -import { translateUpdatePaneLayout } from './old-client-pane-layout-translation' -import { - build, - terminalTab, - testContext, - WS -} from '../commands/workspace-layout-command.test-fixture' -import type { WorkspaceLayoutModel } from '../workspace-layout-model' - -const leafNode = (leafId: string): TerminalPaneLayoutNode => ({ type: 'leaf', leafId }) -const split = ( - direction: 'vertical' | 'horizontal', - first: TerminalPaneLayoutNode, - second: TerminalPaneLayoutNode, - ratio?: number -): TerminalPaneLayoutNode => ({ - type: 'split', - direction, - first, - second, - ...(ratio !== undefined ? { ratio } : {}) -}) - -/** One tab with panes A | B | C side by side, as a desktop splits right twice. */ -function threePanes() { - const ctx = testContext() - const created = build(ctx, [{ type: 'createTerminalTab', workspace: WS }]) - const tabId = created.results[0]!.tabId! - const a = created.results[0]!.leafId! - const first = build( - ctx, - [{ type: 'splitPane', workspace: WS, tabId, leafId: a, direction: 'vertical' }], - created.model - ) - const b = first.results[0]!.leafId! - const second = build( - ctx, - [{ type: 'splitPane', workspace: WS, tabId, leafId: b, direction: 'vertical' }], - first.model - ) - const c = second.results[0]!.leafId! - return { ctx, model: second.model, tabId, a, b, c } -} - -/** Parse older desktop persistence params from use-terminal-pane-layout-persistence.ts. */ -function sent(tabId: string, fields: Record) { - return UpdatePaneLayout.parse({ - worktree: WS, - tabId, - expandedLeafId: null, - intent: 'gesture', - ...fields - }) -} - -function translate(model: WorkspaceLayoutModel, tabId: string, params: ReturnType) { - return translateUpdatePaneLayout(WS, model.workspaces[WS]!, terminalTab(model, tabId), params) -} - -describe('translateUpdatePaneLayout (rule 11)', () => { - it.each([ - [ - 'a pane added', - (p: Panes) => - split( - 'vertical', - leafNode(p.a), - split('vertical', leafNode(p.b), split('vertical', leafNode(p.c), leafNode(NEW_LEAF))) - ) - ], - ['a pane removed', (p: Panes) => split('vertical', leafNode(p.a), leafNode(p.b))], - [ - 'two panes moved', - (p: Panes) => - split('horizontal', leafNode(p.c), split('horizontal', leafNode(p.b), leafNode(p.a))) - ], - [ - 'a pane repeated', - (p: Panes) => - split('vertical', leafNode(p.a), split('vertical', leafNode(p.a), leafNode(p.c))) - ] - ])('refuses the structure for %s, and still applies titles and the chat pane', (_, tree) => { - const panes = threePanes() - const { model, tabId, a, b } = panes - const translation = translate( - model, - tabId, - sent(tabId, { root: tree(panes), titlesByLeafId: { [a]: 'server' }, chatLeafId: b }) - ) - expect(translation).toEqual({ - structureRefused: true, - commands: [ - { type: 'renamePane', workspace: WS, tabId, leafId: a, title: 'server' }, - { type: 'setChatPane', workspace: WS, tabId, leafId: b } - ] - }) - }) - - it('renames only changed panes; a pane missing from the sent titles loses its title', () => { - const { ctx, model, tabId, a, b, c } = threePanes() - const titled = build( - ctx, - [ - { type: 'renamePane', workspace: WS, tabId, leafId: a, title: 'logs' }, - { type: 'renamePane', workspace: WS, tabId, leafId: b, title: 'shell' } - ], - model - ).model - const translation = translate( - titled, - tabId, - sent(tabId, { root: null, titlesByLeafId: { [a]: 'logs', [c]: 'build' } }) - ) - expect(translation.commands).toEqual([ - { type: 'renamePane', workspace: WS, tabId, leafId: b, title: null }, - { type: 'renamePane', workspace: WS, tabId, leafId: c, title: 'build' } - ]) - // No title map leaves titles alone. - expect(translate(titled, tabId, sent(tabId, { root: null })).commands).toEqual([]) - }) -}) - -type Panes = ReturnType -const NEW_LEAF = '99999999-9999-4999-8999-999999999999' diff --git a/src/shared/workspace-layout/old-client/old-client-session-tabs-projection.test.ts b/src/shared/workspace-layout/old-client/old-client-session-tabs-projection.test.ts deleted file mode 100644 index bb4248513c5..00000000000 --- a/src/shared/workspace-layout/old-client/old-client-session-tabs-projection.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import './old-client-session-tab-rows' -import { - projectSessionTabs, - type SessionTabsFacts, - type SessionTabsView -} from './old-client-session-tabs-projection' -import '../persistence/workspace-layout-beside' -import '../editor-tabs/workspace-layout-editor-tab-file' -import { build, testContext, WS } from '../commands/workspace-layout-command.test-fixture' -import type { WorkspaceLayoutModel } from '../workspace-layout-model' - -/** Desktop-shaped fixture: split/agent terminals, file, browser and chat across two groups, with one titled pane. */ -function workspace() { - const ctx = testContext() - const { model, results } = build(ctx, [ - { type: 'createTerminalTab', workspace: WS, title: 'api server' }, - { - type: 'createTerminalTab', - workspace: WS, - creation: { launchAgent: 'claude', startupCwd: '/Users/dev/orca' } - }, - { - type: 'openEditorTab', - workspace: WS, - fileId: '/Users/dev/orca/README.md', - contentType: 'editor', - file: { - filePath: '/Users/dev/orca/README.md', - relativePath: 'README.md', - language: 'markdown' - } - }, - { type: 'openBrowserTab', workspace: WS }, - { type: 'openAgentSessionTab', workspace: WS, sessionId: 'session-1', agent: 'codex' } - ]) - const [api, agent, readme, browser, chat] = results - const left = groupOf(model, api!.tabId!) - const arranged = build( - ctx, - [ - { - type: 'splitPane', - workspace: WS, - tabId: api!.tabId!, - leafId: api!.leafId!, - direction: 'vertical' - }, - { - type: 'renamePane', - workspace: WS, - tabId: api!.tabId!, - leafId: api!.leafId!, - title: 'logs' - }, - { type: 'setTabProps', workspace: WS, tabId: api!.tabId!, color: '#ff0000', isPinned: true }, - { - type: 'splitGroup', - workspace: WS, - tabId: browser!.tabId!, - besideGroupId: left, - direction: 'right' - } - ], - model - ) - const apiSplit = arranged.results[0]!.leafId! - const right = arranged.results[3]!.groupId! - const moved = build( - ctx, - [{ type: 'moveTab', workspace: WS, tabId: chat!.tabId!, toGroupId: right, index: 1 }], - arranged.model - ).model - const ws = moved.workspaces[WS]! - const bound: WorkspaceLayoutModel = { - ...moved, - workspaces: { - [WS]: { - ...ws, - leaves: { - ...ws.leaves, - [api!.leafId!]: { ...ws.leaves?.[api!.leafId!], ptyId: 'pty-1', incarnationId: 'inc-1' }, - [apiSplit]: { ptyId: 'pty-2' } - } - } - } - } - return { model: bound, api, apiSplit, agent, readme, browser, chat, left, right } -} - -function groupOf(model: WorkspaceLayoutModel, tabId: string): string { - return model.workspaces[WS]!.groups.find((group) => group.tabOrder.includes(tabId))!.id -} - -function views(fields: Partial = {}): SessionTabsView { - return { groups: {}, panes: {}, editorDrafts: {}, ...fields } -} - -const noFacts: SessionTabsFacts = { tabLabels: {}, terminalRows: {}, browserTabs: {} } - -describe('projectSessionTabs', () => { - it.each(['check-details', 'conflict-review'] as const)( - 'withholds %s views from file rows and group references', - (mode) => { - const { model, results } = build(testContext(), [ - { - type: 'openEditorTab', - workspace: WS, - fileId: `${WS}::${mode}::check-run:42`, - contentType: mode, - view: { - view: { mode }, - file: { - filePath: `${WS}::${mode}::check-run:42`, - relativePath: 'e2e / changed e2e specs (1/1)', - language: 'plaintext' - } - } - }, - { - type: 'openEditorTab', - workspace: WS, - fileId: '/Users/dev/orca/app.ts', - contentType: 'editor', - file: { - filePath: '/Users/dev/orca/app.ts', - relativePath: 'app.ts', - language: 'typescript' - } - } - ]) - const virtualTabId = results[0]!.tabId! - const fileTabId = results[1]!.tabId! - const groupId = groupOf(model, virtualTabId) - const view = views({ - activeGroupIdByWorktree: { [WS]: groupId }, - groups: { - [WS]: { - [groupId]: { activeTabId: virtualTabId, recentTabIds: [fileTabId, virtualTabId] } - } - } - }) - - const snapshot = projectSessionTabs(WS, model.workspaces[WS]!, view, noFacts, false) - - expect(snapshot.tabs).toMatchObject([ - { id: fileTabId, type: 'file', relativePath: 'app.ts', isActive: false } - ]) - expect(snapshot.tabs).toHaveLength(1) - expect(snapshot.activeTabId).toBeNull() - expect(snapshot.activeTabType).toBeNull() - expect(snapshot.tabGroups).toEqual([ - { id: groupId, activeTabId: null, tabOrder: [fileTabId], recentTabIds: [fileTabId] } - ]) - } - ) - - it('names the first group active when the saved one is gone, as a window restores it', () => { - const { model, left } = workspace() - const view = views({ activeGroupIdByWorktree: { [WS]: 'group-gone' } }) - expect(projectSessionTabs(WS, model.workspaces[WS]!, view, noFacts, false).activeGroupId).toBe( - left - ) - }) -}) From f993c66b74d6d9995c3af0fad9ec56e3387c561c Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:12:40 -0800 Subject: [PATCH 02/52] refactor(menus): share menu row styles and add a compact density (#41847) * refactor(menus): share menu row styles and add a compact density * test(menus): drop the CSS-class density test --- .../src/components/ui/context-menu.tsx | 145 ++++++++------ .../src/components/ui/dropdown-menu.tsx | 187 ++++++++++-------- src/renderer/src/components/ui/menu-item.ts | 109 ++++++++++ 3 files changed, 297 insertions(+), 144 deletions(-) create mode 100644 src/renderer/src/components/ui/menu-item.ts diff --git a/src/renderer/src/components/ui/context-menu.tsx b/src/renderer/src/components/ui/context-menu.tsx index 0279a8b729c..508c69295a7 100644 --- a/src/renderer/src/components/ui/context-menu.tsx +++ b/src/renderer/src/components/ui/context-menu.tsx @@ -10,6 +10,19 @@ import { handleImeOverlayEscape } from '@/lib/text-input/ime/ime-overlay-escape' import { keepFocusWhileMenuCloses } from './menu-item-closing-focus' import { useMenuPointerHighlight } from './menu-pointer-highlight' import { MENU_SURFACE_CLASS } from './menu-surface' +import { + MENU_ITEM_INDICATOR_CLASS, + MENU_LABEL_CLASS, + MENU_SHORTCUT_CLASS, + MENU_SUB_TRIGGER_CHEVRON_CLASS, + MenuDensityProvider, + menuIndicatorItemVariants, + menuItemVariants, + menuSeparatorVariants, + menuSubTriggerVariants, + useMenuDensity, + type MenuDensity +} from './menu-item' function ContextMenu({ ...props }: React.ComponentProps) { return @@ -35,22 +48,22 @@ function ContextMenuSubTrigger({ className, inset, children, + density, ...props }: React.ComponentProps & { inset?: boolean + density?: MenuDensity }) { + const rowDensity = useMenuDensity(density) return ( {children} - + ) } @@ -71,31 +84,38 @@ function ContextMenuSubContent({ animation, style, alignOffset = -5, + density, ...props }: React.ComponentProps & - VariantProps) { + VariantProps & { + /** Defaults to the parent menu's density. */ + density?: MenuDensity + }) { const pointerHighlight = useMenuPointerHighlight(props) const { ref: focusScopeRef, scope } = useOverlayFocusScope(pointerHighlight.ref) + const subDensity = useMenuDensity(density) return ( - handleImeOverlayEscape(event, props.onEscapeKeyDown)} - /> + + handleImeOverlayEscape(event, props.onEscapeKeyDown)} + /> + ) @@ -105,30 +125,36 @@ function ContextMenuContent({ className, animation, style, + density = 'default', ...props }: React.ComponentProps & - VariantProps) { + VariantProps & { + /** Row density for every row in this menu; a row's own `density` overrides it. */ + density?: MenuDensity + }) { const pointerHighlight = useMenuPointerHighlight(props) const { ref: focusScopeRef, scope } = useOverlayFocusScope(pointerHighlight.ref) return ( - handleOverlayCloseAutoFocus(event, props.onCloseAutoFocus)} - {...pointerHighlight} - ref={focusScopeRef} - onEscapeKeyDown={(event) => handleImeOverlayEscape(event, props.onEscapeKeyDown)} - /> + + handleOverlayCloseAutoFocus(event, props.onCloseAutoFocus)} + {...pointerHighlight} + ref={focusScopeRef} + onEscapeKeyDown={(event) => handleImeOverlayEscape(event, props.onEscapeKeyDown)} + /> + ) @@ -138,22 +164,22 @@ function ContextMenuItem({ className, inset, variant = 'default', + density, onPointerMove, onPointerLeave, ...props }: React.ComponentProps & { inset?: boolean variant?: 'default' | 'destructive' + density?: MenuDensity }) { + const rowDensity = useMenuDensity(density) return ( ) { +}: React.ComponentProps & { + density?: MenuDensity +}) { + const rowDensity = useMenuDensity(density) return ( - + @@ -196,10 +223,7 @@ function ContextMenuLabel({ ) @@ -207,12 +231,16 @@ function ContextMenuLabel({ function ContextMenuSeparator({ className, + density, ...props -}: React.ComponentProps) { +}: React.ComponentProps & { + density?: MenuDensity +}) { + const rowDensity = useMenuDensity(density) return ( ) @@ -222,10 +250,7 @@ function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span return ( ) diff --git a/src/renderer/src/components/ui/dropdown-menu.tsx b/src/renderer/src/components/ui/dropdown-menu.tsx index b3ad3f49c0f..b2d00c6d03a 100644 --- a/src/renderer/src/components/ui/dropdown-menu.tsx +++ b/src/renderer/src/components/ui/dropdown-menu.tsx @@ -11,6 +11,19 @@ import { handleImeOverlayEscape } from '@/lib/text-input/ime/ime-overlay-escape' import { keepFocusWhileMenuCloses } from './menu-item-closing-focus' import { useMenuPointerHighlight } from './menu-pointer-highlight' import { MENU_SURFACE_CLASS } from './menu-surface' +import { + MENU_ITEM_INDICATOR_CLASS, + MENU_LABEL_CLASS, + MENU_SHORTCUT_CLASS, + MENU_SUB_TRIGGER_CHEVRON_CLASS, + MenuDensityProvider, + menuIndicatorItemVariants, + menuItemVariants, + menuSeparatorVariants, + menuSubTriggerVariants, + useMenuDensity, + type MenuDensity +} from './menu-item' import { PortalContainerContext, usePortalContainer } from './portal-container-context' const DropdownMenuCloseContext = React.createContext<() => void>(() => {}) @@ -61,9 +74,12 @@ function DropdownMenuContent({ sideOffset = 4, portalContainer, style, + density = 'default', ...props }: React.ComponentProps & { portalContainer?: HTMLElement | null + /** Row density for every row in this menu; a row's own `density` overrides it. */ + density?: MenuDensity // Radix consumes this at its opening focus scope but omits it from the public Menu props. onOpenAutoFocus?: (event: Event) => void }) { @@ -74,23 +90,27 @@ function DropdownMenuContent({ - handleOverlayCloseAutoFocus(event, props.onCloseAutoFocus)} - {...pointerHighlight} - ref={focusScopeRef} - onEscapeKeyDown={(event) => handleImeOverlayEscape(event, props.onEscapeKeyDown)} - /> + + + handleOverlayCloseAutoFocus(event, props.onCloseAutoFocus) + } + {...pointerHighlight} + ref={focusScopeRef} + onEscapeKeyDown={(event) => handleImeOverlayEscape(event, props.onEscapeKeyDown)} + /> + @@ -101,23 +121,23 @@ function DropdownMenuItem({ className, inset, variant = 'default', + density, onPointerMove, onPointerLeave, ...props }: React.ComponentProps & { inset?: boolean - /** `launch`: rows in the shared agent menu; at least 36px tall so every launch menu matches. */ + /** `launch`: rows in the shared agent menu; at least 36px tall in either density. */ variant?: 'default' | 'destructive' | 'launch' + density?: MenuDensity }) { + const rowDensity = useMenuDensity(density) return ( ) { +}: React.ComponentProps & { + density?: MenuDensity +}) { + const rowDensity = useMenuDensity(density) return ( - + @@ -160,18 +181,19 @@ function DropdownMenuRadioGroup({ function DropdownMenuRadioItem({ className, children, + density, ...props -}: React.ComponentProps) { +}: React.ComponentProps & { + density?: MenuDensity +}) { + const rowDensity = useMenuDensity(density) return ( - + @@ -192,10 +214,7 @@ function DropdownMenuLabel({ ) @@ -203,12 +222,16 @@ function DropdownMenuLabel({ function DropdownMenuSeparator({ className, + density, ...props -}: React.ComponentProps) { +}: React.ComponentProps & { + density?: MenuDensity +}) { + const rowDensity = useMenuDensity(density) return ( ) @@ -218,10 +241,7 @@ function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'spa return ( ) @@ -231,42 +251,35 @@ function DropdownMenuSub({ ...props }: React.ComponentProps } -const dropdownMenuSubTriggerVariants = cva( - "flex cursor-default items-center gap-2 rounded-md px-2.5 py-[5px] text-[13px] leading-4 font-normal outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-[15px] [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:stroke-[1.5]", - { - variants: { - variant: { - default: - 'focus:bg-black/8 dark:focus:bg-white/14 data-[state=open]:bg-black/8 dark:data-[state=open]:bg-white/14 data-[disabled]:pointer-events-none data-[disabled]:opacity-40', - 'launch-row': - 'gap-0 rounded-[7px] p-0 text-xs leading-5 font-medium focus:bg-accent focus:text-accent-foreground focus-within:bg-accent focus-within:text-accent-foreground data-[search-default]:bg-accent data-[search-default]:text-accent-foreground has-[[data-context-menu-open]]:bg-accent has-[[data-context-menu-open]]:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-40', - 'header-chip': - 'h-[22px] max-w-[9.5rem] min-w-0 gap-1 rounded-md px-1.5 py-0 text-2xs font-medium text-muted-foreground hover:bg-black/8 hover:text-foreground focus:bg-black/8 focus:text-foreground data-[state=open]:bg-black/8 data-[state=open]:text-foreground dark:hover:bg-white/14 dark:focus:bg-white/14 dark:data-[state=open]:bg-white/14 data-[disabled]:pointer-events-none data-[disabled]:opacity-40' - } - }, - defaultVariants: { variant: 'default' } - } -) - function DropdownMenuSubTrigger({ className, inset, children, hideChevron, variant = 'default', + density, ...props }: React.ComponentProps & { inset?: boolean + density?: MenuDensity // Why: collision-flipped submenus open leftward, where a right-pointing chevron misleads. hideChevron?: boolean variant?: 'default' | 'launch-row' | 'header-chip' }) { + const rowDensity = useMenuDensity(density) return ( {hideChevron ? ( @@ -274,7 +287,7 @@ function DropdownMenuSubTrigger({ ) : ( <> {children} - + )} @@ -293,40 +306,46 @@ function DropdownMenuSubContent({ alignOffset = -5, scrollable = false, variant = 'default', + density, ...props }: React.ComponentProps & { portalContainer?: HTMLElement | null + /** Defaults to the parent menu's density. */ + density?: MenuDensity scrollable?: boolean variant?: 'default' | 'picker' }) { const container = usePortalContainer(portalContainer) const pointerHighlight = useMenuPointerHighlight(props) const { ref: focusScopeRef, scope } = useOverlayFocusScope(pointerHighlight.ref) + const subDensity = useMenuDensity(density) return ( - handleImeOverlayEscape(event, props.onEscapeKeyDown)} - /> + + handleImeOverlayEscape(event, props.onEscapeKeyDown)} + /> + diff --git a/src/renderer/src/components/ui/menu-item.ts b/src/renderer/src/components/ui/menu-item.ts new file mode 100644 index 00000000000..45af07607ee --- /dev/null +++ b/src/renderer/src/components/ui/menu-item.ts @@ -0,0 +1,109 @@ +import * as React from 'react' +import { cva } from 'class-variance-authority' + +/** + * Row styles shared by dropdown-menu.tsx and context-menu.tsx, in the spirit of menu-surface.ts. + * `default` density is the 26px row (5 + 16 + 5); `compact` is the older 24px row for menus + * that need to fit more rows. + */ +export type MenuDensity = 'default' | 'compact' + +const MenuDensityContext = React.createContext('default') + +export const MenuDensityProvider = MenuDensityContext + +/** A row's own density wins; otherwise it follows the nearest menu content. */ +export function useMenuDensity(density: MenuDensity | undefined): MenuDensity { + const inherited = React.useContext(MenuDensityContext) + return density ?? inherited +} + +const ROW_PADDING_Y = { default: 'py-[5px]', compact: 'py-1' } as const + +const ROW_BASE = + 'flex cursor-default items-center gap-2 rounded-md text-[13px] leading-4 font-normal outline-hidden select-none [&_svg]:pointer-events-none [&_svg]:shrink-0' +const ROW_FOCUS = 'focus:bg-black/8 dark:focus:bg-white/14' +const ROW_DISABLED = 'data-[disabled]:pointer-events-none data-[disabled]:opacity-40' +const ROW_ICON = + "[&_svg:not([class*='size-'])]:size-[15px] [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:stroke-[1.5]" + +export const menuItemVariants = cva( + [ + 'relative px-2.5', + ROW_BASE, + ROW_FOCUS, + ROW_DISABLED, + 'data-[inset]:pl-8', + 'data-[variant=destructive]:text-[color-mix(in_srgb,var(--destructive)_78%,black)] dark:data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20', + ROW_ICON, + 'data-[variant=destructive]:*:[svg]:text-current!' + ], + { + variants: { + density: ROW_PADDING_Y, + menu: { + // Dropdown rows carry the extra states its consumers set: search default, nested context + // menu, aria-disabled, current, and the shared agent menu's 36px `launch` row. + dropdown: + 'data-[search-default]:bg-black/8 dark:data-[search-default]:bg-white/14 data-[context-menu-open]:bg-black/8 dark:data-[context-menu-open]:bg-white/14 aria-disabled:opacity-40 data-[current=true]:bg-accent data-[current=true]:data-[disabled]:opacity-100 data-[variant=launch]:min-h-9 data-[variant=launch]:rounded-[7px] data-[variant=launch]:px-2 data-[variant=launch]:py-1.5 data-[variant=launch]:text-[13px] data-[variant=launch]:leading-4 data-[variant=launch]:font-medium', + context: '' + } + }, + defaultVariants: { density: 'default', menu: 'dropdown' } + } +) + +/** Checkbox and radio rows: inset to leave room for the indicator at the left edge. */ +export const menuIndicatorItemVariants = cva( + [ + 'relative pr-2.5 pl-8', + ROW_BASE, + ROW_FOCUS, + ROW_DISABLED, + "[&_svg:not([class*='size-'])]:size-3.5" + ], + { + variants: { density: ROW_PADDING_Y }, + defaultVariants: { density: 'default' } + } +) + +export const MENU_ITEM_INDICATOR_CLASS = + 'pointer-events-none absolute left-2.5 flex size-3.5 items-center justify-center' + +export const menuSubTriggerVariants = cva(['px-2.5', ROW_BASE, 'data-[inset]:pl-8', ROW_ICON], { + variants: { + // Density precedes variant so the chip and launch rows' own padding wins the merge. + density: ROW_PADDING_Y, + variant: { + default: `${ROW_FOCUS} data-[state=open]:bg-black/8 dark:data-[state=open]:bg-white/14`, + 'launch-row': + 'gap-0 rounded-[7px] p-0 text-xs leading-5 font-medium focus:bg-accent focus:text-accent-foreground focus-within:bg-accent focus-within:text-accent-foreground data-[search-default]:bg-accent data-[search-default]:text-accent-foreground has-[[data-context-menu-open]]:bg-accent has-[[data-context-menu-open]]:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-40', + 'header-chip': + 'h-[22px] max-w-[9.5rem] min-w-0 gap-1 rounded-md px-1.5 py-0 text-2xs font-medium text-muted-foreground hover:bg-black/8 hover:text-foreground focus:bg-black/8 focus:text-foreground data-[state=open]:bg-black/8 data-[state=open]:text-foreground dark:hover:bg-white/14 dark:focus:bg-white/14 dark:data-[state=open]:bg-white/14 data-[disabled]:pointer-events-none data-[disabled]:opacity-40' + }, + menu: { dropdown: '', context: '' } + }, + compoundVariants: [ + // Context submenu triggers have never dimmed when disabled; keep that until it is a decision. + { menu: 'dropdown', variant: 'default', class: ROW_DISABLED } + ], + defaultVariants: { + density: 'default', + variant: 'default', + menu: 'dropdown' + } +}) + +export const MENU_LABEL_CLASS = + 'px-2.5 pt-[5px] pb-[3px] text-2xs font-semibold text-muted-foreground data-[inset]:pl-8' + +export const menuSeparatorVariants = cva('-mx-[6px] h-px bg-black/7 dark:bg-white/10', { + variants: { density: { default: 'my-[6px]', compact: 'my-[5px]' } }, + defaultVariants: { density: 'default' } +}) + +export const MENU_SHORTCUT_CLASS = + 'ml-auto shrink-0 whitespace-nowrap pl-4 tracking-normal text-muted-foreground' + +export const MENU_SUB_TRIGGER_CHEVRON_CLASS = 'ml-auto size-3.5 text-current opacity-70' From 0bc55330fc68d19909ab66005ad4705117bd5ba3 Mon Sep 17 00:00:00 2001 From: Yasyf Mohamedali Date: Fri, 13 Nov 2026 16:15:46 -0800 Subject: [PATCH 03/52] fix(orchestration): mark a question read when reply answers it (#41979) --- ...orchestration-mutation-question-db.test.ts | 33 +++++++++++++++++++ .../db/questions/question-threads.ts | 1 + 2 files changed, 34 insertions(+) diff --git a/src/main/runtime/orchestration/db/questions/orchestration-mutation-question-db.test.ts b/src/main/runtime/orchestration/db/questions/orchestration-mutation-question-db.test.ts index 6ec52f4eaa0..e77374310fa 100644 --- a/src/main/runtime/orchestration/db/questions/orchestration-mutation-question-db.test.ts +++ b/src/main/runtime/orchestration/db/questions/orchestration-mutation-question-db.test.ts @@ -70,6 +70,39 @@ describe('OrchestrationDb mutation and question state', () => { ).toThrow(/different answer/) }) + it('marks the question it answers read and leaves other unread mail alone', () => { + const d = createDb() + const run = d.createRun({ + objective: 'Read on answer', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'tab_coord:11111111-1111-4111-8111-111111111111' + }) + const task = d.createTask({ spec: 'ask', runId: run.id }) + const dispatch = createRootDispatch(d, task.id, 'term_worker') + const created = d.createQuestion({ + runId: run.id, + dispatchId: dispatch.id, + askerHandle: 'term_worker', + question: 'Which format?' + }) + const status = d.insertMessage({ + runId: run.id, + from: `dispatch:${dispatch.id}`, + to: `run:${run.id}`, + subject: 'Progress' + }) + + d.answerQuestion({ + messageId: created.message.id, + runId: run.id, + consumerGeneration: run.consumer_generation, + body: 'old' + }) + + expect(d.getMessageById(created.message.id)?.read).toBe(1) + expect(d.getMessageById(status.id)?.read).toBe(0) + }) + it('closes pending questions with their Dispatch', () => { const d = createDb() const run = d.createRun({ diff --git a/src/main/runtime/orchestration/db/questions/question-threads.ts b/src/main/runtime/orchestration/db/questions/question-threads.ts index 5741dc5750a..ee0a450ed12 100644 --- a/src/main/runtime/orchestration/db/questions/question-threads.ts +++ b/src/main/runtime/orchestration/db/questions/question-threads.ts @@ -123,6 +123,7 @@ export function answerQuestion( `Question ${params.messageId} is closed because its Dispatch is inactive.` ) } + this.markAsRead([question.message_id]) if (question.status === 'answered') { if (question.answer_body !== params.body || !question.answer_message_id) { throw new OrchestrationError( From 5463aa10d63a0499b7d80b48c7ea1e80fc8d63e2 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 16:21:12 -0800 Subject: [PATCH 04/52] test: delete shallow telemetry schema and allowlist suites (#42203) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- src/shared/daemon-adoption-telemetry.test.ts | 74 ------------------- .../feature-education-telemetry.test.ts | 29 -------- 2 files changed, 103 deletions(-) delete mode 100644 src/shared/daemon-adoption-telemetry.test.ts delete mode 100644 src/shared/feature-education-telemetry.test.ts diff --git a/src/shared/daemon-adoption-telemetry.test.ts b/src/shared/daemon-adoption-telemetry.test.ts deleted file mode 100644 index df65ffabd4a..00000000000 --- a/src/shared/daemon-adoption-telemetry.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { eventSchemas } from './telemetry-event-registry' - -// The reset remedy is offered for exactly these classes, so main and the fix dialog must agree. - -// Privacy invariant: enum-only. A raw path, version, or exact count must be rejected by .strict(). -describe('daemon_adopted / daemon_pty_cwd_denied schemas', () => { - const adopted = { - app_version_match: 'different', - spawner_path_class: 'updater-cache', - code_identity: 'unresolvable', - tcc_attribution: 'intact', - live_session_count_bucket: '2-5' - } - const denied = { - cwd_class: 'documents', - app_version_match: 'different', - spawner_path_class: 'updater-cache', - code_identity: 'parked' - } - - it('rejects leaked paths, versions, counts, and unknown enum values', () => { - for (const leak of [ - { spawner_exec_path: '/Users/alice/Library/Caches/ShipIt/Orca.app' }, - { app_version: '1.4.187' }, - { live_session_count: 3 }, - { cwd: '/Users/alice/Documents' } - ]) { - expect(eventSchemas.daemon_adopted.safeParse({ ...adopted, ...leak }).success).toBe(false) - expect(eventSchemas.daemon_pty_cwd_denied.safeParse({ ...denied, ...leak }).success).toBe( - false - ) - } - expect( - eventSchemas.daemon_adopted.safeParse({ ...adopted, spawner_path_class: '/Applications' }) - .success - ).toBe(false) - expect( - eventSchemas.daemon_pty_cwd_denied.safeParse({ ...denied, cwd_class: 'Documents' }).success - ).toBe(false) - expect( - eventSchemas.daemon_adopted.safeParse({ ...adopted, code_identity: 'severed' }).success - ).toBe(false) - expect( - eventSchemas.daemon_pty_cwd_readable.safeParse({ ...denied, launch_method: 'stable-copy' }) - .success - ).toBe(false) - expect( - eventSchemas.daemon_pty_cwd_readable.safeParse({ - ...denied, - spawner_path_class: 'stable-copy' - }).success - ).toBe(true) - }) -}) - -// Match the denied-event enum-only privacy budget: no daemon scope, path or folder name. -describe('daemon_folder_access_notice schema', () => { - const shown = { action: 'shown', cwd_class: 'documents' } - - it('rejects an unknown action, an unknown class, and any extra field', () => { - for (const bad of [ - { action: 'open_manage_sessions' }, - { cwd_class: 'Documents' }, - { daemon_scope: 'aaaa111122223333' }, - { cwd: '/Users/alice/Documents' } - ]) { - expect(eventSchemas.daemon_folder_access_notice.safeParse({ ...shown, ...bad }).success).toBe( - false - ) - } - }) -}) diff --git a/src/shared/feature-education-telemetry.test.ts b/src/shared/feature-education-telemetry.test.ts deleted file mode 100644 index c56801c6470..00000000000 --- a/src/shared/feature-education-telemetry.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - normalizeFeatureEducationSource, - normalizeSetupGuideSource -} from './feature-education-telemetry' - -describe('feature education telemetry constants', () => { - it('normalizes unknown telemetry sources to a bounded fallback', () => { - expect(normalizeFeatureEducationSource('tasks_open')).toBe('tasks_open') - expect(normalizeFeatureEducationSource('workspace_agent_sessions_visible')).toBe( - 'workspace_agent_sessions_visible' - ) - expect(normalizeFeatureEducationSource('floating_workspace_visible')).toBe( - 'floating_workspace_visible' - ) - expect(normalizeFeatureEducationSource('setup_guide_parallel_work')).toBe( - 'setup_guide_parallel_work' - ) - expect(normalizeFeatureEducationSource('https://example.com/private')).toBe('unknown') - expect(normalizeFeatureEducationSource(null)).toBe('unknown') - }) - - it('normalizes setup guide telemetry sources to a bounded fallback', () => { - expect(normalizeSetupGuideSource('sidebar')).toBe('sidebar') - expect(normalizeSetupGuideSource('settings')).toBe('settings') - expect(normalizeSetupGuideSource('help_menu')).toBe('help_menu') - expect(normalizeSetupGuideSource('private-source')).toBe('unknown') - }) -}) From cc1e3740dadc0e4d1dfd41c0314af4442ee5f876 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:31:34 +0000 Subject: [PATCH 05/52] feat(computer-use): scroll and select list rows in background Linux windows, and aim GTK 4 clicks (#42201) * feat(computer-use): scroll and select rows in background Linux windows, and aim GTK 4 pointer input Scroll moves the nearest scroll bar's value by whole viewports, handing the scroll outward at a view's end, or pages a web document with Component.ScrollTo, before falling back to the pointer. A click on a list row with no action selects it through the list's Selection when the index is proven to name that row. GTK 4 rectangles come from WINDOW extents plus the X11 client origin, since its SCREEN extents read [0, 0, w, h]. * fix(computer-use): keep Linux background scroll and select honest under partial and slow results Wait for ScrollTo to move before planning the next page, report pages already scrolled instead of falling back, let refused scroll bars fall through, clear a multi-select list before a plain-click select, accept only an InvalidArgs refusal as index proof, bound child walks, and read GTK 4 origins lazily. * fix(computer-use): scroll the innermost Linux view that overflows, and bound the scroll search ScrollTo now runs on each ancestor that overflows its own box, innermost first, so an inner scroller moves before the page; coordinate scrolls start from the deepest node under the point. Cap the scroll bar search to small containers, report a document at its end as a no-op, keep looking past an unusable spanning child, and look up GTK 4 window names once per operation. --- native/computer-use-linux/runtime.py | 484 ++++++++++++++++-- .../computer-use-linux/runtime_render_test.py | 168 +++++- skill-guides/orca-computer-use.md | 2 +- src/cli/skills/bundled-skill-guides.ts | 2 +- 4 files changed, 601 insertions(+), 55 deletions(-) diff --git a/native/computer-use-linux/runtime.py b/native/computer-use-linux/runtime.py index 498fb998bb8..4e9639339b7 100644 --- a/native/computer-use-linux/runtime.py +++ b/native/computer-use-linux/runtime.py @@ -156,20 +156,93 @@ class GeometryReader: finally: Atspi.set_timeout(ATSPI_METHOD_TIMEOUT_MS, ATSPI_STARTUP_TIMEOUT_MS) - def rect(self, node): - return screen_rect(node, self.read) - def screen_rect(node, read=attempt): + return extents_rect(node, Atspi.CoordType.SCREEN, read) + + +def extents_rect(node, coord_type, read=attempt): component = read(node.get_component_iface) if component is None: return None - rect = read(lambda: Atspi.Component.get_extents(component, Atspi.CoordType.SCREEN)) + rect = read(lambda: Atspi.Component.get_extents(component, coord_type)) if rect is None or rect.width <= 0 or rect.height <= 0: return None return Rect(float(rect.x), float(rect.y), float(rect.width), float(rect.height)) +UNREAD = object() + + +class Placement: + """Screen and window-relative rectangles for one window's nodes. + + GTK 4 reports SCREEN extents of [0, 0, w, h] for nearly every node, so its rectangles come from WINDOW + extents plus the X11 client origin (agent-desktop probes/linux/FINDINGS.md L23-37). + """ + + def __init__(self, app, window): + self.app, self.window = app, window + self.base = self._origin = UNREAD + self.window_coords = toolkit_kind(app) == "gtk4" + + @property + def origin(self): + if self._origin is UNREAD: + self._origin = (gtk4_client_origin(self.app, self.window) + if self.window_coords and not wayland_session() else None) + return self._origin + + def screen(self, node, read=attempt): + if not self.window_coords: + return screen_rect(node, read) + rect = extents_rect(node, Atspi.CoordType.WINDOW, read) if self.origin is not None else None + return None if rect is None else Rect(rect.x + self.origin[0], rect.y + self.origin[1], rect.width, rect.height) + + def bounds(self): + if self.window_coords and wayland_session(): + # Why: Wayland capture finds the window through the compositor and only checks its size. + return screen_rect(self.window) + return self.screen(self.window) + + def frame(self, node, read=attempt): + coord_type = Atspi.CoordType.WINDOW if self.window_coords else Atspi.CoordType.SCREEN + if self.base is UNREAD: + self.base = extents_rect(self.window, coord_type, read) + rect = self.base if node is self.window else extents_rect(node, coord_type, read) + if rect is None or self.base is None: + return None + return Rect(rect.x - self.base.x, rect.y - self.base.y, rect.width, rect.height) + + +# Why per operation: list-windows places every window of an app, and each lookup is a subprocess. +_x11_windows_by_pid = {} + + +def gtk4_client_origin(app, window): + xdotool = shutil.which("xdotool") + if not xdotool: + return None + pid = pid_of(app) + if pid not in _x11_windows_by_pid: + ids = x11_window_ids(app, xdotool) or [] + _x11_windows_by_pid[pid] = [(value, x11_window_name(xdotool, value) if len(ids) > 1 else None) for value in ids] + windows = _x11_windows_by_pid[pid] + if len(windows) > 1: + title = name_of(window) + windows = [item for item in windows if item[1] == title] + return x11_client_origin(int(windows[0][0])) if len(windows) == 1 else None + + +def x11_window_name(xdotool, window_id): + try: + result = subprocess.run([xdotool, "getwindowname", window_id], check=False, capture_output=True, + text=True, timeout=2) + except (OSError, subprocess.TimeoutExpired): + return None + return result.stdout.rstrip("\n") if result.returncode == 0 else None + + def desktop_apps(): for _, app in children(desktop_root()): if name_of(app): @@ -323,36 +396,91 @@ def restore_pointer_window(app, window): restore_window(app, window) if not wait_window_focused(window): raise RuntimeError("window_not_focused: window restoration did not focus the target window; no pointer input was sent") - return screen_rect(window) + + +X11_WINDOW = ctypes.c_ulong +X11_ERROR_HANDLER = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p) +# Why kept: Xlib's default handler exits the process on a BadWindow from a window that closed mid-read. +_ignore_x11_errors = X11_ERROR_HANDLER(lambda _display, _event: 0) + + +@contextmanager +def x11_display(): + """libX11 and an open display, or (None, None) when no X11 display answers.""" + try: + x = ctypes.CDLL("libX11.so.6") + except OSError: + yield None, None + return + pointer, window, integer = ctypes.c_void_p, X11_WINDOW, ctypes.c_int + for name, result, args in ( + ("XOpenDisplay", pointer, [ctypes.c_char_p]), + ("XCloseDisplay", integer, [pointer]), + ("XSetErrorHandler", X11_ERROR_HANDLER, [X11_ERROR_HANDLER]), + ("XDefaultRootWindow", window, [pointer]), + ("XQueryPointer", integer, [pointer, window, ctypes.POINTER(window), ctypes.POINTER(window), + *[ctypes.POINTER(integer)] * 4, ctypes.POINTER(ctypes.c_uint)]), + ("XTranslateCoordinates", integer, [pointer, window, window, integer, integer, ctypes.POINTER(integer), + ctypes.POINTER(integer), ctypes.POINTER(window)]), + ("XInternAtom", ctypes.c_ulong, [pointer, ctypes.c_char_p, integer]), + ("XGetWindowProperty", integer, [pointer, window, ctypes.c_ulong, ctypes.c_long, ctypes.c_long, integer, + ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(integer), + ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.POINTER(ctypes.c_long))]), + ("XFree", integer, [pointer]), + ): + fn = getattr(x, name) + fn.restype, fn.argtypes = result, args + display = x.XOpenDisplay(None) + if not display: + yield None, None + return + previous = x.XSetErrorHandler(_ignore_x11_errors) + try: + yield x, display + finally: + x.XCloseDisplay(display) + x.XSetErrorHandler(previous) def x11_pointer_state(): """The X11 pointer's root position (None off the default screen) and modifier mask, or None with no X11 display.""" - try: - x = ctypes.CDLL("libX11.so.6") - except OSError: - return None - pointer, window, integer = ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int - x.XOpenDisplay.restype, x.XOpenDisplay.argtypes = pointer, [ctypes.c_char_p] - x.XDefaultRootWindow.restype, x.XDefaultRootWindow.argtypes = window, [pointer] - x.XQueryPointer.restype = integer - x.XQueryPointer.argtypes = [pointer, window, ctypes.POINTER(window), ctypes.POINTER(window), - *[ctypes.POINTER(integer)] * 4, ctypes.POINTER(ctypes.c_uint)] - x.XCloseDisplay.argtypes = [pointer] - display = x.XOpenDisplay(None) - if not display: - return None - try: - root, child = window(), window() - root_x, root_y, window_x, window_y, mask = integer(), integer(), integer(), integer(), ctypes.c_uint() + with x11_display() as (x, display): + if display is None: + return None + root, child = X11_WINDOW(), X11_WINDOW() + root_x, root_y, window_x, window_y = (ctypes.c_int() for _ in range(4)) + mask = ctypes.c_uint() # Why keep the mask on False: that only means the pointer is on another screen; the modifiers are still valid. if not x.XQueryPointer(display, x.XDefaultRootWindow(display), ctypes.byref(root), ctypes.byref(child), ctypes.byref(root_x), ctypes.byref(root_y), ctypes.byref(window_x), ctypes.byref(window_y), ctypes.byref(mask)): return None, None, mask.value return root_x.value, root_y.value, mask.value - finally: - x.XCloseDisplay(display) + + +def x11_client_origin(window_id): + """Where the visible area of an X11 client window starts on the root: its origin plus its client-side shadow.""" + with x11_display() as (x, display): + if display is None: + return None + root_x, root_y, child = ctypes.c_int(), ctypes.c_int(), X11_WINDOW() + if not x.XTranslateCoordinates(display, window_id, x.XDefaultRootWindow(display), 0, 0, + ctypes.byref(root_x), ctypes.byref(root_y), ctypes.byref(child)): + return None + shadow = (0, 0) + atom = x.XInternAtom(display, b"_GTK_FRAME_EXTENTS", 1) + actual_type, actual_format = ctypes.c_ulong(), ctypes.c_int() + count, remaining, data = ctypes.c_ulong(), ctypes.c_ulong(), ctypes.POINTER(ctypes.c_long)() + if atom and x.XGetWindowProperty(display, window_id, atom, 0, 4, 0, 6, ctypes.byref(actual_type), + ctypes.byref(actual_format), ctypes.byref(count), ctypes.byref(remaining), + ctypes.byref(data)) == 0 and data: + try: + if actual_format.value == 32 and count.value == 4: + shadow = (int(data[0]), int(data[2])) # left, right, top, bottom + finally: + x.XFree(data) + return root_x.value + shadow[0], root_y.value + shadow[1] @contextmanager @@ -1293,7 +1421,9 @@ def app_json(app): def window_json(app, index, window): - bounds = screen_rect(window) + bounds = Placement(app, window).bounds() + # Why the SCREEN fallback: a GTK 4 window with no known origin still has a true size, just no position. + size = bounds or screen_rect(window) showing = has_state(window, Atspi.StateType.SHOWING) return { "index": index, @@ -1302,8 +1432,8 @@ def window_json(app, index, window): "title": name_of(window), "x": round(bounds.x) if bounds else None, "y": round(bounds.y) if bounds else None, - "width": max(0, round(bounds.width if bounds else 0)), - "height": max(0, round(bounds.height if bounds else 0)), + "width": max(0, round(size.width if size else 0)), + "height": max(0, round(size.height if size else 0)), "isMinimized": not showing, "isOffscreen": not showing, "screenIndex": None, @@ -1317,7 +1447,8 @@ def make_snapshot(query, include_screenshot, window_id=None, window_index=None, if restore: restore_window(app, window) window_index, window = choose_window(app, window_id, window_index) - bounds = screen_rect(window) + placement = Placement(app, window) + bounds = placement.bounds() tree_root, root_path = window, [window_index] if root is not None: tree_root = find_element(app, root) @@ -1336,12 +1467,13 @@ def make_snapshot(query, include_screenshot, window_id=None, window_index=None, app_info = app_json(app) window_title = name_of(window) screenshot = capture_png(bounds, app, window) if include_screenshot else None + if include_screenshot and bounds is None and placement.window_coords: + screenshot = screenshot_failure("GTK 4 screenshot skipped: Orca can't tell where this window sits on screen; " + "use --no-screenshot and trust the tree") geometry = GeometryReader() for item in records: node = geometry_nodes[id(item)] - rect = bounds if node is window else geometry.rect(node) - if rect is not None and bounds is not None: - rect = Rect(rect.x - bounds.x, rect.y - bounds.y, rect.width, rect.height) + rect = placement.frame(node, geometry.read) item["frame"] = rect.to_json() if rect else None return { "snapshotId": str(uuid.uuid4()), @@ -1401,7 +1533,7 @@ def handshake_response(): "pressKey": True, "hotkey": has_hotkey, "pasteText": has_clipboard, - "scroll": not is_wayland, + "scroll": True, "drag": not is_wayland, "setValue": True, "performAction": True, @@ -1424,10 +1556,11 @@ def all_nodes(root): result = [] def walk(node): - if len(result) >= MAX_NODES: - return result.append(node) for _, child in children(node): + # Why check before each child: every lookup is an AT-SPI round trip, and a list can hold thousands. + if len(result) >= MAX_NODES: + return walk(child) walk(root) @@ -1556,8 +1689,12 @@ def activate_focused_entry(app, window): "verification": {"state": "unverified", "reason": "accessibility_action_unasserted"}} -def screen_point(window_rect, saved_element=None, x=None, y=None, node=None): - rect = screen_rect(node) if node is not None else None +def screen_point(placed, saved_element=None, x=None, y=None, node=None): + if placed.window_coords and placed.origin is None: + raise RuntimeError("unsupported capability: Orca can't tell where this GTK 4 window sits on screen, so " + "pointer input would miss; nothing was sent. Use an element's accessibility action or set-value") + window_rect = placed.screen(placed.window) + rect = placed.screen(node) if node is not None else None if rect is not None: return rect.x + rect.width / 2, rect.y + rect.height / 2 if saved_element is not None: @@ -1567,8 +1704,9 @@ def screen_point(window_rect, saved_element=None, x=None, y=None, node=None): return window_rect.x + float(x), window_rect.y + float(y) -def window_point(window_rect, saved_element=None, x=None, y=None, node=None): - point = screen_point(window_rect, saved_element, x, y, node) +def window_point(placed, saved_element=None, x=None, y=None, node=None): + point = screen_point(placed, saved_element, x, y, node) + window_rect = placed.screen(placed.window) if (window_rect is None or not window_rect.x <= point[0] < window_rect.x + window_rect.width or not window_rect.y <= point[1] < window_rect.y + window_rect.height): raise RuntimeError("coordinate action target lies outside the target window, so the pointer would land on " @@ -1696,6 +1834,241 @@ def drag_between(start, end): Atspi.generate_mouse_event(round(x), round(y), "b1r") +SCROLL_DIRECTIONS = {"up": ("vertical", -1), "down": ("vertical", 1), "left": ("horizontal", -1), "right": ("horizontal", 1)} +DOCUMENT_ROLES = {"document web", "document frame", "scroll pane"} +MAX_SCROLL_BAR_SIBLINGS = 8 +MAX_SCROLL_TO_PAGES = 10 +SCROLL_SETTLE_SECONDS = 1 + + +def scroll_direction(raw): + direction = str(raw or "").strip().lower() + if not direction: + raise RuntimeError("direction is required") + if direction not in SCROLL_DIRECTIONS: + raise RuntimeError(f"unsupported scroll direction: {direction}") + return SCROLL_DIRECTIONS[direction] + + +def scroll_without_pointer(window, node, placed, x, y, direction, pages): + """Scroll through scroll bar values or Component.ScrollTo, which move no pointer and raise no window + (agent-desktop actions/scroll/scroll_bus.rs; FINDINGS L4-22).""" + axis, sign = scroll_direction(direction) + pages = require_positive_number(1 if pages is None else pages, "pages") + if node is None and x is not None and y is not None: + node = node_at(window, placed, float(x), float(y), [MAX_NODES]) + at_limit, budget = None, [MAX_NODES] + # Why innermost first: like a wheel, the nearest view that can move takes the scroll, and one at its end hands it out. + for container in ancestors_to(node, window): + bar = scroll_bar(container, axis) + if bar is not None: + action = write_scroll_bar(container, bar, axis, sign, pages) + elif float(pages).is_integer(): + action = scroll_to_pages(container, placed, axis, sign, int(pages), budget) + else: + continue + if action is not None and action["verification"].get("reason") != "suspected_noop": + return action + at_limit = at_limit or action + return at_limit + + +def ancestors_to(node, window): + found, current = [], node + for _ in range(MAX_DEPTH): + if current is None: + break + found.append(current) + if current is window or current == window: + break + current = attempt(lambda current=current: current.get_parent()) + return found + + +def node_at(window, placed, x, y, budget): + """The deepest node whose window-relative frame holds the point, preferring later (topmost) siblings.""" + node = window + for _ in range(MAX_DEPTH): + hit = None + count = int(attempt(lambda node=node: node.get_child_count(), 0) or 0) + for index in range(count - 1, -1, -1): + budget[0] -= 1 + if budget[0] < 0: + return node + child = attempt(lambda node=node, index=index: node.get_child_at_index(index)) + frame = placed.frame(child) if child is not None else None + if frame is not None and frame.x <= x < frame.x + frame.width and frame.y <= y < frame.y + frame.height: + hit = child + break + if hit is None: + return node + node = hit + return node + + +def scroll_bar(container, axis): + vertical, horizontal = (getattr(Atspi.StateType, name, None) for name in ("VERTICAL", "HORIZONTAL")) + # Why capped: scroll bars sit beside one viewport child, and reading every row of a big list costs the app memory. + if int(attempt(lambda: container.get_child_count(), 0) or 0) > MAX_SCROLL_BAR_SIBLINGS: + return None + for _, child in children(container): + if role_of(child).lower() != "scroll bar": + continue + if vertical is not None and has_state(child, vertical): + matches = axis == "vertical" + elif horizontal is not None and has_state(child, horizontal): + matches = axis == "horizontal" + else: + rect = screen_rect(child) + matches = rect is not None and (rect.height > rect.width) == (axis == "vertical") + value = attempt(lambda child=child: child.get_value_iface()) if matches else None + if value is None: + continue + low, high, current = (attempt(lambda read=read: read(value)) for read in ( + Atspi.Value.get_minimum_value, Atspi.Value.get_maximum_value, Atspi.Value.get_current_value)) + if None not in (low, high, current) and high > low: + return value, float(low), float(high), float(current) + return None + + +def write_scroll_bar(container, bar, axis, sign, pages): + value, low, high, current = bar + viewport = screen_rect(container) + if viewport is None: + return None + # Why the viewport length: toolkit adjustments count pixels, so one page is one viewport (scroll_plan.rs). + page = viewport.height if axis == "vertical" else viewport.width + wanted = min(high, max(low, current + sign * pages * page)) + action = {"path": "accessibility", "actionName": "scrollBarValue", "fallbackReason": None} + if abs(wanted - current) < 0.5: + action["verification"] = {"state": "unverified", "reason": "suspected_noop"} + return action + if not attempt(lambda: Atspi.Value.set_current_value(value, wanted), False): + return None + readback = attempt(lambda: Atspi.Value.get_current_value(value)) + action["verification"] = ({"state": "verified", "property": "value"} + if readback is not None and abs(float(readback) - wanted) < 0.5 + else {"state": "unverified", "reason": "value_mismatch"}) + return action + + +def scroll_to_pages(container, placed, axis, sign, pages, budget): + edges = {("vertical", 1): "TOP_EDGE", ("vertical", -1): "BOTTOM_EDGE", + ("horizontal", 1): "LEFT_EDGE", ("horizontal", -1): "RIGHT_EDGE"} + scroll_type = getattr(getattr(Atspi, "ScrollType", None), edges[(axis, sign)], None) + if scroll_type is None: + return None + moved = accepted = 0 + at_end = False + for _ in range(min(pages, MAX_SCROLL_TO_PAGES)): + viewport = placed.frame(container) + if viewport is None: + break + start, length = (viewport.y, viewport.height) if axis == "vertical" else (viewport.x, viewport.width) + item = item_past_edge(container, placed, axis, sign, start, start + length, MAX_DEPTH, budget) + at_end = item is None and budget[0] >= 0 + component = attempt(lambda: item.get_component_iface()) if item is not None else None + before = placed.frame(item) if component is not None else None + if before is None or not attempt(lambda: Atspi.Component.scroll_to(component, scroll_type), False): + break + accepted += 1 + if not wait_item_moved(item, placed, axis, before): + break + moved += 1 + if not accepted: + # Why only documents: a document with nothing past its edge is at its end, while other nodes may not scroll. + if at_end and role_of(container).lower() in DOCUMENT_ROLES: + return {"path": "accessibility", "actionName": "scrollTo", "fallbackReason": None, + "verification": {"state": "unverified", "reason": "suspected_noop"}} + return None + # Why an action after any page: once the document moved, falling back to the pointer would scroll it twice. + verification = ({"state": "unverified", "reason": "accessibility_action_unasserted"} if moved + else {"state": "unverified", "reason": "suspected_noop"}) + return {"path": "accessibility", "actionName": "scrollTo", "fallbackReason": None, "verification": verification} + + +def item_past_edge(node, placed, axis, sign, viewport_start, viewport_end, depth, budget): + """The item that should lead the next page: the first one cut by or beyond the viewport edge we scroll toward.""" + if depth <= 0: + return None + edge = viewport_end if sign > 0 else viewport_start + count = int(attempt(lambda: node.get_child_count(), 0) or 0) + for index in (range(count) if sign > 0 else range(count - 1, -1, -1)): + # Why a shared budget: each child is an AT-SPI round trip, and a document can hold thousands. + budget[0] -= 1 + if budget[0] < 0: + return None + child = attempt(lambda index=index: node.get_child_at_index(index)) + frame = placed.frame(child) if child is not None else None + if frame is None: + continue + start, end = (frame.y, frame.y + frame.height) if axis == "vertical" else (frame.x, frame.x + frame.width) + if (start >= edge - 1) if sign > 0 else (end <= edge + 1): + return child + if start < edge < end: + inner = item_past_edge(child, placed, axis, sign, viewport_start, viewport_end, depth - 1, budget) + # Why the cut item itself: its hidden part leads the next page, unless it already fills the viewport. + leads = start > viewport_start + 1 if sign > 0 else end < viewport_end - 1 + if inner is not None or leads: + return inner if inner is not None else child + return None + + +def wait_item_moved(item, placed, axis, before): + """Wait until ScrollTo moved the item, so the next page is planned from settled geometry.""" + deadline = time.monotonic() + SCROLL_SETTLE_SECONDS + was = before.y if axis == "vertical" else before.x + while True: + frame = placed.frame(item) + now = None if frame is None else frame.y if axis == "vertical" else frame.x + if now is not None and abs(now - was) > 1: + return True + if time.monotonic() >= deadline: + return False + time.sleep(0.05) + + +def select_in_parent(app, node): + """Select a row through its container's Selection, proving the index names this row first (select_index.rs).""" + parent = attempt(lambda: node.get_parent()) if node is not None else None + selection = attempt(lambda: parent.get_selection_iface()) if parent is not None else None + index = attempt(lambda: node.get_index_in_parent()) if selection is not None else None + if index is None or index < 0 or not selection_indices_proven(app, parent, selection): + return None + if attempt(lambda: parent.get_child_at_index(index)) != node: + raise RuntimeError("stale element: the selection index no longer names this element; run get-app-state again and use a fresh element index") + multiselectable = getattr(Atspi.StateType, "MULTISELECTABLE", None) + # Why clear first: a plain click replaces the selection, while SelectChild adds to a multi-select list's. + if (multiselectable is not None and has_state(parent, multiselectable) + and not attempt(lambda: Atspi.Selection.clear_selection(selection), False)): + return None + if not attempt(lambda: Atspi.Selection.select_child(selection, index), False): + return None + attempt(lambda: node.clear_cache()) + verified = has_state(node, Atspi.StateType.SELECTED) + return {"path": "accessibility", "actionName": "selectChild", "fallbackReason": None, + "verification": {"state": "verified", "property": "selection"} if verified + else {"state": "unverified", "reason": "accessibility_action_unasserted"}} + + +def selection_indices_proven(app, parent, selection): + # Why: GTK 4 Selection counts item widgets, which can differ from its accessible children (select_index.rs). + if toolkit_kind(app) in {"gtk3", "qt", "chromium", "gecko"}: + return True + count = int(attempt(lambda: parent.get_child_count(), 0) or 0) + + def answer(index): + try: + Atspi.Selection.is_child_selected(selection, index) + return "answered" + except Exception as error: + # Why only InvalidArgs: a timeout or lost connection proves nothing about the index space. + return "refused" if "InvalidArgs" in str(error) else "unknown" + + # Why counted: the index spaces match exactly when the last child answers and the one past it is refused. + return count > 0 and answer(count - 1) == "answered" and answer(count) == "refused" + + def is_enter_key(raw): return key_name(raw) in {"Return", "KP_Enter"} @@ -2125,6 +2498,7 @@ def set_value(node, value): def run_operation(operation): + _x11_windows_by_pid.clear() tool = operation.get("tool") include_screenshot = not bool(operation.get("noScreenshot")) if tool == "handshake": @@ -2154,11 +2528,11 @@ def run_operation(operation): action = None def pointer_input(what, hint, points, send): - points(screen_rect(window)) # Why first: a stale or off-window target is not a reason to ask for a raise. + points(Placement(app, window)) # Why first: a stale or off-window target is not a reason to ask for a raise. require_pointer_route(operation, what, hint) - restored = restore_pointer_window(app, window) + restore_pointer_window(app, window) with pointer_put_back(): - send(*points(restored)) + send(*points(Placement(app, window))) if tool == "click": preferred = preferred_action(node) @@ -2168,7 +2542,8 @@ def run_operation(operation): else 1 ) has_modifiers = bool(str(operation.get("modifiers") or "").strip()) - semantic = not has_modifiers and operation.get("mouse_button", "left") == "left" and click_count <= 1 and preferred is not None + simple = not has_modifiers and operation.get("mouse_button", "left") == "left" and click_count <= 1 + semantic = simple and preferred is not None if semantic: names = action_names(node) name = (names[preferred] if preferred < len(names) else "") or "action" @@ -2176,9 +2551,11 @@ def run_operation(operation): if semantic and perform_action(node, preferred): action = {"path": "accessibility", "actionName": name, "fallbackReason": None} else: + action = select_in_parent(app, node) if simple else None + if action is None: pointer_input( "this click", "Click an element by --element-index that has an accessibility action, or use set-value.", - lambda bounds: [window_point(bounds, saved, operation.get("x"), operation.get("y"), node)], + lambda placed: [window_point(placed, saved, operation.get("x"), operation.get("y"), node)], lambda point: click_at(*point, operation.get("mouse_button", "left"), click_count, operation.get("modifiers")), ) action = {"path": "synthetic", "actionName": None, "fallbackReason": "actionUnsupported"} @@ -2196,20 +2573,23 @@ def run_operation(operation): raise RuntimeError(f'{operation.get("action", "")} is not a valid secondary action') action = {"path": "accessibility", "actionName": label, "fallbackReason": None} elif tool == "scroll": - pointer_input( - "scrolling", "", - lambda bounds: [window_point(bounds, saved, operation.get("x"), operation.get("y"), node)], - lambda point: scroll_at(*point, operation.get("direction"), operation.get("pages")), - ) - action = {"path": "synthetic", "actionName": "scroll", "fallbackReason": None} + action = scroll_without_pointer(window, node, Placement(app, window), operation.get("x"), operation.get("y"), + operation.get("direction"), operation.get("pages")) + if action is None: + pointer_input( + "scrolling", "This view exposes no scroll bar or scrollable document to scroll in the background.", + lambda placed: [window_point(placed, saved, operation.get("x"), operation.get("y"), node)], + lambda point: scroll_at(*point, operation.get("direction"), operation.get("pages")), + ) + action = {"path": "synthetic", "actionName": "scroll", "fallbackReason": None} elif tool == "drag": from_node = find_element(app, operation.get("fromElement")) to_node = find_element(app, operation.get("toElement")) pointer_input( "dragging", "", - lambda bounds: [ - window_point(bounds, operation.get("fromElement"), operation.get("from_x"), operation.get("from_y"), from_node), - window_point(bounds, operation.get("toElement"), operation.get("to_x"), operation.get("to_y"), to_node), + lambda placed: [ + window_point(placed, operation.get("fromElement"), operation.get("from_x"), operation.get("from_y"), from_node), + window_point(placed, operation.get("toElement"), operation.get("to_x"), operation.get("to_y"), to_node), ], drag_between, ) diff --git a/native/computer-use-linux/runtime_render_test.py b/native/computer-use-linux/runtime_render_test.py index 5e613d58896..aa2a9448a8b 100644 --- a/native/computer-use-linux/runtime_render_test.py +++ b/native/computer-use-linux/runtime_render_test.py @@ -22,6 +22,9 @@ class FakeStateType: SENSITIVE = 8 HAS_POPUP = 9 MULTI_LINE = 10 + VERTICAL = 11 + HORIZONTAL = 12 + MULTISELECTABLE = 13 class FakeStateSet: @@ -101,6 +104,15 @@ class FakeAccessible: self.name = name self.value = value self.children = list(children) + self.parent = None + for child in self.children: + child.parent = self + + def get_parent(self): + return self.parent + + def get_index_in_parent(self): + return self.parent.children.index(self) def get_child_count(self): return len(self.children) @@ -161,7 +173,7 @@ class SnapshotFixture(ExitStack): (runtime.time, "monotonic", lambda: self.clock), (runtime.Atspi, "set_timeout", self.set_timeout), (runtime.Atspi, "Component", types.SimpleNamespace(get_extents=self.extents)), - (runtime.Atspi, "CoordType", types.SimpleNamespace(SCREEN=0)), + (runtime.Atspi, "CoordType", types.SimpleNamespace(SCREEN=0, WINDOW=1)), (runtime, "capture_png", self.capture), (runtime, "restore_window", lambda *_: self.restore()), (runtime, "x11_pointer_state", lambda: self.pointer), @@ -673,6 +685,160 @@ class RuntimeRenderTest(unittest.TestCase): self.assertEqual(effects, []) keys.assert_not_called() + def test_gtk4_rectangles_come_from_window_extents_and_the_x11_client_origin(self): + button = FakeAccessible("push button", "Open") + window = FakeAccessible("frame", "Files", children=[button]) + app = FakeAccessible("application", "Files", children=[window]) + app.get_toolkit_name, app.get_toolkit_version = (lambda: "GTK"), (lambda: "4.14.5") + # Why these numbers: GTK 4 answers SCREEN with [0, 0, w, h] (agent-desktop FINDINGS L23-37). + extents = {(window, 0): (0, 0, 800, 600), (window, 1): (0, 0, 800, 600), + (button, 0): (0, 0, 64, 44), (button, 1): (16, 299, 64, 44)} + for node in (window, button): + node.get_component_iface = lambda node=node: node + def get_extents(node, coord_type): + x, y, width, height = extents[(node, coord_type)] + return types.SimpleNamespace(x=x, y=y, width=width, height=height) + for origin, wayland in (((1000, 500), False), (None, False), (None, True)): + with self.subTest(origin=origin, wayland=wayland), \ + patch.object(runtime.Atspi, "Component", types.SimpleNamespace(get_extents=get_extents), create=True), \ + patch.object(runtime.Atspi, "CoordType", types.SimpleNamespace(SCREEN=0, WINDOW=1), create=True), \ + patch.object(runtime, "gtk4_client_origin", lambda *_: origin), \ + patch.object(runtime, "wayland_session", lambda: wayland): + placed = runtime.Placement(app, window) + self.assertEqual(placed.frame(button).to_json(), {"x": 16, "y": 299, "width": 64, "height": 44}) + if origin: + self.assertEqual(runtime.window_point(placed, {"index": 1}, node=button), (1048, 821)) + else: + with self.assertRaisesRegex(RuntimeError, "GTK 4 window"): + runtime.window_point(placed, {"index": 1}, node=button) + + def test_background_scroll_pages_a_scroll_bar_and_hands_the_end_to_the_outer_view(self): + def view(name, value, high, children=()): + bar = FakeAccessible("scroll bar", name + " bar") + bar.position = value + bar.high = high + bar.get_state_set = lambda: FakeStateSet(FakeStateType.VERTICAL) + bar.get_value_iface = lambda: bar + pane = FakeAccessible("scroll pane", name, children=[bar, *children]) + return pane, bar + row = FakeAccessible("list item", "Row") + inner, inner_bar = view("inner", 300, 300, [row]) + outer, outer_bar = view("outer", 0, 2000, [inner]) + writes = [] + def set_value(bar, value): + writes.append((bar.name, value)) + bar.position = value + return True + value_api = types.SimpleNamespace(get_minimum_value=lambda bar: 0, get_maximum_value=lambda bar: bar.high, + get_current_value=lambda bar: bar.position, set_current_value=set_value) + with SnapshotFixture(FakeAccessible("frame", "Editor", children=[outer])) as fixture, \ + patch.object(runtime.Atspi, "Value", value_api, create=True): + fixture.bounds[outer] = runtime.Rect(100, 200, 300, 250) + element = next(item for item in runtime.make_snapshot("Fixture", False)["elements"] if item["name"] == "Row") + result = runtime.run_operation({"tool": "scroll", "app": "Fixture", "element": element, "direction": "down", + "pages": 2, "noScreenshot": True}) + self.assertEqual(writes, [("outer bar", 500)]) + self.assertEqual(result["action"]["verification"], {"state": "verified", "property": "value"}) + self.assertEqual(result["action"]["delivery"], "background") + runtime.run_operation({"tool": "scroll", "app": "Fixture", "element": element, "direction": "up", + "pages": 0.5, "noScreenshot": True}) + self.assertEqual(writes[-1], ("inner bar", 300 - 0.5 * fixture.bounds[inner].height)) + + def test_background_scroll_pages_a_document_with_scroll_to(self): + items = [FakeAccessible("paragraph", f"Item {index}") for index in range(6)] + document = FakeAccessible("document web", "Page", children=items) + scrolled = [] + offset = [0] + with SnapshotFixture(FakeAccessible("frame", "Browser", children=[document])) as fixture: + fixture.bounds[document] = runtime.Rect(0, 100, 400, 300) + def place(): + for index, item in enumerate(items): + fixture.bounds[item] = runtime.Rect(0, 100 + index * 120 - offset[0], 400, 120) + place() + def scroll_to(item, edge): + scrolled.append((item.name, edge)) + offset[0] += fixture.bounds[item].y - 100 + place() + return True + with patch.object(runtime.Atspi.Component, "scroll_to", scroll_to, create=True), \ + patch.object(runtime.Atspi, "ScrollType", types.SimpleNamespace(TOP_EDGE="top", BOTTOM_EDGE="bottom"), create=True): + result = runtime.run_operation({"tool": "scroll", "app": "Fixture", "x": 50, "y": 50, + "direction": "down", "pages": 3, "noScreenshot": True}) + # Why Item 2: it spans 340-460 and the viewport ends at 400, so its hidden half leads the next page. + # The third page finds nothing past the document's end, and the two pages already moved still count. + self.assertEqual(scrolled, [("Item 2", "top"), ("Item 4", "top")]) + self.assertEqual(result["action"]["actionName"], "scrollTo") + + def test_background_scroll_moves_the_inner_scroller_before_the_page(self): + inner_items = [FakeAccessible("list item", f"Message {index}") for index in range(4)] + log = FakeAccessible("panel", "Chat log", children=inner_items) + page_items = [FakeAccessible("paragraph", f"Section {index}") for index in range(4)] + document = FakeAccessible("document web", "Page", children=[log, *page_items]) + scrolled = [] + with SnapshotFixture(FakeAccessible("frame", "Browser", children=[document])) as fixture: + fixture.bounds[fixture.root] = runtime.Rect(0, 0, 400, 400) + fixture.bounds[document] = runtime.Rect(0, 0, 400, 400) + fixture.bounds[log] = runtime.Rect(0, 0, 400, 100) + for index, item in enumerate(inner_items): + fixture.bounds[item] = runtime.Rect(0, index * 60, 400, 60) + for index, item in enumerate(page_items): + fixture.bounds[item] = runtime.Rect(0, 100 + index * 150, 400, 150) + element = next(item for item in runtime.make_snapshot("Fixture", False)["elements"] if item["name"] == "Message 0") + def scroll_to(item, _): + scrolled.append(item.name) + fixture.bounds[item] = runtime.Rect(0, 0, 400, 60) + return True + with patch.object(runtime.Atspi.Component, "scroll_to", scroll_to, create=True), \ + patch.object(runtime.Atspi, "ScrollType", types.SimpleNamespace(TOP_EDGE="top"), create=True): + runtime.run_operation({"tool": "scroll", "app": "Fixture", "element": element, "direction": "down", + "pages": 1, "noScreenshot": True}) + # Why Message 1: it spans 60-120 and the chat log's own box ends at 100, so the log scrolls, not the page. + self.assertEqual(scrolled, ["Message 1"]) + + def test_click_without_an_action_selects_the_row_only_when_its_index_is_proven(self): + cases = ( + ("Qt", "6.6", None, "selected"), + ("GTK", "4.14", (True, False), "selected"), + ("GTK", "4.14", (True, True), "refused"), + ("GTK", "4.14", (True, "timeout"), "refused"), + ("Qt", "6.6", "replaced", "stale"), + ("GTK", "3.24", "multiple", "selected"), + ) + for toolkit, version, counted, expected in cases: + rows = [FakeAccessible("list item", name) for name in ("Mouse", "Keyboard")] + listing = FakeAccessible("list", "Devices", children=rows) + selected = ["Mouse"] if counted == "multiple" else [] + listing.get_state_set = lambda: FakeStateSet(*([FakeStateType.MULTISELECTABLE] if counted == "multiple" else [])) + listing.get_selection_iface = lambda: listing + if counted == "replaced": + rows[1].get_index_in_parent = lambda: 0 + for row in rows: + row.get_state_set = lambda row=row: FakeStateSet(*([FakeStateType.SELECTED] if row.name in selected else [])) + def is_child_selected(_, index): + answer = (counted if isinstance(counted, tuple) else (True, False))[index - len(rows) + 1] + if answer is not True: + raise RuntimeError("Timeout was reached" if answer == "timeout" else "GDBus.Error:org.freedesktop.DBus.Error.InvalidArgs") + return False + selection = types.SimpleNamespace( + select_child=lambda _, index: selected.append(rows[index].name) or True, + clear_selection=lambda _: selected.clear() or True, + is_child_selected=is_child_selected) + with self.subTest(toolkit=toolkit, counted=counted), \ + SnapshotFixture(FakeAccessible("frame", "Settings", children=[listing])) as fixture, \ + patch.object(runtime.Atspi, "Selection", selection, create=True), \ + patch.object(runtime, "gtk4_client_origin", lambda *_: (0, 0)): + fixture.app.get_toolkit_name, fixture.app.get_toolkit_version = (lambda: toolkit), (lambda: version) + element = next(item for item in runtime.make_snapshot("Fixture", False)["elements"] if item["name"] == "Keyboard") + request = {"tool": "click", "app": "Fixture", "element": element, "noScreenshot": True} + if expected == "selected": + result = runtime.run_operation(request) + self.assertEqual(selected, ["Keyboard"]) + self.assertEqual(result["action"]["verification"], {"state": "verified", "property": "selection"}) + else: + with self.assertRaisesRegex(RuntimeError, "background_unavailable" if expected == "refused" else "stale element"): + runtime.run_operation(request) + self.assertEqual(selected, []) + def test_text_entry_inserts_into_the_focused_field_of_a_background_window(self): cases = ( ("type_text", "🚀 café", (6, 11), "Hello 🚀 café", 12), diff --git a/skill-guides/orca-computer-use.md b/skill-guides/orca-computer-use.md index 97bc63f0d1d..5a6158e40a4 100644 --- a/skill-guides/orca-computer-use.md +++ b/skill-guides/orca-computer-use.md @@ -155,7 +155,7 @@ On macOS, background actions that would open a menu or dialog over the user are On macOS, every action without `--restore-window` runs in the background: the target app is not brought forward, the user's frontmost app and key window stay put, and the real pointer does not move. `capabilities` reports this as `supports.input.background`. -On Linux, element clicks through the element's accessibility action, `set-value`, `type-text --element-index` and secondary actions run without raising the window or moving the pointer, and Return in a focused GTK text field runs its activate action. Anything that needs the real pointer (clicks with no accessibility action, right, middle, multiple or modified clicks, scrolling, drags) or the focused window (other keys, typing with no focused editable field) is refused with `background_unavailable` and nothing is sent; so is a click that would open a menu, a keyboard-grabbing popup or a dialog (a GTK 4 or Qt label ending in `…`). Ask the user before retrying with `--restore-window`, which raises only the target window, refuses a window on another workspace and puts the cursor back. On Wayland, synthetic pointer and key input never reaches native windows, so it is refused even with the flag. `action.delivery` is measured: `foreground` when the input went to the window in front or the target came forward. +On Linux, element clicks through the element's accessibility action (or, for a list row with none, its list's selection), `set-value`, `type-text --element-index` and secondary actions run without raising the window or moving the pointer, and Return in a focused GTK text field runs its activate action. Scrolling moves the nearest scroll bar under the element or point by whole viewports, or pages a web document, also in the background. Anything that needs the real pointer (other clicks with no accessibility action, right, middle, multiple or modified clicks, scrolls in a view with no scroll bar or document, drags) or the focused window (other keys, typing with no focused editable field) is refused with `background_unavailable` and nothing is sent; so is a click that would open a menu, a keyboard-grabbing popup or a dialog (a GTK 4 or Qt label ending in `…`). Ask the user before retrying with `--restore-window`, which raises only the target window, refuses a window on another workspace and puts the cursor back. On Wayland, synthetic pointer and key input never reaches native windows, so it is refused even with the flag. `action.delivery` is measured: `foreground` when the input went to the window in front or the target came forward. On Windows, these actions go through UI Automation when the control supports them, without moving the pointer or sending keys: element clicks, `set-value` (including sliders), scrolls of an element or of the scrollable area under `--x`/`--y` (fractional `--pages` too), and secondary actions such as `Invoke`, `Toggle`, `Select`, `Expand`, `Collapse` and `ScrollToVisible` (the last brings a list or tree item into view). Some apps bring their own window forward when driven this way (WPF apps do for most of these), so read `action.delivery`: `background` means the user's foreground window stayed put, `foreground` means the target came forward. Clicks by coordinates, right, middle, modified and multi-clicks, clicks on elements with no `Invoke`, `Select` or `Toggle` action, scrolls over nothing scrollable, and drags need the real mouse, so they are refused with `background_unavailable` and nothing is sent. With `--restore-window` (after asking the user), only the target window comes forward, never one on another virtual desktop, and the pointer goes back where it was. diff --git a/src/cli/skills/bundled-skill-guides.ts b/src/cli/skills/bundled-skill-guides.ts index 4dc65ebf80d..10764a41b49 100644 --- a/src/cli/skills/bundled-skill-guides.ts +++ b/src/cli/skills/bundled-skill-guides.ts @@ -1176,7 +1176,7 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "", "On macOS, every action without `--restore-window` runs in the background: the target app is not brought forward, the user's frontmost app and key window stay put, and the real pointer does not move. `capabilities` reports this as `supports.input.background`.", "", - "On Linux, element clicks through the element's accessibility action, `set-value`, `type-text --element-index` and secondary actions run without raising the window or moving the pointer, and Return in a focused GTK text field runs its activate action. Anything that needs the real pointer (clicks with no accessibility action, right, middle, multiple or modified clicks, scrolling, drags) or the focused window (other keys, typing with no focused editable field) is refused with `background_unavailable` and nothing is sent; so is a click that would open a menu, a keyboard-grabbing popup or a dialog (a GTK 4 or Qt label ending in `…`). Ask the user before retrying with `--restore-window`, which raises only the target window, refuses a window on another workspace and puts the cursor back. On Wayland, synthetic pointer and key input never reaches native windows, so it is refused even with the flag. `action.delivery` is measured: `foreground` when the input went to the window in front or the target came forward.", + "On Linux, element clicks through the element's accessibility action (or, for a list row with none, its list's selection), `set-value`, `type-text --element-index` and secondary actions run without raising the window or moving the pointer, and Return in a focused GTK text field runs its activate action. Scrolling moves the nearest scroll bar under the element or point by whole viewports, or pages a web document, also in the background. Anything that needs the real pointer (other clicks with no accessibility action, right, middle, multiple or modified clicks, scrolls in a view with no scroll bar or document, drags) or the focused window (other keys, typing with no focused editable field) is refused with `background_unavailable` and nothing is sent; so is a click that would open a menu, a keyboard-grabbing popup or a dialog (a GTK 4 or Qt label ending in `…`). Ask the user before retrying with `--restore-window`, which raises only the target window, refuses a window on another workspace and puts the cursor back. On Wayland, synthetic pointer and key input never reaches native windows, so it is refused even with the flag. `action.delivery` is measured: `foreground` when the input went to the window in front or the target came forward.", "", "On Windows, these actions go through UI Automation when the control supports them, without moving the pointer or sending keys: element clicks, `set-value` (including sliders), scrolls of an element or of the scrollable area under `--x`/`--y` (fractional `--pages` too), and secondary actions such as `Invoke`, `Toggle`, `Select`, `Expand`, `Collapse` and `ScrollToVisible` (the last brings a list or tree item into view). Some apps bring their own window forward when driven this way (WPF apps do for most of these), so read `action.delivery`: `background` means the user's foreground window stayed put, `foreground` means the target came forward. Clicks by coordinates, right, middle, modified and multi-clicks, clicks on elements with no `Invoke`, `Select` or `Toggle` action, scrolls over nothing scrollable, and drags need the real mouse, so they are refused with `background_unavailable` and nothing is sent. With `--restore-window` (after asking the user), only the target window comes forward, never one on another virtual desktop, and the pointer goes back where it was.", "", From bff57f1e3726dd3e2624dae6f498515bf4c26de8 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:31:44 +0000 Subject: [PATCH 06/52] fix(browser): keep late page-opened tabs and system-browser opens from moving the user (#42199) A tab a page opened with no gesture counted as the agent's only within the agent's 20 s idle window, so a late open (an OAuth tab finishing after the agent went quiet) switched the user's visible tab. Track, per guest, whether an agent drove the page since the desktop user last gave it input, carry it into popups the page opens, and keep such opens in the background. A popup whose owner tab was gone handed any http(s) open to the system browser, including agent, phone and scripted ones, which took the foreground. Only the desktop user's own click opens it there now; the rest are reported blocked. --- .../input/browser-guest-input-gesture.ts | 7 +- .../manager/browser-manager-state.ts | 2 + .../manager/browser-manager-visibility.ts | 39 ++++- .../browser-manager-guest-popup-policy.ts | 17 +- .../browser-manager-popup-routing.test.ts | 152 ++++++++++++++++-- .../browser-manager-guest-cleanup.ts | 1 + .../browser-manager-registration.ts | 1 + 7 files changed, 194 insertions(+), 25 deletions(-) diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-input-gesture.ts b/src/main/browser/guest-lifecycle/input/browser-guest-input-gesture.ts index c94358b85ab..a88065e75f1 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-input-gesture.ts +++ b/src/main/browser/guest-lifecycle/input/browser-guest-input-gesture.ts @@ -38,7 +38,10 @@ export type BrowserGuestInputGesture = { export function trackBrowserGuestInputGesture( guest: WebContents, - { now = Date.now, onActivatingInput }: { now?: () => number; onActivatingInput?: () => void } = {} + { + now = Date.now, + onActivatingInput + }: { now?: () => number; onActivatingInput?: (byAgent: boolean) => void } = {} ): BrowserGuestInputGesture { let lastGestureAt: number | null = null let lastGestureByAgent = false @@ -46,7 +49,7 @@ export function trackBrowserGuestInputGesture( if (isActivatingBrowserGuestInput(input)) { lastGestureAt = now() lastGestureByAgent = isAgentInjectingInput(guest) - onActivatingInput?.() + onActivatingInput?.(lastGestureByAgent) } } let attached = false diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts index e0c93da3595..2ae5b243233 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts @@ -160,6 +160,8 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt protected readonly annotationViewportBridgeOpsByTabId = new Map>() protected readonly worktreeIdByTabId = new Map() protected readonly policyAttachedGuestIds = new Set() + // Guests an agent command targeted since the desktop user last gave them input. + protected readonly agentLedGuestIds = new Set() protected readonly offscreenGuestIds = new Set() protected readonly devToolsDock = new BrowserGuestDevToolsDock() protected readonly policyCleanupByGuestId = new Map void>() diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts index 89bb3d77c93..b585586dfe5 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts @@ -12,7 +12,8 @@ import { } from '../page-activity/browser-agent-activity' import { BrowserPageEvents, type BrowserPageEvent } from '../page-activity/browser-page-events' import { BrowserPageInputCredit } from '../../routing/input-ownership/browser-page-input-credit' -import { browserPopupPageId } from '../popups/browser-popup-page-id' +import { browserPopupPageId, browserPopupPageWebContentsId } from '../popups/browser-popup-page-id' +import { resolveBrowserRouteGuestPopupOpener } from '../../routing/guest-authority/browser-route-guest-popup-ownership' import type { RpcCallerIdentity } from '../../../runtime/rpc/callers/rpc-caller-identity' export abstract class BrowserManagerVisibility extends BrowserManagerState { @@ -37,7 +38,29 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState { /** Holds the page's agent marking for one queued command, from queueing until it settles. */ beginAgentCommand(browserPageId: string): AgentCommandLease { - return this.agentActivity.beginCommand(browserPageId) + const lease = this.agentActivity.beginCommand(browserPageId) + const guestId = + this.webContentsIdByTabId.get(browserPageId) ?? browserPopupPageWebContentsId(browserPageId) + // Only attached guests, whose teardown releases the lead. + if (lease.agent && guestId !== null && this.policyAttachedGuestIds.has(guestId)) { + this.agentLedGuestIds.add(guestId) + } + return lease + } + + /** A popup opened from a page the agent leads starts led too. */ + protected inheritAgentLead(openerWebContentsId: number, popupWebContentsId: number): void { + if ( + this.agentLedGuestIds.has(openerWebContentsId) && + this.policyAttachedGuestIds.has(popupWebContentsId) + ) { + this.agentLedGuestIds.add(popupWebContentsId) + } + } + + /** The desktop user's own input takes the page back from the agent. */ + protected releaseAgentLead(guestWebContentsId: number): void { + this.agentLedGuestIds.delete(guestWebContentsId) } /** Clears the agent marking from every page this SSH host was driving. */ @@ -65,9 +88,15 @@ export abstract class BrowserManagerVisibility extends BrowserManagerState { } } - /** An agent is driving the page this guest shows (a tab or a popup). */ - isAgentUsingGuest(guestWebContentsId: number): boolean { - return this.isAgentUsingPage(this.pageIdForGuest(guestWebContentsId)) + /** An agent drives the page this guest shows (a tab or a popup), or drove it since the desktop user last gave it input. */ + isAgentLeadingGuest(guestWebContentsId: number): boolean { + // SSH route popups skip guest policies, so they follow their opener's lead. + const leadingGuestId = + resolveBrowserRouteGuestPopupOpener(guestWebContentsId) ?? guestWebContentsId + return ( + this.agentLedGuestIds.has(leadingGuestId) || + this.isAgentUsingPage(this.pageIdForGuest(guestWebContentsId)) + ) } private pageIdForGuest(guestWebContentsId: number): string { diff --git a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts index bb23cd8463a..143ea7be548 100644 --- a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts @@ -29,12 +29,18 @@ import { requestBrowserExternalAppLaunch } from '../../prompts/browser-external- export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavigation { protected installGuestPopupPolicy(guest: Electron.WebContents): () => void { const gesture = trackBrowserGuestInputGesture(guest, { - onActivatingInput: () => this.creditPageInput(guest.id) + onActivatingInput: (byAgent) => { + this.creditPageInput(guest.id) + if (!byAgent) { + this.releaseAgentLead(guest.id) + } + } }) const handleDidCreateWindow = (window: Electron.BrowserWindow): void => { // Popups inherit ownership without replacing the primary guest registration. if (!isBrowserRouteGuestPopup(window.webContents.id)) { this.attachGuestPolicies(window.webContents, this.resolvePopupOwnerContext(guest.id)) + this.inheritAgentLead(guest.id, window.webContents.id) } } guest.on('did-create-window', handleDidCreateWindow) @@ -48,7 +54,7 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig // Only the desktop user's own click may bring a popup forward; agents and late opens wait. const showWhenAppActive = observed?.byAgent !== false const activateTab = disposition !== 'background-tab' - const agentOpened = observed?.byAgent !== false && this.isAgentUsingGuest(guest.id) + const agentOpened = observed?.byAgent !== false && this.isAgentLeadingGuest(guest.id) const browserTabId = this.resolvePopupOwnerContext(guest.id)?.browserTabId ?? null const externalUrl = normalizeExternalBrowserUrl(url) @@ -96,8 +102,8 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig webPreferences: { ...options.webPreferences, session: guest.session } }) } - } else if (externalUrl && !postBody) { - // Redact the Kagi bearer token before opening the OS browser. + } else if (externalUrl && !postBody && observed?.byAgent === false) { + // The OS browser takes the foreground, so only the desktop user's own click opens it. Redact Kagi's bearer token first. void shell.openExternal(redactKagiSessionToken(externalUrl)) this.forwardOrQueuePopupEvent(guest.id, { origin: safeOrigin(externalUrl), @@ -146,7 +152,7 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig guest.downloadURL(newTabUrl) return true } - const agentOpened = observed?.byAgent !== false && this.isAgentUsingGuest(guest.id) + const agentOpened = observed?.byAgent !== false && this.isAgentLeadingGuest(guest.id) if ( this.openLinkInOrcaTab( ownerContext.browserTabId, @@ -223,6 +229,7 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig return false } this.attachGuestPolicies(contents, owner) + this.inheritAgentLead(openerGuest.id, contents.id) return true }) const opened = Boolean(options.webContents || options.nativeWindow) diff --git a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts index 49d9a894e79..705f558cdae 100644 --- a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts @@ -44,6 +44,10 @@ vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ import { browserManager } from '../browser-manager' import { withAgentInputInjection } from '../../../cdp/input/agent-input-injection' import { runWithActiveRpcCaller } from '../../../../runtime/rpc/callers/active-call' +import { + registerBrowserRouteGuestPopup, + releaseBrowserRouteGuestPopup +} from '../../../routing/guest-authority/browser-route-guest-popup-ownership' import { guestNavigationMethods, rendererWebContentsId, @@ -73,7 +77,12 @@ describe('browserManager', () => { // #36804: headless serve pages have no renderer to own Orca's tab model. // orcad's Electron browser registers pages without a workspace, so there is no tab list to open into. - it("opens an agent's link behind the user's tab, and the user's own click in front", async () => { + function attachGuest(): { + guest: { id: number } + rendererSendMock: ReturnType + openLink: (url: string) => void + pressMouse: () => void + } { const rendererSendMock = vi.fn() const guest = { ...guestNavigationMethods(), @@ -99,11 +108,6 @@ describe('browserManager', () => { return null }) browserManager.attachGuestPolicies(guest as never) - browserManager.registerGuest({ - browserPageId: 'browser-1', - webContentsId: guest.id, - rendererWebContentsId - }) const handler: (details: { url: string frameName: string @@ -111,24 +115,46 @@ describe('browserManager', () => { disposition: string }) => unknown = guestSetWindowOpenHandlerMock.mock.calls[0][0] const inputEventHandler = guestOnMock.mock.calls.find(([event]) => event === 'input-event')?.[1] - const openLink = (url: string): void => { - handler({ url, frameName: '', features: '', disposition: 'foreground-tab' }) + return { + guest, + rendererSendMock, + openLink: (url) => { + handler({ url, frameName: '', features: '', disposition: 'foreground-tab' }) + }, + pressMouse: () => inputEventHandler({}, { type: 'mouseUp' }) } + } + + function registerAsTab(guest: { id: number }): void { + browserManager.registerGuest({ + browserPageId: 'browser-1', + webContentsId: guest.id, + rendererWebContentsId + }) + } + + function openedTabs(rendererSendMock: ReturnType): unknown[] { + return rendererSendMock.mock.calls.filter( + ([channel]) => channel === 'browser:open-link-in-orca-tab' + ) + } + + it("opens an agent's link behind the user's tab, and the user's own click in front", async () => { + const { guest, rendererSendMock, openLink, pressMouse } = attachGuest() + registerAsTab(guest) const command = runWithActiveRpcCaller({ kind: 'local-cli' }, () => browserManager.beginAgentCommand('browser-1') ) await withAgentInputInjection(guest as never, async () => { - inputEventHandler({}, { type: 'mouseUp' }) + pressMouse() }) openLink('https://docs.example.com/agent') - inputEventHandler({}, { type: 'mouseUp' }) + pressMouse() openLink('https://docs.example.com/user') command.end() - expect( - rendererSendMock.mock.calls.filter(([channel]) => channel === 'browser:open-link-in-orca-tab') - ).toEqual([ + expect(openedTabs(rendererSendMock)).toEqual([ [ 'browser:open-link-in-orca-tab', { browserPageId: 'browser-1', url: 'https://docs.example.com/agent', activate: false } @@ -139,4 +165,104 @@ describe('browserManager', () => { ] ]) }) + + it('keeps a tab the page opens long after the agent left behind the user, until the user uses the page', async () => { + vi.useFakeTimers() + const { guest, rendererSendMock, openLink, pressMouse } = attachGuest() + registerAsTab(guest) + runWithActiveRpcCaller({ kind: 'local-cli' }, () => + browserManager.beginAgentCommand('browser-1') + ).end() + + vi.advanceTimersByTime(60_000) + openLink('https://login.example.com/late') + pressMouse() + vi.advanceTimersByTime(5_000) + openLink('https://login.example.com/after-user') + + expect(openedTabs(rendererSendMock)).toEqual([ + [ + 'browser:open-link-in-orca-tab', + { browserPageId: 'browser-1', url: 'https://login.example.com/late', activate: false } + ], + [ + 'browser:open-link-in-orca-tab', + { browserPageId: 'browser-1', url: 'https://login.example.com/after-user' } + ] + ]) + }) + + it("keeps a late tab from a popup the agent's page opened behind the user", () => { + vi.useFakeTimers() + const { guest, rendererSendMock } = attachGuest() + registerAsTab(guest) + runWithActiveRpcCaller({ kind: 'local-cli' }, () => + browserManager.beginAgentCommand('browser-1') + ).end() + const popup = { ...guest, id: 146 } + const onDidCreateWindow = guestOnMock.mock.calls.find( + ([event]) => event === 'did-create-window' + )?.[1] + onDidCreateWindow({ webContents: popup }) + const popupHandler = guestSetWindowOpenHandlerMock.mock.calls[1][0] + + vi.advanceTimersByTime(60_000) + popupHandler({ + url: 'https://login.example.com/from-popup', + frameName: '', + features: '', + disposition: 'foreground-tab' + }) + + expect(openedTabs(rendererSendMock)).toEqual([ + [ + 'browser:open-link-in-orca-tab', + { browserPageId: 'browser-1', url: 'https://login.example.com/from-popup', activate: false } + ] + ]) + }) + + it("keeps a late tab from an SSH route popup of the agent's page behind the user", () => { + vi.useFakeTimers() + const { guest, rendererSendMock } = attachGuest() + registerAsTab(guest) + runWithActiveRpcCaller({ kind: 'local-cli' }, () => + browserManager.beginAgentCommand('browser-1') + ).end() + const routePopup = { ...guest, id: 147 } + registerBrowserRouteGuestPopup({ popupWebContentsId: 147, openerWebContentsId: guest.id }) + + vi.advanceTimersByTime(60_000) + browserManager.openNewTabPopup( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: openNewTabPopup reads only the guest fields this fake copies from the tab guest. + routePopup as never, + { url: 'https://login.example.com/from-route', frameName: '', disposition: 'foreground-tab' }, + null + ) + releaseBrowserRouteGuestPopup(147) + + expect(openedTabs(rendererSendMock)).toEqual([ + [ + 'browser:open-link-in-orca-tab', + { browserPageId: 'browser-1', url: 'https://login.example.com/from-route', activate: false } + ] + ]) + }) + + it("opens the system browser for a page with no tab only on the desktop user's own click", async () => { + const { guest, openLink, pressMouse } = attachGuest() + + await withAgentInputInjection(guest as never, async () => { + pressMouse() + }) + openLink('https://docs.example.com/agent') + openLink('https://docs.example.com/scripted') + expect(browserMocks.shellOpenExternalMock).not.toHaveBeenCalled() + + pressMouse() + openLink('https://docs.example.com/user') + expect(browserMocks.shellOpenExternalMock.mock.calls).toEqual([ + ['https://docs.example.com/user'] + ]) + }) }) diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-cleanup.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-cleanup.ts index bbefafd2190..4c83e95eb7d 100644 --- a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-cleanup.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-cleanup.ts @@ -16,6 +16,7 @@ export abstract class BrowserManagerGuestCleanup extends BrowserManagerGuestNavi this.policyCleanupByGuestId.delete(guestWebContentsId) } this.policyAttachedGuestIds.delete(guestWebContentsId) + this.agentLedGuestIds.delete(guestWebContentsId) this.offscreenGuestIds.delete(guestWebContentsId) this.popupOwnerContextByGuestId.delete(guestWebContentsId) this.pageInitiatedTabBudgetByRootGuestId.delete(guestWebContentsId) diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts index 55906091f9f..9b911ca9d60 100644 --- a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts @@ -222,6 +222,7 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli this.unregisterGuest(browserTabId) } this.policyAttachedGuestIds.clear() + this.agentLedGuestIds.clear() this.offscreenGuestIds.clear() // Also clean up guests attached before registration. for (const cleanup of this.policyCleanupByGuestId.values()) { From a36620afd0519980c95347392d0dff78d15faddc Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:33:07 -0800 Subject: [PATCH 07/52] perf(github): share automatic PR reads and reuse the host budget (#42033) * perf(github): share and pace timed pull request reads on the host Reuse exact completed results for automatic refreshes, back off unchanged settled pull requests, and route server revalidation through the existing host budget while preserving foreground reads and older clients. Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> * fix(github): preserve shared producer settlement and selected demand Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> * test(github): cover paired receipt retries and watch fairness * test(github): explain shared fake-clock fixture * test(github): typecheck host and renderer integration together * test(github): name exported fixture mock types * Revert "test(github): typecheck host and renderer integration together" This reverts commit 756a38787cf2ed5790cd8e2bbaa3bffcfc5ee1dd. * test(github): place host and renderer loops in cross-layer suite * fix(github): preserve refresh policy and shared callers Use the same validated freshness for cached queue reads and their follow-up. Keep forced mergeability rereads and detach cancelled consumers independently from the shared lookup. Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> * fix(github): refresh settled rows when exposed again Use the same finite foreground age to admit and consume the queued read. A recent exact result can still satisfy it, and settled rows do not acquire a recurring timer. Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> * fix(github): accept only current PR read completions Keep shared publication and retry planning on the accepted actual read. Preserve legacy own replies, terminal loading and ordinary work after a superseded lookup, and honor the accepted error gate before automatic recovery. Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> * test(github): follow moved request contracts * test(github): explain the partial event fixture type assertion * fix(github): preserve queued deadlines and detachable PR waits * fix(github): compare refresh wakes on the elapsed clock * test(github): format queued refresh deadline cases * fix(github): charge actual producers and fence retry gates * fix(github): preserve fresh intent and producer error policy * fix(github): retain owned cold-read retry gates --------- Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> --- .../github/accounts/github-project-account.ts | 13 + .../client/lookup/pr-branch-read-resources.ts | 94 +++ .../client/lookup/pr-for-branch-outcome.ts | 338 +++++++--- .../github/client/lookup/pr-last-outcome.ts | 223 ++++++- .../client/lookup/pr-quiet-policy-evidence.ts | 89 +++ .../github/client/lookup/pr-read-identity.ts | 83 +++ .../client/lookup/pull-request-lookup-data.ts | 1 + .../refresh/hosted-pr-read-jobs.ts | 308 ++++++++++ .../refresh/pr-refresh-candidate-policy.ts | 62 +- ...oordinator-active-visible-priority.test.ts | 4 +- ...fresh-coordinator-alias-coalescing.test.ts | 4 +- ...efresh-coordinator-cache-follow-up.test.ts | 162 +++++ ...fresh-coordinator-completion-order.test.ts | 4 +- .../pr-refresh-coordinator-test-mocks.ts | 41 +- ...esh-coordinator-wsl-stopped-distro.test.ts | 4 +- .../refresh/pr-refresh-coordinator.ts | 200 +++--- .../refresh/pr-refresh-event-publisher.ts | 3 + .../refresh/pr-refresh-immediate-read.ts | 173 ++++++ .../refresh/pr-refresh-pacing.ts | 13 +- .../refresh/pr-refresh-queue-drainer.ts | 349 ++++++----- .../pr-refresh-queue-growth-bound.test.ts | 4 +- .../refresh/pr-refresh-queue-scheduler.ts | 298 +++++++++ .../pull-requests/refresh/pr-refresh-queue.ts | 22 +- .../pr-refresh-quiet-policy.perf.test.ts | 111 ++++ .../refresh/pr-refresh-read-admission.ts | 64 ++ .../refresh/pr-refresh-retry-state.ts | 34 ++ .../refresh/pr-refresh-watch-jobs.ts | 14 +- .../github-repository-identity.ts | 9 + .../runtime-environment-call-queue.ts | 7 +- ...untime-environment-subscription-routing.ts | 182 ++++++ .../runtime-environment-transport-routing.ts | 140 +---- .../runtime-environment-call-queue.test.ts | 19 + ...nvironments-subscription-lifecycle.test.ts | 64 ++ .../github-pr-refresh-handlers.ts | 6 +- ...osted-pr-producer-settlement-test-cases.ts | 235 +++++++ .../reviews/hosted-pr-selected-demand.test.ts | 157 +++++ .../runtime-hosted-pr-deadlines.test.ts | 142 +++++ .../runtime-hosted-pr-owner-delivery.test.ts | 105 ++++ ...runtime-hosted-pr-snapshot-test-harness.ts | 110 ++++ .../runtime-hosted-pr-snapshots.test.ts | 576 ++++++++++++++++++ .../reviews/runtime-hosted-review-commands.ts | 74 ++- .../runtime-hosted-review-pr-reuse.test.ts | 8 +- .../github/github-pull-request-methods.ts | 7 +- .../api/github/github-pull-request-api.ts | 4 +- .../src/store/github/github-slice-contract.ts | 4 + .../github-pr-request-lifetime.test.ts | 165 ++++- .../pull-requests/pull-request-actions.ts | 83 ++- .../pull-requests/pull-request-execution.ts | 34 +- .../github/refresh/refresh-event-actions.ts | 8 +- .../github/requests/request-coordination.ts | 10 + ...le-hosted-review-refresh-scheduler.test.ts | 45 ++ ...visible-hosted-review-refresh-scheduler.ts | 44 +- .../visible-hosted-review-refresh-targets.ts | 19 +- .../web-runtime-calls-connection-pin.test.ts | 45 +- .../src/web/preload-api/web-runtime-calls.ts | 52 +- .../web-runtime-environments-api.ts | 92 +-- .../web-runtime-pr-subscription-queue.test.ts | 85 +++ .../preload-api/web-runtime-subscription.ts | 112 ++++ .../pull-requests/refresh/pr-quiet-refresh.ts | 22 + .../refresh/pull-request-refresh-types.ts | 23 +- .../github/github-pull-request-params.ts | 2 + src/shared/runtime-rpc-call-queue.test.ts | 65 ++ src/shared/runtime-rpc-call-queue.ts | 40 +- .../runtime-rpc-subscription-queue.test.ts | 114 ++++ src/shared/runtime-rpc-subscription-queue.ts | 77 +++ ...github-pr-hosted-receipt-loop.unit.test.ts | 284 +++++++++ .../pr-refresh-actual-completion.unit.test.ts | 389 ++++++++++++ ...time-hosted-pr-snapshots-perf.unit.test.ts | 247 ++++++++ 68 files changed, 5843 insertions(+), 778 deletions(-) create mode 100644 src/main/github/client/lookup/pr-branch-read-resources.ts create mode 100644 src/main/github/client/lookup/pr-quiet-policy-evidence.ts create mode 100644 src/main/github/client/lookup/pr-read-identity.ts create mode 100644 src/main/github/pull-requests/refresh/hosted-pr-read-jobs.ts create mode 100644 src/main/github/pull-requests/refresh/pr-refresh-coordinator-cache-follow-up.test.ts create mode 100644 src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts create mode 100644 src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts create mode 100644 src/main/github/pull-requests/refresh/pr-refresh-quiet-policy.perf.test.ts create mode 100644 src/main/github/pull-requests/refresh/pr-refresh-read-admission.ts create mode 100644 src/main/ipc/runtime-environments/requests/runtime-environment-subscription-routing.ts create mode 100644 src/main/ipc/runtime-environments/runtime-environment-call-queue.test.ts create mode 100644 src/main/runtime/integrations/reviews/hosted-pr-producer-settlement-test-cases.ts create mode 100644 src/main/runtime/integrations/reviews/hosted-pr-selected-demand.test.ts create mode 100644 src/main/runtime/integrations/reviews/runtime-hosted-pr-deadlines.test.ts create mode 100644 src/main/runtime/integrations/reviews/runtime-hosted-pr-owner-delivery.test.ts create mode 100644 src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshot-test-harness.ts create mode 100644 src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshots.test.ts create mode 100644 src/renderer/src/web/preload-api/web-runtime-pr-subscription-queue.test.ts create mode 100644 src/renderer/src/web/preload-api/web-runtime-subscription.ts create mode 100644 src/shared/github/pull-requests/refresh/pr-quiet-refresh.ts create mode 100644 src/shared/runtime-rpc-subscription-queue.test.ts create mode 100644 src/shared/runtime-rpc-subscription-queue.ts create mode 100644 tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts create mode 100644 tests/e2e/pr-refresh-actual-completion.unit.test.ts create mode 100644 tests/e2e/runtime-hosted-pr-snapshots-perf.unit.test.ts diff --git a/src/main/github/accounts/github-project-account.ts b/src/main/github/accounts/github-project-account.ts index c091d564bac..aa96fd8636c 100644 --- a/src/main/github/accounts/github-project-account.ts +++ b/src/main/github/accounts/github-project-account.ts @@ -87,3 +87,16 @@ export function resolveGitHubProjectAccount(context: GitHubRepoContext) { ? { ghAccount: normalizeGhAccountBinding(matches[0].ghAccount) ?? undefined } : null } + +/** Policy observes project ownership changes without resolving every workspace's account. */ +export function githubPRPolicyProjects(): { source: object | null; selection: string } { + return { + source, + selection: JSON.stringify( + source?.store + .getRepos() + .map((repo) => [repo.id, repo.path, getStoredRepoExecutionHostId(repo), repo.ghAccount]) ?? + [] + ) + } +} diff --git a/src/main/github/client/lookup/pr-branch-read-resources.ts b/src/main/github/client/lookup/pr-branch-read-resources.ts new file mode 100644 index 00000000000..46d94d85763 --- /dev/null +++ b/src/main/github/client/lookup/pr-branch-read-resources.ts @@ -0,0 +1,94 @@ +import type { CoalescedProbes } from '../../../git/remotes/coalesced-probe' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { readTimedPROutcome } from './pr-last-outcome' + +export type PRBranchReadResult = { + outcome: PRRefreshOutcome + sequence: number + current: () => boolean +} + +type PRBranchReadResource = { + probes: CoalescedProbes + running: number + latestStart: number +} + +const resources = new Map() + +export function prBranchReadResource(key: string): PRBranchReadResource { + let resource = resources.get(key) + if (!resource) { + resource = { probes: new Map(), running: 0, latestStart: 0 } + resources.set(key, resource) + } + return resource +} + +export function pendingPRBranchRead( + key: string, + intent: 'fresh' | 'timed' +): Promise | null { + const pending = resources.get(key)?.probes.get(intent) + return pending && Date.now() - pending.startedAt < 2 * 60_000 ? pending.promise : null +} + +export function retirePRBranchReadResource(key: string, resource: PRBranchReadResource): void { + if (resource.probes.size === 0 && resource.running === 0 && resources.get(key) === resource) { + resources.delete(key) + } +} + +export function startPRBranchRead( + key: string, + resource: PRBranchReadResource, + sequence: number +): { current: () => boolean; finish: () => void } { + resource.running += 1 + resource.latestStart = sequence + return { + current: () => + Math.max(resource.latestStart, resources.get(key)?.latestStart ?? 0) === sequence, + finish: () => { + resource.running -= 1 + retirePRBranchReadResource(key, resource) + } + } +} + +export function deliverablePRBranchOutcome( + prepared: Pick, + result: PRBranchReadResult +): PRRefreshOutcome | null { + if (result.current()) { + return result.outcome + } + const cached = prepared.isCurrent() ? prepared.cached() : null + return cached && cached.sequence > result.sequence ? cached.outcome : null +} + +export type PRReadSettlement = ( + outcome: PRRefreshOutcome, + producer: { retained: boolean } +) => PRRefreshOutcome + +export type PreparedPRBranchRead = { + key: string + reprepare: () => Promise + cached: () => ReturnType + isCurrent: () => boolean + accepts: (outcome: PRRefreshOutcome) => boolean + didRead: () => boolean + release: () => void + hold: () => () => void + readRetained: (settle?: PRReadSettlement) => Promise + canRetain: () => boolean + scheduleError: (expected: PRRefreshOutcome, outcome: PRRefreshOutcome) => void + readResult: ( + settle?: PRReadSettlement, + requireRetention?: boolean + ) => Promise + pending: () => Promise | null + withExecution: (operation: () => Promise) => Promise + read: (settle?: PRReadSettlement) => Promise +} diff --git a/src/main/github/client/lookup/pr-for-branch-outcome.ts b/src/main/github/client/lookup/pr-for-branch-outcome.ts index a1d4bc779a5..e4952ecfe99 100644 --- a/src/main/github/client/lookup/pr-for-branch-outcome.ts +++ b/src/main/github/client/lookup/pr-for-branch-outcome.ts @@ -1,56 +1,44 @@ import { withGitHubRepoExecution, - ghRepoExecOptions, - githubRepoContext + captureGitHubRepoExecution, + outsideGitHubRepoExecution } from '../../repositories/github-repository-identity' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { runCoalescedProbe } from '../../../git/remotes/coalesced-probe' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { acquire, release } from '../../execution/github-operation-slots' + +import { hostedReviewLocalGitOptionArgs } from './../github-exec-scope' +import type { GitHubPRBranchLookupOptions } from './pull-request-lookup-data' +import { prRefreshUpstreamError } from './../gh-error-predicates' +import { resolvePRForBranchOutcome } from './branch-lookup-resolution' +import { + readRecentOpenPROutcome, + readTimedPROutcome, + canRetainPROutcome, + beginExactPRLookup, + releaseExactPRLookup, + holdExactPROutcome, + scheduleExactPRError, + recordPRLastOutcome, + startPRLookup +} from './pr-last-outcome' +import { prLookupScope, lastOutcomeKey, completeReadKey } from './pr-read-identity' +import { refreshPRPolicyContext, recordPRPolicyOutcome } from './pr-quiet-policy-evidence' import { hostedReviewRepoScope, scopeGeneration } from '../../../source-control/hosted-review-scope-generations' -import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' -import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' -import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' -import { acquire, release } from '../../execution/github-operation-slots' - -import { hostedReviewLocalGitOptionArgs, githubPRStackExecutionScope } from './../github-exec-scope' -import type { GitHubPRBranchLookupOptions } from './pull-request-lookup-data' -import { prRefreshUpstreamError } from './../gh-error-predicates' -import { resolvePRForBranchOutcome } from './branch-lookup-resolution' -import { readRecentOpenPROutcome, recordPRLastOutcome, startPRLookup } from './pr-last-outcome' -const reads: CoalescedProbes = new Map() - -function prLookupScope( - repoPath: string, - connectionId: string | null | undefined, - options: GitHubPRBranchLookupOptions -) { - const localGitOptions = hostedReviewLocalGitOptionArgs(options)[0] ?? {} - const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)) - return { - localGitOptions, - ghOptions, - executionScope: githubPRStackExecutionScope(connectionId, localGitOptions), - generation: scopeGeneration( - hostedReviewRepoScope(repoPath, getRepoExecutionHostId({ connectionId })) - ), - readScope: githubReadExecutionScope(ghOptions) - } -} - -function lastOutcomeKey( - repoPath: string, - branchName: string, - scope: ReturnType -): string { - return JSON.stringify([ - scope.executionScope, - repoPath, - scope.generation, - branchName, - scope.readScope - ]) -} +import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { + prBranchReadResource, + pendingPRBranchRead, + retirePRBranchReadResource, + startPRBranchRead, + type PRBranchReadResult, + type PRReadSettlement, + type PreparedPRBranchRead +} from './pr-branch-read-resources' +class PRLookupRetentionRefused extends Error {} /** A phone read may take the last lookup's open PR; it was already observed when it was looked up. */ export async function readRecentPhonePROutcome( @@ -84,19 +72,39 @@ export async function readRecentPhonePROutcome( ) } -export async function getPRForBranchOutcome( +export async function preparePRBranchRead( repoPath: string, branch: string, linkedPRNumber?: number | null, connectionId?: string | null, fallbackPRNumber?: number | null, options: GitHubPRBranchLookupOptions = {} -): Promise { +): Promise { + options = { + ...options, + ...(options.localGitExecOptions + ? { + localGitExecOptions: { + ...options.localGitExecOptions, + ...(options.localGitExecOptions.ghAccount + ? { ghAccount: { ...options.localGitExecOptions.ghAccount } } + : {}) + } + } + : {}), + ...(options.sharedLinkPaths ? { sharedLinkPaths: [...options.sharedLinkPaths] } : {}), + ...(options.exactRepository ? { exactRepository: { ...options.exactRepository } } : {}) + } + const reprepare = () => + outsideGitHubRepoExecution(() => + preparePRBranchRead(repoPath, branch, linkedPRNumber, connectionId, fallbackPRNumber, options) + ) return withGitHubRepoExecution( repoPath, connectionId, hostedReviewLocalGitOptionArgs(options)[0] ?? {}, - async (): Promise => { + async (): Promise => { + const withExecution = captureGitHubRepoExecution() const branchName = branch.replace(/^refs\/heads\//, '') // Detached HEAD cannot discover by branch, but explicit PR numbers remain safe. if ( @@ -104,63 +112,193 @@ export async function getPRForBranchOutcome( typeof linkedPRNumber !== 'number' && typeof fallbackPRNumber !== 'number' ) { - return { kind: 'no-pr', fetchedAt: Date.now() } + return { + key: '', + reprepare, + cached: () => null, + isCurrent: () => true, + accepts: () => true, + didRead: () => false, + release: () => {}, + hold: () => () => {}, + readRetained: async () => ({ kind: 'no-pr', fetchedAt: Date.now() }), + readResult: async () => ({ + outcome: { kind: 'no-pr', fetchedAt: Date.now() }, + sequence: 0, + current: () => true + }), + canRetain: () => true, + scheduleError: () => {}, + pending: () => null, + withExecution, + read: async () => ({ kind: 'no-pr', fetchedAt: Date.now() }) + } } + const policyRevision = refreshPRPolicyContext() const scope = prLookupScope(repoPath, connectionId, options) const { localGitOptions, ghOptions, executionScope } = scope - const key = JSON.stringify([ - executionScope, + const key = completeReadKey( repoPath, - scope.generation, branchName, - linkedPRNumber ?? null, - fallbackPRNumber ?? null, - options.acceptMergedFallbackPR ?? false, - options.currentHeadOid ?? null, - options.checkPageLimit ?? null, - options.exactRepository ?? null, - options.includeDerivedData !== false, - scope.readScope - ]) - return runCoalescedProbe( - reads, - key, - async () => { - await acquire() - const start = startPRLookup() - let outcome: PRRefreshOutcome - try { - outcome = await resolvePRForBranchOutcome({ - repoPath, - branchName, - linkedPRNumber, - connectionId, - fallbackPRNumber, - options, - localGitOptions, - ghOptions, - executionScope - }) - } catch (err) { - outcome = prRefreshUpstreamError(err) - } finally { - release() - } - const narrowed = - options.checkPageLimit !== undefined || - options.exactRepository || - options.includeDerivedData === false - recordPRLastOutcome(lastOutcomeKey(repoPath, branchName, scope), { - start, - linkedPRNumber: linkedPRNumber ?? null, - fallbackPRNumber: fallbackPRNumber ?? null, - outcome: narrowed ? null : outcome - }) - return outcome - }, - 2 * 60_000, - options + linkedPRNumber, + fallbackPRNumber, + options, + scope ) + const ownerKey = lastOutcomeKey(repoPath, branchName, scope) + const coalescingKey = options.resetQuietBackoff || options.userRefresh ? 'fresh' : 'timed' + const pendingAt = (intent: 'fresh' | 'timed') => pendingPRBranchRead(key, intent) + const narrowed = + options.checkPageLimit !== undefined || + options.exactRepository || + options.includeDerivedData === false + let didRead = false + const readCore = (requireRetention = false, settle?: PRReadSettlement) => + withExecution(() => { + const resource = prBranchReadResource(key) + return ( + (!options.userRefresh && coalescingKey === 'timed' ? pendingAt('fresh') : null) ?? + runCoalescedProbe( + resource.probes, + coalescingKey, + async (ownsKey) => { + const start = startPRLookup() + const retained = + !narrowed && + beginExactPRLookup( + ownerKey, + key, + start, + options.resetQuietBackoff || options.userRefresh + ) + if (requireRetention && !retained) { + throw new PRLookupRetentionRefused() + } + const producer = startPRBranchRead(key, resource, start.sequence) + didRead = true + try { + await acquire() + let outcome: PRRefreshOutcome + try { + outcome = await resolvePRForBranchOutcome({ + repoPath, + branchName, + linkedPRNumber, + connectionId, + fallbackPRNumber, + options, + localGitOptions, + ghOptions, + executionScope + }) + } catch (err) { + outcome = prRefreshUpstreamError(err) + } finally { + release() + } + recordPRLastOutcome(ownerKey, { + start, + requestKey: key, + currentHeadOid: options.currentHeadOid ?? null, + resetQuiet: options.userRefresh === true || options.resetQuietBackoff === true, + linkedPRNumber: linkedPRNumber ?? null, + fallbackPRNumber: fallbackPRNumber ?? null, + outcome: narrowed ? null : outcome + }) + if (!narrowed) { + recordPRPolicyOutcome(outcome, { + revision: policyRevision, + current: () => + scopeGeneration( + hostedReviewRepoScope(repoPath, getRepoExecutionHostId({ connectionId })) + ) === scope.generation, + cached: () => readTimedPROutcome(ownerKey, key) + }) + } + if ( + settle && + prepared.isCurrent() && + producer.current() && + (retained ? readTimedPROutcome(ownerKey, key)?.outcome === outcome : ownsKey()) + ) { + outcome = settle(outcome, { retained }) + } + return { + outcome, + sequence: start.sequence, + current: () => + producer.current() && + prepared.isCurrent() && + (!retained || prepared.accepts(outcome)) + } + } finally { + if (retained) { + releaseExactPRLookup(key, start.sequence) + } + producer.finish() + } + }, + 2 * 60_000, + { userRefresh: options.userRefresh === true } + ).finally(() => retirePRBranchReadResource(key, resource)) + ) + }) + const readResult = async ( + settle?: PRReadSettlement, + requireRetention = false + ): Promise => { + try { + return await readCore(requireRetention, settle) + } catch (error) { + if (!(error instanceof PRLookupRetentionRefused)) { + throw error + } + return requireRetention ? null : readCore(false, settle) + } + } + const read = async (settle?: PRReadSettlement): Promise => + (await readResult(settle))!.outcome + const readRetained = async (settle?: PRReadSettlement): Promise => + (await readResult(settle, true))?.outcome ?? null + const prepared: PreparedPRBranchRead = { + key, + reprepare, + cached: () => readTimedPROutcome(ownerKey, key), + isCurrent: () => + outsideGitHubRepoExecution( + () => + lastOutcomeKey( + repoPath, + branchName, + prLookupScope(repoPath, connectionId, options) + ) === ownerKey + ), + accepts: (outcome) => readTimedPROutcome(ownerKey, key)?.outcome === outcome, + didRead: () => didRead, + release: () => {}, + hold: () => holdExactPROutcome(key), + readRetained, + readResult, + canRetain: () => canRetainPROutcome(key), + scheduleError: (expected, outcome) => scheduleExactPRError(key, expected, outcome), + pending: () => pendingAt('fresh') ?? pendingAt('timed'), + withExecution, + read + } + return prepared } ) } + +export type { PRReadSettlement, PreparedPRBranchRead } from './pr-branch-read-resources' + +export async function getPRForBranchOutcome( + ...args: Parameters +): Promise { + const prepared = await preparePRBranchRead(...args) + try { + return await prepared.read() + } finally { + prepared.release() + } +} diff --git a/src/main/github/client/lookup/pr-last-outcome.ts b/src/main/github/client/lookup/pr-last-outcome.ts index 7d6dec32aac..cc2a6032eb4 100644 --- a/src/main/github/client/lookup/pr-last-outcome.ts +++ b/src/main/github/client/lookup/pr-last-outcome.ts @@ -1,4 +1,8 @@ import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { + isQuietPR, + QUIET_PR_REFRESH_INTERVAL_MS +} from '../../../../shared/github/pull-requests/refresh/pr-quiet-refresh' // A phone's re-read right after the desktop's own lookup reuses it instead of asking GitHub again. const PHONE_REUSE_MAX_AGE_MS = 30_000 @@ -10,33 +14,228 @@ type PRLastOutcome = { start: PRLookupStart linkedPRNumber: number | null fallbackPRNumber: number | null + requestKey?: string + currentHeadOid?: string | null + resetQuiet?: boolean + quiet?: boolean // null: the last lookup was narrowed (CI-line watch), so nothing is reusable until a full one. outcome: PRRefreshOutcome | null } +type ExactOutcome = PRLastOutcome & { + latestSequence: number + activeSequence: number | null + holds: number + invalidatedBeforeSequence: number + ownerKey: string +} const lastOutcomes = new Map() +const exactOutcomes = new Map() let lookupSequence = 0 -// Two lookups can start in the same millisecond; the sequence still orders them. export function startPRLookup(): PRLookupStart { lookupSequence += 1 return { startedAt: Date.now(), sequence: lookupSequence } } -export function recordPRLastOutcome(key: string, entry: PRLastOutcome): void { - const existing = lastOutcomes.get(key) - // A lookup that started earlier but settled later must not replace a newer answer. - if (existing && existing.start.sequence > entry.start.sequence) { +function trim(entries: Map): void { + while (entries.size > MAX_ENTRIES) { + entries.delete(entries.keys().next().value!) + } +} + +function pinned(entry: ExactOutcome): boolean { + return ( + entry.activeSequence !== null || + entry.holds > 0 || + (entry.outcome?.kind === 'upstream-error' && + Math.max(entry.outcome.nextAutoRetryAt ?? 0, entry.outcome.retryDisabledUntil ?? 0) > + Date.now()) + ) +} + +export function canRetainPROutcome(requestKey: string): boolean { + return ( + exactOutcomes.has(requestKey) || + exactOutcomes.size < MAX_ENTRIES || + [...exactOutcomes.values()].some((entry) => !pinned(entry)) + ) +} + +function evictExactOutcome(requestKey: string): void { + const entry = exactOutcomes.get(requestKey) + if (!entry) { return } - lastOutcomes.delete(key) - lastOutcomes.set(key, entry) - const now = Date.now() - for (const [oldestKey, oldest] of lastOutcomes) { - if (lastOutcomes.size <= MAX_ENTRIES && now - oldest.start.startedAt < PHONE_REUSE_MAX_AGE_MS) { - break + const projection = lastOutcomes.get(entry.ownerKey) + if (projection?.requestKey === requestKey) { + projection.outcome = null + } + exactOutcomes.delete(requestKey) +} + +function makeRoom(requestKey: string): boolean { + if (exactOutcomes.has(requestKey) || exactOutcomes.size < MAX_ENTRIES) { + return true + } + const victim = [...exactOutcomes].find(([, value]) => !pinned(value)) + if (!victim) { + return false + } + evictExactOutcome(victim[0]) + return true +} + +export function beginExactPRLookup( + ownerKey: string, + requestKey: string, + start: PRLookupStart, + resetQuiet = false +): boolean { + const previous = exactOutcomes.get(requestKey) + if (previous) { + previous.latestSequence = start.sequence + previous.activeSequence = start.sequence + if (resetQuiet) { + previous.quiet = false } - lastOutcomes.delete(oldestKey) + } else if (makeRoom(requestKey)) { + exactOutcomes.set(requestKey, { + ownerKey, + start, + latestSequence: start.sequence, + activeSequence: start.sequence, + holds: 0, + invalidatedBeforeSequence: 0, + linkedPRNumber: null, + fallbackPRNumber: null, + outcome: null + }) + } else { + return false + } + return true +} + +export function holdExactPROutcome(requestKey: string): () => void { + const entry = exactOutcomes.get(requestKey) + if (!entry) { + return () => {} + } + entry.holds += 1 + let held = true + return () => { + if (held) { + held = false + const current = exactOutcomes.get(requestKey) + if (current) { + current.holds -= 1 + } + } + } +} + +export function releaseExactPRLookup(requestKey: string, sequence: number): void { + const entry = exactOutcomes.get(requestKey) + if (entry?.activeSequence === sequence) { + entry.activeSequence = null + } +} + +function invalidateOwnerSuccesses(ownerKey: string, sequence: number): void { + for (const entry of exactOutcomes.values()) { + if (entry.ownerKey !== ownerKey) { + continue + } + entry.invalidatedBeforeSequence = Math.max(entry.invalidatedBeforeSequence, sequence) + if (entry.outcome?.kind !== 'upstream-error' && entry.start.sequence < sequence) { + entry.outcome = null + entry.quiet = false + } + } +} + +export function recordPRLastOutcome(key: string, entry: PRLastOutcome): void { + const previous = entry.requestKey ? exactOutcomes.get(entry.requestKey) : undefined + if (entry.outcome) { + if ( + !previous || + previous.ownerKey !== key || + previous.latestSequence !== entry.start.sequence || + (entry.outcome.kind !== 'upstream-error' && + entry.start.sequence < previous.invalidatedBeforeSequence) + ) { + return + } + } + if (!entry.outcome || entry.outcome.kind === 'upstream-error') { + invalidateOwnerSuccesses(key, entry.start.sequence) + } + let retained = false + if (entry.requestKey && entry.outcome && previous) { + const quiet = + !entry.resetQuiet && + previous.outcome?.kind === 'found' && + entry.outcome.kind === 'found' && + isQuietPR(entry.outcome.pr, entry.currentHeadOid ?? null) && + JSON.stringify(previous.outcome.pr) === JSON.stringify(entry.outcome.pr) + exactOutcomes.delete(entry.requestKey) + exactOutcomes.set(entry.requestKey, { + ...entry, + ownerKey: key, + quiet, + activeSequence: previous.activeSequence, + holds: previous.holds, + invalidatedBeforeSequence: previous.invalidatedBeforeSequence, + latestSequence: entry.start.sequence + }) + retained = true + } + const existing = lastOutcomes.get(key) + if (!existing || existing.start.sequence <= entry.start.sequence) { + lastOutcomes.delete(key) + lastOutcomes.set(key, retained ? entry : { ...entry, outcome: null }) + trim(lastOutcomes) + } +} + +export function readTimedPROutcome( + key: string, + requestKey: string +): { + outcome: PRRefreshOutcome + quietIntervalMs: number | null + sequence: number +} | null { + const entry = exactOutcomes.get(requestKey) + if (!entry?.outcome || entry.ownerKey !== key) { + return null + } + if ( + entry.outcome.kind !== 'upstream-error' && + entry.start.sequence < entry.invalidatedBeforeSequence + ) { + return null + } + return { + outcome: entry.outcome, + quietIntervalMs: entry.quiet ? QUIET_PR_REFRESH_INTERVAL_MS : null, + sequence: entry.start.sequence + } +} + +export function scheduleExactPRError( + requestKey: string, + expected: PRRefreshOutcome, + scheduled: PRRefreshOutcome +): void { + const entry = exactOutcomes.get(requestKey) + if ( + entry?.outcome === expected && + entry.start.sequence === entry.latestSequence && + scheduled.kind === 'upstream-error' + ) { + entry.outcome = scheduled } } diff --git a/src/main/github/client/lookup/pr-quiet-policy-evidence.ts b/src/main/github/client/lookup/pr-quiet-policy-evidence.ts new file mode 100644 index 00000000000..c4a7d9546ac --- /dev/null +++ b/src/main/github/client/lookup/pr-quiet-policy-evidence.ts @@ -0,0 +1,89 @@ +import type { + GitHubPRRefreshCandidate, + PRRefreshOutcome +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { githubPRPolicyProjects } from '../../accounts/github-project-account' +import type { readTimedPROutcome } from './pr-last-outcome' + +let revision = 0 +let projects: ReturnType | undefined +let environment: Record = {} +let cwd = '' + +// Called once at a report boundary, never from a per-row policy decision. +export function refreshPRPolicyContext(): number { + const next = githubPRPolicyProjects() + const keys = Object.keys(process.env) + if ( + next.source !== projects?.source || + next.selection !== projects?.selection || + cwd !== process.cwd() || + keys.length !== Object.keys(environment).length || + keys.some((key) => process.env[key] !== environment[key]) + ) { + revision += 1 + projects = next + environment = { ...process.env } + cwd = process.cwd() + } + return revision +} + +type Evidence = { + revision: number + current: () => boolean + cached: () => ReturnType +} +const completed = new WeakMap() +const projections = new Map() + +function key(candidate: GitHubPRRefreshCandidate): string { + return JSON.stringify([ + candidate.repoId, + candidate.repoPath, + candidate.connectionId ?? null, + candidate.localGitOptions?.wslDistro ?? null, + candidate.branch.replace(/^refs\/heads\//, ''), + candidate.currentHeadOid ?? null, + candidate.linkedPRNumber ?? null, + candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null, + candidate.linkedPRNumber == null ? (candidate.fallbackPRSource ?? null) : null + ]) +} + +export function recordPRPolicyOutcome(outcome: PRRefreshOutcome, evidence: Evidence): void { + completed.set(outcome, evidence) +} + +export function projectPRPolicyOutcome( + candidate: GitHubPRRefreshCandidate, + outcome: PRRefreshOutcome +): void { + const evidence = completed.get(outcome) + const identity = key(candidate) + projections.delete(identity) + if (evidence) { + projections.set(identity, evidence) + } + while (projections.size > 256) { + projections.delete(projections.keys().next().value!) + } +} + +export function quietPRIntervalForCandidate(candidate: GitHubPRRefreshCandidate): number | null { + const evidence = projections.get(key(candidate)) + if (!evidence || evidence.revision !== revision || !evidence.current()) { + return null + } + const cached = evidence.cached() + if ( + cached?.outcome.kind !== 'found' || + cached.outcome.fetchedAt !== candidate.cachedFetchedAt || + candidate.cachedHasPR !== true || + candidate.cachedPRState !== cached.outcome.pr.state || + candidate.cachedChecksStatus !== cached.outcome.pr.checksStatus + ) { + return null + } + return cached.quietIntervalMs +} diff --git a/src/main/github/client/lookup/pr-read-identity.ts b/src/main/github/client/lookup/pr-read-identity.ts new file mode 100644 index 00000000000..ba55c8871b9 --- /dev/null +++ b/src/main/github/client/lookup/pr-read-identity.ts @@ -0,0 +1,83 @@ +import { ghRepoExecOptions, githubRepoContext } from '../../repositories/github-repository-identity' +import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { + hostedReviewRepoScope, + scopeGeneration +} from '../../../source-control/hosted-review-scope-generations' +import { codeHostReadExecutionScope as githubReadExecutionScope } from '../../../source-control/code-host-read-execution-scope' +import { hostedReviewLocalGitOptionArgs, githubPRStackExecutionScope } from '../github-exec-scope' +import type { GitHubPRBranchLookupOptions } from './pull-request-lookup-data' +import { readTimedPROutcome } from './pr-last-outcome' + +export function prLookupScope( + repoPath: string, + connectionId: string | null | undefined, + options: GitHubPRBranchLookupOptions +) { + const localGitOptions = hostedReviewLocalGitOptionArgs(options)[0] ?? {} + const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)) + return { + localGitOptions, + ghOptions, + executionScope: githubPRStackExecutionScope(connectionId, localGitOptions), + generation: scopeGeneration( + hostedReviewRepoScope(repoPath, getRepoExecutionHostId({ connectionId })) + ), + readScope: githubReadExecutionScope(ghOptions) + } +} + +export function lastOutcomeKey( + repoPath: string, + branchName: string, + scope: ReturnType +): string { + return JSON.stringify([ + scope.executionScope, + repoPath, + scope.generation, + branchName, + scope.readScope + ]) +} + +export function completeReadKey( + repoPath: string, + branchName: string, + linkedPRNumber: number | null | undefined, + fallbackPRNumber: number | null | undefined, + options: GitHubPRBranchLookupOptions, + scope: ReturnType +): string { + return JSON.stringify([ + scope.executionScope, + repoPath, + scope.generation, + branchName, + linkedPRNumber ?? null, + fallbackPRNumber ?? null, + options.acceptMergedFallbackPR ?? false, + options.currentHeadOid ?? null, + options.checkPageLimit ?? null, + options.exactRepository ?? null, + options.includeDerivedData !== false, + options.sharedLinkPaths ?? null, + scope.readScope + ]) +} + +export function cachedPRBranchOutcome( + repoPath: string, + branch: string, + linkedPRNumber: number | null, + connectionId: string | null, + fallbackPRNumber: number | null, + options: GitHubPRBranchLookupOptions +): ReturnType { + const branchName = branch.replace(/^refs\/heads\//, '') + const scope = prLookupScope(repoPath, connectionId, options) + return readTimedPROutcome( + lastOutcomeKey(repoPath, branchName, scope), + completeReadKey(repoPath, branchName, linkedPRNumber, fallbackPRNumber, options, scope) + ) +} diff --git a/src/main/github/client/lookup/pull-request-lookup-data.ts b/src/main/github/client/lookup/pull-request-lookup-data.ts index 62f23ec8f95..b6812559e5b 100644 --- a/src/main/github/client/lookup/pull-request-lookup-data.ts +++ b/src/main/github/client/lookup/pull-request-lookup-data.ts @@ -92,6 +92,7 @@ export const PR_BRANCH_LIST_JSON_FIELDS = 'number,title,state,url,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository' export type GitHubPRBranchLookupOptions = HostedReviewExecutionOptions & { + resetQuietBackoff?: boolean userRefresh?: boolean /** CI watches need provider status, without local conflict or stack enrichment. */ includeDerivedData?: boolean diff --git a/src/main/github/pull-requests/refresh/hosted-pr-read-jobs.ts b/src/main/github/pull-requests/refresh/hosted-pr-read-jobs.ts new file mode 100644 index 00000000000..ecd7a1d962f --- /dev/null +++ b/src/main/github/pull-requests/refresh/hosted-pr-read-jobs.ts @@ -0,0 +1,308 @@ +import type { + GitHubPRRefreshCandidate, + PRRefreshOutcome, + PRSnapshotReply +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { reviewRefreshIntervalMs } from '../../../../shared/review-refresh-policy' +import { deliverablePRBranchOutcome } from '../../client/lookup/pr-branch-read-resources' +import type { PreparedPRBranchRead } from '../../client/lookup/pr-for-branch-outcome' +import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' +import type { PRRefreshPacing } from './pr-refresh-pacing' +import type { PRRefreshRetryState } from './pr-refresh-retry-state' + +export const HOSTED_PR_COMPLETION_WAIT_MS = 25_000 +const RETRY_MS = 10_000 +const MAX_JOBS = 256 +const MAX_WAITERS = 256 +const JOB_LEASE_MS = 5 * 60_000 + +export type HostedPRReadJob = { + prepared: PreparedPRBranchRead + expiresAt: number + running?: boolean + promoteSelected: () => void + listeners: Set<(outcome: PRRefreshOutcome | null) => void> + finish: (outcome: PRRefreshOutcome | null) => void +} + +export class HostedPRReadJobs { + private readonly jobs = new Map() + private waiters = 0 + + constructor( + private readonly queue: PRRefreshQueue, + private readonly pacing: PRRefreshPacing, + private readonly retry: PRRefreshRetryState, + private readonly wake: () => void, + private readonly observe: ( + candidate: GitHubPRRefreshCandidate, + outcome: PRRefreshOutcome + ) => void + ) {} + + has(prepared: PreparedPRBranchRead): boolean { + return this.jobs.has(`hosted::${prepared.key}`) + } + + fresh(prepared: PreparedPRBranchRead): PRRefreshOutcome | null { + return this.freshOutcome(prepared.cached()) + } + + freshOutcome( + cached: ReturnType, + selected = true + ): PRRefreshOutcome | null { + if (!cached || cached.outcome.kind === 'upstream-error') { + return null + } + const outcome = cached.outcome + const interval = + cached.quietIntervalMs ?? + reviewRefreshIntervalMs({ + state: outcome.kind === 'found' ? outcome.pr.state : null, + checksStatus: outcome.kind === 'found' ? outcome.pr.checksStatus : null, + hasReview: outcome.kind === 'found', + selected + }) + return interval === null || Date.now() - outcome.fetchedAt < interval ? outcome : null + } + + private async legacyRead( + prepared: PreparedPRBranchRead, + candidate: GitHubPRRefreshCandidate + ): Promise { + const current = await prepared.reprepare() + try { + const result = await current.readResult((outcome) => { + this.observe(candidate, outcome) + return outcome + }) + return result!.outcome + } finally { + current.release() + } + } + + private gateUntil(prepared: PreparedPRBranchRead): number { + const outcome = prepared.cached()?.outcome + return Math.max( + this.queue.backgroundGateUntil(`hosted::${prepared.key}`), + outcome?.kind === 'upstream-error' + ? Math.max(outcome.nextAutoRetryAt ?? 0, outcome.retryDisabledUntil ?? 0) + : 0 + ) + } + + retryAfterMs(prepared: PreparedPRBranchRead): number { + return Math.max( + RETRY_MS, + this.pacing.nextBudgetDelay(), + prepared.isCurrent() ? this.gateUntil(prepared) - Date.now() : 0 + ) + } + + async complete( + prepared: PreparedPRBranchRead, + candidate: GitHubPRRefreshCandidate, + outcome: PRRefreshOutcome | null, + acceptRevalidationOnly: boolean + ): Promise { + if (outcome && !acceptRevalidationOnly) { + return outcome + } + const current = prepared.isCurrent() + if (current) { + if (outcome && prepared.accepts(outcome)) { + return outcome + } + const fresh = this.fresh(prepared) + if (fresh) { + return fresh + } + } + const delay = this.retryAfterMs(prepared) + const cached = current ? prepared.cached()?.outcome : null + if (cached) { + return cached.kind === 'upstream-error' + ? cached + : { ...cached, revalidation: { retryAfterMs: delay } } + } + return acceptRevalidationOnly + ? { revalidation: { invalidated: true, retryAfterMs: delay } } + : this.legacyRead(prepared, candidate) + } + + async readCold( + candidate: GitHubPRRefreshCandidate, + prepared: PreparedPRBranchRead, + acceptRevalidationOnly: boolean + ): Promise { + try { + const result = await prepared.readResult((outcome) => { + const settled = + acceptRevalidationOnly && outcome.kind === 'upstream-error' + ? this.retry.settleProducerError( + outcome, + `hosted::${prepared.key}`, + { ...candidate, isSelected: false }, + prepared, + this.queue, + true + ) + : outcome + this.observe(candidate, settled) + return settled + }, acceptRevalidationOnly) + const outcome = result + ? acceptRevalidationOnly + ? deliverablePRBranchOutcome(prepared, result) + : result.outcome + : null + return await this.complete(prepared, candidate, outcome, acceptRevalidationOnly) + } finally { + prepared.release() + } + } + + async read( + prepared: PreparedPRBranchRead, + candidate: GitHubPRRefreshCandidate, + deadline: number, + signal?: AbortSignal, + acceptRevalidationOnly = false + ): Promise { + if (!prepared.isCurrent()) { + return this.complete(prepared, candidate, null, acceptRevalidationOnly) + } + const fresh = this.fresh(prepared) + if (fresh) { + return this.complete(prepared, candidate, fresh, acceptRevalidationOnly) + } + const key = `hosted::${prepared.key}` + for (const [oldKey, old] of this.jobs) { + if (old.expiresAt > Date.now()) { + break + } + if (old.running) { + continue + } + this.queue.delete(oldKey) + old.finish(null) + } + const fallback = () => this.complete(prepared, candidate, null, acceptRevalidationOnly) + const gate = this.gateUntil(prepared) + if (prepared.cached()?.outcome.kind === 'upstream-error' && gate > Date.now()) { + return fallback() + } + let job = this.jobs.get(key) + if (!job) { + if (this.jobs.size >= MAX_JOBS) { + return fallback() + } + const listeners: HostedPRReadJob['listeners'] = new Set() + const releaseHold = prepared.hold() + const expiresAt = Date.now() + JOB_LEASE_MS + const entry: PRRefreshQueueEntry = { + key, + candidate, + aliases: new Map(), + reason: 'swr', + priority: candidate.isSelected ? 80 : prepared.cached()?.quietIntervalMs ? 20 : 40, + dueAt: Math.min(expiresAt, Math.max(Date.now(), gate)), + queuedAt: this.queue.nextOrder() + } + job = { + prepared, + promoteSelected: () => { + if (!entry.candidate.isSelected) { + entry.candidate = { ...entry.candidate, isSelected: true } + entry.priority = 80 + this.wake() + } + }, + expiresAt, + listeners, + finish: (outcome) => { + releaseHold() + if (this.jobs.get(key) === job) { + this.jobs.delete(key) + } + const listenersAtCompletion = Array.from(listeners) + for (const listener of listenersAtCompletion) { + listener(outcome) + } + listeners.clear() + } + } + this.jobs.set(key, job) + entry.hosted = job + this.queue.set(key, entry) + this.wake() + } + if (candidate.isSelected && !job.running) { + job.promoteSelected() + } + if ( + !acceptRevalidationOnly || + this.waiters >= MAX_WAITERS || + Date.now() >= deadline || + Math.max(gate - Date.now(), this.pacing.nextBudgetDelay()) > deadline - Date.now() + ) { + return fallback() + } + const waitingJob = job + return new Promise((resolve, reject) => { + let timer: ReturnType + const settle = (outcome: PRRefreshOutcome | null): void => { + cleanup() + void this.complete(prepared, candidate, outcome, acceptRevalidationOnly).then( + resolve, + reject + ) + } + const abort = (): void => { + cleanup() + reject(new Error('Pull request wait was cancelled')) + } + const cleanup = (): void => { + if (!waitingJob.listeners.delete(settle)) { + return + } + this.waiters -= 1 + clearTimeout(timer) + signal?.removeEventListener('abort', abort) + } + waitingJob.listeners.add(settle) + this.waiters += 1 + signal?.addEventListener('abort', abort, { once: true }) + timer = setTimeout( + () => { + cleanup() + try { + resolve(fallback()) + } catch (error) { + reject(error) + } + }, + Math.max(0, deadline - Date.now()) + ) + if (signal?.aborted) { + abort() + } + }) + } + completeFromCache(entry: PRRefreshQueueEntry): boolean { + const job = entry.hosted + if (!job) { + return false + } + const current = job.prepared.isCurrent() + const fresh = current ? this.fresh(job.prepared) : null + if (job.expiresAt > Date.now() && current && !fresh && job.prepared.canRetain()) { + return false + } + this.queue.delete(entry.key) + job.finish(current && job.expiresAt > Date.now() ? fresh : null) + return true + } +} diff --git a/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts b/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts index de532e3d8ad..e3a3e12355f 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts @@ -1,5 +1,8 @@ import { shouldAcceptMergedFallbackPR } from '../../../../shared/github/pull-requests/refresh/pr-branch-fallback-rule' -import { reviewRefreshIntervalMs } from '../../../../shared/review-refresh-policy' +import { + REVIEW_REFRESH_COOLDOWN_MS, + reviewRefreshIntervalMs +} from '../../../../shared/review-refresh-policy' import type { GitHubPRRefreshAlias, GitHubPRRefreshCandidate, @@ -10,6 +13,8 @@ import type { import type { GitHubPRBranchLookupOptions } from '../../client/lookup/pull-request-lookup-data' import { PR_CHECK_PAGE_LIMIT } from '../../client/check/pr-check-rollup' import { parsePRKey } from '../../pr-watch/pr-watch-types' +import { quietPRIntervalForCandidate } from '../../client/lookup/pr-quiet-policy-evidence' +import { cachedPRBranchOutcome } from '../../client/lookup/pr-read-identity' export const MANUAL_MERGEABILITY_PENDING_REFRESH_MS = 2_500 export const POST_PUSH_DELAY_MS = 2_500 @@ -26,6 +31,9 @@ export function hostedReviewOptionArgs( ): [] | [GitHubPRBranchLookupOptions] { const options: GitHubPRBranchLookupOptions = requestOptions.userRefresh === true ? { userRefresh: true } : {} + if (bypassesFreshnessDelay(reason)) { + options.resetQuietBackoff = true + } options.localGitExecOptions = { ...(candidate.localGitOptions?.wslDistro ? { wslDistro: candidate.localGitOptions.wslDistro } @@ -126,10 +134,52 @@ export function shouldSkipFresh( return Date.now() - candidate.cachedFetchedAt < refreshIntervalForCandidate(candidate) } -export function freshRetryAt(candidate: GitHubPRRefreshCandidate): number | null { +export function foregroundRefreshAgeMs(candidate: GitHubPRRefreshCandidate): number { + const interval = refreshIntervalForCandidate(candidate) + return Number.isFinite(interval) ? interval : REVIEW_REFRESH_COOLDOWN_MS +} + +export function foregroundExposureDueAt( + candidate: GitHubPRRefreshCandidate, + reexposed: boolean +): number | null { + return reexposed && + !Number.isFinite(refreshIntervalForCandidate(candidate)) && + candidate.cachedFetchedAt != null && + Date.now() - candidate.cachedFetchedAt >= foregroundRefreshAgeMs(candidate) + ? Date.now() + : null +} + +export function freshRetryAt( + candidate: GitHubPRRefreshCandidate, + foreground = false +): number | null { return candidate.cachedFetchedAt == null || hasStaleHead(candidate) ? null - : candidate.cachedFetchedAt + refreshIntervalForCandidate(candidate) + : candidate.cachedFetchedAt + + (foreground ? foregroundRefreshAgeMs(candidate) : refreshIntervalForCandidate(candidate)) +} + +export function freshQueuedPROutcome( + candidate: GitHubPRRefreshCandidate, + reason: GitHubPRRefreshReason, + foreground = false +): PRRefreshOutcome | null { + const cached = cachedPRBranchOutcome( + candidate.repoPath, + candidate.branch, + candidate.linkedPRNumber ?? null, + candidate.connectionId ?? null, + candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null, + hostedReviewOptionArgs(candidate, reason)[0] ?? {} + ) + const outcome = cached?.outcome + if (!outcome || outcome.kind === 'upstream-error') { + return null + } + const dueAt = freshRetryAt(visibleCandidateAfterOutcome(candidate, outcome), foreground) + return dueAt !== null && dueAt > Date.now() ? outcome : null } export function aliasFromCandidate(candidate: GitHubPRRefreshCandidate): GitHubPRRefreshAlias { @@ -189,6 +239,12 @@ export function hasStaleHead(candidate: GitHubPRRefreshCandidate): boolean { } export function refreshIntervalForCandidate(candidate: GitHubPRRefreshCandidate): number { + if (candidate.cachedFetchedAt != null && !hasStaleHead(candidate)) { + const quiet = quietPRIntervalForCandidate(candidate) + if (quiet !== null) { + return quiet + } + } return ( reviewRefreshIntervalMs({ state: candidate.cachedPRState, diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts index 14c258f2d5c..61692bcb6c6 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-active-visible-priority.test.ts @@ -8,9 +8,7 @@ const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) vi.mock('../../client/lookup/pr-for-branch-outcome', () => { - return { - getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock - } + return moduleMocks.clientModuleMock(coordinatorMocks) }) vi.mock('../../repositories/github-api-repository-remote-probe', () => { return { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts index db6f0138965..721960799a4 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-alias-coalescing.test.ts @@ -7,9 +7,7 @@ const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) vi.mock('../../client/lookup/pr-for-branch-outcome', () => { - return { - getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock - } + return moduleMocks.clientModuleMock(coordinatorMocks) }) vi.mock('../../repositories/github-api-repository-remote-probe', () => { return { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-cache-follow-up.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-cache-follow-up.test.ts new file mode 100644 index 00000000000..830cb2b2295 --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-cache-follow-up.test.ts @@ -0,0 +1,162 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' + +const mocks = vi.hoisted(() => ({ resolve: vi.fn(), send: vi.fn(), selection: 0 })) +vi.mock('../../client/lookup/branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: mocks.resolve +})) +vi.mock('../../accounts/github-project-account', () => ({ + githubPRPolicyProjects: () => ({ source: null, selection: mocks.selection }), + resolveGitHubProjectAccount: () => null +})) +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: async () => {}, + release: () => {} +})) +vi.mock('./pr-refresh-rate-limit-gate', () => ({ prRefreshRateLimitPausedUntil: async () => null })) +vi.mock('./pr-refresh-renderer-port', () => ({ + prRefreshRenderers: () => ({ isRendererOpen: () => true, sendToTrustedUI: mocks.send }) +})) + +beforeEach(() => { + vi.resetModules() + vi.useFakeTimers() + vi.setSystemTime(1_000) + mocks.selection = 0 + mocks.resolve.mockReset() + mocks.send.mockReset() +}) +afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() +}) + +function found(overrides: Parameters[0] = {}): PRRefreshOutcome { + return { + kind: 'found', + fetchedAt: Date.now(), + pr: makePR({ + checksStatus: 'success', + checksReadComplete: true, + checksFinal: true, + autoMergeEnabled: false, + mergeQueueRequired: false, + ...overrides + }) + } +} + +it('delivers a real refresh after quiet evidence retires without repeating the cached follow-up', async () => { + mocks.resolve.mockImplementation(async () => found()) + const coordinator = await import('./pr-refresh-coordinator') + const { getPRForBranchOutcome } = await import('../../client/lookup/pr-for-branch-outcome') + const candidate = makeCandidate({ currentHeadOid: 'head-sha' }) + const seed = () => + coordinator.runHostedPRRead(candidate, () => + getPRForBranchOutcome('/repo', candidate.branch, null, null, null, { + currentHeadOid: 'head-sha' + }) + ) + await seed() + vi.setSystemTime(2_000) + await seed() + const visible = { + ...candidate, + cachedFetchedAt: 2_000, + cachedHeadOid: 'head-sha', + cachedHasPR: true, + cachedPRState: 'open' as const, + cachedChecksStatus: 'success' as const + } + coordinator.reportVisiblePRRefreshCandidates([visible], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + vi.setSystemTime(132_001) + mocks.selection++ + mocks.resolve.mockImplementation(async () => found({ title: 'updated' })) + mocks.send.mockClear() + mocks.send.mockImplementation(() => { + // Bound the unfixed synchronous loop even though its fake clock would otherwise never advance. + if (mocks.send.mock.calls.length === 8) { + vi.setSystemTime(1_000_000) + } + }) + coordinator.reportVisiblePRRefreshCandidates([visible], 2, 1) + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(3) + expect(mocks.send.mock.calls.length).toBeLessThanOrEqual(2) + expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ + outcome: { fetchedAt: 132_001, pr: { title: 'updated' } } + }) + await vi.advanceTimersByTimeAsync(120_001) + expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ + outcome: { fetchedAt: 252_001, pr: { title: 'updated' } } + }) +}) + +it('rereads unresolved manual mergeability at its forced follow-up despite the timed cache', async () => { + mocks.resolve + .mockImplementationOnce(async () => + found({ mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' }) + ) + .mockImplementation(async () => found({ mergeable: 'MERGEABLE', mergeStateStatus: 'CLEAN' })) + const coordinator = await import('./pr-refresh-coordinator') + const candidate = makeCandidate({ currentHeadOid: 'head-sha' }) + coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) + expect(await coordinator.refreshPRNow(candidate)).toMatchObject({ + pr: { mergeable: 'UNKNOWN' } + }) + await vi.advanceTimersByTimeAsync(2_501) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ + outcome: { pr: { mergeable: 'MERGEABLE', mergeStateStatus: 'CLEAN' } } + }) +}) + +it.each([false, true])( + 'refreshes a settled row on re-exposure and shares a newer exact answer (refreshed while queued: %s)', + async (refreshedWhileQueued) => { + mocks.resolve.mockImplementation(async () => found({ state: 'merged' })) + const coordinator = await import('./pr-refresh-coordinator') + const { getPRForBranchOutcome } = await import('../../client/lookup/pr-for-branch-outcome') + const candidate = makeCandidate({ currentHeadOid: 'head-sha', linkedPRNumber: 12 }) + const seed = () => + coordinator.runHostedPRRead(candidate, () => + getPRForBranchOutcome('/repo', candidate.branch, 12, null, null, { + currentHeadOid: 'head-sha', + userRefresh: true + }) + ) + await seed() + const visible = { + ...candidate, + cachedFetchedAt: 1_000, + cachedHeadOid: 'head-sha', + cachedHasPR: true, + cachedPRState: 'merged' as const, + cachedChecksStatus: 'success' as const + } + coordinator.reportVisiblePRRefreshCandidates([visible], 1, 1) + coordinator.reportVisiblePRRefreshCandidates([], 2, 1) + vi.setSystemTime(2_000) + coordinator.reportVisiblePRRefreshCandidates([visible], 3, 1) + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + coordinator.reportVisiblePRRefreshCandidates([], 4, 1) + vi.setSystemTime(21_000) + mocks.resolve.mockImplementation(async () => found({ state: 'merged', title: 'updated' })) + mocks.send.mockClear() + coordinator.reportVisiblePRRefreshCandidates([visible], 5, 1) + if (refreshedWhileQueued) { + await seed() + } + await vi.advanceTimersByTimeAsync(0) + expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ + outcome: { fetchedAt: 21_000, pr: { state: 'merged', title: 'updated' } } + }) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(600_000) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + } +) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts index f5470dd7ad2..fd787cc66fe 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-completion-order.test.ts @@ -9,9 +9,7 @@ const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { }) vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) vi.mock('../../client/lookup/pr-for-branch-outcome', () => { - return { - getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock - } + return moduleMocks.clientModuleMock(coordinatorMocks) }) vi.mock('../../repositories/github-api-repository-remote-probe', () => { return { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-mocks.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-mocks.ts index cc79d26e1ea..063957a1c12 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-mocks.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-mocks.ts @@ -1,4 +1,8 @@ import type { PRRefreshRendererPort } from './pr-refresh-renderer-port' +import type { + PreparedPRBranchRead, + preparePRBranchRead +} from '../../client/lookup/pr-for-branch-outcome' import { vi, type Mock } from 'vitest' import { isWslUncPath } from '../../../../shared/wsl-paths' @@ -51,11 +55,44 @@ export function rendererPortModuleMock(mocks: PRRefreshCoordinatorMocks): Render return { prRefreshRenderers: () => port } } -export type ClientModuleMock = { getPRForBranchOutcome: Mock } +export type ClientModuleMock = { + getPRForBranchOutcome: Mock + preparePRBranchRead: typeof preparePRBranchRead +} export function clientModuleMock(mocks: PRRefreshCoordinatorMocks): ClientModuleMock { return { - getPRForBranchOutcome: mocks.getPRForBranchOutcomeMock + getPRForBranchOutcome: mocks.getPRForBranchOutcomeMock, + preparePRBranchRead: async (...args) => { + const prepared: PreparedPRBranchRead = { + key: '', + reprepare: async () => prepared, + cached: () => null, + isCurrent: () => true, + accepts: () => true, + didRead: () => true, + release: () => {}, + hold: () => () => {}, + canRetain: () => true, + scheduleError: () => {}, + pending: () => null, + withExecution: (operation) => operation(), + read: async (settle) => { + const outcome = await mocks.getPRForBranchOutcomeMock(...args) + return settle ? settle(outcome, { retained: true }) : outcome + }, + readResult: async (settle) => ({ + outcome: await prepared.read(settle), + sequence: 0, + current: () => true + }), + readRetained: async (settle) => { + const outcome = await mocks.getPRForBranchOutcomeMock(...args) + return settle ? settle(outcome, { retained: true }) : outcome + } + } + return prepared + } } } diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-wsl-stopped-distro.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-wsl-stopped-distro.test.ts index ae9ffdc3d13..f14db379010 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-wsl-stopped-distro.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-wsl-stopped-distro.test.ts @@ -13,9 +13,7 @@ const gate = vi.hoisted(() => ({ vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) vi.mock('../../client/lookup/pr-for-branch-outcome', () => { - return { - getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock - } + return moduleMocks.clientModuleMock(coordinatorMocks) }) vi.mock('../../repositories/github-api-repository-remote-probe', () => { return { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts index 231f2911d74..522c1252ff1 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts @@ -1,14 +1,18 @@ +import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' +import { runImmediatePRRefresh } from './pr-refresh-immediate-read' +import { + deliverablePRBranchOutcome, + type PRBranchReadResult +} from '../../client/lookup/pr-branch-read-resources' import type { GitHubPRRefreshCandidate, GitHubPRRefreshReason, - PRRefreshOutcome + PRRefreshOutcome, + PRSnapshotReply } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' -import { getPRForBranchOutcome } from '../../client/lookup/pr-for-branch-outcome' +import type { PreparedPRBranchRead } from '../../client/lookup/pr-for-branch-outcome' import { aliasFromCandidate, - hostedReviewOptionArgs, - isBackground, - MANUAL_MERGEABILITY_PENDING_REFRESH_MS, refreshKey, shouldBroadcastQueued, validateCandidate @@ -26,13 +30,9 @@ import { type PRWatchJob, type PRWatchJobHooks } from './pr-refresh-watch-jobs' -import { prRefreshRateLimitPausedUntil } from './pr-refresh-rate-limit-gate' import { PRRefreshRetryState } from './pr-refresh-retry-state' import { PRRefreshVisibility } from './pr-refresh-visibility' -import { - blockedWslDistroForPath, - wslDistroForPath -} from '../../../wsl/filesystem/wsl-unc-access-gate' +import { refreshPRPolicyContext } from '../../client/lookup/pr-quiet-policy-evidence' const retry = new PRRefreshRetryState() const queue = new PRRefreshQueue((key) => retry.reset(key)) @@ -46,7 +46,7 @@ export function addPRRefreshOutcomeObserver(observer: PRRefreshOutcomeObserver): } export function setPRRefreshRegistrationCheck(check: PRRefreshRegistrationCheck | null): void { - drainer.setRegistrationCheck(check) + drainer.registrationCheck = check } export function setPRWatchJobHooks(hooks: PRWatchJobHooks | null): void { @@ -72,11 +72,71 @@ export function cancelPRWatchRead(job: PRWatchJob): void { * so a desktop read in flight for the same checkout keeps its follow-up. */ export async function runHostedPRRead( candidate: GitHubPRRefreshCandidate, - read: () => Promise + read: (() => Promise) | PreparedPRBranchRead, + didRead: () => boolean = () => true, + release: () => void = () => {} ): Promise { - const outcome = await read() - events.observe(candidate, outcome) - return outcome + try { + if (typeof read !== 'function') { + const result = await read.readResult((outcome) => { + events.observe(candidate, outcome) + return outcome + }) + return result!.outcome + } + const outcome = await read() + if (didRead()) { + events.observe(candidate, outcome) + } + return outcome + } finally { + if (typeof read !== 'function') { + read.release() + } else { + release() + } + } +} + +export async function runHostedPRSnapshot( + candidate: GitHubPRRefreshCandidate, + prepared: PreparedPRBranchRead, + deadline: number, + signal?: AbortSignal, + acceptRevalidationOnly = false +): Promise { + if (prepared.cached() || drainer.hostedJobs.has(prepared)) { + return drainer.hostedJobs.read(prepared, candidate, deadline, signal, acceptRevalidationOnly) + } + if (acceptRevalidationOnly && !prepared.canRetain()) { + return drainer.hostedJobs.complete(prepared, candidate, null, acceptRevalidationOnly) + } + const pending = prepared.pending() + if (pending) { + const timeout = new Error('Pull request snapshot wait timed out') + let result: PRBranchReadResult + try { + result = await sharedPromiseSettlementWaiters(pending).wait({ + signal, + ...(acceptRevalidationOnly + ? { timeoutMs: Math.max(0, deadline - Date.now()), createTimeoutError: () => timeout } + : {}), + createAbortError: () => new Error('Pull request wait was cancelled') + }) + } catch (error) { + if (error === timeout) { + return drainer.hostedJobs.complete(prepared, candidate, null, acceptRevalidationOnly) + } + throw error + } + return drainer.hostedJobs.complete( + prepared, + candidate, + acceptRevalidationOnly ? deliverablePRBranchOutcome(prepared, result) : result.outcome, + acceptRevalidationOnly + ) + } + return drainer.hostedJobs.readCold(candidate, prepared, acceptRevalidationOnly) } function removeInvisibleVisibleRefreshes(): void { @@ -139,6 +199,7 @@ export function reportVisiblePRRefreshCandidates( generation: number, windowId: number ): void { + refreshPRPolicyContext() const newlyExposed = new Set(candidates.map(refreshKey).filter((key) => !visibility.has(key))) if (!visibility.report(candidates, generation, windowId)) { return @@ -178,110 +239,15 @@ export function _getPRRefreshAliasCountForTests(key: string): number { return queue.aliasCount(key) } -export async function refreshPRNow( +export function refreshPRNow( candidate: GitHubPRRefreshCandidate, reason: GitHubPRRefreshReason = 'manual', options: { userRefresh?: boolean } = {} -): Promise { - const alias = aliasFromCandidate(candidate) - const key = refreshKey(candidate) - const existing = queue.get(key) - const aliasMap = new Map(existing ? existing.aliases : []) - aliasMap.set(alias.cacheKey, alias) - const aliases = Array.from(aliasMap.values()) - const skippedReason = validateCandidate(candidate) - if (skippedReason) { - queue.removeInvalidAlias(key, alias) - const outcome: PRRefreshOutcome = { - kind: 'upstream-error', - errorType: 'unknown', - message: `Cannot refresh PR for this worktree: ${skippedReason}`, - fetchedAt: Date.now() - } - events.broadcast({ aliases: [alias], reason, status: 'skipped', skippedReason }) - return outcome - } - // E9: renderer fallbacks reach here with automatic reasons; only a manual refresh may start a stopped distro. - if ( - isBackground(reason) && - wslDistroForPath(candidate.repoPath, candidate.localGitOptions?.wslDistro) && - (await blockedWslDistroForPath(candidate.repoPath, candidate.localGitOptions?.wslDistro)) - ) { - events.broadcast({ aliases: [alias], reason, status: 'skipped', skippedReason: 'fresh' }) - // Local callers keep their cached PR on an upstream error; nothing is recorded or retried here. - return { - kind: 'upstream-error', - errorType: 'unknown', - message: 'WSL distro is not running', - fetchedAt: Date.now() - } - } - - const primaryGateUntil = await prRefreshRateLimitPausedUntil(candidate, false) - const gateUntil = Math.max(primaryGateUntil ?? 0, retry.manualGateUntil(key)) - if (gateUntil > Date.now()) { - queue.protectBackgroundUntil(key, gateUntil) - queue.set(key, { - key, - candidate, - aliases: aliasMap, - reason, - priority: 40, - dueAt: gateUntil, - queuedAt: queue.nextOrder() - }) - events.broadcast({ - aliases, - reason, - status: 'paused', - pausedUntil: gateUntil, - skippedReason: 'rate-limit' - }) - drainer.schedule(Math.max(1_000, gateUntil - Date.now())) - return { - kind: 'upstream-error', - errorType: 'rate_limited', - message: 'GitHub is temporarily limiting requests. Try again after the limit resets.', - fetchedAt: Date.now(), - nextAutoRetryAt: gateUntil, - retryDisabledUntil: gateUntil - } - } - - queue.delete(key) - const requestSequence = events.nextSequence() - const requestStartedAt = Date.now() - queue.noteRequestStarted(key, requestSequence) - events.broadcast({ aliases, reason, status: 'in-flight', requestStartedAt }, requestSequence) - const outcome = await getPRForBranchOutcome( - candidate.repoPath, - candidate.branch, - candidate.linkedPRNumber ?? null, - candidate.connectionId ?? null, - candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null, - ...hostedReviewOptionArgs(candidate, reason, options) +): Promise { + return runImmediatePRRefresh( + { queue, retry, visibility, events, drainer }, + candidate, + reason, + options ) - if (!queue.ownsRequest(key, requestSequence)) { - events.broadcast({ aliases, reason, outcome, requestStartedAt }, requestSequence) - return outcome - } - let plannedRetryAt: number | undefined - let broadcastOutcome = outcome - if (outcome.kind === 'upstream-error' && visibility.has(key)) { - plannedRetryAt = retry.nextVisibleErrorRetryAt(key, visibility.candidate(key, candidate)) - broadcastOutcome = retry.withErrorSchedule(outcome, plannedRetryAt) - } - events.observe(candidate, outcome, aliases) - retry.noteManualGate(key, broadcastOutcome) - events.broadcast( - { aliases, reason, outcome: broadcastOutcome, requestStartedAt }, - requestSequence - ) - drainer.scheduleVisibleFollowUp(key, candidate, outcome, 40, aliases, undefined, { - plannedRetryAt, - ...(reason === 'manual' - ? { pendingMergeabilityDelayMs: MANUAL_MERGEABILITY_PENDING_REFRESH_MS } - : {}) - }) - return broadcastOutcome } diff --git a/src/main/github/pull-requests/refresh/pr-refresh-event-publisher.ts b/src/main/github/pull-requests/refresh/pr-refresh-event-publisher.ts index 28af9df1b82..1f16af98ef5 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-event-publisher.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-event-publisher.ts @@ -16,6 +16,8 @@ export type PRRefreshOutcomeObserver = ( aliases: readonly GitHubPRRefreshAlias[] ) => void +import { projectPRPolicyOutcome } from '../../client/lookup/pr-quiet-policy-evidence' + const DIAGNOSTIC_BREADCRUMB_MIN_INTERVAL_MS = 30_000 export class PRRefreshEventPublisher { @@ -35,6 +37,7 @@ export class PRRefreshEventPublisher { outcome: PRRefreshOutcome, aliases: readonly GitHubPRRefreshAlias[] = [] ): void { + projectPRPolicyOutcome(candidate, outcome) for (const observer of this.observers) { try { observer(candidate, outcome, aliases) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts b/src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts new file mode 100644 index 00000000000..8438d1a3604 --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts @@ -0,0 +1,173 @@ +import type { + GitHubPRRefreshCandidate, + GitHubPRRefreshReason, + PRRefreshOutcome, + PRSnapshotReply +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { preparePRBranchRead } from '../../client/lookup/pr-for-branch-outcome' +import { deliverablePRBranchOutcome } from '../../client/lookup/pr-branch-read-resources' +import { + aliasFromCandidate, + refreshKey, + validateCandidate, + isBackground, + hostedReviewOptionArgs, + MANUAL_MERGEABILITY_PENDING_REFRESH_MS +} from './pr-refresh-candidate-policy' +import { + blockedWslDistroForPath, + wslDistroForPath +} from '../../../wsl/filesystem/wsl-unc-access-gate' +import { prRefreshRateLimitPausedUntil } from './pr-refresh-rate-limit-gate' +import type { PRRefreshQueue } from './pr-refresh-queue' +import type { PRRefreshRetryState } from './pr-refresh-retry-state' +import type { PRRefreshVisibility } from './pr-refresh-visibility' +import type { PRRefreshEventPublisher } from './pr-refresh-event-publisher' +import type { PRRefreshQueueDrainer } from './pr-refresh-queue-drainer' + +type ImmediateRefreshOwners = { + queue: PRRefreshQueue + retry: PRRefreshRetryState + visibility: PRRefreshVisibility + events: PRRefreshEventPublisher + drainer: PRRefreshQueueDrainer +} +export async function runImmediatePRRefresh( + { queue, retry, visibility, events, drainer }: ImmediateRefreshOwners, + candidate: GitHubPRRefreshCandidate, + reason: GitHubPRRefreshReason = 'manual', + options: { userRefresh?: boolean } = {} +): Promise { + const alias = aliasFromCandidate(candidate) + const key = refreshKey(candidate) + const existing = queue.get(key) + const aliasMap = new Map(existing ? existing.aliases : []) + aliasMap.set(alias.cacheKey, alias) + const aliases = Array.from(aliasMap.values()) + const skippedReason = validateCandidate(candidate) + if (skippedReason) { + queue.removeInvalidAlias(key, alias) + const outcome: PRRefreshOutcome = { + kind: 'upstream-error', + errorType: 'unknown', + message: `Cannot refresh PR for this worktree: ${skippedReason}`, + fetchedAt: Date.now() + } + events.broadcast({ aliases: [alias], reason, status: 'skipped', skippedReason }) + return outcome + } + // E9: renderer fallbacks reach here with automatic reasons; only a manual refresh may start a stopped distro. + if ( + isBackground(reason) && + wslDistroForPath(candidate.repoPath, candidate.localGitOptions?.wslDistro) && + (await blockedWslDistroForPath(candidate.repoPath, candidate.localGitOptions?.wslDistro)) + ) { + events.broadcast({ aliases: [alias], reason, status: 'skipped', skippedReason: 'fresh' }) + // Local callers keep their cached PR on an upstream error; nothing is recorded or retried here. + return { + kind: 'upstream-error', + errorType: 'unknown', + message: 'WSL distro is not running', + fetchedAt: Date.now() + } + } + + const primaryGateUntil = await prRefreshRateLimitPausedUntil(candidate, false) + const gateUntil = Math.max(primaryGateUntil ?? 0, retry.manualGateUntil(key)) + if (gateUntil > Date.now()) { + queue.protectBackgroundUntil(key, gateUntil) + queue.set(key, { + key, + candidate, + aliases: aliasMap, + reason, + priority: 40, + dueAt: gateUntil, + queuedAt: queue.nextOrder() + }) + events.broadcast({ + aliases, + reason, + status: 'paused', + pausedUntil: gateUntil, + skippedReason: 'rate-limit' + }) + drainer.schedule(Math.max(1_000, gateUntil - Date.now())) + return { + kind: 'upstream-error', + errorType: 'rate_limited', + message: 'GitHub is temporarily limiting requests. Try again after the limit resets.', + fetchedAt: Date.now(), + nextAutoRetryAt: gateUntil, + retryDisabledUntil: gateUntil + } + } + + queue.delete(key) + const requestSequence = events.nextSequence() + const requestStartedAt = Date.now() + queue.noteRequestStarted(key, requestSequence) + events.broadcast({ aliases, reason, status: 'in-flight', requestStartedAt }, requestSequence) + const prepared = await preparePRBranchRead( + candidate.repoPath, + candidate.branch, + candidate.linkedPRNumber ?? null, + candidate.connectionId ?? null, + candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null, + ...hostedReviewOptionArgs(candidate, reason, options) + ) + try { + const result = await prepared.readResult( + drainer.scheduler.settleRead(key, candidate, aliases, prepared, requestSequence) + ) + if (!result) { + throw new Error('An unrestricted PR read must return its own result') + } + const outcome = deliverablePRBranchOutcome(prepared, result) + if (!outcome) { + if (queue.ownsRequest(key, requestSequence)) { + events.broadcast( + { aliases, reason, status: 'skipped', skippedReason: 'fresh' }, + requestSequence + ) + drainer.scheduler.completeWithoutOutcome( + key, + candidate, + aliases, + 40, + undefined, + !isBackground(reason) + ) + } + return { + revalidation: { invalidated: true, retryAfterMs: drainer.hostedJobs.retryAfterMs(prepared) } + } + } + if (!queue.ownsRequest(key, requestSequence)) { + events.broadcast({ aliases, reason, outcome, requestStartedAt }, requestSequence) + return outcome + } + let plannedRetryAt: number | undefined + let broadcastOutcome = outcome + if (outcome.kind === 'upstream-error' && visibility.has(key)) { + plannedRetryAt = + outcome.nextAutoRetryAt ?? + retry.nextVisibleErrorRetryAt(key, visibility.candidate(key, candidate)) + broadcastOutcome = retry.withErrorSchedule(outcome, plannedRetryAt) + } + retry.noteManualGate(key, broadcastOutcome) + events.broadcast( + { aliases, reason, outcome: broadcastOutcome, requestStartedAt }, + requestSequence + ) + drainer.scheduleVisibleFollowUp(key, candidate, outcome, 40, aliases, undefined, { + plannedRetryAt, + ...(reason === 'manual' + ? { pendingMergeabilityDelayMs: MANUAL_MERGEABILITY_PENDING_REFRESH_MS } + : {}) + }) + return broadcastOutcome + } finally { + prepared.release() + } +} diff --git a/src/main/github/pull-requests/refresh/pr-refresh-pacing.ts b/src/main/github/pull-requests/refresh/pr-refresh-pacing.ts index 2013a5e05ae..0353b30c4b4 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-pacing.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-pacing.ts @@ -7,6 +7,13 @@ const BACKGROUND_BUDGET_MAX = 20 const ACTIVE_BURST_WINDOW_MS = 30_000 const ACTIVE_BURST_MAX = 3 +export function isSelectedBudgetedPRRefresh(entry: PRRefreshQueueEntry): boolean { + return ( + entry.candidate.isSelected === true && + (entry.reason === 'visible' || (entry.reason === 'swr' && entry.hosted !== undefined)) + ) +} + export function usesActiveRefreshPacing(entry: PRRefreshQueueEntry): boolean { // Selected admission survives deselection while queued; periodic follow-ups clear the flag. return ( @@ -31,8 +38,7 @@ export class PRRefreshPacing { } noteBackgroundStart(entry: PRRefreshQueueEntry): void { - this.lastBudgetedStartWasSelected = - entry.reason === 'visible' && entry.candidate.isSelected === true + this.lastBudgetedStartWasSelected = isSelectedBudgetedPRRefresh(entry) const now = Date.now() this.lastBackgroundStartAt = now this.backgroundStarts.push(now) @@ -70,8 +76,7 @@ export class PRRefreshPacing { private priority(entry: PRRefreshQueueEntry): number { // Reserve the next budgeted slot for other ready reviews after a selected list read. return this.lastBudgetedStartWasSelected && - entry.reason === 'visible' && - entry.candidate.isSelected === true && + isSelectedBudgetedPRRefresh(entry) && entry.bypassBackgroundBudget !== true ? 0 : entry.priority diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts index 17d3712655f..54c39d72422 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts @@ -1,41 +1,38 @@ -import type { - GitHubPRRefreshAlias, - GitHubPRRefreshCandidate, - PRRefreshOutcome -} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' -import { getPRForBranchOutcome } from '../../client/lookup/pr-for-branch-outcome' +import { admitPreparedPRRead } from './pr-refresh-read-admission' +import { deliverablePRBranchOutcome } from '../../client/lookup/pr-branch-read-resources' +import type { GitHubPRRefreshCandidate } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { preparePRBranchRead } from '../../client/lookup/pr-for-branch-outcome' import { - aliasFromCandidate, - freshRetryAt, hostedReviewOptionArgs, + freshQueuedPROutcome, + bypassesFreshnessDelay, isBackground, isBudgetedBackground, - isMergeabilityPendingOutcome, - sameAliasRequestIdentity, - validateCandidate, - visibleCandidateAfterOutcome, - visibleFollowUpPriority + validateCandidate } from './pr-refresh-candidate-policy' import type { PRRefreshEventPublisher } from './pr-refresh-event-publisher' import { type PRRefreshPacing, usesActiveRefreshPacing } from './pr-refresh-pacing' -import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' +import type { PRRefreshQueue } from './pr-refresh-queue' import { PRWatchJobRunner } from './pr-refresh-watch-jobs' import { prRefreshRateLimitPausedUntil } from './pr-refresh-rate-limit-gate' import { blockedWslDistroForPath, wslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' -import { outsideWslUserAct } from '../../../wsl/discovery/wsl-user-act-scope' import type { PRRefreshRetryState } from './pr-refresh-retry-state' import type { PRRefreshVisibility } from './pr-refresh-visibility' +import { HostedPRReadJobs } from './hosted-pr-read-jobs' +import { PRRefreshQueueScheduler } from './pr-refresh-queue-scheduler' export type PRRefreshRegistrationCheck = (candidate: GitHubPRRefreshCandidate) => boolean export class PRRefreshQueueDrainer { private draining = false - private timer: ReturnType | null = null - private registrationCheck: PRRefreshRegistrationCheck | null = null + registrationCheck: PRRefreshRegistrationCheck | null = null readonly watchJobs: PRWatchJobRunner + readonly hostedJobs: HostedPRReadJobs + readonly scheduler: PRRefreshQueueScheduler + readonly scheduleVisibleFollowUp: PRRefreshQueueScheduler['scheduleVisibleFollowUp'] constructor( private readonly queue: PRRefreshQueue, @@ -45,110 +42,27 @@ export class PRRefreshQueueDrainer { private readonly events: PRRefreshEventPublisher ) { this.watchJobs = new PRWatchJobRunner(queue, retry, this) - } - - setRegistrationCheck(check: PRRefreshRegistrationCheck | null): void { - this.registrationCheck = check + this.scheduler = new PRRefreshQueueScheduler( + queue, + pacing, + visibility, + retry, + events, + this.watchJobs, + () => this.drain() + ) + this.scheduleVisibleFollowUp = this.scheduler.scheduleVisibleFollowUp.bind(this.scheduler) + this.hostedJobs = new HostedPRReadJobs( + queue, + pacing, + retry, + () => this.schedule(), + (candidate, outcome) => events.observe(candidate, outcome) + ) } schedule(delay = 0): void { - clearTimeout(this.timer ?? undefined) - this.timer = setTimeout(() => { - this.timer = null - // The drain serves every queued repo; a scheduling call inside a WSL user act must not lend it that act. - void outsideWslUserAct(() => this.drain()) - }, delay) - } - - scheduleVisibleFollowUp( - key: string, - candidate: GitHubPRRefreshCandidate, - outcome: PRRefreshOutcome, - priority: number, - aliases: GitHubPRRefreshAlias[], - windowId?: number, - options?: { pendingMergeabilityDelayMs?: number; plannedRetryAt?: number } - ): void { - if (outcome.kind === 'upstream-error') { - const retryAt = Math.max( - options?.plannedRetryAt ?? - this.retry.nextVisibleErrorRetryAt(key, this.visibility.candidate(key, candidate)), - this.retry.manualGateUntil(key) - ) - this.queue.protectBackgroundUntil(key, retryAt) - if (!this.visibility.has(key)) { - return - } - this.queue.setVisibleFollowUp({ - key, - candidate, - aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), - reason: 'visible', - priority, - dueAt: retryAt, - queuedAt: this.queue.nextOrder(), - windowId - }) - this.schedule(retryAt - Date.now()) - return - } - this.retry.reset(key) - const refreshed = visibleCandidateAfterOutcome(candidate, outcome) - this.visibility.update(refreshed) - if (!this.visibility.has(key)) { - return - } - const followUpCandidate = this.visibility.candidate(key, refreshed) - const regularDueAt = freshRetryAt(followUpCandidate) ?? Date.now() - const pendingDueAt = - options?.pendingMergeabilityDelayMs !== undefined && isMergeabilityPendingOutcome(outcome) - ? outcome.fetchedAt + options.pendingMergeabilityDelayMs - : null - const dueAt = pendingDueAt === null ? regularDueAt : Math.min(regularDueAt, pendingDueAt) - if (!Number.isFinite(dueAt)) { - const pending = this.queue.get(key) - if ( - pending?.reason === 'visible' && - sameAliasRequestIdentity( - aliasFromCandidate(pending.candidate), - aliasFromCandidate(followUpCandidate) - ) - ) { - this.queue.delete(key) - } - return - } - this.queue.setVisibleFollowUp({ - key, - candidate: followUpCandidate, - aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), - reason: 'visible', - priority: visibleFollowUpPriority(followUpCandidate, priority), - dueAt, - queuedAt: this.queue.nextOrder(), - bypassBackgroundBudget: pendingDueAt !== null, - followUp: true, - windowId - }) - this.schedule(Math.max(0, dueAt - Date.now())) - } - - private ordered(): PRRefreshQueueEntry[] { - this.watchJobs.age(this.queue.values(), Date.now()) - return this.queue.ordered((a, b) => this.pacing.order(a, b)) - } - - private nextQueuedWakeDelay(excludedKey: string): number | null { - const now = Date.now() - let nextDelay = Number.POSITIVE_INFINITY - for (const entry of this.queue.values()) { - if (entry.key === excludedKey) { - continue - } - const delay = entry.dueAt > now ? entry.dueAt - now : this.pacing.entryDelay(entry) - nextDelay = Math.min(nextDelay, delay) - } - return Number.isFinite(nextDelay) ? Math.max(0, nextDelay) : null + this.scheduler.schedule(delay) } private async drain(): Promise { @@ -157,8 +71,12 @@ export class PRRefreshQueueDrainer { } this.draining = true try { + const { queue, pacing, events, scheduler, watchJobs } = this while (this.queue.size > 0) { - let next = this.ordered()[0] + let next = this.scheduler.ordered()[0] + if (this.hostedJobs.completeFromCache(next)) { + continue + } const waitMs = next.dueAt - Date.now() if (waitMs > 0) { this.schedule(waitMs) @@ -167,23 +85,27 @@ export class PRRefreshQueueDrainer { let delay = this.pacing.entryDelay(next) if (delay > 0) { - const runnable = this.ordered().find( - (entry) => entry.dueAt <= Date.now() && this.pacing.entryDelay(entry) === 0 - ) + const runnable = this.scheduler + .ordered() + .find((entry) => entry.dueAt <= Date.now() && this.pacing.entryDelay(entry) === 0) if (runnable && runnable.key !== next.key) { next = runnable delay = 0 } else { - this.notePacingDelay(next) - this.schedule(Math.min(delay, this.nextQueuedWakeDelay(next.key) ?? delay)) + this.scheduler.notePacingDelay(next) + this.schedule(Math.min(delay, this.scheduler.nextQueuedWakeDelay(next.key) ?? delay)) return } } this.queue.delete(next.key) + if (this.hostedJobs.completeFromCache(next)) { + continue + } const aliases = Array.from(next.aliases.values()) const skippedReason = validateCandidate(next.candidate) if (skippedReason) { + next.hosted?.finish(null) this.events.record('skipped', next.reason, skippedReason) this.events.broadcast({ aliases, reason: next.reason, status: 'skipped', skippedReason }) continue @@ -199,6 +121,7 @@ export class PRRefreshQueueDrainer { next.candidate.localGitOptions?.wslDistro ))) ) { + next.hosted?.finish(null) this.events.broadcast({ aliases, reason: next.reason, @@ -208,70 +131,158 @@ export class PRRefreshQueueDrainer { this.watchJobs.skipped(next) continue } + if ( + !next.hosted && + !next.watch && + !next.bypassBackgroundBudget && + (next.reason === 'visible' || next.reason === 'swr') + ) { + const candidate = next.candidate + const fresh = freshQueuedPROutcome(candidate, next.reason, next.foreground) + if (fresh) { + this.events.broadcast({ aliases, reason: next.reason, outcome: fresh }) + this.scheduleVisibleFollowUp( + next.key, + candidate, + fresh, + next.priority, + aliases, + next.windowId + ) + continue + } + } const requestSequence = this.events.nextSequence() const requestStartedAt = Date.now() this.queue.noteRequestStarted(next.key, requestSequence) - this.events.broadcast( - { aliases, reason: next.reason, status: 'in-flight', requestStartedAt }, - requestSequence - ) - - if (isBackground(next.reason)) { - const pausedUntil = await prRefreshRateLimitPausedUntil(next.candidate, true) + if (!next.hosted) { + this.events.broadcast( + { aliases, reason: next.reason, status: 'in-flight', requestStartedAt }, + requestSequence + ) + } + let joinedRead = next.hosted?.prepared.pending() + if (isBackground(next.reason) && !joinedRead) { + const checkRateLimit = () => prRefreshRateLimitPausedUntil(next.candidate, true) + const pausedUntil = await (next.hosted + ? next.hosted.prepared.withExecution(checkRateLimit) + : checkRateLimit()) if (!this.queue.ownsRequest(next.key, requestSequence)) { + next.hosted?.finish(null) continue } if (pausedUntil !== null) { this.queue.protectBackgroundUntil(next.key, pausedUntil) - this.queue.set(next.key, { ...next, dueAt: pausedUntil }) - this.events.broadcast({ - aliases, - reason: next.reason, - status: 'paused', - pausedUntil, - skippedReason: 'rate-limit' - }) - this.schedule(Math.max(1_000, pausedUntil - Date.now())) + const dueAt = Math.min(pausedUntil, next.hosted?.expiresAt ?? Infinity) + next.dueAt = dueAt + this.queue.set(next.key, next) + if (!next.hosted) { + this.events.broadcast({ + aliases, + reason: next.reason, + status: 'paused', + pausedUntil, + skippedReason: 'rate-limit' + }) + } + this.schedule(Math.max(1_000, dueAt - Date.now())) continue } - if (next.bypassBackgroundBudget !== true && isBudgetedBackground(next.reason)) { + if (this.hostedJobs.completeFromCache(next)) { + continue + } + if ( + next.watch && + next.bypassBackgroundBudget !== true && + isBudgetedBackground(next.reason) + ) { this.pacing.noteBackgroundStart(next) this.watchJobs.noteBudgetedStart(next) } - if (usesActiveRefreshPacing(next)) { + if (next.watch && usesActiveRefreshPacing(next)) { this.pacing.noteActiveStart(next) } } - if (await this.watchJobs.readHead(next)) { continue } - const outcome = await getPRForBranchOutcome( - next.candidate.repoPath, - next.candidate.branch, - next.candidate.linkedPRNumber ?? null, - next.candidate.connectionId ?? null, - next.candidate.linkedPRNumber == null ? (next.candidate.fallbackPRNumber ?? null) : null, - ...hostedReviewOptionArgs(next.candidate, next.reason, { watchPRKey: next.watch?.prKey }) + if (next.hosted) { + next.hosted.running = true + } + const prepared = + next.hosted?.prepared ?? + (await preparePRBranchRead( + next.candidate.repoPath, + next.candidate.branch, + next.candidate.linkedPRNumber ?? null, + next.candidate.connectionId ?? null, + next.candidate.linkedPRNumber == null + ? (next.candidate.fallbackPRNumber ?? null) + : null, + ...hostedReviewOptionArgs(next.candidate, next.reason, { + watchPRKey: next.watch?.prKey + }) + )) + joinedRead ??= bypassesFreshnessDelay(next.reason) ? undefined : prepared.pending() + const admitted = admitPreparedPRRead( + { queue, pacing, events, scheduler, watchJobs }, + next, + prepared, + aliases, + requestSequence, + requestStartedAt, + Boolean(joinedRead) ) + if (!admitted) { + continue + } + const settle = this.scheduler.settleRead( + next.key, + next.candidate, + aliases, + prepared, + requestSequence, + Boolean(next.hosted) + ) + const result = await (joinedRead ?? prepared.readResult(settle, Boolean(next.hosted))) + const outcome = result ? deliverablePRBranchOutcome(prepared, result) : null + if (!outcome) { + this.scheduler.finishWithoutOutcome(next, aliases, requestSequence) + continue + } + if ( + next.hosted && + (!next.hosted.prepared.isCurrent() || !next.hosted.prepared.accepts(outcome)) + ) { + next.hosted.finish(null) + continue + } if (!this.queue.ownsRequest(next.key, requestSequence)) { + next.hosted?.finish(null) this.events.broadcast( { aliases, reason: next.reason, outcome, requestStartedAt }, requestSequence ) continue } - let plannedRetryAt: number | undefined - let broadcastOutcome = outcome - if (outcome.kind === 'upstream-error' && this.visibility.has(next.key)) { - plannedRetryAt = this.retry.nextVisibleErrorRetryAt( - next.key, - this.visibility.candidate(next.key, next.candidate) - ) - broadcastOutcome = this.retry.withErrorSchedule(outcome, plannedRetryAt) - } - this.events.observe(next.candidate, outcome, aliases) + const plannedRetryAt = this.retry.errorFollowUpAt( + next.key, + this.visibility.candidate(next.key, next.candidate), + outcome, + !next.hosted && this.visibility.has(next.key) + ) + const broadcastOutcome = + plannedRetryAt === undefined + ? outcome + : this.retry.withErrorSchedule(outcome, plannedRetryAt) this.retry.noteManualGate(next.key, broadcastOutcome) + if (next.hosted) { + if (outcome.kind !== 'upstream-error') { + this.retry.reset(next.key) + } + next.hosted.finish(broadcastOutcome) + continue + } this.events.broadcast( { aliases, reason: next.reason, outcome: broadcastOutcome, requestStartedAt }, requestSequence @@ -294,22 +305,4 @@ export class PRRefreshQueueDrainer { this.draining = false } } - - private notePacingDelay(entry: PRRefreshQueueEntry): void { - if (this.pacing.isActiveBurstDelayed(entry) && !entry.activeDelayNotified) { - entry.activeDelayNotified = true - this.events.broadcast({ - aliases: Array.from(entry.aliases.values()), - reason: entry.reason, - status: 'queued' - }) - } - if ( - entry.bypassBackgroundBudget !== true && - isBudgetedBackground(entry.reason) && - this.pacing.nextBudgetDelay() > 0 - ) { - this.events.record('background-pause', entry.reason) - } - } } diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts index 980557b97bc..2a2323a7209 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-growth-bound.test.ts @@ -8,9 +8,7 @@ const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) vi.mock('../../client/lookup/pr-for-branch-outcome', () => { - return { - getPRForBranchOutcome: coordinatorMocks.getPRForBranchOutcomeMock - } + return moduleMocks.clientModuleMock(coordinatorMocks) }) vi.mock('../../repositories/github-api-repository-remote-probe', () => { return { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts new file mode 100644 index 00000000000..2a2459cd804 --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts @@ -0,0 +1,298 @@ +import type { + GitHubPRRefreshAlias, + GitHubPRRefreshCandidate, + PRRefreshOutcome +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { + aliasFromCandidate, + freshRetryAt, + isBudgetedBackground, + isMergeabilityPendingOutcome, + sameAliasRequestIdentity, + visibleCandidateAfterOutcome, + visibleFollowUpPriority +} from './pr-refresh-candidate-policy' +import type { + PreparedPRBranchRead, + PRReadSettlement +} from '../../client/lookup/pr-for-branch-outcome' +import type { PRRefreshEventPublisher } from './pr-refresh-event-publisher' +import type { PRRefreshPacing } from './pr-refresh-pacing' +import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' +import type { PRWatchJobRunner } from './pr-refresh-watch-jobs' +import type { PRRefreshRetryState } from './pr-refresh-retry-state' +import type { PRRefreshVisibility } from './pr-refresh-visibility' +import { outsideWslUserAct } from '../../../wsl/discovery/wsl-user-act-scope' + +export class PRRefreshQueueScheduler { + private timer: ReturnType | null = null + private timerDueAt = Infinity + + constructor( + private readonly queue: PRRefreshQueue, + private readonly pacing: PRRefreshPacing, + private readonly visibility: PRRefreshVisibility, + private readonly retry: PRRefreshRetryState, + private readonly events: PRRefreshEventPublisher, + private readonly watchJobs: PRWatchJobRunner, + private readonly runDrain: () => Promise + ) {} + + schedule(delay = 0): void { + const dueAt = performance.now() + Math.max(0, delay) + if (this.timer !== null && this.timerDueAt <= dueAt) { + return + } + clearTimeout(this.timer ?? undefined) + this.timerDueAt = dueAt + this.timer = setTimeout(() => { + this.timer = null + this.timerDueAt = Infinity + // The drain serves every queued repo; a scheduling call inside a WSL user act must not lend it that act. + void outsideWslUserAct(() => this.runDrain()) + }, delay) + } + + settleRead( + key: string, + candidate: GitHubPRRefreshCandidate, + aliases: GitHubPRRefreshAlias[], + prepared: PreparedPRBranchRead, + requestSequence: number, + hosted = false + ): PRReadSettlement { + return (outcome, producer) => { + if (!prepared.isCurrent()) { + return outcome + } + const settled = + producer.retained && + outcome.kind === 'upstream-error' && + (hosted || this.visibility.has(key)) + ? this.retry.settleProducerError( + outcome, + key, + hosted + ? { ...candidate, isSelected: false } + : this.visibility.candidate(key, candidate), + prepared, + this.queue, + this.queue.ownsRequest(key, requestSequence) + ) + : outcome + this.events.observe(candidate, settled, aliases) + return settled + } + } + + completeWithoutOutcome( + key: string, + candidate: GitHubPRRefreshCandidate, + aliases: GitHubPRRefreshAlias[], + priority: number, + windowId?: number, + foreground = false + ): void { + if (!this.visibility.has(key) || this.queue.get(key)) { + return + } + const current = this.visibility.candidate(key, candidate) + const dueAt = Math.max( + freshRetryAt(current, foreground) ?? Date.now(), + this.queue.backgroundGateUntil(key), + this.retry.manualGateUntil(key) + ) + if (!Number.isFinite(dueAt)) { + return + } + this.queue.setVisibleFollowUp({ + key, + candidate: current, + aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), + reason: 'visible', + priority: visibleFollowUpPriority(current, priority), + dueAt, + queuedAt: this.queue.nextOrder(), + followUp: !foreground, + foreground, + windowId + }) + this.schedule(Math.max(0, dueAt - Date.now())) + } + + finishWithoutOutcome( + next: PRRefreshQueueEntry, + aliases: GitHubPRRefreshAlias[], + requestSequence: number + ): void { + next.hosted?.finish(null) + if (!next.hosted && this.queue.ownsRequest(next.key, requestSequence)) { + this.events.broadcast( + { aliases, reason: next.reason, status: 'skipped', skippedReason: 'fresh' }, + requestSequence + ) + if (next.watch) { + this.watchJobs.skipped(next) + } else { + this.completeWithoutOutcome( + next.key, + next.candidate, + aliases, + next.priority, + next.windowId, + next.foreground + ) + } + } + } + + consumeGatedError( + entry: PRRefreshQueueEntry, + prepared: PreparedPRBranchRead, + requestSequence: number, + requestStartedAt: number + ): boolean { + if ( + entry.hosted || + entry.watch || + entry.bypassBackgroundBudget || + (entry.reason !== 'visible' && entry.reason !== 'swr') || + !prepared.isCurrent() + ) { + return false + } + const outcome = prepared.cached()?.outcome + if (outcome?.kind !== 'upstream-error') { + return false + } + const retryAt = Math.max(outcome.nextAutoRetryAt ?? 0, outcome.retryDisabledUntil ?? 0) + if (retryAt <= Date.now()) { + return false + } + const aliases = Array.from(entry.aliases.values()) + this.retry.noteManualGate(entry.key, outcome) + this.events.broadcast( + { aliases, reason: entry.reason, outcome, requestStartedAt }, + requestSequence + ) + this.scheduleVisibleFollowUp( + entry.key, + entry.candidate, + outcome, + entry.priority, + aliases, + entry.windowId, + { plannedRetryAt: retryAt } + ) + return true + } + + scheduleVisibleFollowUp( + key: string, + candidate: GitHubPRRefreshCandidate, + outcome: PRRefreshOutcome, + priority: number, + aliases: GitHubPRRefreshAlias[], + windowId?: number, + options?: { pendingMergeabilityDelayMs?: number; plannedRetryAt?: number } + ): void { + if (outcome.kind === 'upstream-error') { + const retryAt = Math.max( + options?.plannedRetryAt ?? + this.retry.nextVisibleErrorRetryAt(key, this.visibility.candidate(key, candidate)), + this.retry.manualGateUntil(key) + ) + this.queue.protectBackgroundUntil(key, retryAt) + if (!this.visibility.has(key)) { + return + } + this.queue.setVisibleFollowUp({ + key, + candidate, + aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), + reason: 'visible', + priority, + dueAt: retryAt, + queuedAt: this.queue.nextOrder(), + windowId + }) + this.schedule(retryAt - Date.now()) + return + } + this.retry.reset(key) + const refreshed = visibleCandidateAfterOutcome(candidate, outcome) + this.visibility.update(refreshed) + if (!this.visibility.has(key)) { + return + } + const followUpCandidate = this.visibility.candidate(key, refreshed) + const regularDueAt = freshRetryAt(followUpCandidate) ?? Date.now() + const pendingDueAt = + options?.pendingMergeabilityDelayMs !== undefined && isMergeabilityPendingOutcome(outcome) + ? outcome.fetchedAt + options.pendingMergeabilityDelayMs + : null + const dueAt = pendingDueAt === null ? regularDueAt : Math.min(regularDueAt, pendingDueAt) + if (!Number.isFinite(dueAt)) { + const pending = this.queue.get(key) + if ( + pending?.reason === 'visible' && + sameAliasRequestIdentity( + aliasFromCandidate(pending.candidate), + aliasFromCandidate(followUpCandidate) + ) + ) { + this.queue.delete(key) + } + return + } + this.queue.setVisibleFollowUp({ + key, + candidate: followUpCandidate, + aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), + reason: 'visible', + priority: visibleFollowUpPriority(followUpCandidate, priority), + dueAt, + queuedAt: this.queue.nextOrder(), + bypassBackgroundBudget: pendingDueAt !== null, + followUp: true, + windowId + }) + this.schedule(Math.max(0, dueAt - Date.now())) + } + + ordered(): PRRefreshQueueEntry[] { + this.watchJobs.age(this.queue.values(), Date.now()) + return this.queue.ordered((a, b) => this.pacing.order(a, b)) + } + + nextQueuedWakeDelay(excludedKey: string): number | null { + const now = Date.now() + let nextDelay = Number.POSITIVE_INFINITY + for (const entry of this.queue.values()) { + if (entry.key === excludedKey) { + continue + } + const delay = entry.dueAt > now ? entry.dueAt - now : this.pacing.entryDelay(entry) + nextDelay = Math.min(nextDelay, delay) + } + return Number.isFinite(nextDelay) ? Math.max(0, nextDelay) : null + } + + notePacingDelay(entry: PRRefreshQueueEntry): void { + if (this.pacing.isActiveBurstDelayed(entry) && !entry.activeDelayNotified) { + entry.activeDelayNotified = true + this.events.broadcast({ + aliases: Array.from(entry.aliases.values()), + reason: entry.reason, + status: 'queued' + }) + } + if ( + entry.bypassBackgroundBudget !== true && + isBudgetedBackground(entry.reason) && + this.pacing.nextBudgetDelay() > 0 + ) { + this.events.record('background-pause', entry.reason) + } + } +} diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue.ts index 00caf6e68ae..77db82b084b 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-queue.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue.ts @@ -1,4 +1,5 @@ import { REVIEW_REFRESH_COOLDOWN_MS } from '../../../../shared/review-refresh-policy' +import type { HostedPRReadJob } from './hosted-pr-read-jobs' import type { GitHubPRRefreshAlias, GitHubPRRefreshCandidate, @@ -7,11 +8,11 @@ import type { import { aliasFromCandidate, bypassesFreshnessDelay, + foregroundExposureDueAt, freshRetryAt, POST_PUSH_DELAY_MS, refreshKey, sameAliasRequestIdentity, - refreshIntervalForCandidate, shouldSkipFresh, visibleFollowUpPriority } from './pr-refresh-candidate-policy' @@ -27,9 +28,11 @@ export type PRRefreshQueueEntry = { bypassBackgroundBudget?: boolean activeDelayNotified?: boolean followUp?: boolean + foreground?: boolean windowId?: number /** A watch job: the PR's current head, or with `headSha` one earlier head's checks. */ watch?: { prKey: string; headSha?: string } + hosted?: HostedPRReadJob } export type PRRefreshEnqueue = { @@ -108,6 +111,10 @@ export class PRRefreshQueue { return this.backgroundNotBefore.get(key)?.requestSequence === requestSequence } + backgroundGateUntil(key: string): number { + return this.backgroundNotBefore.get(key)?.until ?? 0 + } + retimeVisible( candidateFor: (key: string, candidate: GitHubPRRefreshCandidate) => GitHubPRRefreshCandidate ): void { @@ -138,14 +145,7 @@ export class PRRefreshQueue { const key = refreshKey(candidate) const existing = this.entries.get(key) const freshDueAt = shouldSkipFresh(candidate, reason) ? freshRetryAt(candidate) : null - const stopped = !Number.isFinite(refreshIntervalForCandidate(candidate)) - const exposureDueAt = - reexposed && - stopped && - candidate.cachedFetchedAt != null && - Date.now() - candidate.cachedFetchedAt >= REVIEW_REFRESH_COOLDOWN_MS - ? Date.now() - : null + const exposureDueAt = foregroundExposureDueAt(candidate, reexposed) const dueAt = Math.max( exposureDueAt ?? freshDueAt ?? Date.now() + (reason === 'post-push' ? POST_PUSH_DELAY_MS : 0), bypassesFreshnessDelay(reason) ? 0 : (this.backgroundNotBefore.get(key)?.until ?? 0) @@ -163,6 +163,7 @@ export class PRRefreshQueue { dueAt, queuedAt: this.nextOrder(), followUp: reason === 'visible' && freshDueAt !== null && exposureDueAt === null, + foreground: exposureDueAt !== null, windowId }) return { alias, key, dueAt, coalesced: false } @@ -171,11 +172,12 @@ export class PRRefreshQueue { setLiveAlias(existing.aliases, alias) if ( reason === 'visible' && - !shouldSkipFresh(candidate, reason) && + (exposureDueAt !== null || !shouldSkipFresh(candidate, reason)) && existing.reason === 'visible' ) { existing.dueAt = Math.min(existing.dueAt, dueAt) existing.followUp = false + existing.foreground ||= exposureDueAt !== null } const shouldPromote = priority > existing.priority || diff --git a/src/main/github/pull-requests/refresh/pr-refresh-quiet-policy.perf.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-quiet-policy.perf.test.ts new file mode 100644 index 00000000000..4aa8e2d8c4e --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-quiet-policy.perf.test.ts @@ -0,0 +1,111 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' + +vi.mock('../../client/lookup/branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: async () => ({ + kind: 'found', + fetchedAt: Date.now(), + pr: makePR({ + headSha: 'head', + checksStatus: 'success', + checksReadComplete: true, + checksFinal: true, + autoMergeEnabled: false, + mergeQueueRequired: false + }) + }) +})) +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: async () => {}, + release: () => {} +})) + +let release: (() => void) | undefined +afterEach(() => { + release?.() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +it.each([750, 7500])( + 'selects owned quiet policy without inventory discovery at %i workspaces', + async (population) => { + vi.resetModules() + vi.useFakeTimers() + vi.setSystemTime(1_000) + const accounts = await import('../../accounts/github-project-account') + const execution = await import('../../../source-control/code-host-read-execution-scope') + const repository = { + id: 'repo', + path: '/repo', + displayName: 'Repo', + badgeColor: 'blue', + addedAt: 0, + ghAccount: { host: 'github.com', user: 'first' } + } + const inventory = vi.fn(() => + Array.from({ length: population }, (_, row) => ({ repoId: 'repo', path: `/repo/wt-${row}` })) + ) + const metadata = vi.fn(() => ({})) + release = accounts.installGitHubProjectAccounts( + { getRepos: () => [repository], getAllWorktreeMetaForHost: metadata }, + inventory + ) + const discovery = vi.spyOn(accounts, 'resolveGitHubProjectAccount') + const hashing = vi.spyOn(execution, 'codeHostReadExecutionScope') + const { getPRForBranchOutcome } = await import('../../client/lookup/pr-for-branch-outcome') + const { runHostedPRRead, reportVisiblePRRefreshCandidates } = + await import('./pr-refresh-coordinator') + const { refreshIntervalForCandidate } = await import('./pr-refresh-candidate-policy') + const { refreshPRPolicyContext } = await import('../../client/lookup/pr-quiet-policy-evidence') + const candidate = makeCandidate({ + repoId: 'repo', + repoPath: '/repo/wt-0', + branch: 'branch', + currentHeadOid: 'head', + cachedHeadOid: 'head', + cachedFetchedAt: 2_000, + cachedPRState: 'open', + cachedChecksStatus: 'success', + cachedHasPR: true + }) + const read = () => + runHostedPRRead(candidate, () => + getPRForBranchOutcome('/repo/wt-0', 'branch', null, null, null, { currentHeadOid: 'head' }) + ) + await read() + vi.setSystemTime(2_000) + await read() + expect(refreshIntervalForCandidate(candidate)).toBe(300_000) + discovery.mockClear() + hashing.mockClear() + inventory.mockClear() + metadata.mockClear() + reportVisiblePRRefreshCandidates([candidate], 1, 1) + for (let row = 0; row < population; row++) { + refreshIntervalForCandidate(candidate) + } + expect(discovery).not.toHaveBeenCalled() + expect(hashing).not.toHaveBeenCalled() + expect(inventory).not.toHaveBeenCalled() + expect(metadata).not.toHaveBeenCalled() + expect(refreshIntervalForCandidate({ ...candidate, fallbackPRNumber: 9 })).toBe(120_000) + const { bumpScopeGeneration, hostedReviewRepoScope } = + await import('../../../source-control/hosted-review-scope-generations') + bumpScopeGeneration(hostedReviewRepoScope(candidate.repoPath, 'local')) + expect(refreshIntervalForCandidate(candidate)).toBe(120_000) + vi.setSystemTime(3_000) + await read() + vi.setSystemTime(4_000) + await read() + expect(refreshIntervalForCandidate({ ...candidate, cachedFetchedAt: 4_000 })).toBe(300_000) + repository.ghAccount = { host: 'github.com', user: 'second' } + refreshPRPolicyContext() + expect(refreshIntervalForCandidate({ ...candidate, cachedFetchedAt: 4_000 })).toBe(120_000) + vi.setSystemTime(5_000) + await read() + vi.setSystemTime(6_000) + await read() + expect(refreshIntervalForCandidate({ ...candidate, cachedFetchedAt: 6_000 })).toBe(300_000) + } +) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-read-admission.ts b/src/main/github/pull-requests/refresh/pr-refresh-read-admission.ts new file mode 100644 index 00000000000..d6a0f23af2a --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-read-admission.ts @@ -0,0 +1,64 @@ +import type { GitHubPRRefreshAlias } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { PreparedPRBranchRead } from '../../client/lookup/pr-for-branch-outcome' +import { isBackground, isBudgetedBackground } from './pr-refresh-candidate-policy' +import type { PRRefreshEventPublisher } from './pr-refresh-event-publisher' +import { type PRRefreshPacing, usesActiveRefreshPacing } from './pr-refresh-pacing' +import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' +import type { PRRefreshQueueScheduler } from './pr-refresh-queue-scheduler' +import type { PRWatchJobRunner } from './pr-refresh-watch-jobs' + +type PRReadAdmissionOwners = { + queue: PRRefreshQueue + pacing: PRRefreshPacing + events: PRRefreshEventPublisher + scheduler: PRRefreshQueueScheduler + watchJobs: PRWatchJobRunner +} + +export function admitPreparedPRRead( + { queue, pacing, events, scheduler, watchJobs }: PRReadAdmissionOwners, + next: PRRefreshQueueEntry, + prepared: PreparedPRBranchRead, + aliases: GitHubPRRefreshAlias[], + requestSequence: number, + requestStartedAt: number, + joinedRead: boolean +): boolean { + if (!queue.ownsRequest(next.key, requestSequence) || !prepared.isCurrent()) { + next.hosted?.finish(null) + prepared.release() + if (!next.hosted && queue.ownsRequest(next.key, requestSequence)) { + events.broadcast( + { aliases, reason: next.reason, status: 'skipped', skippedReason: 'fresh' }, + requestSequence + ) + if (next.watch) { + watchJobs.skipped(next) + } else { + scheduler.completeWithoutOutcome( + next.key, + next.candidate, + aliases, + next.priority, + next.windowId, + next.foreground + ) + } + } + return false + } + if (scheduler.consumeGatedError(next, prepared, requestSequence, requestStartedAt)) { + prepared.release() + return false + } + if (!next.watch && isBackground(next.reason) && !joinedRead) { + if (next.bypassBackgroundBudget !== true && isBudgetedBackground(next.reason)) { + pacing.noteBackgroundStart(next) + watchJobs.noteBudgetedStart(next) + } + if (usesActiveRefreshPacing(next)) { + pacing.noteActiveStart(next) + } + } + return true +} diff --git a/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts b/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts index 13a29365156..3423968a04c 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts @@ -4,6 +4,8 @@ import type { } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { lookupBackoffDelayMs } from '../../../source-control/hosted-review-refresh-pacing' import { refreshIntervalForCandidate } from './pr-refresh-candidate-policy' +import type { PreparedPRBranchRead } from '../../client/lookup/pr-for-branch-outcome' +import type { PRRefreshQueue } from './pr-refresh-queue' export class PRRefreshRetryState { private readonly errorBackoff = new Map() @@ -50,4 +52,36 @@ export class PRRefreshRetryState { nextAutoRetryAt: cooldownUntil !== undefined ? Math.max(retryAt, cooldownUntil) : retryAt } } + + errorFollowUpAt( + key: string, + candidate: GitHubPRRefreshCandidate, + outcome: PRRefreshOutcome, + visible: boolean + ): number | undefined { + return outcome.kind === 'upstream-error' + ? (outcome.nextAutoRetryAt ?? + (visible ? this.nextVisibleErrorRetryAt(key, candidate) : undefined)) + : undefined + } + + settleProducerError( + outcome: PRRefreshOutcome, + key: string, + candidate: GitHubPRRefreshCandidate, + prepared: PreparedPRBranchRead, + queue: PRRefreshQueue, + ownsRequest: boolean + ): PRRefreshOutcome { + const retryAt = this.nextVisibleErrorRetryAt(key, candidate) + const result = this.withErrorSchedule(outcome, retryAt) + prepared.scheduleError(outcome, result) + if (ownsRequest) { + queue.protectBackgroundUntil( + key, + Math.max(retryAt, outcome.kind === 'upstream-error' ? (outcome.retryDisabledUntil ?? 0) : 0) + ) + } + return result + } } diff --git a/src/main/github/pull-requests/refresh/pr-refresh-watch-jobs.ts b/src/main/github/pull-requests/refresh/pr-refresh-watch-jobs.ts index 9551d0e28a0..66d6737f246 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-watch-jobs.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-watch-jobs.ts @@ -2,9 +2,11 @@ import type { GitHubPRRefreshCandidate, PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' -import type { PRInfo } from '../../../../shared/github/pull-requests/pull-request-types' +import { prChecksDone } from '../../../../shared/github/pull-requests/refresh/pr-quiet-refresh' +export { prChecksDone } from '../../../../shared/github/pull-requests/refresh/pr-quiet-refresh' import { reviewRefreshIntervalMs } from '../../../../shared/review-refresh-policy' import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' +import { isSelectedBudgetedPRRefresh } from './pr-refresh-pacing' import type { PRRefreshRetryState } from './pr-refresh-retry-state' export type PRWatchJob = NonNullable @@ -33,14 +35,6 @@ export function prWatchQueueKey(job: PRWatchJob): string { return job.headSha ? `sha-checks::${job.prKey}::${job.headSha}` : `watch::${job.prKey}` } -/** A complete read with nothing left running, or a complete read with no checks at all. A failed - * check beside a running one is not done, whatever the sidebar's failure-first summary says. */ -export function prChecksDone(pr: PRInfo): boolean { - return ( - pr.checksFinal === true || (pr.checksReadComplete === true && pr.checksSummary?.total === 0) - ) -} - /** A watch's next read: the background cadence, or none once the PR has settled. */ export function prWatchNextDueAt(outcome: PRRefreshOutcome): number | null { if (outcome.kind === 'upstream-error') { @@ -104,7 +98,7 @@ export class PRWatchJobRunner { noteBudgetedStart(entry: PRRefreshQueueEntry): void { // Selected list reads have their own reserved turn; preserve the watch/list alternation. - if (entry.reason !== 'visible' || entry.candidate.isSelected !== true) { + if (!isSelectedBudgetedPRRefresh(entry)) { this.lastBudgetedStartWasWatch = entry.watch !== undefined } } diff --git a/src/main/github/repositories/github-repository-identity.ts b/src/main/github/repositories/github-repository-identity.ts index 360bdd7d285..0e2f1c7640d 100644 --- a/src/main/github/repositories/github-repository-identity.ts +++ b/src/main/github/repositories/github-repository-identity.ts @@ -61,6 +61,15 @@ export async function withGitHubRepoExecution( return operations.run(context, operation) } +export function captureGitHubRepoExecution(): (operation: () => Promise) => Promise { + const context = operations.getStore() + return (operation) => (context ? operations.run(context, operation) : operation()) +} + +export function outsideGitHubRepoExecution(operation: () => T): T { + return operations.exit(operation) +} + export function githubRepoContext( repoPath: string, connectionId?: string | null, diff --git a/src/main/ipc/runtime-environments/requests/runtime-environment-call-queue.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-call-queue.ts index e8cb219318e..c75ac4540f9 100644 --- a/src/main/ipc/runtime-environments/requests/runtime-environment-call-queue.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-call-queue.ts @@ -1,12 +1,13 @@ import { RuntimeRpcCallQueuePool } from '../../../../shared/runtime-rpc-call-queue' -const runtimeCallQueuePool = new RuntimeRpcCallQueuePool() +export const runtimeCallQueuePool = new RuntimeRpcCallQueuePool() export function enqueueRuntimeCall( selector: string, method: string, run: () => Promise, - signal?: AbortSignal + signal?: AbortSignal, + params?: unknown ): Promise { - return runtimeCallQueuePool.enqueue(selector, method, run, 0, signal) + return runtimeCallQueuePool.enqueue(selector, method, run, 0, signal, params) } diff --git a/src/main/ipc/runtime-environments/requests/runtime-environment-subscription-routing.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-subscription-routing.ts new file mode 100644 index 00000000000..8096694a40c --- /dev/null +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-subscription-routing.ts @@ -0,0 +1,182 @@ +import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' +import { throwIfSignalAborted } from '../../../../shared/abort-signal-reason' +import { + type RuntimeEnvironmentSetupFailure, + runtimeEnvironmentSetupFailure +} from '../../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' +import { assertCrewSourceCurrent } from '../subscriptions/runtime-environment-subscription-setup' +import { getPreferredPairedRuntimeConnection } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' +import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { + resolveManagedRuntimeEnvironment, + type ManagedRuntimeCallPreparation +} from '../managed-orcad/runtime-environment-managed-tunnel' +import { recordRuntimeEnvironmentUsage } from '../../../../shared/remote-runtime/host-store/runtime-environment-usage-record' +import type * as Rpc from '../../../../shared/runtime-rpc-envelope' +import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hint' +import { decodeRuntimeEnvironmentSubscriptionEvents } from '../subscriptions/runtime-environment-subscription-events' +import { runtimeCallQueuePool } from './runtime-environment-call-queue' +import { isTimedPRRead } from '../../../../shared/runtime-rpc-call-queue' +import { enqueueRuntimeSubscription } from '../../../../shared/runtime-rpc-subscription-queue' +import { + shouldRouteSubscriptionBySupport, + subscribeSupportRoutedRuntimeEnvironment +} from './runtime-environment-support-routing' + +const DEFAULT_REMOTE_RUNTIME_TIMEOUT_MS = 15_000 + +export async function subscribeRuntimeEnvironment( + userDataPath: string, + selector: string, + method: string, + params: unknown, + timeoutMs: number | undefined, + rawCallbacks: { + onEvent: ( + payload: + | { type: 'response'; response: Rpc.RuntimeRpcResponse } + | { type: 'binary'; bytes: Uint8Array } + | { type: 'error'; code: string; message: string } + | { type: 'close' } + ) => void + onClose: () => void + }, + isCurrent: () => boolean = () => true, + signal?: AbortSignal, + preparation?: ManagedRuntimeCallPreparation, + crewAttempt?: { + assertCurrent: () => void + observeFailure: (failure: RuntimeEnvironmentSetupFailure) => void + } +): Promise { + let completeTimed = (): void => {} + const callbacks = { + onEvent: decodeRuntimeEnvironmentSubscriptionEvents( + method, + (event) => { + if (event.type !== 'binary') { + completeTimed() + } + rawCallbacks.onEvent(event) + }, + isCurrent + ), + onClose: () => { + completeTimed() + rawCallbacks.onClose() + } + } + crewAttempt?.assertCurrent() + const environment = crewAttempt + ? resolveEnvironment(userDataPath, selector) + : await resolveManagedRuntimeEnvironment(userDataPath, selector, preparation, method, signal) + crewAttempt?.assertCurrent() + if (crewAttempt) { + assertCrewSourceCurrent(environment) + } + const pairedConnection = getPreferredPairedRuntimeConnection(environment) + const effectiveTimeoutMs = timeoutMs ?? DEFAULT_REMOTE_RUNTIME_TIMEOUT_MS + let markedUsed = false + const markUsedOnce = (runtimeId: string): void => { + if (markedUsed || !isCurrent()) { + return + } + markedUsed = true + recordRuntimeEnvironmentUsage(userDataPath, environment.id, { runtimeId }) + } + const callbacksWithMarkUsed = { + onResponse: (response: Rpc.RuntimeRpcResponse) => { + if ( + crewAttempt && + response._meta?.runtimeId != null && + response._meta.runtimeId !== environment.runtimeId + ) { + throw new RemoteRuntimeClientError( + 'runtime_environment_changed', + 'Runtime environment identity changed; refresh and try again' + ) + } + if (response.ok === true) { + markUsedOnce(response._meta.runtimeId) + } + callbacks.onEvent({ type: 'response' as const, response }) + }, + onBinary: (bytes: Uint8Array) => + callbacks.onEvent({ type: 'binary' as const, bytes }), + onError: (error: { code: string; message: string }) => + callbacks.onEvent({ + type: 'error' as const, + code: error.code, + message: withRuntimeUnreachableHint(environment, error.message, pairedConnection.endpoint) + }), + onClose: () => { + callbacks.onEvent({ type: 'close' as const }) + callbacks.onClose() + } + } + // Initial connection failures reject; midstream errors use onError above. + const connect = async (): Promise => { + try { + if (shouldRouteSubscriptionBySupport(method)) { + return await subscribeSupportRoutedRuntimeEnvironment({ + userDataPath, + environment, + method, + params, + timeoutMs: effectiveTimeoutMs, + callbacks, + isCurrent, + signal + }) + } + const subscription = await subscribeRemoteRuntimeTransport( + pairedConnection, + method, + params, + effectiveTimeoutMs, + callbacksWithMarkUsed, + { clientCapabilities: ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, signal } + ) + if (crewAttempt) { + try { + throwIfSignalAborted(signal) + crewAttempt.assertCurrent() + assertCrewSourceCurrent(environment) + } catch (error) { + subscription.close() + throw error + } + } + return subscription + } catch (error) { + if (error instanceof Error && error.name !== 'AbortError') { + error.message = withRuntimeUnreachableHint( + environment, + error.message, + pairedConnection.endpoint + ) + } + crewAttempt?.observeFailure(runtimeEnvironmentSetupFailure(error, 'subscription')) + throw error + } + } + if (!isTimedPRRead(method, params)) { + return connect() + } + const subscription = await enqueueRuntimeSubscription( + runtimeCallQueuePool, + environment.id, + method, + params, + (complete) => { + completeTimed = complete + return connect() + }, + (handle) => handle.close(), + signal + ) + return { ...subscription, close: () => completeTimed() } +} diff --git a/src/main/ipc/runtime-environments/requests/runtime-environment-transport-routing.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-transport-routing.ts index 8190d290334..bfea8ea7b1f 100644 --- a/src/main/ipc/runtime-environments/requests/runtime-environment-transport-routing.ts +++ b/src/main/ipc/runtime-environments/requests/runtime-environment-transport-routing.ts @@ -1,10 +1,3 @@ -import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' -import { throwIfSignalAborted } from '../../../../shared/abort-signal-reason' -import { - type RuntimeEnvironmentSetupFailure, - runtimeEnvironmentSetupFailure -} from '../../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup' -import { assertCrewSourceCurrent } from '../subscriptions/runtime-environment-subscription-setup' import { getRuntimeEnvironmentStatus } from '../status/runtime-environment-status-probe' import { getPreferredPairedRuntimeConnection } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' @@ -12,16 +5,12 @@ import { resolveEnvironment } from '../../../../shared/remote-runtime/host-store import { prepareFencedRuntimeRequest } from './runtime-environment-request-preparation' import { requireWslHostWithoutStart, - resolveManagedRuntimeEnvironment, type ManagedRuntimeCallPreparation } from '../managed-orcad/runtime-environment-managed-tunnel' import { recordRuntimeEnvironmentUsage } from '../../../../shared/remote-runtime/host-store/runtime-environment-usage-record' import type * as Rpc from '../../../../shared/runtime-rpc-envelope' import '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' -import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' import { withRuntimeUnreachableHint } from './runtime-environment-unreachable-hint' -import { decodeRuntimeEnvironmentSubscriptionEvents } from '../subscriptions/runtime-environment-subscription-events' import { enqueueRuntimeCall } from './runtime-environment-call-queue' import { sendRemoteRuntimeConnectionRequestAbortable, @@ -30,9 +19,7 @@ import { import { runtimeEnvironmentRevisionFailure } from './runtime-environment-revision-guard' import { executeSupportRoutedCall, - shouldRouteCallBySupport, - shouldRouteSubscriptionBySupport, - subscribeSupportRoutedRuntimeEnvironment + shouldRouteCallBySupport } from './runtime-environment-support-routing' import { shouldUseSharedControlEnvelope } from '../connections/runtime-environment-shared-control-envelope' import { sendEnvelopedOneShotCall } from './runtime-environment-runtime-pinned-send' @@ -158,7 +145,8 @@ export async function callRuntimeEnvironment( markEnvironmentUsedFromResponse(userDataPath, currentEnvironment.id, response) return response }, - options?.signal + options?.signal, + params ) } catch (error) { if (error instanceof Error && error.name !== 'AbortError') { @@ -168,127 +156,7 @@ export async function callRuntimeEnvironment( } } -export async function subscribeRuntimeEnvironment( - userDataPath: string, - selector: string, - method: string, - params: unknown, - timeoutMs: number | undefined, - rawCallbacks: { - onEvent: ( - payload: - | { type: 'response'; response: Rpc.RuntimeRpcResponse } - | { type: 'binary'; bytes: Uint8Array } - | { type: 'error'; code: string; message: string } - | { type: 'close' } - ) => void - onClose: () => void - }, - isCurrent: () => boolean = () => true, - signal?: AbortSignal, - preparation?: ManagedRuntimeCallPreparation, - crewAttempt?: { - assertCurrent: () => void - observeFailure: (failure: RuntimeEnvironmentSetupFailure) => void - } -): Promise { - const callbacks = { - ...rawCallbacks, - onEvent: decodeRuntimeEnvironmentSubscriptionEvents(method, rawCallbacks.onEvent, isCurrent) - } - crewAttempt?.assertCurrent() - const environment = crewAttempt - ? resolveEnvironment(userDataPath, selector) - : await resolveManagedRuntimeEnvironment(userDataPath, selector, preparation, method, signal) - crewAttempt?.assertCurrent() - if (crewAttempt) { - assertCrewSourceCurrent(environment) - } - const pairedConnection = getPreferredPairedRuntimeConnection(environment) - const effectiveTimeoutMs = timeoutMs ?? DEFAULT_REMOTE_RUNTIME_TIMEOUT_MS - let markedUsed = false - const markUsedOnce = (runtimeId: string): void => { - if (markedUsed || !isCurrent()) { - return - } - markedUsed = true - recordRuntimeEnvironmentUsage(userDataPath, environment.id, { runtimeId }) - } - const callbacksWithMarkUsed = { - onResponse: (response: Rpc.RuntimeRpcResponse) => { - if ( - crewAttempt && - response._meta?.runtimeId != null && - response._meta.runtimeId !== environment.runtimeId - ) { - throw new RemoteRuntimeClientError( - 'runtime_environment_changed', - 'Runtime environment identity changed; refresh and try again' - ) - } - if (response.ok === true) { - markUsedOnce(response._meta.runtimeId) - } - callbacks.onEvent({ type: 'response' as const, response }) - }, - onBinary: (bytes: Uint8Array) => - callbacks.onEvent({ type: 'binary' as const, bytes }), - onError: (error: { code: string; message: string }) => - callbacks.onEvent({ - type: 'error' as const, - code: error.code, - message: withRuntimeUnreachableHint(environment, error.message, pairedConnection.endpoint) - }), - onClose: () => { - callbacks.onEvent({ type: 'close' as const }) - callbacks.onClose() - } - } - // Initial connection failures reject; midstream errors use onError above. - try { - if (shouldRouteSubscriptionBySupport(method)) { - return await subscribeSupportRoutedRuntimeEnvironment({ - userDataPath, - environment, - method, - params, - timeoutMs: effectiveTimeoutMs, - callbacks, - isCurrent, - signal - }) - } - const subscription = await subscribeRemoteRuntimeTransport( - pairedConnection, - method, - params, - effectiveTimeoutMs, - callbacksWithMarkUsed, - { clientCapabilities: ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, signal } - ) - if (crewAttempt) { - try { - throwIfSignalAborted(signal) - crewAttempt.assertCurrent() - assertCrewSourceCurrent(environment) - } catch (error) { - subscription.close() - throw error - } - } - return subscription - } catch (error) { - if (error instanceof Error && error.name !== 'AbortError') { - error.message = withRuntimeUnreachableHint( - environment, - error.message, - pairedConnection.endpoint - ) - } - crewAttempt?.observeFailure(runtimeEnvironmentSetupFailure(error, 'subscription')) - throw error - } -} +export { subscribeRuntimeEnvironment } from './runtime-environment-subscription-routing' function markEnvironmentUsedFromResponse( userDataPath: string, diff --git a/src/main/ipc/runtime-environments/runtime-environment-call-queue.test.ts b/src/main/ipc/runtime-environments/runtime-environment-call-queue.test.ts new file mode 100644 index 00000000000..8e1edc94148 --- /dev/null +++ b/src/main/ipc/runtime-environments/runtime-environment-call-queue.test.ts @@ -0,0 +1,19 @@ +import { expect, it } from 'vitest' +import { enqueueRuntimeCall } from './requests/runtime-environment-call-queue' + +it('passes timed intent to the desktop queue without holding status or manual PR reads', async () => { + const release = Promise.withResolvers() + const waiting = [0, 1].map(() => + enqueueRuntimeCall('host', 'github.prForBranch', () => release.promise, undefined, { + reason: 'swr' + }) + ) + await expect( + enqueueRuntimeCall('host', 'github.prForBranch', async () => 'current', undefined, { + reason: 'manual' + }) + ).resolves.toBe('current') + await expect(enqueueRuntimeCall('host', 'git.status', async () => 'clean')).resolves.toBe('clean') + release.resolve() + await Promise.all(waiting) +}) diff --git a/src/main/ipc/runtime-environments/subscriptions/runtime-environments-subscription-lifecycle.test.ts b/src/main/ipc/runtime-environments/subscriptions/runtime-environments-subscription-lifecycle.test.ts index 9f6a0fcbc9c..b56261ab229 100644 --- a/src/main/ipc/runtime-environments/subscriptions/runtime-environments-subscription-lifecycle.test.ts +++ b/src/main/ipc/runtime-environments/subscriptions/runtime-environments-subscription-lifecycle.test.ts @@ -118,6 +118,70 @@ describe('registerRuntimeEnvironmentHandlers', () => { rmSync(userDataPath, { recursive: true, force: true }) }) + it('holds timed signal-route admission after setup while foreground and status subscriptions remain runnable', async () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these handlers use only the fixture settings methods. + registerRuntimeEnvironmentHandlers(store as never) + const finish: (() => void)[] = [] + subscribeRemoteRuntimeRequestMock.mockImplementation( + async (_connection, _method, _params, _timeout, callbacks) => { + finish.push(() => + callbacks.onResponse({ id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'runtime' } }) + ) + return { requestId: `request-${finish.length}`, close: vi.fn(), sendBinary: vi.fn() } + } + ) + const add = handler<{ name: string; pairingCode: string }, unknown>( + 'runtimeEnvironments:addFromPairingCode' + ) + await add(null, { name: 'desk', pairingCode: pairingCode() }) + const sender = { + id: 1, + isDestroyed: () => false, + send: vi.fn(), + on: vi.fn(), + removeListener: vi.fn() + } + const subscribe = handler< + { + selector: string + method: string + params: { reason?: string; selected?: boolean } + subscriptionId: string + }, + { subscriptionId: string; requestId: string } + >('runtimeEnvironments:subscribe') + const start = (subscriptionId: string, reason: string, method = 'github.prForBranch') => + subscribe( + { sender }, + { selector: 'desk', subscriptionId, method, params: { reason, selected: true } } + ) + await start('timer-1', 'swr') + expect(subscribeRemoteRuntimeRequestMock.mock.calls[0][2]).toMatchObject({ + reason: 'swr', + selected: true + }) + await start('timer-2', 'swr') + const third = start('timer-3', 'swr') + const cancelled = expect(third).rejects.toThrow() + await start('manual', 'manual') + await start('status', '', 'git.status') + await start('review', '', 'hostedReview.forBranch') + expect(finish).toHaveLength(5) + const cancel = handler<{ subscriptionId: string }, unknown>('runtimeEnvironments:unsubscribe') + await cancel({ sender }, { subscriptionId: 'timer-3' }) + await cancelled + const fourth = start('timer-4', 'swr') + finish[0]() + await fourth + expect(finish).toHaveLength(6) + const unsubscribe = handler<{ subscriptionId: string }, unknown>( + 'runtimeEnvironments:unsubscribe' + ) + for (const subscriptionId of ['timer-1', 'timer-2', 'timer-4', 'manual', 'status', 'review']) { + await unsubscribe({ sender }, { subscriptionId }) + } + }) + it('rejects cross-window streaming subscription control', async () => { registerRuntimeEnvironmentHandlers(store as never) const close = vi.fn() diff --git a/src/main/ipc/source-control/github-pr-refresh-handlers.ts b/src/main/ipc/source-control/github-pr-refresh-handlers.ts index 6fd54453d72..b174d20d914 100644 --- a/src/main/ipc/source-control/github-pr-refresh-handlers.ts +++ b/src/main/ipc/source-control/github-pr-refresh-handlers.ts @@ -4,7 +4,7 @@ import type { GitHubPRRefreshCandidate, GitHubPRRefreshEnqueueResult, GitHubPRRefreshReason, - PRRefreshOutcome + PRSnapshotReply } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { Repo } from '../../../shared/repo-types' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' @@ -44,8 +44,8 @@ export function registerGitHubPRRefreshHandlers( ): void { // The windows these handlers serve are the renderers the coordinator reports to. setPRRefreshRendererPort(electronPRRefreshRenderer) - function recordPRIfNeeded(repo: Repo, outcome: PRRefreshOutcome): void { - if (outcome.kind === 'found' && !stats.hasCountedPR(outcome.pr.url)) { + function recordPRIfNeeded(repo: Repo, outcome: PRSnapshotReply): void { + if ('kind' in outcome && outcome.kind === 'found' && !stats.hasCountedPR(outcome.pr.url)) { stats.record({ type: 'pr_created', at: Date.now(), diff --git a/src/main/runtime/integrations/reviews/hosted-pr-producer-settlement-test-cases.ts b/src/main/runtime/integrations/reviews/hosted-pr-producer-settlement-test-cases.ts new file mode 100644 index 00000000000..420d5caeb56 --- /dev/null +++ b/src/main/runtime/integrations/reviews/hosted-pr-producer-settlement-test-cases.ts @@ -0,0 +1,235 @@ +import { it, expect, vi, type Mock } from 'vitest' +import { makeCandidate } from '../../../github/pull-requests/refresh/pr-refresh-coordinator-test-harness' +import type { + PRRefreshOutcome, + PRSnapshotReply +} from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' + +export function registerPRProducerSettlementTests({ + read, + mocks, + found +}: { + read: ( + branch: string, + reason?: 'active' | 'visible' | 'swr' | 'manual', + head?: string + ) => Promise + mocks: { resolve: Mock; gate: Mock } + found: () => PRRefreshOutcome +}): void { + it('retires a superseded producer error without waiting for or scheduling over fresh work', async () => { + const timedProvider = Promise.withResolvers() + const freshProvider = Promise.withResolvers() + mocks.resolve + .mockReturnValueOnce(timedProvider.promise) + .mockReturnValueOnce(freshProvider.promise) + const timed = read('superseded-error') + await vi.advanceTimersByTimeAsync(0) + const joined = read('superseded-error') + await vi.advanceTimersByTimeAsync(0) + const fresh = read('superseded-error', 'active') + await vi.advanceTimersByTimeAsync(0) + timedProvider.reject(new Error('obsolete network error')) + expect(await Promise.all([timed, joined])).toEqual([ + { revalidation: { invalidated: true, retryAfterMs: 10_000 } }, + { revalidation: { invalidated: true, retryAfterMs: 10_000 } } + ]) + freshProvider.resolve(found()) + const current = await fresh + expect(await read('superseded-error')).toEqual(current) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + }) + + it('delivers the producer error schedule to cold pending consumers before ordinary retry', async () => { + const { addPRRefreshOutcomeObserver } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const observe = vi.fn() + const remove = addPRRefreshOutcomeObserver(observe) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const cold = read('cold-error') + await vi.advanceTimersByTimeAsync(0) + const joined = read('cold-error') + await vi.advanceTimersByTimeAsync(0) + provider.reject(new Error('network offline')) + const results = await Promise.all([cold, joined]) + expect(results[0]).toMatchObject({ + kind: 'upstream-error', + nextAutoRetryAt: expect.any(Number) + }) + expect(results[1]).toEqual(results[0]) + expect(await read('cold-error')).toEqual(results[0]) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + expect(observe).toHaveBeenCalledTimes(1) + remove() + }) + + it.each(['queued', 'immediate'] as const)( + 'keeps the %s producer policy when another active consumer joins the same task', + async (origin) => { + const { + addPRRefreshOutcomeObserver, + reportVisiblePRRefreshCandidates, + enqueuePRRefresh, + refreshPRNow + } = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const { setPRRefreshRendererPort } = + await import('../../../github/pull-requests/refresh/pr-refresh-renderer-port') + setPRRefreshRendererPort({ isRendererOpen: () => true, sendToTrustedUI: () => {} }) + const candidate = makeCandidate({ + cacheKey: '/repo::joined-active', + repoId: 'repo', + branch: 'joined-active', + currentHeadOid: 'head-a', + isSelected: true + }) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const observe = vi.fn() + const remove = addPRRefreshOutcomeObserver(observe) + try { + mocks.gate.mockResolvedValue(Date.now() + 60_000) + reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).not.toHaveBeenCalled() + mocks.gate.mockResolvedValue(null) + let producer: Promise | undefined + if (origin === 'queued') { + enqueuePRRefresh(candidate, 'active', 80) + } else { + producer = refreshPRNow(candidate, 'active') + } + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + const sibling = refreshPRNow(candidate, 'active') + await vi.advanceTimersByTimeAsync(0) + const hosted = read('joined-active') + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + provider.reject(new Error('network offline')) + const result = await hosted + expect(result).toMatchObject({ + kind: 'upstream-error', + nextAutoRetryAt: expect.any(Number) + }) + expect(await sibling).toEqual(result) + if (producer) { + expect(await producer).toEqual(result) + } + expect(await read('joined-active')).toEqual(result) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + expect(observe).toHaveBeenCalledTimes(1) + } finally { + remove() + setPRRefreshRendererPort(null) + } + } + ) + + it.each([false, true])( + 'observes one joined success while fencing a genuine successor (userRefresh=%s)', + async (userRefresh) => { + const { addPRRefreshOutcomeObserver, refreshPRNow } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const candidate = makeCandidate({ + cacheKey: '/repo::joined-success', + repoId: 'repo', + branch: 'joined-success', + currentHeadOid: 'head-a' + }) + const first = Promise.withResolvers() + const successor = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(first.promise).mockReturnValueOnce(successor.promise) + const observe = vi.fn() + const remove = addPRRefreshOutcomeObserver(observe) + try { + const producer = refreshPRNow(candidate, 'active') + await vi.advanceTimersByTimeAsync(0) + const sibling = refreshPRNow(candidate, 'active', { userRefresh }) + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(userRefresh ? 2 : 1) + const joined = read('joined-success') + await vi.advanceTimersByTimeAsync(0) + first.resolve(found()) + await producer + if (userRefresh) { + expect(observe).not.toHaveBeenCalled() + successor.resolve(found()) + } + const result = await sibling + expect(await joined).toEqual(result) + expect(result).toMatchObject({ kind: 'found' }) + expect(observe).toHaveBeenCalledTimes(1) + } finally { + remove() + } + } + ) + + it.each(['queued', 'immediate', 'headless-immediate', 'foreground'] as const)( + 'settles the %s producer before its hosted pending error consumer', + async (origin) => { + const { addPRRefreshOutcomeObserver, reportVisiblePRRefreshCandidates, refreshPRNow } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const { setPRRefreshRendererPort } = + await import('../../../github/pull-requests/refresh/pr-refresh-renderer-port') + if (origin === 'queued' || origin === 'immediate') { + setPRRefreshRendererPort({ isRendererOpen: () => true, sendToTrustedUI: () => {} }) + } + const immediate = origin === 'immediate' || origin === 'headless-immediate' + const candidate = makeCandidate({ + cacheKey: '/repo::origin-error', + repoId: 'repo', + branch: 'origin-error', + currentHeadOid: 'head-a', + isSelected: true + }) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const observe = vi.fn() + const remove = addPRRefreshOutcomeObserver(observe) + try { + let producer: Promise | undefined + if (origin === 'foreground') { + producer = read('origin-error', 'active') + } else { + if (immediate) { + mocks.gate.mockResolvedValue(Date.now() + 60_000) + } + reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + if (immediate) { + expect(mocks.resolve).not.toHaveBeenCalled() + mocks.gate.mockResolvedValue(null) + producer = refreshPRNow(candidate, 'manual') + } + } + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + const joined = read('origin-error') + await vi.advanceTimersByTimeAsync(0) + provider.reject(new Error('network offline')) + const result = await joined + expect(result).toMatchObject({ kind: 'upstream-error' }) + if (!('kind' in result) || result.kind !== 'upstream-error') { + throw new Error('expected the actual provider failure') + } + if (origin === 'foreground' || origin === 'headless-immediate') { + expect(result.nextAutoRetryAt).toBeUndefined() + } else { + expect(result.nextAutoRetryAt).toEqual(expect.any(Number)) + } + if (producer) { + expect(await producer).toEqual(result) + } + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + expect(observe).toHaveBeenCalledTimes(1) + } finally { + remove() + setPRRefreshRendererPort(null) + } + } + ) +} diff --git a/src/main/runtime/integrations/reviews/hosted-pr-selected-demand.test.ts b/src/main/runtime/integrations/reviews/hosted-pr-selected-demand.test.ts new file mode 100644 index 00000000000..d241badea7a --- /dev/null +++ b/src/main/runtime/integrations/reviews/hosted-pr-selected-demand.test.ts @@ -0,0 +1,157 @@ +import { expect, it, vi } from 'vitest' +import { commands, found, mocks, read, rpcRead } from './runtime-hosted-pr-snapshot-test-harness' +import { PrForBranch } from '../../../../shared/rpc-contract/github/github-pull-request-params' + +it('promotes a shared selected demand without losing other rows or renewing its attempt', async () => { + const branches = ['ordinary-a', 'selected-a', 'selected-b'] + await Promise.all(branches.map((branch) => read(branch, 'active'))) + await vi.advanceTimersByTimeAsync(60_000) + // ast-grep-ignore: test-no-wall-clock -- The imported runtime fixture installs the fake clock. + const gate = Date.now() + 60_000 + mocks.gate.mockResolvedValue(gate) + const starts: string[] = [] + mocks.resolve.mockImplementation(async ({ branchName }) => { + starts.push(branchName) + return found() + }) + const demand = (branch: string, selected = false) => + rpcRead({ + repo: 'repo', + branch, + currentHeadOid: 'head-a', + reason: 'swr', + acceptRevalidationOnly: true, + selected + }) + const waiting = branches.map((branch) => demand(branch)) + await vi.advanceTimersByTimeAsync(25_000) + await Promise.all(waiting) + expect(starts).toEqual([]) + await demand('selected-a', true) + await demand('selected-b', true) + await demand('selected-a', false) + const { schedulePRWatchRead } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const { makeCandidate } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator-test-harness') + schedulePRWatchRead( + { prKey: 'github.com/acme/repo#12' }, + makeCandidate({ + repoId: 'repo', + branch: 'watched', + cacheKey: '/repo::watched', + currentHeadOid: 'head-a' + }), + gate + ) + mocks.gate.mockResolvedValue(null) + await vi.advanceTimersByTimeAsync(65_000) + expect(starts).toEqual(['selected-a', 'ordinary-a', 'selected-b', 'watched']) + + // A selected request stays finite even when its only waiter detaches. + await read('expires', 'active') + await vi.advanceTimersByTimeAsync(60_000) + // ast-grep-ignore: test-no-wall-clock -- The imported runtime fixture installs the fake clock. + mocks.gate.mockResolvedValue(Date.now() + 7 * 60_000) + const abort = new AbortController() + const expires = commands.getRepoPRForBranch( + 'repo', + 'expires', + null, + null, + false, + 'head-a', + 'swr', + false, + undefined, + abort.signal, + true, + true + ) + const cancelled = expect(expires).rejects.toThrow('cancelled') + await vi.advanceTimersByTimeAsync(0) + abort.abort() + await cancelled + await vi.advanceTimersByTimeAsync(4 * 60_000) + await demand('expires', true) + const beforeExpiry = starts.length + await vi.advanceTimersByTimeAsync(4 * 60_000) + expect(starts.length).toBe(beforeExpiry) +}) + +it('keeps selected preference optional for old snapshot request parsers', () => { + const params = { repo: 'repo', branch: 'main', reason: 'swr', selected: true } + expect(PrForBranch.parse(params)).toMatchObject({ selected: true }) + expect(PrForBranch.omit({ selected: true }).parse(params)).toEqual({ + repo: 'repo', + branch: 'main', + reason: 'swr' + }) + expect(PrForBranch.parse({ repo: 'repo', branch: 'main' })).toEqual({ + repo: 'repo', + branch: 'main' + }) +}) + +it('keeps a selected join during an awaited quota probe and its later paused admission', async () => { + await read('quiet-selected', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const confirmation = read('quiet-selected') + await vi.advanceTimersByTimeAsync(0) + await confirmation + const branches = ['ordinary-a', 'ordinary-b', 'ordinary-c'] + await Promise.all(branches.map((branch) => read(branch, 'active'))) + await vi.advanceTimersByTimeAsync(300_000) + const quotaProbe = Promise.withResolvers() + // ast-grep-ignore: test-no-wall-clock -- The imported runtime fixture installs the fake clock. + const resetAt = Date.now() + 60_000 + mocks.gate.mockResolvedValue(resetAt).mockReturnValueOnce(quotaProbe.promise) + const starts: string[] = [] + mocks.resolve.mockImplementation(async ({ branchName }) => { + starts.push(branchName) + return found() + }) + const demand = (branch: string, selected = false) => + rpcRead({ + repo: 'repo', + branch, + currentHeadOid: 'head-a', + reason: 'swr', + acceptRevalidationOnly: true, + selected + }) + const first = demand('quiet-selected') + await vi.advanceTimersByTimeAsync(0) + expect(mocks.gate).toHaveBeenCalled() + expect(starts).toEqual([]) + const joined = demand('quiet-selected', true) + const ordinary = branches.map((branch) => demand(branch)) + await vi.advanceTimersByTimeAsync(0) + quotaProbe.resolve(resetAt) + await vi.advanceTimersByTimeAsync(25_000) + await Promise.all([first, joined, ...ordinary]) + mocks.gate.mockResolvedValue(null) + await vi.advanceTimersByTimeAsync(65_000) + expect(starts).toEqual(['quiet-selected', 'ordinary-a', 'ordinary-b', 'ordinary-c']) +}) + +it('uses selected demand only for admission priority, preserving the shared retry interval', async () => { + await read('retry-policy', 'active') + await vi.advanceTimersByTimeAsync(60_000) + mocks.resolve.mockRejectedValueOnce(new Error('offline')) + // ast-grep-ignore: test-no-wall-clock -- The imported runtime fixture installs the fake clock. + const requestedAt = Date.now() + const response = rpcRead({ + repo: 'repo', + branch: 'retry-policy', + currentHeadOid: 'head-a', + reason: 'swr', + acceptRevalidationOnly: true, + selected: true + }) + await vi.advanceTimersByTimeAsync(0) + expect(await response).toMatchObject({ + kind: 'upstream-error', + nextAutoRetryAt: requestedAt + 120_000 + }) +}) diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-pr-deadlines.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-pr-deadlines.test.ts new file mode 100644 index 00000000000..a12fd68ed62 --- /dev/null +++ b/src/main/runtime/integrations/reviews/runtime-hosted-pr-deadlines.test.ts @@ -0,0 +1,142 @@ +import { expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { makeCandidate } from '../../../github/pull-requests/refresh/pr-refresh-coordinator-test-harness' +import { fixture, found, mocks, read, rpcRead } from './runtime-hosted-pr-snapshot-test-harness' + +it('delivers post-push data from its fresh producer while an older timed producer is pending', async () => { + const coordinator = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const old = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(old.promise) + const producer = read('pushed', 'swr') + await vi.advanceTimersByTimeAsync(0) + const delivered: PRRefreshOutcome[] = [] + const remove = coordinator.addPRRefreshOutcomeObserver((_candidate, outcome) => + delivered.push(outcome) + ) + try { + fixture.title = 'after push' + coordinator.enqueuePRRefresh( + makeCandidate({ branch: 'pushed', cacheKey: '/repo::pushed', currentHeadOid: 'head-a' }), + 'post-push' + ) + await vi.advanceTimersByTimeAsync(2_500) + expect(delivered).toContainEqual({ + kind: 'found', + fetchedAt: 3_500, + pr: expect.objectContaining({ title: 'after push' }) + }) + old.resolve(found()) + await producer + } finally { + remove() + } +}) + +it('delivers an unrelated row without a spacing delay after joining an existing producer', async () => { + const coordinator = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const result = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(result.promise) + const producer = read('joining', 'active') + await vi.advanceTimersByTimeAsync(0) + const delivered: { branch: string; outcome: PRRefreshOutcome }[] = [] + const remove = coordinator.addPRRefreshOutcomeObserver((candidate, outcome) => { + delivered.push({ branch: candidate.branch, outcome }) + }) + try { + for (const branch of ['joining', 'unrelated']) { + coordinator.enqueuePRRefresh( + makeCandidate({ branch, cacheKey: `/repo::${branch}`, currentHeadOid: 'head-a' }), + 'swr' + ) + } + await vi.advanceTimersByTimeAsync(0) + fixture.title = 'shared answer' + result.resolve(found()) + await producer + await vi.advanceTimersByTimeAsync(0) + expect(delivered).toContainEqual({ + branch: 'unrelated', + outcome: { + kind: 'found', + fetchedAt: 1_000, + pr: expect.objectContaining({ title: 'shared answer' }) + } + }) + } finally { + remove() + } +}) + +it.each([false, true])( + 'delivers post-push data while another row waits for a later rate-limit reset (clock jump: %s)', + async (clockJump) => { + const coordinator = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const delivered: PRRefreshOutcome[] = [] + const remove = coordinator.addPRRefreshOutcomeObserver((_candidate, outcome) => + delivered.push(outcome) + ) + const candidate = (branch: string) => + makeCandidate({ + branch, + cacheKey: `/repo::${branch}`, + currentHeadOid: 'head-a' + }) + try { + fixture.title = 'after push' + mocks.gate.mockImplementation(async (row) => (row.branch === 'later' ? 61_000 : null)) + if (clockJump) { + await coordinator.refreshPRNow(candidate('later')) + vi.setSystemTime(301_000) + } + coordinator.enqueuePRRefresh(candidate('pushed'), 'post-push') + await vi.advanceTimersByTimeAsync(0) + if (!clockJump) { + await coordinator.refreshPRNow(candidate('later')) + } + await vi.advanceTimersByTimeAsync(2_500) + expect(delivered).toContainEqual({ + kind: 'found', + fetchedAt: clockJump ? 303_500 : 3_500, + pr: expect.objectContaining({ title: 'after push' }) + }) + } finally { + remove() + } + } +) + +it.each(['deadline', 'abort'] as const)( + 'detaches an automatic cold-read waiter on %s while its producer completes for another client', + async (end) => { + const result = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(result.promise) + const producer = read('pending', 'active') + await vi.advanceTimersByTimeAsync(0) + const controller = new AbortController() + const joined = rpcRead( + { + repo: 'repo', + branch: 'pending', + currentHeadOid: 'head-a', + reason: 'swr', + acceptRevalidationOnly: true + }, + controller.signal + ) + const abandoned = + end === 'abort' + ? expect(joined).rejects.toThrow('cancelled') + : expect(joined).resolves.toMatchObject({ revalidation: { retryAfterMs: 10_000 } }) + await vi.advanceTimersByTimeAsync(0) + if (end === 'abort') { + controller.abort() + } else { + await vi.advanceTimersByTimeAsync(25_000) + } + await abandoned + fixture.title = 'producer completed' + result.resolve(found()) + await expect(producer).resolves.toMatchObject({ pr: { title: 'producer completed' } }) + await expect(read('pending')).resolves.toMatchObject({ pr: { title: 'producer completed' } }) + } +) diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-pr-owner-delivery.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-pr-owner-delivery.test.ts new file mode 100644 index 00000000000..244cfff8ffd --- /dev/null +++ b/src/main/runtime/integrations/reviews/runtime-hosted-pr-owner-delivery.test.ts @@ -0,0 +1,105 @@ +import { expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { commands, fixture, found, mocks, read } from './runtime-hosted-pr-snapshot-test-harness' + +it('returns completed legacy cold and pending replies without fallback IO or a successor wait', async () => { + const { preparePRBranchRead } = + await import('../../../github/client/lookup/pr-for-branch-outcome') + const { addPRRefreshOutcomeObserver } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const releases: (() => void)[] = [] + const observe = vi.fn() + const remove = addPRRefreshOutcomeObserver(observe) + try { + for (let index = 0; index < 256; index++) { + const branch = `protected-${index}` + await read(branch, 'active') + const prepared = await preparePRBranchRead('/repo', branch, null, null, null, { + currentHeadOid: 'head-a' + }) + releases.push(prepared.hold()) + } + mocks.resolve.mockClear() + observe.mockClear() + for (const freshFirst of [true, false]) { + const branch = freshFirst ? 'legacy-finished-successor' : 'legacy-running-successor' + const old = Promise.withResolvers() + const fresh = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) + const legacy = () => + commands.getRepoPRForBranch('repo', branch, null, null, false, 'head-a', 'swr') + const first = legacy() + await vi.advanceTimersByTimeAsync(0) + const sibling = legacy() + await vi.advanceTimersByTimeAsync(0) + const foreground = read(branch, 'active') + await vi.advanceTimersByTimeAsync(0) + const delivered = vi.fn() + const completed = Promise.all([first, sibling]).then(delivered) + try { + expect(await read(branch)).toEqual({ + revalidation: { invalidated: true, retryAfterMs: 10_000 } + }) + if (freshFirst) { + fresh.resolve(found()) + await foreground + } + const own: PRRefreshOutcome = { kind: 'no-pr', fetchedAt: 1_000 } + old.resolve(own) + await vi.advanceTimersByTimeAsync(0) + expect(delivered).toHaveBeenCalledWith([own, own]) + } finally { + old.resolve({ kind: 'no-pr', fetchedAt: 1_000 }) + fresh.resolve(found()) + await Promise.all([completed, foreground]) + } + } + expect(mocks.resolve).toHaveBeenCalledTimes(4) + expect(observe).toHaveBeenCalledTimes(2) + } finally { + for (const release of releases) { + release() + } + remove() + } + fixture.title = 'legitimate automatic read' + expect(await read('after-capacity')).toMatchObject({ pr: { title: 'legitimate automatic read' } }) +}) + +it.each(['generation-cold', 'account-cold', 'account-direct'] as const)( + 'fences %s settlement before obsolete error policy and observation', + async (change) => { + const { addPRRefreshOutcomeObserver, _getPRRefreshErrorBackoffCountForTests } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const { invalidateHostedReviewBranchCache } = + await import('../../../source-control/hosted-review-branch-cache') + const observe = vi.fn() + const remove = addPRRefreshOutcomeObserver(observe) + const provider = Promise.withResolvers() + mocks.account.mockReturnValue({ ghAccount: { host: 'github.com', user: 'before' } }) + mocks.resolve.mockReturnValueOnce(provider.promise) + const pending = read('scope', change === 'account-direct' ? 'active' : 'swr') + await vi.advanceTimersByTimeAsync(0) + if (change === 'generation-cold') { + invalidateHostedReviewBranchCache('/repo', 'local') + } else { + mocks.account.mockReturnValue({ ghAccount: { host: 'github.com', user: 'after' } }) + } + try { + provider.reject(new Error('network offline')) + const result = await pending + if (change === 'account-direct') { + expect(result).toMatchObject({ kind: 'upstream-error' }) + } else { + expect(result).toEqual({ revalidation: { invalidated: true, retryAfterMs: 10_000 } }) + } + expect(observe).not.toHaveBeenCalled() + expect(_getPRRefreshErrorBackoffCountForTests()).toBe(0) + fixture.title = 'current scope' + expect(await read('scope', 'active')).toMatchObject({ pr: { title: 'current scope' } }) + expect(observe).toHaveBeenCalledTimes(1) + } finally { + remove() + } + } +) diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshot-test-harness.ts b/src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshot-test-harness.ts new file mode 100644 index 00000000000..0f617d38b8a --- /dev/null +++ b/src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshot-test-harness.ts @@ -0,0 +1,110 @@ +// oxlint-disable-next-line typescript/triple-slash-reference -- Renderer integration tests also compile this main fixture with its ambient build constants. +/// +import { afterEach, beforeEach, vi, type Mock } from 'vitest' +import { makePR } from '../../../github/pull-requests/refresh/pr-refresh-coordinator-test-harness' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { RuntimeHostedReviewCommands } from './runtime-hosted-review-commands' +import type { RpcContext } from '../../rpc/core' + +const mocks: { resolve: Mock; account: Mock; gate: Mock } = vi.hoisted(() => ({ + resolve: vi.fn(), + account: vi.fn(), + gate: vi.fn() +})) +export { mocks } +vi.mock('../../../github/accounts/github-project-account', () => ({ + githubPRPolicyProjects: () => ({ source: null, selection: String(mocks.account()) }), + resolveGitHubProjectAccount: mocks.account +})) +vi.mock('../../../github/execution/github-operation-slots', () => ({ + acquire: async () => {}, + release: () => {} +})) +vi.mock('../../../github/client/lookup/branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: mocks.resolve +})) +vi.mock('../../../github/pull-requests/refresh/pr-refresh-rate-limit-gate', () => ({ + prRefreshRateLimitPausedUntil: mocks.gate +})) + +export let commands: RuntimeHostedReviewCommands +export const fixture = { title: 'before' } +export const found = (): PRRefreshOutcome => ({ + kind: 'found', + fetchedAt: Date.now(), + pr: makePR({ + title: fixture.title, + headSha: 'head-a', + checksStatus: 'success', + checksReadComplete: true, + checksFinal: true, + autoMergeEnabled: false, + mergeQueueRequired: false + }) +}) +export const read = ( + branch: string, + reason: 'active' | 'visible' | 'swr' | 'manual' = 'swr', + head = 'head-a' +) => + commands.getRepoPRForBranch( + 'repo', + branch, + null, + null, + false, + head, + reason, + undefined, + undefined, + undefined, + true + ) + +beforeEach(async () => { + vi.resetModules() + vi.useFakeTimers() + vi.setSystemTime(1_000) + fixture.title = 'before' + mocks.resolve.mockReset().mockImplementation(async () => found()) + mocks.account.mockReset().mockReturnValue(null) + mocks.gate.mockReset().mockResolvedValue(null) + // Resolve the real handler before fake-clock assertions begin. + await import('../../rpc/methods/source-control/github/github-pull-request-methods') + const { RuntimeHostedReviewCommands: Commands } = await import('./runtime-hosted-review-commands') + const repo = { + id: 'repo', + path: '/repo', + kind: 'git' as const, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 0 + } + commands = new Commands({ + resolveRepo: async () => repo, + resolveTarget: async () => ({ repo, repoPath: repo.path }), + getExecutionOptions: () => undefined, + recordCreated: () => {} + }) +}) +afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() +}) + +export async function rpcRead(params: unknown, signal?: AbortSignal) { + const { GITHUB_PULL_REQUEST_METHODS } = + await import('../../rpc/methods/source-control/github/github-pull-request-methods') + const { PrForBranch } = + await import('../../../../shared/rpc-contract/github/github-pull-request-params') + const { repo, branch, ...options } = PrForBranch.parse(params) + const parsed = { repo, branch, ...options } + const runtime = { getRepoPRForBranch: commands.getRepoPRForBranch.bind(commands) } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this handler only needs the bound real PR command and signal. + const context = { runtime, signal } as unknown as RpcContext + const method = GITHUB_PULL_REQUEST_METHODS.find((entry) => entry.name === 'github.prForBranch') + if (!method) { + throw new Error('PR RPC method is missing') + } + return method.handler(parsed, context) +} diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshots.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshots.test.ts new file mode 100644 index 00000000000..5b078a94251 --- /dev/null +++ b/src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshots.test.ts @@ -0,0 +1,576 @@ +import { describe, expect, it, vi } from 'vitest' +import { makeCandidate } from '../../../github/pull-requests/refresh/pr-refresh-coordinator-test-harness' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { registerPRProducerSettlementTests } from './hosted-pr-producer-settlement-test-cases' +import { commands, fixture, found, mocks, read } from './runtime-hosted-pr-snapshot-test-harness' + +describe('hosted PR snapshots', () => { + it('shares true-aged timer data while legacy discovery and actions read current data', async () => { + await read('shared', 'active') + fixture.title = 'after' + expect(await read('shared')).toMatchObject({ + kind: 'found', + pr: { title: 'before' }, + fetchedAt: 1_000 + }) + vi.setSystemTime(2_000) + expect(await read('shared', 'visible')).toMatchObject({ + kind: 'found', + pr: { title: 'after' }, + fetchedAt: 2_000 + }) + fixture.title = 'manual' + expect(await read('shared', 'manual')).toMatchObject({ kind: 'found', pr: { title: 'manual' } }) + }) + + it('keeps a confirmed unchanged quiet result, but a different request head reads again', async () => { + await read('quiet', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const confirmation = read('quiet') + await vi.advanceTimersByTimeAsync(0) + expect(await confirmation).toMatchObject({ fetchedAt: 61_000 }) + await vi.advanceTimersByTimeAsync(120_000) + fixture.title = 'new provider state' + expect(await read('quiet')).toMatchObject({ pr: { title: 'before' }, fetchedAt: 61_000 }) + expect(await read('quiet', 'swr', 'head-b')).toMatchObject({ + pr: { title: 'new provider state' }, + fetchedAt: 181_000 + }) + }) + + it('returns completed checks in each due response for three queued rows', async () => { + await Promise.all(['one', 'two', 'three'].map((branch) => read(branch, 'active'))) + fixture.title = 'finished checks' + mocks.resolve.mockImplementation( + () => + new Promise((resolve) => { + // ast-grep-ignore: test-no-real-time-wait -- Fake-clock provider delay exercises host admission and completion. + setTimeout(() => resolve(found()), 1_000) + }) + ) + await vi.advanceTimersByTimeAsync(60_000) + const responses = Promise.all(['one', 'two', 'three'].map((branch) => read(branch))) + await vi.advanceTimersByTimeAsync(21_000) + expect(await responses).toEqual([ + expect.objectContaining({ pr: expect.objectContaining({ title: 'finished checks' }) }), + expect.objectContaining({ pr: expect.objectContaining({ title: 'finished checks' }) }), + expect.objectContaining({ pr: expect.objectContaining({ title: 'finished checks' }) }) + ]) + }) + + it('delivers a deferred provider failure to the next timer instead of reviving old success', async () => { + await read('slow', 'active') + const provider = Promise.withResolvers() + mocks.resolve.mockImplementation(() => provider.promise) + await vi.advanceTimersByTimeAsync(60_000) + const waiting = read('slow') + await vi.advanceTimersByTimeAsync(25_000) + expect(await waiting).toMatchObject({ + kind: 'found', + fetchedAt: 1_000, + revalidation: { retryAfterMs: 10_000 } + }) + provider.reject(new Error('network down')) + await vi.advanceTimersByTimeAsync(0) + expect(await read('slow')).toMatchObject({ kind: 'upstream-error' }) + mocks.resolve.mockImplementation(async () => found()) + fixture.title = 'manual recovery' + expect(await read('slow', 'manual')).toMatchObject({ pr: { title: 'manual recovery' } }) + }) + + it('retrieves a queued completion on its short retry after local work delays admission', async () => { + await Promise.all(['one', 'two', 'three'].map((branch) => read(branch, 'active'))) + mocks.resolve.mockImplementation( + ({ branchName }) => + new Promise((resolve) => { + // ast-grep-ignore: test-no-real-time-wait -- Fake-clock provider delay exercises host admission and completion. + setTimeout(() => resolve(found()), branchName === 'blocking' ? 6_000 : 1_000) + }) + ) + await vi.advanceTimersByTimeAsync(60_000) + const { enqueuePRRefresh } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + enqueuePRRefresh(makeCandidate({ branch: 'blocking' }), 'active') + await vi.advanceTimersByTimeAsync(0) + fixture.title = 'delivered' + const responses = Promise.all(['one', 'two', 'three'].map((branch) => read(branch))) + await vi.advanceTimersByTimeAsync(25_000) + expect(await responses).toMatchObject([ + { pr: { title: 'delivered' } }, + { pr: { title: 'delivered' } }, + { pr: { title: 'before' }, revalidation: { retryAfterMs: 10_000 } } + ]) + await vi.advanceTimersByTimeAsync(10_000) + expect(await read('three')).toMatchObject({ pr: { title: 'delivered' }, fetchedAt: 88_000 }) + }) + + it('returns a no-data retry after the project account changes', async () => { + mocks.account.mockReturnValue({ ghAccount: { host: 'github.com', user: 'before' } }) + await read('account', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const gate = Promise.withResolvers() + mocks.gate.mockReturnValue(gate.promise) + const waiting = read('account') + await vi.advanceTimersByTimeAsync(0) + mocks.account.mockReturnValue({ ghAccount: { host: 'github.com', user: 'after' } }) + gate.resolve(null) + await vi.advanceTimersByTimeAsync(0) + expect(await waiting).toEqual({ revalidation: { invalidated: true, retryAfterMs: 10_000 } }) + fixture.title = 'new account' + expect(await read('account')).toMatchObject({ pr: { title: 'new account' } }) + }) + + it('cancels one client wait while another receives the shared provider result', async () => { + await read('cancel', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValue(provider.promise) + const controller = new AbortController() + const cancelled = commands.getRepoPRForBranch( + 'repo', + 'cancel', + null, + null, + false, + 'head-a', + 'swr', + false, + undefined, + controller.signal, + true + ) + const rejected = expect(cancelled).rejects.toThrow('cancelled') + const remaining = read('cancel') + await vi.advanceTimersByTimeAsync(0) + controller.abort() + await rejected + fixture.title = 'shared completion' + provider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(await remaining).toMatchObject({ pr: { title: 'shared completion' } }) + }) + + it('returns a receipt to excess waiters and keeps the shared result after cancellation', async () => { + await read('many', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValue(provider.promise) + const controllers = Array.from({ length: 256 }, () => new AbortController()) + const waiting = controllers.map((controller) => + commands.getRepoPRForBranch( + 'repo', + 'many', + null, + null, + false, + 'head-a', + 'swr', + false, + undefined, + controller.signal, + true + ) + ) + const cancellations = Promise.allSettled(waiting) + await vi.advanceTimersByTimeAsync(0) + expect(await read('many')).toMatchObject({ + fetchedAt: 1_000, + revalidation: { retryAfterMs: 10_000 } + }) + for (const controller of controllers) { + controller.abort() + } + await cancellations + fixture.title = 'completed without waiters' + provider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(await read('many')).toMatchObject({ pr: { title: 'completed without waiters' } }) + }) + + it('lets a rate-limited job expire without starting it after demand stops', async () => { + await read('lease', 'active') + await vi.advanceTimersByTimeAsync(60_000) + mocks.gate.mockResolvedValue(Date.now() + 900_000) + const waiting = read('lease') + await vi.advanceTimersByTimeAsync(25_000) + expect(await waiting).toMatchObject({ + fetchedAt: 1_000, + revalidation: { retryAfterMs: 875_000 } + }) + fixture.title = 'not requested' + await vi.advanceTimersByTimeAsync(900_000) + const { readRecentPhonePROutcome } = + await import('../../../github/client/lookup/pr-for-branch-outcome') + expect( + await readRecentPhonePROutcome('/repo', 'lease', null, null, null, { + currentHeadOid: 'head-a' + }) + ).toBeNull() + mocks.gate.mockResolvedValue(null) + expect(await read('lease', 'manual')).toMatchObject({ pr: { title: 'not requested' } }) + }) + it('retains the exact late error and budget gate after narrowed and other-head writes, then recovers', async () => { + await read('retained', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const waiting = read('retained') + await vi.advanceTimersByTimeAsync(25_000) + expect(await waiting).toMatchObject({ revalidation: { retryAfterMs: 10_000 } }) + provider.resolve({ + kind: 'upstream-error', + errorType: 'network', + message: 'offline', + fetchedAt: Date.now() + }) + await vi.advanceTimersByTimeAsync(0) + const { getPRForBranchOutcome } = + await import('../../../github/client/lookup/pr-for-branch-outcome') + await getPRForBranchOutcome('/repo', 'retained', null, null, null, { + currentHeadOid: 'head-a', + includeDerivedData: false + }) + await read('retained', 'active', 'head-b') + const before = mocks.resolve.mock.calls.length + const error = await read('retained') + expect(error).toMatchObject({ + kind: 'upstream-error', + message: 'offline', + nextAutoRetryAt: expect.any(Number) + }) + expect(mocks.resolve).toHaveBeenCalledTimes(before) + if (!('kind' in error) || error.kind !== 'upstream-error') { + throw new Error('expected the actual provider failure') + } + await vi.advanceTimersByTimeAsync(error.nextAutoRetryAt! - Date.now()) + fixture.title = 'recovered' + const recovered = read('retained') + await vi.advanceTimersByTimeAsync(0) + expect(await recovered).toMatchObject({ kind: 'found', pr: { title: 'recovered' } }) + }) + + it('delivers its exact completion when another full identity advances the phone projection', async () => { + await read('identities', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const waiting = read('identities') + await vi.advanceTimersByTimeAsync(0) + fixture.title = 'other head' + await read('identities', 'active', 'head-b') + fixture.title = 'original exact completion' + provider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(await waiting).toMatchObject({ + kind: 'found', + pr: { title: 'original exact completion' } + }) + }) + + it('shares overlapping fresh discovery across clients without joining older timed work', async () => { + mocks.resolve.mockImplementation(async () => { + // ast-grep-ignore: test-no-real-time-wait -- Fake-clock provider delay exercises host admission and completion. + await new Promise((resolve) => setTimeout(resolve, 1_000)) + return found() + }) + const discoveries = Promise.all( + Array.from({ length: 2 }, () => + Promise.all(Array.from({ length: 14 }, (_, row) => read(`discovery-${row}`, 'active'))) + ) + ) + await vi.advanceTimersByTimeAsync(1_000) + await discoveries + expect(mocks.resolve).toHaveBeenCalledTimes(14) + await vi.advanceTimersByTimeAsync(60_000) + const slow = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(slow.promise) + const timed = read('discovery-0') + await vi.advanceTimersByTimeAsync(0) + fixture.title = 'fresh action' + const actions = Promise.all([read('discovery-0', 'active'), read('discovery-0', 'active')]) + await vi.advanceTimersByTimeAsync(1_000) + expect(await actions).toMatchObject([ + { pr: { title: 'fresh action' } }, + { pr: { title: 'fresh action' } } + ]) + expect(mocks.resolve).toHaveBeenCalledTimes(16) + fixture.title = 'obsolete timer' + slow.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(await timed).toMatchObject({ pr: { title: 'fresh action' } }) + expect(await read('discovery-0')).toMatchObject({ pr: { title: 'fresh action' } }) + }) + + it.each([true, false])( + 'does not restore full content after a narrowed observation (warm=%s)', + async (warm) => { + if (warm) { + await read('fenced', 'active') + await vi.advanceTimersByTimeAsync(60_000) + } + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const timed = read('fenced') + await vi.advanceTimersByTimeAsync(0) + const joined = read('fenced') + await vi.advanceTimersByTimeAsync(0) + const { getPRForBranchOutcome, readRecentPhonePROutcome } = + await import('../../../github/client/lookup/pr-for-branch-outcome') + await getPRForBranchOutcome('/repo', 'fenced', null, null, null, { + currentHeadOid: 'head-a', + includeDerivedData: false + }) + fixture.title = 'obsolete full content' + provider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(await Promise.all([timed, joined])).toEqual([ + { revalidation: { invalidated: true, retryAfterMs: 10_000 } }, + { revalidation: { invalidated: true, retryAfterMs: 10_000 } } + ]) + expect(mocks.resolve).toHaveBeenCalledTimes(warm ? 3 : 2) + expect( + await readRecentPhonePROutcome('/repo', 'fenced', null, null, null, { + currentHeadOid: 'head-a' + }) + ).toBeNull() + fixture.title = 'new foreground observation' + expect(await read('fenced', 'active')).toMatchObject({ + pr: { title: 'new foreground observation' } + }) + } + ) + + it('delivers a retained cold no-PR completion to both timed consumers', async () => { + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const cold = read('cold-absence') + await vi.advanceTimersByTimeAsync(0) + const joined = read('cold-absence') + await vi.advanceTimersByTimeAsync(0) + provider.resolve({ kind: 'no-pr', fetchedAt: 1_000 }) + expect(await Promise.all([cold, joined])).toEqual([ + { kind: 'no-pr', fetchedAt: 1_000 }, + { kind: 'no-pr', fetchedAt: 1_000 } + ]) + }) + + registerPRProducerSettlementTests({ read, mocks, found }) + + it('delivers the current result to cold timers and their pending joiners after a fresh successor', async () => { + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const cold = read('cold-successor') + await vi.advanceTimersByTimeAsync(0) + const joined = read('cold-successor') + await vi.advanceTimersByTimeAsync(0) + fixture.title = 'authoritative foreground' + await read('cold-successor', 'active') + fixture.title = 'superseded cold content' + provider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(await Promise.all([cold, joined])).toMatchObject([ + { kind: 'found', pr: { title: 'authoritative foreground' } }, + { kind: 'found', pr: { title: 'authoritative foreground' } } + ]) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + }) + + it('gives a superseded timer a short retry until another client fresh read completes', async () => { + await read('successor', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const timedProvider = Promise.withResolvers() + const freshProvider = Promise.withResolvers() + mocks.resolve + .mockReturnValueOnce(timedProvider.promise) + .mockReturnValueOnce(freshProvider.promise) + const timed = read('successor') + await vi.advanceTimersByTimeAsync(0) + const fresh = read('successor', 'active') + await vi.advanceTimersByTimeAsync(0) + fixture.title = 'superseded timer' + timedProvider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(await timed).toMatchObject({ + kind: 'found', + pr: { title: 'before' }, + fetchedAt: 1_000, + revalidation: { retryAfterMs: 10_000 } + }) + fixture.title = 'another client fresh result' + freshProvider.resolve(found()) + await fresh + const starts = mocks.resolve.mock.calls.length + expect(await read('successor')).toMatchObject({ pr: { title: 'another client fresh result' } }) + expect(mocks.resolve).toHaveBeenCalledTimes(starts) + }) + + it('retains an in-flight timer failure when a new branch fills the exact-result cache', async () => { + for (let branch = 0; branch < 256; branch += 1) { + await read(`capacity-${branch}`, 'active') + } + await vi.advanceTimersByTimeAsync(60_000) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const waiting = read('capacity-0') + await vi.advanceTimersByTimeAsync(25_000) + expect(await waiting).toMatchObject({ revalidation: { retryAfterMs: 10_000 } }) + await read('capacity-new', 'active') + provider.resolve({ + kind: 'upstream-error', + errorType: 'network', + message: 'retained late failure', + fetchedAt: Date.now() + }) + await vi.advanceTimersByTimeAsync(0) + const starts = mocks.resolve.mock.calls.length + expect(await read('capacity-0')).toMatchObject({ + kind: 'upstream-error', + message: 'retained late failure', + nextAutoRetryAt: expect.any(Number) + }) + expect(mocks.resolve).toHaveBeenCalledTimes(starts) + const error = await read('capacity-0') + if (!('kind' in error) || error.kind !== 'upstream-error') { + throw new Error('expected the retained capacity failure') + } + await vi.advanceTimersByTimeAsync(error.nextAutoRetryAt! - Date.now()) + const pausedUntil = Date.now() + 60_000 + mocks.gate.mockResolvedValue(pausedUntil) + const gated = read('capacity-0') + await vi.advanceTimersByTimeAsync(25_000) + expect(await gated).toMatchObject({ kind: 'upstream-error', message: 'retained late failure' }) + expect(mocks.resolve).toHaveBeenCalledTimes(starts) + fixture.title = 'capacity recovery' + mocks.gate.mockResolvedValue(null) + await vi.advanceTimersByTimeAsync(35_000) + expect(await read('capacity-0')).toMatchObject({ + kind: 'found', + pr: { title: 'capacity recovery' } + }) + }) + + it('keeps unrelated timer data after many branch watches invalidate their own content', async () => { + const { getPRForBranchOutcome } = + await import('../../../github/client/lookup/pr-for-branch-outcome') + const watch = (branch: string) => + getPRForBranchOutcome('/repo', branch, null, null, null, { + currentHeadOid: 'head-a', + includeDerivedData: false + }) + for (let branch = 0; branch < 256; branch += 1) { + await watch(`watch-${branch}`) + } + await read('unrelated', 'active') + await watch('watch-0') + await watch('watch-256') + fixture.title = 'should wait for its own refresh' + const starts = mocks.resolve.mock.calls.length + expect(await read('unrelated')).toMatchObject({ + kind: 'found', + pr: { title: 'before' }, + fetchedAt: 1_000 + }) + expect(mocks.resolve).toHaveBeenCalledTimes(starts) + }) + + it('refuses extra automatic retention while protected reads fill capacity but leaves foreground usable', async () => { + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValue(provider.promise) + const foreground = Array.from({ length: 256 }, (_, branch) => + read(`protected-${branch}`, 'active') + ) + await vi.advanceTimersByTimeAsync(0) + expect(await read('excess')).toEqual({ + revalidation: { invalidated: true, retryAfterMs: 10_000 } + }) + expect(mocks.resolve).toHaveBeenCalledTimes(256) + mocks.resolve.mockImplementation(async () => found()) + fixture.title = 'foreground still available' + expect(await read('excess', 'active')).toMatchObject({ + pr: { title: 'foreground still available' } + }) + provider.resolve(found()) + await Promise.all(foreground) + expect(await read('excess')).toMatchObject({ kind: 'found' }) + }) + + it.each(['runtime', 'local'] as const)( + 'observes one provider read when %s starts the local/runtime overlap', + async (first) => { + const { addPRRefreshOutcomeObserver, enqueuePRRefresh } = + await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') + const { setPRRefreshRendererPort } = + await import('../../../github/pull-requests/refresh/pr-refresh-renderer-port') + const observe = vi.fn() + const broadcast = vi.fn() + const remove = addPRRefreshOutcomeObserver(observe) + setPRRefreshRendererPort({ isRendererOpen: () => true, sendToTrustedUI: broadcast }) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValue(provider.promise) + const local = () => + enqueuePRRefresh( + makeCandidate({ + cacheKey: '/repo::observed', + repoId: 'repo', + branch: 'observed', + currentHeadOid: 'head-a' + }), + 'active' + ) + try { + let runtime: ReturnType + if (first === 'runtime') { + runtime = read('observed', 'active') + await vi.advanceTimersByTimeAsync(0) + local() + await vi.advanceTimersByTimeAsync(0) + } else { + local() + await vi.advanceTimersByTimeAsync(0) + runtime = read('observed', 'active') + await vi.advanceTimersByTimeAsync(0) + } + fixture.title = 'shared observable result' + provider.resolve(found()) + expect(await runtime).toMatchObject({ pr: { title: 'shared observable result' } }) + await vi.advanceTimersByTimeAsync(0) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + expect(observe).toHaveBeenCalledTimes(1) + expect(broadcast).toHaveBeenCalledWith( + 'gh:prRefreshEvent', + expect.objectContaining({ + aliases: expect.arrayContaining([ + expect.objectContaining({ cacheKey: '/repo::observed' }) + ]), + outcome: expect.objectContaining({ + kind: 'found', + pr: expect.objectContaining({ title: 'shared observable result' }) + }) + }) + ) + } finally { + remove() + setPRRefreshRendererPort(null) + } + } + ) + + it('returns legacy timed cache immediately and never sends a receipt-only reply', async () => { + await read('legacy', 'active') + await vi.advanceTimersByTimeAsync(60_000) + const provider = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(provider.promise) + const legacy = await commands.getRepoPRForBranch( + 'repo', + 'legacy', + null, + null, + false, + 'head-a', + 'swr' + ) + expect(legacy).toMatchObject({ kind: 'found', fetchedAt: 1_000 }) + provider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + }) +}) diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts index 6a14b007a13..48c026c69f0 100644 --- a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts +++ b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts @@ -1,18 +1,25 @@ import { - getPRForBranchOutcome, + preparePRBranchRead, readRecentPhonePROutcome } from '../../../github/client/lookup/pr-for-branch-outcome' import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../../shared/github/repositories/repository-identity' import type { GitHubPRRefreshReason, - PRRefreshOutcome + PRSnapshotReply } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { Repo } from '../../../../shared/repo-types' import type { DeviceScope } from '../../../../shared/runtime-session-contracts' import { getRepoSlug, getRepoUpstream } from '../../../github/client/fetch/repo-slug-upstream' -import { admissionTierForRefreshReason } from '../../../github/pull-requests/refresh/pr-refresh-candidate-policy' +import { + admissionTierForRefreshReason, + bypassesFreshnessDelay +} from '../../../github/pull-requests/refresh/pr-refresh-candidate-policy' import type { GitHubPRBranchLookupOptions } from '../../../github/client/lookup/pull-request-lookup-data' -import { runHostedPRRead } from '../../../github/pull-requests/refresh/pr-refresh-coordinator' +import { + runHostedPRRead, + runHostedPRSnapshot +} from '../../../github/pull-requests/refresh/pr-refresh-coordinator' +import { HOSTED_PR_COMPLETION_WAIT_MS } from '../../../github/pull-requests/refresh/hosted-pr-read-jobs' import { type CreateHostedReviewInput, type CreateHostedReviewResult, @@ -78,8 +85,12 @@ export class RuntimeHostedReviewCommands { currentHeadOid?: string | null, reason?: GitHubPRRefreshReason, userRefresh?: boolean, - clientKind?: DeviceScope - ): Promise { + clientKind?: DeviceScope, + signal?: AbortSignal, + acceptRevalidationOnly = false, + selected = false + ): Promise { + const deadline = Date.now() + HOSTED_PR_COMPLETION_WAIT_MS const repo = await this.deps.resolveRepo(repoSelector) const lookupOptions: GitHubPRBranchLookupOptions = { ...this.deps.getExecutionOptions( @@ -90,16 +101,17 @@ export class RuntimeHostedReviewCommands { if (userRefresh === true) { lookupOptions.userRefresh = true } + if (reason && bypassesFreshnessDelay(reason)) { + lookupOptions.resetQuietBackoff = true + } if (acceptMergedFallbackPR === true) { lookupOptions.acceptMergedFallbackPR = true } if (typeof currentHeadOid === 'string' && currentHeadOid.trim().length > 0) { lookupOptions.currentHeadOid = currentHeadOid.trim() } - const lookupOptionArgs: [] | [GitHubPRBranchLookupOptions] = - Object.keys(lookupOptions).length > 0 ? [lookupOptions] : [] const connectionId = hostedReviewSshConnectionId(getStoredRepoExecutionHostId(repo)) - // Desktop callers and reason-carrying refreshes keep their own GitHub read. + // Legacy phone reads retain their narrower thirty-second reuse contract. if (clientKind === 'mobile' && reason === undefined) { const recent = await readRecentPhonePROutcome( repo.path, @@ -113,27 +125,31 @@ export class RuntimeHostedReviewCommands { return recent } } - // Through the coordinator, so a client's read also serves this server's CI-line watches. - return runHostedPRRead( - { - cacheKey: `${repo.path}::${branch}`, - repoKind: repo.kind ?? 'git', - repoId: repo.id, - repoPath: repo.path, - branch, - connectionId, - linkedPRNumber: linkedPRNumber ?? null - }, - () => - getPRForBranchOutcome( - repo.path, - branch, - linkedPRNumber ?? null, - connectionId, - linkedPRNumber == null ? (fallbackPRNumber ?? null) : null, - ...lookupOptionArgs - ) + const candidate = { + cacheKey: `${repo.path}::${branch}`, + repoKind: repo.kind ?? ('git' as const), + repoId: repo.id, + repoPath: repo.path, + branch, + connectionId, + currentHeadOid: lookupOptions.currentHeadOid ?? null, + linkedPRNumber: linkedPRNumber ?? null, + fallbackPRNumber: linkedPRNumber == null ? (fallbackPRNumber ?? null) : null, + localGitOptions: lookupOptions.localGitExecOptions, + isSelected: reason === 'swr' && userRefresh !== true && selected + } + const prepared = await preparePRBranchRead( + repo.path, + branch, + linkedPRNumber ?? null, + connectionId, + linkedPRNumber == null ? (fallbackPRNumber ?? null) : null, + lookupOptions ) + if (reason === 'swr' && userRefresh !== true) { + return runHostedPRSnapshot(candidate, prepared, deadline, signal, acceptRevalidationOnly) + } + return runHostedPRRead(candidate, prepared) } async getHostedReviewForBranch(args: { diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts index caa4161c0a1..5da571c10ae 100644 --- a/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts +++ b/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts @@ -1,3 +1,4 @@ +import type { PreparedPRBranchRead } from '../../../github/client/lookup/pr-for-branch-outcome' import type * as GithubRepositoryIdentityModule from '../../../github/repositories/github-repository-identity' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { @@ -31,7 +32,10 @@ vi.mock('../../../github/client/lookup/branch-lookup-resolution', () => ({ resolvePRForBranchOutcome: mocks.resolve })) vi.mock('../../../github/pull-requests/refresh/pr-refresh-coordinator', () => ({ - runHostedPRRead: (_candidate: unknown, read: () => Promise) => read() + runHostedPRRead: ( + _candidate: unknown, + read: (() => Promise) | PreparedPRBranchRead + ) => (typeof read === 'function' ? read() : read.read()) })) import { RuntimeHostedReviewCommands } from './runtime-hosted-review-commands' @@ -153,6 +157,6 @@ describe('phone PR lookups reuse the desktop’s last result', () => { userRefresh, clientKind ) - expect(outcome.kind === 'found' ? outcome.pr.title : null).toBe(expected) + expect('kind' in outcome && outcome.kind === 'found' ? outcome.pr.title : null).toBe(expected) }) }) diff --git a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts index 0c2c03dbfa0..924b2cf2bbe 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts @@ -16,7 +16,7 @@ export const GITHUB_PULL_REQUEST_METHODS = [ name: 'github.prForBranch', permission: 'workspace', params: PrForBranch, - handler: async (params, { runtime, clientKind }) => + handler: async (params, { runtime, clientKind, signal }) => runtime.getRepoPRForBranch( params.repo, params.branch, @@ -26,7 +26,10 @@ export const GITHUB_PULL_REQUEST_METHODS = [ params.currentHeadOid, params.reason, params.userRefresh, - clientKind + clientKind, + signal, + params.acceptRevalidationOnly, + params.selected ) }), defineMethod({ diff --git a/src/preload/api/github/github-pull-request-api.ts b/src/preload/api/github/github-pull-request-api.ts index c763ebb7798..0a56df1cf50 100644 --- a/src/preload/api/github/github-pull-request-api.ts +++ b/src/preload/api/github/github-pull-request-api.ts @@ -14,7 +14,7 @@ import type { GitHubPRRefreshEnqueueResult, GitHubPRRefreshEvent, GitHubPRRefreshReason, - PRRefreshOutcome + PRSnapshotReply } from '../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../shared/github/repositories/repository-identity' import type { @@ -52,7 +52,7 @@ export type GithubPullRequestApi = { candidate: GitHubPRRefreshCandidate reason?: GitHubPRRefreshReason userRefresh?: boolean - }) => Promise + }) => Promise enqueuePRRefresh: (args: { candidate: GitHubPRRefreshCandidate reason: GitHubPRRefreshReason diff --git a/src/renderer/src/store/github/github-slice-contract.ts b/src/renderer/src/store/github/github-slice-contract.ts index 182a10164f0..450eaa75f38 100644 --- a/src/renderer/src/store/github/github-slice-contract.ts +++ b/src/renderer/src/store/github/github-slice-contract.ts @@ -9,6 +9,7 @@ import type { } from '../../../../shared/github/comments/comment-types' import type { GitHubPRRefreshEvent, + PRSnapshotReply, GitHubPRRefreshReason } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { GitHubRepositoryIdentity as GitHubOwnerRepo } from '../../../../shared/github/repositories/repository-identity' @@ -70,6 +71,9 @@ export type GitHubSlice = { fallbackPRSource?: GitHubPRFallbackSource | null reason?: GitHubPRRefreshReason userRefresh?: boolean + selected?: boolean + onReadOutcome?: (outcome: PRSnapshotReply) => void + signal?: AbortSignal } ) => Promise fetchIssue: ( diff --git a/src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts b/src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts index e97a508a13f..1663d6d6673 100644 --- a/src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts +++ b/src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts @@ -5,7 +5,8 @@ import { makePR, mockApi, resetRemoteRuntimeMocks, - runtimeEnvironmentCall + runtimeEnvironmentCall, + runtimeEnvironmentSubscribe } from '../github-slice-test-harness' beforeEach(() => { @@ -23,7 +24,7 @@ afterEach(() => { vi.restoreAllMocks() }) -function found(number: number): PRRefreshOutcome { +function found(number: number): Extract { return { kind: 'found', pr: makePR({ number }), fetchedAt: Date.now() } } @@ -116,3 +117,163 @@ describe('pull-request lookup ownership after newer settlement', () => { } ) }) + +it.each(['post-push', 'active'] as const)( + 'keeps %s fresh while a timed snapshot is waiting', + async (reason) => { + const store = createTestStore() + store.setState({ + repos: [ + { + id: 'runtime-repo', + path: '/runtime/repo', + displayName: 'Runtime repo', + badgeColor: 'blue', + addedAt: 1, + executionHostId: 'runtime:env-1' + } + ] + }) + const timed = Promise.withResolvers() + const action = Promise.withResolvers() + const actionStarted = Promise.withResolvers() + runtimeEnvironmentCall.mockImplementation(async (args) => { + const isAction = + typeof args.params === 'object' && + args.params !== null && + 'reason' in args.params && + args.params.reason === reason + if (isAction) { + actionStarted.resolve() + } + return { + id: 'rpc', + ok: true, + result: await (isAction ? action.promise : timed.promise) + } + }) + let timerReceipt: unknown + const timer = store.getState().fetchPRForBranch('/runtime/repo', 'intent', { + force: true, + reason: 'swr', + onReadOutcome: (outcome) => { + timerReceipt = outcome + } + }) + await vi.advanceTimersByTimeAsync(0) + const refresh = store + .getState() + .fetchPRForBranch('/runtime/repo', 'intent', { force: true, reason }) + await actionStarted.promise + action.resolve(found(20)) + await refresh + timed.resolve({ ...found(10), revalidation: { retryAfterMs: 10_000 } }) + await timer + expect(store.getState().prCache['runtime:env-1::runtime-repo::intent']?.data?.number).toBe(20) + expect(timerReceipt).toBeUndefined() + } +) + +it('handles negotiated invalidation before data or linked-PR settlement', async () => { + const store = createTestStore() + store.setState({ + repos: [ + { + id: 'runtime-repo', + path: '/runtime/repo', + displayName: 'Runtime repo', + badgeColor: 'blue', + addedAt: 1, + executionHostId: 'runtime:env-1' + } + ] + }) + runtimeEnvironmentCall.mockResolvedValue({ id: 'rpc', ok: true, result: found(20) }) + await store + .getState() + .fetchPRForBranch('/runtime/repo', 'receipt', { force: true, reason: 'active' }) + const before = store.getState().prCache['runtime:env-1::runtime-repo::receipt'] + const onReadOutcome = vi.fn() + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc', + ok: true, + result: { revalidation: { invalidated: true, retryAfterMs: 10_000 } } + }) + await store + .getState() + .fetchPRForBranch('/runtime/repo', 'receipt', { force: true, reason: 'swr', onReadOutcome }) + expect(onReadOutcome).toHaveBeenCalledWith({ + revalidation: { invalidated: true, retryAfterMs: 10_000 } + }) + expect(store.getState().prCache['runtime:env-1::runtime-repo::receipt']).toBe(before) + expect(store.getState().prRefreshStates['runtime:env-1::runtime-repo::receipt']).toBeUndefined() + expect(runtimeEnvironmentCall.mock.calls.at(-1)?.[0].params).toMatchObject({ + reason: 'swr', + acceptRevalidationOnly: true + }) + runtimeEnvironmentCall.mockResolvedValue({ id: 'rpc', ok: true, result: found(30).pr }) + await store + .getState() + .fetchPRForBranch('/runtime/repo', 'receipt', { force: true, reason: 'swr' }) + expect(store.getState().prCache['runtime:env-1::runtime-repo::receipt']?.data?.number).toBe(30) + runtimeEnvironmentCall.mockResolvedValue({ id: 'rpc', ok: true, result: null }) + await store + .getState() + .fetchPRForBranch('/runtime/repo', 'receipt', { force: true, reason: 'active' }) + expect(store.getState().prCache['runtime:env-1::runtime-repo::receipt']?.data).toBeNull() +}) + +it.each(['origin', 'joiner'] as const)( + 'detaches an aborted %s while the live consumer receives the shared result', + async (cancelled) => { + const store = createTestStore() + store.setState({ + repos: [ + { + id: 'runtime-repo', + path: '/runtime/repo', + displayName: 'Runtime repo', + badgeColor: 'blue', + addedAt: 1, + executionHostId: 'runtime:env-1' + } + ] + }) + const reply = Promise.withResolvers() + runtimeEnvironmentCall.mockImplementation(async () => ({ + id: 'rpc', + ok: true, + result: await reply.promise + })) + const origin = new AbortController() + const joiner = new AbortController() + const originOutcome = vi.fn() + const joinerOutcome = vi.fn() + const first = store.getState().fetchPRForBranch('/runtime/repo', 'shared-cancel', { + force: true, + reason: 'active', + signal: origin.signal, + onReadOutcome: originOutcome + }) + await vi.advanceTimersByTimeAsync(0) + const second = store.getState().fetchPRForBranch('/runtime/repo', 'shared-cancel', { + force: true, + reason: 'active', + signal: joiner.signal, + onReadOutcome: joinerOutcome + }) + ;(cancelled === 'origin' ? origin : joiner).abort() + expect(await (cancelled === 'origin' ? first : second)).toBeNull() + reply.resolve(found(30)) + expect((await (cancelled === 'origin' ? second : first))?.number).toBe(30) + expect( + store.getState().prCache['runtime:env-1::runtime-repo::shared-cancel']?.data?.number + ).toBe(30) + expect(cancelled === 'origin' ? originOutcome : joinerOutcome).not.toHaveBeenCalled() + expect(cancelled === 'origin' ? joinerOutcome : originOutcome).toHaveBeenCalledWith( + expect.objectContaining({ kind: 'found', pr: expect.objectContaining({ number: 30 }) }) + ) + expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(1) + expect(runtimeEnvironmentSubscribe).toHaveBeenCalledTimes(1) + } +) diff --git a/src/renderer/src/store/github/pull-requests/pull-request-actions.ts b/src/renderer/src/store/github/pull-requests/pull-request-actions.ts index 8280dca0ec6..4d7e04d136f 100644 --- a/src/renderer/src/store/github/pull-requests/pull-request-actions.ts +++ b/src/renderer/src/store/github/pull-requests/pull-request-actions.ts @@ -8,14 +8,24 @@ import { findRepoForGitHubOwner } from '../repositories/repository-routing' import '../cache/cache-identity' import { getGitHubRepoCacheKey } from '../../../../../shared/github/cache/github-cache-key' import { isFresh } from '../cache/cache-policy' -import { buildGitHubPRRefreshStateClearToken } from '../refresh/pr-refresh-state' +import { + buildGitHubPRRefreshStateClearToken, + bypassesGitHubPRRefreshFreshness +} from '../refresh/pr-refresh-state' import { githubHostedReviewFallbackPRNumber, prLookupHintKey } from './pr-result-routing' import { nextLookupGeneration } from '../../slices/hosted-review/refresh/lookup-generation-sequence' -import { inflightPRRequests, prRequestGenerations } from '../requests/request-coordination' +import { + inflightPRRequests, + prRequestGenerations, + type InflightPR +} from '../requests/request-coordination' +import { sharedPromiseSettlementWaiters } from '../../../../../shared/promise-settlement-waiters' import { getGitHubSourceTarget, settingsForGitHubRepoOwner } from '../work-items/work-item-routing' import { captureLinkedReviewClearScope, clearLinkedReview } from './linked-review-clear' import { shouldClearDivergedLinkedMergedPR } from '../../../../../shared/github/pull-requests/refresh/linked-pr-staleness' import { startPullRequestLookup } from './pull-request-execution' +import { findWorktreeById } from '../refresh/worktree-refresh' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' export const createPullRequestActions = ( set: Parameters>[0], @@ -40,6 +50,9 @@ export const createPullRequestActions = ( repo !== undefined ) const cached = get().prCache[cacheKey] + if (options?.signal?.aborted) { + return cached?.data ?? null + } const hostedReviewCacheKey = getHostedReviewCacheKey( repoPath, branch, @@ -68,7 +81,16 @@ export const createPullRequestActions = ( ? null : (options?.fallbackPRSource ?? (explicitFallbackPRNumber != null ? 'explicit' : 'hosted-review')) - const lookupHintKey = prLookupHintKey(linkedPRNumber, fallbackPRNumber) + const lookupHintKey = JSON.stringify([ + prLookupHintKey(linkedPRNumber, fallbackPRNumber), + options?.worktreeId + ? (findWorktreeById( + get(), + options.worktreeId, + repo ? getRepoExecutionHostId(repo) : undefined + )?.head ?? null) + : null + ]) const linkedRefetch = cached?.data === null && (linkedPRNumber !== null || fallbackPRNumber !== null) if (!options?.force && !options?.userRefresh && !linkedRefetch && isFresh(cached)) { @@ -102,13 +124,25 @@ export const createPullRequestActions = ( if ( !options?.userRefresh && inflightRequest && + !inflightRequest.controller.signal.aborted && (!options?.force || inflightRequest.force) && inflightRequest.lookupHintKey === lookupHintKey && + !( + inflightRequest.reason === 'swr' && + bypassesGitHubPRRefreshFreshness(options?.reason ?? 'manual') + ) && !linkedRefetch ) { - return inflightRequest.promise + return waitForPullRequest( + inflightRequest, + options, + () => get().prCache[cacheKey]?.data ?? null + ) } + if (inflightRequest) { + inflightRequest.superseded = true + } const generation = nextLookupGeneration() const requestStartedAt = Date.now() const requestStartedHostedReviewEntry = get().hostedReviewCache[hostedReviewCacheKey] @@ -120,12 +154,13 @@ export const createPullRequestActions = ( ) prRequestGenerations.set(cacheKey, generation) + const controller = new AbortController() const request = startPullRequestLookup({ set, get, repoPath, branch, - options, + options: { ...options, signal: controller.signal, onReadOutcome: undefined }, repo, repoId, requestSettings, @@ -141,12 +176,44 @@ export const createPullRequestActions = ( requestStartedPRRefreshToken }) - inflightPRRequests.set(cacheKey, { + const inflight: InflightPR = { promise: request, + controller, + waiters: sharedPromiseSettlementWaiters(request), force: Boolean(options?.force), generation, + reason: options?.reason, lookupHintKey - }) - return request + } + inflightPRRequests.set(cacheKey, inflight) + return waitForPullRequest(inflight, options, () => get().prCache[cacheKey]?.data ?? null) } }) + +function waitForPullRequest( + inflight: InflightPR, + options: Parameters[2], + fallback: () => PRInfo | null +): Promise { + return inflight.waiters + .wait({ + signal: options?.signal, + deferSettled: true, + onFulfilled: () => { + if (inflight.outcome && !inflight.superseded) { + options?.onReadOutcome?.(inflight.outcome) + } + }, + onAbandon: () => { + if (inflight.waiters.waiterCount === 0) { + inflight.controller.abort() + } + } + }) + .catch((error: unknown) => { + if (options?.signal?.aborted) { + return fallback() + } + throw error + }) +} diff --git a/src/renderer/src/store/github/pull-requests/pull-request-execution.ts b/src/renderer/src/store/github/pull-requests/pull-request-execution.ts index 317b4d28b4c..3315464036a 100644 --- a/src/renderer/src/store/github/pull-requests/pull-request-execution.ts +++ b/src/renderer/src/store/github/pull-requests/pull-request-execution.ts @@ -14,12 +14,13 @@ import { import type { GitHubPRRefreshCandidate, - PRRefreshOutcome + PRSnapshotReply } from '../../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { normalizeGitHubPRForBranchOutcome, githubPRTransportFailureOutcome } from '../../../../../shared/github/pull-requests/refresh/pull-request-for-branch-outcome' +import { isPRRevalidationOnly } from '../../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { getRepoExecutionHostId } from '../../../../../shared/execution-host' import { callRuntimeRpc } from '../../../runtime/rpc/calls/runtime-rpc-call' import { inflightPRRequests, prRequestGenerations } from '../requests/request-coordination' @@ -95,7 +96,7 @@ export function startPullRequestLookup(args: { const requestHeadOid = candidateWorktree?.head ?? null let transportFailed = false const response = runtimeRepo - ? callRuntimeRpc( + ? callRuntimeRpc( runtimeRepo.target, 'github.prForBranch', { @@ -104,13 +105,23 @@ export function startPullRequestLookup(args: { linkedPRNumber, currentHeadOid: requestHeadOid, ...(options?.reason ? { reason: options.reason } : {}), + ...(options?.reason === 'swr' + ? { + acceptRevalidationOnly: true, + ...(options.userRefresh !== true && options.selected === true + ? { selected: true } + : {}) + } + : {}), ...(options?.userRefresh === true ? { userRefresh: true } : {}), ...(fallbackPRNumber !== null ? { fallbackPRNumber, acceptMergedFallbackPR: fallbackPRSource !== null } : {}) }, - { timeoutMs: 30_000, ...checkContract.sourceRpcOptions } - ).then((result) => normalizeGitHubPRForBranchOutcome(result)) + { timeoutMs: 30_000, signal: options?.signal, ...checkContract.sourceRpcOptions } + ).then((result) => + isPRRevalidationOnly(result) ? result : normalizeGitHubPRForBranchOutcome(result) + ) : (async () => { const candidate: GitHubPRRefreshCandidate = { repoId: repoId ?? '', @@ -136,15 +147,26 @@ export function startPullRequestLookup(args: { ...requestOptions, repoOwnerExecutionHostId: options?.repoOwnerExecutionHostId }) - return normalizeGitHubPRForBranchOutcome(response) + return isPRRevalidationOnly(response) + ? response + : normalizeGitHubPRForBranchOutcome(response) })() const outcome = await response.catch(() => { transportFailed = true return githubPRTransportFailureOutcome() }) - if (!checkContract.sourceCurrent()) { + if (!checkContract.sourceCurrent() || options?.signal?.aborted) { return cached?.data ?? null } + if (prRequestGenerations.get(cacheKey) === generation) { + const inflight = inflightPRRequests.get(cacheKey) + if (inflight?.generation === generation) { + inflight.outcome = outcome + } + } + if (isPRRevalidationOnly(outcome)) { + return get().prCache[cacheKey]?.data ?? null + } const pr = outcome.kind === 'found' ? outcome.pr : null let acceptedPR: PRInfo | null = null // RPC and lost IPC replies get no coordinator settlement; a lost reply is reported only to the click that asked, so polls stay silent. diff --git a/src/renderer/src/store/github/refresh/refresh-event-actions.ts b/src/renderer/src/store/github/refresh/refresh-event-actions.ts index 0feb59c1623..7a301f72c31 100644 --- a/src/renderer/src/store/github/refresh/refresh-event-actions.ts +++ b/src/renderer/src/store/github/refresh/refresh-event-actions.ts @@ -69,8 +69,14 @@ export const createRefreshEventActions = ( nextSequences[alias.cacheKey] ?? 0, prRefreshStartedLinkedReviewScopes.get(alias.cacheKey)?.sequence ?? 0 ) + const completesOwnedRequest = + event.status === 'skipped' && + event.sequence === previousSequence && + nextStates[alias.cacheKey]?.status === 'in-flight' if ( - event.outcome ? event.sequence < previousSequence : event.sequence <= previousSequence + event.outcome + ? event.sequence < previousSequence + : event.sequence <= previousSequence && !completesOwnedRequest ) { if (event.outcome || event.status !== 'in-flight') { deletePRRefreshStartedEntry(event.sequence, alias.cacheKey) diff --git a/src/renderer/src/store/github/requests/request-coordination.ts b/src/renderer/src/store/github/requests/request-coordination.ts index 311fc38181b..18d5d558c1f 100644 --- a/src/renderer/src/store/github/requests/request-coordination.ts +++ b/src/renderer/src/store/github/requests/request-coordination.ts @@ -1,6 +1,10 @@ import type { PRCheckContract } from '@/lib/source-control/checks/pr-check-observation-contract' import type { PRCheckDetail } from '../../../../../shared/github/checks/check-types' import type { PRComment } from '../../../../../shared/github/comments/comment-types' +import type { + GitHubPRRefreshReason, + PRSnapshotReply +} from '../../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { IssueInfo, PRInfo @@ -10,12 +14,18 @@ import type { GetProjectViewTableResult } from '../../../../../shared/github/pro import type { LinkedReviewClearScope } from '../pull-requests/linked-review-clear' import type { AppState } from '../../types' import { matchesRepoCacheEviction, type RepoCacheEviction } from '../cache/cache-identity' +import type { PromiseSettlementWaiters } from '../../../../../shared/promise-settlement-waiters' export type InflightPR = { promise: Promise + controller: AbortController + waiters: PromiseSettlementWaiters force: boolean generation: number lookupHintKey: string + reason?: GitHubPRRefreshReason + superseded?: boolean + outcome?: PRSnapshotReply } export type InflightChecks = { promise: Promise diff --git a/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.test.ts b/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.test.ts index 4b47d853ca1..1c362ed2503 100644 --- a/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.test.ts +++ b/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.test.ts @@ -40,6 +40,26 @@ describe('visible hosted review scheduler', () => { vi.useRealTimers() }) + it('retrieves a deferred completion with an ordinary timer read and resets on a head change', async () => { + const refresh = vi.fn(async () => ({ succeeded: true, retryAfterMs: 10_000 })) + const row = target({ fetchedAt: Date.now() - 120_000, refresh }) + const scheduler = setup([row]) + await vi.advanceTimersByTimeAsync(0) + expect(refresh.mock.calls[0]).toEqual([true, expect.any(AbortSignal), 'discovery']) + await vi.advanceTimersByTimeAsync(10_000) + expect(refresh.mock.calls[1]).toEqual([false, expect.any(AbortSignal), 'timer']) + scheduler.update([{ ...row, revision: 'new-head|' }]) + await vi.advanceTimersByTimeAsync(10_000) + expect(refresh.mock.calls[2]).toEqual([true, expect.any(AbortSignal), 'discovery']) + }) + + it('keeps successful same-age cache replies on the normal interval without a receipt', async () => { + const refresh = vi.fn(async () => ({ succeeded: true })) + setup([target({ fetchedAt: Date.now() - 120_000, refresh })]) + await vi.advanceTimersByTimeAsync(120_000) + expect(refresh.mock.calls[1]).toEqual([false, expect.any(AbortSignal), 'timer']) + }) + it.each(['remove', 'hide', 'dispose'])( 'aborts abandoned demand on %s without releasing native work early', async (action) => { @@ -77,3 +97,28 @@ describe('visible hosted review scheduler', () => { } ) }) + +it('limits refocus discovery to opted-in open GitHub rows and the existing stopped interval', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + const github = target({ + key: 'github', + fetchedAt: Date.now(), + intervalMs: 120_000, + refreshOnForeground: true + }) + const closed = target({ key: 'closed', fetchedAt: Date.now(), intervalMs: 900_000 }) + const other = target({ key: 'other', fetchedAt: Date.now(), intervalMs: 120_000 }) + const stopped = target({ key: 'stopped', fetchedAt: Date.now(), intervalMs: null }) + const scheduler = setup([github, closed, other, stopped]) + scheduler.setVisible(false) + await vi.advanceTimersByTimeAsync(130_000) + scheduler.setVisible(true) + await vi.advanceTimersByTimeAsync(0) + expect(github.refresh).toHaveBeenCalledWith(true, expect.any(AbortSignal), 'discovery') + expect(stopped.refresh).toHaveBeenCalledWith(true, expect.any(AbortSignal), 'discovery') + expect(closed.refresh).not.toHaveBeenCalled() + expect(other.refresh).toHaveBeenCalledWith(false, expect.any(AbortSignal), 'timer') + scheduler.dispose() + vi.useRealTimers() +}) diff --git a/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.ts b/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.ts index 4f0b05d4adc..56a05906ad1 100644 --- a/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.ts +++ b/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.ts @@ -7,15 +7,25 @@ export type VisibleHostedReviewRefreshTarget = { fetchedAt: number | null intervalMs: number | null selected: boolean - refresh: (force?: boolean, signal?: AbortSignal) => Promise + refreshOnForeground?: boolean + refresh: ( + force?: boolean, + signal?: AbortSignal, + intent?: 'discovery' | 'timer' + ) => Promise } +export type VisibleHostedReviewRefreshResult = + | boolean + | { succeeded: boolean; retryAfterMs?: number } + type Entry = { target: VisibleHostedReviewRefreshTarget lastAttemptAt: number failures: number retryAt: number | null discovery: boolean + deferredUntil: number | null } function discoveryIdentityChanged( @@ -56,6 +66,9 @@ export function createVisibleHostedReviewRefreshScheduler() { const dueAt = (entry: Entry): number => { const cooldown = entry.lastAttemptAt + REVIEW_REFRESH_COOLDOWN_MS + if (entry.deferredUntil !== null && !entry.discovery) { + return Math.max(cooldown, entry.deferredUntil) + } if (entry.retryAt !== null) { return Math.max(cooldown, entry.retryAt) } @@ -84,8 +97,9 @@ export function createVisibleHostedReviewRefreshScheduler() { key: string, startedAt: number, target: VisibleHostedReviewRefreshTarget, - succeeded: boolean + result: VisibleHostedReviewRefreshResult ): void => { + const succeeded = typeof result === 'boolean' ? result : result.succeeded const cancelled = inFlight.get(key)?.controller.signal.aborted inFlight.get(key)?.controller.abort() inFlight.delete(key) @@ -94,11 +108,17 @@ export function createVisibleHostedReviewRefreshScheduler() { } const entry = entries.get(key) ?? recent.get(key) if (entry && entry.lastAttemptAt === startedAt) { - if (cancelled) { + if (cancelled || discoveryIdentityChanged(target, entry.target)) { entry.discovery = true - } else if (!succeeded || !discoveryIdentityChanged(target, entry.target)) { + entry.deferredUntil = null + } else { entry.discovery = false entry.failures = succeeded ? 0 : entry.failures + 1 + const retry = typeof result === 'boolean' ? undefined : result.retryAfterMs + entry.deferredUntil = + succeeded && retry !== undefined && Number.isFinite(retry) && retry >= 0 + ? Date.now() + Math.max(REVIEW_REFRESH_COOLDOWN_MS, retry) + : null entry.retryAt = succeeded ? null : Date.now() + @@ -134,13 +154,14 @@ export function createVisibleHostedReviewRefreshScheduler() { continue } const force = entry.discovery || entry.failures > 0 || entry.target.fetchedAt === null + const intent = entry.discovery || entry.target.fetchedAt === null ? 'discovery' : 'timer' entry.lastAttemptAt = now entry.discovery = false const startedTarget = entry.target const controller = new AbortController() inFlight.set(key, { target: startedTarget, controller }) try { - void entry.target.refresh(force, controller.signal).then( + void entry.target.refresh(force, controller.signal, intent).then( (succeeded) => finish(key, now, startedTarget, succeeded), () => finish(key, now, startedTarget, false) ) @@ -192,11 +213,13 @@ export function createVisibleHostedReviewRefreshScheduler() { discovery: (previous !== undefined && discoveryIdentityChanged(previous.target, target)) || target.fetchedAt === null || - Date.now() - target.fetchedAt >= (target.intervalMs ?? 60_000) + Date.now() - target.fetchedAt >= (target.intervalMs ?? 60_000), + deferredUntil: null } entries.set(target.key, entry) } else if (discoveryIdentityChanged(entry.target, target)) { entry.discovery = true + entry.deferredUntil = null } else if ( (target.fetchedAt ?? -Infinity) > (entry.target.fetchedAt ?? -Infinity) && (!inFlight.has(target.key) || @@ -205,6 +228,7 @@ export function createVisibleHostedReviewRefreshScheduler() { entry.failures = 0 entry.retryAt = null entry.discovery = false + entry.deferredUntil = null } entry.target = target } @@ -216,6 +240,9 @@ export function createVisibleHostedReviewRefreshScheduler() { } visible = next if (!visible) { + for (const entry of entries.values()) { + entry.deferredUntil = null + } for (const request of inFlight.values()) { request.controller.abort() } @@ -223,8 +250,9 @@ export function createVisibleHostedReviewRefreshScheduler() { if (visible) { for (const entry of entries.values()) { if ( - entry.target.intervalMs === null && - Date.now() - (entry.target.fetchedAt ?? -Infinity) >= 60_000 + (entry.target.intervalMs === null || entry.target.refreshOnForeground === true) && + Date.now() - (entry.target.fetchedAt ?? -Infinity) >= + Math.max(60_000, entry.target.intervalMs ?? 60_000) ) { entry.discovery = true } diff --git a/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets.ts b/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets.ts index 8c4853d057b..bba964017ea 100644 --- a/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets.ts +++ b/src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets.ts @@ -25,6 +25,7 @@ import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' import { isWslHostOffForForge } from '../../../github/repositories/wsl-host-off-forge' +import type { PRSnapshotReply } from '../../../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' export function* getVisibleHostedReviewWorkspaces( state: AppState, @@ -180,13 +181,16 @@ export function getVisibleHostedReviewRefreshTargets( ? null : fetchedAt, selected, + refreshOnForeground: + !!runtime && knownGitHub && (review?.state === 'open' || review?.state === 'draft'), intervalMs: reviewRefreshIntervalMs({ state: review?.state, checksStatus: usePR ? prEntry.data?.checksStatus : hostedEntry?.data?.status, hasReview: review ? true : fetchedAt !== null ? false : null, selected }), - refresh: async (force = true) => { + refresh: async (force = true, signal, intent) => { + let outcome: PRSnapshotReply | undefined const before = getState() const beforeFetchedAt = knownGitHub ? before.prCache[candidate.cacheKey]?.fetchedAt @@ -194,7 +198,12 @@ export function getVisibleHostedReviewRefreshTargets( await (runtime ? before.fetchPRForBranch(candidate.repoPath, candidate.branch, { force: true, - reason: 'visible', + signal, + reason: (intent ? intent === 'discovery' : force) ? 'active' : 'swr', + selected, + onReadOutcome: (next) => { + outcome = next + }, repoId: candidate.repoId, repoOwnerExecutionHostId: getRepoExecutionHostId(candidate), worktreeId: id, @@ -214,6 +223,12 @@ export function getVisibleHostedReviewRefreshTargets( admissionTier: selected ? 'interactive' : 'background' })) const after = getState() + if (runtime && outcome) { + return { + succeeded: !('kind' in outcome) || outcome.kind !== 'upstream-error', + retryAfterMs: outcome.revalidation?.retryAfterMs + } + } const afterFetchedAt = knownGitHub ? after.prCache[candidate.cacheKey]?.fetchedAt : after.hostedReviewCache[key]?.fetchedAt diff --git a/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts b/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts index 51ef1ad4cca..d4c6d56f431 100644 --- a/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts +++ b/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts @@ -9,17 +9,24 @@ const session = vi.hoisted(() => { return { client, environment: { id: 'env-1', createdAt: 1 } } }) -vi.mock('./web-runtime-session', () => ({ - getClientForEnvironment: () => session.client, - manuallyDisconnectedEnvironmentIds: new Set(), - manuallyDisconnectedResponse: () => ({ ok: false }), - requireActiveEnvironment: () => session.environment, - resolveEnvironment: () => session.environment, - runtimeCallQueuePool: { enqueue: (_id: string, _method: string, run: () => unknown) => run() }, - updateEnvironmentFromResponse: () => undefined -})) +vi.mock('./web-runtime-session', async () => { + const { RuntimeRpcCallQueuePool } = await import('../../../../shared/runtime-rpc-call-queue') + return { + getClientForEnvironment: () => session.client, + manuallyDisconnectedEnvironmentIds: new Set(), + manuallyDisconnectedResponse: () => ({ ok: false }), + requireActiveEnvironment: () => session.environment, + resolveEnvironment: () => session.environment, + runtimeCallQueuePool: new RuntimeRpcCallQueuePool(), + updateEnvironmentFromResponse: () => undefined + } +}) -import { callEnvironmentEnvelope, callRuntimeResult } from './web-runtime-calls' +import { + callRuntimeEnvelope, + callEnvironmentEnvelope, + callRuntimeResult +} from './web-runtime-calls' import { RuntimeConnectionChangedBeforeSendError, RuntimeRpcCallError @@ -88,3 +95,21 @@ it('preserves runtime failure details for web callers', async () => { response: { error: { data: { reason: 'windows_drive' } } } }) }) + +it('routes both web callers timed PR waits away from status and action calls', async () => { + const release = Promise.withResolvers() + session.client.call.mockImplementation(async (_method, params) => { + if (params?.reason === 'swr') { + await release.promise + } + return { id: 'rpc', ok: true, result: 'current' } + }) + const first = callRuntimeEnvelope('github.prForBranch', { reason: 'swr' }) + const second = callEnvironmentEnvelope('env-1', 'github.prForBranch', { reason: 'swr' }) + await expect( + callEnvironmentEnvelope('env-1', 'github.prForBranch', { reason: 'manual' }) + ).resolves.toMatchObject({ result: 'current' }) + await expect(callRuntimeEnvelope('git.status')).resolves.toMatchObject({ result: 'current' }) + release.resolve() + await Promise.all([first, second]) +}) diff --git a/src/renderer/src/web/preload-api/web-runtime-calls.ts b/src/renderer/src/web/preload-api/web-runtime-calls.ts index e476a1d42af..8722c09b6f8 100644 --- a/src/renderer/src/web/preload-api/web-runtime-calls.ts +++ b/src/renderer/src/web/preload-api/web-runtime-calls.ts @@ -43,12 +43,19 @@ export async function callRuntimeEnvelope( if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { return manuallyDisconnectedResponse(environment) } - const response = await runtimeCallQueuePool.enqueue(environment.id, method, () => { - if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { - return Promise.resolve(manuallyDisconnectedResponse(environment)) - } - return getClientForEnvironment(environment).call(method, params, { timeoutMs }) - }) + const response = await runtimeCallQueuePool.enqueue( + environment.id, + method, + () => { + if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { + return Promise.resolve(manuallyDisconnectedResponse(environment)) + } + return getClientForEnvironment(environment).call(method, params, { timeoutMs }) + }, + 0, + undefined, + params + ) if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { return manuallyDisconnectedResponse(environment) } @@ -137,19 +144,26 @@ export async function callEnvironmentEnvelope( if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { return manuallyDisconnectedResponse(environment) } - const response = await runtimeCallQueuePool.enqueue(environment.id, method, () => { - assertPairing() - if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { - return Promise.resolve(manuallyDisconnectedResponse(environment)) - } - return callPinnedToRuntime( - getClientForEnvironment(environment), - method, - params, - timeoutMs, - expectedEnvironmentRuntimeId - ) - }) + const response = await runtimeCallQueuePool.enqueue( + environment.id, + method, + () => { + assertPairing() + if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { + return Promise.resolve(manuallyDisconnectedResponse(environment)) + } + return callPinnedToRuntime( + getClientForEnvironment(environment), + method, + params, + timeoutMs, + expectedEnvironmentRuntimeId + ) + }, + 0, + undefined, + params + ) if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { return manuallyDisconnectedResponse(environment) } diff --git a/src/renderer/src/web/preload-api/web-runtime-environments-api.ts b/src/renderer/src/web/preload-api/web-runtime-environments-api.ts index f1228dd392f..6be6c3b6916 100644 --- a/src/renderer/src/web/preload-api/web-runtime-environments-api.ts +++ b/src/renderer/src/web/preload-api/web-runtime-environments-api.ts @@ -1,3 +1,4 @@ +import { createWebRuntimeEnvironmentSubscriber } from './web-runtime-subscription' import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' import { createWebRuntimeSubscriptionApiControl, @@ -20,11 +21,9 @@ import { import { translate } from '@/i18n/i18n' import { translateHostAccessLinkError } from '@/lib/remote-pairing/remote-pairing-copy' import { - assertEnvironmentPairing, callEnvironmentEnvelope, callWebRuntimeEnvironment, - getWebRuntimeStatus, - pinnedWebSubscriptionOptions + getWebRuntimeStatus } from './web-runtime-calls' import { closeActiveRuntimeClients, @@ -36,10 +35,7 @@ import { removeActiveRuntimeEnvironment, requireActiveEnvironmentOrNull, resolveEnvironment, - webRuntimeState, - runtimeCallQueuePool, - updateEnvironmentFromResponse, - manuallyDisconnectedResponse + webRuntimeState } from './web-runtime-session' export function createRuntimeEnvironmentsApi(): PreloadApi['runtimeEnvironments'] { return { @@ -216,86 +212,6 @@ export function createRuntimeEnvironmentsApi(): PreloadApi['runtimeEnvironments' prepareBrowserClientHostPlacement: async () => ({ kind: 'server' }), call: callWebRuntimeEnvironment, ...createWebRuntimeSubscriptionApiControl(pendingSubscriptions), - subscribe: async ( - { - selector, - method, - params, - timeoutMs, - subscriptionId, - expectedEnvironmentPairingRevision, - expectedEnvironmentRuntimeId - }, - callbacks - ) => { - const environment = resolveEnvironment(selector) - assertEnvironmentPairing(selector, expectedEnvironmentPairingRevision) - const client = getClientForEnvironment(environment) - const controller = new AbortController() - if (subscriptionId) { - if (pendingSubscriptions.has(subscriptionId)) { - throw new Error('Subscription id already exists') - } - pendingSubscriptions.set(subscriptionId, { controller }) - } - let subscription - try { - subscription = await runtimeCallQueuePool.enqueue( - environment.id, - method, - () => { - assertEnvironmentPairing(selector, expectedEnvironmentPairingRevision) - if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { - throw new Error('runtime_manually_disconnected') - } - return client.subscribe( - method, - params, - { - ...callbacks, - onResponse: (response) => { - try { - assertEnvironmentPairing(selector, expectedEnvironmentPairingRevision) - } catch (error) { - callbacks.onError?.({ - code: 'runtime_environment_changed', - message: String(error) - }) - callbacks.onClose?.() - controller.abort() - return - } - const result = manuallyDisconnectedEnvironmentIds.has(environment.id) - ? manuallyDisconnectedResponse(environment) - : response - updateEnvironmentFromResponse(environment, result) - callbacks.onResponse(result) - } - }, - { - timeoutMs, - signal: controller.signal, - ...pinnedWebSubscriptionOptions( - selector, - expectedEnvironmentPairingRevision, - expectedEnvironmentRuntimeId - ) - } - ) - }, - 0, - controller.signal - ) - } finally { - if (subscriptionId && pendingSubscriptions.get(subscriptionId)?.controller === controller) { - pendingSubscriptions.delete(subscriptionId) - } - } - if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { - subscription.unsubscribe() - throw new Error('runtime_manually_disconnected') - } - return subscription - } + subscribe: createWebRuntimeEnvironmentSubscriber(pendingSubscriptions) } } diff --git a/src/renderer/src/web/preload-api/web-runtime-pr-subscription-queue.test.ts b/src/renderer/src/web/preload-api/web-runtime-pr-subscription-queue.test.ts new file mode 100644 index 00000000000..4291b757a40 --- /dev/null +++ b/src/renderer/src/web/preload-api/web-runtime-pr-subscription-queue.test.ts @@ -0,0 +1,85 @@ +import { expect, it, vi } from 'vitest' + +const session = vi.hoisted(() => ({ + environment: { id: 'env', createdAt: 1, runtimeId: 'runtime' }, + client: { connectionEpoch: 1, runtimeId: 'runtime', call: vi.fn(), subscribe: vi.fn() } +})) +vi.mock('./web-runtime-session', async () => { + const { RuntimeRpcCallQueuePool } = await import('../../../../shared/runtime-rpc-call-queue') + return { + closeActiveRuntimeClients: vi.fn(), + subscribeWebRuntimeStatus: vi.fn(), + readWebRuntimeStatusSnapshots: vi.fn(), + disconnectActiveRuntimeEnvironment: vi.fn(), + getClientForEnvironment: () => session.client, + manuallyDisconnectedEnvironmentIds: new Set(), + removeActiveRuntimeEnvironment: vi.fn(), + requireActiveEnvironment: () => session.environment, + requireActiveEnvironmentOrNull: () => session.environment, + resolveEnvironment: () => session.environment, + webRuntimeState: { activeEnvironment: session.environment }, + runtimeCallQueuePool: new RuntimeRpcCallQueuePool(), + updateEnvironmentFromResponse: vi.fn(), + manuallyDisconnectedResponse: vi.fn() + } +}) +import { createRuntimeEnvironmentsApi } from './web-runtime-environments-api' + +it('holds web signal-route slots through responses and releases queued and active cancellations', async () => { + const responseOrder: string[] = [] + const finish: (() => void)[] = [] + const closed = vi.fn() + session.client.subscribe.mockImplementation(async (_method, _params, callbacks) => { + finish.push(() => + callbacks.onResponse({ id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'runtime' } }) + ) + return { + unsubscribe: () => { + closed() + responseOrder.push('close') + callbacks.onClose?.() + }, + sendBinary: vi.fn() + } + }) + const api = createRuntimeEnvironmentsApi() + const start = (subscriptionId: string, reason: string, method = 'github.prForBranch') => + api.subscribe( + { + selector: 'env', + subscriptionId, + method, + params: { reason, selected: true }, + timeoutMs: 30_000 + }, + { onResponse: () => responseOrder.push('response') } + ) + const first = await start('timer-1', 'swr') + expect(session.client.subscribe.mock.calls[0][1]).toMatchObject({ reason: 'swr', selected: true }) + const second = await start('timer-2', 'swr') + const third = start('timer-3', 'swr') + const cancelled = expect(third).rejects.toThrow() + const manual = await start('manual', 'manual') + const status = await start('status', '', 'git.status') + const review = await start('review', '', 'hostedReview.forBranch') + expect(finish).toHaveLength(5) + await api.cancelSubscription({ subscriptionId: 'timer-3' }) + await cancelled + const fourth = start('timer-4', 'swr') + finish[0]() + const fourthHandle = await fourth + expect(finish).toHaveLength(6) + expect(responseOrder.slice(0, 2)).toEqual(['response', 'close']) + const fifth = start('timer-5', 'swr') + second.unsubscribe() + const fifthHandle = await fifth + expect(finish).toHaveLength(7) + first.unsubscribe() + fourthHandle.unsubscribe() + fifthHandle.unsubscribe() + manual.unsubscribe() + status.unsubscribe() + review.unsubscribe() + await Promise.resolve() + expect(closed).toHaveBeenCalledTimes(7) +}) diff --git a/src/renderer/src/web/preload-api/web-runtime-subscription.ts b/src/renderer/src/web/preload-api/web-runtime-subscription.ts new file mode 100644 index 00000000000..ea0c85dddde --- /dev/null +++ b/src/renderer/src/web/preload-api/web-runtime-subscription.ts @@ -0,0 +1,112 @@ +import type { PreloadApi } from '../../../../preload/api-types' +import { enqueueRuntimeSubscription } from '../../../../shared/runtime-rpc-subscription-queue' +import { isTimedPRRead } from '../../../../shared/runtime-rpc-call-queue' +import type { WebRuntimeSubscriptionRegistration } from './web-runtime-crew-subscription' +import { assertEnvironmentPairing, pinnedWebSubscriptionOptions } from './web-runtime-calls' +import { + resolveEnvironment, + getClientForEnvironment, + manuallyDisconnectedEnvironmentIds, + manuallyDisconnectedResponse, + runtimeCallQueuePool, + updateEnvironmentFromResponse +} from './web-runtime-session' + +export function createWebRuntimeEnvironmentSubscriber( + pendingSubscriptions: Map +): PreloadApi['runtimeEnvironments']['subscribe'] { + return async ( + { + selector, + method, + params, + timeoutMs, + subscriptionId, + expectedEnvironmentPairingRevision, + expectedEnvironmentRuntimeId + }, + callbacks + ) => { + const environment = resolveEnvironment(selector) + assertEnvironmentPairing(selector, expectedEnvironmentPairingRevision) + const client = getClientForEnvironment(environment) + const controller = new AbortController() + if (subscriptionId) { + if (pendingSubscriptions.has(subscriptionId)) { + throw new Error('Subscription id already exists') + } + pendingSubscriptions.set(subscriptionId, { controller }) + } + let subscription + try { + subscription = await enqueueRuntimeSubscription( + runtimeCallQueuePool, + environment.id, + method, + params, + (complete) => { + assertEnvironmentPairing(selector, expectedEnvironmentPairingRevision) + if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { + throw new Error('runtime_manually_disconnected') + } + return client.subscribe( + method, + params, + { + ...callbacks, + onError: (error) => { + complete() + callbacks.onError?.(error) + }, + onClose: () => { + complete() + callbacks.onClose?.() + }, + onResponse: (response) => { + complete() + try { + assertEnvironmentPairing(selector, expectedEnvironmentPairingRevision) + } catch (error) { + callbacks.onError?.({ + code: 'runtime_environment_changed', + message: String(error) + }) + callbacks.onClose?.() + controller.abort() + return + } + const result = manuallyDisconnectedEnvironmentIds.has(environment.id) + ? manuallyDisconnectedResponse(environment) + : response + updateEnvironmentFromResponse(environment, result) + callbacks.onResponse(result) + } + }, + { + timeoutMs, + signal: controller.signal, + ...pinnedWebSubscriptionOptions( + selector, + expectedEnvironmentPairingRevision, + expectedEnvironmentRuntimeId + ) + } + ) + }, + (handle) => handle.unsubscribe(), + controller.signal + ) + } finally { + if (subscriptionId && pendingSubscriptions.get(subscriptionId)?.controller === controller) { + pendingSubscriptions.delete(subscriptionId) + } + } + if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { + subscription.unsubscribe() + throw new Error('runtime_manually_disconnected') + } + return isTimedPRRead(method, params) + ? { ...subscription, unsubscribe: () => controller.abort() } + : subscription + } +} diff --git a/src/shared/github/pull-requests/refresh/pr-quiet-refresh.ts b/src/shared/github/pull-requests/refresh/pr-quiet-refresh.ts new file mode 100644 index 00000000000..3bb9101d790 --- /dev/null +++ b/src/shared/github/pull-requests/refresh/pr-quiet-refresh.ts @@ -0,0 +1,22 @@ +import type { PRInfo } from '../pull-request-types' + +export const QUIET_PR_REFRESH_INTERVAL_MS = 5 * 60_000 + +export function prChecksDone(pr: PRInfo): boolean { + return ( + pr.checksFinal === true || (pr.checksReadComplete === true && pr.checksSummary?.total === 0) + ) +} + +export function isQuietPR(pr: PRInfo, currentHeadOid: string | null): boolean { + return ( + (pr.state === 'open' || pr.state === 'draft') && + !!currentHeadOid && + pr.headSha === currentHeadOid && + pr.checksReadComplete === true && + prChecksDone(pr) && + (pr.mergeable === 'MERGEABLE' || pr.mergeable === 'CONFLICTING') && + pr.autoMergeEnabled === false && + pr.mergeQueueRequired === false + ) +} diff --git a/src/shared/github/pull-requests/refresh/pull-request-refresh-types.ts b/src/shared/github/pull-requests/refresh/pull-request-refresh-types.ts index bce9d7bac2d..734830dca3e 100644 --- a/src/shared/github/pull-requests/refresh/pull-request-refresh-types.ts +++ b/src/shared/github/pull-requests/refresh/pull-request-refresh-types.ts @@ -12,7 +12,7 @@ export type PRRefreshErrorType = | 'server_error' | 'unknown' -export type PRRefreshOutcome = +export type PRRefreshOutcome = ( | { kind: 'found'; pr: PRInfo; fetchedAt: number } | { kind: 'no-pr'; fetchedAt: number; rejectedPRUrls?: string[] } | { @@ -24,6 +24,27 @@ export type PRRefreshOutcome = nextAutoRetryAt?: number retryDisabledUntil?: number } +) & { revalidation?: { retryAfterMs: number } } + +export type PRRevalidationOnly = { revalidation: { invalidated: true; retryAfterMs: number } } +export type PRSnapshotReply = PRRefreshOutcome | PRRevalidationOnly + +export function isPRRevalidationOnly(value: unknown): value is PRRevalidationOnly { + if (!value || typeof value !== 'object' || 'kind' in value || !('revalidation' in value)) { + return false + } + const receipt = value.revalidation + return ( + !!receipt && + typeof receipt === 'object' && + 'invalidated' in receipt && + receipt.invalidated === true && + 'retryAfterMs' in receipt && + typeof receipt.retryAfterMs === 'number' && + Number.isFinite(receipt.retryAfterMs) && + receipt.retryAfterMs >= 0 + ) +} /** `watch` is host-only: a background read for a chat's CI lines, never sent by a client. */ export type GitHubPRRefreshReason = 'visible' | 'active' | 'post-push' | 'manual' | 'swr' | 'watch' diff --git a/src/shared/rpc-contract/github/github-pull-request-params.ts b/src/shared/rpc-contract/github/github-pull-request-params.ts index 925315ce91a..2573a5e20af 100644 --- a/src/shared/rpc-contract/github/github-pull-request-params.ts +++ b/src/shared/rpc-contract/github/github-pull-request-params.ts @@ -20,6 +20,8 @@ export const PrForBranch = RepoSelector.extend({ branch: requiredString('Missing branch'), reason: OptionalPRRefreshReason, userRefresh: z.boolean().optional(), + acceptRevalidationOnly: z.boolean().optional(), + selected: z.boolean().optional(), linkedPRNumber: z.number().int().positive().nullable().optional(), fallbackPRNumber: z.number().int().positive().nullable().optional(), acceptMergedFallbackPR: z.boolean().optional(), diff --git a/src/shared/runtime-rpc-call-queue.test.ts b/src/shared/runtime-rpc-call-queue.test.ts index 6c870dbdb3e..1d91d969cc6 100644 --- a/src/shared/runtime-rpc-call-queue.test.ts +++ b/src/shared/runtime-rpc-call-queue.test.ts @@ -245,3 +245,68 @@ describe('runtime RPC call queue', () => { ).resolves.toBe('recovered') }) }) + +it('keeps actions and status runnable while timed PR snapshots wait', async () => { + const pool = new RuntimeRpcCallQueuePool() + const release = Promise.withResolvers() + const started: string[] = [] + const timers = [0, 1, 2].map((row) => + pool.enqueue( + 'host', + 'github.prForBranch', + async () => { + started.push(`timer-${row}`) + await release.promise + }, + 0, + undefined, + { reason: 'swr' } + ) + ) + expect(started).toEqual(['timer-0', 'timer-1']) + for (const reason of ['manual', 'active', 'post-push', 'visible', undefined, 'swr']) { + await expect( + pool.enqueue('host', 'github.prForBranch', async () => 'current', 0, undefined, { + reason, + userRefresh: reason === 'swr' + }) + ).resolves.toBe('current') + } + await expect(pool.enqueue('host', 'git.status', async () => 'clean')).resolves.toBe('clean') + await expect(pool.enqueue('host', 'hostedReview.forBranch', async () => 'review')).resolves.toBe( + 'review' + ) + expect(started).toEqual(['timer-0', 'timer-1']) + release.resolve() + await Promise.all(timers) + expect(started).toEqual(['timer-0', 'timer-1', 'timer-2']) +}) + +it('shares pending and byte limits across ordinary and timed PR lanes and removes cancelled calls', async () => { + const pool = new RuntimeRpcCallQueuePool(1, 1, 1, 5, 4) + const release = Promise.withResolvers() + const active = pool.enqueue('host', 'github.prForBranch', () => release.promise, 1, undefined, { + reason: 'swr' + }) + const controller = new AbortController() + const queued = pool.enqueue( + 'host', + 'github.prForBranch', + async () => 'unused', + 1, + controller.signal, + { reason: 'swr' } + ) + await expect(pool.enqueue('host', 'git.status', async () => 'overflow')).rejects.toMatchObject({ + scope: 'selector' + }) + const cancelled = expect(queued).rejects.toMatchObject({ name: 'AbortError' }) + controller.abort() + await cancelled + await expect(pool.enqueue('host', 'git.status', async () => 'clean', 3)).resolves.toBe('clean') + await expect(pool.enqueue('host', 'git.status', async () => 'oversize', 4)).rejects.toMatchObject( + { scope: 'memory' } + ) + release.resolve() + await active +}) diff --git a/src/shared/runtime-rpc-call-queue.ts b/src/shared/runtime-rpc-call-queue.ts index 532d6241358..8a88ef672ec 100644 --- a/src/shared/runtime-rpc-call-queue.ts +++ b/src/shared/runtime-rpc-call-queue.ts @@ -53,6 +53,17 @@ export function isBackgroundRuntimeMethod(method: string): boolean { ) } +export function isTimedPRRead(method: string, params: unknown): boolean { + return ( + method === 'github.prForBranch' && + typeof params === 'object' && + params !== null && + 'reason' in params && + params.reason === 'swr' && + !('userRefresh' in params && params.userRefresh === true) + ) +} + // Slow worktree removal/model listing waits get a separate lane so foreground refresh/send slots remain free; // background slots belong to status. function isLongWaitRuntimeMethod(method: string): boolean { @@ -86,23 +97,38 @@ export class RuntimeRpcCallQueuePool { method: string, run: () => Promise, retainedBytes = 0, - signal?: AbortSignal + signal?: AbortSignal, + params?: unknown ): Promise { if (signal?.aborted) { return Promise.reject(abortSignalReason(signal)) } // Same concurrency bound, counted apart from the selector's other calls; global caps still apply. const bulkRead = isBulkReadRuntimeMethod(method) + const timedPR = isTimedPRRead(method, params) + const timedKey = `${selector}\u0000timed-pr` const queueKey = isLongWaitRuntimeMethod(method) ? `${selector}\u0000long-wait` : bulkRead ? `${selector}\u0000bulk-read` - : selector + : timedPR + ? timedKey + : selector if (this.queuedCallCount >= this.maxQueuedTotal) { return Promise.reject(new RuntimeRpcCallQueueOverloadError('global')) } const existingQueue = this.queues.get(queueKey) - if (existingQueue && this.queuedCount(existingQueue) >= this.maxQueuedPerSelector) { + const pending = (key: string): number => { + const queue = this.queues.get(key) + return queue ? this.queuedCount(queue) : 0 + } + const queued = + queueKey === selector || timedPR + ? pending(selector) + pending(timedKey) + : existingQueue + ? this.queuedCount(existingQueue) + : 0 + if (queued >= this.maxQueuedPerSelector) { return Promise.reject(new RuntimeRpcCallQueueOverloadError('selector')) } if ( @@ -115,11 +141,15 @@ export class RuntimeRpcCallQueuePool { const queue = this.getQueue( queueKey, - bulkRead ? Math.min(this.concurrency, REMOTE_RUNTIME_BULK_READ_CONCURRENCY) : this.concurrency + timedPR + ? Math.min(this.concurrency, 2) + : bulkRead + ? Math.min(this.concurrency, REMOTE_RUNTIME_BULK_READ_CONCURRENCY) + : this.concurrency ) return new Promise((resolve, reject) => { const call: QueuedRuntimeCall = { - background: isBackgroundRuntimeMethod(method), + background: !timedPR && isBackgroundRuntimeMethod(method), retainedBytes, run, resolve, diff --git a/src/shared/runtime-rpc-subscription-queue.test.ts b/src/shared/runtime-rpc-subscription-queue.test.ts new file mode 100644 index 00000000000..b47ed6eb628 --- /dev/null +++ b/src/shared/runtime-rpc-subscription-queue.test.ts @@ -0,0 +1,114 @@ +import { expect, it, vi } from 'vitest' +import { RuntimeRpcCallQueuePool } from './runtime-rpc-call-queue' +import { enqueueRuntimeSubscription } from './runtime-rpc-subscription-queue' + +it('shares timed occupancy with one-shot calls through first response and removes a queued abort', async () => { + const pool = new RuntimeRpcCallQueuePool() + const oneShot = Promise.withResolvers() + const running = pool.enqueue('host', 'github.prForBranch', () => oneShot.promise, 0, undefined, { + reason: 'swr' + }) + let respond = (): void => {} + const close = vi.fn() + const handle = await enqueueRuntimeSubscription( + pool, + 'host', + 'github.prForBranch', + { reason: 'swr' }, + async (complete) => { + respond = complete + return { close } + }, + (value) => value.close() + ) + const controller = new AbortController() + const sendThird = vi.fn(async () => ({ close })) + const third = enqueueRuntimeSubscription( + pool, + 'host', + 'github.prForBranch', + { reason: 'swr' }, + sendThird, + (value) => value.close(), + controller.signal + ) + const rejected = expect(third).rejects.toThrow() + await expect(pool.enqueue('host', 'git.status', async () => 'clean')).resolves.toBe('clean') + expect(sendThird).not.toHaveBeenCalled() + controller.abort() + await rejected + respond() + await Promise.resolve() + expect(close).toHaveBeenCalledOnce() + expect(handle).toEqual({ close }) + oneShot.resolve() + await running +}) + +it('releases a response before setup settles and closes its late handle', async () => { + const pool = new RuntimeRpcCallQueuePool() + const late = Promise.withResolvers<{ close: () => void }>() + const close = vi.fn() + const setup = enqueueRuntimeSubscription( + pool, + 'host', + 'github.prForBranch', + { reason: 'swr' }, + (complete) => { + complete() + return late.promise + }, + (value) => value.close() + ) + await expect( + pool.enqueue('host', 'github.prForBranch', async () => 'next', 0, undefined, { reason: 'swr' }) + ).resolves.toBe('next') + late.resolve({ close }) + await setup + expect(close).toHaveBeenCalledOnce() +}) + +it('cancels an active setup, closes its late handle, and recovers after setup rejection', async () => { + const pool = new RuntimeRpcCallQueuePool() + const late = Promise.withResolvers<{ close: () => void }>() + const close = vi.fn() + const controller = new AbortController() + const started = Promise.withResolvers() + const setup = enqueueRuntimeSubscription( + pool, + 'host', + 'github.prForBranch', + { reason: 'swr' }, + () => { + started.resolve() + return late.promise + }, + (value) => value.close(), + controller.signal + ) + const rejected = expect(setup).rejects.toThrow() + await started.promise + controller.abort() + await rejected + late.resolve({ close }) + await Promise.resolve() + await Promise.resolve() + expect(close).toHaveBeenCalledOnce() + await expect( + enqueueRuntimeSubscription( + pool, + 'host', + 'github.prForBranch', + { reason: 'swr' }, + async () => { + throw new Error('setup failed') + }, + (value: { close: () => void }) => value.close() + ) + ).rejects.toThrow('setup failed') + await expect( + pool.enqueue('host', 'github.prForBranch', async () => 'recovered', 0, undefined, { + reason: 'swr' + }) + ).resolves.toBe('recovered') +}) diff --git a/src/shared/runtime-rpc-subscription-queue.ts b/src/shared/runtime-rpc-subscription-queue.ts new file mode 100644 index 00000000000..a4978f042ed --- /dev/null +++ b/src/shared/runtime-rpc-subscription-queue.ts @@ -0,0 +1,77 @@ +import { abortSignalReason } from './abort-signal-reason' +import { isTimedPRRead, type RuntimeRpcCallQueuePool } from './runtime-rpc-call-queue' + +export function enqueueRuntimeSubscription( + pool: RuntimeRpcCallQueuePool, + selector: string, + method: string, + params: unknown, + open: (complete: () => void) => Promise, + close: (handle: T) => void, + signal?: AbortSignal, + retainedBytes = 0 +): Promise { + if (!isTimedPRRead(method, params)) { + return pool.enqueue(selector, method, () => open(() => {}), retainedBytes, signal, params) + } + const setup = Promise.withResolvers() + const completion = Promise.withResolvers() + let handle: T | undefined + let completed = false + const closeHandle = (value: T): void => { + try { + close(value) + } catch { + // Terminal cleanup must still release admission if transport close throws. + } + } + const complete = (): void => { + if (completed) { + return + } + completed = true + completion.resolve() + if (handle !== undefined) { + const terminalHandle = handle + queueMicrotask(() => closeHandle(terminalHandle)) + } + } + const onAbort = (): void => { + complete() + if (signal) { + setup.reject(abortSignalReason(signal)) + } + } + signal?.addEventListener('abort', onAbort, { once: true }) + void pool + .enqueue( + selector, + method, + async () => { + void Promise.resolve() + .then(() => open(complete)) + .then( + (opened) => { + handle = opened + if (completed) { + closeHandle(opened) + } + setup.resolve(opened) + }, + (error) => { + setup.reject(error) + complete() + } + ) + await completion.promise + }, + retainedBytes, + signal, + params + ) + .catch(setup.reject) + .finally(() => { + signal?.removeEventListener('abort', onAbort) + }) + return setup.promise +} diff --git a/tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts b/tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts new file mode 100644 index 00000000000..24610ba73a5 --- /dev/null +++ b/tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts @@ -0,0 +1,284 @@ +import { describe, expect, it, vi } from 'vitest' +import { + commands, + fixture, + found, + mocks, + rpcRead +} from '../../src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshot-test-harness' +import type { PRRefreshOutcome } from '../../src/shared/github/pull-requests/refresh/pull-request-refresh-types' + +describe('hosted PR receipt delivery', () => { + it('carries a real deferred reply through the visible target, store and scheduler to its completion', async () => { + const { + createTestStore, + makePRRefreshWorktree, + resetRemoteRuntimeMocks, + runtimeEnvironmentCall + } = await import('../../src/renderer/src/store/github/github-slice-test-harness') + const { getVisibleHostedReviewRefreshTargets } = + await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets') + const { createVisibleHostedReviewRefreshScheduler } = + await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler') + const { PrForBranch } = + await import('../../src/shared/rpc-contract/github/github-pull-request-params') + const readReceipt = (reason: 'active' | 'swr') => + commands.getRepoPRForBranch( + 'repo', + 'receipt', + 12, + null, + false, + 'head-a', + reason, + undefined, + undefined, + undefined, + true + ) + resetRemoteRuntimeMocks() + const store = createTestStore() + const seed = await readReceipt('active') + if (!('kind' in seed) || seed.kind !== 'found') { + throw new Error('expected the initial PR') + } + store.setState({ + repos: [ + { + id: 'repo', + path: '/repo', + kind: 'git', + executionHostId: 'runtime:env-1', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 0 + } + ], + worktreesByRepo: { + repo: [ + makePRRefreshWorktree({ + id: 'receipt-worktree', + repoId: 'repo', + branch: 'receipt', + head: 'head-a', + linkedPR: 12, + hostId: 'runtime:env-1', + runtimeOwnerEnvironmentId: 'env-1' + }) + ] + }, + detectedWorktreesByRepo: {}, + activeWorktreeId: 'receipt-worktree', + activeWorkspaceExecutionHostId: 'runtime:env-1', + visibleReviewWorktreeIds: ['receipt-worktree'], + prCache: { 'runtime:env-1::repo::receipt': { data: seed.pr, fetchedAt: 1_000 } } + }) + const reasons: string[] = [] + const replies: unknown[] = [] + runtimeEnvironmentCall.mockImplementation(async (args) => { + if (args.method !== 'github.prForBranch') { + throw new Error('unexpected fixture RPC') + } + const params = PrForBranch.parse(args.params) + expect(params).toMatchObject({ + repo: 'repo', + branch: 'receipt', + linkedPRNumber: 12, + currentHeadOid: 'head-a', + reason: 'swr', + acceptRevalidationOnly: true, + selected: true + }) + reasons.push(params.reason!) + const result = await rpcRead(args.params) + replies.push(result) + return { id: 'rpc', ok: true, result } + }) + const timerProvider = Promise.withResolvers() + const freshProvider = Promise.withResolvers() + mocks.resolve + .mockReturnValueOnce(timerProvider.promise) + .mockReturnValueOnce(freshProvider.promise) + const scheduler = createVisibleHostedReviewRefreshScheduler() + const update = () => + scheduler.update(getVisibleHostedReviewRefreshTargets(store.getState(), store.getState)) + const unsubscribe = store.subscribe(update) + try { + expect(getVisibleHostedReviewRefreshTargets(store.getState(), store.getState)).toMatchObject([ + { selected: true, intervalMs: 60_000, fetchedAt: 1_000 } + ]) + update() + scheduler.setVisible(true) + await vi.advanceTimersByTimeAsync(60_000) + // Fake timers defer the host's nested zero-delay drain to the next clock tick. + await vi.advanceTimersByTimeAsync(1) + expect(reasons).toEqual(['swr']) + expect(replies).toEqual([]) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + const otherClient = readReceipt('active') + await vi.advanceTimersByTimeAsync(0) + fixture.title = 'superseded provider result' + timerProvider.resolve(found()) + await vi.advanceTimersByTimeAsync(0) + expect(replies).toMatchObject([{ fetchedAt: 1_000, revalidation: { retryAfterMs: 10_000 } }]) + expect(store.getState().prCache['runtime:env-1::repo::receipt']?.data?.title).toBe('before') + expect(store.getState().prCache['runtime:env-1::repo::receipt']?.fetchedAt).toBe(1_000) + fixture.title = 'completed by another client' + freshProvider.resolve(found()) + await otherClient + await vi.advanceTimersByTimeAsync(9_999) + expect(reasons).toEqual(['swr']) + await vi.advanceTimersByTimeAsync(1) + expect(reasons).toEqual(['swr', 'swr']) + expect(store.getState().prCache['runtime:env-1::repo::receipt']?.data?.title).toBe( + 'completed by another client' + ) + expect(mocks.resolve).toHaveBeenCalledTimes(3) + } finally { + unsubscribe() + scheduler.dispose() + } + }) +}) + +it('applies data-bearing retry replies to both clients and sends selection after an unselected wait', async () => { + const seed = await commands.getRepoPRForBranch( + 'repo', + 'shared', + 12, + null, + false, + 'head-a', + 'active' + ) + if (!('kind' in seed) || seed.kind !== 'found') { + throw new Error('expected initial PR') + } + const clients: { + select: () => void + title: () => string | undefined + fetchedAt: () => number | undefined + dispose: () => void + }[] = [] + const selection: boolean[][] = [[], []] + const receipts: unknown[][] = [[], []] + const reasons: string[] = [] + for (let client = 0; client < 2; client += 1) { + // Separate module graphs retain each renderer's own request coalescer. + vi.resetModules() + const { + createTestStore, + makePRRefreshWorktree, + resetRemoteRuntimeMocks, + runtimeEnvironmentCall + } = await import('../../src/renderer/src/store/github/github-slice-test-harness') + const { getVisibleHostedReviewRefreshTargets } = + await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets') + const { createVisibleHostedReviewRefreshScheduler } = + await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler') + resetRemoteRuntimeMocks() + runtimeEnvironmentCall.mockImplementation(async (args) => { + if (args.method !== 'github.prForBranch') { + throw new Error('unexpected fixture RPC') + } + const { PrForBranch } = + await import('../../src/shared/rpc-contract/github/github-pull-request-params') + const params = PrForBranch.parse(args.params) + const requestClient = 'selector' in args && args.selector === 'env-client-0' ? 0 : 1 + reasons.push(params.reason ?? 'missing') + selection[requestClient].push(params.selected === true) + const result = await rpcRead(args.params) + receipts[requestClient].push(result) + return { id: 'rpc', ok: true, result } + }) + const store = createTestStore() + store.setState({ + repos: [ + { + id: 'repo', + path: '/repo', + kind: 'git', + executionHostId: `runtime:env-client-${client}`, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 0 + } + ], + worktreesByRepo: { + repo: [ + makePRRefreshWorktree({ + id: 'shared-worktree', + repoId: 'repo', + branch: 'shared', + head: 'head-a', + linkedPR: 12, + hostId: `runtime:env-client-${client}`, + runtimeOwnerEnvironmentId: `env-client-${client}` + }) + ] + }, + detectedWorktreesByRepo: {}, + activeWorktreeId: null, + activeWorkspaceExecutionHostId: `runtime:env-client-${client}`, + visibleReviewWorktreeIds: ['shared-worktree'], + prCache: { + [`runtime:env-client-${client}::repo::shared`]: { data: seed.pr, fetchedAt: seed.fetchedAt } + } + }) + const scheduler = createVisibleHostedReviewRefreshScheduler() + const update = () => + scheduler.update(getVisibleHostedReviewRefreshTargets(store.getState(), store.getState)) + const unsubscribe = store.subscribe(update) + update() + scheduler.setVisible(true) + clients.push({ + select: () => store.setState({ activeWorktreeId: 'shared-worktree' }), + title: () => + store.getState().prCache[`runtime:env-client-${client}::repo::shared`]?.data?.title, + fetchedAt: () => + store.getState().prCache[`runtime:env-client-${client}::repo::shared`]?.fetchedAt, + dispose: () => { + unsubscribe() + scheduler.dispose() + } + }) + } + try { + // A second client's fresh result can settle in the same millisecond as the first. + fixture.title = 'changed on another client' + await commands.getRepoPRForBranch('repo', 'shared', 12, null, false, 'head-a', 'active') + mocks.gate.mockResolvedValue(181_000) + await vi.advanceTimersByTimeAsync(120_001) + // The first job learns the quota pause after admission, so its wait ends at the response deadline. + await vi.advanceTimersByTimeAsync(25_000) + expect(selection).toEqual([[false], [false]]) + for (let client = 0; client < 2; client += 1) { + expect(receipts[client]).toMatchObject([ + { + kind: 'found', + pr: { title: 'changed on another client' }, + revalidation: { retryAfterMs: expect.any(Number) } + } + ]) + expect(clients[client].title()).toBe('changed on another client') + expect(clients[client].fetchedAt()).toBe(1_000) + clients[client].select() + } + mocks.gate.mockResolvedValue(null) + await vi.advanceTimersByTimeAsync(70_000) + expect(selection).toEqual([ + [false, true], + [false, true] + ]) + expect(reasons).toEqual(['swr', 'swr', 'swr', 'swr']) + for (const client of clients) { + expect(client.title()).toBe('changed on another client') + expect(client.fetchedAt()).toBe(181_000) + } + expect(mocks.resolve).toHaveBeenCalledTimes(3) + } finally { + for (const client of clients) { + client.dispose() + } + } +}) diff --git a/tests/e2e/pr-refresh-actual-completion.unit.test.ts b/tests/e2e/pr-refresh-actual-completion.unit.test.ts new file mode 100644 index 00000000000..eb2031837bc --- /dev/null +++ b/tests/e2e/pr-refresh-actual-completion.unit.test.ts @@ -0,0 +1,389 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createStore } from 'zustand/vanilla' +import type { AppState } from '../../src/renderer/src/store/types' +import type { + GitHubPRRefreshEvent, + PRRefreshOutcome, + PRSnapshotReply +} from '../../src/shared/github/pull-requests/refresh/pull-request-refresh-types' +import { + makeCandidate, + makePR +} from '../../src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-harness' + +const mocks = vi.hoisted(() => ({ resolve: vi.fn(), send: vi.fn(), gate: vi.fn() })) +vi.mock('../../src/main/github/client/lookup/branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: mocks.resolve +})) +vi.mock('../../src/main/github/accounts/github-project-account', () => ({ + githubPRPolicyProjects: () => ({ source: null, selection: 0 }), + resolveGitHubProjectAccount: () => null +})) +vi.mock('../../src/main/github/execution/github-operation-slots', () => ({ + acquire: async () => {}, + release: () => {} +})) +vi.mock('../../src/main/github/pull-requests/refresh/pr-refresh-rate-limit-gate', () => ({ + prRefreshRateLimitPausedUntil: mocks.gate +})) +vi.mock('../../src/main/github/pull-requests/refresh/pr-refresh-renderer-port', () => ({ + prRefreshRenderers: () => ({ isRendererOpen: () => true, sendToTrustedUI: mocks.send }) +})) + +let context: Awaited> +beforeEach(async () => { + vi.resetModules() + vi.useFakeTimers() + vi.setSystemTime(1_000) + mocks.resolve.mockReset() + mocks.send.mockReset() + mocks.gate.mockReset().mockResolvedValue(null) + context = await fixture() +}) +afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +async function fixture() { + const { createGitHubSlice } = await import('../../src/renderer/src/store/github/github') + const coordinator = + await import('../../src/main/github/pull-requests/refresh/pr-refresh-coordinator') + const { RuntimeHostedReviewCommands } = + await import('../../src/main/runtime/integrations/reviews/runtime-hosted-review-commands') + const candidate = makeCandidate({ + cacheKey: 'repo::feature/test', + repoId: 'repo', + currentHeadOid: 'head-sha' + }) + const repo = { + id: 'repo', + path: '/repo', + kind: 'git' as const, + displayName: 'repo', + badgeColor: '', + addedAt: 0 + } + const commands = new RuntimeHostedReviewCommands({ + resolveRepo: async () => repo, + resolveTarget: async () => ({ repo, repoPath: repo.path }), + getExecutionOptions: () => undefined, + recordCreated: () => {} + }) + const store = createStore()((set, get, api) => ({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture supplies only the state read by real PR event application. + ...({ + settings: {}, + repos: [repo], + worktreesByRepo: { + repo: [{ id: 'wt-1', repoId: 'repo', branch: candidate.branch, head: 'head-sha' }] + }, + prCache: {}, + hostedReviewCache: {}, + prRefreshStates: {}, + prRefreshSequences: {} + } as unknown as AppState), + ...createGitHubSlice(set, get, api) + })) + mocks.send.mockImplementation((_channel, event: GitHubPRRefreshEvent) => { + store.getState().applyGitHubPRRefreshEvent(event) + }) + vi.stubGlobal('window', { + api: { + gh: { + refreshPRNow: (args: Parameters[0]) => + coordinator.refreshPRNow(args.candidate, args.reason, { userRefresh: args.userRefresh }) + } + } + }) + const foreground = (forced = false) => + commands.getRepoPRForBranch( + 'repo', + candidate.branch, + null, + null, + false, + 'head-sha', + 'active', + forced + ) + const found = (title: string): PRRefreshOutcome => ({ + kind: 'found', + fetchedAt: Date.now(), + pr: makePR({ title }) + }) + return { coordinator, candidate, store, foreground, found } +} + +it.each(['queued', 'immediate'] as const)( + 'delivers the accepted external result after a rejected late %s completion', + async (origin) => { + const { coordinator, candidate, store, foreground, found } = context + const old = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(old.promise).mockImplementation(async () => found('current')) + coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) + let immediate: Promise | undefined + if (origin === 'immediate') { + immediate = coordinator.refreshPRNow(candidate, 'active') + } + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(5_000) + await expect(foreground(origin === 'immediate')).resolves.toMatchObject({ + fetchedAt: 5_000, + pr: { title: 'current' } + }) + vi.setSystemTime(6_000) + old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) + await immediate + await vi.advanceTimersByTimeAsync(0) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 5_000, + data: { title: 'current' } + }) + expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).not.toBe('in-flight') + const { preparePRBranchRead } = + await import('../../src/main/github/client/lookup/pr-for-branch-outcome') + const prepared = await preparePRBranchRead('/repo', candidate.branch, null, null, null, { + currentHeadOid: 'head-sha' + }) + expect(prepared.cached()?.outcome).toMatchObject({ fetchedAt: 5_000, pr: { title: 'current' } }) + mocks.resolve.mockImplementation(async () => found('next ordinary read')) + await vi.advanceTimersByTimeAsync(118_999) + expect(store.getState().prCache[candidate.cacheKey]?.data?.title).toBe('current') + await vi.advanceTimersByTimeAsync(1) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 125_000, + data: { title: 'next ordinary read' } + }) + } +) + +it('keeps the accepted external failure and gate when the old local success completes', async () => { + const { coordinator, candidate, store, foreground, found } = context + const old = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(old.promise).mockImplementation(async () => ({ + kind: 'upstream-error', + fetchedAt: Date.now(), + errorType: 'rate_limited', + message: 'wait', + retryDisabledUntil: 305_000 + })) + coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(5_000) + await expect(foreground()).resolves.toMatchObject({ errorType: 'rate_limited' }) + vi.setSystemTime(6_000) + old.resolve(found('obsolete')) + await vi.advanceTimersByTimeAsync(0) + expect(store.getState().prCache[candidate.cacheKey]?.data).toBeUndefined() + expect(store.getState().prRefreshStates[candidate.cacheKey]).toMatchObject({ + status: 'error', + retryDisabledUntil: 305_000, + nextAutoRetryAt: 305_000 + }) + await expect(coordinator.refreshPRNow(candidate)).resolves.toMatchObject({ + errorType: 'rate_limited' + }) + mocks.resolve.mockImplementation(async () => found('after gate')) + await vi.advanceTimersByTimeAsync(298_999) + expect(store.getState().prCache[candidate.cacheKey]?.data).toBeUndefined() + await vi.advanceTimersByTimeAsync(1) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 305_000, + data: { title: 'after gate' } + }) +}) + +it.each(['queued', 'immediate'] as const)( + 'finishes rejected %s loading and later delivers the pending actual result', + async (origin) => { + const { coordinator, candidate, store, foreground, found } = context + const old = Promise.withResolvers() + const fresh = Promise.withResolvers() + mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) + coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) + const immediate = origin === 'immediate' ? coordinator.refreshPRNow(candidate, 'active') : null + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(5_000) + const external = foreground(origin === 'immediate') + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(6_000) + old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) + if (immediate) { + await expect(immediate).resolves.toEqual({ + revalidation: { invalidated: true, retryAfterMs: 10_000 } + }) + } + await vi.advanceTimersByTimeAsync(0) + expect(store.getState().prCache[candidate.cacheKey]).toBeUndefined() + expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).toBe('skipped') + await vi.advanceTimersByTimeAsync(1_000) + fresh.resolve(found('current')) + await external + await vi.advanceTimersByTimeAsync(4_000) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 7_000, + data: { title: 'current' } + }) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + } +) + +it('keeps rejected raw data out of the actual local action reply writer', async () => { + const { coordinator, candidate, store, foreground, found } = context + const old = Promise.withResolvers() + const fresh = Promise.withResolvers() + store.setState({ + prCache: { [candidate.cacheKey]: { fetchedAt: 500, data: makePR({ title: 'displayed' }) } } + }) + mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) + coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) + const action = store.getState().fetchPRForBranch('/repo', candidate.branch, { + repoId: 'repo', + worktreeId: 'wt-1', + reason: 'active', + force: true + }) + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(5_000) + const external = foreground(true) + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(6_000) + old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) + await expect(action).resolves.toMatchObject({ title: 'displayed' }) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 500, + data: { title: 'displayed' } + }) + expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).not.toBe('in-flight') + await vi.advanceTimersByTimeAsync(1_000) + fresh.resolve(found('current')) + await external + await vi.advanceTimersByTimeAsync(4_000) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 500, + data: { title: 'displayed' } + }) + await vi.advanceTimersByTimeAsync(109_499) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 500, + data: { title: 'displayed' } + }) + await vi.advanceTimersByTimeAsync(1) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: 7_000, + data: { title: 'current' } + }) +}) + +it.each([ + { duringQuota: false, retryAt: 307_000, failureAt: 7_000, remaining: 295_999 }, + { duringQuota: true, retryAt: 312_000, failureAt: 12_000, remaining: 299_999 } +])( + 'honors a later actual Retry-After error (during quota: $duringQuota)', + async ({ duringQuota, retryAt, failureAt, remaining }) => { + const { coordinator, candidate, store, foreground, found } = context + const old = Promise.withResolvers() + const fresh = Promise.withResolvers() + const observe = vi.fn() + const remove = coordinator.addPRRefreshOutcomeObserver(observe) + mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) + try { + coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(5_000) + const external = foreground() + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(6_000) + old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) + await vi.advanceTimersByTimeAsync(0) + expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).toBe('skipped') + const quota = Promise.withResolvers() + if (duringQuota) { + mocks.gate.mockReturnValueOnce(quota.promise) + await vi.advanceTimersByTimeAsync(6_000) + expect(mocks.gate).toHaveBeenCalledTimes(2) + } else { + await vi.advanceTimersByTimeAsync(1_000) + } + fresh.reject(new Error('HTTP 429: secondary rate limit\nRetry-After: 300')) + await expect(external).resolves.toMatchObject({ + errorType: 'rate_limited', + fetchedAt: failureAt, + retryDisabledUntil: retryAt + }) + mocks.resolve.mockImplementation(async () => found('after actual gate')) + if (duringQuota) { + quota.resolve(null) + await vi.advanceTimersByTimeAsync(0) + } else { + await vi.advanceTimersByTimeAsync(4_000) + } + expect(mocks.resolve).toHaveBeenCalledTimes(2) + expect(observe).toHaveBeenCalledTimes(1) + expect(store.getState().prRefreshStates[candidate.cacheKey]).toMatchObject({ + status: 'error', + nextAutoRetryAt: retryAt, + retryDisabledUntil: retryAt + }) + await vi.advanceTimersByTimeAsync(remaining) + expect(mocks.resolve).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ + fetchedAt: retryAt, + data: { title: 'after actual gate' } + }) + expect(mocks.resolve).toHaveBeenCalledTimes(3) + expect(observe).toHaveBeenCalledTimes(2) + } finally { + remove() + } + } +) + +it('restores an overdue watch turn after one ordinary actual read', async () => { + const { coordinator, found } = context + vi.setSystemTime(241_000) + const starts: string[] = [] + mocks.resolve.mockImplementation(async ({ branchName }) => { + starts.push(branchName) + return found('current') + }) + const candidate = (branch: string) => + makeCandidate({ + branch, + cacheKey: `/repo::${branch}`, + currentHeadOid: 'head-sha' + }) + coordinator.schedulePRWatchRead({ prKey: 'github.com/acme/repo#1' }, candidate('watch-a'), 1_000) + coordinator.schedulePRWatchRead({ prKey: 'github.com/acme/repo#2' }, candidate('watch-b'), 2_000) + coordinator.reportVisiblePRRefreshCandidates( + [candidate('ordinary-a'), candidate('ordinary-b')], + 1, + 1 + ) + await vi.advanceTimersByTimeAsync(20_000) + expect(starts).toEqual(['watch-a', 'ordinary-a', 'watch-b']) +}) + +it('admits only the still-owned equal-sequence terminal event', () => { + const { store, candidate } = context + const aliases = [candidate] + const apply = store.getState().applyGitHubPRRefreshEvent + apply({ aliases, reason: 'active', sequence: 1, status: 'in-flight', requestStartedAt: 1_000 }) + apply({ aliases, reason: 'active', sequence: 2, status: 'in-flight', requestStartedAt: 2_000 }) + apply({ aliases, reason: 'active', sequence: 1, status: 'skipped', skippedReason: 'fresh' }) + expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).toBe('in-flight') + apply({ + aliases, + reason: 'active', + sequence: 2, + outcome: { kind: 'upstream-error', errorType: 'network', fetchedAt: 3_000, message: 'offline' } + }) + apply({ aliases, reason: 'active', sequence: 2, status: 'skipped', skippedReason: 'fresh' }) + expect(store.getState().prRefreshStates[candidate.cacheKey]).toMatchObject({ + status: 'error', + message: 'offline' + }) +}) diff --git a/tests/e2e/runtime-hosted-pr-snapshots-perf.unit.test.ts b/tests/e2e/runtime-hosted-pr-snapshots-perf.unit.test.ts new file mode 100644 index 00000000000..db4bd7080c0 --- /dev/null +++ b/tests/e2e/runtime-hosted-pr-snapshots-perf.unit.test.ts @@ -0,0 +1,247 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { makePR } from '../../src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-harness' +import type { PRRefreshOutcome } from '../../src/shared/github/pull-requests/refresh/pull-request-refresh-types' +import type { VisibleHostedReviewRefreshTarget as Target } from '../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler' +import type { RuntimeHostedReviewCommands } from '../../src/main/runtime/integrations/reviews/runtime-hosted-review-commands' + +const mocks = vi.hoisted(() => ({ resolve: vi.fn(), account: vi.fn(), gate: vi.fn() })) +vi.mock('../../src/main/github/accounts/github-project-account', () => ({ + githubPRPolicyProjects: () => ({ source: null, selection: String(mocks.account()) }), + resolveGitHubProjectAccount: mocks.account +})) +vi.mock('../../src/main/github/execution/github-operation-slots', () => ({ + acquire: async () => {}, + release: () => {} +})) +vi.mock('../../src/main/github/client/lookup/branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: mocks.resolve +})) +vi.mock('../../src/main/github/pull-requests/refresh/pr-refresh-rate-limit-gate', () => ({ + prRefreshRateLimitPausedUntil: mocks.gate +})) + +let commands: RuntimeHostedReviewCommands +let title = 'before' +const found = (): PRRefreshOutcome => ({ + kind: 'found', + fetchedAt: Date.now(), + pr: makePR({ + title, + headSha: 'head-a', + checksStatus: 'success', + checksReadComplete: true, + checksFinal: true, + autoMergeEnabled: false, + mergeQueueRequired: false + }) +}) +const read = async ( + branch: string, + reason: 'active' | 'visible' | 'swr' | 'manual' = 'swr', + head = 'head-a' +): Promise => { + const reply = await commands.getRepoPRForBranch( + 'repo', + branch, + null, + null, + false, + head, + reason, + undefined, + undefined, + undefined, + true + ) + if (!('kind' in reply)) { + throw new Error('Stable benchmark ownership was invalidated') + } + return reply +} + +beforeEach(async () => { + vi.resetModules() + vi.useFakeTimers() + vi.setSystemTime(1_000) + title = 'before' + mocks.resolve.mockReset().mockImplementation(async () => found()) + mocks.account.mockReset().mockReturnValue(null) + mocks.gate.mockReset().mockResolvedValue(null) + const { RuntimeHostedReviewCommands: Commands } = + await import('../../src/main/runtime/integrations/reviews/runtime-hosted-review-commands') + const repo = { + id: 'repo', + path: '/repo', + kind: 'git' as const, + displayName: 'repo', + badgeColor: 'blue', + addedAt: 0 + } + commands = new Commands({ + resolveRepo: async () => repo, + resolveTarget: async () => ({ repo, repoPath: repo.path }), + getExecutionOptions: () => undefined, + recordCreated: () => {} + }) +}) +afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() +}) + +it.each([ + { rows: 14, clients: 2 }, + { rows: 14, clients: 20 }, + { rows: 140, clients: 2 } +])( + 'bounds shared polling for $rows rows and $clients clients over thirty minutes', + async ({ rows, clients }) => { + const { createVisibleHostedReviewRefreshScheduler } = + await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler') + const start = Date.now() + const spans: { branch: string; startedAt: number; completedAt: number }[] = [] + const deliveries: number[] = [] + const admissionDelays: number[] = [] + const pendingDemand = new Map() + const settledAt: number[] = [] + let requests = 0 + let receipts = 0 + mocks.resolve.mockImplementation(async ({ branchName }) => { + const startedAt = Date.now() + const demand = pendingDemand.get(branchName) + if (demand !== undefined) { + admissionDelays.push(startedAt - demand) + } + pendingDemand.delete(branchName) + // ast-grep-ignore: test-no-real-time-wait -- Fake-clock provider delay exercises host admission and completion. + await new Promise((resolve) => setTimeout(resolve, 1_000)) + const pending = Number(branchName.slice(4)) < 2 && Date.now() - start < 600_000 + const outcome: PRRefreshOutcome = { + kind: 'found', + fetchedAt: Date.now(), + pr: makePR({ + title: pending ? 'running' : 'settled', + headSha: 'head-a', + checksStatus: pending ? 'pending' : 'success', + checksReadComplete: true, + checksFinal: !pending, + autoMergeEnabled: false, + mergeQueueRequired: false + }) + } + spans.push({ branch: branchName, startedAt, completedAt: Date.now() }) + return outcome + }) + const warm = Promise.all(Array.from({ length: rows }, (_, i) => read(`row-${i}`, 'active'))) + await vi.advanceTimersByTimeAsync(1_000) + const initial = await warm + const schedulers = Array.from({ length: clients }, (_, client) => { + const scheduler = createVisibleHostedReviewRefreshScheduler() + const cache = initial.map((outcome) => outcome.fetchedAt) + const delivered = new Set(initial.map((outcome, row) => `${row}:${outcome.fetchedAt}`)) + const sawSettled = new Set() + const targets = (): Target[] => + cache.map((fetchedAt, row) => ({ + key: `row-${row}`, + revision: 'head-a', + fetchedAt, + intervalMs: row === 0 ? 60_000 : 120_000, + selected: row === 0, + refresh: async (_force, signal, intent) => { + requests += 1 + const branch = `row-${row}` + if (!pendingDemand.has(branch)) { + pendingDemand.set(branch, Date.now()) + } + const outcome = await commands.getRepoPRForBranch( + 'repo', + `row-${row}`, + null, + null, + false, + 'head-a', + intent === 'discovery' ? 'active' : 'swr', + false, + undefined, + signal, + true + ) + if (!('kind' in outcome)) { + throw new Error('Stable benchmark ownership was invalidated') + } + if (outcome.kind !== 'upstream-error') { + cache[row] = outcome.fetchedAt + if (outcome.revalidation) { + receipts += 1 + } else { + pendingDemand.delete(branch) + const completion = `${row}:${outcome.fetchedAt}` + if (!delivered.has(completion)) { + delivered.add(completion) + deliveries.push(Date.now() - outcome.fetchedAt) + } + if ( + outcome.kind === 'found' && + row < 2 && + outcome.pr.title === 'settled' && + !sawSettled.has(row) + ) { + sawSettled.add(row) + settledAt.push(Date.now() - start - 600_000) + } + } + scheduler.update(targets()) + } + return { + succeeded: outcome.kind !== 'upstream-error', + retryAfterMs: outcome.revalidation?.retryAfterMs + } + } + })) + scheduler.update(targets()) + setTimeout(() => scheduler.setVisible(true), (client % 2) * 5_000) + return scheduler + }) + await vi.advanceTimersByTimeAsync(30 * 60_000) + for (const scheduler of schedulers) { + scheduler.dispose() + } + const atHide = spans.length + await vi.advanceTimersByTimeAsync(6 * 60_000) + const drained = spans.length + await vi.advanceTimersByTimeAsync(5 * 60_000) + expect(spans.length).toBe(drained) + // Timers share one twenty-start/five-minute budget, independent of client multiplicity. + const timed = spans.slice(rows) + for (const span of timed) { + expect( + timed.filter( + (other) => other.startedAt > span.startedAt - 300_000 && other.startedAt <= span.startedAt + ).length + ).toBeLessThanOrEqual(20) + } + expect(timed.length).toBeLessThanOrEqual(140) + expect( + spans.some((span) => span.branch === 'row-0' && span.completedAt - start >= 600_000) + ).toBe(true) + console.info( + 'SERVE_PR_BENCH', + JSON.stringify({ + clients, + rows, + simulatedMinutes: 30, + providerReads: spans.length, + atHide, + drainedAfterHide: drained - atHide, + snapshotRequests: requests, + deferredReceipts: receipts, + maxProviderMs: Math.max(...spans.map((s) => s.completedAt - s.startedAt)), + maxCompletionToFirstClientApplicationMs: Math.max(0, ...deliveries), + maxAdmissionDelayMs: Math.max(0, ...admissionDelays), + settledRunningRowsApplied: settledAt.length, + maxCiFinishToApplicationMs: Math.max(0, ...settledAt) + }) + ) + }, + 60_000 +) From 9f956312e38ba04b9a971b3ebc9b7b0068edb7bc Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:33:59 -0800 Subject: [PATCH 08/52] perf(hooks): skip lint-staged's serial worktree walks in pre-commit (#42184) lint-staged 16.4.0 walks the whole worktree several times before any linter runs. On a cold stat cache that made small commits take over a minute. Extend the existing lint-staged patch: - getDeletedFiles: replace the serial `ls-files --deleted` with `diff-files -D` (parallel preload, fsmonitor bypassed) plus assume-unchanged entries, filtered by the same lstat rule, so the deleted-file contract is unchanged. - getUnstagedFiles: `status --untracked-files=no`; the `??` lines were already discarded. - config discovery: list tracked config files only. A nested config must be tracked or staged to apply; untracked configs at the repo root are still found. Run lint-staged directly from the hook; husky already puts node_modules/.bin on PATH, so `pnpm exec` only added startup time. --- .husky/pre-commit | 2 +- config/patches/lint-staged@16.4.0.patch | 81 ++++++++++++++++++++++++- pnpm-lock.yaml | 6 +- 3 files changed, 82 insertions(+), 7 deletions(-) diff --git a/.husky/pre-commit b/.husky/pre-commit index 26fc3643d41..980f430682f 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,2 +1,2 @@ #!/usr/bin/env sh -pnpm exec lint-staged +lint-staged diff --git a/config/patches/lint-staged@16.4.0.patch b/config/patches/lint-staged@16.4.0.patch index cd5bcf57740..e0e933f1de3 100644 --- a/config/patches/lint-staged@16.4.0.patch +++ b/config/patches/lint-staged@16.4.0.patch @@ -1,5 +1,5 @@ diff --git a/lib/gitWorkflow.js b/lib/gitWorkflow.js -index 3a32d6a9cd65c7ecb6b3cbccfce5a15c96530435..363513128bf7302eab73ea775102bb8a633a3b8b 100644 +index 3a32d6a9cd65c7ecb6b3cbccfce5a15c96530435..f91b1931224ce59df5cf9880248d4fad93e74f03 100644 --- a/lib/gitWorkflow.js +++ b/lib/gitWorkflow.js @@ -50,6 +50,9 @@ export const STASH = 'lint-staged automatic backup' @@ -39,7 +39,66 @@ index 3a32d6a9cd65c7ecb6b3cbccfce5a15c96530435..363513128bf7302eab73ea775102bb8a /** Print stash list with short hash and subject */ const stashes = await this.execGit(['stash', 'list', '--format="%h %s"', '-z']) .then(parseGitZOutput) -@@ -270,11 +286,14 @@ export class GitWorkflow { +@@ -142,11 +158,44 @@ export class GitWorkflow { + */ + async getDeletedFiles() { + debugLog('Getting deleted files...') +- const lsFiles = await this.execGit(['ls-files', '--deleted']) +- const deletedFiles = lsFiles +- .split('\n') +- .filter(Boolean) +- .map((file) => path.resolve(this.topLevelDir, file)) ++ // Orca patch: `ls-files --deleted` lstat()s every tracked file one at a time, which takes tens ++ // of seconds when the stat cache is cold. `diff-files` reads the index with parallel lstat ++ // (preload) instead. Like `ls-files --deleted`, it must not trust an fsmonitor (a stale one ++ // would hide a deletion), so the monitor is turned off for this read-only query. It does ++ // trust the assume-unchanged bit, so those entries (lowercase `ls-files -v` tag; `s` is also ++ // skip-worktree, which `--deleted` skips) are added as candidates. A candidate counts only ++ // if lstat() fails, which is the `--deleted` rule. ++ const [diffOutput, taggedOutput] = await Promise.all([ ++ this.execGit([ ++ '-c', ++ 'core.fsmonitor=false', ++ 'diff-files', ++ '--name-only', ++ '--diff-filter=D', ++ '--no-renames', ++ '--no-relative', ++ '--ignore-submodules=none', ++ '-z', ++ ]), ++ this.execGit(['ls-files', '-v', '-z']), ++ ]) ++ const assumeUnchanged = parseGitZOutput(taggedOutput).flatMap((line) => ++ /^[a-rt-z] /.test(line) ? [line.slice(2)] : [] ++ ) ++ const candidates = new Set( ++ [...parseGitZOutput(diffOutput), ...assumeUnchanged].map((file) => ++ path.resolve(this.topLevelDir, file) ++ ) ++ ) ++ const isGone = await Promise.all( ++ [...candidates].map((file) => ++ fs.lstat(file).then( ++ () => false, ++ () => true ++ ) ++ ) ++ ) ++ const deletedFiles = [...candidates].filter((_, i) => isGone[i]) + debugLog('Found deleted files:', deletedFiles) + return deletedFiles + } +@@ -194,7 +243,7 @@ export class GitWorkflow { + */ + async getUnstagedFiles({ onlyPartial = false } = {}) { + debugLog('Getting partially staged files...') +- const status = await this.execGit(['status', '-z']) ++ const status = await this.execGit(['status', '-z', '--untracked-files=no']) + /** + * See https://git-scm.com/docs/git-status#_short_format + * Entries returned in machine format are separated by a NUL character. +@@ -270,11 +319,14 @@ export class GitWorkflow { } else { /** Save stash of all changes, keeping all files as-is */ const stashHash = await this.execGit(['stash', 'create']) @@ -56,7 +115,7 @@ index 3a32d6a9cd65c7ecb6b3cbccfce5a15c96530435..363513128bf7302eab73ea775102bb8a debugLog(task.title) } } catch (error) { -@@ -425,7 +444,11 @@ export class GitWorkflow { +@@ -425,7 +477,11 @@ export class GitWorkflow { async cleanup(ctx) { try { debugLog('Dropping backup stash...') @@ -111,6 +170,22 @@ index 993f8d81cac48132b5ae2ebdc8ca452c7217caad..2dc2291bc82451eacc5babfc8ce40805 > git stash list --format="%h %s" ${hash} On main: lint-staged automatic backup +diff --git a/lib/searchConfigs.js b/lib/searchConfigs.js +index 77ffe8f2423bb24ed80e2e23b57847a69c137195..822ff82c189cf712029e5e5870e5b3d9266f74a2 100644 +--- a/lib/searchConfigs.js ++++ b/lib/searchConfigs.js +@@ -36,8 +36,9 @@ const listConfigFilesFromGit = async ({ cwd, topLevelDir }) => + [ + ...EXEC_GIT, + '--cached', // show all tracked files +- '--others', // show untracked files +- '--exclude-standard', // apply standard git exclusions (.gitignore, etc.) ++ // Orca patch: no `--others`. Listing untracked files walks the whole worktree, which takes ++ // seconds on a cold stat cache. Untracked configs in `cwd` and above are still found by ++ // `listConfigFilesFromFs`; a nested config must be tracked or staged to apply. + '--', + ...CONFIG_PATHSPEC, + ], diff --git a/lib/state.js b/lib/state.js index da30e6f639d31307ebf503691aa991bb93948f8a..4a38799fa7773a8e8629c7c3a6b72287e6b22f4b 100644 --- a/lib/state.js diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be8837a88c4..490176fe903 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -209,7 +209,7 @@ patchedDependencies: '@xterm/xterm@6.1.0-beta.336': 4b7fbfe7a7f626843ab88535cc6e2181872ea7c107876b15406a295182bc3c2c glob@13.0.6: 163edae2cab27bf7a8cf791c9a0ee368b596bfef898e490b3b77e7e44a8f0223 i18next-cli@1.74.2: 2ee32eef742615cd133e1a6940f027deb3723a8430bb7953bba3a6769b0aac47 - lint-staged@16.4.0: 7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673 + lint-staged@16.4.0: b3b398fa76585526ea579cbb07949ce69c2456afb5ab0b49e10de2de4ea76f6d minimatch@10.2.5: 4324868e550a69eee9addc4801001bee415e98339c9b2b88d6ab4fc6028741c6 minimatch@10.2.6: 4324868e550a69eee9addc4801001bee415e98339c9b2b88d6ab4fc6028741c6 minimatch@9.0.9: c356feccb9147b4d6a1cc72b10270defcb95d14cb42ee74ddfe7219341417161 @@ -544,7 +544,7 @@ importers: version: 0.18.10 lint-staged: specifier: ^16.4.0 - version: 16.4.0(patch_hash=7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673) + version: 16.4.0(patch_hash=b3b398fa76585526ea579cbb07949ce69c2456afb5ab0b49e10de2de4ea76f6d) lowlight: specifier: ^3.3.0 version: 3.3.0 @@ -13410,7 +13410,7 @@ snapshots: linkifyjs@4.3.3: {} - lint-staged@16.4.0(patch_hash=7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673): + lint-staged@16.4.0(patch_hash=b3b398fa76585526ea579cbb07949ce69c2456afb5ab0b49e10de2de4ea76f6d): dependencies: commander: 14.0.3 listr2: 9.0.5 From 8c306365dd4ba6af14a6898e7cd07461c698058e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:34:06 -0800 Subject: [PATCH 09/52] perf: refresh agent models when CLI inputs change (#41976) * perf: refresh agent model catalogs when launch inputs change * test: cover model catalog launch input changes * test: require explicit refresh intent for floating agents * fix: combine model catalog ownership imports * Observe direct agent scripts after interpreter options * Expose refresh intent in preflight API types * Keep slow model discovery alive beyond picker waits * Explain the real transport regression test budget * Use typed catalog test requests and locate cast rationale * Assert discovered ACP effort choices directly * Fix catalog regression fixture types --- .../use-mobile-new-tab-agent-options.test.tsx | 15 + .../acp-listing-session-models.test.ts | 313 ++++++++++++++++++ .../discovery/acp-listing-session-models.ts | 127 ++++--- .../acp/discovery/acp-model-catalog-probe.ts | 293 ++++++++++------ .../acp-model-catalog-selected-demand.test.ts | 94 ++++++ src/main/acp/launch/acp-launch-version.ts | 13 +- .../preflight/agent-cli-version-probe.test.ts | 25 +- .../preflight/agent-cli-version-probe.ts | 23 +- .../claude-model-catalog-observation.ts | 43 +++ .../claude-model-catalog-probe.test.ts | 69 ++++ .../claude-model-catalog-probe.ts | 111 ++++--- .../sdk-transport/claude-control-responses.ts | 11 +- .../app-server/codex-app-server-session.ts | 21 +- .../catalog/codex-model-catalog-probe.test.ts | 290 +++++++++++++++- .../catalog/codex-model-catalog-probe.ts | 153 ++++++--- .../catalog/codex-structured-model-catalog.ts | 10 +- .../codex-configured-launch-defaults.ts | 4 +- src/main/ipc/preflight.ts | 4 +- .../agent-model-catalog-account-expiry.ts | 8 +- .../agent-model-catalog-account-resolution.ts | 46 +++ ...-model-catalog-discovery-freshness.test.ts | 7 +- .../agent-model-catalog-discovery.ts | 18 +- .../agent-model-catalog-effort-discovery.ts | 2 +- .../agent-model-catalog-entry-lifetime.ts | 123 +++++-- .../agent-model-catalog-input-stamp.test.ts | 309 +++++++++++++++++ .../agent-model-catalog-input-stamp.ts | 49 +++ .../agent-model-catalog-inputs.ts | 83 +++++ .../agent-model-catalog-lister.ts | 184 +++++----- .../agent-model-catalog-listing-waiters.ts | 41 +-- .../agent-model-catalog-lookup.ts | 1 + .../agent-model-catalog-probe-runner.test.ts | 40 +++ .../agent-model-catalog-probe-runner.ts | 108 ++++-- .../agent-model-catalog-refresh.ts | 171 +++++----- .../agent-model-catalog-scope.ts | 52 ++- .../agent-model-catalog-scoped-lister.ts | 48 +++ .../agent-model-catalog-script-entry.ts | 104 ++++++ .../agent-model-catalog-service-contract.ts | 2 + .../agent-model-catalog-service.ts | 19 +- ...agent-model-catalog-shared-listing.test.ts | 295 ++++++++++++++++- .../agent-model-catalog-shared-setup.test.ts | 91 +++-- .../agent-model-catalog-snapshot.ts | 9 +- .../agent-model-catalog-store.test.ts | 87 +++++ .../agent-model-catalog-store.ts | 98 +++--- .../structured-agent-session-catalog-reads.ts | 2 +- src/main/pi/rpc-runtime-metadata.ts | 1 + .../pi/rpc/launch/rpc-launch-resolution.ts | 9 +- .../options/rpc-model-catalog-probe.test.ts | 88 +++++ .../pi/rpc/options/rpc-model-catalog-probe.ts | 181 ++++++---- src/main/pi/rpc/options/rpc-model-options.ts | 7 +- .../preflight/agents-refreshed-on-host.ts | 8 +- .../preflight/workspace-agent-detection.ts | 5 +- ...ed-agent-shell-environment-catalog.test.ts | 172 ++++++++-- .../structured-agent-shell-environment.ts | 17 +- ...tructured-agent-model-catalog-discovery.ts | 1 + .../rpc/methods/preflight/preflight.ts | 6 +- ...uctured-agent-session-options-read.test.ts | 19 ++ .../structured-agent-session-options-read.ts | 11 +- src/preload/api/preflight/preflight-api.ts | 12 +- src/preload/api/preflight/preflight-bridge.ts | 12 +- .../agent-launch-picker-acquisition.test.ts | 48 +++ .../agent/agent-launch-picker-acquisition.ts | 2 +- .../AgentLaunchChoiceEditor.test.tsx | 20 ++ .../use-agent-settings-model-catalog.ts | 7 +- .../host-access/native-chat-host-setup.ts | 4 +- .../components/settings/agents/AgentsPane.tsx | 4 +- .../status-bar/use-status-bar-controller.ts | 2 +- .../src/hooks/useDetectedAgents.test.tsx | 6 +- src/renderer/src/hooks/useDetectedAgents.ts | 11 +- .../agent-inventory/detected-agents.test.ts | 52 +++ .../local-agent-inventory-refresh.ts | 13 +- .../local-detected-agent-state.test.ts | 18 + .../local-detected-agent-state.ts | 1 + .../local-detected-agent-store-state.ts | 2 +- .../runtime-agent-detection-request.ts | 48 +++ .../runtime-detected-agents.ts | 115 +++---- .../preload-api/web-host-capability-api.ts | 4 +- ...nt-session-renderer-client-capabilities.ts | 2 + ...ured-agent-session-surface-capabilities.ts | 4 + .../process/agent-command-line-entrypoint.ts | 10 +- src/shared/node-interpreter-options.ts | 7 + .../preflight/preflight-params.ts | 4 + .../rpc-params-catalog.generated.ts | 4 +- 82 files changed, 3745 insertions(+), 808 deletions(-) create mode 100644 src/main/acp/discovery/acp-listing-session-models.test.ts create mode 100644 src/main/acp/discovery/acp-model-catalog-selected-demand.test.ts create mode 100644 src/main/claude/model-catalog/claude-model-catalog-observation.ts create mode 100644 src/main/native-chat/agent-model-catalog/agent-model-catalog-account-resolution.ts create mode 100644 src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.test.ts create mode 100644 src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.ts create mode 100644 src/main/native-chat/agent-model-catalog/agent-model-catalog-inputs.ts create mode 100644 src/main/native-chat/agent-model-catalog/agent-model-catalog-scoped-lister.ts create mode 100644 src/main/native-chat/agent-model-catalog/agent-model-catalog-script-entry.ts create mode 100644 src/main/pi/rpc/options/rpc-model-catalog-probe.test.ts create mode 100644 src/renderer/src/store/slices/agent-inventory/runtime-agent-detection-request.ts create mode 100644 src/shared/node-interpreter-options.ts diff --git a/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.test.tsx b/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.test.tsx index 87a94023e7d..1c2e3c1d99d 100644 --- a/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.test.tsx +++ b/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.test.tsx @@ -139,4 +139,19 @@ describe('useMobileNewTabAgentOptions', () => { expect(drawer.options()).toEqual([]) drawer.unmount() }) + it('keeps a stale-sheet automatic refresh distinct from an explicit user refresh', async () => { + const client = createClient({ agents: () => claude }) + const first = mountDrawer(queryClient) + await first.render({ client, open: true }) + first.unmount() + vi.setSystemTime(1_000_001) + const reopened = mountDrawer(queryClient) + await reopened.render({ client, open: true }) + expect( + client.sendRequest.mock.calls + .filter(([method]) => method === 'preflight.refreshAgents') + .map(([, params]) => params) + ).toEqual([expect.not.objectContaining({ userInitiated: true })]) + reopened.unmount() + }) }) diff --git a/src/main/acp/discovery/acp-listing-session-models.test.ts b/src/main/acp/discovery/acp-listing-session-models.test.ts new file mode 100644 index 00000000000..987d1237c05 --- /dev/null +++ b/src/main/acp/discovery/acp-listing-session-models.test.ts @@ -0,0 +1,313 @@ +import { createStructuredAgentSessionCatalogReads } from '../../native-chat/agent-session-wire/options/structured-agent-session-catalog-reads' +import type { StructuredAgentSessionHostDeps } from '../../native-chat/agent-session-wire/host/structured-agent-session-host-types' +import type { createAgentModelCatalogSuccessWriter } from '../../native-chat/agent-model-catalog/agent-model-catalog-entry-lifetime' +import { createAcpModelCatalogProbe } from './acp-model-catalog-probe' +import { AgentModelCatalogStore } from '../../native-chat/agent-model-catalog/agent-model-catalog-store' +import { createAgentModelCatalogService } from '../../native-chat/agent-model-catalog/agent-model-catalog-service' +import { NewSessionResponseSchema } from '../generated/acp-protocol.generated' +import recorded from '../fixtures/opencode-v2-start-options.json' +import { expect, it, vi, onTestFinished } from 'vitest' +import { acpLaunchSpecFor } from '../launch/acp-launch-registry' +import { + readSessionModels, + type AcpModelCatalogSessionConnection +} from './acp-listing-session-models' +import type { runAgentModelCatalogListing } from '../../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' +import { runAgentModelCatalogSession } from '../../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' + +const LEARNED_EFFORTS = [ + { value: 'low', label: 'Low' }, + { value: 'high', label: 'High' }, + { value: 'max', label: 'Max' }, + { value: 'default', label: 'Default' } +] + +it('publishes inventory before a slow optional effort reply and retains its valid late result', async () => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const late = + Promise.withResolvers< + Awaited> + >() + const observations: Awaited>[] = [] + const connection: AcpModelCatalogSessionConnection = { + initialize: async () => ({ + protocolVersion: 1, + agentCapabilities: { sessionCapabilities: { delete: {} } } + }), + start: async () => ({ + kind: 'new', + sessionId: 'listing', + response: NewSessionResponseSchema.parse(recorded) + }), + setConfigOption: () => late.promise, + deleteSession: async () => ({}), + close: async () => {} + } + const run = runAgentModelCatalogSession< + AcpModelCatalogSessionConnection, + Awaited> + >( + () => connection, + (connection, ready) => + readSessionModels( + acpLaunchSpecFor('opencode2')!, + { kind: 'session', listingNamesConfiguredModel: false }, + connection, + '/workspace', + undefined, + ['opencode/big-pickle'], + undefined, + ready, + (result) => observations.push(result) + ), + { label: 'opencode2', timeoutMs: null } + ) + await vi.advanceTimersByTimeAsync(45_000) + expect(observations[0]?.models.find((row) => row.id === 'opencode/big-pickle')).toMatchObject({ + efforts: [], + effortsKnown: false + }) + const options = structuredClone(recorded.configOptions) + options.find((option) => option.id === 'model')!.currentValue = 'opencode/big-pickle' + late.resolve({ + configOptions: NewSessionResponseSchema.parse({ ...recorded, configOptions: options }) + .configOptions! + }) + const result = await run + expect(result.models.find((row) => row.id === 'opencode/big-pickle')?.efforts).toEqual([ + { value: 'low', label: 'Low' }, + { value: 'high', label: 'High' }, + { value: 'max', label: 'Max' }, + { value: 'default', label: 'Default' } + ]) + expect(result.attemptedModels).toEqual(['opencode/big-pickle']) + expect( + observations.at(-1)?.models.find((row) => row.id === 'opencode/big-pickle')?.efforts + ).toEqual(result.models.find((row) => row.id === 'opencode/big-pickle')?.efforts) + expect( + observations[0]?.models.find((row) => row.id === 'opencode/big-pickle')?.effortsKnown + ).toBe(false) +}) + +function accumulatedCatalogHarness(count: number) { + const baseSpec = acpLaunchSpecFor('opencode2')! + const spec = { + ...baseSpec, + managedRuntime: undefined, + account: { + ...baseSpec.account, + environment: (_home: unknown, env: Record) => env + } + } + const config = (selected = 'm0') => + NewSessionResponseSchema.parse({ + ...recorded, + configOptions: recorded.configOptions.map((option) => + option.id === 'model' + ? { + ...option, + currentValue: selected, + options: Array.from({ length: count }, (_, index) => ({ + value: `m${index}`, + name: `Model ${index}` + })) + } + : option + ) + }) + const requests: { + model: string + reply: PromiseWithResolvers< + Awaited> + > + }[] = [] + const connect = vi.fn((): AcpModelCatalogSessionConnection => ({ + initialize: async () => ({ + protocolVersion: 1, + agentCapabilities: { sessionCapabilities: { delete: {} } } + }), + start: async () => ({ kind: 'new', sessionId: 'listing', response: config() }), + setConfigOption: (_id, model) => { + const reply = + Promise.withResolvers< + Awaited> + >() + requests.push({ model, reply }) + return reply.promise + }, + deleteSession: async () => ({}), + close: async () => {} + })) + const store = new AgentModelCatalogStore() + const writes = vi.spyOn( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: measure the production publication boundary required by the scaling regression. + store as unknown as { writeSuccess: ReturnType }, + 'writeSuccess' + ) + const probe = createAcpModelCatalogProbe(spec, { + resolveEnvironment: async () => ({}), + resolveCommand: () => process.execPath, + probeVersion: async () => ({ version: '2.1.0' }), + homePath: '/account', + dataDirectory: '/unused', + connectSession: connect + }) + const service = createAgentModelCatalogService({ + store, + getRecord: () => undefined, + getConversation: () => undefined, + drivesRecord: () => true, + resolveAccountHome: async () => ({ variable: 'HOME', path: '/account' }), + probes: { opencode2: probe } + }) + const externalRead = createStructuredAgentSessionCatalogReads(() => ({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: sessionless catalog reads only access modelCatalog; no chat or journal is mocked. + deps: { modelCatalog: service } as StructuredAgentSessionHostDeps, + serialize: async (_id, task) => task(), + scopeOwned: async () => null + })) + const read = async (waitForListing = true, selectedModel?: string) => { + const result = await externalRead({ + agent: 'opencode2', + workspacePath: '/workspace', + waitForListing, + selectedModel + }) + if (result.origin === 'unknown') { + throw new Error('Expected the listing inventory') + } + return result + } + onTestFinished(() => service.stop()) + const answer = (index: number) => { + const request = requests[index]! + request.reply.resolve({ configOptions: config(request.model).configOptions! }) + } + return { store, writes, service, requests, connect, read, answer } +} + +it.each([10, 100])( + 'accumulates %i untargeted menus without publishing the full catalog per reply', + async (count) => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const h = accumulatedCatalogHarness(count) + const first = h.read() + await vi.advanceTimersByTimeAsync(0) + expect((await first).models).toHaveLength(count) + let delivered = false + const observer = h.read().then((answer) => { + delivered = true + return answer + }) + await vi.advanceTimersByTimeAsync(0) + for (let index = 0; index < count - 1; index++) { + h.answer(index) + await vi.advanceTimersByTimeAsync(0) + if (index < count - 2) { + expect(delivered).toBe(false) + } + } + const final = await observer + expect(final.models?.every((model) => model.effortsKnown !== false)).toBe(true) + expect(h.connect).toHaveBeenCalledOnce() + // One initial inventory and one terminal observation, independent of the target count. + expect(h.writes.mock.calls.length).toBeLessThanOrEqual(2) + expect( + h.writes.mock.calls.reduce((rows, call) => rows + call[2].models.length, 0) + ).toBeLessThanOrEqual(count * 2) + } +) + +it.each(['snapshot', 'deadline', 'selected'])( + 'exposes accumulated menus at a %s boundary while the next switch is unanswered', + async (boundary) => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const h = accumulatedCatalogHarness(5) + const first = h.read() + await first + const observer = h.read() + h.answer(0) + await vi.advanceTimersByTimeAsync(6_000) + // m1 has answered; m2 is still pending, beyond the old optional sweep cutoff. + if (boundary === 'snapshot') { + expect((await h.read(false)).models?.find((row) => row.id === 'm1')?.efforts).toEqual( + LEARNED_EFFORTS + ) + } else if (boundary === 'selected') { + expect((await h.read(true, 'm1')).models?.find((row) => row.id === 'm1')?.efforts).toEqual( + LEARNED_EFFORTS + ) + } else { + await vi.advanceTimersByTimeAsync(24_000) + } + expect((await observer).models?.find((row) => row.id === 'm1')?.efforts).toEqual( + LEARNED_EFFORTS + ) + let followed = false + const follow = h.read().then((answer) => { + followed = true + return answer + }) + await vi.advanceTimersByTimeAsync(1_000) + expect(followed).toBe(false) + // New selected demand joins the same owner and is promoted after its outstanding switch. + const selected = h.read(true, 'm4') + h.answer(1) + await vi.advanceTimersByTimeAsync(6_000) + expect(h.requests[2]?.model).toBe('m4') + h.answer(2) + await vi.advanceTimersByTimeAsync(0) + expect((await selected).models?.find((row) => row.id === 'm4')?.efforts).toEqual( + LEARNED_EFFORTS + ) + await follow + h.answer(3) + await vi.advanceTimersByTimeAsync(0) + expect(h.connect).toHaveBeenCalledOnce() + } +) + +it('keeps a slow OpenCode 1.x version response and selects its command listing', async () => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const version = Promise.withResolvers<{ version: string }>() + const requested = Promise.withResolvers() + const base = acpLaunchSpecFor('opencode')! + const session = vi.fn() + const command = vi.fn( + async () => 'opencode/slow-valid-model\n' + ) + const probe = createAcpModelCatalogProbe( + { ...base, account: { ...base.account, environment: (_home, env) => env } }, + { + resolveEnvironment: async () => ({}), + resolveCommand: () => process.execPath, + probeVersion: async () => { + requested.resolve() + return version.promise + }, + dataDirectory: '/unused', + homePath: '/account', + runListing: command, + connectSession: session + } + ) + const result = probe({ variable: 'HOME', path: '/account' }, { workspacePath: '/workspace' }) + await requested.promise + await vi.advanceTimersByTimeAsync(45_000) + version.resolve({ version: '1.18.31' }) + expect((await result).models.map((row) => row.id)).toEqual(['opencode/slow-valid-model']) + expect(session).not.toHaveBeenCalled() + expect(command.mock.calls[0]?.[1]).toMatchObject({ timeoutMs: null }) +}) diff --git a/src/main/acp/discovery/acp-listing-session-models.ts b/src/main/acp/discovery/acp-listing-session-models.ts index 3fd072a2000..d3e2b519830 100644 --- a/src/main/acp/discovery/acp-listing-session-models.ts +++ b/src/main/acp/discovery/acp-listing-session-models.ts @@ -13,7 +13,8 @@ import type { InitializeResponse, SetSessionConfigOptionResponse } from '../generated/acp-protocol.generated' -import { withTimeout } from '../../../shared/promise-timeout-fallback' +import type { AgentModelCatalogReady } from '../../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' +import type { AgentModelCatalogProgress } from '../../native-chat/agent-model-catalog/agent-model-catalog-discovery' import { AcpAgentError } from '../transport/acp-errors' /** Session-free capability boundary: no session methods are exposed. */ @@ -61,7 +62,15 @@ export async function readSessionModels( operation?: StructuredAgentResolutionOperation, selectedModels?: readonly string[], launchedModel?: string, - ready?: (cleanup: () => Promise) => void + ready?: AgentModelCatalogReady<{ models: AgentSessionModelOption[]; attemptedModels: string[] }>, + publish?: (result: { models: AgentSessionModelOption[]; attemptedModels: string[] }) => void, + deferred?: { + defer: ( + read: () => { models: AgentSessionModelOption[]; attemptedModels: string[] }, + known: (model: string) => boolean + ) => void + demanded: NonNullable + } ): Promise<{ models: AgentSessionModelOption[]; attemptedModels: string[] }> { const initialized = await connection.initialize() assertStructuredAgentResolutionCurrent(operation) @@ -80,12 +89,16 @@ export async function readSessionModels( }) } } - // Startup and menu discovery have separate budgets; cleanup also runs on cancellation. - ready?.(cleanup) const options = new AcpStructuredOptions(spec.dialect) options.adoptSession(started.response, 'new') - let models = options.read().models + let models = [...options.read().models] const attemptedModels: string[] = [] + const partial = () => { + stopped = true + return { models: [...models], attemptedModels: [...attemptedModels] } + } + ready?.(cleanup, models.length > 0 ? partial : undefined) + const progress = () => publish?.({ models: [...models], attemptedModels: [...attemptedModels] }) try { if (launchedModel !== undefined) { attemptedModels.push(launchedModel) @@ -96,49 +109,77 @@ export async function readSessionModels( row.id === running ? { ...row, efforts: [], effortsKnown: false as const } : row ) } + progress() } else if (spec.dialect.effortChangesModel) { - const byId = new Map(models.map((model) => [model.id, model])) - const targets = selectedModels ? selectedModels.flatMap((id) => byId.get(id) ?? []) : models - const sweep = async () => { - for (const model of targets) { - if (stopped) { - return - } - assertStructuredAgentResolutionCurrent(operation) - if (model.effortsKnown !== false) { - continue - } - attemptedModels.push(model.id) - try { - for (let attempt = 0; attempt < 2 && !stopped; attempt++) { - const write = options.write('model', model.id) - if (write?.method !== 'config') { - break - } - const reply = await connection.setConfigOption(write.configId, write.value) - if (stopped) { - return - } - assertStructuredAgentResolutionCurrent(operation) - options.adoptConfigOptions(reply.configOptions) - const observed = options.read() - if (observed.current.model !== model.id) { - continue - } - const known = observed.models.find((row) => row.id === model.id) - if (known) { - models = models.map((row) => (row.id === model.id ? known : row)) - } - break - } - } catch { - assertStructuredAgentResolutionCurrent(operation) + progress() + const indices = new Map(models.map((model, index) => [model.id, index])) + const remaining = new Set(selectedModels ?? models.map((model) => model.id)) + const visited = new Set() + const known = (id: string) => { + const index = indices.get(id) + return index !== undefined && models[index].effortsKnown !== false + } + const snapshot = () => ({ models: [...models], attemptedModels: [...attemptedModels] }) + while (!stopped) { + const demanded = deferred?.demanded() ?? new Set(selectedModels) + for (const id of demanded) { + if (!visited.has(id) && indices.has(id)) { + remaining.add(id) } } + const id = [...demanded].find((id) => remaining.has(id)) ?? remaining.values().next().value + if (id === undefined) { + break + } + remaining.delete(id) + visited.add(id) + const index = indices.get(id) + if (index === undefined || known(id)) { + continue + } + assertStructuredAgentResolutionCurrent(operation) + let conclusive = false + try { + for (let attempt = 0; attempt < 2 && !stopped; attempt++) { + const write = options.write('model', id) + if (write?.method !== 'config') { + conclusive = true + break + } + const reply = await connection.setConfigOption(write.configId, write.value) + if (stopped) { + break + } + assertStructuredAgentResolutionCurrent(operation) + options.adoptConfigOptions(reply.configOptions) + const observed = options.read() + if (observed.current.model !== id) { + continue + } + const learned = observed.models.find((row) => row.id === id) + if (learned) { + models[index] = learned + } + conclusive = true + break + } + } catch { + assertStructuredAgentResolutionCurrent(operation) + conclusive = true + } + if (conclusive) { + attemptedModels.push(id) + } + if (deferred?.demanded().has(id)) { + progress() + } else if (deferred) { + deferred.defer(snapshot, known) + } else { + progress() + } } - await withTimeout(sweep(), 5_000, undefined) + stopped = true } - assertStructuredAgentResolutionCurrent(operation) return { models, attemptedModels } } finally { if (!ready) { diff --git a/src/main/acp/discovery/acp-model-catalog-probe.ts b/src/main/acp/discovery/acp-model-catalog-probe.ts index 7f8da46c04a..62cf3f8b230 100644 --- a/src/main/acp/discovery/acp-model-catalog-probe.ts +++ b/src/main/acp/discovery/acp-model-catalog-probe.ts @@ -1,9 +1,18 @@ +import { readAgentCliVersion } from '../../agent-launch/preflight/agent-cli-version-probe' import { observeAcpForkSupport } from '../capabilities/acp-fork-support' -import { assertStructuredAgentResolutionCurrent } from '../../native-chat/agent-launch/structured-agent-command-resolution' +import { + assertStructuredAgentResolutionCurrent, + type StructuredAgentResolutionOperation +} from '../../native-chat/agent-launch/structured-agent-command-resolution' import { homedir } from 'node:os' import { join } from 'node:path' import type { AgentCliVersionReader } from '../../agent-launch/preflight/agent-cli-version-probe' -import type { AgentModelCatalogProbe } from '../../native-chat/agent-model-catalog/agent-model-catalog-store' +import type { + AgentModelCatalogProgress, + AgentModelCatalogProbe, + AgentModelCatalogLookup +} from '../../native-chat/agent-model-catalog/agent-model-catalog-discovery' +import { agentModelCatalogInputStamp } from '../../native-chat/agent-model-catalog/agent-model-catalog-input-stamp' import { runAgentModelCatalogListing, runAgentModelCatalogSession @@ -34,6 +43,7 @@ import { AgentModelCatalogUnavailableError } from '../../native-chat/agent-model import { usesModelSpecificAcpEfforts } from '../../../shared/agent-session/options/agent-model-catalog-ownership' export type AcpModelCatalogProbeDeps = AcpLaunchInvocationDeps & { + resolveSavedEnvironment?: () => Promise> probeVersion?: AgentCliVersionReader connect?: (launch: ProviderProcessLaunch) => AcpModelCatalogConnection connectSession?: (launch: ProviderProcessLaunch) => AcpModelCatalogSessionConnection @@ -45,14 +55,17 @@ export function createAcpModelCatalogProbe( spec: AcpLaunchSpec, deps: AcpModelCatalogProbeDeps ): AgentModelCatalogProbe { - const probe: AgentModelCatalogProbe = async (accountHome, options) => { - const operation = options?.operation ?? { signal: options?.signal } + const resolve = async ( + accountHome: Parameters[0], + workspace: string, + lookup: AgentModelCatalogLookup = 'recover', + operation?: StructuredAgentResolutionOperation + ) => { assertStructuredAgentResolutionCurrent(operation) const discovery = spec.modelDiscovery if (discovery.kind === 'unavailable') { throw new Error(discovery.reason) } - const workspace = options?.workspacePath // Reject folderless session discovery before spawning even a version probe. if (!workspace && acpListingNeedsChatFolder(discovery)) { throw folderlessListing(spec) @@ -64,121 +77,175 @@ export function createAcpModelCatalogProbe( accountHome, { ...deps, + ...(lookup !== 'recover' + ? { + resolveEnvironment: deps.resolveSavedEnvironment ?? deps.resolveEnvironment, + refreshEnvironmentAfterMiss: undefined + } + : {}), operation, resolveWorkingDirectory: () => cwd } ) assertStructuredAgentResolutionCurrent(operation) - const release = await checkAcpLaunchVersion( - spec, - { command, prefixArgs, cwd, env }, - acpListingDependsOnRelease(discovery), - deps.probeVersion - ) - assertStructuredAgentResolutionCurrent(operation) - if (release.status === 'tooOld') { - throw new Error(`${spec.agent} at ${command} does not run structured chats`) - } - const listing = acpModelListingForRelease(discovery, release.version) - if (listing === null) { - throw new Error(`${spec.agent} at ${command} lists its models only through its chats`) - } - const launch = { - command, - args: [...prefixArgs, ...spec.args({ fullAccess: false, pluginDir: null })], - cwd, - env, - envToDelete - } - const run = { label: spec.agent, signal: options?.signal } - // OMP records every model switch as account usage; starting on the picked model records none. - const launchedModel = - spec.launchesWithModel && usesModelSpecificAcpEfforts(spec.agent) - ? options?.selectedModels?.[0] - : undefined - let models: AgentSessionModelOption[] - let attemptedModels: string[] | undefined - if (listing.kind === 'command') { - const stdout = await (deps.runListing ?? runAgentModelCatalogListing)( - { + return { + identity: { command, prefixArgs, cwd, workspace }, + inputStamp: JSON.stringify( + await Promise.all( + [ + ...new Set([cwd, ...(discovery.kind === 'command' && workspace ? [workspace] : [])]) + ].map((directory) => + agentModelCatalogInputStamp({ command, prefixArgs, cwd: directory, env }) + ) + ) + ), + run: async ( + signal?: AbortSignal, + runOperation = operation, + selectedModels?: readonly string[], + publish?: AgentModelCatalogProgress + ) => { + const options = { signal, operation: runOperation, selectedModels } + const operation = runOperation + assertStructuredAgentResolutionCurrent(operation) + const release = await checkAcpLaunchVersion( + spec, + { command, prefixArgs, cwd, env, operation }, + acpListingDependsOnRelease(discovery), + deps.probeVersion ?? ((input) => readAgentCliVersion({ ...input, timeoutMs: null })) + ) + assertStructuredAgentResolutionCurrent(operation) + if (release.status === 'tooOld') { + throw new Error(`${spec.agent} at ${command} does not run structured chats`) + } + const listing = acpModelListingForRelease(discovery, release.version) + if (listing === null) { + throw new Error(`${spec.agent} at ${command} lists its models only through its chats`) + } + const launch = { command, - args: [...prefixArgs, ...listing.args], - cwd: workspace ?? cwd, + args: [...prefixArgs, ...spec.args({ fullAccess: false, pluginDir: null })], + cwd, env, envToDelete - }, - { site: `${spec.agent}-model-catalog-probe`, signal: options?.signal } - ) - models = listing.parse(stdout) - } else if (listing.kind === 'session') { - if (!workspace) { - throw folderlessListing(spec) - } - // Remove disposable session storage after the process closes. - const folderArgs = listing.sessionFolderArgs - const listInSession = async (model: string | undefined) => { - const folder = folderArgs - ? await acpRunFolder(join(deps.dataDirectory, 'acp-listing-sessions', spec.agent)) - : null - try { - assertStructuredAgentResolutionCurrent(operation) - const args = [ - ...prefixArgs, - ...spec.args({ fullAccess: false, pluginDir: null, model }), - ...(folderArgs && folder ? folderArgs(folder.path) : []) - ] - return await runAgentModelCatalogSession( - () => (deps.connectSession ?? createAcpAgentConnection)({ ...launch, args }), - (connection, ready) => - readSessionModels( - spec, - listing, - connection, - workspace, - operation, - options?.selectedModels, - model, - spec.dialect.effortChangesModel ? ready : undefined - ), + } + const run = { label: spec.agent, signal: options?.signal, timeoutMs: null } + // OMP records every model switch as account usage; starting on the picked model records none. + const launchedModel = + spec.launchesWithModel && usesModelSpecificAcpEfforts(spec.agent) + ? options?.selectedModels?.[0] + : undefined + let models: AgentSessionModelOption[] + let attemptedModels: string[] | undefined + if (listing.kind === 'command') { + const stdout = await (deps.runListing ?? runAgentModelCatalogListing)( + { + command, + args: [...prefixArgs, ...listing.args], + cwd: workspace ?? cwd, + env, + envToDelete + }, + { site: `${spec.agent}-model-catalog-probe`, signal: options?.signal, timeoutMs: null } + ) + models = listing.parse(stdout) + } else if (listing.kind === 'session') { + if (!workspace) { + throw folderlessListing(spec) + } + // Remove disposable session storage after the process closes. + const folderArgs = listing.sessionFolderArgs + const listInSession = async (model: string | undefined) => { + const folder = folderArgs + ? await acpRunFolder(join(deps.dataDirectory, 'acp-listing-sessions', spec.agent)) + : null + try { + assertStructuredAgentResolutionCurrent(operation) + const args = [ + ...prefixArgs, + ...spec.args({ fullAccess: false, pluginDir: null, model }), + ...(folderArgs && folder ? folderArgs(folder.path) : []) + ] + return await runAgentModelCatalogSession< + AcpModelCatalogSessionConnection, + Awaited> + >( + () => (deps.connectSession ?? createAcpAgentConnection)({ ...launch, args }), + (connection, ready) => + readSessionModels( + spec, + listing, + connection, + workspace, + operation, + options?.selectedModels, + model, + spec.dialect.effortChangesModel ? ready : undefined, + (result) => + publish?.( + { + ...result, + models: [...result.models], + attemptedModels: [...result.attemptedModels], + origin: 'probe', + complete: false + }, + true + ), + publish?.defer && publish.demanded + ? { + defer: (read, known) => + publish.defer?.( + () => ({ ...read(), origin: 'probe', complete: false }), + known + ), + demanded: publish.demanded + } + : undefined + ), + run + ) + } finally { + await folder?.remove() + } + } + let result: Awaited> + try { + result = await listInSession(launchedModel) + } catch (error) { + // OMP exits before ACP on a model it cannot start (a stale `:level` id); list without it. + if (launchedModel === undefined || !(error instanceof AcpAgentExitedError)) { + throw error + } + assertStructuredAgentResolutionCurrent(operation) + result = { ...(await listInSession(undefined)), attemptedModels: [launchedModel] } + } + models = result.models + attemptedModels = result.attemptedModels + } else { + models = await runAgentModelCatalogSession( + () => (deps.connect ?? createAcpAgentConnection)(launch), + async (connection) => { + const initialized = await connection.initialize() + assertStructuredAgentResolutionCurrent(operation) + observeAcpForkSupport(spec.agent, initialized) + return listing.read(initialized, connection) + }, run ) - } finally { - await folder?.remove() } - } - let result: Awaited> - try { - result = await listInSession(launchedModel) - } catch (error) { - // OMP exits before ACP on a model it cannot start (a stale `:level` id); list without it. - if (launchedModel === undefined || !(error instanceof AcpAgentExitedError)) { - throw error + if (models.length === 0) { + throw new Error(`${spec.agent} listed no models`) } - assertStructuredAgentResolutionCurrent(operation) - result = { ...(await listInSession(undefined)), attemptedModels: [launchedModel] } + return { models, origin: 'probe' as const, ...(attemptedModels ? { attemptedModels } : {}) } } - models = result.models - attemptedModels = result.attemptedModels - } else { - models = await runAgentModelCatalogSession( - () => (deps.connect ?? createAcpAgentConnection)(launch), - async (connection) => { - const initialized = await connection.initialize() - assertStructuredAgentResolutionCurrent(operation) - observeAcpForkSupport(spec.agent, initialized) - return listing.read(initialized, connection) - }, - run - ) } - if (models.length === 0) { - throw new Error(`${spec.agent} listed no models`) - } - return { models, origin: 'probe', ...(attemptedModels ? { attemptedModels } : {}) } } - return async (home, options) => { + const probe: AgentModelCatalogProbe = async (home, options) => { try { - return await probe(home, options) + return await ( + await resolve(home, options?.workspacePath ?? '', 'recover', options?.operation) + ).run(options?.signal, options?.operation, options?.selectedModels, options?.publish) } catch (error) { if (error instanceof AcpAgentError && error.code === -32000) { throw new AgentModelCatalogUnavailableError({ reason: 'notSignedIn' }) @@ -186,6 +253,24 @@ export function createAcpModelCatalogProbe( throw error } } + return Object.assign(probe, { + resolve: async (...args: Parameters) => { + const resolved = await resolve(...args) + return { + ...resolved, + run: async (...runArgs: Parameters) => { + try { + return await resolved.run(...runArgs) + } catch (error) { + if (error instanceof AcpAgentError && error.code === -32000) { + throw new AgentModelCatalogUnavailableError({ reason: 'notSignedIn' }) + } + throw error + } + } + } + } + }) } const folderlessListing = (spec: AcpLaunchSpec) => diff --git a/src/main/acp/discovery/acp-model-catalog-selected-demand.test.ts b/src/main/acp/discovery/acp-model-catalog-selected-demand.test.ts new file mode 100644 index 00000000000..a768e570567 --- /dev/null +++ b/src/main/acp/discovery/acp-model-catalog-selected-demand.test.ts @@ -0,0 +1,94 @@ +import type { ProviderProcessLaunch } from '../../provider-process/provider-process-launch' +import { expect, it, vi, onTestFinished } from 'vitest' +import { acpLaunchSpecFor } from '../launch/acp-launch-registry' +import { NewSessionResponseSchema } from '../generated/acp-protocol.generated' +import { createAcpModelCatalogProbe } from './acp-model-catalog-probe' +import type { AcpModelCatalogSessionConnection } from './acp-listing-session-models' +import { AgentModelCatalogStore } from '../../native-chat/agent-model-catalog/agent-model-catalog-store' +import { createAgentModelCatalogService } from '../../native-chat/agent-model-catalog/agent-model-catalog-service' + +it('starts the first OMP listing on demand collected before admission, without a second session', async () => { + const base = acpLaunchSpecFor('omp')! + const connect = vi.fn((launch: ProviderProcessLaunch): AcpModelCatalogSessionConnection => { + const modelAt = launch.args.indexOf('--model') + const current = modelAt !== -1 ? launch.args[modelAt + 1] : 'provider/default' + return { + initialize: async () => ({ + protocolVersion: 1, + agentCapabilities: { sessionCapabilities: { delete: {} } } + }), + start: async () => ({ + kind: 'new', + sessionId: 'listing', + response: NewSessionResponseSchema.parse({ + sessionId: 'listing', + configOptions: [ + { + id: 'model', + name: 'Model', + category: 'model', + type: 'select', + currentValue: current, + options: [ + { value: 'provider/default', name: 'Default' }, + { value: 'provider/selected', name: 'Selected' } + ] + }, + { + id: 'thinking', + name: 'Thinking', + category: 'thought_level', + type: 'select', + currentValue: 'high', + options: [{ value: 'high', name: 'High' }] + } + ] + }) + }), + setConfigOption: async () => { + throw new Error('OMP selects on launch') + }, + deleteSession: async () => ({}), + close: async () => {} + } + }) + const probe = createAcpModelCatalogProbe( + { + ...base, + account: { ...base.account, environment: (_home, env) => env }, + modelDiscovery: { kind: 'session', listingNamesConfiguredModel: false } + }, + { + resolveEnvironment: async () => ({}), + resolveCommand: () => process.execPath, + probeVersion: async () => ({ version: '18.0.0' }), + homePath: '/account', + dataDirectory: '/unused', + connectSession: connect + } + ) + const store = new AgentModelCatalogStore() + const service = createAgentModelCatalogService({ + store, + getRecord: () => undefined, + getConversation: () => undefined, + drivesRecord: () => true, + resolveAccountHome: async () => ({ variable: 'PI_CODING_AGENT_DIR', path: '/account' }), + probes: { omp: probe } + }) + onTestFinished(() => service.stop()) + const result = await service.read({ + agent: 'omp', + workspacePath: '/workspace', + selectedModel: 'provider/selected', + waitForListing: true + }) + if (result.origin === 'unknown') { + throw new Error('Expected the selected model inventory') + } + expect(result.models?.find((row) => row.id === 'provider/selected')).toMatchObject({ + efforts: [{ value: 'high', label: 'High' }] + }) + expect(connect).toHaveBeenCalledOnce() + expect(connect.mock.calls[0]?.[0].args).toEqual(['acp', '--model', 'provider/selected']) +}) diff --git a/src/main/acp/launch/acp-launch-version.ts b/src/main/acp/launch/acp-launch-version.ts index 92fb537d854..41d8b356068 100644 --- a/src/main/acp/launch/acp-launch-version.ts +++ b/src/main/acp/launch/acp-launch-version.ts @@ -1,3 +1,4 @@ +import type { StructuredAgentResolutionOperation } from '../../native-chat/agent-launch/structured-agent-command-resolution' import { checkAgentCliVersion, type AgentCliVersionCheck, @@ -9,7 +10,9 @@ import { noteAcpForkVersion } from '../capabilities/acp-fork-support' export async function checkAcpLaunchVersion( spec: AcpLaunchSpec, - launch: Pick, + launch: Pick & { + operation?: StructuredAgentResolutionOperation + }, wantVersion: boolean, read?: AgentCliVersionReader ): Promise { @@ -18,7 +21,13 @@ export async function checkAcpLaunchVersion( return { status: 'unknown', version: null } } const result = await checkAgentCliVersion( - { program: launch.command, prefixArgs: launch.prefixArgs, cwd: launch.cwd, env: launch.env }, + { + program: launch.command, + prefixArgs: launch.prefixArgs, + cwd: launch.cwd, + env: launch.env, + operation: launch.operation + }, spec.minimumVersions ?? [], read ) diff --git a/src/main/agent-launch/preflight/agent-cli-version-probe.test.ts b/src/main/agent-launch/preflight/agent-cli-version-probe.test.ts index f3508c15ef0..c53b3149acc 100644 --- a/src/main/agent-launch/preflight/agent-cli-version-probe.test.ts +++ b/src/main/agent-launch/preflight/agent-cli-version-probe.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { checkAgentCliVersion } from './agent-cli-version-probe' +import { checkAgentCliVersion, readAgentCliVersion } from './agent-cli-version-probe' const { runProcess } = vi.hoisted(() => ({ runProcess: vi.fn() })) vi.mock('@orca/process-host', () => ({ runProcess })) @@ -38,6 +38,17 @@ describe('checkAgentCliVersion', () => { ) }) + it('propagates owner cancellation instead of certifying a missing CLI', async () => { + const owner = new AbortController() + const closed = Promise.withResolvers() + runProcess.mockReturnValue(closed.promise) + const read = checkAgentCliVersion({ ...INPUT, operation: { signal: owner.signal } }, []) + const observed = expect(read).rejects.toThrow('superseded') + owner.abort(new Error('superseded')) + closed.resolve({ code: null, signal: 'SIGTERM', stdout: '', stderr: '', timedOut: false }) + await observed + }) + it('reads a version printed only on stderr, as Pi 0.73 does', async () => { prints('', { stderr: '0.73.1\n' }) expect(await checkAgentCliVersion(INPUT, ['0.84.0'])).toEqual({ @@ -47,3 +58,15 @@ describe('checkAgentCliVersion', () => { }) }) }) + +it('allows a catalog version prerequisite to complete late without changing normal preflight limits', async () => { + const answer = Promise.withResolvers() + runProcess.mockReturnValueOnce(answer.promise) + const catalog = readAgentCliVersion({ ...INPUT, timeoutMs: null }) + expect(runProcess.mock.lastCall?.[0].timeoutMs).toBeNull() + answer.resolve({ code: 0, stdout: '1.18.31', stderr: '', timedOut: false }) + expect(await catalog).toEqual({ version: '1.18.31' }) + runProcess.mockResolvedValueOnce({ code: null, stdout: '', stderr: '', timedOut: true }) + expect(await readAgentCliVersion(INPUT)).toEqual({ version: null }) + expect(runProcess.mock.lastCall?.[0].timeoutMs).toBe(5_000) +}) diff --git a/src/main/agent-launch/preflight/agent-cli-version-probe.ts b/src/main/agent-launch/preflight/agent-cli-version-probe.ts index d01a9a981ff..84dc4ba53d8 100644 --- a/src/main/agent-launch/preflight/agent-cli-version-probe.ts +++ b/src/main/agent-launch/preflight/agent-cli-version-probe.ts @@ -1,3 +1,7 @@ +import { + assertStructuredAgentResolutionCurrent, + type StructuredAgentResolutionOperation +} from '../../native-chat/agent-launch/structured-agent-command-resolution' import { compareAppVersions, parseCliVersion } from '../../../shared/app-version' import { runProcess } from '@orca/process-host' import type { ProcessSpec } from '@orca/process-host/process-spec' @@ -14,6 +18,8 @@ export type AgentCliVersionCheck = | { status: 'unknown' | 'missing'; version: null } export type AgentCliVersionInput = Pick & { + operation?: StructuredAgentResolutionOperation + timeoutMs?: number | null prefixArgs?: readonly string[] } @@ -60,21 +66,34 @@ export async function readAgentCliVersion( input: AgentCliVersionInput, parseVersion: typeof parseCliVersion = parseCliVersion ): Promise<{ version: string | null; started?: false }> { - const { prefixArgs = [], ...launch } = input + const { prefixArgs = [], operation, timeoutMs = 5_000, ...launch } = input + assertStructuredAgentResolutionCurrent(operation) let result try { result = await runProcess({ ...launch, args: [...prefixArgs, '--version'], terminationBarrier: true, - timeoutMs: 5_000, + signal: operation?.signal, + timeoutMs: + timeoutMs === null + ? null + : Math.max( + 1, + Math.min( + timeoutMs, + operation?.deadline === undefined ? Infinity : operation.deadline - Date.now() + ) + ), maxOutputBytes: 4_096, killOnOutputLimit: true }) } catch (error) { + assertStructuredAgentResolutionCurrent(operation) warnRefused(input.program, `did not start (${String(error)})`) return { version: null, started: false } } + assertStructuredAgentResolutionCurrent(operation) const output = `${result.stdout}\n${result.stderr}` if (result.timedOut || result.outputTruncated || result.code !== 0) { const why = result.timedOut diff --git a/src/main/claude/model-catalog/claude-model-catalog-observation.ts b/src/main/claude/model-catalog/claude-model-catalog-observation.ts new file mode 100644 index 00000000000..68032bdf3d2 --- /dev/null +++ b/src/main/claude/model-catalog/claude-model-catalog-observation.ts @@ -0,0 +1,43 @@ +import type { AgentSessionAccountKind } from '../../../shared/agent-session/agent-session-availability' +import type { AgentModelCatalogSuccess } from '../../native-chat/agent-model-catalog/agent-model-catalog-entry' +import { + isCompleteClaudeModelListing, + listedModels, + record +} from '../structured/launch/claude-structured-model-catalog' +import { claudeCatalogSignedOut } from './claude-model-catalog-signed-out' +import { + claudeFastModeSupport, + wireClaudeModels +} from '../structured/launch/claude-structured-catalog-listing' +import { readClaudeSettingsApplied } from '../structured/launch/claude-structured-session-options' + +export function readClaudeCatalogObservation( + replies: ReadonlyMap, + env: Readonly>, + account: AgentSessionAccountKind +): AgentModelCatalogSuccess { + const listing = replies.get('orca-model-discovery') + const models = listedModels(listing) + const settings = replies.get('orca-model-settings') + const applied = record(record(settings)?.applied) + const configured = + applied && + ['model', 'effort'].every((key) => applied[key] == null || typeof applied[key] === 'string') + ? (readClaudeSettingsApplied(settings) ?? undefined) + : undefined + if (models.length === 0) { + throw new Error('claude listed no models') + } + const fastModeSupport = claudeFastModeSupport(models) + return { + models: wireClaudeModels(models), + origin: 'probe', + complete: isCompleteClaudeModelListing(listing) && configured !== undefined, + ...(fastModeSupport ? { fastModeSupport } : {}), + ...(configured ? { configured } : {}), + ...(claudeCatalogSignedOut(replies.get('orca-signin-discovery'), settings, env) + ? { unavailable: { reason: 'notSignedIn', account } } + : {}) + } +} diff --git a/src/main/claude/model-catalog/claude-model-catalog-probe.test.ts b/src/main/claude/model-catalog/claude-model-catalog-probe.test.ts index 667762251d4..4943768337e 100644 --- a/src/main/claude/model-catalog/claude-model-catalog-probe.test.ts +++ b/src/main/claude/model-catalog/claude-model-catalog-probe.test.ts @@ -1,3 +1,4 @@ +import type { AgentModelCatalogSuccess } from '../../native-chat/agent-model-catalog/agent-model-catalog-entry' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -47,3 +48,71 @@ describe('Claude catalog availability', () => { } }) }) + +it('publishes models before settings and preserves a late sign-in response', async () => { + const settings = Promise.withResolvers() + const signin = Promise.withResolvers() + const inventory = Promise.withResolvers() + const observations: { + success: AgentModelCatalogSuccess + accountKnown?: boolean + }[] = [] + const response = (id: string, value: unknown) => + `${JSON.stringify({ + type: 'control_response', + response: { subtype: 'success', request_id: id, response: value } + })}\n` + const probe = createClaudeModelCatalogProbe({ + ...probeDeps(), + resolveEnv: () => ({}), + runListing: async (launch, options) => { + expect( + launch.stdin + ?.split(String.fromCharCode(10)) + .filter(Boolean) + .map((line) => JSON.parse(line).request_id) + ).toEqual(['orca-model-discovery', 'orca-model-settings', 'orca-signin-discovery']) + let stdout = response('orca-model-discovery', { + models: [{ value: 'opus', displayName: 'Opus', supportsEffort: false }] + }) + options.onOutput?.(stdout.slice(0, 17)) + options.onOutput?.(stdout.slice(17)) + inventory.resolve() + await settings.promise + const settingsReply = response('orca-model-settings', { + applied: { model: 'opus' }, + effective: {} + }) + stdout += settingsReply + options.onOutput?.(settingsReply) + await signin.promise + const signinReply = response('orca-signin-discovery', { + account: { tokenSource: 'none', apiProvider: 'firstParty' } + }) + stdout += signinReply + options.onOutput?.(signinReply) + return stdout + } + }) + const done = probe(HOME('/homes/a'), { + publish: (success, accountKnown) => observations.push({ success, accountKnown }) + }) + await inventory.promise + expect(observations[0]).toMatchObject({ + success: { models: [{ id: 'opus' }], complete: false }, + accountKnown: false + }) + settings.resolve() + await Promise.resolve() + signin.resolve() + expect(await done).toMatchObject({ + models: [{ id: 'opus' }], + configured: { model: 'opus' }, + unavailable: { reason: 'notSignedIn' } + }) + expect(observations.at(-1)).toMatchObject({ + accountKnown: true, + success: { unavailable: { reason: 'notSignedIn' } } + }) + expect(observations[0].success.configured).toBeUndefined() +}) diff --git a/src/main/claude/model-catalog/claude-model-catalog-probe.ts b/src/main/claude/model-catalog/claude-model-catalog-probe.ts index fee0027363d..c885cf01b5f 100644 --- a/src/main/claude/model-catalog/claude-model-catalog-probe.ts +++ b/src/main/claude/model-catalog/claude-model-catalog-probe.ts @@ -1,3 +1,5 @@ +import { join } from 'node:path' +import { agentModelCatalogInputStamp } from '../../native-chat/agent-model-catalog/agent-model-catalog-input-stamp' import { withOrcaClaudeChatEntrypoint } from '../../../shared/agent-launch/startup/claude-chat-entrypoint' import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { @@ -10,17 +12,8 @@ import { } from '../../../shared/claude-model-list-probe' import { requireLegacyAgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import { runClaudeBackgroundAttempts } from '../../../shared/claude-background-run-isolation' -import { - isCompleteClaudeModelListing, - listedModels, - record -} from '../structured/launch/claude-structured-model-catalog' -import { claudeCatalogSignedOut } from './claude-model-catalog-signed-out' -import { - claudeFastModeSupport, - wireClaudeModels -} from '../structured/launch/claude-structured-catalog-listing' -import { readClaudeSettingsApplied } from '../structured/launch/claude-structured-session-options' +import { listedModels, record } from '../structured/launch/claude-structured-model-catalog' +import { readClaudeCatalogObservation } from './claude-model-catalog-observation' import { readClaudeControlResponses } from '../sdk-transport/claude-control-responses' import { claudeStructuredLaunchArgs } from '../structured/launch/claude-structured-launch-args' import { AgentModelCatalogUnavailableError } from '../../native-chat/agent-model-catalog/agent-model-catalog-unavailable' @@ -39,6 +32,7 @@ import { type ClaudeEnvDeps } from '../structured/launch/claude-structured-child-env' import type { + AgentModelCatalogProgress, AgentModelCatalogProbe, AgentModelCatalogLookup } from '../../native-chat/agent-model-catalog/agent-model-catalog-discovery' @@ -147,7 +141,9 @@ export function createClaudeModelCatalogProbe( const launchDeps = { ...deps, operation, - ...(lookup === 'saved' ? { resolveInheritedEnv: deps.resolveSavedEnvironment } : {}), + ...(lookup !== 'recover' + ? { resolveInheritedEnv: deps.resolveSavedEnvironment ?? deps.resolveInheritedEnv } + : {}), ...(lookup === 'recover' ? {} : { refreshEnvironmentAfterMiss: undefined }), ...(launchDirectory ? { resolveWorkingDirectory: () => launchDirectory } : {}) } @@ -175,6 +171,13 @@ export function createClaudeModelCatalogProbe( const settingSources = listIn === cwd ? CLAUDE_DEFAULT_SETTING_SOURCES : ['user'] const args = argsFor(true, settingSources) return { + inputStamp: await agentModelCatalogInputStamp({ + command, + prefixArgs, + cwd: listIn ?? process.cwd(), + env: launchDirectory ? envWithPathRelativeTo(env, launchDirectory) : env, + configFiles: [join(requireLegacyAgentSessionAccountHome(accountHome).path, 'settings.json')] + }), identity: { command, prefixArgs, @@ -184,7 +187,9 @@ export function createClaudeModelCatalogProbe( }, run: async ( signal?: AbortSignal, - runOperation = operation + runOperation = operation, + _selectedModels?: readonly string[], + publish?: AgentModelCatalogProgress ): Promise => { assertStructuredAgentResolutionCurrent(runOperation) signal?.throwIfAborted() @@ -193,6 +198,14 @@ export function createClaudeModelCatalogProbe( run: (strictMcp) => { assertStructuredAgentResolutionCurrent(runOperation) signal?.throwIfAborted() + const requests = [ + 'orca-model-discovery', + 'orca-model-settings', + 'orca-signin-discovery' + ] + const settled = new Set() + const replies = new Map() + let incomplete: string[] = [] return (deps.runListing ?? runAgentModelCatalogListing)( { command, @@ -208,16 +221,37 @@ export function createClaudeModelCatalogProbe( process.platform ), signal, - partialOutput: { - timeoutMs: 2_000, - ready: (stdout) => { - const replies = readClaudeControlResponses(stdout) - return ( - listedModels(replies.get('orca-model-discovery')).length > 0 && - replies.has('orca-model-settings') + timeoutMs: null, + onOutput: (chunk) => { + const lines = chunk.split('\n') + incomplete.push(lines[0]) + if (lines.length === 1) { + return + } + const stdout = [incomplete.join(''), ...lines.slice(1, -1)].join('\n') + incomplete = [lines.at(-1)!] + const previous = settled.size + for (const [id, value] of readClaudeControlResponses(stdout, (id) => { + if (requests.includes(id)) { + settled.add(id) + } + })) { + if (requests.includes(id)) { + replies.set(id, value) + } + } + if ( + settled.size > previous && + listedModels(replies.get('orca-model-discovery')).length > 0 + ) { + publish?.( + readClaudeCatalogObservation(replies, env, account), + record(record(replies.get('orca-signin-discovery'))?.account) !== null && + record(record(replies.get('orca-model-settings'))?.effective) !== null ) } - } + }, + completeOutput: () => requests.every((id) => settled.has(id)) } ).catch((error: unknown) => { if (error instanceof AgentModelCatalogProbeError) { @@ -237,33 +271,7 @@ export function createClaudeModelCatalogProbe( } throw outcome } - const stdout = outcome - const replies = readClaudeControlResponses(stdout) - const listing = replies.get('orca-model-discovery') - const models = listedModels(listing) - const settings = replies.get('orca-model-settings') - const applied = record(record(settings)?.applied) - const configured = - applied && - ['model', 'effort'].every( - (key) => applied[key] == null || typeof applied[key] === 'string' - ) - ? (readClaudeSettingsApplied(settings) ?? undefined) - : undefined - if (models.length === 0) { - throw new Error('claude listed no models') - } - const fastModeSupport = claudeFastModeSupport(models) - return { - models: wireClaudeModels(models), - origin: 'probe', - complete: isCompleteClaudeModelListing(listing) && configured !== undefined, - ...(fastModeSupport ? { fastModeSupport } : {}), - ...(configured ? { configured } : {}), - ...(claudeCatalogSignedOut(replies.get('orca-signin-discovery'), settings, env) - ? { unavailable: { reason: 'notSignedIn', account } } - : {}) - } + return readClaudeCatalogObservation(readClaudeControlResponses(outcome), env, account) } } } @@ -279,7 +287,10 @@ export function createClaudeModelCatalogProbe( 'recover', options?.operation ) - ).run(options?.signal), - { resolve, resolveLegacy: (home, operation) => resolve(home, undefined, 'recover', operation) } + ).run(options?.signal, options?.operation, options?.selectedModels, options?.publish), + { + resolve, + resolveLegacy: (home, operation, lookup) => resolve(home, undefined, lookup, operation) + } ) } diff --git a/src/main/claude/sdk-transport/claude-control-responses.ts b/src/main/claude/sdk-transport/claude-control-responses.ts index df1f7ab318c..4c5818b6f1d 100644 --- a/src/main/claude/sdk-transport/claude-control-responses.ts +++ b/src/main/claude/sdk-transport/claude-control-responses.ts @@ -6,7 +6,10 @@ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } -export function readClaudeControlResponses(stdout: string): Map { +export function readClaudeControlResponses( + stdout: string, + settled?: (requestId: string) => void +): Map { const responses = new Map() for (const line of stdout.split(/\r?\n/)) { if (!line.trimStart().startsWith('{') || !line.includes('request_id')) { @@ -19,6 +22,12 @@ export function readClaudeControlResponses(stdout: string): Map continue } const response = frame.response + if ( + (response.subtype === 'success' || response.subtype === 'error') && + typeof response.request_id === 'string' + ) { + settled?.(response.request_id) + } if (response.subtype === 'success' && typeof response.request_id === 'string') { responses.set(response.request_id, response.response) } diff --git a/src/main/codex/app-server/codex-app-server-session.ts b/src/main/codex/app-server/codex-app-server-session.ts index 29668ce02cb..03579f0a2b1 100644 --- a/src/main/codex/app-server/codex-app-server-session.ts +++ b/src/main/codex/app-server/codex-app-server-session.ts @@ -25,7 +25,7 @@ export type CodexAppServerInvocation = { env?: Record /** Keys stripped after the overlay, e.g. CODEX_HOME when targeting the real ~/.codex. */ envToDelete?: readonly string[] - timeoutMs: number + timeoutMs: number | null signal?: AbortSignal experimentalApi?: boolean /** Kill unsupervised plugin trees before stdin EOF; root exit leaves children behind and blocks tree killing. */ @@ -186,15 +186,18 @@ export async function runCodexAppServerSession( failPending(error) rejectDeadline(error) } - const deadline = setTimeout( - () => - endSession( - new CodexAppServerTimeoutError( - `codex app-server session exceeded ${invocation.timeoutMs}ms (${invocation.command})` + const deadline = + invocation.timeoutMs === null + ? undefined + : setTimeout( + () => + endSession( + new CodexAppServerTimeoutError( + `codex app-server session exceeded ${invocation.timeoutMs}ms (${invocation.command})` + ) + ), + invocation.timeoutMs ) - ), - invocation.timeoutMs - ) const onAbort = (): void => endSession(new Error('codex app-server session stopped')) if (invocation.signal?.aborted) { onAbort() diff --git a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts index 9f5f9ac9a62..5a798b10f0e 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts @@ -1,5 +1,18 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { runAgentModelCatalogSession } from '../../../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' +import { PrioritySemaphore } from '../../../../shared/priority-semaphore' +import type { AgentModelCatalogSuccess } from '../../../native-chat/agent-model-catalog/agent-model-catalog-entry' +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + getSystemCodexHomePath, + resolveOrcaManagedCodexHomePath +} from '../../configuration/homes/codex-home-paths' +import { createAgentModelCatalogService } from '../../../native-chat/agent-model-catalog/agent-model-catalog-service' +import { AgentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' +import { afterEach, describe, expect, it, vi, onTestFinished } from 'vitest' import { createCodexModelCatalogProbe } from './codex-model-catalog-probe' +import { fetchCodexModelCatalogListing } from './codex-structured-model-catalog' import { runCodexAppServerSession, type CodexAppServerInvocation @@ -13,7 +26,10 @@ const MODEL_ROW = { isDefault: true } -afterEach(() => vi.unstubAllGlobals()) +afterEach(() => { + vi.unstubAllGlobals() + vi.unstubAllEnvs() +}) describe('codex model catalog probe', () => { it.each([ @@ -120,7 +136,7 @@ describe('codex model catalog probe', () => { }) const success = await probe({ variable: 'CODEX_HOME', path: '/homes/a' }) expect(success.complete).toBe(false) - expect(configReadTimeouts).toEqual([3_000]) + expect(configReadTimeouts).toEqual([null]) expect(configReadFailures).toEqual([ expect.objectContaining({ name: 'CodexAppServerTimeoutError', @@ -132,3 +148,271 @@ describe('codex model catalog probe', () => { ]) }, 10_000) }) + +it('observes the shared source config while ignoring mirror writes, and observes a self-contained home itself', async () => { + const folder = await mkdtemp(join(tmpdir(), 'orca-codex-input-source-')) + vi.stubEnv('HOME', folder) + vi.stubEnv('USERPROFILE', folder) + vi.stubEnv('ORCA_USER_DATA_PATH', join(folder, 'user-data')) + const source = getSystemCodexHomePath() + const mirror = resolveOrcaManagedCodexHomePath() + const own = join(folder, 'account') + expect(source.startsWith(folder)).toBe(true) + await Promise.all([source, mirror, own].map((path) => mkdir(path, { recursive: true }))) + for (const path of [source, mirror, own]) { + await writeFile(join(path, 'config.toml'), 'model="original"') + } + let model = 'original' + let account = mirror + const probe = createCodexModelCatalogProbe({ + resolveEnvironment: async () => ({}), + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), + runSession: async (_invocation, body) => + body({ + request: async (method) => + method === 'model/list' + ? { data: [{ ...MODEL_ROW, model }], nextCursor: null } + : method === 'config/read' + ? { config: {} } + : {}, + notify: () => {} + }) + }) + const service = createAgentModelCatalogService({ + store: new AgentModelCatalogStore(), + getConversation: () => undefined, + getRecord: () => undefined, + drivesRecord: () => true, + resolveAccountHome: async () => ({ variable: 'CODEX_HOME', path: account }), + probes: { codex: probe } + }) + try { + const read = () => service.read({ agent: 'codex', workspacePath: folder, waitForListing: true }) + expect(await read()).toMatchObject({ models: [{ id: 'original' }] }) + model = 'changed' + await writeFile(join(mirror, 'config.toml'), 'model="mirrored-probe-write"') + expect(await read()).toMatchObject({ models: [{ id: 'original' }] }) + await writeFile(join(source, 'config.toml'), 'model="source-changed"') + expect(await read()).toMatchObject({ models: [{ id: 'changed' }] }) + account = own + expect(await read()).toMatchObject({ models: [{ id: 'changed' }] }) + model = 'own-changed' + await writeFile(join(own, 'config.toml'), 'model="own-changed"') + expect(await read()).toMatchObject({ models: [{ id: 'own-changed' }] }) + } finally { + await service.stop() + await rm(folder, { recursive: true, force: true }) + } +}) + +it('delivers inventory while config and account are pending, then keeps both late replies', async () => { + const config = Promise.withResolvers() + const account = Promise.withResolvers() + const inventoried = Promise.withResolvers() + const observations: AgentModelCatalogSuccess[] = [] + const probe = createCodexModelCatalogProbe({ + resolveEnvironment: async () => ({}), + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), + runSession: async (_invocation, body) => + body({ + request: async (method, _params, options) => { + if (options?.timeoutMs !== null) { + throw new Error('catalog request retained its response deadline') + } + if (method === 'config/read') { + return config.promise + } + if (method === 'account/read') { + return account.promise + } + return { data: [MODEL_ROW], nextCursor: null } + }, + notify: () => {} + }) + }) + const done = probe( + { variable: 'CODEX_HOME', path: '/account' }, + { + publish: (success) => { + observations.push(success) + inventoried.resolve() + } + } + ) + await inventoried.promise + expect(observations[0]).toMatchObject({ models: [{ id: 'gpt-live' }], complete: false }) + expect(observations[0].configured).toBeUndefined() + config.resolve({ config: { model: 'gpt-live', model_reasoning_effort: 'high' } }) + account.resolve({ requiresOpenaiAuth: true, account: null }) + expect(await done).toMatchObject({ + models: [{ id: 'gpt-live', defaultEffort: 'high' }], + complete: true, + unavailable: { reason: 'notSignedIn' } + }) + expect(observations[0].complete).toBe(false) +}) + +it.each([ + ['empty', { requiresOpenaiAuth: true, account: null }, 'notSignedIn'], + ['rejected', { requiresOpenaiAuth: true, account: null }, 'notSignedIn'], + ['empty', { requiresOpenaiAuth: false, account: { type: 'apiKey' } }, undefined], + ['empty', {}, undefined] +] as const)( + 'classifies %s inventory after delayed account evidence %j without optional config, retaining admission through close', + async (kind, accountResult, reason) => { + const configRead = vi.fn(() => new Promise(() => {})) + const account = Promise.withResolvers() + const inventory = Promise.withResolvers() + const closing = Promise.withResolvers() + const closed = Promise.withResolvers() + onTestFinished(() => { + account.resolve({ requiresOpenaiAuth: true, account: null }) + closed.resolve() + }) + const probe = createCodexModelCatalogProbe({ + resolveEnvironment: async () => ({}), + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), + runSession: async (invocation, body) => + runAgentModelCatalogSession( + () => ({ + request: async (method: string) => { + if (method === 'account/read') { + return account.promise + } + if (method === 'config/read') { + return configRead() + } + inventory.resolve() + if (kind === 'rejected') { + throw new Error('model listing refused') + } + return { data: [], nextCursor: null } + }, + notify: () => {}, + close: () => { + closing.resolve() + return closed.promise + } + }), + body, + { label: 'codex', signal: invocation.signal, timeoutMs: null } + ) + }) + const store = new AgentModelCatalogStore() + const admission = new PrioritySemaphore(1) + const first = store.refresh( + 'signed-out', + 'codex', + (_selected, operation) => + probe( + { variable: 'CODEX_HOME', path: '/account' }, + { operation, signal: operation.signal } + ), + { admission } + ) + await inventory.promise + expect(store.failure('signed-out')).toBeNull() + expect(store.isListing('signed-out')).toBe(true) + account.resolve(accountResult) + await closing.promise + let nextStarted = false + const next = store.refresh( + 'next', + 'codex', + async () => { + nextStarted = true + return { + origin: 'probe', + complete: true, + models: [{ id: 'next', label: 'Next', isDefault: true, efforts: [] }] + } + }, + { admission } + ) + await Promise.resolve() + expect(nextStarted).toBe(false) + closed.resolve() + expect(await first).toBeNull() + expect(configRead).not.toHaveBeenCalled() + expect(store.failure('signed-out')).not.toBeNull() + expect(store.failure('signed-out')?.unavailable).toEqual(reason ? { reason } : undefined) + expect((await next)?.models[0]?.id).toBe('next') + } +) + +// A real child must complete startup and supervised shutdown within this wall-clock budget. +it('settles a failed inventory and pending sign-in classification when the real transport closes', async () => { + const server = String.raw` + const readline = require('node:readline') + readline.createInterface({ input: process.stdin }).on('line', (line) => { + const message = JSON.parse(line) + if (message.method === 'account/read') return + if (message.method === 'model/list') { + process.stdout.write(JSON.stringify({ id: message.id, error: { code: -32000, message: 'inventory unavailable' } }) + '\n', () => process.exit(1)) + return + } + if (typeof message.id === 'number') process.stdout.write(JSON.stringify({ id: message.id, result: {} }) + '\n') + }) + ` + const store = new AgentModelCatalogStore() + const probe = createCodexModelCatalogProbe({ + resolveEnvironment: async () => ({}), + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), + runSession: (invocation, body) => + runCodexAppServerSession( + { ...invocation, command: process.execPath, cliPath: null, args: ['-e', server] }, + body + ) + }) + const home = { variable: 'CODEX_HOME', path: '/account' } + await expect( + store.refresh('closed', 'codex', async (_models, operation) => + probe(home, { operation, signal: operation.signal }) + ) + ).resolves.toBeNull() + expect(store.isListing('closed')).toBe(false) + expect(store.failure('closed')).not.toBeNull() +}, 10_000) + +it('keeps a later nonempty page and late configured model after an empty first page', async () => { + const config = Promise.withResolvers() + const observations: string[][] = [] + const request = vi.fn(async (method: string, params?: Record) => { + if (method === 'config/read') { + return config.promise + } + return params?.cursor + ? { data: [MODEL_ROW], nextCursor: null } + : { data: [], nextCursor: 'next' } + }) + const result = fetchCodexModelCatalogListing({ + connection: { request }, + timeoutMs: null, + publish: (listing) => observations.push(listing.models.map((model) => model.id)) + }) + await vi.waitFor(() => expect(observations).toEqual([['gpt-live']])) + config.resolve({ config: { model: 'gpt-live', model_reasoning_effort: 'high' } }) + expect(await result).toMatchObject({ + complete: true, + models: [{ id: 'gpt-live' }], + configured: { model: 'gpt-live', effort: 'high' } + }) +}) + +it.each(['empty', 'malformed', 'capped'])( + 'returns incomplete %s inventory without optional configuration', + async (kind) => { + const request = vi.fn(async (method: string) => { + if (method === 'config/read') { + throw new Error('configuration cannot provide inventory') + } + return kind === 'malformed' + ? { data: [{}], nextCursor: null } + : { data: [], nextCursor: kind === 'capped' ? 'more' : null } + }) + expect( + await fetchCodexModelCatalogListing({ connection: { request }, timeoutMs: null }) + ).toEqual({ models: [], complete: false }) + expect(request.mock.calls.every(([method]) => method === 'model/list')).toBe(true) + } +) diff --git a/src/main/codex/structured/catalog/codex-model-catalog-probe.ts b/src/main/codex/structured/catalog/codex-model-catalog-probe.ts index 2bc912e2a13..b56dbde9ad7 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.ts @@ -1,3 +1,9 @@ +import { join, resolve as resolvePath } from 'node:path' +import { + getSystemCodexHomePath, + resolveOrcaManagedCodexHomePath +} from '../../configuration/homes/codex-home-paths' +import { agentModelCatalogInputStamp } from '../../../native-chat/agent-model-catalog/agent-model-catalog-input-stamp' import { assertStructuredAgentResolutionCurrent, type StructuredAgentResolutionOperation @@ -21,8 +27,8 @@ import { type CodexStructuredInvocationDeps } from '../launch/codex-structured-launch-resolution' import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' -import { AGENT_MODEL_CATALOG_PROBE_TIMEOUT_MS } from '../../../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' import type { + AgentModelCatalogProgress, AgentModelCatalogProbe, AgentModelCatalogLookup } from '../../../native-chat/agent-model-catalog/agent-model-catalog-discovery' @@ -64,7 +70,9 @@ export function createCodexModelCatalogProbe( const accountHomePath = requireLegacyAgentSessionAccountHome(accountHome).path const overlay = overlayEnvironmentVariables({}, deps.resolveEnv?.(), process.platform) const readEnvironment = - lookup === 'saved' ? deps.resolveSavedEnvironment : deps.resolveEnvironment + lookup !== 'recover' + ? (deps.resolveSavedEnvironment ?? deps.resolveEnvironment) + : deps.resolveEnvironment const { command, prefixArgs, environment } = await resolveCodexStructuredInvocation({ ...deps, operation, @@ -98,15 +106,48 @@ export function createCodexModelCatalogProbe( CODEX_HOME: accountHomePath } return { + inputStamp: await agentModelCatalogInputStamp({ + command, + prefixArgs, + cwd: listIn ?? process.cwd(), + env: launchDirectory ? envWithPathRelativeTo(env, launchDirectory) : env, + configFiles: [ + join( + resolvePath(accountHomePath) === resolvePath(resolveOrcaManagedCodexHomePath()) + ? getSystemCodexHomePath() + : accountHomePath, + 'config.toml' + ) + ] + }), identity: { command, args, cwd: listIn, overlay: Object.entries(overlay).sort() }, run: async ( signal?: AbortSignal, - runOperation = operation + runOperation = operation, + _selectedModels?: readonly string[], + publish?: AgentModelCatalogProgress ): Promise => { assertStructuredAgentResolutionCurrent(runOperation) signal?.throwIfAborted() deps.prepareHome?.(accountHomePath) const run = deps.runSession ?? runCodexAppServerSession + const successFromListing = ( + listing: Awaited>, + unavailable: AgentModelCatalogSuccess['unavailable'] + ): AgentModelCatalogSuccess => { + return { + models: cwd + ? listing.models + : applyCodexConfiguredLaunchDefaults(listing.models, { + model: listing.configured?.model ?? null, + effort: listing.configured?.effort ?? null + }), + complete: listing.complete !== false, + ...(cwd && listing.configured ? { configured: listing.configured } : {}), + origin: 'probe', + ...(unavailable ? { unavailable } : {}) + } + } const { listing, unavailable } = await run( { command, @@ -114,44 +155,60 @@ export function createCodexModelCatalogProbe( ...(listIn ? { cwd: listIn } : {}), cliPath: command, env, - timeoutMs: AGENT_MODEL_CATALOG_PROBE_TIMEOUT_MS, + timeoutMs: null, ...(signal ? { signal } : {}) }, async (rpc) => { - assertStructuredAgentResolutionCurrent(runOperation) - // Overlap model and account reads to avoid serial probe latency. - const listed = fetchCodexModelCatalogListing({ + let latest: Awaited> | undefined + let accountKnown = false + let unavailable: AgentModelCatalogSuccess['unavailable'] + const observe = (next: NonNullable) => { + assertStructuredAgentResolutionCurrent(runOperation) + latest = next + publish?.(successFromListing(next, unavailable), accountKnown) + } + const account = rpc + .request('account/read', { refreshToken: false }, { timeoutMs: null }) + .catch(() => undefined) + .then((response: unknown) => { + assertStructuredAgentResolutionCurrent(runOperation) + if ( + typeof response === 'object' && + response !== null && + !Array.isArray(response) && + 'account' in response + ) { + accountKnown = true + if ( + 'requiresOpenaiAuth' in response && + response.requiresOpenaiAuth === true && + response.account === null + ) { + const kind = deps.resolveAccountKind?.(accountHomePath) + unavailable = { reason: 'notSignedIn', ...(kind ? { account: kind } : {}) } + } + } + if (latest) { + observe(latest) + } + }) + void account.catch(() => {}) + const listing = await fetchCodexModelCatalogListing({ connection: rpc, cwd, - operation: runOperation + operation: runOperation, + timeoutMs: null, + publish: observe + }).catch(async (error: unknown) => { + await account + if (unavailable) { + throw new AgentModelCatalogUnavailableError(unavailable) + } + throw error }) - void listed.catch(() => {}) - assertStructuredAgentResolutionCurrent(runOperation) - const response: unknown = await rpc - .request('account/read', { refreshToken: false }, { timeoutMs: 2_000 }) - // Failed account reads do not establish sign-out. - .catch(() => undefined) - assertStructuredAgentResolutionCurrent(runOperation) - if ( - typeof response !== 'object' || - response === null || - Array.isArray(response) || - !('requiresOpenaiAuth' in response) || - response.requiresOpenaiAuth !== true || - !('account' in response) || - response.account !== null - ) { - return { listing: await listed, unavailable: undefined } - } - const account = deps.resolveAccountKind?.(accountHomePath) - const signedOut = { reason: 'notSignedIn' as const, ...(account ? { account } : {}) } - // Gateways may misreport sign-out; keep models that were successfully listed. - const inHand = await listed.catch(() => null) - assertStructuredAgentResolutionCurrent(runOperation) - if (!inHand?.models.length) { - throw new AgentModelCatalogUnavailableError(signedOut) - } - return { listing: inHand, unavailable: signedOut } + observe(listing) + await account + return { listing, unavailable } } ).catch((error: unknown) => { if (isMissingProviderExecutable(error, command)) { @@ -161,20 +218,12 @@ export function createCodexModelCatalogProbe( }) assertStructuredAgentResolutionCurrent(runOperation) if (listing.models.length === 0) { + if (unavailable) { + throw new AgentModelCatalogUnavailableError(unavailable) + } throw new Error('codex app-server listed no models') } - return { - models: cwd - ? listing.models - : applyCodexConfiguredLaunchDefaults(listing.models, { - model: listing.configured?.model ?? null, - effort: listing.configured?.effort ?? null - }), - complete: listing.complete !== false, - ...(cwd && listing.configured ? { configured: listing.configured } : {}), - origin: 'probe', - ...(unavailable ? { unavailable } : {}) - } + return successFromListing(listing, unavailable) } } } @@ -184,8 +233,14 @@ export function createCodexModelCatalogProbe( >( async (home, options) => (await resolve(home, options?.cwd ?? process.cwd(), 'recover', options?.operation)).run( - options?.signal + options?.signal, + options?.operation, + options?.selectedModels, + options?.publish ), - { resolve, resolveLegacy: (home, operation) => resolve(home, undefined, 'recover', operation) } + { + resolve, + resolveLegacy: (home, operation, lookup) => resolve(home, undefined, lookup, operation) + } ) } diff --git a/src/main/codex/structured/catalog/codex-structured-model-catalog.ts b/src/main/codex/structured/catalog/codex-structured-model-catalog.ts index 55f15f01174..e56a3ec12bc 100644 --- a/src/main/codex/structured/catalog/codex-structured-model-catalog.ts +++ b/src/main/codex/structured/catalog/codex-structured-model-catalog.ts @@ -154,16 +154,17 @@ export async function listCodexModelPages( export async function fetchCodexModelCatalogListing(input: { connection: Pick - timeoutMs?: number + timeoutMs?: number | null deadlineMs?: number cwd?: string operation?: StructuredAgentResolutionOperation + publish?: (listing: CodexModelCatalogListing) => void }): Promise { const deadline = Math.min( input.operation?.deadline ?? Infinity, input.deadlineMs === undefined ? Infinity : Date.now() + input.deadlineMs ) - const remainingTimeout = (): number | undefined => { + const remainingTimeout = (): number | null | undefined => { assertStructuredAgentResolutionCurrent(input.operation) if (!Number.isFinite(deadline)) { return input.timeoutMs @@ -182,6 +183,11 @@ export async function fetchCodexModelCatalogListing(input: { return response }) ) + assertStructuredAgentResolutionCurrent(input.operation) + if (parsedModels.length === 0) { + return { models: [], complete: false } + } + input.publish?.({ models: parsedModels, complete: false }) const configured = await readCodexConfiguredLaunchDefaults( input.connection, remainingTimeout(), diff --git a/src/main/codex/structured/launch/codex-configured-launch-defaults.ts b/src/main/codex/structured/launch/codex-configured-launch-defaults.ts index 42a43a73027..458c14b1988 100644 --- a/src/main/codex/structured/launch/codex-configured-launch-defaults.ts +++ b/src/main/codex/structured/launch/codex-configured-launch-defaults.ts @@ -17,12 +17,12 @@ function configuredText(value: unknown): string | null { export async function readCodexConfiguredLaunchDefaults( connection: Pick, - timeoutMs = CONFIG_READ_TIMEOUT_MS, + timeoutMs: number | null = CONFIG_READ_TIMEOUT_MS, cwd?: string ): Promise { try { const response = await connection.request('config/read', cwd ? { cwd } : {}, { - timeoutMs: Math.min(timeoutMs, CONFIG_READ_TIMEOUT_MS) + timeoutMs: timeoutMs === null ? null : Math.min(timeoutMs, CONFIG_READ_TIMEOUT_MS) }) const config = typeof response === 'object' && response !== null && 'config' in response diff --git a/src/main/ipc/preflight.ts b/src/main/ipc/preflight.ts index 5df5385a9c9..79d92918e35 100644 --- a/src/main/ipc/preflight.ts +++ b/src/main/ipc/preflight.ts @@ -78,11 +78,11 @@ export function registerPreflightHandlers(store?: Pick): v ipcMain.handle( 'preflight:refreshAgents', - async (_event, args?: AgentDetectionRequest & PreflightWake) => + async (_event, args?: AgentDetectionRequest & PreflightWake & { userInitiated?: boolean }) => runPreflightAct(args, async () => { const host: AgentDetectionHost = { kind: 'local', context: args } await assertAgentDetectionHostRunning(host) - return refreshAgentsOnHost(host, detectionOptions(args)) + return refreshAgentsOnHost(host, detectionOptions(args), args?.userInitiated) }) ) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-expiry.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-expiry.ts index 3674f20d6e9..1d65f224792 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-expiry.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-expiry.ts @@ -12,7 +12,7 @@ const ACCOUNT_SETTINGS = { /** Account changes invalidate probe answers even when the account path stays the same. */ export function expireAgentModelCatalogFailuresForSettings( - store: Pick, + store: Pick, updates: Partial ): void { const agents = new Set( @@ -21,7 +21,7 @@ export function expireAgentModelCatalogFailuresForSettings( .map(([, agent]) => agent) ) for (const agent of agents) { - store.expireFailures(agent) + store.expireScopes(agent) } } @@ -72,9 +72,9 @@ export function agentsWithChangedLaunchSettings( ) } -/** Account changes expire failures; command/environment changes also expire saved listings. */ +/** Account and launch-setting changes retain display while requiring rediscovery. */ export function createAgentModelCatalogSettingsExpiry( - store: Pick, + store: Pick, initial: AgentLaunchSettings ): (updates: Partial, settings: AgentLaunchSettings) => void { let launch = initial diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-resolution.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-resolution.ts new file mode 100644 index 00000000000..4c4f8d3a8fe --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-account-resolution.ts @@ -0,0 +1,46 @@ +import { independentAgentModelCatalog } from '../../../shared/agent-session/options/agent-model-catalog-ownership' +import type { AgentModelCatalogServiceDeps } from './agent-model-catalog-service-contract' +import type { AgentModelCatalogLaunch } from './agent-model-catalog-refresh' +import { recordCatalogKey } from './agent-model-catalog-fingerprint' +import { newChatCatalogKey } from './agent-model-catalog-prewarm' +import { catalogFolder, sessionWorkspacePath } from './agent-model-catalog-workspace' + +export async function resolveAgentModelCatalogAccount( + deps: AgentModelCatalogServiceDeps, + launch: AgentModelCatalogLaunch, + current: () => boolean +) { + const { agent, records } = launch + const { record, scoped } = records + const workspacePath = + launch.inSessionWorkspace || + (record && + launch.workspacePath === undefined && + !launch.legacy && + (independentAgentModelCatalog(agent) || deps.agentReadsProjectModelConfig?.(agent) === true)) + ? record + ? await sessionWorkspacePath(deps, record) + : null + : launch.workspacePath + if (!current()) { + return null + } + const folder = await catalogFolder(deps, agent, workspacePath, scoped) + if (!current()) { + return null + } + const account = scoped + ? recordCatalogKey(scoped, folder) + : await newChatCatalogKey(deps, agent, folder) + if (!current() || !account) { + return null + } + return { + record, + scoped, + workspacePath, + folder, + base: account.fingerprint, + probeHome: account.accountHome + } +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts index e49f7e3ad20..224a1c183d8 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts @@ -102,7 +102,7 @@ describe('a live listing beside the account-level discovery', () => { expect(read?.models[0]?.defaultEffort).toBe('high') }) - it('still refreshes the account listing after ten minutes of live saves', async () => { + it('keeps discovery across elapsed time and live saves until the user refreshes', async () => { let configured = 'grok-4' const run = harness(async () => discovery(configured)) expect(await run.defaultOf()).toBe('grok-4') @@ -113,7 +113,10 @@ describe('a live listing beside the account-level discovery', () => { run.advance(60_000) run.saveLive() } - expect(run.store.shouldRefresh(agentModelCatalogFingerprintForRecord(RECORD))).toBe(true) + expect(run.store.shouldRefresh(agentModelCatalogFingerprintForRecord(RECORD))).toBe(false) + await run.catalog.demand({ agent: 'grok' }) + expect(await run.defaultOf()).toBe('grok-4') + run.store.refreshInputs(true) await run.catalog.demand({ agent: 'grok' }) await vi.waitFor(() => expect(run.probes).toHaveBeenCalledTimes(2)) await vi.waitFor(async () => expect(await run.defaultOf()).toBe('grok-3-mini')) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts index 358cd99b082..6d7c579c24e 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery.ts @@ -2,12 +2,24 @@ import type { StructuredAgentResolutionOperation } from '../agent-launch/structu import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import type { AgentModelCatalogSuccess } from './agent-model-catalog-entry' +export type AgentModelCatalogProgress = (( + success: AgentModelCatalogSuccess, + accountKnown?: boolean +) => void) & { + /** Retain the latest accumulator; only real reads or settlement materialize it. */ + defer?: (read: () => AgentModelCatalogSuccess, known: (model: string) => boolean) => void + demanded?: () => ReadonlySet +} + export type AgentModelCatalogResolvedProbe = { identity: unknown + inputStamp?: string /** `operation` owns the run; it defaults to the one the invocation was resolved under. */ run: ( signal?: AbortSignal, - operation?: StructuredAgentResolutionOperation + operation?: StructuredAgentResolutionOperation, + selectedModels?: readonly string[], + publish?: AgentModelCatalogProgress ) => Promise } @@ -22,11 +34,13 @@ export type AgentModelCatalogProbe = (( cwd?: string selectedModels?: readonly string[] operation?: StructuredAgentResolutionOperation + publish?: AgentModelCatalogProgress } ) => Promise) & { resolveLegacy?: ( home: AgentSessionAccountHome, - operation?: StructuredAgentResolutionOperation + operation?: StructuredAgentResolutionOperation, + lookup?: AgentModelCatalogLookup ) => Promise resolve?: ( home: AgentSessionAccountHome, diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-effort-discovery.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-effort-discovery.ts index 3bd96e94007..cc728b573a7 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-effort-discovery.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-effort-discovery.ts @@ -29,7 +29,7 @@ export function createAgentModelEffortDiscovery(input: { }, due: (fingerprint: string, model: string | undefined): boolean => !input.failed(fingerprint) && - agentModelEffortProbeDue(input.entries.get(fingerprint), input.attempts, model, input.now()), + agentModelEffortProbeDue(input.entries.get(fingerprint), input.attempts, model), demand: (fingerprint: string, model: string | undefined): void => demandAgentModelEfforts(input.refreshes.get(fingerprint), model, input.cap), attempted: (fingerprint: string, agent: string, model: string): void => diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-entry-lifetime.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-entry-lifetime.ts index 68c3194af40..ea55d5a5ce0 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-entry-lifetime.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-entry-lifetime.ts @@ -1,39 +1,23 @@ -import { - agentModelCatalogEntryWithSuccess, - type AgentModelCatalogEntry, - type AgentModelCatalogSuccess, - type AgentModelCatalogSource -} from './agent-model-catalog-entry' import { independentAgentModelCatalog, usesModelSpecificAcpEfforts } from '../../../shared/agent-session/options/agent-model-catalog-ownership' - -export const AGENT_MODEL_CATALOG_FRESH_MS = 10 * 60_000 +import type { AgentModelCatalogFailures } from './agent-model-catalog-failures' +import type { AgentModelCatalogPersistence } from './agent-model-catalog-persistence' +import type { createAgentModelEffortDiscovery } from './agent-model-catalog-effort-discovery' +import { + agentModelCatalogEntryWithSuccess, + agentModelCatalogListingKey, + type AgentModelCatalogEntry, + type AgentModelCatalogSuccess, + type AgentModelCatalogSource +} from './agent-model-catalog-entry' export function agentModelCatalogEntryIsStale( entry: AgentModelCatalogEntry, - due: boolean, - now: number + due: boolean ): boolean { - return ( - due || - !entry.discovered || - (independentAgentModelCatalog(entry.agent) && entry.discovered.complete !== true) || - now - entry.discovered.at >= - (independentAgentModelCatalog(entry.agent) ? 2 * 60_000 : AGENT_MODEL_CATALOG_FRESH_MS) - ) -} - -export function pruneAgentModelCatalogPartialAttempts( - attempts: Map, - now: number -): void { - for (const [key, attempt] of attempts) { - if (now - attempt.at >= 2 * 60_000) { - attempts.delete(key) - } - } + return due || !entry.discovered } export function recordAgentModelCatalogPartialAttempt( @@ -55,13 +39,11 @@ export function recordAgentModelCatalogPartialAttempt( export function agentModelEffortProbeDue( entry: AgentModelCatalogEntry | undefined, attempts: Map, - model: string | undefined, - now: number + model: string | undefined ): boolean { if (!model || !entry || !usesModelSpecificAcpEfforts(entry.agent)) { return false } - pruneAgentModelCatalogPartialAttempts(attempts, now) return ( entry.models.some((row) => row.id === model && row.effortsKnown === false) && !attempts.has(JSON.stringify([entry.fingerprint, model])) @@ -132,3 +114,82 @@ export function createAgentModelCatalogEntryFactory( now() ) } + +function writeAgentModelCatalogSuccess( + state: { + entries: Map + retiredObservations: Set + dueEntries: Set + failures: AgentModelCatalogFailures + efforts: ReturnType + entryFromSuccess: ReturnType + persistence: AgentModelCatalogPersistence | null + evict: () => void + }, + fingerprint: string, + agent: string, + success: AgentModelCatalogSuccess, + source: AgentModelCatalogSource, + settled = true, + accountKnown = settled, + unchanged = false +): AgentModelCatalogEntry | null { + const entry = + (unchanged ? state.entries.get(fingerprint) : undefined) ?? + state.entryFromSuccess(fingerprint, agent, success, source) + if (!entry) { + if (settled && source === 'discovery' && independentAgentModelCatalog(agent)) { + state.failures.probeFailed(fingerprint, agent, new Error('agent listed no models')) + } + return null + } + state.retiredObservations.delete(fingerprint) + const previous = state.entries.get(fingerprint) + state.entries.delete(fingerprint) + state.entries.set(fingerprint, entry) + // Live listings cannot clear discovery failures or account-unavailability verdicts. + if (source === 'discovery') { + if (settled) { + state.dueEntries.delete(fingerprint) + } + if (accountKnown || success.unavailable) { + state.failures.listed(fingerprint, agent, success.origin, success.unavailable) + } + } + if (settled && source === 'discovery' && independentAgentModelCatalog(agent)) { + state.efforts.catalogAttempted(fingerprint, agent, success.complete === true) + } + state.evict() + // Unchanged per-turn listings need no disk write. + if ( + previous !== entry && + (!previous || agentModelCatalogListingKey(previous) !== agentModelCatalogListingKey(entry)) + ) { + state.persistence?.save(() => [...state.entries.values()]) + } + return entry +} + +export function createAgentModelCatalogSuccessWriter( + readState: () => Parameters[0] +) { + return ( + fingerprint: string, + agent: string, + success: AgentModelCatalogSuccess, + source: AgentModelCatalogSource, + settled = true, + accountKnown = settled, + unchanged = false + ) => + writeAgentModelCatalogSuccess( + readState(), + fingerprint, + agent, + success, + source, + settled, + accountKnown, + unchanged + ) +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.test.ts new file mode 100644 index 00000000000..ae5d21db97f --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.test.ts @@ -0,0 +1,309 @@ +import { createAcpModelCatalogProbe } from '../../acp/discovery/acp-model-catalog-probe' +import { acpLaunchSpecFor } from '../../acp/launch/acp-launch-registry' +import { openCodeAcpAccountBinding } from '../../opencode/accounts/opencode-structured-account-home' +import { ManagedDataAccountService } from '../../managed-data-accounts/service' +import { mkdtemp, writeFile, readFile, rm, mkdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { expect, it, onTestFinished } from 'vitest' +import { agentModelCatalogInputStamp } from './agent-model-catalog-input-stamp' +import { agentModelCatalogScriptEntry } from './agent-model-catalog-script-entry' +import { createAgentModelCatalogService } from './agent-model-catalog-service' +import { AgentModelCatalogStore } from './agent-model-catalog-store' +import type { AgentModelCatalogProbe } from './agent-model-catalog-discovery' + +it.each(['grok', 'codex'])( + 'observes %s installs before deciding freshness, ignoring probe-owned writes', + async (agent) => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-inputs-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + const script = join(folder, 'cli.js') + const config = join(folder, 'settings.json') + await writeFile(script, 'version-one') + await writeFile(config, '{}') + let model = 'first' + const resolve = async () => ({ + identity: 'same-invocation', + inputStamp: await agentModelCatalogInputStamp({ + command: process.execPath, + prefixArgs: [script], + cwd: folder, + env: {}, + configFiles: [config] + }), + run: async () => ({ + models: [{ id: model, label: model, efforts: [], isDefault: true }], + origin: 'probe' as const + }) + }) + const probe: AgentModelCatalogProbe = Object.assign( + async () => { + throw new Error('unresolved') + }, + { resolve, resolveLegacy: resolve } + ) + const service = createAgentModelCatalogService({ + store: new AgentModelCatalogStore(), + getConversation: () => undefined, + getRecord: () => undefined, + drivesRecord: () => true, + resolveAccountHome: async () => ({ + variable: agent === 'codex' ? 'CODEX_HOME' : 'GROK_HOME', + path: folder + }), + probes: { [agent]: probe } + }) + onTestFinished(() => service.stop()) + const read = () => + service.read({ + agent, + legacy: agent === 'codex', + workspacePath: folder, + waitForListing: true + }) + expect(await read()).toMatchObject({ models: [{ id: 'first' }] }) + model = 'second' + await writeFile(join(folder, '.claude.json'), 'probe usage') + await read() + expect(await read()).toMatchObject({ models: [{ id: 'first' }] }) + await writeFile(script, 'version-two-with-new-model') + expect(await read()).toMatchObject({ models: [{ id: 'second' }] }) + model = 'configured' + await writeFile(config, '{"model":"configured"}') + expect(await read()).toMatchObject({ models: [{ id: 'configured' }] }) + } +) + +it('resolves relative PATH installs and direct interpreter scripts from their actual cwd', async () => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-relative-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + const command = join(folder, 'bin', process.platform === 'win32' ? 'node.exe' : 'node') + await mkdir(dirname(command), { recursive: true }) + await writeFile(command, 'install-one', { mode: 0o755 }) + await writeFile(join(folder, 'cli.js'), 'script-one') + const input = { command: 'node', prefixArgs: ['cli.js'], cwd: folder, env: { PATH: 'bin' } } + const before = await agentModelCatalogInputStamp(input) + await writeFile(command, 'install-two-new') + const installed = await agentModelCatalogInputStamp(input) + expect(installed).not.toBe(before) + await writeFile(join(folder, 'cli.js'), 'script-two-new') + expect(await agentModelCatalogInputStamp(input)).not.toBe(installed) +}) + +it.each(['bun', 'deno'])( + 'observes the direct %s run operand rather than the run subcommand', + async (command) => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-script-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + await writeFile(join(folder, 'agent.ts'), 'one') + const input = { command, prefixArgs: ['run', 'agent.ts'], cwd: folder, env: {} } + const original = await agentModelCatalogInputStamp(input) + await writeFile(join(folder, 'run'), 'unrelated') + expect(await agentModelCatalogInputStamp(input)).toBe(original) + await writeFile(join(folder, 'agent.ts'), 'replacement-script') + expect(await agentModelCatalogInputStamp(input)).not.toBe(original) + } +) + +it('observes the real ACP legacy command script in its listing folder before using saved rows', async () => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-legacy-acp-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + const home = join(folder, 'home') + const workspace = join(folder, 'workspace') + await Promise.all([mkdir(home), mkdir(workspace)]) + await writeFile(join(home, 'agent.js'), 'home-model') + await writeFile(join(workspace, 'agent.js'), 'workspace-model') + const probe = createAcpModelCatalogProbe( + { + ...acpLaunchSpecFor('grok')!, + minimumVersions: undefined, + modelDiscovery: { + kind: 'command', + args: [], + listingNamesConfiguredModel: true, + parse: (id) => [{ id, label: id, efforts: [], isDefault: true }] + } + }, + { + homePath: home, + dataDirectory: folder, + resolveEnvironment: async () => ({}), + resolveCommandSettings: () => ({ + agentCmdOverrides: { grok: `"${process.execPath}" agent.js` } + }), + runListing: async (launch) => readFile(join(launch.cwd!, launch.args[0]!), 'utf8') + } + ) + const store = new AgentModelCatalogStore() + const service = createAgentModelCatalogService({ + store, + getConversation: () => undefined, + getRecord: () => undefined, + drivesRecord: () => true, + resolveAccountHome: async () => ({ variable: 'GROK_HOME', path: home }), + probes: { grok: probe } + }) + onTestFinished(() => service.stop()) + const read = async () => { + const params = { agent: 'grok', legacy: true, workspacePath: workspace, waitForListing: true } + await service.demand(params) + return service.read(params) + } + expect(await read()).toMatchObject({ models: [{ id: 'workspace-model' }] }) + await writeFile(join(workspace, 'agent.js'), 'upgraded-workspace-model') + expect(await read()).toMatchObject({ models: [{ id: 'upgraded-workspace-model' }] }) +}) + +it.each([ + ['node', '--no-warnings'], + ['python3', '-u'] +])('refreshes a cached catalog when the %s script after an option changes', async (name, flag) => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-flagged-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + const home = join(folder, 'home') + const workspace = join(folder, 'workspace') + await Promise.all([mkdir(home), mkdir(workspace)]) + const executable = join(folder, process.platform === 'win32' ? `${name}.exe` : name) + await writeFile(executable, 'fixture interpreter', { mode: 0o755 }) + await writeFile(join(home, 'agent.js'), 'qa/home') + await writeFile(join(workspace, 'agent.js'), 'qa/first') + const accounts = new ManagedDataAccountService(join(folder, 'profiles')) + const probe = createAcpModelCatalogProbe( + { + ...acpLaunchSpecFor('opencode')!, + account: openCodeAcpAccountBinding(() => accounts) + }, + { + homePath: home, + dataDirectory: folder, + resolveEnvironment: async () => ({}), + resolveCommandSettings: () => ({ + agentCmdOverrides: { opencode: `"${executable}" ${flag} agent.js` } + }), + probeVersion: async (input) => { + expect(input).toMatchObject({ + program: executable, + prefixArgs: [flag, 'agent.js'], + cwd: home + }) + return { version: '1.19.5' } + }, + runListing: async (launch) => { + expect(launch).toMatchObject({ + command: executable, + args: [flag, 'agent.js', 'models', '--verbose'], + cwd: workspace + }) + return readFile(join(workspace, 'agent.js'), 'utf8') + } + } + ) + const service = createAgentModelCatalogService({ + store: new AgentModelCatalogStore(), + getConversation: () => undefined, + getRecord: () => undefined, + drivesRecord: () => true, + resolveAccountHome: async () => ({ kind: 'opencode', locator: { kind: 'unmanaged' } }), + listsInChatFolder: new Set(['opencode']), + probes: { opencode: probe } + }) + onTestFinished(() => service.stop()) + const read = () => + service.read({ agent: 'opencode', workspacePath: workspace, waitForListing: true }) + expect(await read()).toMatchObject({ models: [{ id: 'qa/first' }] }) + await writeFile(join(workspace, 'agent.js'), 'qa/upgraded-script') + expect(await read()).toMatchObject({ models: [{ id: 'qa/upgraded-script' }] }) +}) + +it.each([ + { command: 'node', args: ['--trace-warnings', '--no-warnings', 'agent.js', 'argument.txt'] }, + { command: 'node', args: ['-r', 'preload.js', '--import=loader.js', 'agent.js', 'argument.txt'] }, + { command: 'node', args: ['--', '-agent.js'], script: '-agent.js' }, + { command: 'python3', args: ['-u', '-W', 'ignore', '-Xdev', 'agent.js', 'argument.txt'] }, + { command: 'deno', args: ['run', '-A', '--allow-read', 'agent.js', 'argument.txt'] }, + { + command: 'deno', + args: [ + 'run', + '--allow-read=permission.txt', + '--config', + 'config.json', + '--import-map=map.json', + 'agent.js' + ] + } +])( + 'stamps only the direct file in $command $args', + async ({ command, args, script = 'agent.js' }) => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-operand-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + await writeFile(join(folder, script), 'original script') + const input = { command, prefixArgs: args, cwd: folder, env: {} } + const original = await agentModelCatalogInputStamp(input) + for (const name of [ + 'preload.js', + 'loader.js', + 'ignore', + 'permission.txt', + 'config.json', + 'map.json', + 'argument.txt' + ]) { + await writeFile(join(folder, name), 'unselected file changed') + } + expect(await agentModelCatalogInputStamp(input)).toBe(original) + await writeFile(join(folder, script), 'replacement entry script') + expect(await agentModelCatalogInputStamp(input)).not.toBe(original) + } +) + +it.skipIf(process.platform === 'win32')( + 'observes a Node literal filename containing a colon', + async () => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-colon-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + const script = join(folder, 'agent:stable.cjs') + await writeFile(script, 'original script') + const input = { command: 'node', prefixArgs: ['agent:stable.cjs'], cwd: folder, env: {} } + const original = await agentModelCatalogInputStamp(input) + await writeFile(script, 'replacement entry script') + expect(await agentModelCatalogInputStamp(input)).not.toBe(original) + } +) + +it.each<[string, string[]]>([ + ['node', ['--unknown', 'candidate.js', 'agent.js']], + ['node', ['--no-warnings=true', 'candidate.js']], + ['node', ['--require', '--', 'candidate.js']], + ['node', ['--require=', 'candidate.js']], + ['node', ['-rpreload.js', 'candidate.js']], + ['node', ['--eval=candidate.js', 'agent.js']], + ['node', ['-p', 'candidate.js', 'agent.js']], + ['node', ['inspect', 'candidate.js']], + ['node', ['-', 'candidate.js']], + ['node', ['--']], + ['python3', ['-c', 'candidate.js', 'agent.js']], + ['python3', ['-mcandidate.js', 'agent.js']], + ['python3', ['-uB', 'candidate.js']], + ['deno', ['run', '--unknown=value', 'candidate.js']], + ['deno', ['run', '--allow-fictional', 'candidate.js']], + ['deno', ['run', '--config', '--', 'candidate.js']], + ['deno', ['run', '--allow-read=', 'candidate.js']], + ['deno', ['run', 'npm:candidate.js']], + ['deno', ['run', 'https://example.com/candidate.js']], + ['deno', ['run', '-', 'candidate.js']] +])('does not guess a file for opaque %s arguments %j', async (command, args) => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-opaque-')) + onTestFinished(() => rm(folder, { recursive: true, force: true })) + const input = { command, prefixArgs: args, cwd: folder, env: {} } + const original = await agentModelCatalogInputStamp(input) + await writeFile(join(folder, 'candidate.js'), 'not an identified file') + await writeFile(join(folder, 'agent.js'), 'not an identified file') + expect(await agentModelCatalogInputStamp(input)).toBe(original) +}) + +it('recognizes a Deno Windows file without treating its drive as a URI scheme', () => { + expect(agentModelCatalogScriptEntry('deno', ['run', '-A', 'C:\\tools\\agent.ts'])).toBe( + 'C:\\tools\\agent.ts' + ) +}) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.ts new file mode 100644 index 00000000000..5a0b91b8683 --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-input-stamp.ts @@ -0,0 +1,49 @@ +import { access, realpath, stat } from 'node:fs/promises' +import { constants } from 'node:fs' +import { basename, delimiter, isAbsolute, resolve } from 'node:path' +import { getExecutableNames } from '../../../shared/node-cli-command-resolution' +import { agentModelCatalogScriptEntry } from './agent-model-catalog-script-entry' + +async function fileStamp(path: string): Promise { + try { + const target = await realpath(path) + const info = await stat(target) + return [target, info.ino, info.size, info.ctimeMs, info.mtimeMs] + } catch { + return [path, 'unknown'] + } +} + +/** Observe install/config identity without running the CLI or reading credentials. */ +export async function agentModelCatalogInputStamp(input: { + command: string + prefixArgs?: readonly string[] + cwd: string + env: NodeJS.ProcessEnv + configFiles?: readonly string[] +}): Promise { + const pathEnv = input.env.PATH ?? input.env.Path ?? '' + let executable = resolve(input.cwd, input.command) + if (!isAbsolute(input.command) && !/[\\/]/.test(input.command)) { + search: for (const directory of pathEnv.split(delimiter)) { + for (const name of getExecutableNames(process.platform, input.command)) { + const candidate = resolve(input.cwd, directory, name) + try { + await access(candidate, process.platform === 'win32' ? constants.F_OK : constants.X_OK) + executable = candidate + break search + } catch {} + } + } + } + const interpreter = basename(input.command) + .replace(/\.exe$/i, '') + .toLowerCase() + const operand = agentModelCatalogScriptEntry(interpreter, input.prefixArgs ?? []) + const script = operand ? resolve(input.cwd, operand) : undefined + return JSON.stringify([ + await fileStamp(executable), + script ? await fileStamp(script) : null, + await Promise.all((input.configFiles ?? []).map(fileStamp)) + ]) +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-inputs.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-inputs.ts new file mode 100644 index 00000000000..d705ecfff78 --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-inputs.ts @@ -0,0 +1,83 @@ +import type { AgentModelCatalogEntry } from './agent-model-catalog-entry' +import type { AgentModelCatalogFailures } from './agent-model-catalog-failures' +import type { AgentModelCatalogListingWaiters } from './agent-model-catalog-listing-waiters' +import { retireAgentModelCatalogListing, type InFlightListing } from './agent-model-catalog-lister' + +export class AgentModelCatalogInputs { + private readonly inputStamps = new Map() + + constructor( + private readonly state: { + entries: Map + refreshes: Map + dueEntries: Set + failures: AgentModelCatalogFailures + partialAttempts: Map + listingWaiters: AgentModelCatalogListingWaiters + agents: () => Iterable + retireAgent: (agent: string) => void + cap: number + } + ) {} + + observeInputs(fingerprint: string, stamp: string): void { + const previous = this.inputStamps.get(fingerprint) + this.inputStamps.delete(fingerprint) + this.inputStamps.set(fingerprint, stamp) + if (previous !== stamp && (previous !== undefined || this.state.entries.has(fingerprint))) { + this.expireScope(fingerprint) + } + if (this.inputStamps.size > this.state.cap) { + this.inputStamps.delete(this.inputStamps.keys().next().value!) + } + } + + expireScope(fingerprint: string): void { + const flight = this.state.refreshes.get(fingerprint) + if (flight) { + retireAgentModelCatalogListing( + this.state.refreshes, + this.state.listingWaiters, + fingerprint, + flight + ) + } + if (this.state.entries.has(fingerprint)) { + this.state.dueEntries.add(fingerprint) + } + this.state.failures.expire(fingerprint) + this.state.partialAttempts.delete(fingerprint) + const prefix = `${JSON.stringify([fingerprint]).slice(0, -1)},` + for (const key of this.state.partialAttempts.keys()) { + if (key.startsWith(prefix)) { + this.state.partialAttempts.delete(key) + } + } + } + + refreshInputs(userInitiated: boolean): void { + for (const agent of this.state.agents()) { + this.state.failures.expireAgent(agent) + } + if (userInitiated) { + this.expireScopes() + } + } + + expireScopes(agent?: string): void { + if (agent) { + this.state.retireAgent(agent) + } + const scopes = new Set([ + ...[...this.state.entries.values()] + .filter((entry) => !agent || entry.agent === agent) + .map((entry) => entry.fingerprint), + ...[...this.state.refreshes] + .filter(([, flight]) => !agent || flight.agent === agent) + .map(([fingerprint]) => fingerprint) + ]) + for (const fingerprint of scopes) { + this.expireScope(fingerprint) + } + } +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts index c070ecf3eb0..237702e6dd7 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lister.ts @@ -1,5 +1,4 @@ import type { StructuredAgentResolutionOperation } from '../agent-launch/structured-agent-command-resolution' -import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import type { PrioritySemaphore } from '../../../shared/priority-semaphore' import { startSpan } from '../../observability/tracer' import { @@ -12,10 +11,7 @@ import type { AgentModelCatalogSource, AgentModelCatalogSuccess } from './agent-model-catalog-entry' -import type { - AgentModelCatalogProbe, - AgentModelCatalogResolvedProbe -} from './agent-model-catalog-discovery' +import type { AgentModelCatalogProgress } from './agent-model-catalog-discovery' import type { AgentModelCatalogStore } from './agent-model-catalog-store' /** Pin listings to the spawned child's account so later selections cannot receive its results. */ @@ -25,26 +21,25 @@ export type AgentModelCatalogSessionAccess = { accountHomePath: string } -/** `owner` is the listing's own operation: its fixed budget, never a reader's. */ +/** The owner outlives readers and fences all observations from this listing. */ export type AgentModelCatalogListModels = ( selectedModels: readonly string[] | undefined, - owner: StructuredAgentResolutionOperation + owner: StructuredAgentResolutionOperation, + publish?: AgentModelCatalogProgress ) => Promise /** Covers the gap between one waiting read and the next, so a following reader keeps its place. */ const AGENT_MODEL_CATALOG_RELEASE_GRACE_MS = 5_000 -/** Queued listings need a holder; admitted probes run to their own timeout. */ +/** Queued listings need a holder; admitted probes run until completion or retirement. */ export type AgentModelCatalogListingBudget = { - /** Expiry withdraws it from admission, stops its process and drops its late answer. */ + /** Queue expiry withdraws unadmitted work only. */ deadline?: number /** This caller's interest; a queued listing is withdrawn a grace after no holder is left. */ signal?: AbortSignal /** Service shutdown retires the listing immediately, without the holder release grace. */ lifetime?: AbortSignal admission?: PrioritySemaphore - /** Execution time after admission. */ - timeoutMs?: number } export type InFlightListing = { @@ -53,6 +48,7 @@ export type InFlightListing = { current: () => boolean /** Adds a queued holder until its signal aborts; admitted probes need none. */ hold: (signal: AbortSignal | undefined) => void + flush: (model?: string) => void promise: Promise finish: (entry: AgentModelCatalogEntry | null) => void cleanup: () => void @@ -64,7 +60,11 @@ export function demandAgentModelEfforts( cap: number ): void { if (model && flight && flight.targets.size < cap) { + const fresh = !flight.targets.has(model) flight.targets.add(model) + if (fresh) { + flight.flush(model) + } } } @@ -96,15 +96,19 @@ export function refreshAgentModelCatalogListing(input: { refreshes: Map failures: AgentModelCatalogFailures listingWaiters: AgentModelCatalogListingWaiters + failed: () => void writeSuccess: ( fingerprint: string, agent: string, success: AgentModelCatalogSuccess, - source: AgentModelCatalogSource + source: AgentModelCatalogSource, + settled?: boolean, + accountKnown?: boolean, + unchanged?: boolean ) => AgentModelCatalogEntry | null }): Promise { const { fingerprint, agent, listModels } = input - const { signal, lifetime, admission, timeoutMs, deadline: budgetDeadline } = input.budget ?? {} + const { signal, lifetime, admission, deadline: budgetDeadline } = input.budget ?? {} let deadline = budgetDeadline const existing = input.refreshes.get(fingerprint) if (existing) { @@ -117,6 +121,8 @@ export function refreshAgentModelCatalogListing(input: { let expiry: ReturnType | undefined const holders = new Map void>() // A listing started without a signal is held until it settles. + let admitted = false + const queuedAt = Date.now() let held = signal === undefined const setDeadline = (next: number | undefined): void => { deadline = next @@ -125,10 +131,12 @@ export function refreshAgentModelCatalogListing(input: { expiry = setTimeout(retire, Math.max(0, deadline - Date.now())) } } + let flush: (model?: string) => void = () => {} const flight: InFlightListing = { agent, targets: new Set(input.selectedModel ? [input.selectedModel] : []), - current: () => !lifetime?.aborted && (deadline === undefined || Date.now() < deadline), + current: () => + !lifetime?.aborted && (admitted || deadline === undefined || Date.now() < deadline), hold: (holder) => { if (!held && holder && !holder.aborted && !holders.has(holder)) { setDeadline(budgetDeadline) @@ -147,6 +155,7 @@ export function refreshAgentModelCatalogListing(input: { holder.addEventListener('abort', abandon, { once: true }) } }, + flush: (model) => flush(model), promise: result.promise, finish: result.resolve, cleanup: () => { @@ -171,51 +180,114 @@ export function refreshAgentModelCatalogListing(input: { const span = startSpan('agentModelCatalog.discovery', { attributes: { agent, lister: 'probe' } }) void Promise.resolve().then(async () => { let release: (() => void) | undefined + let entry: AgentModelCatalogEntry | null = null + let lastSuccess: AgentModelCatalogSuccess | undefined + let lastAccountKnown = false + let published: string | undefined + let deferred: + | { read: () => AgentModelCatalogSuccess; known: (model: string) => boolean } + | undefined + const publish = (success: AgentModelCatalogSuccess, accountKnown = false, settled = false) => { + if (!current() || stopped.signal.aborted || success.models.length === 0) { + return + } + const key = JSON.stringify([success, accountKnown]) + if (key === published) { + if (settled) { + entry = input.writeSuccess( + fingerprint, + agent, + success, + 'discovery', + true, + accountKnown, + true + ) + } + return + } + deferred = undefined + published = key + lastSuccess = success + lastAccountKnown = accountKnown + entry = input.writeSuccess(fingerprint, agent, success, 'discovery', settled, accountKnown) + input.listingWaiters.notify(fingerprint) + } + const progress: AgentModelCatalogProgress = Object.assign(publish, { + defer: (read: () => AgentModelCatalogSuccess, known: (model: string) => boolean) => { + if (current() && !stopped.signal.aborted) { + deferred = { read, known } + } + }, + demanded: () => flight.targets + }) + flush = (model) => { + if (!current() || stopped.signal.aborted || !deferred || (model && !deferred.known(model))) { + return + } + const observation = deferred + deferred = undefined + publish(observation.read(), true) + } try { release = await admission?.acquire(0, stopped.signal) if (!current()) { span.end() return } + admitted = true + span.setAttribute('queuedMs', Date.now() - queuedAt) held = true - // Admission replaces the abandonment deadline with the probe's own execution budget. - setDeadline( - timeoutMs === undefined - ? budgetDeadline - : Math.min(budgetDeadline ?? Infinity, Date.now() + timeoutMs) - ) + setDeadline(undefined) const owner: StructuredAgentResolutionOperation = { - current, - signal: stopped.signal, - deadline + current: () => current() && !stopped.signal.aborted, + signal: stopped.signal } - let targets = input.selectedModel ? [input.selectedModel] : undefined - let entry: AgentModelCatalogEntry | null = null + let targets = flight.targets.size > 0 ? [...flight.targets] : undefined + const tried = new Set() do { - const success = await listModels(targets, owner) + for (const target of targets ?? []) { + tried.add(target) + } + const success = await listModels(targets, owner, progress) if (!current()) { return } + deferred = undefined span.setAttribute('models', success.models.length) - entry = input.writeSuccess(fingerprint, agent, success, 'discovery') - const attempted = new Set(targets ? (success.attemptedModels ?? targets) : []) - for (const target of targets ?? []) { - if (attempted.has(target)) { - input.targetAttempted(target) - } + publish(success, lastSuccess ? lastAccountKnown : true, true) + const attempted = new Set(success.attemptedModels ?? targets ?? []) + for (const target of attempted) { + tried.add(target) + input.targetAttempted(target) + } + for (const target of flight.targets) { if (attempted.has(target) || !input.targetDue(target)) { flight.targets.delete(target) } } - targets = [...flight.targets].filter(input.targetDue) - } while (targets.length > 0 && current()) + targets = [...flight.targets].filter( + (target) => !tried.has(target) && input.targetDue(target) + ) + } while (targets.length > 0 && current() && !stopped.signal.aborted) if (current()) { flight.finish(entry) } span.end() } catch (error) { span.fail(error instanceof Error ? error : String(error)) - if (current() && !(error instanceof AgentModelCatalogListingStoppedError)) { + if ( + current() && + !stopped.signal.aborted && + !(error instanceof AgentModelCatalogListingStoppedError) + ) { + flush() + if (entry && lastSuccess) { + publish({ ...lastSuccess, complete: false }, lastAccountKnown, true) + flight.finish(entry) + return + } + input.failed() input.failures.probeFailed(fingerprint, agent, error) } } finally { @@ -225,45 +297,3 @@ export function refreshAgentModelCatalogListing(input: { }) return flight.promise } - -export function scopedAgentModelCatalogLister(input: { - legacy?: boolean - signal: AbortSignal - resolved: AgentModelCatalogResolvedProbe | undefined - probe: AgentModelCatalogProbe | undefined - probeHome: AgentSessionAccountHome | null - workspacePath: string | undefined -}): AgentModelCatalogListModels { - const { legacy, resolved, probe, probeHome, workspacePath } = input - return async (selectedModels, operation) => { - const signal = operation.signal - ? AbortSignal.any([input.signal, operation.signal]) - : input.signal - const deadline = new AbortController() - // Share the retry budget and await bounded provider teardown before settling. - const timer = legacy ? setTimeout(() => deadline.abort(), 30_000) : undefined - const attemptSignal = AbortSignal.any([signal, deadline.signal]) - try { - // A slot that frees as the budget ends never starts the queued listing. - if (operation.current?.() === false) { - throw new AgentModelCatalogListingStoppedError('listing budget ended') - } - if (resolved) { - return await resolved.run(attemptSignal, operation) - } - if (!probe || !probeHome) { - throw new AgentModelCatalogListingStoppedError('catalog scope unavailable') - } - return await probe(probeHome, { - signal: attemptSignal, - workspacePath, - ...(selectedModels ? { selectedModels } : {}), - operation - }) - } catch (error) { - throw signal.aborted ? new AgentModelCatalogListingStoppedError(String(error)) : error - } finally { - clearTimeout(timer) - } - } -} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-listing-waiters.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-listing-waiters.ts index c88765eacf8..a0f7ef5c45b 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-listing-waiters.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-listing-waiters.ts @@ -1,10 +1,6 @@ import type { AgentModelCatalogStore } from './agent-model-catalog-store' import type { AgentModelCatalogReadParams } from './agent-model-catalog-service-contract' import type { AgentModelCatalogBinding } from './agent-model-catalog-snapshot' -import { - independentAgentModelCatalog, - usesModelSpecificAcpEfforts -} from '../../../shared/agent-session/options/agent-model-catalog-ownership' import { withTimeout } from '../../../shared/promise-timeout-fallback' import type { AgentModelCatalogEntry } from './agent-model-catalog-entry' import type { AgentModelCatalogRefresh } from './agent-model-catalog-refresh' @@ -25,12 +21,13 @@ export class AgentModelCatalogListingWaiters { fingerprint: string, waitForChange = false, terminal = false, - signal?: AbortSignal + signal?: AbortSignal, + baseline?: AgentModelCatalogEntry | null ): Promise | null { if (!this.listing(fingerprint) || signal?.aborted) { return null } - const previous = this.read(fingerprint) + const previous = baseline === undefined ? this.read(fingerprint) : baseline return new Promise((resolve) => { const waiters = this.waiters.get(fingerprint) ?? new Set<() => void>() let settled = false @@ -99,29 +96,35 @@ export async function waitForAgentModelCatalogRead(input: { params: AgentModelCatalogReadParams reader: { deadline: number; signal: AbortSignal } store: AgentModelCatalogStore - refresh: AgentModelCatalogRefresh | undefined + refresh: () => AgentModelCatalogRefresh | undefined binding: () => AgentModelCatalogBinding | undefined }): Promise { - const { params, store, refresh } = input + const { params, store } = input // Once the reader stops waiting, nothing it left behind subscribes to or holds a listing wait. const left = new AbortController() + const original = input.binding() + const baseline = original ? store.get(original.fingerprint) : null + const refresh = input.refresh() const wait = async (): Promise => { await refresh?.listing - await (refresh?.defaults ?? input.binding()?.projecting) const bound = left.signal.aborted ? undefined : input.binding() - if ( - bound && - (!store.get(bound.fingerprint) || - independentAgentModelCatalog(params.agent) || - (usesModelSpecificAcpEfforts(params.agent) && store.isListing(bound.fingerprint)) || - store.heldReasonDue(bound.fingerprint)) - ) { - await store.pendingListing( + if (bound) { + const entry = store.get(bound.fingerprint) + if (params.progress !== false && entry && entry !== baseline) { + return + } + const pending = store.pendingListing( bound.fingerprint, true, - params.legacy || usesModelSpecificAcpEfforts(params.agent), - left.signal + params.progress === false, + left.signal, + baseline ) + const projection = + params.progress === false && store.isListing(bound.fingerprint) + ? undefined + : bound.projecting + await (pending && projection ? Promise.race([pending, projection]) : (pending ?? projection)) } if (bound && !store.isListing(bound.fingerprint)) { await refresh?.done diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-lookup.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lookup.ts index c887e78f97a..9bbd4c45abb 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-lookup.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lookup.ts @@ -54,6 +54,7 @@ export function createAgentModelCatalogLookup( return undefined } const refresh = refreshes.join(found.key, found.launch) + refresh.hold(operation) refresh.want( usesModelSpecificAcpEfforts(params.agent) ? (params.selectedModel ?? diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts index 11c34b40566..9dc30f878c5 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts @@ -168,6 +168,46 @@ describe('the shared catalog probe runner', () => { expect(failure).toMatchObject({ reason: 'spawn', executableMissing: true }) }) + it('returns a ready partial list on work expiry, awaits close, and drops it on cancellation', async () => { + for (const expiry of ['body', 'owner', 'cancel'] as const) { + const stop = new AbortController() + const closing = Promise.withResolvers() + const beganClose = Promise.withResolvers() + const run = runAgentModelCatalogSession( + () => ({ + close: () => { + beganClose.resolve() + return closing.promise + } + }), + async (_connection, ready) => { + ready( + async () => {}, + () => ['usable-model'] + ) + return new Promise(() => {}) + }, + { label: 'partial', signal: stop.signal, timeoutMs: expiry === 'body' ? 20 : 60_000 } + ) + const observed = run.then( + (value) => value, + (error: unknown) => error + ) + if (expiry !== 'body') { + stop.abort( + expiry === 'owner' ? new AgentModelCatalogProbeError('deadline', 'timeout') : undefined + ) + } + await beganClose.promise + closing.resolve() + if (expiry === 'cancel') { + expect(await observed).toMatchObject({ reason: 'stopped' }) + } else { + expect(await observed).toEqual(['usable-model']) + } + } + }) + it('closes a probe connection on success, failure and timeout alike', async () => { const closes: string[] = [] const open = (name: string) => () => ({ diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.ts index d65011427c1..f8576dfc81d 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.ts @@ -1,5 +1,6 @@ import type { ClaudeBackgroundFailedExit } from '../../../shared/claude-background-run-isolation' import type { PipedProcessSpawner } from '@orca/process-host/process-spec' +import { StringDecoder } from 'node:string_decoder' import { withTimeout } from '../../../shared/promise-timeout-fallback' import { createOutputSink } from '@orca/process-host/bounded-output-sink' @@ -53,7 +54,7 @@ export type AgentModelCatalogListingLaunch = ProviderProcessLaunch & { export type AgentModelCatalogRunnerOptions = { site: string - timeoutMs?: number + timeoutMs?: number | null maxOutputBytes?: number signal?: AbortSignal spawnImpl?: PipedProcessSpawner @@ -61,6 +62,8 @@ export type AgentModelCatalogRunnerOptions = { inheritedEnv?: NodeJS.ProcessEnv /** Finish required replies even when an optional control request never completes. */ partialOutput?: { ready: (stdout: string) => boolean; timeoutMs: number } + onOutput?: (chunk: string) => void + completeOutput?: () => boolean } /** Bound the listing and await child teardown before success, failure or cancellation settles. */ @@ -68,7 +71,8 @@ export async function runAgentModelCatalogListing( launch: AgentModelCatalogListingLaunch, options: AgentModelCatalogRunnerOptions ): Promise { - const timeoutMs = options.timeoutMs ?? AGENT_MODEL_CATALOG_PROBE_TIMEOUT_MS + const timeoutMs = + options.timeoutMs === undefined ? AGENT_MODEL_CATALOG_PROBE_TIMEOUT_MS : options.timeoutMs throwIfStopped(options.signal, launch.command) const managed = spawnManagedProviderProcess(launch, { site: options.site, @@ -79,6 +83,7 @@ export async function runAgentModelCatalogListing( ...(options.platform ? { platform: options.platform } : {}), ...(options.inheritedEnv ? { inheritedEnv: options.inheritedEnv } : {}) }) + const progressDecoder = options.onOutput ? new StringDecoder('utf8') : undefined const { child } = managed const output = createOutputSink( options.maxOutputBytes ?? AGENT_MODEL_CATALOG_PROBE_MAX_OUTPUT_BYTES @@ -106,13 +111,22 @@ export async function runAgentModelCatalogListing( // Required replies already in hand outlive an optional reply that runs out of time or room. const failUnlessReady = (message: string, reason: AgentModelCatalogProbeFailure): void => partialTimer === undefined ? fail(message, reason) : resolve(output.text()) - onAbort = () => fail(`${launch.command} listing stopped`, 'stopped') + onAbort = () => + isAgentModelCatalogWorkTimeout(options.signal) + ? failUnlessReady(`${launch.command} listing timed out`, 'timeout') + : fail(`${launch.command} listing stopped`, 'stopped') options.signal?.addEventListener('abort', onAbort, { once: true }) - timer = setTimeout( - () => - failUnlessReady(`${launch.command} did not list models within ${timeoutMs}ms`, 'timeout'), - timeoutMs - ) + timer = + timeoutMs === null + ? undefined + : setTimeout( + () => + failUnlessReady( + `${launch.command} did not list models within ${timeoutMs}ms`, + 'timeout' + ), + timeoutMs + ) child.stdout.on('data', (chunk: Buffer | string) => { output.write(chunk) if (output.truncated()) { @@ -120,8 +134,24 @@ export async function runAgentModelCatalogListing( `${launch.command} listed more than the model catalog reads`, 'output-overflow' ) - } else if (partialTimer === undefined && options.partialOutput?.ready(output.text())) { - partialTimer = setTimeout(() => resolve(output.text()), options.partialOutput.timeoutMs) + } else { + try { + if (progressDecoder) { + options.onOutput?.( + progressDecoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)) + ) + } + if (options.completeOutput?.()) { + resolve(output.text()) + } else if (partialTimer === undefined && options.partialOutput?.ready(output.text())) { + partialTimer = setTimeout( + () => resolve(output.text()), + options.partialOutput.timeoutMs + ) + } + } catch (error) { + reject(error) + } } }) child.stdout.on('error', () => {}) @@ -167,41 +197,61 @@ function throwIfStopped(signal: AbortSignal | undefined, label: string): void { } } +export function isAgentModelCatalogWorkTimeout(signal?: AbortSignal): boolean { + return ( + signal?.aborted === true && + signal.reason instanceof AgentModelCatalogProbeError && + signal.reason.reason === 'timeout' + ) +} + +export type AgentModelCatalogReady = (cleanup: () => Promise, partial?: () => T) => void + export type AgentModelCatalogProbeConnection = { close(): Promise } export async function runAgentModelCatalogSession( open: () => C, - body: (connection: C, ready: (cleanup: () => Promise) => void) => Promise, - options: { label: string; timeoutMs?: number; signal?: AbortSignal } + body: (connection: C, ready: AgentModelCatalogReady) => Promise, + options: { label: string; timeoutMs?: number | null; signal?: AbortSignal } ): Promise { - const timeoutMs = options.timeoutMs ?? AGENT_MODEL_CATALOG_PROBE_TIMEOUT_MS + const timeoutMs = + options.timeoutMs === undefined ? AGENT_MODEL_CATALOG_PROBE_TIMEOUT_MS : options.timeoutMs throwIfStopped(options.signal, options.label) const connection = open() let timer: ReturnType | undefined let cleanup: (() => Promise) | undefined - const ready = (closeSession: () => Promise): void => { - cleanup = closeSession - clearTimeout(timer) + let partial: (() => T) | undefined + let settled = false + const ready: AgentModelCatalogReady = (closeSession, readPartial) => { + if (!settled) { + cleanup = closeSession + partial = readPartial + } } let onAbort = (): void => {} - const deadline = new Promise((_resolve, reject) => { - onAbort = () => - reject(new AgentModelCatalogProbeError(`${options.label} listing stopped`, 'stopped')) + const deadline = new Promise((resolve, reject) => { + const expire = (): void => { + settled = true + if (partial) { + resolve(partial()) + } else { + reject(new AgentModelCatalogProbeError(`${options.label} listing timed out`, 'timeout')) + } + } + onAbort = () => { + if (isAgentModelCatalogWorkTimeout(options.signal)) { + expire() + } else { + reject(new AgentModelCatalogProbeError(`${options.label} listing stopped`, 'stopped')) + } + } options.signal?.addEventListener('abort', onAbort, { once: true }) - timer = setTimeout( - () => - reject( - new AgentModelCatalogProbeError( - `${options.label} did not list models within ${timeoutMs}ms`, - 'timeout' - ) - ), - timeoutMs - ) + timer = timeoutMs === null ? undefined : setTimeout(expire, timeoutMs) }) try { return await Promise.race([body(connection, ready), deadline]) } finally { + settled = true clearTimeout(timer) options.signal?.removeEventListener('abort', onAbort) if (cleanup) { diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-refresh.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-refresh.ts index 202174b0d1b..d8593cba732 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-refresh.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-refresh.ts @@ -1,3 +1,4 @@ +import { resolveAgentModelCatalogAccount } from './agent-model-catalog-account-resolution' import type { PrioritySemaphore } from '../../../shared/priority-semaphore' import { independentAgentModelCatalog } from '../../../shared/agent-session/options/agent-model-catalog-ownership' import type { @@ -5,16 +6,12 @@ import type { AgentModelCatalogServiceDeps } from './agent-model-catalog-service-contract' import type { AgentModelCatalogReadRecords } from './agent-model-catalog-running-account' -import { recordCatalogKey } from './agent-model-catalog-fingerprint' -import { newChatCatalogKey } from './agent-model-catalog-prewarm' import { agentModelCatalogDefaultFollowsAccount, - agentModelCatalogListedDefault, - catalogFolder, - sessionWorkspacePath + agentModelCatalogListedDefault } from './agent-model-catalog-workspace' import { resolveAgentModelCatalogScope } from './agent-model-catalog-scope' -import { scopedAgentModelCatalogLister } from './agent-model-catalog-lister' +import { scopedAgentModelCatalogLister } from './agent-model-catalog-scoped-lister' import { seedAccountList } from './agent-model-catalog-account-list' import type { AgentModelCatalogEntry } from './agent-model-catalog-entry' import { @@ -22,10 +19,7 @@ import { bindAgentModelCatalogScope, type AgentModelCatalogBinding } from './agent-model-catalog-snapshot' -import { AGENT_MODEL_CATALOG_PICKER_WAIT_MS } from './agent-model-catalog-listing-waiters' - -/** Bounds scope resolution and the folder's settings; listings own their execution budget. */ -const AGENT_MODEL_CATALOG_REFRESH_MS = AGENT_MODEL_CATALOG_PICKER_WAIT_MS +import type { AgentModelCatalogReadOperation } from './agent-model-catalog-operation' /** What a refresh resolves, captured when it starts; no reader's session, deadline or callback. */ export type AgentModelCatalogLaunch = { @@ -48,6 +42,7 @@ export type AgentModelCatalogRefresh = { defaults: Promise /** Its listing ingested and the account's list seeded, or it ended. */ done: Promise + hold: (reader: AgentModelCatalogReadOperation) => void /** Also lists efforts for a reader's selected model. */ want: (model: string | undefined) => void } @@ -55,7 +50,7 @@ export type AgentModelCatalogRefresh = { type Held = AgentModelCatalogRefresh & { workspaceId?: string; end: () => void } /** Equivalent requests share one refresh that belongs to no reader. It ends when it finishes, at - * its setup budget, on its agent's or workspace's retirement, or with the service; readers only + * on its agent's or workspace's retirement, or with the service; readers only * wait on it, each until its own deadline or cancellation, and never extend or end it. */ export function createAgentModelCatalogRefreshes(context: { deps: AgentModelCatalogServiceDeps @@ -70,16 +65,11 @@ export function createAgentModelCatalogRefreshes(context: { const start = (key: string, launch: AgentModelCatalogLaunch): Held => { const { agent } = launch const retirement = deps.store.retirementRevision(agent) - const deadline = Date.now() + AGENT_MODEL_CATALOG_REFRESH_MS const ended = new AbortController() - // Retiring its agent ends it at once, like its budget, its workspace or shutdown. + // Scope work belongs to the host, independent of reader deadlines. const signal = AbortSignal.any([lifetime, ended.signal, deps.store.retirements.signal(agent)]) const current = (): boolean => - !signal.aborted && - Date.now() < deadline && - deps.store.retirementRevision(agent) === retirement - const timer = setTimeout(() => ended.abort(), AGENT_MODEL_CATALOG_REFRESH_MS) - timer.unref?.() + !signal.aborted && deps.store.retirementRevision(agent) === retirement const gone = new Promise((resolve) => { signal.addEventListener('abort', () => resolve(null), { once: true }) }) @@ -95,10 +85,12 @@ export function createAgentModelCatalogRefreshes(context: { const listing = Promise.withResolvers() const defaults = Promise.withResolvers() const targets = new Set() - let list: ((model: string | undefined) => void) | undefined + const holders = new Set() + let register: ((holder?: AbortSignal) => void) | undefined + let demand: ((model: string) => void) | undefined let projecting: Promise | undefined const run = async (): Promise => { - const facts = await bounded(resolveAccount(deps, launch, current)) + const facts = await bounded(resolveAgentModelCatalogAccount(deps, launch, current)) if (!facts) { return } @@ -135,6 +127,7 @@ export function createAgentModelCatalogRefreshes(context: { if (keepDefault !== null) { bound.keepDefault = keepDefault } + bound.projecting = undefined }) projecting = bound.projecting void projecting.finally(defaults.resolve) @@ -146,7 +139,7 @@ export function createAgentModelCatalogRefreshes(context: { base, probeHome, current, - { deadline, current, signal } + { current, signal } ) ) if (!scope) { @@ -171,43 +164,60 @@ export function createAgentModelCatalogRefreshes(context: { probeHome, workspacePath: cwd ?? folder }) - list = (model) => { - if ( - current() && - (deps.store.probeDue(fingerprint) || - deps.store.efforts.due(fingerprint, model) || - deps.store.isListing(fingerprint)) + const attach = (holder: AbortSignal) => { + if (holder.aborted || !current()) { + return + } + completion = deps.store.refresh( + fingerprint, + agent, + (selected, owner, publish) => { + const task = lister(selected, owner, publish) + tasks.add(task) + void task.finally(() => tasks.delete(task)).catch(() => {}) + return task + }, + { signal: holder, lifetime, admission } + ) + } + register = (holder) => { + if (!current()) { + return + } + if (deps.store.isListing(fingerprint)) { + if (holder) { + attach(holder) + } else { + for (const live of holders) { + attach(live) + } + } + } else if ( + deps.store.probeDue(fingerprint) || + [...targets].some((model) => deps.store.efforts.due(fingerprint, model)) ) { - // This refresh holds the listing while it runs; once admitted, the listing runs on. - completion = deps.store.refresh( - fingerprint, - agent, - (selected, owner) => { - const task = lister(selected, owner) - tasks.add(task) - void task.finally(() => tasks.delete(task)).catch(() => {}) - return task - }, - { - signal, - lifetime, - ...(launch.legacy - ? { deadline } - : { admission, timeoutMs: AGENT_MODEL_CATALOG_REFRESH_MS }) - }, - model - ) + for (const live of holders) { + attach(live) + } + for (const model of targets) { + deps.store.efforts.demand(fingerprint, model) + } } } - for (const model of targets.size > 0 ? [...targets] : [undefined]) { - list(model) + demand = (model) => { + if (!deps.store.isListing(fingerprint)) { + register?.() + } else { + deps.store.efforts.demand(fingerprint, model) + } } + register() } listing.resolve() if (launch.passive) { await bound.projecting } else { - // Discovery may finish after this refresh's setup budget ends. + // Readers can leave while current discovery continues. const seeded = Promise.resolve(completion).then((entry) => { if (entry !== null && bound.current()) { seedAccountList(deps, scope, agent) @@ -219,13 +229,31 @@ export function createAgentModelCatalogRefreshes(context: { const end = (): void => ended.abort() const held: Held = { current: () => current() && refreshes.get(key) === held, + hold: (reader) => { + if (reader.signal.aborted) { + return + } + const released = new AbortController() + const timer = + reader.deadline === undefined + ? undefined + : setTimeout(() => released.abort(), Math.max(0, reader.deadline - Date.now())) + const holder = AbortSignal.any([signal, reader.signal, released.signal]) + const leave = () => { + clearTimeout(timer) + holders.delete(holder) + } + holders.add(holder) + holder.addEventListener('abort', leave, { once: true }) + register?.(holder) + }, listing: listing.promise, defaults: defaults.promise, done: Promise.resolve(), want: (model) => { if (model && !targets.has(model)) { targets.add(model) - list?.(model) + demand?.(model) } }, workspaceId: launch.records.record?.location.workspaceId, @@ -235,11 +263,10 @@ export function createAgentModelCatalogRefreshes(context: { held.done = run() .catch(() => {}) .finally(() => listing.resolve()) - // The folder's settings may still arrive, inside the same budget, after the listing ends. + // The folder's settings may still arrive after the listing ends. const settled = held.done .then(() => projecting) .finally(() => { - clearTimeout(timer) ended.abort() defaults.resolve() if (refreshes.get(key) === held) { @@ -267,43 +294,3 @@ export function createAgentModelCatalogRefreshes(context: { } } } - -async function resolveAccount( - deps: AgentModelCatalogServiceDeps, - launch: AgentModelCatalogLaunch, - current: () => boolean -) { - const { agent, records } = launch - const { record, scoped } = records - const workspacePath = - launch.inSessionWorkspace || - (record && - launch.workspacePath === undefined && - !launch.legacy && - (independentAgentModelCatalog(agent) || deps.agentReadsProjectModelConfig?.(agent) === true)) - ? record - ? await sessionWorkspacePath(deps, record) - : null - : launch.workspacePath - if (!current()) { - return null - } - const folder = await catalogFolder(deps, agent, workspacePath, scoped) - if (!current()) { - return null - } - const account = scoped - ? recordCatalogKey(scoped, folder) - : await newChatCatalogKey(deps, agent, folder) - if (!current() || !account) { - return null - } - return { - record, - scoped, - workspacePath, - folder, - base: account.fingerprint, - probeHome: account.accountHome - } -} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts index 90a4cedaef7..94a3615bfee 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-scope.ts @@ -34,7 +34,7 @@ export async function resolveAgentModelCatalogScope( if (!current()) { return null } - if (!independentAgentModelCatalog(params.agent) || !home) { + if (!home) { return { base, fingerprint: base, exact: false } } if (record && !isNativeLocalLocation(record.location)) { @@ -43,15 +43,26 @@ export async function resolveAgentModelCatalogScope( const probe = deps.probes?.[params.agent] // Fixed when its readers asked: no chat closing later turns a shared refresh passive. const savedOnly = () => !!params.savedOnly - if (params.legacy) { + if (params.legacy && independentAgentModelCatalog(params.agent)) { const fingerprint = agentModelCatalogScopeFingerprint(base, 'legacy-account') - const resolved = - savedOnly() || !deps.store.probeDue(fingerprint) - ? null - : await probe?.resolveLegacy?.(home, operation).catch(() => null) + let resolved = await probe + ?.resolveLegacy?.(home, operation, savedOnly() ? 'saved' : 'snapshot') + .catch(() => null) if (!current()) { return null } + if (resolved?.inputStamp !== undefined) { + deps.store.observeInputs(fingerprint, resolved.inputStamp) + } + if (!savedOnly() && deps.store.probeDue(fingerprint)) { + resolved = await probe?.resolveLegacy?.(home, operation, 'recover').catch(() => null) + } + if (!current()) { + return null + } + if (resolved?.inputStamp !== undefined) { + deps.store.observeInputs(fingerprint, resolved.inputStamp) + } return { base, fingerprint, @@ -59,6 +70,29 @@ export async function resolveAgentModelCatalogScope( ...(resolved ? { resolved } : {}) } } + if (!independentAgentModelCatalog(params.agent)) { + const cwd = + params.workspacePath ?? (record ? await sessionWorkspacePath(deps, record) : undefined) + let resolved = await probe + ?.resolve?.(home, cwd ?? '', savedOnly() ? 'saved' : 'snapshot', operation) + .catch(() => null) + if (!current()) { + return null + } + if (resolved?.inputStamp !== undefined) { + deps.store.observeInputs(base, resolved.inputStamp) + } + if (!savedOnly() && deps.store.probeDue(base)) { + resolved = await probe?.resolve?.(home, cwd ?? '', 'recover', operation).catch(() => null) + } + if (!current()) { + return null + } + if (resolved?.inputStamp !== undefined) { + deps.store.observeInputs(base, resolved.inputStamp) + } + return { base, fingerprint: base, exact: false, ...(resolved ? { resolved } : {}) } + } // The list belongs to the account and the CLI a chat here would launch, not to this folder: // resolve the executable where the chat runs, but list from an empty Orca-owned folder so the // listing reads only account settings (a home folder can hold another account's settings as @@ -90,6 +124,9 @@ export async function resolveAgentModelCatalogScope( if (!current()) { return null } + if (resolved?.inputStamp !== undefined) { + deps.store.observeInputs(scopeKey(resolved), resolved.inputStamp) + } // Rerun shells only for reads due to list; saved-only reads must remain passive. if (!savedOnly() && (!resolved || deps.store.probeDue(scopeKey(resolved)))) { resolved = await resolve('recover') @@ -97,6 +134,9 @@ export async function resolveAgentModelCatalogScope( if (!current() || (probe?.resolve && !resolved)) { return null } + if (resolved?.inputStamp !== undefined) { + deps.store.observeInputs(scopeKey(resolved), resolved.inputStamp) + } return { base, fingerprint: scopeKey(resolved), diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-scoped-lister.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-scoped-lister.ts new file mode 100644 index 00000000000..424b3a0a33b --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-scoped-lister.ts @@ -0,0 +1,48 @@ +import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import type { + AgentModelCatalogProbe, + AgentModelCatalogResolvedProbe +} from './agent-model-catalog-discovery' +import type { AgentModelCatalogListModels } from './agent-model-catalog-lister' +import { AgentModelCatalogListingStoppedError } from './agent-model-catalog-failures' + +export function scopedAgentModelCatalogLister(input: { + legacy?: boolean + signal: AbortSignal + resolved: AgentModelCatalogResolvedProbe | undefined + probe: AgentModelCatalogProbe | undefined + probeHome: AgentSessionAccountHome | null + workspacePath: string | undefined +}): AgentModelCatalogListModels { + const { resolved, probe, probeHome, workspacePath } = input + return async (selectedModels, operation, publish) => { + const signal = operation.signal + ? AbortSignal.any([input.signal, operation.signal]) + : input.signal + try { + // A slot that frees as the budget ends never starts the queued listing. + if (operation.current?.() === false) { + throw new AgentModelCatalogListingStoppedError('listing budget ended') + } + if (resolved) { + return await resolved.run(signal, operation, selectedModels, publish) + } + if (!probe || !probeHome) { + throw new AgentModelCatalogListingStoppedError('catalog scope unavailable') + } + return await probe(probeHome, { + signal, + workspacePath, + ...(selectedModels ? { selectedModels } : {}), + operation, + publish + }) + } catch (error) { + throw input.signal.aborted + ? new AgentModelCatalogListingStoppedError(String(error)) + : operation.signal?.aborted + ? operation.signal.reason + : error + } + } +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-script-entry.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-script-entry.ts new file mode 100644 index 00000000000..cfb6a4be997 --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-script-entry.ts @@ -0,0 +1,104 @@ +import { NODE_INTERPRETER_OPTIONS_WITH_VALUE } from '../../../shared/node-interpreter-options' + +const NODE_FLAGS = new Set([ + '--no-warnings', + '--trace-warnings', + '--enable-source-maps', + '--preserve-symlinks', + '--preserve-symlinks-main' +]) +const PYTHON_FLAGS = new Set(['-u', '-B', '-E', '-s', '-S', '-I', '-O', '-OO', '-q']) +const PYTHON_VALUES = new Set(['-W', '-X']) +const DENO_FLAGS = new Set(['-A', '--allow-all', '--no-prompt']) +const DENO_VALUES = new Set(['-c', '--config', '--import-map']) +const DENO_PERMISSIONS = new Set([ + '--allow-read', + '--allow-write', + '--allow-net', + '--allow-env', + '--allow-run', + '--allow-ffi', + '--allow-sys', + '--allow-import', + '--deny-read', + '--deny-write', + '--deny-net', + '--deny-env', + '--deny-run', + '--deny-ffi', + '--deny-sys' +]) + +function scriptFile(token: string | undefined, deno = false): string | undefined { + if (!token || token === '-') { + return undefined + } + return deno && /^[a-z][a-z\d+.-]*:/i.test(token) && !/^[a-z]:[\\/]/i.test(token) + ? undefined + : token +} + +/** Unknown option arity cannot safely identify a file; those commands use explicit Refresh. */ +export function agentModelCatalogScriptEntry( + interpreter: string, + args: readonly string[] +): string | undefined { + const node = /^(node|nodejs)$/.test(interpreter) + const python = /^python\d*(?:\.\d+)?$/.test(interpreter) + const deno = interpreter === 'deno' + if (!node && !python && !deno) { + if (!/^(bun|ruby|sh|bash|zsh)$/.test(interpreter)) { + return undefined + } + const operand = interpreter === 'bun' && args[0] === 'run' ? args[1] : args[0] + return operand?.startsWith('-') || (interpreter === 'bun' && operand === 'eval') + ? undefined + : scriptFile(operand) + } + if (deno && args[0] !== 'run') { + return undefined + } + const flags = node ? NODE_FLAGS : python ? PYTHON_FLAGS : DENO_FLAGS + const values = node ? NODE_INTERPRETER_OPTIONS_WITH_VALUE : python ? PYTHON_VALUES : DENO_VALUES + for (let index = deno ? 1 : 0; index < args.length; index += 1) { + const token = args[index]! + if (!token) { + return undefined + } + if (token === '--') { + return scriptFile(args[index + 1], deno) + } + if (!token.startsWith('-')) { + return node && token === 'inspect' ? undefined : scriptFile(token, deno) + } + if (flags.has(token)) { + continue + } + if (values.has(token)) { + const value = args[++index] + if (!value || value.startsWith('-')) { + return undefined + } + continue + } + const equals = token.indexOf('=') + const name = equals === -1 ? token : token.slice(0, equals) + if (token.startsWith('--') && values.has(name) && equals !== -1) { + if (equals === token.length - 1) { + return undefined + } + continue + } + if (deno && DENO_PERMISSIONS.has(name)) { + if (equals === token.length - 1) { + return undefined + } + continue + } + if (python && /^-[WX].+/.test(token)) { + continue + } + return undefined + } + return undefined +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts index a790ee48ed5..88ec30489ed 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts @@ -62,6 +62,8 @@ export type AgentModelCatalogService = { export type AgentModelCatalogReadParams = { agent: string + /** Older readers follow only actual wait expiry, so retain their terminal wait. */ + progress?: boolean records?: AgentModelCatalogReadRecords | null operation?: AgentModelCatalogReadOperation /** Original explicit operation budget, shared with compatibility saved-scope continuation. */ diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts index 71d60ff9a0d..cc41d75786f 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts @@ -1,3 +1,4 @@ +import { onAgentsRefreshedOnHost } from '../../preflight/agents-refreshed-on-host' import { onLiveAccount } from './agent-model-catalog-running-account' import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/agent-session-conversation-view' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' @@ -34,6 +35,9 @@ import { export function createAgentModelCatalogService( deps: AgentModelCatalogServiceDeps ): AgentModelCatalogService { + const unbindRefresh = onAgentsRefreshedOnHost((userInitiated) => + deps.store.refreshInputs(userInitiated) + ) const tasks = new Set>() const lifetime = new AbortController() const admission = new PrioritySemaphore(2) @@ -78,9 +82,18 @@ export function createAgentModelCatalogService( const operation = params.operation ?? captureRead(params) await waitWithinAgentModelCatalogRead(operation, lookup.request(params, operation)?.done) } + const flush = (params: AgentModelCatalogReadParams) => { + const bound = memoryBinding(params) + if (!params.savedOnly && bound?.current()) { + deps.store.flushProgress(bound.fingerprint) + } + } return { captureRead, - snapshot, + snapshot: (params) => { + flush(params) + return snapshot(params) + }, demand: async (params) => { if (!params.savedOnly) { await demand(params) @@ -108,7 +121,7 @@ export function createAgentModelCatalogService( params, reader: { deadline, signal: operation.signal }, store: deps.store, - refresh: lookup.request(params, operation), + refresh: () => lookup.request(params, operation), binding: () => bindings.get(requestKey(params)) }) } @@ -118,6 +131,7 @@ export function createAgentModelCatalogService( expired && params.operation?.current({ ignoreDeadline: true }) ? { ...params, operation: undefined } : params + flush(answerParams) const result = snapshot(answerParams) const answer = lifetime.signal.aborted ? result @@ -140,6 +154,7 @@ export function createAgentModelCatalogService( async stop() { lifetime.abort() unbindRetirement() + unbindRefresh() retireContext() deps.store.clearPartialAttempts() await Promise.allSettled(tasks) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts index 836bb19aec6..9720d720134 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-listing.test.ts @@ -1,3 +1,5 @@ +import { PrioritySemaphore } from '../../../shared/priority-semaphore' +import { runAgentModelCatalogSession } from './agent-model-catalog-probe-runner' import { expect, it, onTestFinished, vi } from 'vitest' import { createAgentModelCatalogService } from './agent-model-catalog-service' import { @@ -5,6 +7,7 @@ import { type StructuredAgentResolutionOperation } from '../agent-launch/structured-agent-command-resolution' import { AgentModelCatalogStore } from './agent-model-catalog-store' +import type { AgentModelCatalogProgress } from './agent-model-catalog-discovery' import type { AgentModelCatalogSuccess } from './agent-model-catalog-entry' function listing(id: string): AgentModelCatalogSuccess { @@ -29,7 +32,12 @@ function sharedListingHarness() { deadline?: number }[] = [] const run = vi.fn( - (identity: string, signal?: AbortSignal, operation?: StructuredAgentResolutionOperation) => { + ( + identity: string, + signal?: AbortSignal, + operation?: StructuredAgentResolutionOperation, + _publish?: AgentModelCatalogProgress + ) => { runs.push({ identity, signal, current: operation?.current, deadline: operation?.deadline }) return new Promise((resolve, reject) => { void listingFor(identity).promise.then(resolve) @@ -60,7 +68,12 @@ function sharedListingHarness() { const identity = folder?.startsWith('/own') ? folder : 'codex' return { identity, - run: (signal?: AbortSignal, owner = operation) => run(identity, signal, owner) + run: ( + signal?: AbortSignal, + owner = operation, + _selected?: readonly string[], + publish?: AgentModelCatalogProgress + ) => run(identity, signal, owner, publish) } } }) @@ -91,3 +104,281 @@ it("never answers a newly picked folder with the previous folder's late listing" models: [{ id: 'old' }] }) }) + +it('keeps physical admission through late success and actual teardown', async () => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const store = new AgentModelCatalogStore() + const admission = new PrioritySemaphore(1) + const close = Promise.withResolvers() + const closing = Promise.withResolvers() + const answer = Promise.withResolvers() + const first = store.refresh( + 'first', + 'grok', + async (_selected, owner, publish) => + runAgentModelCatalogSession( + () => ({ + close: () => { + closing.resolve() + return close.promise + } + }), + async () => { + publish?.(listing('partial')) + const result = await answer.promise + assertStructuredAgentResolutionCurrent(owner) + return result + }, + { label: 'grok', signal: owner.signal, timeoutMs: null } + ), + { admission } + ) + let secondStarted = false + const second = store.refresh( + 'second', + 'grok', + async () => { + secondStarted = true + return listing('second') + }, + { admission } + ) + await vi.advanceTimersByTimeAsync(45_000) + expect(store.get('first')?.models[0]?.id).toBe('partial') + answer.resolve(listing('late')) + await closing.promise + expect(secondStarted).toBe(false) + expect(store.isListing('first')).toBe(true) + expect(store.get('first')?.models[0]?.id).toBe('partial') + close.resolve() + expect((await first)?.models[0]?.id).toBe('late') + expect((await second)?.models[0]?.id).toBe('second') +}) + +it.each([false, true])( + 'keeps a slow successful listing after its reader leaves (saved=%s)', + async (saved) => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const h = sharedListingHarness() + if (saved) { + const initial = h.service.read({ agent: 'codex', waitForListing: true }) + await vi.advanceTimersByTimeAsync(0) + h.discovery.resolve({ ...listing('saved'), complete: true }) + await initial + h.store.expireScopes('codex') + } + const answer = Promise.withResolvers() + h.run.mockImplementation((_identity, signal, operation) => + runAgentModelCatalogSession( + () => ({ close: async () => {} }), + async () => { + const result = await answer.promise + assertStructuredAgentResolutionCurrent(operation) + return result + }, + { label: 'cold', signal, timeoutMs: null } + ) + ) + const reader = h.service.read({ agent: 'codex', waitForListing: true }) + await vi.advanceTimersByTimeAsync(30_000) + expect(await reader).toMatchObject({ listingInProgress: true, waitExpired: true }) + const snapshot = h.service.snapshot({ agent: 'codex' }) + if (saved) { + expect(snapshot).toMatchObject({ models: [{ id: 'saved' }] }) + } else { + expect(snapshot.origin).toBe('unknown') + } + await vi.advanceTimersByTimeAsync(15_000) + answer.resolve({ ...listing('slow-success'), complete: true }) + await vi.advanceTimersByTimeAsync(0) + expect(await h.service.read({ agent: 'codex', waitForListing: true })).toMatchObject({ + models: [{ id: 'slow-success' }] + }) + expect(h.service.snapshot({ agent: 'codex' }).listingInProgress).toBeUndefined() + } +) + +it.each([true, false])( + 'delivers progress and waits for a changed observation (progress=%s)', + async (progress) => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const h = sharedListingHarness() + const answer = Promise.withResolvers() + let publish: AgentModelCatalogProgress | undefined + h.run.mockImplementation((_identity, _signal, _operation, notify) => { + publish = notify + return answer.promise + }) + const first = h.service.read({ agent: 'codex', waitForListing: true, progress }) + await vi.advanceTimersByTimeAsync(0) + publish?.({ ...listing('listed'), complete: false }) + await vi.advanceTimersByTimeAsync(progress ? 0 : 30_000) + expect(await first).toMatchObject({ + models: [{ id: 'listed', isDefault: false }], + listingInProgress: true + }) + expect((await first).waitExpired).toBe(progress ? undefined : true) + let next: unknown + const follow = h.service + .read({ agent: 'codex', waitForListing: true, progress: true }) + .then((result) => { + next = result + }) + await vi.advanceTimersByTimeAsync(1_000) + expect(next).toBeUndefined() + publish?.({ ...listing('listed'), complete: true, configured: { model: 'listed' } }, true) + await follow + expect(next).toMatchObject({ + models: [{ id: 'listed', isDefault: true }], + listingInProgress: true + }) + answer.resolve({ ...listing('listed'), complete: true, configured: { model: 'listed' } }) + await vi.advanceTimersByTimeAsync(0) + expect(h.service.snapshot({ agent: 'codex' }).listingInProgress).toBeUndefined() + } +) + +it('keeps an account verdict until discovery actually answers it, including optional failure', async () => { + const store = new AgentModelCatalogStore() + store.recordSuccess( + 'held', + 'codex', + { ...listing('saved'), complete: true, unavailable: { reason: 'notSignedIn' } }, + 'discovery' + ) + store.expireFailure('held') + await store.refresh('held', 'codex', async (_selected, _owner, publish) => { + publish?.({ ...listing('listed'), complete: true }, false) + return { ...listing('listed'), complete: true } + }) + expect(store.failure('held')?.unavailable).toEqual({ reason: 'notSignedIn' }) + await store.refresh('held', 'codex', async (_selected, _owner, publish) => { + publish?.({ ...listing('listed'), complete: true }, true) + return { ...listing('listed'), complete: true } + }) + expect(store.failure('held')).toBeNull() +}) + +it('fences obsolete progress and final results while retaining admission until cancelled teardown', async () => { + const store = new AgentModelCatalogStore() + const admission = new PrioritySemaphore(1) + const started = Promise.withResolvers() + const closing = Promise.withResolvers() + const closed = Promise.withResolvers() + const answer = Promise.withResolvers() + let notify: AgentModelCatalogProgress | undefined + const first = store.refresh( + 'old', + 'grok', + async (_selected, owner, publish) => + runAgentModelCatalogSession( + () => ({ + close: () => { + closing.resolve() + return closed.promise + } + }), + async () => { + notify = publish + publish?.(listing('usable')) + started.resolve() + return answer.promise + }, + { label: 'grok', timeoutMs: null, signal: owner.signal } + ), + { admission } + ) + await started.promise + notify?.defer?.( + () => listing('obsolete-deferred'), + () => true + ) + store.expireScopes('grok') + store.flushProgress('old') + await closing.promise + notify?.(listing('obsolete-progress')) + notify?.defer?.( + () => listing('obsolete-new-deferred'), + () => true + ) + store.flushProgress('old') + answer.resolve(listing('obsolete-final')) + let entered = false + const next = store.refresh( + 'new', + 'grok', + async () => { + entered = true + return listing('new') + }, + { admission } + ) + await Promise.resolve() + expect(entered).toBe(false) + expect(store.get('old')?.models[0]?.id).toBe('usable') + closed.resolve() + expect(await first).toBeNull() + expect((await next)?.models[0]?.id).toBe('new') + expect(store.get('old')?.models[0]?.id).toBe('usable') +}) + +it('withdraws an abandoned queued scope while the two admitted listings continue', async () => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const h = sharedListingHarness() + void h.service.demand({ agent: 'codex', workspacePath: '/own-a' }) + void h.service.demand({ agent: 'codex', workspacePath: '/own-b' }) + const queued = h.service.read({ agent: 'codex', workspacePath: '/own-c', waitForListing: true }) + await vi.advanceTimersByTimeAsync(30_000) + expect(await queued).toMatchObject({ + origin: 'unknown', + listingInProgress: true, + waitExpired: true + }) + await vi.advanceTimersByTimeAsync(5_001) + expect( + h.service.snapshot({ agent: 'codex', workspacePath: '/own-c' }).listingInProgress + ).toBeUndefined() + h.listingFor('/own-a').resolve({ ...listing('a'), complete: true }) + await vi.advanceTimersByTimeAsync(0) + expect(h.service.snapshot({ agent: 'codex', workspacePath: '/own-c' }).origin).toBe('unknown') +}) + +it.each([false, true])( + 'settles an identical final observation, including eviction (evicted=%s)', + async (evicted) => { + const store = new AgentModelCatalogStore() + let first: unknown + const success = { ...listing('same'), complete: true } + const result = await store.refresh('same', 'codex', async (_selected, _owner, publish) => { + publish?.(success, true) + first = store.get('same') + if (evicted) { + for (let index = 0; index < 256; index++) { + store.recordSuccess(`other-${index}`, 'codex', success, 'discovery') + } + expect(store.get('same')).toBeNull() + } + return success + }) + expect(result?.models[0]?.id).toBe('same') + if (!evicted) { + expect(store.get('same')).toBe(first) + } + expect(store.get('same')?.models[0]?.id).toBe('same') + expect(store.failure('same')).toBeNull() + expect(store.isListing('same')).toBe(false) + expect(store.probeDue('same')).toBe(false) + } +) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts index 19c2f6f17f2..613981d2654 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-shared-setup.test.ts @@ -137,7 +137,7 @@ it('keeps one listing for a workspace on the same folder when another workspace expect(await a).toMatchObject({ models: [{ id: 'other' }] }) }) -it('ends a shorter reader at its own deadline, and a stalled refresh lists nothing after its budget', async () => { +it('ends a shorter reader while scope resolution remains current', async () => { vi.useFakeTimers() onTestFinished(() => { vi.useRealTimers() @@ -163,9 +163,7 @@ it('ends a shorter reader at its own deadline, and a stalled refresh lists nothi // Its readers are gone, but the refresh runs on its own budget. expect(h.service.snapshot({ agent: 'codex', sessionId: 'b' })).toHaveProperty('listingInProgress') await vi.advanceTimersByTimeAsync(29_000) - expect(h.service.snapshot({ agent: 'codex', sessionId: 'b' })).not.toHaveProperty( - 'listingInProgress' - ) + expect(h.service.snapshot({ agent: 'codex', sessionId: 'b' })).toHaveProperty('listingInProgress') gate.resolve() await vi.advanceTimersByTimeAsync(0) expect(h.run).not.toHaveBeenCalled() @@ -177,7 +175,8 @@ it('holds readers of a stalled refresh only to their own deadlines, and starts n vi.useRealTimers() }) const h = harness() - h.folder.gate = Promise.withResolvers() + const gate = Promise.withResolvers() + h.folder.gate = gate void h.service.demand({ agent: 'codex', sessionId: 'a', deadline: Date.now() + 1_000 }) const b = h.service.read({ agent: 'codex', @@ -187,7 +186,7 @@ it('holds readers of a stalled refresh only to their own deadlines, and starts n }) await vi.advanceTimersByTimeAsync(30_000) // b's deadline ended its wait; a reader leaving never restarts the work. - expect(await b).toEqual({ origin: 'unknown' }) + expect(await b).toMatchObject({ origin: 'unknown', listingInProgress: true, waitExpired: true }) expect(h.recordWorkspacePath).toHaveBeenCalledOnce() const c = h.service.read({ agent: 'codex', @@ -195,8 +194,10 @@ it('holds readers of a stalled refresh only to their own deadlines, and starts n waitForListing: true, deadline: Date.now() + 30_000 }) - await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce()) - expect(h.recordWorkspacePath).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(15_000) + gate.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(h.recordWorkspacePath).toHaveBeenCalledOnce() h.discovery.resolve(listing('fresh')) await vi.advanceTimersByTimeAsync(0) expect(await c).toMatchObject({ models: [{ id: 'fresh' }] }) @@ -226,26 +227,32 @@ it("keeps the folder's defaults when they arrive after a shorter last reader lef expect(await a).toMatchObject({ models: [{ id: 'listed', isDefault: true }] }) }) -it("keeps the listing when the folder's settings stall, naming no default, within the reader's budget", async () => { +it('delivers inventory before slow folder defaults, then delivers the proven default', async () => { vi.useFakeTimers() onTestFinished(() => { vi.useRealTimers() }) const h = harness(agent) - h.folder.settings = Promise.withResolvers() - void h.service.demand({ agent, sessionId: 'a', deadline: Date.now() + 1_000 }) - let answer: unknown - void h.service - .read({ agent, sessionId: 'b', waitForListing: true, deadline: Date.now() + 30_000 }) - .then((result) => { - answer = result - }) - await vi.waitFor(() => expect(h.run).toHaveBeenCalledOnce()) + const settings = Promise.withResolvers() + h.folder.settings = settings + const first = h.service.read({ agent, sessionId: 'b', waitForListing: true }) + await vi.advanceTimersByTimeAsync(0) h.discovery.resolve(listing('listed')) - await vi.advanceTimersByTimeAsync(30_000) - // Whether the project picks its own model stays unknown, so the account's default isn't named. - expect(answer).toMatchObject({ models: [{ id: 'listed', isDefault: false }] }) - expect(answer).not.toHaveProperty('listingInProgress') + await vi.advanceTimersByTimeAsync(0) + expect(await first).toMatchObject({ + models: [{ id: 'listed', isDefault: false }], + listingInProgress: true + }) + let next: unknown + const follow = h.service.read({ agent, sessionId: 'b', waitForListing: true }).then((result) => { + next = result + }) + await vi.advanceTimersByTimeAsync(1_000) + expect(next).toBeUndefined() + settings.resolve() + await follow + expect(next).toMatchObject({ models: [{ id: 'listed', isDefault: true }] }) + expect(next).not.toHaveProperty('listingInProgress') }) it("never lets a moved folder's late settings describe the folder it moved to", async () => { @@ -326,3 +333,43 @@ it('keeps one folder-agent listing for a workspace on the same folder when anoth expect(await a).toMatchObject({ models: [{ id: 'other' }] }) expect(probe.mock.calls.map((call) => call[1]?.workspacePath)).toEqual(['/repo', '/other']) }) + +it.each([10, 100])( + 'registers %i readers and unique targets once per shared flight', + async (count) => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + for (const delayedScope of [false, true]) { + const h = harness('opencode2') + const scope = Promise.withResolvers() + if (delayedScope) { + h.folder.gate = scope + } + const registrations = vi.spyOn(h.store, 'refresh') + const submissions = vi.spyOn(h.store.efforts, 'demand') + const readers: Promise[] = [] + for (let index = 0; index < count; index++) { + readers.push( + h.service.read({ + agent: 'opencode2', + sessionId: 'a', + selectedModel: `m${index}`, + waitForListing: true + }) + ) + if (!delayedScope) { + await vi.advanceTimersByTimeAsync(0) + } + } + scope.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(h.run).toHaveBeenCalledOnce() + expect(registrations.mock.calls.length).toBe(count) + expect(submissions.mock.calls.length).toBe(count) + h.discovery.resolve(listing('shared')) + await Promise.all(readers) + } + } +) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts index 55cb348482b..d654c868e70 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts @@ -8,10 +8,7 @@ import type { AgentSessionConversationView } from '../../../shared/agent-session import type { AgentSessionModelCatalogResult } from '../../../shared/agent-session/agent-session-wire' import { agentModelCatalogResultFromEntry } from './agent-model-catalog-entry' import { agentModelCatalogDefaultFollowsAccount } from './agent-model-catalog-workspace' -import { - independentAgentModelCatalog, - usesModelSpecificAcpEfforts -} from '../../../shared/agent-session/options/agent-model-catalog-ownership' +import { independentAgentModelCatalog } from '../../../shared/agent-session/options/agent-model-catalog-ownership' import type { AgentModelCatalogReadParams, AgentModelCatalogServiceDeps @@ -239,11 +236,11 @@ export function projectAgentModelCatalogSnapshot( ...(!params.savedOnly && !params.verifiedOnly && (deps.store.isListing(bound.fingerprint) || + (resolving && bound.projecting !== undefined) || (resolving && (deps.store.probeDue(bound.fingerprint) || // The picked model's menu is listed by the refresh this read just asked for. - deps.store.efforts.due(bound.fingerprint, params.selectedModel)))) && - (independent || !listed || usesModelSpecificAcpEfforts(params.agent)) + deps.store.efforts.due(bound.fingerprint, params.selectedModel)))) ? { listingInProgress: true as const } : {}), ...(deps.store.failure(bound.fingerprint)?.unavailable diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts index 27013afc0b9..2cb06345424 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts @@ -4,6 +4,7 @@ import { join } from 'node:path' import { describe, expect, it } from 'vitest' import type { AgentSessionModelOption } from '../../../shared/agent-session/agent-session-wire' import { createAgentModelCatalogFilePersistence } from './agent-model-catalog-persistence' +import { expireAgentModelCatalogFailuresForSettings } from './agent-model-catalog-account-expiry' import { AgentModelCatalogStore, type AgentModelCatalogSuccess } from './agent-model-catalog-store' function models(...ids: string[]): AgentSessionModelOption[] { @@ -23,6 +24,52 @@ function success(...ids: string[]): AgentModelCatalogSuccess { } describe('agent model catalog store', () => { + it('invalidates changed inputs only, retaining rows and incomplete evidence until rediscovery', async () => { + let now = 0 + const store = new AgentModelCatalogStore({ now: () => now }) + store.observeInputs('a', 'install-1') + store.recordSuccess( + 'a', + 'claude', + { ...success('opus'), origin: 'probe', complete: false }, + 'discovery' + ) + store.recordSuccess( + 'b', + 'codex', + { ...success('gpt'), origin: 'probe', complete: true }, + 'discovery' + ) + now = 13 * 60 * 60_000 + store.refreshInputs(false) + expect(store.probeDue('a')).toBe(false) + expect(store.verified(store.get('a')!)).toBe(false) + expect(store.probeDue('b')).toBe(false) + store.observeInputs('a', 'install-2') + expect(store.probeDue('a')).toBe(true) + expect(store.get('a')?.models[0]?.id).toBe('opus') + expect(store.probeDue('b')).toBe(false) + expect(store.retirementRevision('claude')).toBe(0) + await store.refresh('a', 'claude', async () => { + throw new Error('network unavailable') + }) + expect(store.probeDue('a')).toBe(false) + now += 30_001 + expect(store.probeDue('a')).toBe(true) + expect(store.get('a')?.models[0]?.id).toBe('opus') + await store.refresh('a', 'claude', async () => ({ + ...success('sonnet'), + origin: 'probe', + complete: true + })) + now += 13 * 60 * 60_000 + expect(store.probeDue('a')).toBe(false) + expect(store.get('a')?.models[0]?.id).toBe('sonnet') + store.refreshInputs(true) + expect(store.probeDue('a')).toBe(true) + expect(store.probeDue('b')).toBe(true) + }) + it("keeps a live child's default effort through a listing that names none, across a restart", async () => { const directory = mkdtempSync(join(tmpdir(), 'agent-model-catalog-')) const store = new AgentModelCatalogStore() @@ -102,3 +149,43 @@ describe('agent model catalog store', () => { ) }) }) + +it('requires validation when a retained catalog has lost its bounded input baseline', () => { + const store = new AgentModelCatalogStore() + for (let index = 0; index < 256; index++) { + store.observeInputs(String(index), 'original') + store.recordSuccess(String(index), 'grok', success('old'), 'discovery') + } + store.get('0') + store.observeInputs('256', 'original') + store.recordSuccess('256', 'grok', success('new'), 'discovery') + store.observeInputs('0', 'replacement') + expect(store.probeDue('0')).toBe(true) + expect(store.get('0')?.models[0]?.id).toBe('old') + store.observeInputs('2', 'original') + expect(store.probeDue('2')).toBe(false) +}) + +it('requires new account evidence after same-home reauthentication while preserving other agents', async () => { + const store = new AgentModelCatalogStore() + for (const agent of ['claude', 'codex', 'grok']) { + store.recordSuccess(agent, agent, { ...success('old'), complete: true }, 'discovery') + } + const stale = Promise.withResolvers() + const flight = store.refresh('claude', 'claude', () => stale.promise) + await Promise.resolve() + expireAgentModelCatalogFailuresForSettings(store, { claudeManagedAccounts: [] }) + expect(store.probeDue('claude')).toBe(true) + expect(store.get('claude')?.models[0]?.id).toBe('old') + expect(store.probeDue('codex')).toBe(false) + expect(store.probeDue('grok')).toBe(false) + stale.resolve(success('wrong-account')) + await flight + await Promise.resolve() + expect(store.get('claude')?.models[0]?.id).toBe('old') + await store.refresh('claude', 'claude', async () => ({ + ...success('new-account'), + complete: true + })) + expect(store.get('claude')?.models[0]?.id).toBe('new-account') +}) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts index 781ced64ed5..6786abc1b6c 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-store.ts @@ -1,12 +1,13 @@ +import { AgentModelCatalogInputs } from './agent-model-catalog-inputs' import { createAgentModelEffortDiscovery } from './agent-model-catalog-effort-discovery' import { createAgentModelCatalogFences } from './agent-model-catalog-fences' import { evictAgentModelCatalogEntries, createAgentModelCatalogEntryFactory, + createAgentModelCatalogSuccessWriter, retireAgentModelCatalogObservations, agentModelCatalogLaunchAgents, - agentModelCatalogEntryIsStale, - pruneAgentModelCatalogPartialAttempts + agentModelCatalogEntryIsStale } from './agent-model-catalog-entry-lifetime' import { independentAgentModelCatalog } from '../../../shared/agent-session/options/agent-model-catalog-ownership' export type { AgentModelCatalogProbe } from './agent-model-catalog-discovery' @@ -41,10 +42,6 @@ import { export { AGENT_MODEL_CATALOG_FAILURE_TTL_MS, AGENT_MODEL_CATALOG_PICKER_WAIT_MS } export type { AgentModelCatalogFailure } -// Persist successful catalogs only; failures/unavailability are held separately. -// Saved display data may be stale, while launch proof requires fresh discovery in this process. - -export { AGENT_MODEL_CATALOG_FRESH_MS } from './agent-model-catalog-entry-lifetime' export const AGENT_MODEL_CATALOG_MAX_ENTRIES = 256 import { @@ -65,6 +62,7 @@ export class AgentModelCatalogStore { (fingerprint) => this.refreshes.has(fingerprint) ) // Changed launch commands/env invalidate catalogs until rediscovery. + private readonly inputs: AgentModelCatalogInputs private readonly dueEntries = new Set() private readonly partialAttempts = new Map() private readonly retirementRevisions = new Map() @@ -78,6 +76,17 @@ export class AgentModelCatalogStore { constructor(options?: { now?: () => number }) { this.now = options?.now ?? Date.now this.failures = new AgentModelCatalogFailures(this.now) + this.inputs = new AgentModelCatalogInputs({ + entries: this.entries, + refreshes: this.refreshes, + dueEntries: this.dueEntries, + failures: this.failures, + partialAttempts: this.partialAttempts, + listingWaiters: this.listingWaiters, + agents: () => agentModelCatalogLaunchAgents(this.retirementRevisions, this.entries), + retireAgent: (agent) => this.expireFailures(agent), + cap: AGENT_MODEL_CATALOG_MAX_ENTRIES + }) this.efforts = createAgentModelEffortDiscovery({ entries: this.entries, refreshes: this.refreshes, @@ -94,9 +103,7 @@ export class AgentModelCatalogStore { for (const entry of await persistence.load()) { if (!this.entries.has(entry.fingerprint)) { this.entries.set(entry.fingerprint, entry) - if (independentAgentModelCatalog(entry.agent)) { - this.dueEntries.add(entry.fingerprint) - } + this.dueEntries.add(entry.fingerprint) } } this.evictOverCap() @@ -128,7 +135,7 @@ export class AgentModelCatalogStore { /** Live saves must not delay account-level discovery. */ isStale(entry: AgentModelCatalogEntry): boolean { - return agentModelCatalogEntryIsStale(entry, this.dueEntries.has(entry.fingerprint), this.now()) + return agentModelCatalogEntryIsStale(entry, this.dueEntries.has(entry.fingerprint)) } failureDetail(fingerprint: string): string | null { @@ -172,6 +179,18 @@ export class AgentModelCatalogStore { this.failures.expireAgent(agent) } + observeInputs(fingerprint: string, stamp: string): void { + this.inputs.observeInputs(fingerprint, stamp) + } + + refreshInputs(userInitiated: boolean): void { + this.inputs.refreshInputs(userInitiated) + } + + expireScopes(agent?: string): void { + this.inputs.expireScopes(agent) + } + expireFailure(fingerprint: string): void { this.failures.expire(fingerprint) } @@ -223,46 +242,17 @@ export class AgentModelCatalogStore { this.listingWaiters.notify(fingerprint) } - private writeSuccess( - fingerprint: string, - agent: string, - success: AgentModelCatalogSuccess, - source: AgentModelCatalogSource - ): AgentModelCatalogEntry | null { - const entry = this.entryFromSuccess(fingerprint, agent, success, source) - if (!entry) { - if (source === 'discovery' && independentAgentModelCatalog(agent)) { - this.failures.probeFailed(fingerprint, agent, new Error('agent listed no models')) - } - return null - } - this.retiredObservations.delete(fingerprint) - const previous = this.entries.get(fingerprint) - this.entries.delete(fingerprint) - this.entries.set(fingerprint, entry) - // Live listings cannot clear discovery failures or account-unavailability verdicts. - if ( - source === 'discovery' && - (!independentAgentModelCatalog(agent) || success.complete === true) - ) { - this.dueEntries.delete(fingerprint) - this.failures.listed(fingerprint, agent, success.origin, success.unavailable) - } - if (source === 'discovery' && independentAgentModelCatalog(agent)) { - this.efforts.catalogAttempted(fingerprint, agent, success.complete === true) - if (success.complete !== true) { - this.failures.listed(fingerprint, agent, success.origin, success.unavailable) - } - } - this.evictOverCap() - // Unchanged per-turn listings need no disk write. - if (!previous || agentModelCatalogListingKey(previous) !== agentModelCatalogListingKey(entry)) { - this.persistence?.save(() => [...this.entries.values()]) - } - return entry - } + private readonly writeSuccess = createAgentModelCatalogSuccessWriter(() => ({ + entries: this.entries, + retiredObservations: this.retiredObservations, + dueEntries: this.dueEntries, + failures: this.failures, + efforts: this.efforts, + entryFromSuccess: this.entryFromSuccess, + persistence: this.persistence, + evict: () => this.evictOverCap() + })) - /** One probe per canonical scope; failures resolve null. Its starter's budget bounds it. */ refresh( fingerprint: string, agent: string, @@ -283,10 +273,18 @@ export class AgentModelCatalogStore { refreshes: this.refreshes, failures: this.failures, listingWaiters: this.listingWaiters, + failed: () => { + if (this.entries.has(fingerprint)) { + this.dueEntries.add(fingerprint) + } + this.partialAttempts.delete(fingerprint) + }, writeSuccess: (...args) => this.writeSuccess(...args) }) } + flushProgress = (key: string): void => this.refreshes.get(key)?.flush() + isListing(fingerprint: string): boolean { const flight = this.refreshes.get(fingerprint) if (flight && !flight.current()) { @@ -302,6 +300,7 @@ export class AgentModelCatalogStore { verified(entry: AgentModelCatalogEntry): boolean { return ( !this.isStale(entry) && + (!independentAgentModelCatalog(entry.agent) || entry.discovered?.complete === true) && !this.hasActiveFailure(entry.fingerprint) && !this.failure(entry.fingerprint)?.unavailable ) @@ -319,7 +318,6 @@ export class AgentModelCatalogStore { if (this.isListing(fingerprint) || this.hasActiveFailure(fingerprint)) { return false } - pruneAgentModelCatalogPartialAttempts(this.partialAttempts, this.now()) const entry = this.entries.get(fingerprint) return !this.partialAttempts.has(fingerprint) && (!entry || this.isStale(entry)) } diff --git a/src/main/native-chat/agent-session-wire/options/structured-agent-session-catalog-reads.ts b/src/main/native-chat/agent-session-wire/options/structured-agent-session-catalog-reads.ts index cbf7642a223..da4f1024c4c 100644 --- a/src/main/native-chat/agent-session-wire/options/structured-agent-session-catalog-reads.ts +++ b/src/main/native-chat/agent-session-wire/options/structured-agent-session-catalog-reads.ts @@ -59,7 +59,7 @@ export function createStructuredAgentSessionCatalogReads( return { origin: 'unknown' } } const request = { ...params, records, operation, deadline: operation.deadline } - if (!params.savedOnly) { + if (!params.savedOnly && !params.waitForListing) { void catalog.demand(request) } return catalog.read(request) diff --git a/src/main/pi/rpc-runtime-metadata.ts b/src/main/pi/rpc-runtime-metadata.ts index 3193edd9d28..bd184a51b20 100644 --- a/src/main/pi/rpc-runtime-metadata.ts +++ b/src/main/pi/rpc-runtime-metadata.ts @@ -17,6 +17,7 @@ export const PI_RPC_RUNTIME_METADATA: StructuredAgentRuntimeMetadata = { listingNamesConfiguredModel: false, probe: createPiModelCatalogProbe({ resolveEnvironment: () => context.environment.resolveAgentEnvironment('pi'), + resolveSavedEnvironment: () => context.environment.resolveAgentEnvironment('pi', true), refreshEnvironmentAfterMiss: context.environment.refreshAfterMissingProgram, ...(context.deps.resolveAgentCommandSettings ? { resolveCommandSettings: context.deps.resolveAgentCommandSettings } diff --git a/src/main/pi/rpc/launch/rpc-launch-resolution.ts b/src/main/pi/rpc/launch/rpc-launch-resolution.ts index a6b2b1ce698..39784f4ecf4 100644 --- a/src/main/pi/rpc/launch/rpc-launch-resolution.ts +++ b/src/main/pi/rpc/launch/rpc-launch-resolution.ts @@ -76,6 +76,7 @@ export function resolvePiRpcCommand( export function checkPiRpcVersion( launch: { + operation?: StructuredAgentResolutionOperation command: string prefixArgs?: readonly string[] cwd: string @@ -84,7 +85,13 @@ export function checkPiRpcVersion( read?: AgentCliVersionReader ): Promise { return checkAgentCliVersion( - { program: launch.command, prefixArgs: launch.prefixArgs, cwd: launch.cwd, env: launch.env }, + { + program: launch.command, + prefixArgs: launch.prefixArgs, + cwd: launch.cwd, + env: launch.env, + operation: launch.operation + }, PI_RPC_MINIMUM_VERSIONS, read ) diff --git a/src/main/pi/rpc/options/rpc-model-catalog-probe.test.ts b/src/main/pi/rpc/options/rpc-model-catalog-probe.test.ts new file mode 100644 index 00000000000..d58a9d477aa --- /dev/null +++ b/src/main/pi/rpc/options/rpc-model-catalog-probe.test.ts @@ -0,0 +1,88 @@ +import { expect, it, vi, onTestFinished } from 'vitest' +import { createPiModelCatalogProbe } from './rpc-model-catalog-probe' +import type { AgentModelCatalogSuccess } from '../../../native-chat/agent-model-catalog/agent-model-catalog-entry' + +it('publishes a slow inventory independently of state, then keeps the late default', async () => { + vi.useFakeTimers() + onTestFinished(() => { + vi.useRealTimers() + }) + const inventory = Promise.withResolvers() + const state = Promise.withResolvers() + const requested = Promise.withResolvers() + const observations: AgentModelCatalogSuccess[] = [] + const probe = createPiModelCatalogProbe({ + resolveEnvironment: async () => ({}), + resolveCommand: () => process.execPath, + probeVersion: async () => ({ version: '0.84.0' }), + homePath: '/account', + connect: () => ({ + request: (command, _params, options) => { + // The real peer's explicit-null contract retains responses past its default 30s wait. + if (options?.timeoutMs !== null) { + return Promise.reject(new Error('catalog request retained its response deadline')) + } + if (command === 'get_available_models') { + requested.resolve() + return inventory.promise + } + return state.promise + }, + close: async () => {} + }) + }) + const result = probe( + { variable: 'PI_CODING_AGENT_DIR', path: '/account' }, + { publish: (success) => observations.push(success) } + ) + await requested.promise + await vi.advanceTimersByTimeAsync(45_000) + inventory.resolve({ + models: [{ id: 'gpt-live', provider: 'openai', name: 'GPT Live', reasoning: false }] + }) + await vi.advanceTimersByTimeAsync(0) + expect(observations[0]).toMatchObject({ models: [{ id: 'openai/gpt-live' }] }) + expect(observations[0].configured).toBeUndefined() + state.resolve({ model: { id: 'gpt-live', provider: 'openai' }, thinkingLevel: 'high' }) + expect(await result).toMatchObject({ + models: [{ id: 'openai/gpt-live' }], + configured: { model: 'openai/gpt-live', effort: 'high' } + }) + expect(observations[0].configured).toBeUndefined() +}) + +it.each(['empty', 'rejected'])( + 'retains delayed sign-out evidence after %s inventory', + async (kind) => { + const state = Promise.withResolvers() + const requested = Promise.withResolvers() + const probe = createPiModelCatalogProbe({ + resolveEnvironment: async () => ({}), + resolveCommand: () => process.execPath, + probeVersion: async () => ({ version: '0.84.0' }), + homePath: '/account', + connect: () => ({ + request: (command) => { + if (command === 'get_state') { + return state.promise + } + requested.resolve() + return kind === 'empty' + ? Promise.resolve({ models: [] }) + : Promise.reject(new Error('inventory unavailable')) + }, + close: async () => {} + }) + }) + let settled = false + const result = probe({ variable: 'PI_CODING_AGENT_DIR', path: '/account' }).finally(() => { + settled = true + }) + const verdict = expect(result).rejects.toMatchObject({ unavailable: { reason: 'notSignedIn' } }) + await requested.promise + await Promise.resolve() + expect(settled).toBe(false) + state.resolve({ model: { id: 'unknown', provider: 'unknown' } }) + await verdict + } +) diff --git a/src/main/pi/rpc/options/rpc-model-catalog-probe.ts b/src/main/pi/rpc/options/rpc-model-catalog-probe.ts index 4c693c62485..0d76b60f453 100644 --- a/src/main/pi/rpc/options/rpc-model-catalog-probe.ts +++ b/src/main/pi/rpc/options/rpc-model-catalog-probe.ts @@ -1,14 +1,23 @@ +import { agentModelCatalogInputStamp } from '../../../native-chat/agent-model-catalog/agent-model-catalog-input-stamp' import { assertStructuredAgentResolutionCurrent, + type StructuredAgentResolutionOperation, type StructuredAgentCommandSettings } from '../../../native-chat/agent-launch/structured-agent-command-resolution' import { homedir } from 'node:os' import { z } from 'zod' import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' import type { resolveCliCommand } from '../../../../shared/node-cli-command-resolution' -import type { AgentCliVersionReader } from '../../../agent-launch/preflight/agent-cli-version-probe' +import { + readAgentCliVersion, + type AgentCliVersionReader +} from '../../../agent-launch/preflight/agent-cli-version-probe' import { JsonlRpcAgentConnection } from '../../../jsonl-rpc/agent-connection' -import type { AgentModelCatalogProbe } from '../../../native-chat/agent-model-catalog/agent-model-catalog-discovery' +import type { + AgentModelCatalogProgress, + AgentModelCatalogProbe, + AgentModelCatalogLookup +} from '../../../native-chat/agent-model-catalog/agent-model-catalog-discovery' import type { AgentModelCatalogSuccess } from '../../../native-chat/agent-model-catalog/agent-model-catalog-entry' import { runAgentModelCatalogSession } from '../../../native-chat/agent-model-catalog/agent-model-catalog-probe-runner' import { AgentModelCatalogUnavailableError } from '../../../native-chat/agent-model-catalog/agent-model-catalog-unavailable' @@ -26,6 +35,7 @@ const discoveryStateSchema = z.object({ }) export type PiModelCatalogProbeDeps = { + resolveSavedEnvironment?: () => Promise resolveEnvironment: () => Promise /** Refresh once on a missing Pi binary; absent disables retry. */ refreshEnvironmentAfterMiss?: (askedAt: number) => Promise @@ -54,74 +64,129 @@ function connectPiModelCatalog(launch: ProviderProcessLaunch): PiModelCatalogCon } export function createPiModelCatalogProbe(deps: PiModelCatalogProbeDeps): AgentModelCatalogProbe { - return async (accountHome, options): Promise => { - const operation = options?.operation ?? { signal: options?.signal } + const resolve = async ( + accountHome: Parameters[0], + _workspace: string, + lookup: AgentModelCatalogLookup = 'recover', + operation?: StructuredAgentResolutionOperation + ) => { assertStructuredAgentResolutionCurrent(operation) const cwd = deps.homePath ?? homedir() const { env, command, prefixArgs } = await resolvePiRpcInvocation({ operation, accountDir: requireLegacyAgentSessionAccountHome(accountHome).path, - resolveEnvironment: deps.resolveEnvironment, + resolveEnvironment: + lookup === 'recover' + ? deps.resolveEnvironment + : (deps.resolveSavedEnvironment ?? deps.resolveEnvironment), commandSettings: deps.resolveCommandSettings?.(), resolveCommand: deps.resolveCommand, - refreshEnvironmentAfterMiss: deps.refreshEnvironmentAfterMiss, + refreshEnvironmentAfterMiss: + lookup === 'recover' ? deps.refreshEnvironmentAfterMiss : undefined, resolveWorkingDirectory: () => cwd }) assertStructuredAgentResolutionCurrent(operation) - const release = await checkPiRpcVersion({ command, prefixArgs, cwd, env }, deps.probeVersion) - assertStructuredAgentResolutionCurrent(operation) - if (release.status === 'tooOld') { - throw new Error(`pi at ${command} does not run structured chats`) - } - const launch = buildPiRpcLaunch({ - command, - prefixArgs, - cwd, - ...piRpcSessionlessEnvironment(env), - fullAccess: true - }) - const success = await runAgentModelCatalogSession( - () => - (deps.connect ?? connectPiModelCatalog)({ - ...launch, - args: [...launch.args, '--no-session'] - }), - async (connection): Promise => { - let configured: AgentModelCatalogSuccess['configured'] - let unknownProvider = false - try { - const state = discoveryStateSchema.safeParse(await connection.request('get_state')) - unknownProvider = state.success && state.data.model?.provider === 'unknown' - if (state.success && state.data.model && !unknownProvider) { - configured = { - model: piModelOptionId(state.data.model.provider, state.data.model.id), - ...(typeof state.data.thinkingLevel === 'string' && state.data.thinkingLevel - ? { effort: state.data.thinkingLevel } - : {}) - } - } - } catch { - // Optional default facts cannot prevent a usable inventory from being discovered. - } + return { + identity: { command, prefixArgs, cwd }, + inputStamp: await agentModelCatalogInputStamp({ command, prefixArgs, cwd, env }), + run: async ( + signal?: AbortSignal, + runOperation = operation, + _selectedModels?: readonly string[], + publish?: AgentModelCatalogProgress + ): Promise => { + const operation = runOperation + const options = { signal } assertStructuredAgentResolutionCurrent(operation) - options?.signal?.throwIfAborted() - // Pi's own "No models available" condition: no selected provider and nothing listable. - const models = await readPiRpcModelOptions(connection).catch((error: unknown) => { - if (unknownProvider) { - throw new AgentModelCatalogUnavailableError({ reason: 'notSignedIn' }) - } - throw error - }) - if (unknownProvider && models.length === 0) { - throw new AgentModelCatalogUnavailableError({ reason: 'notSignedIn' }) + const release = await checkPiRpcVersion( + { command, prefixArgs, cwd, env, operation }, + deps.probeVersion ?? ((input) => readAgentCliVersion({ ...input, timeoutMs: null })) + ) + assertStructuredAgentResolutionCurrent(operation) + if (release.status === 'tooOld') { + throw new Error(`pi at ${command} does not run structured chats`) } - return { models, origin: 'probe', ...(configured ? { configured } : {}) } - }, - { label: 'pi', signal: options?.signal } - ) - if (success.models.length === 0) { - throw new Error('pi listed no models') + const launch = buildPiRpcLaunch({ + command, + prefixArgs, + cwd, + ...piRpcSessionlessEnvironment(env), + fullAccess: true + }) + const success = await runAgentModelCatalogSession( + () => + (deps.connect ?? connectPiModelCatalog)({ + ...launch, + args: [...launch.args, '--no-session'] + }), + async (connection): Promise => { + let configured: AgentModelCatalogSuccess['configured'] + let unknownProvider = false + let stateKnown = false + let models: AgentModelCatalogSuccess['models'] | undefined + const progress = () => { + assertStructuredAgentResolutionCurrent(operation) + if (models?.length) { + publish?.( + { models, origin: 'probe', ...(configured ? { configured } : {}) }, + stateKnown + ) + } + } + const state = connection + .request('get_state', undefined, { timeoutMs: null }) + .catch(() => undefined) + .then((response) => { + assertStructuredAgentResolutionCurrent(operation) + const parsed = discoveryStateSchema.safeParse(response) + stateKnown = parsed.success + unknownProvider = parsed.success && parsed.data.model?.provider === 'unknown' + if (parsed.success && parsed.data.model && !unknownProvider) { + configured = { + model: piModelOptionId(parsed.data.model.provider, parsed.data.model.id), + ...(typeof parsed.data.thinkingLevel === 'string' && parsed.data.thinkingLevel + ? { effort: parsed.data.thinkingLevel } + : {}) + } + } + progress() + }) + void state.catch(() => {}) + try { + models = await readPiRpcModelOptions(connection, { timeoutMs: null }) + } catch (error) { + await state + if (unknownProvider) { + throw new AgentModelCatalogUnavailableError({ reason: 'notSignedIn' }) + } + throw error + } + progress() + await state + assertStructuredAgentResolutionCurrent(operation) + options.signal?.throwIfAborted() + if (unknownProvider && models.length === 0) { + throw new AgentModelCatalogUnavailableError({ reason: 'notSignedIn' }) + } + return { models, origin: 'probe', ...(configured ? { configured } : {}) } + }, + { label: 'pi', signal: options?.signal, timeoutMs: null } + ) + if (success.models.length === 0) { + throw new Error('pi listed no models') + } + return success + } } - return success } + return Object.assign>( + async (home, options) => + (await resolve(home, '', 'recover', options?.operation)).run( + options?.signal, + options?.operation, + options?.selectedModels, + options?.publish + ), + { resolve } + ) } diff --git a/src/main/pi/rpc/options/rpc-model-options.ts b/src/main/pi/rpc/options/rpc-model-options.ts index 1c1b0b45c40..4c2936a6201 100644 --- a/src/main/pi/rpc/options/rpc-model-options.ts +++ b/src/main/pi/rpc/options/rpc-model-options.ts @@ -35,9 +35,12 @@ export function parsePiModelOptionId(value: string): { provider: string; modelId /** Native inventory projection shared by running chats and the pre-session catalog. */ export async function readPiRpcModelOptions( - rpc: PiRpcRequester + rpc: PiRpcRequester, + options?: { timeoutMs?: number | null } ): Promise { - const models = modelsSchema.parse(await rpc.request('get_available_models')).models + const models = modelsSchema.parse( + await rpc.request('get_available_models', undefined, options) + ).models return models.map((model) => { const id = piModelOptionId(model.provider, model.id) const efforts = diff --git a/src/main/preflight/agents-refreshed-on-host.ts b/src/main/preflight/agents-refreshed-on-host.ts index 8028cb9f90f..78f70ec2d87 100644 --- a/src/main/preflight/agents-refreshed-on-host.ts +++ b/src/main/preflight/agents-refreshed-on-host.ts @@ -1,11 +1,11 @@ -const agentRefreshListeners = new Set<() => void>() +const agentRefreshListeners = new Set<(userInitiated: boolean) => void>() /** An agent refresh is how a user says a CLI or its login changed; host caches drop on it. */ -export function onAgentsRefreshedOnHost(listener: () => void): () => void { +export function onAgentsRefreshedOnHost(listener: (userInitiated: boolean) => void): () => void { agentRefreshListeners.add(listener) return () => agentRefreshListeners.delete(listener) } -export function notifyAgentsRefreshedOnHost(): void { - agentRefreshListeners.forEach((listener) => listener()) +export function notifyAgentsRefreshedOnHost(userInitiated = false): void { + agentRefreshListeners.forEach((listener) => listener(userInitiated)) } diff --git a/src/main/preflight/workspace-agent-detection.ts b/src/main/preflight/workspace-agent-detection.ts index 6b73d7486d9..820a83b18e3 100644 --- a/src/main/preflight/workspace-agent-detection.ts +++ b/src/main/preflight/workspace-agent-detection.ts @@ -157,7 +157,8 @@ export async function assertAgentDetectionHostRunning(host: AgentDetectionHost): export async function refreshAgentsOnHost( host: AgentDetectionHost, - options?: InstalledAgentDetectionOptions + options?: InstalledAgentDetectionOptions, + userInitiated = false ): Promise { if (host.kind === 'ssh') { throw new SshHostNotServedError(host.connectionId) @@ -169,7 +170,7 @@ export async function refreshAgentsOnHost( ? refreshShellPathAndDetectAgents(host.context, options) : refreshShellPathAndDetectAgents(host.context) const result = wsl ? await detect() : await captureHostShellEnvironment(detect) - notifyAgentsRefreshedOnHost() + notifyAgentsRefreshedOnHost(userInitiated && !wsl) return result } return wsl ? refresh() : refreshAtRestCommandContext(refresh) diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts index 0935e71ddb3..89cf9be8276 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts @@ -1,3 +1,9 @@ +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, delimiter } from 'node:path' +import { resolveCliCommand } from '../../../../shared/node-cli-command-resolution' +import { createCodexModelCatalogProbe } from '../../../codex/structured/catalog/codex-model-catalog-probe' +import { refreshAtRestCommandContext } from '../../../native-chat/agent-session-wire/options/at-rest-command-context' import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' import { afterEach, expect, it, vi } from 'vitest' import { agentSessionRecordFixture } from '../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' @@ -11,8 +17,8 @@ import { const shell = vi.hoisted( (): { - current: { PATH: string; IGNORED: string } - next: { PATH: string; IGNORED: string } + current: { PATH: string; Path?: string; path?: string; IGNORED: string } + next: { PATH: string; Path?: string; path?: string; IGNORED: string } saved: string[] nextSaved: string[] } => ({ @@ -68,11 +74,12 @@ function rig(overlay?: Record) { workspaceMayOverrideDefaultModel: defaults }) const environment = createStructuredAgentEnvironmentResolvers({ - resolveShellEnvironmentPolicy: () => ({ inheritAll: false, names: [] }), + resolveShellEnvironmentPolicy: () => ({ inheritAll: false, names: ['IGNORED'] }), resolveAgentLaunchEnv: () => overlay ?? {} }) cleanups.push(service.stop, environment.bindCatalogSources(['grok'])) const listing = (id: string) => ({ + origin: 'probe' as const, models: [{ id, label: id, isDefault: true, efforts: [] }], configuredDefault: { modelId: id, effort: 'high' } }) @@ -86,21 +93,38 @@ function rig(overlay?: Record) { } } -it('keeps a Windows catalog source while only a shadowed inherited path changes', async () => { - vi.stubGlobal('process', { ...process, platform: 'win32' }) - const overlay = { path: '/configured/bin' } - const h = rig(overlay) - const source = h.service.captureSource(h.record) - cleanups.push(() => source.release?.()) - await captureHostShellEnvironment(async () => { - shell.next = { PATH: '/changed', IGNORED: 'a' } - }) - expect(source()).toBe(true) - await captureHostShellEnvironment(async () => { - overlay.path = '/new-configured/bin' - }) - expect(source()).toBe(false) -}) +it.each(['darwin', 'win32'] as const)( + 'keeps a %s catalog source through PATH-only and overlay-shadowed changes', + async (platform) => { + vi.stubGlobal('process', { ...process, platform }) + shell.current = { PATH: '/a', Path: '/shadow-a', path: '/shadow-b', IGNORED: 'a' } + const overlay = { IGNORED: 'configured' } + const h = rig(overlay) + const source = h.service.captureSource(h.record) + cleanups.push(() => source.release?.()) + agentModelCatalogStore.recordSuccess(h.fingerprint, 'grok', h.listing('saved'), 'discovery') + const held = Promise.withResolvers>() + const flight = agentModelCatalogStore.refresh(h.fingerprint, 'grok', () => held.promise) + await Promise.resolve() + await captureHostShellEnvironment(async () => { + shell.next = { + PATH: '/changed', + Path: '/other-shadow-a', + path: '/other-shadow-b', + IGNORED: 'shadowed' + } + }) + expect(source()).toBe(true) + expect(agentModelCatalogStore.get(h.fingerprint)?.models[0]?.id).toBe('saved') + held.resolve(h.listing('current')) + await flight + expect(agentModelCatalogStore.get(h.fingerprint)?.models[0]?.id).toBe('current') + await captureHostShellEnvironment(async () => { + overlay.IGNORED = 'new-configured' + }) + expect(source()).toBe(false) + } +) it('retires a producer on effective Refresh before new publication and fences late defaults and new old reports', async () => { const h = rig() @@ -116,7 +140,7 @@ it('retires a producer on effective Refresh before new publication and fences la h.service.recordLiveListing(h.record.sessionId, h.listing('A'), sourceA) await vi.waitFor(() => expect(h.defaults).toHaveBeenCalledOnce()) await captureHostShellEnvironment(async () => { - shell.next = { PATH: '/b', IGNORED: 'a' } + shell.next = { PATH: '/b', IGNORED: 'b' } }) expect(sourceA()).toBe(false) const sourceB = h.service.captureSource(h.record) @@ -169,3 +193,113 @@ it.each([true, false])( expect(env.CODEX_CI).toBe('set-by-user') } ) + +it('reuses the selected Codex across folders and capture, then follows a different PATH executable', async () => { + const folder = await mkdtemp(join(tmpdir(), 'orca-catalog-capture-')) + const [a, b, bin, replacement, unrelated] = ['a', 'b', 'bin', 'replacement', 'unrelated'].map( + (name) => join(folder, name) + ) + await Promise.all([a, b, bin, replacement, unrelated].map((path) => mkdir(path))) + const executable = process.platform === 'win32' ? 'catalog-codex.cmd' : 'catalog-codex' + await Promise.all( + [bin, replacement].map((path) => + writeFile(join(path, executable), 'test binary identity', { mode: 0o755 }) + ) + ) + shell.current = { + PATH: `../bin${delimiter}./node_modules/.bin${delimiter}${folder}/unused-one${delimiter}`, + IGNORED: 'a' + } + shell.next = { ...shell.current } + const environment = createStructuredAgentEnvironmentResolvers({ + prewarm: false, + resolveShellEnvironmentPolicy: () => ({ inheritAll: false, names: [] }) + }) + const firstStarted = Promise.withResolvers() + const otherStarted = Promise.withResolvers() + const first = Promise.withResolvers() + const other = Promise.withResolvers() + let duplicate = false + const probe = createCodexModelCatalogProbe({ + resolveEnvironment: () => environment.resolveAgentEnvironment('codex'), + resolveSavedEnvironment: () => environment.resolveAgentEnvironment('codex', true), + resolveCommand: (options) => ({ + command: resolveCliCommand('catalog-codex', options), + prefixArgs: [] + }), + runSession: async (invocation, body) => { + let id = 'replacement' + if (invocation.command === join(bin, executable)) { + id = duplicate ? 'duplicate' : 'original' + duplicate = true + firstStarted.resolve() + await first.promise + } + return body({ + request: async (method) => + method === 'model/list' + ? { + data: [ + { + model: id, + displayName: id, + hidden: false, + supportedReasoningEfforts: [], + isDefault: true + } + ], + nextCursor: null + } + : method === 'config/read' + ? { config: {} } + : {}, + notify: () => {} + }) + } + }) + const service = createAgentModelCatalogService({ + store: agentModelCatalogStore, + getConversation: () => undefined, + getRecord: () => undefined, + drivesRecord: () => true, + resolveAccountHome: async () => ({ variable: 'CODEX_HOME', path: folder }), + probes: { codex: probe } + }) + cleanups.push(environment.bindCatalogSources(['codex']), service.stop, () => { + void rm(folder, { recursive: true, force: true }) + }) + const read = (workspacePath: string) => + service.read({ agent: 'codex', workspacePath, waitForListing: true }) + const firstRead = read(a) + await firstStarted.promise + await refreshAtRestCommandContext(() => + captureHostShellEnvironment(async () => { + shell.next = { ...shell.current, PATH: `../bin${delimiter}${folder}/unused-two${delimiter}` } + }) + ) + const shared = read(b) + first.resolve() + await firstRead + expect(await shared).toMatchObject({ models: [{ id: 'original' }] }) + const unrelatedRead = agentModelCatalogStore.refresh( + 'unrelated-input-fixture', + 'codex', + async () => { + otherStarted.resolve() + await other.promise + return { + origin: 'probe', + models: [{ id: 'unrelated', label: 'Unrelated', efforts: [], isDefault: true }] + } + } + ) + await otherStarted.promise + await refreshAtRestCommandContext(() => + captureHostShellEnvironment(async () => { + shell.next = { ...shell.current, PATH: `${replacement}${delimiter}../bin${delimiter}` } + }) + ) + expect(await read(a)).toMatchObject({ models: [{ id: 'replacement' }] }) + other.resolve() + expect(await unrelatedRead).toMatchObject({ models: [{ id: 'unrelated' }] }) +}) diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts index 256ce90d5ce..abbe75437ef 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts @@ -204,7 +204,7 @@ export function createStructuredAgentEnvironmentResolvers( /** The shared base every agent's child env starts from, before its own overlay. */ resolveBaseEnvironment: (cachedOnly?: boolean) => Promise> /** The base with the user's overlay for `agent` laid over it. */ - resolveAgentEnvironment: (agent: string) => Promise> + resolveAgentEnvironment: (agent: string, cachedOnly?: boolean) => Promise> refreshAfterMissingProgram: (askedAt: number) => Promise bindCatalogSources: (agents: readonly string[]) => () => void } { @@ -245,7 +245,16 @@ export function createStructuredAgentEnvironmentResolvers( overlays.get(agent), process.platform ) - return [agent, structuredAgentEnvironmentIdentity(effective)] + return [ + agent, + structuredAgentEnvironmentIdentity( + Object.fromEntries( + Object.entries(effective).filter(([key]) => + process.platform === 'win32' ? key.toUpperCase() !== 'PATH' : key !== 'PATH' + ) + ) + ) + ] }) ) } @@ -256,9 +265,9 @@ export function createStructuredAgentEnvironmentResolvers( } }, resolveBaseEnvironment: resolveBase, - resolveAgentEnvironment: async (agent) => + resolveAgentEnvironment: async (agent, cachedOnly) => overlayEnvironmentVariables( - await resolveBase(), + await resolveBase(cachedOnly), sources.resolveAgentLaunchEnv?.(agent), process.platform ) diff --git a/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts b/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts index eb1f124e40f..21a52b02ef3 100644 --- a/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts +++ b/src/main/runtime/agent-session/model-catalog/structured-agent-model-catalog-discovery.ts @@ -87,6 +87,7 @@ export function acpModelCatalogDiscovery( ...(acpListingNeedsChatFolder(discovery) ? { listsInChatFolder: true as const } : {}), probe: createAcpModelCatalogProbe(spec, { resolveEnvironment: environment.resolveBaseEnvironment, + resolveSavedEnvironment: () => environment.resolveBaseEnvironment(true), refreshEnvironmentAfterMiss: environment.refreshAfterMissingProgram, dataDirectory: deps.stateDirectory, ...(deps.resolveAgentLaunchEnv ? { resolveLaunchEnv: deps.resolveAgentLaunchEnv } : {}), diff --git a/src/main/runtime/rpc/methods/preflight/preflight.ts b/src/main/runtime/rpc/methods/preflight/preflight.ts index e8ea0998ae0..d912e6fc88f 100644 --- a/src/main/runtime/rpc/methods/preflight/preflight.ts +++ b/src/main/runtime/rpc/methods/preflight/preflight.ts @@ -14,7 +14,7 @@ import { refreshAgentsOnHost } from '../../../../preflight/workspace-agent-detection' import { - PreflightAgentDetection, + PreflightAgentRefresh, PreflightProjectAgentDetection, PreflightCheck, PreflightDetectRemoteAgents, @@ -74,11 +74,11 @@ export const PREFLIGHT_METHODS = [ defineMethod({ name: 'preflight.refreshAgents', permission: 'workspace', - params: PreflightAgentDetection, + params: PreflightAgentRefresh, handler: async (params, { runtime }) => { const host = await resolveQualifiedAgentDetectionHost(runtime, params) await assertAgentDetectionHostRunning(host) - return refreshAgentsOnHost(host, hostDetectionOptions(runtime)) + return refreshAgentsOnHost(host, hostDetectionOptions(runtime), params.userInitiated) } }) ] diff --git a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.test.ts b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.test.ts index d92cf102a78..33512588f64 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.test.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.test.ts @@ -78,6 +78,25 @@ describe('agentSession.modelCatalog', () => { ) }) + it.each([false, true])( + 'negotiates early progress through the existing client capability (enabled=%s)', + async (enabled) => { + record = { ...agentSessionRecordFixture(), provider: 'codex' } + const result = await call( + 'agentSession.modelCatalog', + { agent: 'codex', sessionId: record.sessionId, waitForListing: true }, + { + ...STRUCTURED_CLIENT, + clientCapabilities: DESKTOP_RENDERER_RUNTIME_CLIENT_CAPABILITIES.filter( + (capability) => enabled || capability !== 'agent-session.model-catalog.progress.v1' + ) + } + ) + expect(result.ok, JSON.stringify(result)).toBe(true) + expect(read).toHaveBeenLastCalledWith(expect.objectContaining({ progress: enabled })) + } + ) + it("keeps a moved floating workspace's list apart from the old folder's late answer", async () => { const late = Promise.withResolvers() const listed = (id: string): AgentModelCatalogSuccess => ({ diff --git a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts index df3412bce8d..64de6072066 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.ts @@ -1,4 +1,7 @@ -import { AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY } from '../../../../../../shared/agent-session/structured-agent-session-surface-capabilities' +import { + AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY, + AGENT_SESSION_MODEL_CATALOG_PROGRESS_CAPABILITY +} from '../../../../../../shared/agent-session/structured-agent-session-surface-capabilities' // options reads at-rest records/catalogs or the live provider; modelCatalog reads stored/start-published facts without waiting on attach. // Older hosts return method_not_found (mobile may see forbidden); clients retain static seeds. @@ -113,6 +116,10 @@ export const STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS = [ const request = { ...params, ...scope, + progress: + ctx.clientKind === undefined || + ctx.clientCapabilities?.includes(AGENT_SESSION_MODEL_CATALOG_PROGRESS_CAPABILITY) === + true, ...(waits && resolving ? { deadline } : {}), ...(launchDirectory ? { workspacePath: launchDirectory } @@ -140,7 +147,7 @@ export const STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS = [ ) } // A floating read lists the folder it resolves to (above), never the unresolved one. - if (!host && !params.savedOnly && !follows) { + if (!waits && !host && !params.savedOnly && !follows) { void catalog.demand(request) } const result = host ? await host.readModelCatalog(request) : await catalog.read(request) diff --git a/src/preload/api/preflight/preflight-api.ts b/src/preload/api/preflight/preflight-api.ts index 1a302473560..8051b767317 100644 --- a/src/preload/api/preflight/preflight-api.ts +++ b/src/preload/api/preflight/preflight-api.ts @@ -48,7 +48,11 @@ export type PreflightApi = { ) => Promise /** Complete by default; background callers opt into host-owned enabled preferences. */ detectAgents: ( - args?: PreflightRuntimeContext & { enabledOnly?: boolean; wakeWslDistro?: boolean } + args?: PreflightRuntimeContext & { + enabledOnly?: boolean + wakeWslDistro?: boolean + userInitiated?: boolean + } ) => Promise /** A WSL distro a background check was refused for is running now; re-ask. Desktop only. */ onWslDistroRunning?: (callback: (distro: string) => void) => () => void @@ -56,7 +60,11 @@ export type PreflightApi = { zcodeInteractiveCapability: () => Promise /** `wakeWslDistro`: a user act that may start a stopped WSL distro; background refreshes omit it. */ refreshAgents: ( - args?: PreflightRuntimeContext & { enabledOnly?: boolean; wakeWslDistro?: boolean } + args?: PreflightRuntimeContext & { + enabledOnly?: boolean + wakeWslDistro?: boolean + userInitiated?: boolean + } ) => Promise detectRemoteAgents: (args: { connectionId: string }) => Promise detectRemoteWindowsTerminalCapabilities: (args: { connectionId: string }) => Promise<{ diff --git a/src/preload/api/preflight/preflight-bridge.ts b/src/preload/api/preflight/preflight-bridge.ts index da0c45ad7a6..e337af98440 100644 --- a/src/preload/api/preflight/preflight-bridge.ts +++ b/src/preload/api/preflight/preflight-bridge.ts @@ -29,7 +29,11 @@ export const preflightApi = { linear: { connected: boolean } }> => ipcRenderer.invoke('preflight:check', args), detectAgents: ( - args?: PreflightRuntimeContext & { enabledOnly?: boolean; wakeWslDistro?: boolean } + args?: PreflightRuntimeContext & { + enabledOnly?: boolean + wakeWslDistro?: boolean + userInitiated?: boolean + } ): Promise => ipcRenderer.invoke('preflight:detectAgents', args), onWslDistroRunning: (callback: (distro: string) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, distro: string): void => callback(distro) @@ -39,7 +43,11 @@ export const preflightApi = { zcodeInteractiveCapability: (): Promise => ipcRenderer.invoke('preflight:zcodeInteractiveCapability'), refreshAgents: ( - args?: PreflightRuntimeContext & { enabledOnly?: boolean; wakeWslDistro?: boolean } + args?: PreflightRuntimeContext & { + enabledOnly?: boolean + wakeWslDistro?: boolean + userInitiated?: boolean + } ): Promise => ipcRenderer.invoke('preflight:refreshAgents', args), detectRemoteAgents: (args: { connectionId: string }): Promise => ipcRenderer.invoke('preflight:detectRemoteAgents', args), diff --git a/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts b/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts index 61dc3cb3aca..11d58425ccb 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-acquisition.test.ts @@ -206,3 +206,51 @@ it('keeps an unflagged saved catalog provisional when its read fails', async () stop() } }) + +it('keeps an open picker subscribed after usable progress until late enrichment arrives', async () => { + const inventory = Promise.withResolvers() + const enriched = Promise.withResolvers() + let next = inventory.promise + let published: AgentPickerEntry[] = [] + const close = observeAgentPickerAcquisition( + 'late-enrichment', + [codex], + { + catalog: async (_entry, wait) => + wait ? next : { origin: 'unknown', listingInProgress: true }, + support: async () => undefined + }, + { + selected: () => 'codex', + publish: (entries) => { + published = entries + } + } + ) + onTestFinished(close) + await vi.waitFor(() => expect(published[0]?.catalog).toMatchObject({ listingInProgress: true })) + next = enriched.promise + inventory.resolve({ + origin: 'probe', + fetchedAt: 1, + models: [model('listed')], + listingInProgress: true + }) + await vi.waitFor(() => + expect(published[0]?.catalog).toMatchObject({ models: [{ id: 'listed' }] }) + ) + expect(published[0]?.catalogRead).toBe('pending') + enriched.resolve({ + origin: 'probe', + fetchedAt: 2, + models: [ + { ...model('listed'), defaultEffort: 'high', efforts: [{ value: 'high', label: 'High' }] } + ] + }) + await vi.waitFor(() => + expect(published[0]).toMatchObject({ + catalogRead: 'settled', + catalog: { models: [{ id: 'listed', defaultEffort: 'high' }] } + }) + ) +}) diff --git a/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts b/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts index ce07b04ae45..bbc08d9c020 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts @@ -190,7 +190,7 @@ class AgentPickerAcquisition { const refresh = !signal.aborted && this.observers.size > 0 && - (waitForListing ? catalog.waitExpired : catalog.listingInProgress) === true + (catalog.waitExpired === true || catalog.listingInProgress === true) if (refresh) { this.queued.refresh.add(index) } diff --git a/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.test.tsx b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.test.tsx index f5ae1848217..c59c8e5e215 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.test.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentLaunchChoiceEditor.test.tsx @@ -78,6 +78,26 @@ describe('AgentLaunchChoiceEditor model list', () => { useAppStore.setState({ settings: initialSettings }) }) + it('shows later catalog updates while Settings stays open after initial progress', async () => { + const inventory = Promise.withResolvers() + const enriched = Promise.withResolvers() + call + .mockResolvedValueOnce({ origin: 'unknown', listingInProgress: true }) + .mockReturnValueOnce(inventory.promise) + .mockReturnValueOnce(enriched.promise) + useAppStore.setState({ settings: getDefaultSettings('') }) + renderEditor() + await act(async () => inventory.resolve({ ...LISTED, listingInProgress: true })) + await waitFor(() => expect(menus.get('Model')).toContain('gpt-6-astra')) + await act(async () => + enriched.resolve({ + ...LISTED, + models: [{ id: 'late-model', label: 'Late model', efforts: [] }] + }) + ) + await waitFor(() => expect(menus.get('Model')).toEqual(['__agent_default__', 'late-model'])) + }) + it('shows the refreshed model after the agent command changes and ignores the older answer', async () => { let answerOlder: (catalog: unknown) => void = () => {} call.mockReturnValueOnce(new Promise((resolve) => (answerOlder = resolve))) diff --git a/src/renderer/src/components/agent/launch-settings/use-agent-settings-model-catalog.ts b/src/renderer/src/components/agent/launch-settings/use-agent-settings-model-catalog.ts index dc38bb37afe..cba609cee1c 100644 --- a/src/renderer/src/components/agent/launch-settings/use-agent-settings-model-catalog.ts +++ b/src/renderer/src/components/agent/launch-settings/use-agent-settings-model-catalog.ts @@ -92,11 +92,10 @@ export function useAgentSettingsModelCatalog( if (stale) { return } - if (wait ? catalog.waitExpired : catalog.listingInProgress) { - read(true) - return - } setAnswer({ key, accountSettings, generation, catalog }) + if (catalog.waitExpired || catalog.listingInProgress) { + read(true) + } }) // Why not the snapshot: an unanswered read can't vouch for an older list. .catch(() => { diff --git a/src/renderer/src/components/native-chat/host-access/native-chat-host-setup.ts b/src/renderer/src/components/native-chat/host-access/native-chat-host-setup.ts index 9c0c62bf984..d6c0a6cee1f 100644 --- a/src/renderer/src/components/native-chat/host-access/native-chat-host-setup.ts +++ b/src/renderer/src/components/native-chat/host-access/native-chat-host-setup.ts @@ -231,8 +231,8 @@ function useNativeChatInstall( setRechecking(true) void ( environmentId - ? state.refreshRuntimeDetectedAgents(environmentId, worktreeId) - : state.refreshDetectedAgents(worktreeId, { wakeWslDistro: true }) + ? state.refreshRuntimeDetectedAgents(environmentId, worktreeId, { userInitiated: true }) + : state.refreshDetectedAgents(worktreeId, { wakeWslDistro: true, userInitiated: true }) ) .then(() => { // Refreshes can resolve with cached agents after failure; check their explicit outcome. diff --git a/src/renderer/src/components/settings/agents/AgentsPane.tsx b/src/renderer/src/components/settings/agents/AgentsPane.tsx index 515b1721801..2e7c891e548 100644 --- a/src/renderer/src/components/settings/agents/AgentsPane.tsx +++ b/src/renderer/src/components/settings/agents/AgentsPane.tsx @@ -74,7 +74,9 @@ export function AgentsPane({ settings={settings} updateSettings={updateSettings} refresh={() => - useAppStore.getState().refreshDetectedAgents(undefined, { wakeWslDistro: true }) + useAppStore + .getState() + .refreshDetectedAgents(undefined, { wakeWslDistro: true, userInitiated: true }) } wslSupportedPlatform={wslSupportedPlatform} wslAvailable={wslAvailable} diff --git a/src/renderer/src/components/status-bar/use-status-bar-controller.ts b/src/renderer/src/components/status-bar/use-status-bar-controller.ts index 5a8b4cf3cc0..9141d96d067 100644 --- a/src/renderer/src/components/status-bar/use-status-bar-controller.ts +++ b/src/renderer/src/components/status-bar/use-status-bar-controller.ts @@ -94,7 +94,7 @@ export function useStatusBarController(floatingTerminalOpen: boolean) { // Why: re-run PATH detection so a freshly-installed/removed CLI's bar appears/hides without restarting Orca. await Promise.all([ (refreshRemote ?? refreshRateLimits)(), - refreshDetectedAgents(undefined, { wakeWslDistro: true }) + refreshDetectedAgents(undefined, { wakeWslDistro: true, userInitiated: true }) ]) } finally { if (mountedRef.current) { diff --git a/src/renderer/src/hooks/useDetectedAgents.test.tsx b/src/renderer/src/hooks/useDetectedAgents.test.tsx index ca37e790dd0..975e7b81c8f 100644 --- a/src/renderer/src/hooks/useDetectedAgents.test.tsx +++ b/src/renderer/src/hooks/useDetectedAgents.test.tsx @@ -220,7 +220,11 @@ describe('Floating Workspace authority', () => { expect(activeResult.current?.detectedIds).toEqual(['claude']) expect(floatingResult.current?.detectedIds).toEqual(['codex']) expect(useAppStore.getState().detectedAgentIds).toEqual(['claude']) - expect(refreshLocalAgents).toHaveBeenLastCalledWith({ enabledOnly: true, wakeWslDistro: true }) + expect(refreshLocalAgents).toHaveBeenLastCalledWith({ + enabledOnly: true, + wakeWslDistro: true, + userInitiated: true + }) }) }) diff --git a/src/renderer/src/hooks/useDetectedAgents.ts b/src/renderer/src/hooks/useDetectedAgents.ts index 9e0d5f44b4c..fa041682c60 100644 --- a/src/renderer/src/hooks/useDetectedAgents.ts +++ b/src/renderer/src/hooks/useDetectedAgents.ts @@ -176,15 +176,20 @@ export function useDetectedAgents( // Imperative action reads avoid six inert subscriptions per retained tab bar. const state = useAppStore.getState() if (targetKind === 'runtime' && targetId) { - return state.refreshRuntimeDetectedAgents(targetId, runtimeWorktreeId) + return state.refreshRuntimeDetectedAgents(targetId, runtimeWorktreeId, { + userInitiated: true + }) } if (targetKind === 'ssh' && targetId) { return state.refreshRemoteDetectedAgents(targetId) } // Only the refresh control calls this: a user act that may start a stopped WSL distro. return includeDisabled - ? state.refreshAllDetectedAgents(localWorktreeId, { wakeWslDistro: true }) - : state.refreshDetectedAgents(localWorktreeId, { wakeWslDistro: true }) + ? state.refreshAllDetectedAgents(localWorktreeId, { + wakeWslDistro: true, + userInitiated: true + }) + : state.refreshDetectedAgents(localWorktreeId, { wakeWslDistro: true, userInitiated: true }) }, [includeDisabled, isUnknown, localWorktreeId, runtimeWorktreeId, targetKind, targetId]) useEffect(() => { diff --git a/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts b/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts index 143b266805d..39f6da48816 100644 --- a/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts +++ b/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts @@ -173,6 +173,58 @@ describe('createDetectedAgentsSlice remote detection', () => { expect(store.getState().remoteDetectedAgentIds['ssh-1']).toEqual(['kilo']) }) + it.each([false, true])( + 'follows an automatic host refresh with one explicit request (automatic fails: %s)', + async (fails) => { + const store = createTestStore() + const automaticReply = Promise.withResolvers() + runtimeEnvironmentCall.mockImplementation( + ({ method, params }: { method: string; params?: { userInitiated?: boolean } }) => { + if (method === 'preflight.refreshAgents') { + return params?.userInitiated + ? Promise.resolve({ id: method, ok: true, result: { agents: ['grok'] } }) + : automaticReply.promise + } + return Promise.resolve({ + id: method, + ok: true, + result: { + runtimeId: 'runtime', + rendererGraphEpoch: 1, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0, + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + } + }) + } + ) + const automatic = store.getState().refreshRuntimeDetectedAgents('env-explicit') + const explicit = store + .getState() + .refreshRuntimeDetectedAgents('env-explicit', undefined, { userInitiated: true }) + expect( + store + .getState() + .refreshRuntimeDetectedAgents('env-explicit', undefined, { userInitiated: true }) + ).toBe(explicit) + if (fails) { + automaticReply.reject(new Error('host temporarily unavailable')) + } else { + automaticReply.resolve({ + id: 'preflight.refreshAgents', + ok: true, + result: { agents: ['claude'] } + }) + } + await automatic + expect(await explicit).toEqual(['grok']) + expect(store.getState().runtimeDetectedAgentIds['env-explicit']).toEqual(['grok']) + } + ) + it('keeps a late initial detect from overwriting a runtime refresh', async () => { const store = createTestStore() let resolveDetect: (value: unknown) => void = () => {} diff --git a/src/renderer/src/store/slices/agent-inventory/local-agent-inventory-refresh.ts b/src/renderer/src/store/slices/agent-inventory/local-agent-inventory-refresh.ts index 9f07f888350..911732eb292 100644 --- a/src/renderer/src/store/slices/agent-inventory/local-agent-inventory-refresh.ts +++ b/src/renderer/src/store/slices/agent-inventory/local-agent-inventory-refresh.ts @@ -16,6 +16,7 @@ export type LocalAgentInventoryLifecycle = { refreshPromises: Map> /** Refreshes sent as a user act; a background one may be refused for a stopped WSL distro. */ wakeRefreshes: WeakSet> + explicitRefreshes: WeakSet> wakeDetects: WeakSet> /** Contexts whose last probe the E9 gate refused (distro not running), not a real failure. */ refusedContextKeys: Set @@ -68,7 +69,11 @@ export function refreshLocalAgentInventory( } const inflight = lifecycle.refreshPromises.get(contextKey) // A refresh click must reach main as a wake, not ride a background refresh it would refuse. - if (inflight && (!options.wakeWslDistro || lifecycle.wakeRefreshes.has(inflight))) { + if ( + inflight && + (!options.wakeWslDistro || lifecycle.wakeRefreshes.has(inflight)) && + (!options.userInitiated || lifecycle.explicitRefreshes.has(inflight)) + ) { exposeInflightToLegacy() return inflight } @@ -103,7 +108,7 @@ export function refreshLocalAgentInventory( })) const refreshArgs = includeDisabled ? context : { ...context, enabledOnly: true } const pending = window.api.preflight - .refreshAgents(options.wakeWslDistro ? { ...refreshArgs, wakeWslDistro: true } : refreshArgs) + .refreshAgents({ ...refreshArgs, ...options }) .then((result) => { const typed = result.agents.filter(isTuiAgent) const published = includeDisabled @@ -205,6 +210,10 @@ export function refreshLocalAgentInventory( lifecycle.wakeRefreshes.add(pending) lifecycle.wakeRefreshes.add(publishedPending) } + if (options.userInitiated) { + lifecycle.explicitRefreshes.add(pending) + lifecycle.explicitRefreshes.add(publishedPending) + } lifecycle.refreshPromises.set(contextKey, pending) return pending } diff --git a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts index 9142e5a3370..6fcc16bf834 100644 --- a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts +++ b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts @@ -62,6 +62,24 @@ describe('local detected agent context lifecycle', () => { }) }) + it('sends explicit catalog intent even while an automatic refresh is pending', async () => { + const store = createTestStore([]) + const automaticReply = Promise.withResolvers<{ agents: string[] }>() + refreshAgents.mockImplementation((args) => + args?.userInitiated ? Promise.resolve({ agents: ['grok'] }) : automaticReply.promise + ) + const automatic = store.getState().refreshDetectedAgents() + const explicit = store.getState().refreshDetectedAgents(undefined, { userInitiated: true }) + expect(store.getState().refreshDetectedAgents(undefined, { userInitiated: true })).toBe( + explicit + ) + expect(await explicit).toEqual(['grok']) + automaticReply.resolve({ agents: ['claude'] }) + await automatic + expect(store.getState().detectedAgentIds).toEqual(['grok']) + expect(refreshAgents).toHaveBeenCalledWith(expect.objectContaining({ userInitiated: true })) + }) + it('keeps complete Settings inventory separate from automatic probes in either completion order', async () => { const store = createTestStore([]) const resolveDetection = new Map void>() diff --git a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.ts b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.ts index 1b1d85f6215..4b877253fb1 100644 --- a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.ts +++ b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.ts @@ -36,6 +36,7 @@ export const createLocalDetectedAgentState: LocalDetectedAgentStateCreator = (se detectPromises: new Map(), refreshPromises: new Map(), wakeRefreshes: new WeakSet(), + explicitRefreshes: new WeakSet(), wakeDetects: new WeakSet(), refusedContextKeys: new Set(), keptThroughFailure: new WeakSet(), diff --git a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-store-state.ts b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-store-state.ts index e6e85e01e5e..5017501dc25 100644 --- a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-store-state.ts +++ b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-store-state.ts @@ -6,7 +6,7 @@ import type { import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' /** `wakeWslDistro`: a user act (a click, a runtime choice) that may start a stopped WSL distro. */ -export type LocalAgentRefreshOptions = { wakeWslDistro?: boolean } +export type LocalAgentRefreshOptions = { wakeWslDistro?: boolean; userInitiated?: boolean } export type LocalDetectedAgentState = { readLocalAgentInventory: (worktreeId?: string | null) => { diff --git a/src/renderer/src/store/slices/agent-inventory/runtime-agent-detection-request.ts b/src/renderer/src/store/slices/agent-inventory/runtime-agent-detection-request.ts new file mode 100644 index 00000000000..1e81924603b --- /dev/null +++ b/src/renderer/src/store/slices/agent-inventory/runtime-agent-detection-request.ts @@ -0,0 +1,48 @@ +import { getRuntimeEnvironmentStatus } from '@/runtime/rpc/compatibility/runtime-compatibility-probe' +import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' +import { PREFLIGHT_WORKSPACE_SCOPED_RUNTIME_CAPABILITY } from '../../../../../shared/preflight-runtime-capabilities' + +export class RuntimeAgentDetectionNeedsServerUpdateError extends Error { + constructor() { + super("Update Orca on this server to list this workspace's agents.") + this.name = 'RuntimeAgentDetectionNeedsServerUpdateError' + } +} + +/** A paired host's workspace that lives on one of that host's own SSH targets. */ +export type NestedSshAgentDetection = { + connectionId: string + call: (params: { connectionId: string }) => Promise +} + +/** Old hosts can supply workspace agents via host defaults only on known non-Windows platforms; host-default requests remain synchronous. */ +export function callRuntimeAgentDetection( + environmentId: string, + worktreeId: string | null | undefined, + call: (params: { worktreeId: string } | undefined) => Promise, + nestedSsh?: NestedSshAgentDetection +): Promise { + if (!worktreeId) { + return call(undefined) + } + const capability = PREFLIGHT_WORKSPACE_SCOPED_RUNTIME_CAPABILITY + return runtimeEnvironmentSupportsCapability(environmentId, capability).then(async (supported) => { + if (supported) { + return call({ worktreeId }) + } + // Why: a fresh status both reports the platform and catches an in-place upgrade. + const status = await getRuntimeEnvironmentStatus(environmentId) + if (status.capabilities?.includes(capability)) { + return call({ worktreeId }) + } + // Why: the host's SSH workspace runs on its SSH target, which old hosts already probe by id. + if (nestedSsh) { + return nestedSsh.call({ connectionId: nestedSsh.connectionId }) + } + // Why: an old Windows host's default omits a WSL workspace's agents; an absent platform may be one. + if (!status.hostPlatform || status.hostPlatform === 'win32') { + throw new RuntimeAgentDetectionNeedsServerUpdateError() + } + return call(undefined) + }) +} diff --git a/src/renderer/src/store/slices/agent-inventory/runtime-detected-agents.ts b/src/renderer/src/store/slices/agent-inventory/runtime-detected-agents.ts index fb2b37731eb..ddac9e79a7c 100644 --- a/src/renderer/src/store/slices/agent-inventory/runtime-detected-agents.ts +++ b/src/renderer/src/store/slices/agent-inventory/runtime-detected-agents.ts @@ -1,12 +1,18 @@ +import { + callRuntimeAgentDetection, + RuntimeAgentDetectionNeedsServerUpdateError, + type NestedSshAgentDetection +} from './runtime-agent-detection-request' +export { + callRuntimeAgentDetection, + RuntimeAgentDetectionNeedsServerUpdateError +} from './runtime-agent-detection-request' import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' -import { getRuntimeEnvironmentStatus } from '@/runtime/rpc/compatibility/runtime-compatibility-probe' -import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result' import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { captureRuntimeEnvironmentRequestRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import { PREFLIGHT_WORKSPACE_SCOPED_RUNTIME_CAPABILITY } from '../../../../../shared/preflight-runtime-capabilities' import { getRuntimeAgentInventoryEnvironmentId, getRuntimeAgentInventoryKey @@ -27,7 +33,8 @@ export type RuntimeDetectedAgentsSlice = { /** Refresh login-shell PATH; fall back to detectAgents only for servers predating refreshAgents. */ refreshRuntimeDetectedAgents: ( environmentId: string, - worktreeId?: string | null + worktreeId?: string | null, + options?: { userInitiated?: boolean } ) => Promise clearRuntimeDetectedAgents: (environmentId: string) => void /** Prune removed environments’ inventories via setRuntimeEnvironments. */ @@ -38,56 +45,12 @@ export type RuntimeDetectedAgentsSlice = { const runtimeDetectPromises = new Map>() const latestOutcome = new Map() const runtimeRefreshPromises = new Map>() +const explicitRefreshes = new WeakSet>() function isRuntimeMethodNotFoundError(error: unknown): boolean { return error instanceof RuntimeRpcCallError && error.code === 'method_not_found' } -export class RuntimeAgentDetectionNeedsServerUpdateError extends Error { - constructor() { - super("Update Orca on this server to list this workspace's agents.") - this.name = 'RuntimeAgentDetectionNeedsServerUpdateError' - } -} - -/** A paired host's workspace that lives on one of that host's own SSH targets. */ -type NestedSshAgentDetection = { - connectionId: string - call: (params: { connectionId: string }) => Promise -} - -/** Old hosts can supply workspace agents via host defaults only on known non-Windows platforms; host-default requests remain synchronous. */ -export function callRuntimeAgentDetection( - environmentId: string, - worktreeId: string | null | undefined, - call: (params: { worktreeId: string } | undefined) => Promise, - nestedSsh?: NestedSshAgentDetection -): Promise { - if (!worktreeId) { - return call(undefined) - } - const capability = PREFLIGHT_WORKSPACE_SCOPED_RUNTIME_CAPABILITY - return runtimeEnvironmentSupportsCapability(environmentId, capability).then(async (supported) => { - if (supported) { - return call({ worktreeId }) - } - // Why: a fresh status both reports the platform and catches an in-place upgrade. - const status = await getRuntimeEnvironmentStatus(environmentId) - if (status.capabilities?.includes(capability)) { - return call({ worktreeId }) - } - // Why: the host's SSH workspace runs on its SSH target, which old hosts already probe by id. - if (nestedSsh) { - return nestedSsh.call({ connectionId: nestedSsh.connectionId }) - } - // Why: an old Windows host's default omits a WSL workspace's agents; an absent platform may be one. - if (!status.hostPlatform || status.hostPlatform === 'win32') { - throw new RuntimeAgentDetectionNeedsServerUpdateError() - } - return call(undefined) - }) -} - type PairingFence = { expectedEnvironmentPairingRevision: number | undefined } // Why: captured before the capability wait, so a re-pair during it cannot retarget the probe. @@ -257,10 +220,14 @@ export const createRuntimeDetectedAgentsSlice: ( return pending }, - refreshRuntimeDetectedAgents: (environmentId: string, worktreeId?: string | null) => { + refreshRuntimeDetectedAgents: ( + environmentId: string, + worktreeId?: string | null, + options = {} + ) => { const key = getRuntimeAgentInventoryKey(environmentId, worktreeId) const inflight = runtimeRefreshPromises.get(key) - if (inflight) { + if (inflight && (!options.userInitiated || explicitRefreshes.has(inflight))) { return inflight } @@ -273,20 +240,35 @@ export const createRuntimeDetectedAgentsSlice: ( const target = { kind: 'environment', environmentId } as const const fence = capturePairingFence(environmentId) - const pending = callRuntimeAgentDetection( - environmentId, - worktreeId, - (params) => - callRuntimeRpc<{ agents: TuiAgent[] }>(target, 'preflight.refreshAgents', params, fence) - .then((result) => result.agents) - .catch((error) => { - if (!isRuntimeMethodNotFoundError(error)) { - throw error - } - // Fallback only for old servers; repeating disconnect/runtime failures just doubles remote work. - return callRuntimeRpc(target, 'preflight.detectAgents', params, fence) - }), - nestedSshDetection(target, worktreeId, fence) + const request = () => + callRuntimeAgentDetection( + environmentId, + worktreeId, + (params) => + callRuntimeRpc<{ agents: TuiAgent[] }>( + target, + 'preflight.refreshAgents', + options.userInitiated ? { ...params, userInitiated: true } : params, + fence + ) + .then((result) => result.agents) + .catch((error) => { + if (!isRuntimeMethodNotFoundError(error)) { + throw error + } + // Fallback only for old servers; repeating disconnect/runtime failures just doubles remote work. + return callRuntimeRpc(target, 'preflight.detectAgents', params, fence) + }), + nestedSshDetection(target, worktreeId, fence) + ) + const pending = ( + inflight + ? inflight.then(() => + runtimeRefreshPromises.get(key) === pending + ? request() + : (get().runtimeDetectedAgentIds[key] ?? []) + ) + : request() ) .then((typed) => { // Ignore refreshes detached by environment removal or re-pair. @@ -319,6 +301,9 @@ export const createRuntimeDetectedAgentsSlice: ( } }) + if (options.userInitiated) { + explicitRefreshes.add(pending) + } runtimeRefreshPromises.set(key, pending) return pending }, diff --git a/src/renderer/src/web/preload-api/web-host-capability-api.ts b/src/renderer/src/web/preload-api/web-host-capability-api.ts index 59dd32ca5a8..f796baf3f58 100644 --- a/src/renderer/src/web/preload-api/web-host-capability-api.ts +++ b/src/renderer/src/web/preload-api/web-host-capability-api.ts @@ -71,9 +71,9 @@ export function createPreflightApi(): NonNullable['preflight } return callRuntimeResult('preflight.detectAgents').catch(() => []) }, - refreshAgents: () => + refreshAgents: (args) => requireActiveEnvironmentOrNull() - ? callRuntimeResult('preflight.refreshAgents') + ? callRuntimeResult('preflight.refreshAgents', args) .then((result) => result as RefreshAgentsResult) .catch(() => fallbackRefreshAgents) : Promise.resolve(fallbackRefreshAgents), diff --git a/src/shared/agent-session/structured-agent-session-renderer-client-capabilities.ts b/src/shared/agent-session/structured-agent-session-renderer-client-capabilities.ts index 3c18f0a0f48..2a6ea47beb9 100644 --- a/src/shared/agent-session/structured-agent-session-renderer-client-capabilities.ts +++ b/src/shared/agent-session/structured-agent-session-renderer-client-capabilities.ts @@ -1,6 +1,7 @@ import { AGENT_SESSION_COMMANDS_ON_REQUEST_CAPABILITY, AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY, + AGENT_SESSION_MODEL_CATALOG_PROGRESS_CAPABILITY, PI_STRUCTURED_DIALOGS_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY } from './structured-agent-session-surface-capabilities' @@ -36,6 +37,7 @@ export const STRUCTURED_AGENT_SESSION_RENDERER_CLIENT_CAPABILITIES = [ AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY, AGENT_SESSION_OPTIONAL_MODEL_CLIENT_CAPABILITY, AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY, + AGENT_SESSION_MODEL_CATALOG_PROGRESS_CAPABILITY, AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY, // Read cursors settle acknowledged echoes even when snapshots omit their rows. AGENT_SESSION_SNAPSHOT_CATCH_UP_CLIENT_CAPABILITY, diff --git a/src/shared/agent-session/structured-agent-session-surface-capabilities.ts b/src/shared/agent-session/structured-agent-session-surface-capabilities.ts index c92854e44dc..68c58582555 100644 --- a/src/shared/agent-session/structured-agent-session-surface-capabilities.ts +++ b/src/shared/agent-session/structured-agent-session-surface-capabilities.ts @@ -44,6 +44,10 @@ export const STRUCTURED_AGENT_SESSION_RESUME_WRITER_ADMISSION_RUNTIME_CAPABILITY export const STRUCTURED_AGENT_SESSION_AVAILABILITY_RUNTIME_CAPABILITY = 'agent-session.structured.availability.v1' as const +// Progress-aware readers renew on listingInProgress before their wait expires. +export const AGENT_SESSION_MODEL_CATALOG_PROGRESS_CAPABILITY = + 'agent-session.model-catalog.progress.v1' as const + export const AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY = 'agent-session.coherent-model-catalog.v1' as const diff --git a/src/shared/agent-status/process/agent-command-line-entrypoint.ts b/src/shared/agent-status/process/agent-command-line-entrypoint.ts index 3d2d9796e67..bd5d7035cd7 100644 --- a/src/shared/agent-status/process/agent-command-line-entrypoint.ts +++ b/src/shared/agent-status/process/agent-command-line-entrypoint.ts @@ -1,4 +1,5 @@ /** Resolve the entrypoint within interpreter argv separately from recognizing which agent it names. */ +import { NODE_INTERPRETER_OPTIONS_WITH_VALUE } from '../../node-interpreter-options' const PROCESS_EXTENSION_RE = /\.(?:exe|cmd|bat|ps1)$/i @@ -16,13 +17,6 @@ const STATIC_INTERPRETER_PROCESS_NAMES = new Set([ export const PYTHON_PROCESS_RE = /^python(?:\d+(?:\.\d+)*)?$/ -const INTERPRETER_OPTIONS_WITH_VALUE = new Set([ - '-r', - '--require', - '--import', - '--loader', - '--experimental-loader' -]) const INTERPRETER_OPTIONS_WITH_INLINE_SOURCE = new Set(['-e', '--eval', '-p', '--print', '--check']) export function isInterpreterProcessName(normalized: string): boolean { @@ -102,7 +96,7 @@ export function findInterpreterEntrypointToken( if (INTERPRETER_OPTIONS_WITH_INLINE_SOURCE.has(name)) { return null } - if (INTERPRETER_OPTIONS_WITH_VALUE.has(name) && name === token) { + if (NODE_INTERPRETER_OPTIONS_WITH_VALUE.has(name) && name === token) { index += 1 } continue diff --git a/src/shared/node-interpreter-options.ts b/src/shared/node-interpreter-options.ts new file mode 100644 index 00000000000..a252abf7200 --- /dev/null +++ b/src/shared/node-interpreter-options.ts @@ -0,0 +1,7 @@ +export const NODE_INTERPRETER_OPTIONS_WITH_VALUE: ReadonlySet = new Set([ + '-r', + '--require', + '--import', + '--loader', + '--experimental-loader' +]) diff --git a/src/shared/rpc-contract/preflight/preflight-params.ts b/src/shared/rpc-contract/preflight/preflight-params.ts index 4d308844093..2d8ad66dadd 100644 --- a/src/shared/rpc-contract/preflight/preflight-params.ts +++ b/src/shared/rpc-contract/preflight/preflight-params.ts @@ -37,6 +37,10 @@ export const PreflightAgentDetection = z } }) +export const PreflightAgentRefresh = PreflightAgentDetection.safeExtend({ + userInitiated: z.boolean().optional() +}) + export const PreflightProjectAgentDetection = PreflightAgentDetection.safeExtend({ project: RepoSelector.extend({ repo: RepoSelector.shape.repo.pipe(z.string().max(4096)) }) .strict() diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index e9dd57239ae..cc64774f151 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -516,7 +516,7 @@ import { PluginsPanelActionParams } from './plugins/plugins-params' import { - PreflightAgentDetection, + PreflightAgentRefresh, PreflightCheck, PreflightDetectRemoteAgents, PreflightDetectRemoteWindowsTerminalCapabilities, @@ -1479,7 +1479,7 @@ export const RPC_PARAMS_BY_METHOD = { 'preflight.detectRemoteAgents': PreflightDetectRemoteAgents, 'preflight.detectRemoteWindowsTerminalCapabilities': PreflightDetectRemoteWindowsTerminalCapabilities, - 'preflight.refreshAgents': PreflightAgentDetection, + 'preflight.refreshAgents': PreflightAgentRefresh, 'project.list': null, 'project.update': ProjectUpdate, 'projectGroup.checkHooks': ProjectGroupHooksCheck, From 235d4468730f35f7b8170537a0a44b209728e6c1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:37:49 -0800 Subject: [PATCH 10/52] perf(codex): derive mirror section headers once per document (#42190) --- .../settings/codex-config-mirror-merge.ts | 20 ++--- .../config-toml-runtime-owned-sections.ts | 78 +++++++++++-------- 2 files changed, 55 insertions(+), 43 deletions(-) diff --git a/src/main/codex/configuration/settings/codex-config-mirror-merge.ts b/src/main/codex/configuration/settings/codex-config-mirror-merge.ts index 1cd49e1803e..dbdac8c309b 100644 --- a/src/main/codex/configuration/settings/codex-config-mirror-merge.ts +++ b/src/main/codex/configuration/settings/codex-config-mirror-merge.ts @@ -24,22 +24,22 @@ export function mergeSystemCodexConfigIntoRuntime( const runtimeSections = deduplicateProjectTomlSections(getTomlSections(runtimeConfig)) const runtimeProjectHeaders = new Set( runtimeSections - .filter((section) => isRuntimeProjectTomlSection(section.header)) - .map((section) => getTomlSectionHeaderKey(section.header)) + .filter((section) => isRuntimeProjectTomlSection(section)) + .map((section) => getTomlSectionHeaderKey(section)) ) const systemProjectSections = deduplicateProjectTomlSections( getTomlSections(systemConfig) - ).filter((section) => isRuntimeProjectTomlSection(section.header)) + ).filter((section) => isRuntimeProjectTomlSection(section)) const systemUntrustedProjectHeaders = new Set( systemProjectSections .filter((section) => getProjectTrustLevel(section.block) === 'untrusted') - .map((section) => getRevocationTomlSectionHeaderKey(section.header)) + .map((section) => getRevocationTomlSectionHeaderKey(section)) ) // Exact-cased re-grants must override legacy case-drifted revocations or each mirror reverts trust. const systemTrustedProjectHeaders = new Set( systemProjectSections .filter((section) => getProjectTrustLevel(section.block) === 'trusted') - .map((section) => getTomlSectionHeaderKey(section.header)) + .map((section) => getTomlSectionHeaderKey(section)) ) const systemMcpServers = readMcpServerTomlOwnership(systemConfig) // Mirror ordinary settings while retaining runtime trust, subject to explicit system project revocations. @@ -50,10 +50,10 @@ export function mergeSystemCodexConfigIntoRuntime( }), ...runtimeSections .filter((section) => { - if (isRuntimePreservedTomlSection(section.header)) { + if (isRuntimePreservedTomlSection(section)) { return true } - const mcpServerName = getMcpServerTomlSectionName(section.header) + const mcpServerName = getMcpServerTomlSectionName(section) return ( mcpServerName !== null && !systemMcpServers.ownsRoot && @@ -64,9 +64,9 @@ export function mergeSystemCodexConfigIntoRuntime( }) .filter( (section) => - !isRuntimeProjectTomlSection(section.header) || - !systemUntrustedProjectHeaders.has(getRevocationTomlSectionHeaderKey(section.header)) || - systemTrustedProjectHeaders.has(getTomlSectionHeaderKey(section.header)) + !isRuntimeProjectTomlSection(section) || + !systemUntrustedProjectHeaders.has(getRevocationTomlSectionHeaderKey(section)) || + systemTrustedProjectHeaders.has(getTomlSectionHeaderKey(section)) ) .map((section) => section.block) ]) diff --git a/src/main/codex/configuration/toml/config-toml-runtime-owned-sections.ts b/src/main/codex/configuration/toml/config-toml-runtime-owned-sections.ts index bb1e4777070..9549b4187d4 100644 --- a/src/main/codex/configuration/toml/config-toml-runtime-owned-sections.ts +++ b/src/main/codex/configuration/toml/config-toml-runtime-owned-sections.ts @@ -5,13 +5,9 @@ import { isTomlStructuralLine, updateTomlLineScanState } from './config-toml-line-scan' -import { parseTomlTableHeaderPath } from './config-toml-key-path' +import { parseTomlTableHeaderPath, type ParsedTomlTableHeaderPath } from './config-toml-key-path' import { findProjectTrustLevelEntries } from '../../trust/toml/config-toml-project-trust-level' -import { - CODEX_HOOK_TRUST_KEY, - parseHookStateTomlHeaderKey, - parseProjectTomlHeaderPath as parseCodexProjectHeaderPath -} from './config-toml-syntax' +import { CODEX_HOOK_TRUST_KEY } from './config-toml-syntax' import '../../trust/toml/config-toml-trust' import { codexTrustSourcePathsEqual as codexHookSourcePathsEqual, @@ -24,6 +20,7 @@ export type TomlSection = { header: string block: string start: number + table: ParsedTomlTableHeaderPath | null } export type SharedHookTrustCarry = { @@ -48,14 +45,14 @@ export function stripRuntimeOwnedTomlSections( ...sections .filter( (section) => - !isRuntimeHookTrustTomlSection(section.header) || + !isRuntimeHookTrustTomlSection(section) || (sharedHookTrust !== undefined && - claimSharedHookTrustSection(section.header, sharedHookTrust, carriedHookTrustKeys)) + claimSharedHookTrustSection(section, sharedHookTrust, carriedHookTrustKeys)) ) .filter( (section) => - !isRuntimeProjectTomlSection(section.header) || - !runtimeProjectHeaders.has(getTomlSectionHeaderKey(section.header)) || + !isRuntimeProjectTomlSection(section) || + !runtimeProjectHeaders.has(getTomlSectionHeaderKey(section)) || getProjectTrustLevel(section.block) === 'untrusted' ) .map((section) => section.block) @@ -80,7 +77,8 @@ export function getTomlSections(config: string): TomlSection[] { sections.push({ header: sectionHeader ?? '', block: lines.slice(sectionStart, index).join('\n'), - start: sectionStart + start: sectionStart, + table: parseTomlTableHeaderPath(sectionHeader ?? '') }) } sectionStart = index @@ -92,18 +90,19 @@ export function getTomlSections(config: string): TomlSection[] { sections.push({ header: sectionHeader ?? '', block: lines.slice(sectionStart).join('\n'), - start: sectionStart + start: sectionStart, + table: parseTomlTableHeaderPath(sectionHeader ?? '') }) } return sections } -export function isRuntimePreservedTomlSection(header: string): boolean { - return isRuntimeHookTrustTomlSection(header) || isRuntimeProjectTomlSection(header) +export function isRuntimePreservedTomlSection(section: TomlSection): boolean { + return isRuntimeHookTrustTomlSection(section) || isRuntimeProjectTomlSection(section) } -export function isRuntimeHookTrustTomlSection(header: string): boolean { - const table = parseTomlTableHeaderPath(header) +export function isRuntimeHookTrustTomlSection(section: TomlSection): boolean { + const table = section.table // Preserve the hooks.state parent Codex materializes on Windows, including quoted spellings. return !!table && !table.isArray && table.segments[0] === 'hooks' && table.segments[1] === 'state' } @@ -128,7 +127,7 @@ export function classifyHookTrustKey(key: string, homeDir: string): 'home-scoped export function getHookTrustTomlSectionKeys(sections: readonly TomlSection[]): Set { const keys = new Set() for (const section of sections) { - const key = parseHookStateTomlHeaderKey(section.header) + const key = sectionLeafKey(section, ['hooks', 'state']) if (key !== null) { keys.add(key) } @@ -138,11 +137,11 @@ export function getHookTrustTomlSectionKeys(sections: readonly TomlSection[]): S // Runtime trust wins; compare exact keys to retain required Windows separator variants. function claimSharedHookTrustSection( - header: string, + section: TomlSection, { systemHomeDir }: SharedHookTrustCarry, claimedKeys: Set ): boolean { - const key = parseHookStateTomlHeaderKey(header) + const key = sectionLeafKey(section, ['hooks', 'state']) if (key === null || classifyHookTrustKey(key, systemHomeDir) === 'home-scoped') { return false } @@ -153,32 +152,45 @@ function claimSharedHookTrustSection( return true } -export function isRuntimeProjectTomlSection(header: string): boolean { - return parseCodexProjectHeaderPath(header) !== null +function sectionLeafKey(section: TomlSection, parent: readonly string[]): string | null { + const table = section.table + if ( + !table || + table.isArray || + table.segments.length !== parent.length + 1 || + parent.some((segment, index) => table.segments[index] !== segment) + ) { + return null + } + return table.segments.at(-1) ?? null +} + +export function isRuntimeProjectTomlSection(section: TomlSection): boolean { + return sectionLeafKey(section, ['projects']) !== null } const CODEX_MCP_SERVER_TABLE_ROOT = 'mcp_servers' -export function getMcpServerTomlSectionName(header: string): string | null { - const table = parseTomlTableHeaderPath(header) +export function getMcpServerTomlSectionName(section: TomlSection): string | null { + const table = section.table if (!table || table.isArray || table.segments[0] !== CODEX_MCP_SERVER_TABLE_ROOT) { return null } return table.segments[1] ?? null } -export function getTomlSectionHeaderKey(header: string): string { - const projectPath = parseCodexProjectHeaderPath(header) +export function getTomlSectionHeaderKey(section: TomlSection): string { + const projectPath = sectionLeafKey(section, ['projects']) return projectPath === null - ? header.trim() + ? section.header.trim() : `project:${normalizeCodexProjectPathForLookup(projectPath)}` } // Match legacy WSL revocations loosely so case drift cannot restore trust. -export function getRevocationTomlSectionHeaderKey(header: string): string { - const projectPath = parseCodexProjectHeaderPath(header) +export function getRevocationTomlSectionHeaderKey(section: TomlSection): string { + const projectPath = sectionLeafKey(section, ['projects']) return projectPath === null - ? header.trim() + ? section.header.trim() : `project:${normalizeCodexProjectPathForRevocationLookup(projectPath)}` } @@ -187,11 +199,11 @@ export function deduplicateProjectTomlSections(sections: TomlSection[]): TomlSec const deduplicated: TomlSection[] = [] const projectIndexes = new Map() for (const section of sections) { - if (!isRuntimeProjectTomlSection(section.header)) { + if (!isRuntimeProjectTomlSection(section)) { deduplicated.push(section) continue } - const key = getTomlSectionHeaderKey(section.header) + const key = getTomlSectionHeaderKey(section) const existingIndex = projectIndexes.get(key) if (existingIndex === undefined) { projectIndexes.set(key, deduplicated.length) @@ -225,8 +237,8 @@ export function extractOrdinaryCodexSettings(config: string): string { const sections = deduplicateProjectTomlSections(getTomlSections(config)) const projectHeaders = new Set( sections - .filter((section) => isRuntimeProjectTomlSection(section.header)) - .map((section) => getTomlSectionHeaderKey(section.header)) + .filter((section) => isRuntimeProjectTomlSection(section)) + .map((section) => getTomlSectionHeaderKey(section)) ) // The daemon override belongs to the managed home and must not be promoted. return stripCodexDaemonOverride(stripRuntimeOwnedTomlSections(config, projectHeaders)).trimEnd() From 746b031870eb3bfb84214ea471f5e119bbc5a428 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:44:02 +0000 Subject: [PATCH 11/52] fix(terminal): keep the user's focus when an agent splits a terminal (#42204) --- .../events/runtime-notifier-contract.ts | 2 + .../runtime/terminal/launch/terminal-split.ts | 3 +- src/main/window/runtime-window-lifecycle.ts | 3 +- .../ui-bridge-terminal-and-session-tabs.ts | 2 + .../api/window-ui/ui-command-event-api.ts | 1 + .../mounting/terminal-pane-mount-events.ts | 3 +- src/renderer/src/constants/terminal.ts | 2 + .../ipc-events/app-lifetime-ipc-bridge.ts | 2 + .../terminal-presentation-ipc-bridge.ts | 29 +---- .../terminal-presentation-split-focus.test.ts | 105 ++++++++++++++++++ .../terminal-tab-mount-ipc-bridge.ts | 31 ++++++ .../terminal-ui-routing-ipc-bridge.ts | 3 +- .../pane-layout/pane-split-close.ts | 29 ++++- .../pane-layout/pane-subtree-split.ts | 2 + .../pane-manager-split-focus.test.ts | 49 ++++++++ .../pane-manager-tree-mutations.ts | 2 + .../lib/pane-manager/pane-manager-types.ts | 2 + 17 files changed, 234 insertions(+), 36 deletions(-) create mode 100644 src/renderer/src/hooks/ipc-events/terminal-presentation-split-focus.test.ts create mode 100644 src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts create mode 100644 src/renderer/src/lib/pane-manager/pane-manager-split-focus.test.ts diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index 299078fa642..b92d0e77789 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -131,6 +131,8 @@ export type RuntimeNotifier = { sourceLeafId?: string telemetrySource?: TerminalPaneSplitSource newLeafId?: string + /** An agent's split: the new pane leaves the user's active pane and keyboard focus alone. */ + activate?: false } ): void /** `recordInteraction: false` marks a title the host applied, not one the user typed. */ diff --git a/src/main/runtime/terminal/launch/terminal-split.ts b/src/main/runtime/terminal/launch/terminal-split.ts index 328ddfe7b8e..1a82cd4ae3e 100644 --- a/src/main/runtime/terminal/launch/terminal-split.ts +++ b/src/main/runtime/terminal/launch/terminal-split.ts @@ -101,7 +101,8 @@ export abstract class OrcaRuntimeWithSplitTerminal extends OrcaRuntimeWithStopEx worktreeId: leaf.worktreeId, sourceLeafId: leaf.leafId, telemetrySource: opts.telemetrySource, - newLeafId + newLeafId, + ...(opts.activate === false ? { activate: false } : {}) }) return await this.awaitRendererSplit(split, newLeafId) } diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index f1bc293bfc6..478145e006f 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -176,7 +176,8 @@ export function registerRuntimeWindowLifecycle( worktreeId: opts.worktreeId, sourceLeafId: opts.sourceLeafId, telemetrySource: opts.telemetrySource, - newLeafId: opts.newLeafId + newLeafId: opts.newLeafId, + ...(opts.activate === false ? { activate: false } : {}) }) }, renameTerminal: (tabId, title, options) => diff --git a/src/preload/api/window-ui/ui-bridge-terminal-and-session-tabs.ts b/src/preload/api/window-ui/ui-bridge-terminal-and-session-tabs.ts index 11f75d66557..fa57dcf5c79 100644 --- a/src/preload/api/window-ui/ui-bridge-terminal-and-session-tabs.ts +++ b/src/preload/api/window-ui/ui-bridge-terminal-and-session-tabs.ts @@ -158,6 +158,7 @@ export const uiTerminalAndSessionTabsApi = { sourceLeafId?: string telemetrySource?: TerminalPaneSplitSource newLeafId?: string + activate?: false }) => void ): (() => void) => { const listener = ( @@ -171,6 +172,7 @@ export const uiTerminalAndSessionTabsApi = { sourceLeafId?: string telemetrySource?: TerminalPaneSplitSource newLeafId?: string + activate?: false } ) => callback(data) ipcRenderer.on('ui:splitTerminal', listener) diff --git a/src/preload/api/window-ui/ui-command-event-api.ts b/src/preload/api/window-ui/ui-command-event-api.ts index a39ca774733..d509efd2ef1 100644 --- a/src/preload/api/window-ui/ui-command-event-api.ts +++ b/src/preload/api/window-ui/ui-command-event-api.ts @@ -240,6 +240,7 @@ export type UiCommandEventApi = { sourceLeafId?: string telemetrySource?: TerminalPaneSplitSource newLeafId?: string + activate?: false }) => void ) => () => void onRenameTerminal: ( diff --git a/src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-events.ts b/src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-events.ts index eb6f008f232..fd5d6f5bc69 100644 --- a/src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-events.ts +++ b/src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-events.ts @@ -76,7 +76,8 @@ export function installTerminalPaneMountEvents(args: { } const splitOptions = { ...(detail.newLeafId ? { leafId: detail.newLeafId } : {}), - ...(detail.ptyId ? { ptyId: detail.ptyId } : {}) + ...(detail.ptyId ? { ptyId: detail.ptyId } : {}), + ...(detail.activate === false ? { activate: false } : {}) } if (detail.command) { const createdPane = splitPaneWithOneShotStartup(ptyDeps, { command: detail.command }, () => diff --git a/src/renderer/src/constants/terminal.ts b/src/renderer/src/constants/terminal.ts index 98b69d068fb..8dde47fee8b 100644 --- a/src/renderer/src/constants/terminal.ts +++ b/src/renderer/src/constants/terminal.ts @@ -48,6 +48,8 @@ export type SplitTerminalPaneDetail = { telemetrySource?: TerminalPaneSplitSource newLeafId?: string ptyId?: string + /** An agent's split: the new pane leaves the user's active pane and keyboard focus alone. */ + activate?: false } export type RequestActiveTerminalPaneSplitDetail = { diff --git a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts index cba150db317..d5d16ff31fa 100644 --- a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts @@ -35,6 +35,7 @@ import { registerSettingsAndSidebarIpcBridge } from './settings-sidebar-ipc-brid import { registerQuitAndStopAllSessionsIpcBridge } from './quit-and-stop-all-sessions-ipc-bridge' import { registerTabLifecycleIpcBridge } from './tab-lifecycle-ipc-bridge' import { registerTerminalPresentationIpcBridge } from './terminal-presentation-ipc-bridge' +import { registerTerminalTabMountIpcBridge } from './terminal-tab-mount-ipc-bridge' import { registerPtySourceDisownedIpcBridge } from './pty-source-disowned-ipc-bridge' import { registerTerminalRequestIpcBridge } from './terminal-request-ipc-bridge' import { registerAgentLaunchTabIpcBridge } from './agent-launch-tab-ipc-bridge' @@ -133,6 +134,7 @@ export function installAppLifetimeIpcEvents(): () => void { ) registerTerminalPresentationIpcBridge(unsubs) + registerTerminalTabMountIpcBridge(unsubs) registerTerminalRequestIpcBridge(unsubs) registerAgentLaunchTabIpcBridge(unsubs) registerPtySourceDisownedIpcBridge(unsubs) diff --git a/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts index 1135e643686..61fbdd112c7 100644 --- a/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts @@ -1,7 +1,6 @@ import { presentAgentLaunchTab } from '@/lib/agent-session/launch/pane/agent-launch-tab-presentation' import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' import { hasRegisteredRuntimeTerminalTab } from '@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry' -import { planMobileTerminalTabMount } from '@/components/terminal-pane/mounting/mobile-terminal-tab-mount' import { resolveTerminalTabPtyOwnership } from '@/lib/workspace/tabs/terminal-tab-for-pty-id' import { dispatchTerminalPaneSplitRequest, @@ -202,7 +201,8 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v sourcePtyId: existingLayout?.ptyIdsByLeafId?.[splitFromLeafId], telemetrySource: splitTelemetrySource, newLeafId: leafId, - ptyId + ptyId, + ...(shouldActivate ? {} : { activate: false }) } const targetMounted = hasRegisteredRuntimeTerminalTab(tab.id, worktreeId) if (!targetMounted) { @@ -289,30 +289,5 @@ export function registerTerminalPresentationIpcBridge(unsubs: (() => void)[]): v ) ) - // Why: background-mount a mobile-subscribed tab's PTY without navigating the desktop (STA-1840). - unsubs.push( - window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => { - if (!worktreeId) { - return - } - // Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree. - const mount = planMobileTerminalTabMount( - useAppStore.getState(), - { - worktreeId, - ...(tabId ? { tabId } : {}), - ...(ptyId ? { ptyId } : {}) - }, - { - isTabMounted: (tabId, targetWorktreeId) => - hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId) - } - ) - if (mount) { - requestBackgroundTerminalWorktreeMount(mount) - } - }) - ) - // Why: CLI-driven terminal creation waits for the tabId reply so it can hand the caller a usable handle immediately. } diff --git a/src/renderer/src/hooks/ipc-events/terminal-presentation-split-focus.test.ts b/src/renderer/src/hooks/ipc-events/terminal-presentation-split-focus.test.ts new file mode 100644 index 00000000000..f8ddb73b8cf --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/terminal-presentation-split-focus.test.ts @@ -0,0 +1,105 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createTestStore, seedStore } from '../../store/testing/app-store-test-fixture' +import { makeTab } from '../../store/terminals/testing/terminal-tab.test-fixture' +import { makeWorktree } from '../../store/slices/worktrees/worktree.test-fixture' +import { createStoreSessionMockApi } from '../../store/testing/app-store-session-api.test-fixture' + +const mocks = vi.hoisted(() => { + const store: { current: ReturnType | null } = { current: null } + return { store, dispatchSplit: vi.fn() } +}) + +vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) +vi.mock('../../store', () => ({ + useAppStore: { + getState: () => mocks.store.current!.getState(), + setState: (...args: Parameters['setState']>) => + mocks.store.current!.setState(...args), + subscribe: () => () => {} + } +})) +vi.mock( + '@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry', + async (importOriginal) => ({ + ...(await importOriginal()), + hasRegisteredRuntimeTerminalTab: () => true + }) +) +vi.mock('@/components/terminal-pane/layout/split/terminal-pane-split-request-routing', () => ({ + dispatchTerminalPaneSplitRequest: mocks.dispatchSplit, + queueTerminalPaneSplitRequest: vi.fn() +})) +vi.mock('@/components/terminal-pane/input/focus/focus-terminal-tab-surface', () => ({ + focusTerminalTabSurface: vi.fn() +})) + +import { registerTerminalPresentationIpcBridge } from './terminal-presentation-ipc-bridge' + +const WORKTREE = 'repo1::/repo1/main' +const TAB = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const SOURCE_LEAF = '11111111-1111-4111-8111-111111111111' +const NEW_LEAF = '22222222-2222-4222-8222-222222222222' + +type Listener = (payload: Record) => void + +function revealBackgroundSplit(): void { + const listeners = new Map() + const ui = new Proxy( + {}, + { + get: (_target, name) => + typeof name === 'string' && name.startsWith('on') + ? (listener: Listener) => { + listeners.set(name, listener) + return () => {} + } + : vi.fn() + } + ) + vi.stubGlobal('window', { dispatchEvent: vi.fn(), api: { ...createStoreSessionMockApi(), ui } }) + const store = createTestStore() + mocks.store.current = store + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: WORKTREE, repoId: 'repo1', path: '/repo1/main' })] + }, + tabsByWorktree: { + [WORKTREE]: [makeTab({ id: TAB, worktreeId: WORKTREE, ptyId: 'pty-1' })] + }, + terminalLayoutsByTabId: { + [TAB]: { + root: { type: 'leaf', leafId: SOURCE_LEAF }, + activeLeafId: SOURCE_LEAF, + expandedLeafId: null, + ptyIdsByLeafId: { [SOURCE_LEAF]: 'pty-1' } + } + } + }) + registerTerminalPresentationIpcBridge([]) + listeners.get('onCreateTerminal')?.({ + worktreeId: WORKTREE, + ptyId: 'pty-2', + tabId: TAB, + leafId: NEW_LEAF, + splitFromLeafId: SOURCE_LEAF, + splitDirection: 'vertical', + activate: false, + presentation: 'background' + }) +} + +beforeEach(() => { + vi.unstubAllGlobals() + mocks.dispatchSplit.mockReset() +}) + +describe('a runtime split revealed in the window', () => { + it('asks the pane not to take focus when the split is in the background', () => { + revealBackgroundSplit() + + expect(mocks.dispatchSplit).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ newLeafId: NEW_LEAF, activate: false }) + ) + }) +}) diff --git a/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts new file mode 100644 index 00000000000..11d6c5d8de4 --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/terminal-tab-mount-ipc-bridge.ts @@ -0,0 +1,31 @@ +import { requestBackgroundTerminalWorktreeMount } from '@/components/terminal/background-terminal-worktree-mount' +import { hasRegisteredRuntimeTerminalTab } from '@/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry' +import { planMobileTerminalTabMount } from '@/components/terminal-pane/mounting/mobile-terminal-tab-mount' +import { useAppStore } from '../../store/index' + +export function registerTerminalTabMountIpcBridge(unsubs: (() => void)[]): void { + // Why: background-mount a mobile-subscribed tab's PTY without navigating the desktop (STA-1840). + unsubs.push( + window.api.ui.onRequestTerminalTabMount(({ worktreeId, tabId, ptyId }) => { + if (!worktreeId) { + return + } + // Why: synthetic pty handles need persisted-tab resolution; a miss must not mount every saved tab in a hidden worktree. + const mount = planMobileTerminalTabMount( + useAppStore.getState(), + { + worktreeId, + ...(tabId ? { tabId } : {}), + ...(ptyId ? { ptyId } : {}) + }, + { + isTabMounted: (tabId, targetWorktreeId) => + hasRegisteredRuntimeTerminalTab(tabId, targetWorktreeId) + } + ) + if (mount) { + requestBackgroundTerminalWorktreeMount(mount) + } + }) + ) +} diff --git a/src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge.ts index 9b723b2ae41..9a71d58341d 100644 --- a/src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge.ts @@ -120,7 +120,8 @@ export function routeRuntimeTerminalSplitRequest(request: RuntimeTerminalSplitRe command: request.command, sourceLeafId: request.sourceLeafId, telemetrySource: request.telemetrySource, - newLeafId: request.newLeafId + newLeafId: request.newLeafId, + ...(request.activate === false ? { activate: false } : {}) } if (hasRegisteredRuntimeTerminalTab(request.tabId, worktreeId)) { dispatchTerminalPaneSplitRequest(detail) diff --git a/src/renderer/src/lib/pane-manager/pane-layout/pane-split-close.ts b/src/renderer/src/lib/pane-manager/pane-layout/pane-split-close.ts index 71d262c8f6e..59f715d2850 100644 --- a/src/renderer/src/lib/pane-manager/pane-layout/pane-split-close.ts +++ b/src/renderer/src/lib/pane-manager/pane-layout/pane-split-close.ts @@ -47,6 +47,7 @@ type SplitManagedPaneArgs = { spawnHints?: Parameters>[1] ) => void getDragCallbacks: () => DragReorderCallbacks + activePaneId: number | null setActivePaneId: (paneId: number | null) => void isDestroyed: () => boolean } @@ -66,13 +67,24 @@ export function splitManagedPane(args: SplitManagedPaneArgs): ManagedPane | null const divider = args.createDivider(isVertical) const movedPaneStates = prepareMovedPanesForSplit(existingContainer, existing, args.panes) + const activate = args.opts?.activate !== false + const focusedBefore = activate ? null : document.activeElement wrapInSplit(existingContainer, newPane.container, isVertical, divider, { ratio: args.opts?.ratio, newPaneFirst: args.newPaneFirst }) - args.setActivePaneId(newPane.id) - openSplitPane(args, newPane, existing.leafId, args.opts?.cwd) + if (activate) { + args.setActivePaneId(newPane.id) + } else if ( + focusedBefore instanceof HTMLElement && + focusedBefore.isConnected && + document.activeElement !== focusedBefore + ) { + // Reparenting the source pane drops its focus; give the user's keyboard back. + focusedBefore.focus({ preventScroll: true }) + } + openSplitPane(args, newPane, existing.leafId, activate) for (const movedPaneState of movedPaneStates) { scheduleSplitScrollRestore( @@ -143,15 +155,22 @@ function openSplitPane( args: SplitManagedPaneArgs, newPane: ManagedPaneInternal, parentLeafId: string, - cwd?: string + activate: boolean ): void { + const cwd = args.opts?.cwd openTerminal(newPane, { ligatures: args.managerOptions.terminalLigaturesEnabled?.(), inlineImages: args.managerOptions.terminalInlineImagesEnabled?.() }) - applyPaneOpacity(args.panes.values(), newPane.id, args.styleOptions) + applyPaneOpacity( + args.panes.values(), + activate ? newPane.id : args.activePaneId, + args.styleOptions + ) applyDividerStyles(args.root, args.styleOptions) - newPane.terminal.focus() + if (activate) { + newPane.terminal.focus() + } updateMultiPaneState(args.getDragCallbacks()) // Forward creation hints to inherit local cwd or adopt the runtime-spawned PTY in web splits. args.publishPaneCreated(newPane, { diff --git a/src/renderer/src/lib/pane-manager/pane-layout/pane-subtree-split.ts b/src/renderer/src/lib/pane-manager/pane-layout/pane-subtree-split.ts index d71ae6a77c9..7697d52b049 100644 --- a/src/renderer/src/lib/pane-manager/pane-layout/pane-subtree-split.ts +++ b/src/renderer/src/lib/pane-manager/pane-layout/pane-subtree-split.ts @@ -33,6 +33,7 @@ type SplitPaneAroundLeafIdsArgs = { spawnHints?: Parameters>[1] ) => void getDragCallbacks: () => DragReorderCallbacks + activePaneId: number | null setActivePaneId: (paneId: number | null) => void isDestroyed: () => boolean } @@ -61,6 +62,7 @@ export function splitPaneAroundMountedSubtree( createDivider: args.createDivider, publishPaneCreated: args.publishPaneCreated, getDragCallbacks: args.getDragCallbacks, + activePaneId: args.activePaneId, setActivePaneId: args.setActivePaneId, isDestroyed: args.isDestroyed }) diff --git a/src/renderer/src/lib/pane-manager/pane-manager-split-focus.test.ts b/src/renderer/src/lib/pane-manager/pane-manager-split-focus.test.ts new file mode 100644 index 00000000000..b4881ae83d9 --- /dev/null +++ b/src/renderer/src/lib/pane-manager/pane-manager-split-focus.test.ts @@ -0,0 +1,49 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { Terminal } from '@xterm/xterm' + +// Why: happy-dom has no canvas, so xterm cannot open; focus is what this checks. +vi.mock('./pane-lifecycle', async (importOriginal) => { + const actual: object = await importOriginal() + return { ...actual, openTerminal: vi.fn() } +}) + +const { PaneManager } = await import('./pane-manager') + +const LEAF_A = '11111111-1111-4111-8111-111111111111' +const LEAF_B = '22222222-2222-4222-8222-222222222222' + +describe('PaneManager split focus', () => { + let root: HTMLDivElement + let manager: InstanceType + + beforeEach(() => { + vi.stubGlobal('requestAnimationFrame', () => 1) + vi.stubGlobal('cancelAnimationFrame', () => {}) + root = document.createElement('div') + document.body.appendChild(root) + manager = new PaneManager(root, { linkOpenHint: () => '' }) + }) + + afterEach(() => { + manager.destroy() + root.remove() + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('leaves the active pane and keyboard focus alone for a split that must not activate', () => { + const source = manager.createInitialPane({ leafId: LEAF_A, focus: false }) + // Stands in for xterm's input, which the split reparents along with its pane. + const input = source.container.appendChild(document.createElement('textarea')) + input.focus() + const focus = vi.spyOn(Terminal.prototype, 'focus') + + const created = manager.splitPane(source.id, 'vertical', { leafId: LEAF_B, activate: false }) + + expect(created?.leafId).toBe(LEAF_B) + expect(manager.getActivePane()?.leafId).toBe(LEAF_A) + expect(focus).not.toHaveBeenCalled() + expect(document.activeElement).toBe(input) + }) +}) diff --git a/src/renderer/src/lib/pane-manager/pane-manager-tree-mutations.ts b/src/renderer/src/lib/pane-manager/pane-manager-tree-mutations.ts index 3193f622ae0..79001dc12f6 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-tree-mutations.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-tree-mutations.ts @@ -27,6 +27,7 @@ export function splitPaneOnManager( createDivider: (isVertical) => host.createDivider(isVertical), publishPaneCreated: (pane, spawnHints) => host.publishPaneCreated(pane, spawnHints), getDragCallbacks: () => host.getDragCallbacks(), + activePaneId: host.getActivePaneId(), setActivePaneId: (id) => { host.setActivePaneId(id) }, @@ -55,6 +56,7 @@ export function splitPaneAroundLeafIdsOnManager( createDivider: (isVertical) => host.createDivider(isVertical), publishPaneCreated: (pane, spawnHints) => host.publishPaneCreated(pane, spawnHints), getDragCallbacks: () => host.getDragCallbacks(), + activePaneId: host.getActivePaneId(), setActivePaneId: (id) => { host.setActivePaneId(id) }, diff --git a/src/renderer/src/lib/pane-manager/pane-manager-types.ts b/src/renderer/src/lib/pane-manager/pane-manager-types.ts index 04922abb8fa..54b6b1aca1a 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-types.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-types.ts @@ -27,6 +27,8 @@ export type PaneSpawnHints = { export type PaneSplitOptions = Omit & { ratio?: number leafId?: string + /** False for a split the user did not ask for: the active pane and keyboard focus stay put. */ + activate?: boolean } export type ClosedPaneInfo = { From a376f8fbe370f7373faa4df5848f8883f52c4a98 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:51:45 +0000 Subject: [PATCH 12/52] fix(cli): keep orca open and computer permissions from taking the foreground (#42166) * fix(cli): keep Orca in the background when orca open launches it * docs(cli): say orca open leaves the foreground alone * fix(cli): ask a running Orca to open its window in the background * fix(main): keep background reveals inactive on Linux maximize and drop the flag on admin restart * fix(cli): narrow the open status before returning it * fix(main): keep focus-existing-window free of main-window contracts for the web typecheck * fix(cli): cap the open window request at five seconds --- docs/site/content/docs/cli/reference.mdx | 2 + src/cli/computer/computer.ts | 3 +- src/cli/runtime/client.ts | 9 ++- src/cli/runtime/launch.ts | 18 +++-- src/cli/runtime/open-local-orca.test.ts | 71 ++++++++++++++++++ src/cli/runtime/open-local-orca.ts | 29 ++++++- src/cli/specs/core.ts | 2 +- ...-computer-use-permissions-shutdown.test.ts | 17 +++++ .../macos-computer-use-permissions.ts | 14 +++- src/main/index.ts | 15 +++- src/main/ipc/computer-use-permissions.ts | 4 +- .../runtime/rpc/methods/computer/computer.ts | 2 +- .../methods/host-management/desktop-window.ts | 12 +++ .../rpc/methods/rpc-method-registry.ts | 2 + src/main/startup/main-process-preflight.ts | 6 +- .../main-window/main-window-actions.ts | 9 ++- .../main-window/main-window-controller.ts | 11 ++- src/main/startup/quit/app-relaunch.ts | 13 +++- .../serve-desktop-activation.test.ts | 12 +++ .../serve-launch/serve-desktop-activation.ts | 23 +++--- .../activation/background-window-open.ts | 15 ++++ .../activation/focus-existing-window.test.ts | 75 +++++++++++++++++++ .../activation/focus-existing-window.ts | 41 +++++++--- .../foreground-activation-policy.ts | 13 +++- src/main/window/createMainWindow.ts | 1 + .../main-window/main-window-contracts.ts | 7 ++ .../main-window-state-lifecycle.ts | 26 +++++-- .../windows/windows-administrator-restart.ts | 6 +- src/shared/background-open-argv.ts | 6 ++ .../computer/computer-schemas-params.ts | 4 +- .../rpc-params-catalog.generated.ts | 1 + 31 files changed, 409 insertions(+), 60 deletions(-) create mode 100644 src/cli/runtime/open-local-orca.test.ts create mode 100644 src/main/runtime/rpc/methods/host-management/desktop-window.ts create mode 100644 src/main/window/activation/background-window-open.ts create mode 100644 src/main/window/activation/focus-existing-window.test.ts create mode 100644 src/shared/background-open-argv.ts diff --git a/docs/site/content/docs/cli/reference.mdx b/docs/site/content/docs/cli/reference.mdx index e8314c890ff..4225d32bf6c 100644 --- a/docs/site/content/docs/cli/reference.mdx +++ b/docs/site/content/docs/cli/reference.mdx @@ -39,6 +39,8 @@ orca open --json orca status --json ``` +`orca open` starts Orca without taking keyboard focus from the app you're using. If an Orca window is already open, it does nothing. + Use `--json` when another tool will parse the result. Human-readable output is for quick terminal checks. ## Selectors diff --git a/src/cli/computer/computer.ts b/src/cli/computer/computer.ts index 0b2249bf794..3fdaabf059f 100644 --- a/src/cli/computer/computer.ts +++ b/src/cli/computer/computer.ts @@ -49,6 +49,7 @@ export const COMPUTER_HANDLERS: Record = { }, 'computer permissions': async ({ flags, client, json }) => { const id = getComputerPermissionSetupId(flags) + // Agents run this on errors; System Settings over the user's work is only worth it when something is missing. const result = await client.call<{ platform: NodeJS.Platform helperAppPath: string | null @@ -57,7 +58,7 @@ export const COMPUTER_HANDLERS: Record = { launchQueued?: boolean permissions?: { id: string; status: string }[] nextStep?: string | null - }>('computer.permissions', id ? { id } : {}) + }>('computer.permissions', id ? { id, skipGranted: true } : {}) printResult(result, json, (value) => { if (value.platform !== 'darwin') { return 'Computer-use permission setup is only required on macOS.' diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index 04f2cdad1b4..4c07a3fb815 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -304,6 +304,13 @@ export class RuntimeClient { } async openOrca(timeoutMs = 15_000): Promise> { - return this.remote ? this.getCliStatus() : openLocalOrca(() => this.getCliStatus(), timeoutMs) + if (this.remote) { + return this.getCliStatus() + } + return openLocalOrca( + () => this.getCliStatus(), + (options) => this.call<{ requested: boolean }>('desktop.openWindowInBackground', {}, options), + timeoutMs + ) } } diff --git a/src/cli/runtime/launch.ts b/src/cli/runtime/launch.ts index 526c689e764..103fe160f93 100644 --- a/src/cli/runtime/launch.ts +++ b/src/cli/runtime/launch.ts @@ -21,6 +21,7 @@ import { superviseForegroundServe } from './serve-update-supervisor' import { RuntimeClientError } from './types' +import { BACKGROUND_OPEN_ARG } from '../../shared/background-open-argv' import { getExecutableAppArgs, resolveAppRoot, @@ -69,7 +70,7 @@ export function launchOrcaApp(): void { const overrideExecutable = process.env.ORCA_APP_EXECUTABLE if (typeof overrideExecutable === 'string' && overrideExecutable.trim().length > 0) { const pinned = pinLaunchUserDataPath( - getExecutableAppArgs(overrideExecutable), + [...getExecutableAppArgs(overrideExecutable), BACKGROUND_OPEN_ARG], stripElectronRunAsNode(process.env), userDataPath ) @@ -93,7 +94,7 @@ export function launchOrcaApp(): void { } const pinned = pinLaunchUserDataPath( - getExecutableAppArgs(process.execPath), + [...getExecutableAppArgs(process.execPath), BACKGROUND_OPEN_ARG], stripElectronRunAsNode(process.env), userDataPath ) @@ -107,12 +108,19 @@ export function launchOrcaApp(): void { ) } -/** Nondefault profiles need a new instance: open drops env and only new instances receive --args. */ +/** Nondefault profiles need a new instance: open drops env and only new instances receive --args. -g keeps the user's app in front. */ export function getMacOpenArgs(appBundlePath: string, userDataPath: string): string[] { if (isSameUserDataPath(userDataPath, getPlatformUserDataPath())) { - return [appBundlePath] + return ['-g', appBundlePath, '--args', BACKGROUND_OPEN_ARG] } - return ['-n', appBundlePath, '--args', `--user-data-dir=${userDataPath}`] + return [ + '-g', + '-n', + appBundlePath, + '--args', + `--user-data-dir=${userDataPath}`, + BACKGROUND_OPEN_ARG + ] } function spawnDetached(command: string, args: string[], options: SpawnOptions): void { diff --git a/src/cli/runtime/open-local-orca.test.ts b/src/cli/runtime/open-local-orca.test.ts new file mode 100644 index 00000000000..560268cee14 --- /dev/null +++ b/src/cli/runtime/open-local-orca.test.ts @@ -0,0 +1,71 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { CliStatusResult } from '../../shared/runtime-types' +import { launchOrcaApp } from './launch' +import { openLocalOrca } from './open-local-orca' +import type { RuntimeRpcSuccess } from './types' + +vi.mock('./launch', () => ({ launchOrcaApp: vi.fn() })) + +function status(desktopWindowStatus: string): RuntimeRpcSuccess { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: openLocalOrca reads only runtime.reachable and app.desktopWindowStatus. + return { + ok: true, + result: { runtime: { reachable: true }, app: { desktopWindowStatus } } + } as unknown as RuntimeRpcSuccess +} + +describe('openLocalOrca', () => { + beforeEach(() => { + vi.mocked(launchOrcaApp).mockClear() + }) + + it('asks a running Orca to show its window instead of relaunching it', async () => { + const readStatus = vi + .fn() + .mockResolvedValueOnce(status('openable')) + .mockResolvedValueOnce(status('available')) + const openWindowInBackground = vi.fn(async () => ({ + id: '1', + ok: true as const, + result: { requested: true }, + _meta: { runtimeId: 'runtime' } + })) + + await openLocalOrca(readStatus, openWindowInBackground, 1_000) + + expect(openWindowInBackground).toHaveBeenCalledOnce() + expect(launchOrcaApp).not.toHaveBeenCalled() + }) + + it('does not relaunch an older Orca whose window is already available', async () => { + const available = status('available') + + await expect( + openLocalOrca( + async () => available, + async () => { + throw new Error('method_not_found') + }, + 1_000 + ) + ).resolves.toBe(available) + expect(launchOrcaApp).not.toHaveBeenCalled() + }) + + it('launches Orca when an older headless runtime cannot open its own window', async () => { + const readStatus = vi + .fn() + .mockResolvedValueOnce(status('openable')) + .mockResolvedValueOnce(status('available')) + + await openLocalOrca( + readStatus, + async () => { + throw new Error('method_not_found') + }, + 1_000 + ) + + expect(launchOrcaApp).toHaveBeenCalledOnce() + }) +}) diff --git a/src/cli/runtime/open-local-orca.ts b/src/cli/runtime/open-local-orca.ts index 18c87338954..aafbeab3f8f 100644 --- a/src/cli/runtime/open-local-orca.ts +++ b/src/cli/runtime/open-local-orca.ts @@ -3,21 +3,34 @@ import { launchOrcaApp } from './launch' import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcSuccess } from './types' type ReadStatus = () => Promise> +type OpenWindowInBackground = (options: { + timeoutMs: number +}) => Promise> + +// The runtime only queues a window request; a stuck one must not hold `orca open` for a full RPC timeout. +const OPEN_WINDOW_RPC_TIMEOUT_MS = 5_000 export async function openLocalOrca( readStatus: ReadStatus, + openWindowInBackground: OpenWindowInBackground, timeoutMs: number ): Promise> { const initial = await getStatusForOpen(readStatus) + const windowStatus = initial?.result.app.desktopWindowStatus // A blocked runtime cannot open a window; a second app would only hit its instance lock. - if (initial?.result.app.desktopWindowStatus === 'blocked') { + if (windowStatus === 'blocked') { throwDesktopActivationBlocked() } - launchOrcaApp() - if (initial?.result.app.desktopWindowStatus === 'available') { + // Relaunching a running Orca would hand it the foreground, so ask it to show its own window. + const asked = + initial?.result.runtime.reachable === true && (await askToOpenWindow(openWindowInBackground)) + if (initial && windowStatus === 'available') { return initial } + if (!asked) { + launchOrcaApp() + } const startedAt = Date.now() while (Date.now() - startedAt < timeoutMs) { @@ -55,6 +68,16 @@ async function getStatusForOpen( } } +async function askToOpenWindow(openWindowInBackground: OpenWindowInBackground): Promise { + try { + const response = await openWindowInBackground({ timeoutMs: OPEN_WINDOW_RPC_TIMEOUT_MS }) + return response.result.requested === true + } catch { + // Older runtimes lack the method; any failure falls back to relaunching, as open always did. + return false + } +} + function throwDesktopActivationBlocked(): never { throw new RuntimeClientError( 'desktop_activation_blocked', diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index 7c6b71a20ae..c91a201418e 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -16,7 +16,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ usage: 'orca open [--json]', allowedFlags: [...GLOBAL_FLAGS], notes: [ - "It can bring Orca's window to the front. Agents should run it only when the user asks or `orca status --json` reports Orca is not running or still cannot connect after about 30 seconds of retries, never to retry a failed command." + 'Starts Orca without taking the foreground and does nothing when an Orca window is already open. Agents should run it only when the user asks or `orca status --json` reports Orca is not running or still cannot connect after about 30 seconds of retries, never to retry a failed command.' ], examples: ['orca open', 'orca open --json'] }, diff --git a/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts b/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts index 5123bca82ac..28b95b2b687 100644 --- a/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts +++ b/src/main/computer/macos-permissions/macos-computer-use-permissions-shutdown.test.ts @@ -251,4 +251,21 @@ describe('computer-use setup cancellation', () => { }) expect(setupLaunches()).toEqual([['--permission', 'accessibility']]) }) + + it('leaves System Settings closed when an agent asks for a granted permission', async () => { + mocks.peek.mockResolvedValue({ + ...denied, + permissions: [ + { id: 'accessibility', status: 'granted' }, + { id: 'screenshots', status: 'not-granted' } + ] + }) + const { permissions } = await loadModules() + await expect( + permissions.openComputerUsePermissions('accessibility', { skipGranted: true }) + ).resolves.toMatchObject({ launchedHelper: false, openedSettings: false }) + expect(setupLaunches()).toEqual([]) + await permissions.openComputerUsePermissions('screenshots', { skipGranted: true }) + expect(setupLaunches()).toEqual([['--permission', 'screenshots']]) + }) }) diff --git a/src/main/computer/macos-permissions/macos-computer-use-permissions.ts b/src/main/computer/macos-permissions/macos-computer-use-permissions.ts index 4dbba0fdf65..41f34ffedaf 100644 --- a/src/main/computer/macos-permissions/macos-computer-use-permissions.ts +++ b/src/main/computer/macos-permissions/macos-computer-use-permissions.ts @@ -33,9 +33,9 @@ let resetInProgress: Promise | null = null /** `locale` comes from the desktop caller; orcad and CLI opens leave the helper on its default copy. */ export function openComputerUsePermissions( permissionId?: ComputerUsePermissionId, - locale?: string + options: { locale?: string; skipGranted?: boolean } = {} ): Promise { - return openComputerUsePermissionsAsync(permissionId, locale, ++setupRequestSeq, setupGeneration) + return openComputerUsePermissionsAsync(permissionId, options, ++setupRequestSeq, setupGeneration) } function cancelPendingSetupLaunches(): void { @@ -151,7 +151,7 @@ async function launchSetupHelper( async function openComputerUsePermissionsAsync( permissionId: ComputerUsePermissionId | undefined, - locale: string | undefined, + { locale, skipGranted }: { locale?: string; skipGranted?: boolean }, seq: number, generation: number ): Promise { @@ -191,7 +191,13 @@ async function openComputerUsePermissionsAsync( ) } - if (!permissionId && !nextStep) { + const alreadyGranted = permissionId + ? skipGranted === true && + status.permissions.some( + (permission) => permission.id === permissionId && permission.status === 'granted' + ) + : !nextStep + if (alreadyGranted) { return { platform: process.platform, helperAppPath, diff --git a/src/main/index.ts b/src/main/index.ts index 50254b4c1b8..6606da9fc28 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -51,18 +51,23 @@ import { registerOrcaProtocolClient } from './startup/open-routing/orca-protocol import { clearWindowsStdHandleInheritance } from './startup/windows-startup/windows-std-handle-inheritance' import { installWindowsIsolatedSpawner } from './startup/windows-startup/windows-isolated-spawner' import { dropE2eSpawnLogOutsideE2e } from './startup/testing/e2e-spawn-log-env' +import type { MainWindowOpenOptions } from './window/main-window/main-window-contracts' +import type { DesktopActivationRequest } from './startup/serve-launch/serve-desktop-activation' +import { argvRequestsBackgroundOpen, BACKGROUND_OPEN_ARG } from '../shared/background-open-argv' +import { setBackgroundWindowOpener } from './window/activation/background-window-open' // Before anything spawns, so no daemon, PTY or agent inherits it outside e2e. dropE2eSpawnLogOutsideE2e() -function openMainWindow(options: { revealOnDidFinishLoad?: boolean } = {}): BrowserWindow { +function openMainWindow(options: MainWindowOpenOptions = {}): BrowserWindow { return openMainWindowController(options) } setMainWindowOpener(openMainWindow) +setBackgroundWindowOpener(() => requestDesktopActivation([BACKGROUND_OPEN_ARG])) -function focusExistingWindow(): void { - focusExistingWindowAction() +function focusExistingWindow(request: DesktopActivationRequest = {}): void { + focusExistingWindowAction(request) } const requestDesktopHandoff = createDesktopHandoff({ @@ -86,7 +91,9 @@ function requestDesktopActivation(argv: readonly string[] = []): void { requestDesktopHandoff() return } - state.desktopActivationGate?.requestActivation() + state.desktopActivationGate?.requestActivation({ + background: argvRequestsBackgroundOpen(argv) + }) } /** Buffer documents until listener readiness; webContents.send silently drops unhandled messages. */ diff --git a/src/main/ipc/computer-use-permissions.ts b/src/main/ipc/computer-use-permissions.ts index 1fb4a4ec047..73edce4f5cd 100644 --- a/src/main/ipc/computer-use-permissions.ts +++ b/src/main/ipc/computer-use-permissions.ts @@ -17,7 +17,9 @@ export function registerComputerUsePermissionHandlers(): void { ): Promise => { const { openComputerUsePermissions } = await import('../computer/macos-permissions/macos-computer-use-permissions') - return openComputerUsePermissions(args?.id, mainI18n.resolvedLanguage ?? mainI18n.language) + return openComputerUsePermissions(args?.id, { + locale: mainI18n.resolvedLanguage ?? mainI18n.language + }) } ) ipcMain.handle( diff --git a/src/main/runtime/rpc/methods/computer/computer.ts b/src/main/runtime/rpc/methods/computer/computer.ts index 0279258b115..dd278acc5d7 100644 --- a/src/main/runtime/rpc/methods/computer/computer.ts +++ b/src/main/runtime/rpc/methods/computer/computer.ts @@ -55,7 +55,7 @@ export const COMPUTER_METHODS = [ handler: async (params) => { const { openComputerUsePermissions } = await import('../../../../computer/macos-permissions/macos-computer-use-permissions') - return openComputerUsePermissions(params.id) + return openComputerUsePermissions(params.id, { skipGranted: params.skipGranted === true }) } }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/host-management/desktop-window.ts b/src/main/runtime/rpc/methods/host-management/desktop-window.ts new file mode 100644 index 00000000000..f1e7a27af5c --- /dev/null +++ b/src/main/runtime/rpc/methods/host-management/desktop-window.ts @@ -0,0 +1,12 @@ +import { defineMethod } from '../../core' +import { requestBackgroundWindowOpen } from '../../../../window/activation/background-window-open' + +export const DESKTOP_WINDOW_METHODS = [ + // `orca open` asks the running app instead of relaunching it, which would hand it the foreground. + defineMethod({ + name: 'desktop.openWindowInBackground', + permission: 'desktop-control', + params: null, + handler: async () => ({ requested: requestBackgroundWindowOpen() }) + }) +] diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index c0168ed85ee..3d603d1141f 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -1,4 +1,5 @@ import { STATUS_METHODS } from './host-management/status' +import { DESKTOP_WINDOW_METHODS } from './host-management/desktop-window' import { SIDEBAR_INPUT_METHODS } from './sidebar-inputs/sidebar-inputs' import { ORCAD_TERMINAL_CENSUS_METHODS } from './orcad/orcad-terminal-census' import { ORCAD_MIGRATION_METHODS } from './orcad/orcad-migration' @@ -87,6 +88,7 @@ import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../../shared/sidebar-inputs-s // Keep registration order and the full RPC/security surface visible in one manifest. export const ALL_RPC_METHODS = [ ...STATUS_METHODS, + ...DESKTOP_WINDOW_METHODS, ...ORCAD_TERMINAL_CENSUS_METHODS, ...ORCAD_MIGRATION_METHODS, ...SESSION_TERMINAL_SCROLLBACK_METHODS, diff --git a/src/main/startup/main-process-preflight.ts b/src/main/startup/main-process-preflight.ts index 090ef91e592..66a0e592e2e 100644 --- a/src/main/startup/main-process-preflight.ts +++ b/src/main/startup/main-process-preflight.ts @@ -116,7 +116,7 @@ import { import { ensureWindowsAppDataPath } from './windows-startup/windows-app-data-path' export type MainProcessPreflightOptions = { - focusExistingWindow: () => void + focusExistingWindow: (request: { background?: boolean }) => void requestDesktopActivation: (argv?: readonly string[]) => void } @@ -166,10 +166,10 @@ function initializeMainProcessPreflight(options: MainProcessPreflightOptions): b state.desktopActivationGate = createServeDesktopActivationGate({ // Hold activation until the startup window exists; early second-instance activation otherwise opens a duplicate and aborts launch. initialState: 'initializing', - activateWindow: () => { + activateWindow: (request) => { // Updater replacement must not resurrect the old bundle. if (!isQuittingForUpdate()) { - options.focusExistingWindow() + options.focusExistingWindow(request) } }, onBlocked: (reason) => console.error(`[serve] Desktop activation blocked: ${reason}`) diff --git a/src/main/startup/main-window/main-window-actions.ts b/src/main/startup/main-window/main-window-actions.ts index 988d5e75d0a..5008615e490 100644 --- a/src/main/startup/main-window/main-window-actions.ts +++ b/src/main/startup/main-window/main-window-actions.ts @@ -47,18 +47,21 @@ import { import { isHoldingForNewerProtocolDaemon } from '../../daemon/providers/routing/daemon-newer-protocol-hold' import { getDaemonProvider } from '../../daemon/providers/lifecycle/daemon-provider-state' import { confirmNoDaemonSessionsRemain } from '../../ipc/pty/pty-management' +import type { MainWindowOpenOptions } from '../../window/main-window/main-window-contracts' +import type { DesktopActivationRequest } from '../serve-launch/serve-desktop-activation' // Inject the opener to avoid an actions/lifecycle import cycle. -let openWindow: (options?: { revealOnDidFinishLoad?: boolean }) => BrowserWindow +let openWindow: (options?: MainWindowOpenOptions) => BrowserWindow export function setMainWindowOpener( - opener: (options?: { revealOnDidFinishLoad?: boolean }) => BrowserWindow + opener: (options?: MainWindowOpenOptions) => BrowserWindow ): void { openWindow = opener } -export function focusExistingWindow(): void { +export function focusExistingWindow(request: DesktopActivationRequest = {}): void { focusExistingMainWindow({ app, + background: request.background === true, getWindow: () => state.mainWindow, openWindow, // Repair rewrites renderer DACLs; second-click activation during a blank launch must wait for the gated opener. diff --git a/src/main/startup/main-window/main-window-controller.ts b/src/main/startup/main-window/main-window-controller.ts index 1e3e4031df3..0d2300352e5 100644 --- a/src/main/startup/main-window/main-window-controller.ts +++ b/src/main/startup/main-window/main-window-controller.ts @@ -45,12 +45,18 @@ import { applyBackgroundActivationPolicy, applyServeDesktopWindowActivationPolicy } from '../../window/activation/foreground-activation-policy' +import type { MainWindowOpenOptions } from '../../window/main-window/main-window-contracts' +import { argvRequestsBackgroundOpen } from '../../../shared/background-open-argv' const TRAY_CREATE_FALLBACK_MS = 12_000 const AGENT_STATE_CRASH_BREADCRUMB_MIN_INTERVAL_MS = 30_000 -export function openMainWindow(options: { revealOnDidFinishLoad?: boolean } = {}): BrowserWindow { +export function openMainWindow(options: MainWindowOpenOptions = {}): BrowserWindow { logStartupMilestone('open-main-window-start') + // The launch's first window honours the background request `orca open` put on its argv. + const revealInBackground = + options.revealInBackground ?? + (!state.hasOpenedMainWindow && argvRequestsBackgroundOpen(process.argv)) const { store, keybindings } = requireMainWindowServices({ store: state.store, runtime: state.runtime, @@ -89,7 +95,7 @@ export function openMainWindow(options: { revealOnDidFinishLoad?: boolean } = {} } } if (state.isServeMode) { - applyServeDesktopWindowActivationPolicy({ warn: console.warn }) + applyServeDesktopWindowActivationPolicy({ warn: console.warn, background: revealInBackground }) } const window = createMainWindow(store, { getIsQuitting: () => state.isQuitting, @@ -142,6 +148,7 @@ export function openMainWindow(options: { revealOnDidFinishLoad?: boolean } = {} }, deferLoad: true, ...(options.revealOnDidFinishLoad === true ? { revealOnDidFinishLoad: true } : {}), + revealInBackground, title: state.devInstanceIdentity?.name ?? app.name, getKeybindings: () => keybindings.getOverrides(), onBeforeReload: ({ ignoreCache, webContentsId }) => { diff --git a/src/main/startup/quit/app-relaunch.ts b/src/main/startup/quit/app-relaunch.ts index 3059783d668..1b535b3d7b2 100644 --- a/src/main/startup/quit/app-relaunch.ts +++ b/src/main/startup/quit/app-relaunch.ts @@ -3,6 +3,7 @@ import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { runWithLaunchPath } from '../shell-environment/hydrate-shell-path' import { getWindowsAdministratorRelaunchOptions } from '../../windows/windows-administrator-restart' +import { BACKGROUND_OPEN_ARG } from '../../../shared/background-open-argv' export type AppRelaunchReason = | 'admin-restart' @@ -20,7 +21,17 @@ export function relaunchApp( ): void { // Persist the cause before relaunch can exit this process. recordDurableCrashBreadcrumb('app_relaunch_requested', { ...data, reason }) - runWithLaunchPath(() => app.relaunch(options ?? getWindowsAdministratorRelaunchOptions())) + runWithLaunchPath(() => app.relaunch(options ?? defaultRelaunchOptions())) +} + +// The user restarted Orca, so the new window comes forward even when `orca open` started this one. +function defaultRelaunchOptions(): Electron.RelaunchOptions | undefined { + const administrator = getWindowsAdministratorRelaunchOptions() + if (!administrator && !process.argv.includes(BACKGROUND_OPEN_ARG)) { + return undefined + } + const args = administrator?.args ?? process.argv.slice(1) + return { ...administrator, args: args.filter((arg) => arg !== BACKGROUND_OPEN_ARG) } } export async function runBeforeRelaunchCleanup( diff --git a/src/main/startup/serve-launch/serve-desktop-activation.test.ts b/src/main/startup/serve-launch/serve-desktop-activation.test.ts index 18e3e147771..d83c32ad844 100644 --- a/src/main/startup/serve-launch/serve-desktop-activation.test.ts +++ b/src/main/startup/serve-launch/serve-desktop-activation.test.ts @@ -38,4 +38,16 @@ describe('createServeDesktopActivationGate', () => { expect(onBlocked).toHaveBeenCalledTimes(2) expect(gate.getState()).toBe('blocked') }) + + it('lets a queued user activation keep the foreground over a background open', () => { + const activateWindow = vi.fn() + const gate = createServeDesktopActivationGate({ initialState: 'initializing', activateWindow }) + + gate.requestActivation({ background: true }) + gate.requestActivation() + gate.requestActivation({ background: true }) + gate.markReady() + + expect(activateWindow.mock.calls).toEqual([[{ background: false }]]) + }) }) diff --git a/src/main/startup/serve-launch/serve-desktop-activation.ts b/src/main/startup/serve-launch/serve-desktop-activation.ts index e1bc1731f23..90606996697 100644 --- a/src/main/startup/serve-launch/serve-desktop-activation.ts +++ b/src/main/startup/serve-launch/serve-desktop-activation.ts @@ -2,9 +2,11 @@ import type { RuntimeDesktopWindowStatus } from '../../../shared/runtime-session type ActivationGateState = Exclude | 'ready' +export type DesktopActivationRequest = { background?: boolean } + export type ServeDesktopActivationGate = { getState: () => ActivationGateState - requestActivation: () => void + requestActivation: (request?: DesktopActivationRequest) => void markReady: () => void markBlocked: (reason: string) => void } @@ -37,22 +39,24 @@ export function releaseDesktopActivationAfter( export function createServeDesktopActivationGate(options: { initialState: 'initializing' | 'ready' - activateWindow: () => void + activateWindow: (request: DesktopActivationRequest) => void onBlocked?: (reason: string) => void }): ServeDesktopActivationGate { let state: ActivationGateState = options.initialState - let pendingActivation = false + let pendingActivation: DesktopActivationRequest | null = null let blockedReason = 'desktop activation is unavailable' return { getState: () => state, - requestActivation: () => { + requestActivation: (request = {}) => { if (state === 'ready') { - options.activateWindow() + options.activateWindow(request) return } if (state === 'initializing') { - pendingActivation = true + // Any queued user activation keeps its claim to the foreground. + const background = request.background === true && pendingActivation?.background !== false + pendingActivation = { background } return } options.onBlocked?.(blockedReason) @@ -63,8 +67,9 @@ export function createServeDesktopActivationGate(options: { } state = 'ready' if (pendingActivation) { - pendingActivation = false - options.activateWindow() + const request = pendingActivation + pendingActivation = null + options.activateWindow(request) } }, markBlocked: (reason) => { @@ -74,7 +79,7 @@ export function createServeDesktopActivationGate(options: { state = 'blocked' blockedReason = reason if (pendingActivation) { - pendingActivation = false + pendingActivation = null options.onBlocked?.(blockedReason) } } diff --git a/src/main/window/activation/background-window-open.ts b/src/main/window/activation/background-window-open.ts new file mode 100644 index 00000000000..6de1ae1ffff --- /dev/null +++ b/src/main/window/activation/background-window-open.ts @@ -0,0 +1,15 @@ +// Registered by the desktop main process; orcad has no window to open and leaves it unset. +let openWindowInBackground: (() => void) | null = null + +export function setBackgroundWindowOpener(opener: () => void): void { + openWindowInBackground = opener +} + +/** Shows Orca's window without taking the foreground; false when this host has no desktop. */ +export function requestBackgroundWindowOpen(): boolean { + if (!openWindowInBackground) { + return false + } + openWindowInBackground() + return true +} diff --git a/src/main/window/activation/focus-existing-window.test.ts b/src/main/window/activation/focus-existing-window.test.ts new file mode 100644 index 00000000000..55cd6d46f03 --- /dev/null +++ b/src/main/window/activation/focus-existing-window.test.ts @@ -0,0 +1,75 @@ +import type { BrowserWindow } from 'electron' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ app: {}, BaseWindow: { getFocusedWindow: () => null } })) + +const { focusExistingMainWindow } = await import('./focus-existing-window') + +function makeWindow(visible: boolean) { + return { + isDestroyed: () => false, + isMinimized: () => false, + isVisible: () => visible, + restore: vi.fn(), + show: vi.fn(), + showInactive: vi.fn(), + focus: vi.fn(), + moveTop: vi.fn(), + isAlwaysOnTop: () => false, + setAlwaysOnTop: vi.fn() + } +} + +describe('focusExistingMainWindow for a background open', () => { + // The test runner itself launches in the background, which would hide what the request decides. + beforeEach(() => { + vi.stubEnv('ORCA_BACKGROUND_LAUNCH', '') + }) + afterEach(() => { + vi.unstubAllEnvs() + }) + + it('shows a hidden window without taking the foreground', () => { + const window = makeWindow(false) + const app = { focus: vi.fn(), isReady: () => true } + + focusExistingMainWindow({ + app, + background: true, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the background path reads only these window methods. + getWindow: () => window as unknown as BrowserWindow, + openWindow: vi.fn(), + platform: 'win32', + setTimeout: vi.fn() + }) + + expect(window.showInactive).toHaveBeenCalledOnce() + expect(app.focus).not.toHaveBeenCalled() + expect(window.show).not.toHaveBeenCalled() + expect(window.focus).not.toHaveBeenCalled() + expect(window.moveTop).not.toHaveBeenCalled() + expect(window.setAlwaysOnTop).not.toHaveBeenCalled() + }) + + it('opens a missing window to reveal itself in the background', () => { + const window = makeWindow(false) + const app = { focus: vi.fn(), isReady: () => true } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the background path reads only these window methods. + const openWindow = vi.fn((_options?: unknown) => window as unknown as BrowserWindow) + + expect( + focusExistingMainWindow({ + app, + background: true, + getWindow: () => null, + openWindow, + platform: 'win32', + setTimeout: vi.fn() + }) + ).toBe('opened') + + expect(openWindow).toHaveBeenCalledWith({ revealInBackground: true }) + expect(app.focus).not.toHaveBeenCalled() + expect(window.showInactive).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/window/activation/focus-existing-window.ts b/src/main/window/activation/focus-existing-window.ts index 3af5528222f..f406bb7442a 100644 --- a/src/main/window/activation/focus-existing-window.ts +++ b/src/main/window/activation/focus-existing-window.ts @@ -12,7 +12,10 @@ export type FocusExistingMainWindowResult = 'focused' | 'opened' | 'pending' export type FocusExistingMainWindowOptions = { app: Pick getWindow: () => BrowserWindow | null - openWindow: () => BrowserWindow + // Structural: the web project typechecks this file and can't reach main-window-contracts. + openWindow: (options?: { revealInBackground?: boolean }) => BrowserWindow + /** `orca open` asked: show the window if needed, never take the foreground. */ + background?: boolean /** False while some other path must own the first window; the reopen is dropped, not queued. */ canOpenWindow?: () => boolean platform?: NodeJS.Platform @@ -82,8 +85,21 @@ function activateWindow( window: BrowserWindow, app: Pick, platform: NodeJS.Platform, - setTimer: FocusTimer + setTimer: FocusTimer, + background: boolean ): void { + if (background) { + // A minimized window stays minimized: restoring it would pull the user's attention. + if ( + !window.isDestroyed() && + !window.isVisible() && + !window.isMinimized() && + !isWindowlessLaunch() + ) { + window.showInactive() + } + return + } safelyFocusApp(app) safelyRevealWindow(window) // Windows reinforcement raises windows over other work; suppress it during background launches. @@ -109,10 +125,11 @@ function openWindowWithRetry( >, platform: NodeJS.Platform, setTimer: FocusTimer, - attempt: number + attempt: number, + background: boolean ): BrowserWindow | null { try { - return opts.openWindow() + return opts.openWindow(background ? { revealInBackground: true } : undefined) } catch (error) { opts.warn?.('[window] Failed to reopen main window for second-instance launch', error) if (attempt >= REOPEN_MAX_ATTEMPTS) { @@ -122,16 +139,16 @@ function openWindowWithRetry( // openWindow constructs each time; adopt windows created by concurrent/partially failed attempts to avoid orphaning duplicates. const existing = opts.getWindow() if (existing && !existing.isDestroyed()) { - activateWindow(existing, opts.app, platform, setTimer) + activateWindow(existing, opts.app, platform, setTimer, background) return } // Opening may have become forbidden (e.g. quit teardown) since this retry was scheduled. if (opts.canOpenWindow?.() === false) { return } - const window = openWindowWithRetry(opts, platform, setTimer, attempt + 1) - if (window) { - activateWindow(window, opts.app, platform, setTimer) + const window = openWindowWithRetry(opts, platform, setTimer, attempt + 1, background) + if (window && !background) { + activateWindow(window, opts.app, platform, setTimer, false) } }, REOPEN_RETRY_DELAY_MS) return null @@ -143,6 +160,7 @@ export function focusExistingMainWindow( ): FocusExistingMainWindowResult { const platform = opts.platform ?? process.platform const setTimer = opts.setTimeout ?? setTimeout + const background = opts.background === true let window = opts.getWindow() let openedWindow = false @@ -150,13 +168,16 @@ export function focusExistingMainWindow( if (!opts.app.isReady() || opts.canOpenWindow?.() === false) { return 'pending' } - window = openWindowWithRetry(opts, platform, setTimer, 1) + window = openWindowWithRetry(opts, platform, setTimer, 1, background) if (!window) { return 'pending' } openedWindow = true } - activateWindow(window, opts.app, platform, setTimer) + // A window opened in the background reveals itself inactive on first paint. + if (!(openedWindow && background)) { + activateWindow(window, opts.app, platform, setTimer, background) + } return openedWindow ? 'opened' : 'focused' } diff --git a/src/main/window/activation/foreground-activation-policy.ts b/src/main/window/activation/foreground-activation-policy.ts index 5f0926df050..e91c00fd1cd 100644 --- a/src/main/window/activation/foreground-activation-policy.ts +++ b/src/main/window/activation/foreground-activation-policy.ts @@ -68,7 +68,10 @@ export function applyBackgroundActivationPolicy(options: ActivationPolicyOptions /** Gives a serve process its Dock tile and menu bar back while it hosts a desktop window. */ export function applyServeDesktopWindowActivationPolicy( - options: Omit = {} + options: Omit & { + /** The window opens behind the user's app: take the Dock tile without dock.show()'s activation. */ + background?: boolean + } = {} ): boolean { const platform = options.platform ?? process.platform // dock.show() activates the app, so automated launches keep the accessory policy. @@ -78,9 +81,11 @@ export function applyServeDesktopWindowActivationPolicy( try { const app = options.app ?? electronApp app.setActivationPolicy('regular') - void app.dock?.show?.().catch((error: unknown) => { - options.warn?.('[window] Failed to show the Dock icon', error) - }) + if (options.background !== true) { + void app.dock?.show?.().catch((error: unknown) => { + options.warn?.('[window] Failed to show the Dock icon', error) + }) + } return true } catch (error) { options.warn?.('[window] Failed to apply foreground activation policy', error) diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index d7a1ef426ac..4855db93ffa 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -209,6 +209,7 @@ export function createMainWindow( const state = installMainWindowStateLifecycle({ mainWindow, revealOnDidFinishLoad: opts?.revealOnDidFinishLoad === true, + revealInBackground: opts?.revealInBackground, savedMaximized, savedFullScreen, store diff --git a/src/main/window/main-window/main-window-contracts.ts b/src/main/window/main-window/main-window-contracts.ts index 0d84dd910c7..4a1654db8fb 100644 --- a/src/main/window/main-window/main-window-contracts.ts +++ b/src/main/window/main-window/main-window-contracts.ts @@ -13,6 +13,11 @@ export type MainWindowLoadObserver = { onError?: (error: Error) => void } +export type MainWindowOpenOptions = Pick< + CreateMainWindowOptions, + 'revealOnDidFinishLoad' | 'revealInBackground' +> + export type CreateMainWindowOptions = { /** Returns true when a manual app.quit() (Cmd+Q) is in progress, so the renderer skips the running-process confirm dialog. */ getIsQuitting?: () => boolean @@ -43,6 +48,8 @@ export type CreateMainWindowOptions = { deferLoad?: boolean /** Reveal after load instead of first paint when startup must show the shell before slower renderer work. */ revealOnDidFinishLoad?: boolean + /** Show without taking the foreground: `orca open` asked, not the user. */ + revealInBackground?: boolean title?: string getKeybindings?: () => KeybindingOverrides | undefined onBeforeReload?: (options: { ignoreCache: boolean; webContentsId: number }) => void diff --git a/src/main/window/main-window/main-window-state-lifecycle.ts b/src/main/window/main-window/main-window-state-lifecycle.ts index 7e6db78021d..bb86be1c48f 100644 --- a/src/main/window/main-window/main-window-state-lifecycle.ts +++ b/src/main/window/main-window/main-window-state-lifecycle.ts @@ -19,11 +19,19 @@ export type MainWindowStateLifecycle = { export function installMainWindowStateLifecycle(args: { mainWindow: BrowserWindow revealOnDidFinishLoad: boolean + revealInBackground?: boolean savedMaximized: boolean savedFullScreen: boolean store: Store | null }): MainWindowStateLifecycle { - const { mainWindow, revealOnDidFinishLoad, savedMaximized, savedFullScreen, store } = args + const { + mainWindow, + revealOnDidFinishLoad, + revealInBackground = false, + savedMaximized, + savedFullScreen, + store + } = args mainWindow.webContents.on('dom-ready', () => { const level = store?.getUI().uiZoomLevel ?? 0 mainWindow.webContents.setZoomLevel(level) @@ -67,12 +75,20 @@ export function installMainWindowStateLifecycle(args: { if (isWindowlessLaunch()) { return } - if (savedMaximized) { - mainWindow.maximize() + if (revealInBackground) { + // Maximizing a hidden window shows it active; Windows activates on any maximize, so it stays restored there. + mainWindow.showInactive() + if (savedMaximized && process.platform !== 'win32') { + mainWindow.maximize() + } + } else { + if (savedMaximized) { + mainWindow.maximize() + } + showWindowWithoutStealingFocus(mainWindow) } - showWindowWithoutStealingFocus(mainWindow) // Fullscreen needs a shown window; after maximize so leaving it returns there. Background launches must not take a Space. - if (savedFullScreen && !isBackgroundLaunch()) { + if (savedFullScreen && !isBackgroundLaunch() && !revealInBackground) { mainWindow.setFullScreen(true) } } diff --git a/src/main/windows/windows-administrator-restart.ts b/src/main/windows/windows-administrator-restart.ts index 4c1d9d75763..9985d2fc31b 100644 --- a/src/main/windows/windows-administrator-restart.ts +++ b/src/main/windows/windows-administrator-restart.ts @@ -4,6 +4,7 @@ import { app } from 'electron' import { quoteWindowsArgument } from '@orca/process-host/windows-command-line' import { getBundledLauncherPath } from '../cli/packaged-assets/bundled-cli-launcher-path' import { getWindowsAdministratorStatus } from './windows-administrator-status' +import { BACKGROUND_OPEN_ARG } from '../../shared/background-open-argv' const RESTART_LOCAL_TERMINALS_ARG = '--orca-restart-local-terminals-as-administrator' @@ -28,7 +29,10 @@ export function prepareWindowsAdministratorRestart(): Electron.RelaunchOptions { if (!launcher || !existsSync(launcher)) { throw new Error('The Windows administrator launcher is unavailable.') } - const args = process.argv.slice(1).filter((arg) => arg !== RESTART_LOCAL_TERMINALS_ARG) + // The user asked for this restart, so the elevated window comes forward even when `orca open` started this one. + const args = process.argv + .slice(1) + .filter((arg) => arg !== RESTART_LOCAL_TERMINALS_ARG && arg !== BACKGROUND_OPEN_ARG) return { execPath: launcher, args: [ diff --git a/src/shared/background-open-argv.ts b/src/shared/background-open-argv.ts new file mode 100644 index 00000000000..4f010ff436a --- /dev/null +++ b/src/shared/background-open-argv.ts @@ -0,0 +1,6 @@ +/** `orca open` launches carry this so Orca shows its window without taking the foreground. */ +export const BACKGROUND_OPEN_ARG = '--orca-background-open' + +export function argvRequestsBackgroundOpen(argv: readonly string[]): boolean { + return argv.includes(BACKGROUND_OPEN_ARG) +} diff --git a/src/shared/rpc-contract/computer/computer-schemas-params.ts b/src/shared/rpc-contract/computer/computer-schemas-params.ts index e66ca391b47..eb0709302c2 100644 --- a/src/shared/rpc-contract/computer/computer-schemas-params.ts +++ b/src/shared/rpc-contract/computer/computer-schemas-params.ts @@ -217,7 +217,9 @@ export const Hotkey = ComputerObserveTargetBase.extend({ }) export const ComputerPermissions = z.object({ - id: z.enum(['accessibility', 'screenshots']).optional() + id: z.enum(['accessibility', 'screenshots']).optional(), + // Older hosts drop it and open as before; Settings buttons leave it off so a click always opens. + skipGranted: z.boolean().optional() }) export const PasteText = ComputerObserveTargetBase.extend({ diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index cc64774f151..611cc668c25 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -1065,6 +1065,7 @@ export const RPC_PARAMS_BY_METHOD = { 'connector.send': ConnectorSend, 'connector.start': ConnectorStart, 'connector.watch': ConnectorWatch, + 'desktop.openWindowInBackground': null, 'desktopBrowserBridge.attach': DesktopBrowserBridgeAttachParams, 'desktopBrowserBridge.result': DesktopBrowserBridgeResultParams, 'diagnostics.memory': null, From 80a514cfb6ac169ef311e70ea2b8a07b961416d8 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:51:47 +0000 Subject: [PATCH 13/52] fix(browser): stop agent CLI clicks over --environment from moving the desktop (#42205) --- src/cli/runtime/websocket-transport.ts | 4 +++- .../browser-page-input-credit.test.ts | 11 ++++++++-- .../browser-page-input-credit.ts | 9 ++++++-- src/main/runtime/rpc/callers/active-call.ts | 4 ++-- .../rpc/callers/rpc-caller-identity.ts | 20 ++++++++++++------ .../agent-launch/agent-launch-handoff-card.ts | 5 ++--- .../cli-agent-caller-capability.ts | 2 ++ .../paired-remote-browser-blank-link.spec.ts | 21 +++++++++++++++++++ 8 files changed, 60 insertions(+), 16 deletions(-) create mode 100644 src/shared/remote-runtime/cli-agent-caller-capability.ts diff --git a/src/cli/runtime/websocket-transport.ts b/src/cli/runtime/websocket-transport.ts index e79ac676dff..2b0350ef31b 100644 --- a/src/cli/runtime/websocket-transport.ts +++ b/src/cli/runtime/websocket-transport.ts @@ -7,6 +7,7 @@ import { RemoteRuntimeClientError } from '../../shared/remote-runtime/remote-run import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../shared/agent-launch/contracts/agent-launch-runtime-capability' import { AGENT_SESSION_RENAME_ONLY_CLIENT_CAPABILITY } from '../../shared/agent-session/structured-agent-session-surface-capabilities' import { REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' +import { CLI_AGENT_CALLER_CLIENT_CAPABILITY } from '../../shared/remote-runtime/cli-agent-caller-capability' import { sendRemoteRuntimeRequestOnSocket } from '../../shared/remote-runtime/requests/remote-runtime-request-socket' import type { RuntimeStatus } from '../../shared/runtime-types' import { RuntimeClientError, type RuntimeRpcResponse } from './types' @@ -15,7 +16,8 @@ import { RuntimeClientError, type RuntimeRpcResponse } from './types' const CLI_CLIENT_CAPABILITIES = [ AGENT_LAUNCH_RUNTIME_CAPABILITY, REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY, - AGENT_SESSION_RENAME_ONLY_CLIENT_CAPABILITY + AGENT_SESSION_RENAME_ONLY_CLIENT_CAPABILITY, + CLI_AGENT_CALLER_CLIENT_CAPABILITY ] as const export async function sendWebSocketRequest( diff --git a/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts b/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts index 58db3ac263a..0eea461c0c4 100644 --- a/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts +++ b/src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { BrowserPageInputCredit } from './browser-page-input-credit' -import type { LOCAL_CLI_RPC_CALLER } from '../../../runtime/rpc/callers/rpc-caller-identity' +import type { RpcCallerIdentity } from '../../../runtime/rpc/callers/rpc-caller-identity' const desktop = { kind: 'paired-device', deviceId: 'desk-1' } as const @@ -8,7 +8,7 @@ function setup() { let now = 1_000 const credit = new BrowserPageInputCredit(() => now) // A command that delivers activating input to the page while it runs, as a click does. - const click = (caller: typeof desktop | typeof LOCAL_CLI_RPC_CALLER, page = 'page-1') => + const click = (caller: RpcCallerIdentity, page = 'page-1') => credit.during(page, caller, async () => credit.creditInput('tab-1', page)) return { credit, click, advance: (ms: number) => (now += ms) } } @@ -22,4 +22,11 @@ describe('BrowserPageInputCredit', () => { expect(credit.consume('tab-1')).toBe('desk-1') expect(credit.consume('tab-1')).toBeNull() }) + + it("credits no one for an agent CLI's click over the desktop's pairing", async () => { + const { credit, click } = setup() + await click({ ...desktop, agent: true }) + + expect(credit.consume('tab-1')).toBeNull() + }) }) diff --git a/src/main/browser/routing/input-ownership/browser-page-input-credit.ts b/src/main/browser/routing/input-ownership/browser-page-input-credit.ts index 39ff41c4958..a3361ade910 100644 --- a/src/main/browser/routing/input-ownership/browser-page-input-credit.ts +++ b/src/main/browser/routing/input-ownership/browser-page-input-credit.ts @@ -1,5 +1,8 @@ import { isRecentBrowserGuestInput } from '../../guest-lifecycle/input/browser-guest-input-gesture' -import type { RpcCallerIdentity } from '../../../runtime/rpc/callers/rpc-caller-identity' +import { + isAgentRpcCaller, + type RpcCallerIdentity +} from '../../../runtime/rpc/callers/rpc-caller-identity' type Runner = { pairedDeviceId: string | null } @@ -23,7 +26,9 @@ export class BrowserPageInputCredit { execute: () => Promise ): Promise { const runner: Runner = { - pairedDeviceId: caller?.kind === 'paired-device' ? caller.deviceId : null + // An agent's CLI moves no one's view, even when it calls with a device's pairing. + pairedDeviceId: + caller?.kind === 'paired-device' && !isAgentRpcCaller(caller) ? caller.deviceId : null } this.runnerByPageId.set(browserPageId, runner) try { diff --git a/src/main/runtime/rpc/callers/active-call.ts b/src/main/runtime/rpc/callers/active-call.ts index 5f2f49adf70..ac9958555d3 100644 --- a/src/main/runtime/rpc/callers/active-call.ts +++ b/src/main/runtime/rpc/callers/active-call.ts @@ -1,6 +1,6 @@ import { AsyncLocalStorage } from 'node:async_hooks' import { isOrcaSessionId } from '../../../../shared/orca-session-address' -import { isAgentRpcCaller, type RpcCallerIdentity } from './rpc-caller-identity' +import type { RpcCallerIdentity } from './rpc-caller-identity' type ActiveRpcCall = { caller: RpcCallerIdentity | undefined @@ -17,7 +17,7 @@ export function runWithActiveRpcCaller( ): T { // Only this host's CLI can name a chat here; as in the handoff card, other callers act for a person. const agentSessionId = - isAgentRpcCaller(caller) && claimedAgentSessionId && isOrcaSessionId(claimedAgentSessionId) + caller?.kind === 'local-cli' && claimedAgentSessionId && isOrcaSessionId(claimedAgentSessionId) ? claimedAgentSessionId : undefined return activeCall.run({ caller, agentSessionId }, run) diff --git a/src/main/runtime/rpc/callers/rpc-caller-identity.ts b/src/main/runtime/rpc/callers/rpc-caller-identity.ts index 0f726a4238e..4f138dc164b 100644 --- a/src/main/runtime/rpc/callers/rpc-caller-identity.ts +++ b/src/main/runtime/rpc/callers/rpc-caller-identity.ts @@ -1,29 +1,34 @@ /** Transport-proven identity, never request params, controls durable ledger namespaces and whose view a launch moves. */ import type { RpcDispatchStreamingOptions } from '../dispatch/dispatcher-stream-options' +import { CLI_AGENT_CALLER_CLIENT_CAPABILITY } from '../../../../shared/remote-runtime/cli-agent-caller-capability' export type RpcCallerIdentity = /** The `orca` CLI over the runtime socket, and the in-process bridges that relay it. */ | { kind: 'local-cli' } /** All local IPC windows share identity across reload and app restart. */ | { kind: 'desktop' } - /** A paired phone or remote desktop, by its device subject, which survives credential rotation. */ - | { kind: 'paired-device'; deviceId: string } + /** A paired phone or remote desktop, by its device subject, which survives credential rotation. + * `agent`: the orca CLI calling with that device's pairing (`--environment`), not the person using it. */ + | { kind: 'paired-device'; deviceId: string; agent?: true } export const DESKTOP_RPC_CALLER: RpcCallerIdentity = { kind: 'desktop' } /** Stamped by the owner-token runtime socket, which only the local `orca` CLI holds. */ export const LOCAL_CLI_RPC_CALLER: RpcCallerIdentity = { kind: 'local-cli' } -/** The orca CLI agents run, locally or forwarded from a remote host; relayed devices are people. */ +/** The orca CLI agents run, on this host or over a device's pairing; people's windows and phones are not. */ export function isAgentRpcCaller(caller: RpcCallerIdentity | undefined): boolean { - return caller?.kind === 'local-cli' + return caller?.kind === 'local-cli' || (caller?.kind === 'paired-device' && caller.agent === true) } /** Trust explicit transport identity; unnamed declared clients have none. Temporarily, no declared client means local CLI. * The runtime socket stamps local-cli explicitly; plugin approval never trusts identity alone (it needs the approve fingerprint). */ export function resolveRpcCallerIdentity( transport: - | Pick + | Pick< + RpcDispatchStreamingOptions, + 'caller' | 'clientKind' | 'pairedDeviceId' | 'clientCapabilities' + > | undefined ): RpcCallerIdentity | undefined { if (transport?.caller) { @@ -31,7 +36,10 @@ export function resolveRpcCallerIdentity( } const deviceId = transport?.pairedDeviceId?.trim() if (deviceId) { - return { kind: 'paired-device', deviceId } + // A false claim only gives up the person's view-following, never any authority. + return transport?.clientCapabilities?.includes(CLI_AGENT_CALLER_CLIENT_CAPABILITY) + ? { kind: 'paired-device', deviceId, agent: true } + : { kind: 'paired-device', deviceId } } return transport?.clientKind === undefined ? { kind: 'local-cli' } : undefined } diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts index 87056f65c61..cd4d35a2ce8 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-handoff-card.ts @@ -8,7 +8,6 @@ import { startedAgentSender } from '../../../orchestration/workers/launch/worker-start-card' import type { RpcContext } from '../../core' -import { isAgentRpcCaller } from '../../callers/rpc-caller-identity' /** An agent that hands work to another from its chat leaves a card there linking to it. * Display bookkeeping: nothing here refuses, holds or fails the launch, whose result passes through. */ @@ -27,10 +26,10 @@ function prepareHandoffRecord( params: AgentLaunchParams & { operationId: string }, context: RpcContext ): (result: AgentLaunchResult) => void { - // Only the orca CLI on this host names its chat; windows, phones and remote CLIs launch for a person. + // Only the orca CLI on this host names a chat here; windows and phones launch for a person, and a remote CLI's chat is on its own host. const callerSessionId = context.orchestrationCompatibilityEvidence?.agentSessionId if ( - !isAgentRpcCaller(context.caller) || + context.caller?.kind !== 'local-cli' || callerSessionId === undefined || !isOrcaSessionId(callerSessionId) ) { diff --git a/src/shared/remote-runtime/cli-agent-caller-capability.ts b/src/shared/remote-runtime/cli-agent-caller-capability.ts new file mode 100644 index 00000000000..95d5a63b846 --- /dev/null +++ b/src/shared/remote-runtime/cli-agent-caller-capability.ts @@ -0,0 +1,2 @@ +/** Sent by the orca CLI on a paired socket: an agent's command, not the person whose pairing it shares. */ +export const CLI_AGENT_CALLER_CLIENT_CAPABILITY = 'caller.orca-cli.v1' as const diff --git a/tests/e2e/paired-remote-browser-blank-link.spec.ts b/tests/e2e/paired-remote-browser-blank-link.spec.ts index f3ee0c26881..38b88af2bae 100644 --- a/tests/e2e/paired-remote-browser-blank-link.spec.ts +++ b/tests/e2e/paired-remote-browser-blank-link.spec.ts @@ -14,6 +14,7 @@ import { } from './helpers/paired-electron-client' import { waitForPairedClientWorktree } from './helpers/paired-client-host-session' import { readHostBrowserPageIds } from './helpers/host-session-tabs' +import { orcaCliResult } from './helpers/compiled-orca-cli' // #36804: a click on a target=_blank link in a streamed server page opens a new Orca tab. @@ -96,6 +97,26 @@ test('a target=_blank click in a streamed server page opens a new Orca tab', asy await waitForOpenedTab(before) await expect(addressBar).toHaveValue(`${origin}/`) + // An agent's CLI on the client shares the desktop's pairing, but its click must not move the desktop. + before = await listPages() + const cli = (args: string[]) => + orcaCliResult(client!.userDataDir, [ + ...args, + '--page', + created.browserPageId, + '--environment', + environmentId + ]) + // agent-browser keys refs by id: { e1: { role, name } }. + const { refs } = await cli<{ refs: Record }>(['snapshot']) + const linkRef = Object.entries(refs).find(([, ref]) => ref.name === 'Open destination')?.[0] + if (!linkRef) { + throw new Error(`snapshot has no link ref: ${JSON.stringify(refs)}`) + } + await cli(['click', '--element', `@${linkRef}`]) + await waitForOpenedTab(before) + await expect(addressBar).toHaveValue(`${origin}/`) + // The client that clicks gets the new tab in front, as a local page would. before = await listPages() await remoteFrame.click() From 70525610f769098a591acbbc36619c69c19ed9e8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:52:46 -0800 Subject: [PATCH 14/52] Keep remote browser certificate warnings actionable (#41235) * Preserve remote browser certificate warnings through navigation * Apply current remote observations at the session boundary * Document array proxy forwarding in the performance contract * Keep remote browser failure fallbacks within current observations * Defer remote observation reads to lifecycle callbacks * Apply remote page observations without preempting pending outcomes * Preserve command loading ownership across partial page updates * Reuse browser host identity within each mirror record * Explain transparent record access in the loading contract fixture * Keep adoption fixture aligned with remote loading session * Name the remote navigation fixture return contract --- config/react-compiler-bailout-baseline.txt | 1 - ...er-workspace-pane.adoption-chrome.test.tsx | 6 +- .../describe-page/browser-page-types.ts | 7 + .../remote-browser-page-input-model.ts | 2 +- .../remote-browser-page-loading.test.ts | 240 ++++++ .../remote-browser-page-navigation-command.ts | 166 ++++ ...te-browser-page-navigation.test-fixture.ts | 184 +++++ .../remote-browser-page-observation.ts | 27 + .../remote-browser-page-pane.tsx | 20 +- .../remote-browser-page-session.test.ts | 1 + .../remote-browser-page-session.ts | 152 +++- .../remote-browser-page-viewport.tsx | 3 + ...e-browser-stream-lifecycle-test-harness.ts | 1 + .../remote-browser-stream-lifecycle.test.ts | 29 + .../remote-browser-stream-lifecycle.ts | 64 +- .../remote-browser-stream-restart-attempt.ts | 7 +- .../use-remote-browser-page-lifecycle.ts | 43 +- ...use-remote-browser-page-navigation.test.ts | 708 ++++++++++++++++-- .../use-remote-browser-page-navigation.ts | 159 ++-- .../use-remote-browser-page-stream.ts | 2 +- .../browser/browser-page-loading-ownership.ts | 39 + .../apply-browser-records.ts | 14 + .../mirrored-browser-tabs.ts | 54 +- .../runtime/web-session-tabs-sync/state.ts | 2 + .../slices/browser/browser-slice-contract.ts | 13 +- .../browser/pages/browser-page-records.ts | 14 +- .../pages/browser-page-state-actions.ts | 37 +- .../pages/browser-page-viewport-actions.ts | 12 +- 28 files changed, 1757 insertions(+), 250 deletions(-) create mode 100644 src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-loading.test.ts create mode 100644 src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation-command.ts create mode 100644 src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation.test-fixture.ts create mode 100644 src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-observation.ts create mode 100644 src/renderer/src/lib/browser/browser-page-loading-ownership.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 62b0b0c36d6..06b3aed8c79 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -65,7 +65,6 @@ 2 src/renderer/src/components/browser-pane/passwords/BrowserPasswordFillDropdown.tsx 1 src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-input.ts 4 src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts -1 src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.ts 2 src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-wheel.ts 3 src/renderer/src/components/browser-pane/workspace-doc/doc-preview-directory-access.tsx 1 src/renderer/src/components/browser-pane/workspace-doc/doc-preview-overflow-menu.tsx diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx index 471f1f4725c..e223b76fedf 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx @@ -58,7 +58,10 @@ vi.mock('../stream-remote/use-remote-browser-page-lifecycle', () => ({ useRemoteBrowserPageLifecycle: () => ({ lifecycle: { session: { - ensureRemotePage: mocks.ensureRemotePage, + resolveNavigationPage: mocks.ensureRemotePage, + invalidateTabInfoReads: vi.fn(), + setPageLoading: vi.fn(), + refreshTabInfo: vi.fn(async () => null), scheduleTabInfoRefresh: vi.fn() }, tokens: {} @@ -575,7 +578,6 @@ describe.each([{ tree: 'under StrictMode', strict: true }])( adoptOntoServer() }) - expect(mocks.ensureRemotePage).toHaveBeenCalledTimes(1) expect(mocks.callRuntimeRpc).toHaveBeenCalledWith( expect.objectContaining({ environmentId: ENVIRONMENT_ID }), 'browser.goto', diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts b/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts index 6bed75438f0..f9be89d6fc1 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts @@ -8,6 +8,7 @@ import type { } from '../../../../../shared/browser/element-grab/browser-grab-types' import type { BrowserContextMenuRequestedEvent } from '../../../../../shared/browser/guest-lifecycle/browser-guest-events' import type { BrowserPage as BrowserPageState } from '../../../../../shared/browser-workspace-types' +import type { BrowserPageLoadingOwner } from '@/lib/browser/browser-page-loading-ownership' import type { GrabModeHook } from '../annotate/useGrabMode' import type { BrowserOverlayViewport } from './browser-annotation-geometry' @@ -18,6 +19,12 @@ export type BrowserTabPageState = Partial< > > +export type BrowserPageStateWriter = ( + pageId: string, + updates: BrowserTabPageState, + loadingOwner?: BrowserPageLoadingOwner +) => void + export type BrowserPageUrlSetter = ( tabId: string, url: string, diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.ts index 357ca71570c..dbc80cd7d9a 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.ts @@ -57,7 +57,7 @@ export const WHEEL_DELTA_LINE = 1 export const WHEEL_DELTA_PAGE = 2 export type RemoteBrowserStreamBridge = { - applyTabInfo: (tab: Pick) => void + applyTabInfo: (tab: BrowserTabInfo) => void clearFrame: () => void handleFrameBytes: (token: RemoteBrowserStreamToken, bytes: Uint8Array) => void closeMissingRemotePage: (remotePageId: string | null) => void diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-loading.test.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-loading.test.ts new file mode 100644 index 00000000000..ae01865cb02 --- /dev/null +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-loading.test.ts @@ -0,0 +1,240 @@ +// @vitest-environment happy-dom +import { act, cleanup } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { applyWebSessionTabsSnapshot } from '@/runtime/web-session-tabs-sync/snapshot-api' +import { recordBrowserInitializationReceipt } from '@/runtime/web-session-tabs-sync/browser-initialization-presentation' +import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-types' +import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +import type { BrowserTabInfo } from '../../../../../shared/browser/runtime/runtime-browser-contracts' +import { + currentPage, + deferred, + failedTab, + renderNavigation, + page +} from './remote-browser-page-navigation.test-fixture' + +vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: vi.fn() })) +vi.mock('@/runtime/browser/client-hosting/browser-client-host-identity', () => ({ + readBrowserClientHostId: () => 'loading-client' +})) +beforeEach(() => vi.mocked(callRuntimeRpc).mockReset()) +afterEach(cleanup) + +function applyNativeLoading(loading: boolean, pendingOnClient = false): void { + const snapshot: RuntimeMobileSessionTabsResult = { + worktree: 'worktree-a', + publicationEpoch: 'loading-test', + snapshotVersion: pendingOnClient ? 2 : 1, + activeTabType: 'browser', + activeTabId: 'host-tab', + activeGroupId: 'host-group', + tabs: [ + { + type: 'browser', + id: 'host-tab', + browserWorkspaceId: 'workspace-a', + browserPageId: 'remote-page-a', + url: 'about:blank', + title: 'New Tab', + loading, + canGoBack: false, + canGoForward: false, + isActive: true, + loadError: null, + certificateFailure: null, + ...(pendingOnClient + ? { + initializationState: 'pending', + placement: { + kind: 'client', + browserHostClientId: 'loading-client', + browserHostGeneration: 1, + pageHostGeneration: 0 + } + } + : {}) + } + ] + } + if (pendingOnClient) { + recordBrowserInitializationReceipt('environment-a', snapshot, 2) + } + useAppStore.setState((state) => + applyWebSessionTabsSnapshot(state, snapshot, 'environment-a', 100) + ) +} + +describe('remote command loading ownership', () => { + it.each([ + ['synthetic', true, false], + ['explicit', true, true], + ['native', true, true], + ['native', false, true] + ] as const)( + 'settles only %s loading after local updates=%s', + async (owner, edit, expectedLoading) => { + const { result, busy } = renderNavigation(1, 'mailto:help@example.test') + act(() => applyNativeLoading(false)) + const read = deferred<{ tab: BrowserTabInfo }>() + vi.mocked(callRuntimeRpc).mockImplementation(async (_target, method) => { + if (method === 'browser.reload') { + return { url: 'about:blank', title: 'New Tab' } + } + if (method === 'browser.tabShow') { + return read.promise + } + return undefined + }) + let command!: Promise + await act(async () => { + command = result.current.runRemoteNavigation('browser.reload') + }) + expect(currentPage().loading).toBe(true) + const before = useAppStore.getState() + const changed = vi.fn() + const unsubscribe = useAppStore.subscribe(changed) + act(() => { + if (owner === 'native') { + applyNativeLoading(true) + } + if (owner === 'explicit') { + useAppStore.getState().updateBrowserPageState('page-a', { loading: true }) + } + }) + unsubscribe() + expect(useAppStore.getState().browserPagesByWorkspace).toBe(before.browserPagesByWorkspace) + expect(useAppStore.getState().browserTabsByWorktree).toBe(before.browserTabsByWorktree) + expect(changed).not.toHaveBeenCalled() + if (edit) { + act(() => { + result.current.submitAddressBar() + useAppStore.getState().setBrowserPageViewportPreset('page-a', 'mobile-s') + }) + expect(currentPage().loadError).toMatchObject({ + code: 0, + validatedUrl: 'mailto:help@example.test' + }) + } + await act(async () => { + read.resolve({ tab: { ...failedTab('stale'), title: 'Stale result' } }) + await command + }) + expect(currentPage().loading).toBe(expectedLoading) + expect(currentPage().title).toBe('New Tab') + expect(currentPage().url).toBe('about:blank') + expect(busy).toHaveBeenLastCalledWith(false) + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + if (edit) { + expect(currentPage().loadError).toMatchObject({ + code: 0, + validatedUrl: 'mailto:help@example.test' + }) + expect(currentPage().viewportPresetId).toBe('mobile-s') + } + } + ) + + it('keeps initialization loading when an older remote command retires', async () => { + const { session, tokens } = renderNavigation() + act(() => applyNativeLoading(false)) + const token = tokens.createOperationToken('remote-page-a')! + act(() => session.setPageLoading(token, true, useAppStore.getState().updateBrowserPageState)) + const read = deferred<{ tab: BrowserTabInfo }>() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(read.promise) + const pending = session.refreshTabInfo(token) + act(() => applyNativeLoading(true, true)) + await act(async () => { + read.resolve({ tab: failedTab('stale') }) + expect(await pending).toBeNull() + session.setPageLoading(token, false, useAppStore.getState().updateBrowserPageState) + }) + expect(currentPage().loading).toBe(true) + expect(currentPage().loadError).toBeNull() + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + }) + + it('discharges synthetic loading across external ABA without admitting the old read', async () => { + const { session, tokens } = renderNavigation() + const token = tokens.createOperationToken('remote-page-a')! + act(() => session.setPageLoading(token, true, useAppStore.getState().updateBrowserPageState)) + const read = deferred<{ tab: BrowserTabInfo }>() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(read.promise) + const pending = session.refreshTabInfo(token) + act(() => { + useAppStore.getState().updateBrowserPageState('page-a', { loadError: failedTab().loadError }) + useAppStore.getState().updateBrowserPageState('page-a', { loadError: null }) + session.setPageLoading(token, false, useAppStore.getState().updateBrowserPageState) + }) + await act(async () => { + read.resolve({ tab: failedTab('stale') }) + expect(await pending).toBeNull() + }) + expect(currentPage().loading).toBe(false) + expect(currentPage().loadError).toBeNull() + expect(currentPage().url).toBe('about:blank') + }) + + it('does not claim an explicit equal loading write from a synchronous store subscriber', () => { + const { session, tokens } = renderNavigation() + const token = tokens.createOperationToken('remote-page-a')! + const unsubscribe = useAppStore.subscribe(() => { + useAppStore.getState().updateBrowserPageState('page-a', { loading: true }) + }) + act(() => session.setPageLoading(token, true, useAppStore.getState().updateBrowserPageState)) + unsubscribe() + act(() => session.setPageLoading(token, false, useAppStore.getState().updateBrowserPageState)) + expect(currentPage().loading).toBe(true) + }) + + it.each([100, 1000])('native takeover visits no unrelated records at N=%s', async (count) => { + const { session, tokens } = renderNavigation() + act(() => applyNativeLoading(false)) + const token = tokens.createOperationToken('remote-page-a')! + act(() => session.setPageLoading(token, true, useAppStore.getState().updateBrowserPageState)) + const read = deferred<{ tab: BrowserTabInfo }>() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(read.promise) + const pending = session.refreshTabInfo(token) + const unrelated = Object.fromEntries( + Array.from({ length: count }, (_, index) => { + const workspaceId = `unrelated-${index}` + return [workspaceId, [{ ...page(`other-${index}`), workspaceId, worktreeId: 'other' }]] + }) + ) + let enumerations = 0 + let unrelatedReads = 0 + const pages = new Proxy( + { ...useAppStore.getState().browserPagesByWorkspace, ...unrelated }, + { + ownKeys(target) { + enumerations += 1 + return Reflect.ownKeys(target) + }, + get(target, key, receiver) { + if (typeof key === 'string' && key.startsWith('unrelated-')) { + unrelatedReads += 1 + } + // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy must forward record access unchanged while counting unrelated lookups. + return Reflect.get(target, key, receiver) + } + } + ) + useAppStore.setState({ browserPagesByWorkspace: pages }) + const changed = vi.fn() + const unsubscribe = useAppStore.subscribe(changed) + act(() => applyNativeLoading(true)) + unsubscribe() + expect(enumerations).toBe(0) + expect(unrelatedReads).toBe(0) + expect(useAppStore.getState().browserPagesByWorkspace).toBe(pages) + expect(changed).not.toHaveBeenCalled() + await act(async () => { + read.resolve({ tab: failedTab('stale') }) + expect(await pending).toBeNull() + session.setPageLoading(token, false, useAppStore.getState().updateBrowserPageState) + }) + expect(currentPage().loading).toBe(true) + expect(currentPage().loadError).toBeNull() + }) +}) diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation-command.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation-command.ts new file mode 100644 index 00000000000..55a2453f32f --- /dev/null +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation-command.ts @@ -0,0 +1,166 @@ +import type { useRemoteBrowserPageNavigation } from './use-remote-browser-page-navigation' +import type { + BrowserBackResult, + BrowserGotoResult, + BrowserReloadResult, + BrowserTabInfo +} from '../../../../../shared/browser/runtime/runtime-browser-contracts' +import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +import { redactKagiSessionToken } from '../../../../../shared/browser-url' +import { deferBrowserPageNavigation } from '../navigate/browser-page-deferred-navigation' +import { isRemoteBrowserPageMissingError } from './remote-browser-stream-errors' + +type RemoteBrowserNavigationCommandOptions = Pick< + Parameters[0], + | 'browserTab' + | 'stagedPage' + | 'lifecycle' + | 'runtimeWorktree' + | 'runtimeTarget' + | 'createRemoteOperationToken' + | 'isCurrentRemoteOperationToken' + | 'closeMissingRemotePage' + | 'onUpdatePageState' + | 'setPaneNotice' + | 'setPaneBusy' +> & { + navigationSequence: { current: number } + applyRemoteTabMetadata: (tab: Pick) => void +} + +export async function runRemoteBrowserNavigationCommand( + { + browserTab, + stagedPage, + lifecycle, + runtimeWorktree, + runtimeTarget, + createRemoteOperationToken, + isCurrentRemoteOperationToken, + closeMissingRemotePage, + onUpdatePageState, + setPaneNotice, + setPaneBusy, + navigationSequence, + applyRemoteTabMetadata + }: RemoteBrowserNavigationCommandOptions, + method: 'browser.goto' | 'browser.back' | 'browser.forward' | 'browser.reload', + url?: string +): Promise { + const target = runtimeTarget() + if (!target) { + return + } + if (stagedPage) { + // No staged host page exists yet: park goto until adoption; history/reload cannot replay against an uncreated page. + if (method === 'browser.goto' && url) { + deferBrowserPageNavigation(browserTab.id, url) + onUpdatePageState(browserTab.id, { loading: true, loadError: null }) + } + return + } + const operationToken = createRemoteOperationToken() + if (!operationToken || !isCurrentRemoteOperationToken(operationToken)) { + return + } + const sequence = ++navigationSequence.current + lifecycle.session.invalidateTabInfoReads() + let pageId: string | null = null + const ownsAction = (): boolean => + sequence === navigationSequence.current && + isCurrentRemoteOperationToken({ ...operationToken, remotePageId: pageId }) + const reportFailure = (error: unknown): void => { + if (!ownsAction()) { + return + } + if (isRemoteBrowserPageMissingError(error)) { + closeMissingRemotePage(pageId) + return + } + const message = error instanceof Error ? error.message : 'Remote browser command failed.' + setPaneNotice({ kind: 'consequence', text: message }) + // Why: goto results carry no load error, but the rejection keeps Electron's "ERR_NAME (-code)" text. + const netError = /\b(ERR_[A-Z_]+) \((-\d+)\)/.exec(message) + onUpdatePageState(browserTab.id, { + loading: false, + // Why: validatedUrl is persisted, so redact the Kagi session token like the main-process failure path does. + loadError: { + code: netError ? Number(netError[2]) : 0, + description: netError ? netError[1] : message, + validatedUrl: redactKagiSessionToken(url ?? browserTab.url) + } + }) + } + setPaneBusy(true) + setPaneNotice(null) + // A standing failure stays visible until the native outcome is observed. + lifecycle.session.setPageLoading(operationToken, true, onUpdatePageState) + try { + pageId = await lifecycle.session.resolveNavigationPage(operationToken) + if (!pageId || !ownsAction()) { + return + } + const pageToken = { ...operationToken, remotePageId: pageId } + const params = + method === 'browser.goto' + ? { worktree: runtimeWorktree, page: pageId, url: url ?? 'about:blank' } + : { worktree: runtimeWorktree, page: pageId } + let commandError: unknown + let result: BrowserGotoResult | BrowserBackResult | BrowserReloadResult | undefined + try { + result = await callRuntimeRpc( + target, + method, + params, + { timeoutMs: 30_000, suppressFeatureInteraction: true } + ) + } catch (error) { + if (isRemoteBrowserPageMissingError(error)) { + throw error + } + commandError = error + } + if (!ownsAction()) { + return + } + await lifecycle.session.refreshTabInfo(pageToken, { + onApplied: (tab) => { + if (!ownsAction() || !commandError || tab.loadError) { + return + } + if (tab.loadError === undefined) { + reportFailure(commandError) + } else { + setPaneNotice({ + kind: 'consequence', + text: + commandError instanceof Error + ? commandError.message + : 'Remote browser command failed.' + }) + } + }, + onError: (error) => { + if (!ownsAction()) { + return + } + if (isRemoteBrowserPageMissingError(error)) { + reportFailure(error) + } else if (result) { + if (!result.url.startsWith('chrome-error:')) { + applyRemoteTabMetadata(result) + } + } else { + reportFailure(commandError ?? error) + } + } + }) + } catch (error) { + reportFailure(error) + } finally { + if (ownsAction()) { + lifecycle.session.setPageLoading(operationToken, false, onUpdatePageState) + setPaneBusy(false) + } + } +} diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation.test-fixture.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation.test-fixture.ts new file mode 100644 index 00000000000..bc069c7fe81 --- /dev/null +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-navigation.test-fixture.ts @@ -0,0 +1,184 @@ +import { renderHook, type RenderHookResult } from '@testing-library/react' +import { expect, vi, type Mock } from 'vitest' +import { useAppStore } from '@/store' +import { annotateBrowserPageHandles } from '@/store/slices/browser/hosts/browser-initialization-presentation-ownership' +import { findPage } from '@/store/slices/browser/pages/browser-page-records' +import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +import type { BrowserPage } from '../../../../../shared/browser-workspace-types' +import type { BrowserTabInfo } from '../../../../../shared/browser/runtime/runtime-browser-contracts' +import { useRemoteBrowserPageNavigation } from './use-remote-browser-page-navigation' +import { + readRemoteBrowserPage, + readRemoteBrowserPageObservation +} from './remote-browser-page-observation' +import { RemoteBrowserStreamLifecycle } from './remote-browser-stream-lifecycle' +import type { RemoteBrowserScreencastSubscribe } from './remote-browser-screencast-subscription' + +type NavigationOptions = Parameters[0] +type NavigationFixture = RenderHookResult< + ReturnType, + unknown +> & { + lifecycle: RemoteBrowserStreamLifecycle + subscribe: Mock + session: RemoteBrowserStreamLifecycle['session'] + tokens: RemoteBrowserStreamLifecycle['tokens'] + identity: { mounted: boolean; active: boolean; environmentId: string } + busy: Mock + notice: Mock + closeMissing: Mock +} + +export function page(id = 'page-a'): BrowserPage { + return { + id, + workspaceId: 'workspace-a', + worktreeId: 'worktree-a', + url: 'about:blank', + title: 'New Tab', + loading: false, + faviconUrl: null, + canGoBack: false, + canGoForward: false, + loadError: null, + createdAt: 1 + } +} + +export function failedTab(challengeId = 'challenge-x'): BrowserTabInfo { + return { + browserPageId: 'remote-page-a', + index: 0, + active: true, + url: 'https://selfsigned.test/', + title: 'TLS', + loadError: { + code: -202, + description: 'ERR_CERT_AUTHORITY_INVALID', + validatedUrl: 'https://selfsigned.test/' + }, + certificateFailure: { + challengeId, + browserPageId: 'remote-page-a', + errorCode: -202, + error: 'ERR_CERT_AUTHORITY_INVALID', + origin: 'https://selfsigned.test', + displayHost: 'selfsigned.test', + canProceed: true, + observedAt: 1 + } + } +} + +export function deferred() { + let resolve!: (value: T) => void + let reject!: (error: unknown) => void + const promise = new Promise((done, fail) => { + resolve = done + reject = fail + }) + return { promise, resolve, reject } +} + +export function renderNavigation(count = 1, addressBarValue = 'about:blank'): NavigationFixture { + const pages = Array.from({ length: count }, (_, index) => + page(index ? `page-${index}` : 'page-a') + ) + const first = pages[0] + useAppStore.setState({ + browserPagesByWorkspace: { 'workspace-a': pages }, + browserTabsByWorktree: { + 'worktree-a': [ + { + ...first, + id: 'workspace-a', + activePageId: 'page-a', + pageIds: pages.map((entry) => entry.id) + } + ] + }, + unifiedTabsByWorktree: {}, + browserCertificateFailuresByPageId: {}, + browserUrlHistory: [], + remoteBrowserPageHandlesByPageId: annotateBrowserPageHandles( + { 'page-a': { environmentId: 'environment-a', remotePageId: 'remote-page-a' } }, + ['page-a'] + ) + }) + const identity = { mounted: true, active: true, environmentId: 'environment-a' } + const paneIdentity = { + isMounted: () => identity.mounted, + isActive: () => identity.active, + getTabId: () => 'page-a', + getEnvironmentId: () => identity.environmentId, + browserPageExists: (pageId) => + Boolean(readRemoteBrowserPage(useAppStore.getState(), 'workspace-a', pageId)) + } + let project: (tab: BrowserTabInfo) => void = () => {} + const subscribe = vi.fn(async () => ({ unsubscribe: vi.fn() })) + const lifecycle = new RemoteBrowserStreamLifecycle({ + identity: paneIdentity, + subscribeScreencast: subscribe, + askJavaScriptDialog: async () => null, + waitForViewportSize: async () => ({ width: 800, height: 600 }), + readViewportSize: () => ({ width: 800, height: 600 }), + syncViewport: async () => {}, + getDeviceScaleFactor: () => 1, + setStatus: vi.fn(), + clearFrame: vi.fn(), + handleFrameBytes: vi.fn(), + callRpc: callRuntimeRpc, + getWorktreeSelector: () => 'worktree-a', + getCurrentUrl: () => currentPage().url, + readCurrentObservation: () => + readRemoteBrowserPageObservation(useAppStore.getState(), 'workspace-a', 'page-a'), + readStoredHandle: () => ({ environmentId: 'environment-a', remotePageId: 'remote-page-a' }), + writeStoredHandle: vi.fn(), + removeStoredHandle: vi.fn(), + applyTabInfo: (tab) => project(tab), + closeMissingRemotePage: vi.fn() + }) + const { session, tokens } = lifecycle + tokens.setRemotePage('remote-page-a') + const closeMissing = vi.fn() + const busy = vi.fn() + const notice = vi.fn() + const hook = renderHook(() => + useRemoteBrowserPageNavigation({ + browserTab: first, + stagedPage: false, + addressBarValue, + setAddressBarValueFromPage: vi.fn(), + lifecycle, + runtimeWorktree: 'worktree-a', + runtimeTarget: () => ({ kind: 'environment', environmentId: identity.environmentId }), + createRemoteOperationToken: () => tokens.createOperationToken(), + isCurrentRemoteOperationToken: (token) => tokens.isCurrent(token), + closeMissingRemotePage: closeMissing, + onSetUrl: useAppStore.getState().setBrowserPageUrl, + onUpdatePageState: useAppStore.getState().updateBrowserPageState, + setPaneNotice: notice, + setPaneBusy: busy + }) + ) + project = (tab) => hook.result.current.applyRemoteTabInfo(tab) + return { ...hook, lifecycle, subscribe, session, tokens, identity, busy, notice, closeMissing } +} + +export function currentPage(): BrowserPage { + return findPage(useAppStore.getState().browserPagesByWorkspace, 'page-a')! +} + +export function expectPending(challengeId = 'challenge-x') { + expect(currentPage().url).toBe('https://selfsigned.test/') + expect(currentPage().loadError).toEqual({ + code: -202, + description: 'ERR_CERT_AUTHORITY_INVALID', + validatedUrl: 'https://selfsigned.test/' + }) + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toMatchObject({ + challengeId, + browserPageId: 'remote-page-a', + canProceed: true + }) +} diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-observation.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-observation.ts new file mode 100644 index 00000000000..890bd6f42ca --- /dev/null +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-observation.ts @@ -0,0 +1,27 @@ +import type { + BrowserPage, + BrowserCertificateFailure +} from '../../../../../shared/browser-workspace-types' +import { readBrowserPageLoadingOwner } from '@/lib/browser/browser-page-loading-ownership' + +type BrowserObservationState = { + browserPagesByWorkspace: Record + browserCertificateFailuresByPageId: Record +} + +export function readRemoteBrowserPage( + state: BrowserObservationState, + workspaceId: string, + pageId: string +): BrowserPage | undefined { + return state.browserPagesByWorkspace[workspaceId]?.find((page) => page.id === pageId) +} + +export function readRemoteBrowserPageObservation( + state: BrowserObservationState, + workspaceId: string, + pageId: string +): readonly unknown[] { + const page = readRemoteBrowserPage(state, workspaceId, pageId) + return [page, state.browserCertificateFailuresByPageId[pageId], readBrowserPageLoadingOwner(page)] +} diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-pane.tsx b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-pane.tsx index 893eda43de7..946c053e580 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-pane.tsx +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-pane.tsx @@ -21,7 +21,7 @@ import { import type { BrowserChromeShortcutScope, BrowserPageUrlSetter, - BrowserTabPageState + BrowserPageStateWriter } from '../describe-page/browser-page-types' import type { RemoteBrowserPaneNotice } from './remote-browser-page-input-model' import { useRemoteBrowserPageLifecycle } from './use-remote-browser-page-lifecycle' @@ -57,10 +57,9 @@ export function RemoteBrowserPagePane({ worktreeId: string isActive: boolean chromeShortcutScope: BrowserChromeShortcutScope - onUpdatePageState: (tabId: string, updates: BrowserTabPageState) => void + onUpdatePageState: BrowserPageStateWriter onSetUrl: BrowserPageUrlSetter }): React.JSX.Element { - const activeRuntimeEnvironmentId = runtimeEnvironmentId const addressBarInputRef = useRef(null) const imageRef = useRef(null) const remoteViewportRef = useRef(null) @@ -94,16 +93,15 @@ export function RemoteBrowserPagePane({ // Why: runtimes predating browser.certificate-trust.v1 can't honor a proceed request, so hide "Proceed Anyway" until support is advertised. const [remoteCertificateTrustSupported, setRemoteCertificateTrustSupported] = useState(false) - const remoteCertificateEnvironmentId = remotePageHandle?.environmentId ?? null const certificateChallengeId = certificateFailure?.challengeId ?? null useEffect(() => { - if (!remoteCertificateEnvironmentId || !certificateChallengeId) { + if (!remotePageHandle?.environmentId || !certificateChallengeId) { setRemoteCertificateTrustSupported(false) return } let cancelled = false void runtimeEnvironmentSupportsCapability( - remoteCertificateEnvironmentId, + remotePageHandle?.environmentId, BROWSER_CERTIFICATE_TRUST_RUNTIME_CAPABILITY ) .then((supported) => { @@ -119,7 +117,7 @@ export function RemoteBrowserPagePane({ return () => { cancelled = true } - }, [remoteCertificateEnvironmentId, certificateChallengeId]) + }, [remotePageHandle?.environmentId, certificateChallengeId]) const { enqueueRemoteInput, @@ -154,7 +152,7 @@ export function RemoteBrowserPagePane({ } = useRemoteBrowserPageLifecycle({ browserTab, worktreeId, - activeRuntimeEnvironmentId, + activeRuntimeEnvironmentId: runtimeEnvironmentId, isActive, setPaneNotice, setPaneBusy, @@ -174,6 +172,7 @@ export function RemoteBrowserPagePane({ const { applyRemoteTabInfo, + prepareCertificateProceed, scheduleRemoteTabInfoRefresh, runRemoteNavigation, navigateToUrl, @@ -224,7 +223,7 @@ export function RemoteBrowserPagePane({ }, [hasStreamFrame]) const { reconnectRemoteStream } = useRemoteBrowserPageStream({ - activeRuntimeEnvironmentId, + activeRuntimeEnvironmentId: runtimeEnvironmentId, browserPageId: browserTab.id, isActive, lifecycle, @@ -405,7 +404,7 @@ export function RemoteBrowserPagePane({ remoteCertificateTrustSupported={remoteCertificateTrustSupported} certificateFailure={certificateFailure} remotePageHandle={remotePageHandle} - activeRuntimeEnvironmentId={activeRuntimeEnvironmentId} + activeRuntimeEnvironmentId={runtimeEnvironmentId} worktreeId={worktreeId} runtimeWorktree={runtimeWorktree} runtimeTarget={runtimeTarget} @@ -413,6 +412,7 @@ export function RemoteBrowserPagePane({ onGoto={(url) => runRemoteNavigation('browser.goto', url)} onNavigateToUrl={navigateToUrl} onReconnect={reconnectRemoteStream} + onBeforeProceedCertificate={prepareCertificateProceed} handleRemotePointerDown={handleRemotePointerDown} handleRemotePointerUp={handleRemotePointerUp} handleRemoteContextMenu={handleRemoteContextMenu} diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts index edf85ba93ab..3c522a48d7c 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts @@ -53,6 +53,7 @@ function setup(args: { show: ShowReply; switchOn?: boolean; onShow?: () => void tokens, callRpc, getWorktreeSelector: () => 'id:wt-1', + readCurrentObservation: () => [], getCurrentUrl: () => 'about:blank', readStoredHandle: () => stored, writeStoredHandle: (handle) => { diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts index d4e9b579c57..a3fafbb93d2 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts @@ -1,4 +1,6 @@ import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' +import type { BrowserPageLoadingOwner } from '@/lib/browser/browser-page-loading-ownership' +import type { BrowserPageStateWriter } from '../describe-page/browser-page-types' import '../../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' @@ -26,20 +28,148 @@ export type RemoteBrowserPageSessionDeps = { callRpc: RemoteBrowserRpcCall getWorktreeSelector(): string getCurrentUrl(): string + readCurrentObservation(): readonly unknown[] readStoredHandle(): RemoteBrowserPageHandle | null writeStoredHandle(handle: RemoteBrowserPageHandle): void removeStoredHandle(remotePageId: string): void - applyTabInfo(tab: Pick): void + applyTabInfo(tab: BrowserTabInfo): void closeMissingRemotePage(remotePageId: string | null): void } // Keep runtime page identity and post-input refresh separate from screencast ownership. export class RemoteBrowserPageSession { private tabRefreshTimer: ReturnType | null = null + private observationGeneration = 0 + private nextObservationId = 0 + private appliedObservationId = 0 + private observationAnchor: readonly unknown[] | null = null + private loadingOwner: BrowserPageLoadingOwner | null = null constructor(private readonly deps: RemoteBrowserPageSessionDeps) {} - async fetchTabInfo(token: RemoteBrowserOperationToken): Promise { + invalidateTabInfoReads(): void { + this.observationGeneration += 1 + this.cancelTabInfoRefresh() + } + + private observeExternalChanges(): readonly unknown[] { + const current = this.deps.readCurrentObservation() + if ( + this.observationAnchor && + (this.observationAnchor.length !== current.length || + this.observationAnchor.some((value, index) => value !== current[index])) + ) { + this.observationGeneration += 1 + if (this.loadingOwner && current[2] !== this.loadingOwner) { + this.loadingOwner.active = false + this.loadingOwner = null + } + } + this.observationAnchor = current + return current + } + + private applyObservedWrite(write: () => void): void { + try { + write() + } finally { + this.observationAnchor = this.deps.readCurrentObservation() + } + } + + setPageLoading( + token: RemoteBrowserOperationToken, + loading: boolean, + update: BrowserPageStateWriter + ): void { + if (!this.deps.tokens.isCurrent(token)) { + return + } + const observation = this.observeExternalChanges() + if (!loading && (!this.loadingOwner || observation[2] !== this.loadingOwner)) { + return + } + const owner = loading ? { active: true } : undefined + this.loadingOwner = owner ?? null + this.applyObservedWrite(() => update(token.tabId, { loading }, owner)) + } + + captureTabInfoAdmission(token: RemoteBrowserOperationToken): { + isCurrent: () => boolean + apply: (tab: BrowserTabInfo, onApplied?: (tab: BrowserTabInfo) => void) => boolean + } { + const id = ++this.nextObservationId + const active = this.deps.tokens.isCurrent(token) + if (active) { + this.observeExternalChanges() + } + const generation = this.observationGeneration + const isCurrent = (): boolean => { + if ( + generation !== this.observationGeneration || + !active || + id < this.appliedObservationId || + !this.deps.tokens.isCurrent(token) + ) { + return false + } + this.observeExternalChanges() + return generation === this.observationGeneration + } + return { + isCurrent, + apply: (tab, onApplied) => { + if (!isCurrent()) { + return false + } + this.applyObservedWrite(() => { + this.deps.applyTabInfo(tab) + this.appliedObservationId = id + this.loadingOwner = null + onApplied?.(tab) + }) + return true + } + } + } + + async refreshTabInfo( + token: RemoteBrowserOperationToken, + callbacks: { + onApplied?: (tab: BrowserTabInfo) => void + onError?: (error: unknown) => void + } = {} + ): Promise | null> { + const admission = this.captureTabInfoAdmission(token) + let tab: BrowserTabInfo | null + try { + tab = await this.readTabInfo(token) + } catch (error) { + if (!admission.isCurrent()) { + return null + } + if (callbacks.onError) { + this.applyObservedWrite(() => callbacks.onError?.(error)) + return null + } + throw error + } + return tab && admission.apply(tab, callbacks.onApplied) ? { loadError: tab.loadError } : null + } + + async resolveNavigationPage(token: RemoteBrowserOperationToken): Promise { + if (!this.deps.tokens.isCurrent(token)) { + return null + } + const handle = this.deps.readStoredHandle() + if (handle?.environmentId === token.environmentId) { + this.deps.tokens.setRemotePage(handle.remotePageId) + return handle.remotePageId + } + return this.ensureRemotePage(token) + } + + private async readTabInfo(token: RemoteBrowserOperationToken): Promise { if (!this.deps.tokens.isCurrent(token) || !token.remotePageId) { return null } @@ -70,7 +200,7 @@ export class RemoteBrowserPageSession { } tokens.setRemotePage(existingHandle.remotePageId) try { - const cachedTab = await this.fetchTabInfo({ + const cachedTab = await this.readTabInfo({ ...token, remotePageId: existingHandle.remotePageId }) @@ -101,17 +231,13 @@ export class RemoteBrowserPageSession { if (!tokens.isCurrent(token)) { return } - void this.fetchTabInfo(token) - .then((tab) => { - if (tab && tokens.isCurrent(token)) { - this.deps.applyTabInfo(tab) - } - }) - .catch((error: unknown) => { - if (tokens.isCurrent(token) && isRemoteBrowserPageMissingError(error)) { + void this.refreshTabInfo(token, { + onError: (error) => { + if (isRemoteBrowserPageMissingError(error)) { this.deps.closeMissingRemotePage(token.remotePageId) } - }) + } + }) }, delayMs) } @@ -137,7 +263,7 @@ export class RemoteBrowserPageSession { tokens.setRemotePage(provisional) try { // tabShow also starts a saved page the host has not opened yet. - if (!(await this.fetchTabInfo(probe)) || !tokens.isCurrent(probe)) { + if (!(await this.readTabInfo(probe)) || !tokens.isCurrent(probe)) { release() return null } diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-viewport.tsx b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-viewport.tsx index 5b446b726b0..385f2f304f5 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-viewport.tsx +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-viewport.tsx @@ -46,6 +46,7 @@ export function RemoteBrowserPageViewport({ onGoto, onNavigateToUrl, onReconnect, + onBeforeProceedCertificate, handleRemotePointerDown, handleRemotePointerUp, handleRemoteContextMenu, @@ -73,6 +74,7 @@ export function RemoteBrowserPageViewport({ /** The address bar's submit path, which also parks a URL typed before the host page exists. */ onNavigateToUrl: (url: string) => void onReconnect: () => void + onBeforeProceedCertificate: () => void handleRemotePointerDown: (event: React.PointerEvent) => void handleRemotePointerUp: (event: React.PointerEvent) => void handleRemoteContextMenu: (event: React.MouseEvent) => void @@ -180,6 +182,7 @@ export function RemoteBrowserPageViewport({ ) { return { ok: false, reason: 'missing' } } + onBeforeProceedCertificate() return callRuntimeRpc( target, 'browser.certificate.proceed', diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle-test-harness.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle-test-harness.ts index c2052eb4fa9..2b281335e7c 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle-test-harness.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle-test-harness.ts @@ -190,6 +190,7 @@ export function createHarness() { callRpc, subscribeScreencast, getWorktreeSelector: () => 'worktree:wt-1', + readCurrentObservation: () => [], getCurrentUrl: () => 'https://example.test/', readStoredHandle: () => storedHandle, writeStoredHandle: (handle) => { diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts index 499a965110b..9ad4bcada40 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts @@ -15,6 +15,35 @@ describe('RemoteBrowserStreamLifecycle', () => { vi.useRealTimers() }) + it('applies current ready metadata after open and a viewport restart', async () => { + const harness = createHarness() + harness.lifecycle.open() + await settle() + const before = harness.appliedTitles.length + harness.streams[0].emitReady() + await settle() + expect(harness.appliedTitles.slice(before)).toEqual(['Example']) + harness.setViewportSize({ width: 1400, height: 900 }) + harness.lifecycle.restartForViewport('page-1') + await settle() + const beforeRestartReady = harness.appliedTitles.length + harness.streams.at(-1)!.emitReady() + await settle() + expect(harness.appliedTitles.slice(beforeRestartReady)).toEqual(['Example']) + }) + + it('keeps a stream live without applying ready metadata superseded by navigation', async () => { + const harness = createHarness() + harness.lifecycle.open() + await settle() + const before = [...harness.appliedTitles] + harness.lifecycle.session.invalidateTabInfoReads() + harness.streams[0].emitReady() + await settle() + expect(harness.appliedTitles).toEqual(before) + expect(harness.currentStatusKind).toBe('live') + }) + it("asks once about the streamed page's dialog and answers it on the host", async () => { const harness = createHarness() await openStreamAndConfirmReady(harness) diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.ts index fb3c40ce406..0232af0439e 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.ts @@ -1,4 +1,3 @@ -import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import type { RuntimeStatus } from '../../../../../shared/runtime-types' import { RemoteBrowserPageSession } from './remote-browser-page-session' import { RemoteBrowserJavaScriptDialog } from './remote-browser-javascript-dialog' @@ -22,6 +21,7 @@ import { resolveRemoteBrowserStreamFailure } from './remote-browser-stream-errors' import { + toOperationToken, areRemoteViewportSizesNear, RemoteBrowserOperationTokens, type RemoteBrowserStreamSubscription, @@ -74,6 +74,25 @@ export class RemoteBrowserStreamLifecycle { this.setStatus(REMOTE_BROWSER_STREAM_IDLE) return () => {} } + const handleOpenFailure = (error: unknown): void => { + if (cancelled) { + return + } + if (isRemoteBrowserPageMissingError(error)) { + deps.closeMissingRemotePage(tokens.remotePage) + return + } + const failure = resolveRemoteBrowserStreamFailure(error, 'opening') + if (failure.logRawError) { + console.warn('[browser-pane] remote browser failed to open:', error) + } + // The host can close before subscribe rejects; preserve the newer armed restart’s ownership of status. + if (this.restartScheduler.isScheduled) { + return + } + // An initial open has no retry budget; preserve manual recovery. + this.setStatus(remoteBrowserStreamStopped(failure.message)) + } void this.session .ensureRemotePage(operationToken) .then(async (pageId) => { @@ -81,11 +100,14 @@ export class RemoteBrowserStreamLifecycle { return } const pageToken = { ...operationToken, remotePageId: pageId } - const tab = await this.session.fetchTabInfo(pageToken) - if (tab && !cancelled && tokens.isCurrent(pageToken)) { - deps.applyTabInfo(tab) - } - if (cancelled || !tokens.isCurrent(pageToken)) { + let readFailed = false + await this.session.refreshTabInfo(pageToken, { + onError: (error) => { + readFailed = true + handleOpenFailure(error) + } + }) + if (readFailed || cancelled || !tokens.isCurrent(pageToken)) { return } const subscription = await this.startStream(pageId) @@ -95,25 +117,7 @@ export class RemoteBrowserStreamLifecycle { } this.adoptSubscription(subscription) }) - .catch((error: unknown) => { - if (cancelled) { - return - } - if (isRemoteBrowserPageMissingError(error)) { - deps.closeMissingRemotePage(tokens.remotePage) - return - } - const failure = resolveRemoteBrowserStreamFailure(error, 'opening') - if (failure.logRawError) { - console.warn('[browser-pane] remote browser failed to open:', error) - } - // The host can close before subscribe rejects; preserve the newer armed restart’s ownership of status. - if (this.restartScheduler.isScheduled) { - return - } - // An initial open has no retry budget; preserve manual recovery. - this.setStatus(remoteBrowserStreamStopped(failure.message)) - }) + .catch(handleOpenFailure) return () => { cancelled = true this.retireInFlightWork()?.unsubscribe() @@ -216,10 +220,8 @@ export class RemoteBrowserStreamLifecycle { if (!operationToken || !tokens.isCurrent(operationToken)) { return null } - const target: RuntimeClientTarget = { - kind: 'environment', - environmentId: operationToken.environmentId - } + const { environmentId } = operationToken + const target = { kind: 'environment' as const, environmentId } const status = await deps.callRpc(target, 'status.get', undefined, { timeoutMs: 15_000 }) @@ -236,6 +238,7 @@ export class RemoteBrowserStreamLifecycle { } this.streamViewportSize = viewportSize const token = tokens.claimStreamToken(operationToken, pageId) + const admitsTabInfo = this.session.captureTabInfoAdmission(toOperationToken(token)) // Treat a silent host as a drop so it spends the same bounded retry budget. this.liveness.watch(() => { if (this.tokens.isCurrentStreamToken(token)) { @@ -258,7 +261,7 @@ export class RemoteBrowserStreamLifecycle { // Record uptime; only sustained streams earn a refill at close. Live status also clears healed notices. this.liveness.markReady() this.setStatus(REMOTE_BROWSER_STREAM_LIVE) - deps.applyTabInfo(event.tab) + admitsTabInfo.apply(event.tab) void deps.syncViewport(event.browserPageId).catch(() => {}) }, onEnded: () => this.handleStreamClosed(token, true), @@ -324,7 +327,6 @@ export class RemoteBrowserStreamLifecycle { tokens: this.tokens, session: this.session, setStatus: (status) => this.setStatus(status), - applyTabInfo: (tab) => this.deps.applyTabInfo(tab), closeMissingRemotePage: (remotePageId) => this.deps.closeMissingRemotePage(remotePageId), startStream: (pageId) => this.startStream(pageId), adoptSubscription: (subscription) => this.adoptSubscription(subscription) diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-attempt.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-attempt.ts index 415f1888538..6d365cf8f27 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-attempt.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-attempt.ts @@ -14,13 +14,11 @@ import { type RemoteBrowserStreamSubscription, type RemoteBrowserStreamToken } from './remote-browser-stream-tokens' -import type { BrowserTabInfo } from '../../../../../shared/browser/runtime/runtime-browser-contracts' export type RemoteBrowserStreamRestartAttemptDeps = { tokens: RemoteBrowserOperationTokens session: RemoteBrowserPageSession setStatus: (status: RemoteBrowserStreamStatus) => void - applyTabInfo: (tab: BrowserTabInfo) => void closeMissingRemotePage: (remotePageId: string) => void startStream: (pageId: string) => Promise adoptSubscription: (subscription: RemoteBrowserStreamSubscription) => void @@ -41,10 +39,7 @@ export function createRemoteBrowserStreamRestartAttempt( deps.setStatus(remoteBrowserStreamRetrying(lastNotice)) const operationToken = toOperationToken(token) try { - const tab = await deps.session.fetchTabInfo(operationToken).catch(() => null) - if (tab && tokens.isCurrentStreamOperation(token)) { - deps.applyTabInfo(tab) - } + await deps.session.refreshTabInfo(operationToken).catch(() => null) if (!tokens.isCurrentStreamOperation(token)) { return false } diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts index 0f4f6a42ca5..c390f3032aa 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts @@ -11,7 +11,6 @@ import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-t import { toRuntimeWorktreeSelector } from '@/runtime/rpc/targets/runtime-worktree-selector' import type { BrowserScreencastFrameMetadata } from '../../../../../shared/browser/screencast/browser-screencast-protocol' import type { BrowserPage as BrowserPageState } from '../../../../../shared/browser-workspace-types' -import { browserPageExists } from '../describe-page/browser-page-load-error' import { REMOTE_BROWSER_STREAM_IDLE, type RemoteBrowserStreamStatus @@ -23,6 +22,10 @@ import { type RemoteBrowserStreamBridge } from './remote-browser-page-input-model' import { subscribeRuntimeEnvironment } from '@/runtime/rpc/environment-revisions/runtime-environment-pairing-refresh' +import { + readRemoteBrowserPage, + readRemoteBrowserPageObservation +} from './remote-browser-page-observation' import { useConfirmationDialog } from '@/components/confirmation-dialog-context' import { javaScriptDialogPrompt } from '../browser-javascript-dialog-prompt' @@ -60,6 +63,7 @@ export function useRemoteBrowserPageLifecycle({ const pendingFrameDecodeRef = useRef(0) const mountedRef = useRef(true) const isActiveRef = useRef(isActive) + const currentWorkspaceIdRef = useRef(browserTab.workspaceId) const currentBrowserTabIdRef = useRef(browserTab.id) const currentBrowserTabUrlRef = useRef(browserTab.url) const runtimeWorktree = useMemo(() => toRuntimeWorktreeSelector(worktreeId), [worktreeId]) @@ -74,12 +78,20 @@ export function useRemoteBrowserPageLifecycle({ const confirm = useConfirmationDialog() useLayoutEffect(() => { + currentWorkspaceIdRef.current = browserTab.workspaceId currentBrowserTabIdRef.current = browserTab.id currentBrowserTabUrlRef.current = browserTab.url activeRuntimeEnvironmentIdRef.current = activeRuntimeEnvironmentId isActiveRef.current = isActive runtimeWorktreeRef.current = runtimeWorktree - }, [activeRuntimeEnvironmentId, browserTab.id, browserTab.url, isActive, runtimeWorktree]) + }, [ + activeRuntimeEnvironmentId, + browserTab.id, + browserTab.workspaceId, + browserTab.url, + isActive, + runtimeWorktree + ]) if (!lifecycleRef.current) { lifecycleRef.current = new RemoteBrowserStreamLifecycle({ @@ -88,12 +100,21 @@ export function useRemoteBrowserPageLifecycle({ isActive: () => isActiveRef.current, getTabId: () => currentBrowserTabIdRef.current, getEnvironmentId: () => activeRuntimeEnvironmentIdRef.current, - browserPageExists + browserPageExists: (pageId) => + Boolean( + readRemoteBrowserPage(useAppStore.getState(), currentWorkspaceIdRef.current, pageId) + ) }, callRpc: callRuntimeRpc, subscribeScreencast: (args, callbacks) => subscribeRuntimeEnvironment(args, callbacks), getWorktreeSelector: () => runtimeWorktreeRef.current, getCurrentUrl: () => currentBrowserTabUrlRef.current, + readCurrentObservation: () => + readRemoteBrowserPageObservation( + useAppStore.getState(), + currentWorkspaceIdRef.current, + currentBrowserTabIdRef.current + ), readStoredHandle: () => useAppStore.getState().remoteBrowserPageHandlesByPageId[currentBrowserTabIdRef.current] ?? null, @@ -235,7 +256,12 @@ export function useRemoteBrowserPageLifecycle({ } const state = useAppStore.getState() const currentEnvironmentId = runtimeEnvironmentIdOrLocalUnlessTwin(state, worktreeId) - const pageStillExists = browserPageExists(browserTab.id) + const pageStillExists = + useAppStore + .getState() + .browserPagesByWorkspace[browserTab.workspaceId]?.some( + (page) => page.id === browserTab.id + ) ?? false if (currentEnvironmentId === activeRuntimeEnvironmentId && pageStillExists) { return } @@ -252,7 +278,14 @@ export function useRemoteBrowserPageLifecycle({ { timeoutMs: 15_000, suppressFeatureInteraction: true } ).catch(() => {}) } - }, [activeRuntimeEnvironmentId, browserTab.id, lifecycle, runtimeWorktree, worktreeId]) + }, [ + activeRuntimeEnvironmentId, + browserTab.id, + browserTab.workspaceId, + lifecycle, + runtimeWorktree, + worktreeId + ]) return { lifecycle, diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts index 481965f3b90..769c9fc1b92 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts @@ -1,74 +1,672 @@ // @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' +import { act, cleanup } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useAppStore } from '@/store' -import type { BrowserPage } from '../../../../../shared/browser-workspace-types' -import { useRemoteBrowserPageNavigation } from './use-remote-browser-page-navigation' -import type { RemoteBrowserStreamLifecycle } from './remote-browser-stream-lifecycle' +import { applyWebSessionTabsSnapshot } from '@/runtime/web-session-tabs-sync/snapshot-api' +import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +import type { BrowserTabInfo } from '../../../../../shared/browser/runtime/runtime-browser-contracts' -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: vi.fn(async () => ({})) -})) +import { + page, + failedTab, + deferred, + renderNavigation, + currentPage, + expectPending +} from './remote-browser-page-navigation.test-fixture' -function page(): BrowserPage { - return { - id: 'page-a', - workspaceId: 'workspace-a', - worktreeId: 'worktree-a', - url: 'about:blank', - title: 'New Tab', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } -} +vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: vi.fn() })) -function renderNavigation(): ReturnType< - typeof renderHook, void> -> { - return renderHook(() => - useRemoteBrowserPageNavigation({ - browserTab: page(), - stagedPage: false, - addressBarValue: 'about:blank', - setAddressBarValueFromPage: vi.fn(), - lifecycle: { - session: { ensureRemotePage: vi.fn(), scheduleTabInfoRefresh: vi.fn() } - } as unknown as RemoteBrowserStreamLifecycle, - runtimeWorktree: 'worktree-a', - runtimeTarget: () => null, - createRemoteOperationToken: () => null, - isCurrentRemoteOperationToken: () => false, - closeMissingRemotePage: vi.fn(), - onSetUrl: vi.fn(), - onUpdatePageState: vi.fn(), - setPaneNotice: vi.fn(), - setPaneBusy: vi.fn() - }) - ) -} +beforeEach(() => vi.mocked(callRuntimeRpc).mockReset()) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) -describe('useRemoteBrowserPageNavigation history recording', () => { - beforeEach(() => { - useAppStore.setState({ browserUrlHistory: [] }) +describe('remote browser authoritative page state', () => { + it('projects a pending host challenge through local actions and clears an old full snapshot without fields', () => { + const { result } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + expectPending() + act(() => + result.current.applyRemoteTabInfo({ + browserPageId: 'remote-page-a', + index: 0, + active: true, + url: 'https://example.test/', + title: 'Example' + }) + ) + expect(currentPage().loadError).toBeNull() + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() }) - afterEach(() => cleanup()) - it('redacts a Kagi session token before it reaches history', () => { const { result } = renderNavigation() - act(() => result.current.applyRemoteTabInfo({ + browserPageId: 'remote-page-a', + index: 0, + active: true, url: 'https://kagi.com/search?q=orca&token=secret-session', title: 'Kagi' }) ) - - const [entry] = useAppStore.getState().browserUrlHistory - expect(entry.url).not.toContain('secret-session') + expect(useAppStore.getState().browserUrlHistory[0].url).not.toContain('secret-session') }) + + it.each(['browser.goto', 'browser.back', 'browser.forward', 'browser.reload'] as const)( + 'reads authoritative state after %s rejects or resolves, without a pre-command read', + async (method) => { + const { result, busy, notice } = renderNavigation() + const calls: string[] = [] + vi.mocked(callRuntimeRpc).mockImplementation(async (_target, called) => { + if (typeof called !== 'string' || !called.startsWith('browser.')) { + return undefined + } + calls.push(called) + if (called === 'browser.tabShow') { + return { tab: failedTab('challenge-y') } + } + if (called === 'browser.goto') { + throw new Error('ERR_CERT_AUTHORITY_INVALID (-202)') + } + return { url: 'chrome-error://chromewebdata/', title: 'Error' } + }) + await act(() => result.current.runRemoteNavigation(method, 'https://selfsigned.test/')) + expect(calls).toEqual([method, 'browser.tabShow']) + expectPending('challenge-y') + expect(currentPage().loading).toBe(false) + expect(busy).toHaveBeenLastCalledWith(false) + expect(notice).not.toHaveBeenCalledWith(expect.objectContaining({ kind: 'consequence' })) + expect( + useAppStore + .getState() + .browserUrlHistory.some((entry) => entry.url.startsWith('chrome-error:')) + ).toBe(false) + } + ) + + it('keeps a pending failure when a resolved reload outcome read times out', async () => { + const { result } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + vi.mocked(callRuntimeRpc).mockImplementation(async (_target, method) => { + if (method === 'browser.tabShow') { + throw new Error('request timed out') + } + return { url: 'chrome-error://chromewebdata/', title: 'Error' } + }) + await act(() => result.current.runRemoteNavigation('browser.reload')) + expectPending() + expect(currentPage().loading).toBe(false) + }) + + it('does not let a command settling after Proceed overwrite the native success or start another read', async () => { + const { result, busy, notice } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + const command = deferred() + vi.mocked(callRuntimeRpc).mockReturnValue(command.promise) + let pending!: Promise + await act(async () => { + pending = result.current.runRemoteNavigation('browser.reload') + await Promise.resolve() + }) + act(() => { + result.current.prepareCertificateProceed() + useAppStore.getState().updateBrowserPageState('page-a', { loadError: null, loading: false }) + }) + const publications = busy.mock.calls.length + await act(async () => { + command.resolve({ url: 'chrome-error://chromewebdata/', title: 'Old' }) + await pending + }) + expect(currentPage().loadError).toBeNull() + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + expect(vi.mocked(callRuntimeRpc).mock.calls.map((call) => call[1])).toEqual(['browser.reload']) + expect(busy.mock.calls.length).toBe(publications) + expect(notice).not.toHaveBeenCalledWith(expect.objectContaining({ kind: 'consequence' })) + }) + + it.each(['older-first', 'newer-first', 'newer-fails'] as const)( + 'retains current outcomes across command cleanup with %s settlement', + async (order) => { + const { result, session, tokens } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + const older = deferred<{ tab: BrowserTabInfo }>() + const newer = deferred<{ tab: BrowserTabInfo }>() + vi.mocked(callRuntimeRpc) + .mockResolvedValueOnce({ url: 'https://selfsigned.test/', title: 'Reload' }) + .mockReturnValueOnce(older.promise) + .mockReturnValueOnce(newer.promise) + let command!: Promise + await act(async () => { + command = result.current.runRemoteNavigation('browser.reload') + }) + const refresh = session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!) + if (order === 'newer-fails') { + await act(async () => { + newer.reject(new Error('input read unavailable')) + await expect(refresh).rejects.toThrow('input read unavailable') + }) + } else if (order === 'newer-first') { + await act(async () => { + newer.resolve({ tab: { ...failedTab('challenge-z'), title: 'Current input' } }) + await refresh + }) + } + await act(async () => { + older.resolve({ tab: { ...failedTab('challenge-y'), title: 'Reload outcome' } }) + await command + }) + if (order === 'older-first') { + await act(async () => { + newer.resolve({ tab: { ...failedTab('challenge-z'), title: 'Current input' } }) + await refresh + }) + } + expectPending(order === 'newer-fails' ? 'challenge-y' : 'challenge-z') + expect(currentPage().title).toBe(order === 'newer-fails' ? 'Reload outcome' : 'Current input') + expect(currentPage().loading).toBe(false) + } + ) + + it('releases retired Reload loading before failed Proceed without a native wake', async () => { + const { result } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + const reload = deferred() + vi.mocked(callRuntimeRpc).mockImplementation(async (_target, method) => + method === 'browser.reload' ? reload.promise : undefined + ) + let pending!: Promise + await act(async () => { + pending = result.current.runRemoteNavigation('browser.reload') + }) + expect(currentPage().loading).toBe(true) + act(() => result.current.prepareCertificateProceed()) + expect(currentPage().loading).toBe(false) + await act(async () => { + reload.reject(new Error('connection lost before reaching host')) + await pending + }) + expectPending() + expect(currentPage().loading).toBe(false) + }) + + it('does not bless external ABA or clear native-owned loading during local cleanup', async () => { + const { session, tokens, result } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + const token = tokens.createOperationToken('remote-page-a')! + act(() => session.setPageLoading(token, true, useAppStore.getState().updateBrowserPageState)) + const response = deferred<{ tab: BrowserTabInfo }>() + vi.mocked(callRuntimeRpc).mockReturnValue(response.promise) + const pending = session.refreshTabInfo(token) + act(() => { + useAppStore.getState().updateBrowserPageState('page-a', { loadError: null }) + result.current.applyRemoteTabInfo(failedTab()) + useAppStore.getState().updateBrowserPageState('page-a', { loading: true }) + session.setPageLoading(token, false, useAppStore.getState().updateBrowserPageState) + }) + await act(async () => { + response.resolve({ tab: failedTab('stale') }) + await pending + }) + expectPending() + expect(currentPage().loading).toBe(true) + }) + + it.each(['initial-open', 'restart'] as const)( + 'preserves command failure when %s fails before ready', + async (phase) => { + vi.useFakeTimers() + const { lifecycle, subscribe, result } = renderNavigation() + const status = deferred<{ capabilities: string[] }>() + const read = deferred<{ tab: BrowserTabInfo }>() + let held = phase === 'initial-open' + let commandStarted = false + vi.mocked(callRuntimeRpc).mockImplementation(async (_target, method) => { + if (method === 'status.get') { + return held ? status.promise : { capabilities: ['browser.screencast.v1'] } + } + if (method === 'browser.goto') { + commandStarted = true + throw new Error('ERR_NAME_NOT_RESOLVED (-105)') + } + if (method === 'browser.tabShow') { + return commandStarted ? read.promise : { tab: failedTab() } + } + return undefined + }) + try { + lifecycle.open() + await act(() => vi.advanceTimersByTimeAsync(0)) + if (phase === 'restart') { + const callbacks = subscribe.mock.calls[0][1] + callbacks.onResponse({ + id: 'stream-1', + ok: true, + result: { + type: 'ready', + subscriptionId: 'stream-1', + browserPageId: 'remote-page-a', + format: 'jpeg', + tab: failedTab() + }, + _meta: { runtimeId: 'host-a' } + }) + held = true + callbacks.onClose?.() + await act(() => vi.runOnlyPendingTimersAsync()) + } + let command!: Promise + await act(async () => { + command = result.current.runRemoteNavigation('browser.goto', 'https://missing.test/') + }) + subscribe.mockRejectedValueOnce( + Object.assign(new Error('stream unavailable'), { code: 'browser_screencast_unsupported' }) + ) + await act(async () => { + status.resolve({ capabilities: ['browser.screencast.v1'] }) + await vi.advanceTimersByTimeAsync(0) + }) + await act(async () => { + read.reject(new Error('outcome read unavailable')) + await command + }) + expect(currentPage().loadError).toEqual({ + code: -105, + description: 'ERR_NAME_NOT_RESOLVED', + validatedUrl: 'https://missing.test/' + }) + expect(currentPage().loading).toBe(false) + } finally { + lifecycle.dispose() + } + } + ) + + it('rejects a late read after native replacement/clear, another action, host switch, or unmount, then accepts a current read', async () => { + const { result, session, tokens, identity } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + for (const supersede of [ + () => + useAppStore + .getState() + .setBrowserPageCertificateFailure('page-a', failedTab('challenge-y').certificateFailure!), + () => useAppStore.getState().updateBrowserPageState('page-a', { loadError: null }), + () => session.invalidateTabInfoReads(), + () => { + identity.environmentId = 'environment-b' + }, + () => { + identity.mounted = false + } + ]) { + const response = deferred() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(response.promise) + const read = session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!) + act(supersede) + response.resolve({ tab: failedTab() }) + expect(await read).toBeNull() + identity.environmentId = 'environment-a' + identity.mounted = true + } + vi.mocked(callRuntimeRpc).mockResolvedValueOnce({ tab: failedTab('challenge-z') }) + await act(() => session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!)) + expectPending('challenge-z') + }) + + it('keeps the second navigation loading when an older outcome read rejects', async () => { + const { result, busy, notice } = renderNavigation() + const stale = deferred() + const second = deferred() + vi.mocked(callRuntimeRpc) + .mockResolvedValueOnce({ url: 'about:blank' }) + .mockReturnValueOnce(stale.promise) + .mockReturnValueOnce(second.promise) + .mockResolvedValueOnce({ tab: failedTab('challenge-y') }) + let first!: Promise + let next!: Promise + await act(async () => { + first = result.current.runRemoteNavigation('browser.reload') + await Promise.resolve() + await Promise.resolve() + next = result.current.runRemoteNavigation('browser.back') + await Promise.resolve() + }) + await act(async () => { + stale.reject(new Error('stale read failed')) + await first + }) + expect(currentPage().loading).toBe(true) + expect(busy).toHaveBeenLastCalledWith(true) + expect(notice).not.toHaveBeenCalledWith(expect.objectContaining({ kind: 'consequence' })) + await act(async () => { + second.resolve({ url: 'chrome-error://chromewebdata/' }) + await next + }) + expectPending('challenge-y') + expect(currentPage().loading).toBe(false) + }) + + it.each(['success', 'failure'] as const)( + 'accepts a later native mirror %s after an early Proceed observation and rejects the older read', + async (outcome) => { + const { result, session, tokens } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + expectPending() + act(() => { + result.current.prepareCertificateProceed() + result.current.applyRemoteTabInfo({ + ...failedTab(), + certificateFailure: null + }) + }) + const stale = deferred() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(stale.promise) + const read = session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!) + const failure = outcome === 'failure' ? failedTab('challenge-y') : null + act(() => + useAppStore.setState((state) => + applyWebSessionTabsSnapshot( + state, + { + worktree: 'worktree-a', + publicationEpoch: 'tls-test', + snapshotVersion: 1, + activeTabType: 'browser', + activeTabId: 'host-tab', + activeGroupId: 'host-group', + tabs: [ + { + type: 'browser', + id: 'host-tab', + browserWorkspaceId: 'workspace-a', + browserPageId: 'remote-page-a', + url: 'https://selfsigned.test/', + title: 'TLS', + loading: false, + canGoBack: false, + canGoForward: false, + isActive: true, + loadError: failure?.loadError ?? null, + certificateFailure: failure?.certificateFailure ?? null + } + ] + }, + 'environment-a', + 100 + ) + ) + ) + stale.resolve({ tab: failedTab() }) + expect(await read).toBeNull() + if (outcome === 'failure') { + expectPending('challenge-y') + } else { + expect(currentPage().loadError).toBeNull() + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + } + } + ) + + it.each([null, undefined])( + 'keeps an explicit native clear but retains the legacy omitted-error fallback (%s)', + async (loadError) => { + const { result } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + vi.mocked(callRuntimeRpc).mockImplementation(async (_target, method) => { + if (typeof method !== 'string') { + return undefined + } + if (method === 'browser.tabShow') { + return { + tab: { + ...failedTab(), + url: 'https://loaded.test/', + loadError, + certificateFailure: null + } + } + } + throw new Error('ERR_TIMED_OUT (-7)') + }) + await act(() => result.current.runRemoteNavigation('browser.goto', 'https://loaded.test/')) + expect(currentPage().url).toBe('https://loaded.test/') + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + if (loadError === null) { + expect(currentPage().loadError).toBeNull() + } else { + expect(currentPage().loadError).toEqual({ + code: -7, + description: 'ERR_TIMED_OUT', + validatedUrl: 'https://loaded.test/' + }) + } + } + ) + + it('retains parsed command failure when its authoritative read also fails', async () => { + const { result } = renderNavigation() + vi.mocked(callRuntimeRpc).mockImplementation(async (_target, method) => { + if (typeof method !== 'string') { + return undefined + } + throw new Error(method === 'browser.tabShow' ? 'read timed out' : 'ERR_TIMED_OUT (-7)') + }) + await act(() => result.current.runRemoteNavigation('browser.goto', 'https://loaded.test/')) + expect(currentPage().loadError).toEqual({ + code: -7, + description: 'ERR_TIMED_OUT', + validatedUrl: 'https://loaded.test/' + }) + expect(currentPage().loading).toBe(false) + }) + + it('does not reinstall X after native clear-to-failure-to-clear at the same URL', async () => { + const { result, session, tokens } = renderNavigation() + act(() => + result.current.applyRemoteTabInfo({ + ...failedTab(), + loadError: null, + certificateFailure: null + }) + ) + const response = deferred() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(response.promise) + const pending = session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!) + act(() => { + useAppStore.getState().updateBrowserPageState('page-a', { loadError: failedTab().loadError }) + useAppStore + .getState() + .setBrowserPageCertificateFailure('page-a', failedTab().certificateFailure!) + useAppStore.getState().updateBrowserPageState('page-a', { loadError: null }) + }) + response.resolve({ tab: failedTab() }) + expect(await pending).toBeNull() + expect(currentPage().loadError).toBeNull() + vi.mocked(callRuntimeRpc).mockResolvedValueOnce({ tab: failedTab('challenge-y') }) + await act(() => session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!)) + expectPending('challenge-y') + }) + + it('applies admitted state before resolving, so a queued native clear remains final', async () => { + const { session, tokens } = renderNavigation() + const response = deferred() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(response.promise) + const pending = session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!) + const nativeClear = response.promise.then(() => + queueMicrotask(() => + useAppStore.getState().updateBrowserPageState('page-a', { loadError: null }) + ) + ) + await act(async () => { + response.resolve({ tab: failedTab() }) + await pending + await nativeClear + }) + expect(currentPage().loadError).toBeNull() + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + }) + + it.each(['rejected', 'resolved', 'missing'] as const)( + 'keeps a queued native replacement after an admitted %s read failure', + async (outcome) => { + const { result, notice, closeMissing } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + const read = deferred() + vi.mocked(callRuntimeRpc).mockImplementation((_target, method) => { + if (typeof method !== 'string') { + return Promise.resolve(undefined) + } + if (method === 'browser.tabShow') { + return read.promise + } + if (outcome === 'rejected') { + return Promise.reject(new Error('ERR_CERT_AUTHORITY_INVALID (-202)')) + } + return Promise.resolve({ url: 'https://old.test/', title: 'Old' }) + }) + let pending!: Promise + await act(async () => { + pending = result.current.runRemoteNavigation('browser.goto', 'https://old.test/') + await Promise.resolve() + await Promise.resolve() + }) + const native = read.promise.catch(() => + queueMicrotask(() => { + useAppStore.getState().setBrowserPageUrl('page-a', 'https://native.test/') + useAppStore + .getState() + .updateBrowserPageState('page-a', { loadError: null, loading: false, title: 'Native' }) + notice.mockClear() + closeMissing.mockClear() + }) + ) + await act(async () => { + read.reject( + outcome === 'missing' + ? Object.assign(new Error('page missing'), { code: 'browser_tab_not_found' }) + : new Error('read timed out') + ) + await pending + await native + }) + expect(currentPage().url).toBe('https://native.test/') + expect(currentPage().title).toBe('Native') + expect(currentPage().loadError).toBeNull() + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + expect(notice).not.toHaveBeenCalled() + expect(closeMissing).not.toHaveBeenCalled() + } + ) + + it.each([100, 1000])( + 'drops an obsolete read without visiting %i unrelated workspace pages after map replacement', + async (count) => { + const { result, session, tokens } = renderNavigation() + act(() => result.current.applyRemoteTabInfo(failedTab())) + const response = deferred() + vi.mocked(callRuntimeRpc).mockReturnValueOnce(response.promise) + const pending = session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!) + let visits = 0 + let copies = 0 + const unrelated = Object.fromEntries( + Array.from({ length: count }, (_, index) => [ + `other-${index}`, + new Proxy([page(`other-${index}`)], { + get(target, key, receiver) { + if (key === 'map') { + copies += 1 + } + if (typeof key === 'string' && /^\d+$/.test(key)) { + visits += 1 + } + // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy must forward array access unchanged while counting visits. + return Reflect.get(target, key, receiver) + } + }) + ]) + ) + useAppStore.setState((state) => ({ + browserPagesByWorkspace: { ...state.browserPagesByWorkspace, ...unrelated } + })) + session.invalidateTabInfoReads() + response.resolve({ tab: failedTab('stale') }) + expect(await pending).toBeNull() + expect(visits).toBe(0) + expect(copies).toBe(0) + expectPending() + vi.mocked(callRuntimeRpc).mockResolvedValueOnce({ tab: failedTab('challenge-y') }) + await act(() => session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!)) + expectPending('challenge-y') + } + ) + + it.each([100, 1000])( + 'publishes no work for identical decoded failure observations among %i pages', + async (count) => { + const { result, session, tokens } = renderNavigation(count) + const failures = Object.fromEntries( + Array.from({ length: count }, (_, index) => [ + `page-${index}`, + failedTab(`other-${index}`).certificateFailure! + ]) + ) + useAppStore.setState({ browserCertificateFailuresByPageId: failures }) + act(() => result.current.applyRemoteTabInfo(failedTab())) + let enumerations = 0 + let copies = 0 + let visits = 0 + const state = useAppStore.getState() + const counted = (value: T): T => + new Proxy(value, { + ownKeys(target) { + enumerations += 1 + return Reflect.ownKeys(target) + } + }) + const countedPages = new Proxy(state.browserPagesByWorkspace['workspace-a'], { + get(target, key, receiver) { + if (key === 'map') { + copies += 1 + } + if (typeof key === 'string' && /^\d+$/.test(key)) { + visits += 1 + } + // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy must forward array access unchanged while counting visits. + return Reflect.get(target, key, receiver) + } + }) + useAppStore.setState({ + browserPagesByWorkspace: counted({ + ...state.browserPagesByWorkspace, + 'workspace-a': countedPages + }), + browserCertificateFailuresByPageId: counted(state.browserCertificateFailuresByPageId) + }) + currentPage() + const before = useAppStore.getState() + enumerations = 0 + copies = 0 + visits = 0 + const changed = vi.fn() + const unsubscribe = useAppStore.subscribe(changed) + vi.mocked(callRuntimeRpc).mockResolvedValueOnce({ + tab: JSON.parse(JSON.stringify(failedTab())) + }) + await act(async () => { + await session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!) + }) + unsubscribe() + expect(changed).not.toHaveBeenCalled() + expect(enumerations).toBe(0) + expect(copies).toBe(0) + expect(visits).toBeLessThanOrEqual(count + 20) + expect(useAppStore.getState()).toBe(before) + const unrelated = before.browserPagesByWorkspace['workspace-a'][1] + act(() => result.current.applyRemoteTabInfo(failedTab('challenge-y'))) + expectPending('challenge-y') + expect(useAppStore.getState().browserPagesByWorkspace['workspace-a'][1]).toBe(unrelated) + } + ) }) diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.ts index 7898e381226..0bf0af227b7 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.ts @@ -1,22 +1,18 @@ +import { runRemoteBrowserNavigationCommand } from './remote-browser-page-navigation-command' import { useCallback, useRef } from 'react' import { useAppStore } from '@/store' import { redactKagiSessionToken } from '../../../../../shared/browser-url' import { normalizeBrowserHistoryUrl } from '../../../../../shared/workspace-session/workspace-session-browser-history' import { resolveBrowserAddressBarSubmission } from '../navigate/browser-address-bar-navigation' import { routeWorkspaceDocAddressSubmission } from '../navigate/workspace-doc-address-submission' -import { deferBrowserPageNavigation } from '../navigate/browser-page-deferred-navigation' -import type { - BrowserBackResult, - BrowserGotoResult, - BrowserReloadResult, - BrowserTabInfo -} from '../../../../../shared/browser/runtime/runtime-browser-contracts' +import type { BrowserTabInfo } from '../../../../../shared/browser/runtime/runtime-browser-contracts' import type { BrowserPage as BrowserPageState } from '../../../../../shared/browser-workspace-types' -import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' -import { isRemoteBrowserPageMissingError } from './remote-browser-stream-errors' import type { RemoteBrowserOperationToken } from './remote-browser-stream-tokens' import type { RemoteBrowserStreamLifecycle } from './remote-browser-stream-lifecycle' -import type { BrowserPageUrlSetter, BrowserTabPageState } from '../describe-page/browser-page-types' +import type { + BrowserPageUrlSetter, + BrowserPageStateWriter +} from '../describe-page/browser-page-types' import { getBrowserDisplayTitle, toDisplayUrl } from '../describe-page/browser-page-url-display' import type { RemoteBrowserPaneNotice, @@ -51,11 +47,12 @@ export function useRemoteBrowserPageNavigation({ isCurrentRemoteOperationToken: (token: RemoteBrowserOperationToken) => boolean closeMissingRemotePage: (remotePageId?: string | null) => void onSetUrl: BrowserPageUrlSetter - onUpdatePageState: (tabId: string, updates: BrowserTabPageState) => void + onUpdatePageState: BrowserPageStateWriter setPaneNotice: (notice: RemoteBrowserPaneNotice | null) => void setPaneBusy: (busy: boolean) => void }): { - applyRemoteTabInfo: (tab: Pick) => void + applyRemoteTabInfo: (tab: BrowserTabInfo) => void + prepareCertificateProceed: () => void scheduleRemoteTabInfoRefresh: (token: RemoteBrowserOperationToken, delayMs?: number) => void runRemoteNavigation: ( method: 'browser.goto' | 'browser.back' | 'browser.forward' | 'browser.reload', @@ -66,16 +63,26 @@ export function useRemoteBrowserPageNavigation({ } { const addBrowserHistoryEntry = useAppStore((state) => state.addBrowserHistoryEntry) const lastFiledHistoryRef = useRef(null) + const navigationSequence = useRef(0) - const applyRemoteTabInfo = useCallback( - (tab: Pick): void => { + const applyRemoteTabMetadata = useCallback( + ( + tab: Pick & Partial> + ): void => { const safeUrl = redactKagiSessionToken(tab.url || 'about:blank') const title = getBrowserDisplayTitle(tab.title, safeUrl) - onSetUrl(browserTab.id, safeUrl) + const page = useAppStore + .getState() + .browserPagesByWorkspace[browserTab.workspaceId]?.find( + (entry) => entry.id === browserTab.id + ) + if (page?.url !== safeUrl) { + onSetUrl(browserTab.id, safeUrl, { preserveLoadError: true }) + } onUpdatePageState(browserTab.id, { title, loading: false, - loadError: null + ...(tab.loadError !== undefined ? { loadError: tab.loadError } : {}) }) // File remote navigations in client suggestion history only when URL/title changes; post-input tab reads must not rewrite the store. const filing = `${normalizeBrowserHistoryUrl(safeUrl)}\n${title}` @@ -85,9 +92,37 @@ export function useRemoteBrowserPageNavigation({ } setAddressBarValueFromPage(toDisplayUrl(safeUrl)) }, - [addBrowserHistoryEntry, browserTab.id, onSetUrl, onUpdatePageState, setAddressBarValueFromPage] + [ + addBrowserHistoryEntry, + browserTab.id, + browserTab.workspaceId, + onSetUrl, + onUpdatePageState, + setAddressBarValueFromPage + ] ) + const applyRemoteTabInfo = useCallback( + (tab: BrowserTabInfo): void => { + applyRemoteTabMetadata({ ...tab, loadError: tab.loadError ?? null }) + useAppStore + .getState() + .setBrowserPageCertificateFailure(browserTab.id, tab.certificateFailure ?? null) + }, + [applyRemoteTabMetadata, browserTab.id] + ) + + const prepareCertificateProceed = useCallback((): void => { + navigationSequence.current += 1 + const token = createRemoteOperationToken() + if (token) { + lifecycle.session.setPageLoading(token, false, onUpdatePageState) + } + lifecycle.session.invalidateTabInfoReads() + setPaneBusy(false) + setPaneNotice(null) + }, [createRemoteOperationToken, lifecycle, onUpdatePageState, setPaneBusy, setPaneNotice]) + const scheduleRemoteTabInfoRefresh = useCallback( (token: RemoteBrowserOperationToken, delayMs = 250): void => { lifecycle.session.scheduleTabInfoRefresh(token, delayMs) @@ -100,76 +135,29 @@ export function useRemoteBrowserPageNavigation({ method: 'browser.goto' | 'browser.back' | 'browser.forward' | 'browser.reload', url?: string ) => { - const target = runtimeTarget() - if (!target) { - return - } - if (stagedPage) { - // No staged host page exists yet: park goto until adoption; history/reload cannot replay against an uncreated page. - if (method === 'browser.goto' && url) { - deferBrowserPageNavigation(browserTab.id, url) - onUpdatePageState(browserTab.id, { loading: true, loadError: null }) - } - return - } - const operationToken = createRemoteOperationToken() - if (!operationToken) { - return - } - const pageId = await lifecycle.session.ensureRemotePage(operationToken) - if (!pageId) { - return - } - const pageToken = { ...operationToken, remotePageId: pageId } - if (!isCurrentRemoteOperationToken(pageToken)) { - return - } - setPaneBusy(true) - setPaneNotice(null) - // Why: a standing failure (and its auto-retry) stays up until a load succeeds or fails anew. - onUpdatePageState(browserTab.id, { loading: true }) - try { - const params = - method === 'browser.goto' - ? { worktree: runtimeWorktree, page: pageId, url: url ?? 'about:blank' } - : { worktree: runtimeWorktree, page: pageId } - const result = await callRuntimeRpc< - BrowserGotoResult | BrowserBackResult | BrowserReloadResult - >(target, method, params, { timeoutMs: 30_000, suppressFeatureInteraction: true }) - if (isCurrentRemoteOperationToken(pageToken)) { - applyRemoteTabInfo(result) - } - } catch (error) { - if (!isCurrentRemoteOperationToken(pageToken)) { - return - } - if (isRemoteBrowserPageMissingError(error)) { - closeMissingRemotePage(pageId) - return - } - const message = error instanceof Error ? error.message : 'Remote browser command failed.' - setPaneNotice({ kind: 'consequence', text: message }) - // Why: goto results carry no load error, but the rejection keeps Electron's "ERR_NAME (-code)" text. - const netError = /\b(ERR_[A-Z_]+) \((-\d+)\)/.exec(message) - onUpdatePageState(browserTab.id, { - loading: false, - // Why: validatedUrl is persisted, so redact the Kagi session token like the main-process failure path does. - loadError: { - code: netError ? Number(netError[2]) : 0, - description: netError ? netError[1] : message, - validatedUrl: redactKagiSessionToken(url ?? browserTab.url) - } - }) - } finally { - if (isCurrentRemoteOperationToken(pageToken)) { - setPaneBusy(false) - } - } + return runRemoteBrowserNavigationCommand( + { + browserTab, + stagedPage, + lifecycle, + runtimeWorktree, + runtimeTarget, + createRemoteOperationToken, + isCurrentRemoteOperationToken, + closeMissingRemotePage, + onUpdatePageState, + setPaneNotice, + setPaneBusy, + navigationSequence, + applyRemoteTabMetadata + }, + method, + url + ) }, [ - applyRemoteTabInfo, - browserTab.id, - browserTab.url, + applyRemoteTabMetadata, + browserTab, createRemoteOperationToken, lifecycle, closeMissingRemotePage, @@ -216,6 +204,7 @@ export function useRemoteBrowserPageNavigation({ return { applyRemoteTabInfo, + prepareCertificateProceed, scheduleRemoteTabInfoRefresh, runRemoteNavigation, navigateToUrl, diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-stream.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-stream.ts index 2b279627285..02002cd9c8c 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-stream.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-stream.ts @@ -58,7 +58,7 @@ export function useRemoteBrowserPageStream({ pendingFrameDecodeRef: React.MutableRefObject streamBridgeRef: React.MutableRefObject isActiveRef: React.RefObject - applyTabInfo: (tab: Pick) => void + applyTabInfo: (tab: BrowserTabInfo) => void clearStreamFrame: () => void closeMissingRemotePage: (remotePageId?: string | null) => void clearPendingRemoteWheel: () => void diff --git a/src/renderer/src/lib/browser/browser-page-loading-ownership.ts b/src/renderer/src/lib/browser/browser-page-loading-ownership.ts new file mode 100644 index 00000000000..2f95e267a37 --- /dev/null +++ b/src/renderer/src/lib/browser/browser-page-loading-ownership.ts @@ -0,0 +1,39 @@ +import type { BrowserPage } from '../../../../shared/browser-workspace-types' + +export type BrowserPageLoadingOwner = { active: boolean } + +const loadingOwners = new WeakMap() + +export function readBrowserPageLoadingOwner( + page: BrowserPage | undefined +): BrowserPageLoadingOwner | undefined { + const owner = page && loadingOwners.get(page) + return owner?.active ? owner : undefined +} + +export function revokeBrowserPageLoadingOwner(page: BrowserPage): void { + const owner = loadingOwners.get(page) + if (owner) { + owner.active = false + loadingOwners.delete(page) + } +} + +export function preserveBrowserPageLoadingOwner(previous: BrowserPage, next: BrowserPage): void { + const owner = readBrowserPageLoadingOwner(previous) + if (owner && previous !== next) { + loadingOwners.delete(previous) + loadingOwners.set(next, owner) + } +} + +export function assignBrowserPageLoadingOwner( + previous: BrowserPage, + next: BrowserPage, + owner?: BrowserPageLoadingOwner +): void { + revokeBrowserPageLoadingOwner(previous) + if (owner?.active) { + loadingOwners.set(next, owner) + } +} diff --git a/src/renderer/src/runtime/web-session-tabs-sync/apply-browser-records.ts b/src/renderer/src/runtime/web-session-tabs-sync/apply-browser-records.ts index 5a9834619f5..612e2106725 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/apply-browser-records.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/apply-browser-records.ts @@ -1,5 +1,9 @@ import { annotateBrowserPageHandles } from '@/store/slices/browser/hosts/browser-initialization-presentation-ownership' import type { applyTerminalRecordUpdates } from './apply-terminal-records' +import { + preserveBrowserPageLoadingOwner, + revokeBrowserPageLoadingOwner +} from '@/lib/browser/browser-page-loading-ownership' import { browserCertificateFailureEqual, optionalRuntimeBrowserPlacementsEqual, @@ -50,6 +54,7 @@ export function applyBrowserRecordUpdates(context: BrowserRecordContext) { if (nextBrowserPageIds.has(page.id)) { continue } + revokeBrowserPageLoadingOwner(page) if (nextBrowserCertificateFailuresByPageId[page.id]) { nextBrowserCertificateFailuresByPageId = nextBrowserCertificateFailuresByPageId === state.browserCertificateFailuresByPageId @@ -79,12 +84,21 @@ export function applyBrowserRecordUpdates(context: BrowserRecordContext) { for (const { page, + previousPage, + preservesLoading, certificateFailure, remotePageId, browserProfileId, placement, initializationPresentation } of mirroredBrowserTabs) { + if (previousPage) { + if (preservesLoading) { + preserveBrowserPageLoadingOwner(previousPage, page) + } else { + revokeBrowserPageLoadingOwner(previousPage) + } + } const current = nextBrowserPagesByWorkspace[page.workspaceId] ?? [] if (!sameBrowserPages(current, [page])) { nextBrowserPagesByWorkspace = diff --git a/src/renderer/src/runtime/web-session-tabs-sync/mirrored-browser-tabs.ts b/src/renderer/src/runtime/web-session-tabs-sync/mirrored-browser-tabs.ts index 2a0c094c33d..0dac89a95e9 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/mirrored-browser-tabs.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/mirrored-browser-tabs.ts @@ -128,7 +128,13 @@ export function resolveMirroredBrowserPageContent( previousPresentation?: BrowserInitializationPresentation, stale = false, reconcile = false -): Pick { +): { + content: Pick< + BrowserPage, + 'url' | 'title' | 'loading' | 'canGoBack' | 'canGoForward' | 'faviconUrl' + > + preservesLoading: boolean +} { const localAction = existingPage && hasBrowserPageInitializationAction(existingPage.id) if ( existingPage && @@ -137,27 +143,33 @@ export function resolveMirroredBrowserPageContent( (!reconcile && clientHostsMirroredBrowserPage(tab) && !presentation && !previousPresentation)) ) { return { - url: existingPage.url, - title: existingPage.title, - loading: - presentation?.disposition === 'pending' - ? true - : presentation - ? false - : existingPage.loading, - canGoBack: existingPage.canGoBack, - canGoForward: existingPage.canGoForward, - faviconUrl: existingPage.faviconUrl + preservesLoading: !presentation, + content: { + url: existingPage.url, + title: existingPage.title, + loading: + presentation?.disposition === 'pending' + ? true + : presentation + ? false + : existingPage.loading, + canGoBack: existingPage.canGoBack, + canGoForward: existingPage.canGoForward, + faviconUrl: existingPage.faviconUrl + } } } return { - url: tab.url, - title: resolveMirroredBrowserTitle(tab, existingPage), - loading: tab.loading, - canGoBack: tab.canGoBack, - canGoForward: tab.canGoForward, - // Old hosts omit the field; keep what this client already has. - faviconUrl: tab.faviconUrl === undefined ? (existingPage?.faviconUrl ?? null) : tab.faviconUrl + preservesLoading: false, + content: { + url: tab.url, + title: resolveMirroredBrowserTitle(tab, existingPage), + loading: tab.loading, + canGoBack: tab.canGoBack, + canGoForward: tab.canGoForward, + // Old hosts omit the field; keep what this client already has. + faviconUrl: tab.faviconUrl === undefined ? (existingPage?.faviconUrl ?? null) : tab.faviconUrl + } } } @@ -210,7 +222,7 @@ export function buildMirroredBrowserTabs( const groupId = clientGroupId ?? hostGroupId const previousHandle = existing ? state.remoteBrowserPageHandlesByPageId[pageId] : undefined const presentation = browserInitializationPresentation(snapshot, tab, previousHandle) - const content = resolveMirroredBrowserPageContent( + const { content, preservesLoading } = resolveMirroredBrowserPageContent( tab, existing?.page, presentation, @@ -270,6 +282,8 @@ export function buildMirroredBrowserTabs( return { workspace, page, + previousPage: existing?.page, + preservesLoading, certificateFailure: tab.certificateFailure ?? null, remotePageId: tab.browserPageId, initializationPresentation: presentation, diff --git a/src/renderer/src/runtime/web-session-tabs-sync/state.ts b/src/renderer/src/runtime/web-session-tabs-sync/state.ts index ef3e006cf6b..694d63e95ac 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/state.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/state.ts @@ -190,6 +190,8 @@ export type MirroredTerminalTab = { export type MirroredBrowserTab = { workspace: BrowserWorkspace page: BrowserPage + previousPage?: BrowserPage + preservesLoading: boolean certificateFailure: BrowserCertificateFailure | null remotePageId: string browserProfileId?: string diff --git a/src/renderer/src/store/slices/browser/browser-slice-contract.ts b/src/renderer/src/store/slices/browser/browser-slice-contract.ts index e6b9238b7f1..6831f7383f2 100644 --- a/src/renderer/src/store/slices/browser/browser-slice-contract.ts +++ b/src/renderer/src/store/slices/browser/browser-slice-contract.ts @@ -1,4 +1,5 @@ import type { StateCreator } from 'zustand' +import type { BrowserPageLoadingOwner } from '@/lib/browser/browser-page-loading-ownership' import type { ManagedBrowserProfileOwner } from '../../../../../shared/browser/profiles/browser-profile-scope' /** What a new tab opens on; a partition only when it must not be derived from the profile. */ @@ -190,8 +191,16 @@ export type BrowserSlice = { options?: { surfacePane?: boolean } ) => void consumeAddressBarFocusRequest: (pageId: string) => boolean - updateBrowserTabPageState: (pageId: string, updates: BrowserTabPageState) => void - updateBrowserPageState: (pageId: string, updates: BrowserTabPageState) => void + updateBrowserTabPageState: ( + pageId: string, + updates: BrowserTabPageState, + loadingOwner?: BrowserPageLoadingOwner + ) => void + updateBrowserPageState: ( + pageId: string, + updates: BrowserTabPageState, + loadingOwner?: BrowserPageLoadingOwner + ) => void setBrowserPageCertificateFailure: ( pageId: string, failure: BrowserCertificateFailure | null diff --git a/src/renderer/src/store/slices/browser/pages/browser-page-records.ts b/src/renderer/src/store/slices/browser/pages/browser-page-records.ts index 1bd356ad44c..04589f91bb5 100644 --- a/src/renderer/src/store/slices/browser/pages/browser-page-records.ts +++ b/src/renderer/src/store/slices/browser/pages/browser-page-records.ts @@ -97,12 +97,17 @@ export function mirrorWorkspaceFromActivePage( workspace: BrowserWorkspace, pages: BrowserPage[] ): BrowserWorkspace { + const pageIds = + workspace.pageIds?.length === pages.length && + pages.every((page, index) => page.id === workspace.pageIds?.[index]) + ? workspace.pageIds + : pages.map((page) => page.id) const activePage = pages.find((page) => page.id === workspace.activePageId) ?? null if (!activePage) { return { ...workspace, activePageId: null, - pageIds: pages.map((page) => page.id), + pageIds, url: 'about:blank', title: translate('auto.store.slices.browser.08fc23631d', 'Browser'), loading: false, @@ -116,7 +121,7 @@ export function mirrorWorkspaceFromActivePage( return { ...workspace, activePageId: activePage.id, - pageIds: pages.map((page) => page.id), + pageIds, url: activePage.url, title: activePage.title, loading: activePage.loading, @@ -136,8 +141,9 @@ export function browserWorkspaceMirrorFieldsEqual( const mirroredPageIds = mirrored.pageIds ?? [] return ( workspace.activePageId === mirrored.activePageId && - workspacePageIds.length === mirroredPageIds.length && - workspacePageIds.every((pageId, index) => pageId === mirroredPageIds[index]) && + (workspacePageIds === mirroredPageIds || + (workspacePageIds.length === mirroredPageIds.length && + workspacePageIds.every((pageId, index) => pageId === mirroredPageIds[index]))) && workspace.url === mirrored.url && workspace.title === mirrored.title && workspace.loading === mirrored.loading && diff --git a/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts b/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts index 65c73269684..79718fc4db3 100644 --- a/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts +++ b/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts @@ -1,5 +1,10 @@ import type { BrowserSlice, BrowserSliceGet, BrowserSliceSet } from '../browser-slice-contract' import type { AppState } from '../../../types' +import { + assignBrowserPageLoadingOwner, + preserveBrowserPageLoadingOwner, + revokeBrowserPageLoadingOwner +} from '@/lib/browser/browser-page-loading-ownership' import '../../../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../../../shared/browser/browser-blank-page' import { @@ -12,6 +17,10 @@ import { } from './browser-page-records' import { normalizeBrowserHistoryUrl } from '../../../../../../shared/workspace-session/workspace-session-browser-history' import { replaceTabBuckets } from '../../../keyed-record-transitions' +import { + browserCertificateFailureEqual, + browserPageEqual +} from '@/runtime/web-session-tabs-sync/state-equality-tabs' export function createBrowserPageStateActions( set: BrowserSliceSet, @@ -25,9 +34,10 @@ export function createBrowserPageStateActions( | 'setBrowserPageUrl' > { return { - updateBrowserTabPageState: (pageId, updates) => get().updateBrowserPageState(pageId, updates), + updateBrowserTabPageState: (pageId, updates, loadingOwner) => + get().updateBrowserPageState(pageId, updates, loadingOwner), - updateBrowserPageState: (pageId, updates) => { + updateBrowserPageState: (pageId, updates, loadingOwner) => { set((s) => { const page = findPage(s.browserPagesByWorkspace, pageId) if (!page) { @@ -58,13 +68,12 @@ export function createBrowserPageStateActions( : -1 const unifiedLabelNeedsRepair = unifiedIndex !== -1 && unifiedTabs[unifiedIndex]?.label !== nextPage.title - const pageStateUnchanged = - nextPage.title === page.title && - nextPage.loading === page.loading && - nextPage.faviconUrl === page.faviconUrl && - nextPage.canGoBack === page.canGoBack && - nextPage.canGoForward === page.canGoForward && - nextPage.loadError === page.loadError + const pageStateUnchanged = browserPageEqual(nextPage, page) + if (updates.loading === undefined) { + preserveBrowserPageLoadingOwner(page, pageStateUnchanged ? page : nextPage) + } else { + assignBrowserPageLoadingOwner(page, pageStateUnchanged ? page : nextPage, loadingOwner) + } const currentPages = s.browserPagesByWorkspace[workspace.id] ?? [] const mirroredWorkspace = pageStateUnchanged ? mirrorWorkspaceFromActivePage(workspace, currentPages) @@ -158,7 +167,10 @@ export function createBrowserPageStateActions( delete nextFailures[pageId] return { browserCertificateFailuresByPageId: nextFailures } } - if (!findPage(s.browserPagesByWorkspace, pageId) || current === failure) { + if ( + !findPage(s.browserPagesByWorkspace, pageId) || + browserCertificateFailureEqual(current, failure) + ) { return s } return { @@ -191,6 +203,7 @@ export function createBrowserPageStateActions( } // Keep document URL blank at navigation sink too; committing grants here leaks to persistence, publication and address bar. const nextPageUrl = page.docLocation ? ORCA_BROWSER_BLANK_URL : nextUrl + revokeBrowserPageLoadingOwner(page) const nextPages = (s.browserPagesByWorkspace[workspace.id] ?? []).map((entry) => entry.id === pageId ? { @@ -217,7 +230,9 @@ export function createBrowserPageStateActions( } } }) - get().setBrowserPageCertificateFailure(pageId, null) + if (!options?.preserveLoadError) { + get().setBrowserPageCertificateFailure(pageId, null) + } } } } diff --git a/src/renderer/src/store/slices/browser/pages/browser-page-viewport-actions.ts b/src/renderer/src/store/slices/browser/pages/browser-page-viewport-actions.ts index 7c3076387aa..2117a92d616 100644 --- a/src/renderer/src/store/slices/browser/pages/browser-page-viewport-actions.ts +++ b/src/renderer/src/store/slices/browser/pages/browser-page-viewport-actions.ts @@ -1,5 +1,6 @@ import type { BrowserSlice, BrowserSliceSet } from '../browser-slice-contract' import { findPage, findWorkspace } from './browser-page-records' +import { preserveBrowserPageLoadingOwner } from '@/lib/browser/browser-page-loading-ownership' export function createBrowserPageViewportActions( set: BrowserSliceSet @@ -15,9 +16,14 @@ export function createBrowserPageViewportActions( if (!workspace) { return s } - const nextPages = (s.browserPagesByWorkspace[workspace.id] ?? []).map((entry) => - entry.id === pageId ? { ...entry, viewportPresetId } : entry - ) + const nextPages = (s.browserPagesByWorkspace[workspace.id] ?? []).map((entry) => { + if (entry.id !== pageId) { + return entry + } + const nextPage = { ...entry, viewportPresetId } + preserveBrowserPageLoadingOwner(entry, nextPage) + return nextPage + }) return { browserPagesByWorkspace: { ...s.browserPagesByWorkspace, From cf02703c1380def9bd75676379d76000f19a5496 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:57:19 +0000 Subject: [PATCH 15/52] fix(browser): refuse exec commands that leave Orca's page; keep orcad Chromium headless (#42200) * fix(browser): keep agent-browser exec on Orca's page and orcad Chromium headless exec passed raw agent-browser argv through after stripping only --cdp and --session, so connect, tab/window, close, set viewport, batch items and global launch options could move the helper to another browser or create targets behind Orca's tab model. Refuse them in one shared gate used by the desktop bridge and orcad's external-Chromium provider. orcad's external-Chromium helper inherited AGENT_BROWSER_* and read the user's ~/.agent-browser/config.json and ./agent-browser.json, so headed or extensions settings opened a visible window. Drop inherited settings, point AGENT_BROWSER_CONFIG at an empty Orca-owned file and pin --headed false. * fix(browser): refuse inspect, stream and auth in exec and match agent-browser's batch escapes * fix(browser): retry orcad's agent-browser config write after a failure --- .../agent-browser/agent-browser-bridge.ts | 8 +- ...gent-browser-passthrough-arguments.test.ts | 43 ++++ .../agent-browser-passthrough-arguments.ts | 187 ++++++++++++++++-- ...rnal-chromium-agent-browser-environment.ts | 33 ++++ .../external-chromium-browser-session.test.ts | 34 +++- .../external-chromium-browser-session.ts | 50 ++--- .../external-chromium-command-arguments.ts | 75 +------ 7 files changed, 325 insertions(+), 105 deletions(-) create mode 100644 src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.test.ts create mode 100644 src/main/orcad/browser-providers/chromium/external-chromium-agent-browser-environment.ts diff --git a/src/main/browser/agent-browser/agent-browser-bridge.ts b/src/main/browser/agent-browser/agent-browser-bridge.ts index b746a98d472..521d9132ecd 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge.ts +++ b/src/main/browser/agent-browser/agent-browser-bridge.ts @@ -14,8 +14,8 @@ import type { } from '../../../shared/browser/runtime/runtime-browser-contracts' import { BrowserError } from '../browser-error' import { - parseShellArgs, - stripAgentBrowserTargetArgs + assertAgentBrowserPassthroughStaysOnPage, + parseShellArgs } from './protocol/agent-browser-passthrough-arguments' import { AgentBrowserBridgeInteractionCommands } from './commands/agent-browser-bridge-interaction-commands' import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' @@ -272,8 +272,8 @@ export class AgentBrowserBridge extends AgentBrowserBridgeInteractionCommands { } async exec(command: string, worktreeId?: string, browserPageId?: string): Promise { - // Passthrough arguments must not override Orca's selected page or CDP proxy. - const args = stripAgentBrowserTargetArgs(parseShellArgs(command.trim())) + const args = parseShellArgs(command.trim()) + assertAgentBrowserPassthroughStaysOnPage(args) return this.enqueueTargetedCommand( worktreeId, browserPageId, diff --git a/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.test.ts b/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.test.ts new file mode 100644 index 00000000000..dc0a7360d48 --- /dev/null +++ b/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest' +import { assertAgentBrowserPassthroughStaysOnPage } from './agent-browser-passthrough-arguments' + +describe('assertAgentBrowserPassthroughStaysOnPage', () => { + it.each([ + [['connect', '9222']], + [['tab', 'new']], + [['window', 'new']], + [['close']], + [['set', 'viewport', '800', '600']], + [['set', 'device', 'iPhone 15']], + [['click', '@e1', '--new-tab']], + [['get', 'text', '@e3', '--cdp', 'ws://127.0.0.1:9222']], + [['get', 'url', '--session=other']], + [['snapshot', '--auto-connect']], + [['open', 'https://example.com', '-p', 'browserbase']], + [['fill', '@e1', '--headed']], + [['batch', 'get title', 'connect 9222']], + [['batch', '--bail', 'tab new']], + [['batch', 'c\\onnect 9222']], + [['batch', 'close\\']], + [['inspect']], + [['stream', 'enable', '--port', '9999']], + [['auth', 'login', 'github', '--url', 'https://example.com/login']], + [['batch', 'batch "tab new"']], + [['batch', 'get url --cdp 9222']] + ])('refuses %j', (args) => { + expect(() => assertAgentBrowserPassthroughStaysOnPage(args)).toThrow( + expect.objectContaining({ code: 'invalid_argument' }) + ) + }) + + it.each([ + [['get', 'text', '@e3']], + [['read']], + [['is', 'visible', '@e3']], + [['set', 'media', 'dark']], + [['wait', '--text', 'Done']], + [['batch', '--bail', 'get title', 'snapshot -i']] + ])('runs %j', (args) => { + expect(() => assertAgentBrowserPassthroughStaysOnPage(args)).not.toThrow() + }) +}) diff --git a/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.ts b/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.ts index 1ba5a18c9cc..54cf322e2df 100644 --- a/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.ts +++ b/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.ts @@ -1,3 +1,5 @@ +import { BrowserError } from '../../browser-error' + export function parseShellArgs(input: string): string[] { const args: string[] = [] let current = '' @@ -25,18 +27,179 @@ export function parseShellArgs(input: string): string[] { return args } -export function stripAgentBrowserTargetArgs(args: string[]): string[] { - const stripped: string[] = [] - for (let index = 0; index < args.length; index++) { - const arg = args[index] - if (arg === '--cdp' || arg === '--session') { - index++ - continue +/** Splits a command line the way agent-browser splits each `batch` command (backslash escapes, quotes). */ +export function splitAgentBrowserCommandLine(input: string): string[] { + const args: string[] = [] + let value = '' + let quote: '"' | "'" | null = null + let escaped = false + for (const char of input.trim()) { + if (escaped) { + value += char + escaped = false + } else if (char === '\\' && quote !== "'") { + escaped = true + } else if (quote) { + if (char === quote) { + quote = null + } else { + value += char + } + } else if (char === '"' || char === "'") { + quote = char + } else if (/\s/.test(char)) { + if (value) { + args.push(value) + value = '' + } + } else { + value += char + } + } + // Like agent-browser, drop a trailing lone backslash: `close\` runs `close`. + if (quote) { + throw new BrowserError('invalid_argument', 'Browser command has an unclosed quote.') + } + if (value) { + args.push(value) + } + return args +} + +// agent-browser's global options (0.39 through 0.43). It reads them anywhere in argv, even after +// a command, and they choose the browser, session and launch, which Orca owns. +const GLOBAL_OPTIONS = new Set([ + '--action-policy', + '--allow-file-access', + '--allowed-domains', + '--annotate', + '--args', + '--auto-connect', + '--ca-cert', + '--capture', + '--cdp', + '--cdp-headers', + '--color-scheme', + '--config', + '--confirm-actions', + '--confirm-interactive', + '--content-boundaries', + '--debug', + '--device', + '--download-path', + '--enable', + '--engine', + '--executable-path', + '--extension', + '--fix', + '--headed', + '--headers', + '--hide-scrollbars', + '--idle-timeout', + '--ignore-https-errors', + '--init-script', + '--input-mode', + '--json', + '--max-output', + '--model', + '--namespace', + '--no-auto-connect', + '--no-auto-dialog', + '--no-ca-cert', + '--no-pin-tab', + '--no-webmcp', + '--offline', + '--pin-tab', + '--profile', + '--provider', + '--proxy', + '--proxy-bypass', + '--quick', + '--quiet', + '--relaunch', + '--restore', + '--restore-check-fn', + '--restore-check-text', + '--restore-check-url', + '--restore-save', + '--screenshot-dir', + '--screenshot-format', + '--screenshot-quality', + '--session', + '--session-name', + '--state', + '--use-system-ca', + '--user-agent', + '--verbose', + '--webgpu', + '-p', + '-q', + '-v' +]) + +const TAB_HINT = 'Use the typed tab commands (tab list, tab create, tab switch, tab close).' +const VIEWPORT_HINT = 'Use the typed viewport or set device command.' +const NOT_THE_PAGE = 'It acts outside the selected Orca page.' + +// Commands that leave Orca's page: connect/tab/window/close retarget or create targets behind +// Orca's tab model; inspect opens the system browser; stream serves an unguarded command relay; +// auth types agent-browser's saved logins into any URL; the rest act on the machine. +const REFUSED_COMMANDS = new Map([ + ['connect', NOT_THE_PAGE], + ['inspect', NOT_THE_PAGE], + ['stream', NOT_THE_PAGE], + ['auth', NOT_THE_PAGE], + ['tab', TAB_HINT], + ['window', TAB_HINT], + ['close', TAB_HINT], + ['quit', TAB_HINT], + ['exit', TAB_HINT], + ['state', NOT_THE_PAGE], + ['session', NOT_THE_PAGE], + ['install', NOT_THE_PAGE], + ['upgrade', NOT_THE_PAGE], + ['doctor', NOT_THE_PAGE], + ['dashboard', NOT_THE_PAGE], + ['profiles', NOT_THE_PAGE], + ['plugin', NOT_THE_PAGE], + ['plugins', NOT_THE_PAGE], + ['mcp', NOT_THE_PAGE], + ['chat', NOT_THE_PAGE] +]) + +function refuse(what: string, hint: string): never { + throw new BrowserError('invalid_argument', `exec does not run ${what}. ${hint}`) +} + +/** Refuses raw agent-browser lines that would move the helper off Orca's selected page. */ +export function assertAgentBrowserPassthroughStaysOnPage(args: readonly string[]): void { + for (const arg of args) { + const option = arg.split('=')[0] + if (GLOBAL_OPTIONS.has(option)) { + refuse(`agent-browser's global option ${option}`, 'Orca sets global options itself.') + } + } + const [command, subcommand] = args + if (!command) { + return + } + const refusal = REFUSED_COMMANDS.get(command) + if (refusal) { + refuse(`\`${command}\``, refusal) + } + // Both resize the real window around the page (Browser.setContentsSize). + if (command === 'set' && (subcommand === 'viewport' || subcommand === 'device')) { + refuse(`\`set ${subcommand}\``, VIEWPORT_HINT) + } + if (command === 'click' && args.includes('--new-tab')) { + refuse('`click --new-tab`', TAB_HINT) + } + if (command === 'batch') { + // agent-browser runs every operand except `--bail` as its own command line. + for (const step of args.slice(1)) { + if (step !== '--bail') { + assertAgentBrowserPassthroughStaysOnPage(splitAgentBrowserCommandLine(step)) + } } - if (arg.startsWith('--cdp=') || arg.startsWith('--session=')) { - continue - } - stripped.push(arg) } - return stripped } diff --git a/src/main/orcad/browser-providers/chromium/external-chromium-agent-browser-environment.ts b/src/main/orcad/browser-providers/chromium/external-chromium-agent-browser-environment.ts new file mode 100644 index 00000000000..5bd2c0dd856 --- /dev/null +++ b/src/main/orcad/browser-providers/chromium/external-chromium-agent-browser-environment.ts @@ -0,0 +1,33 @@ +// Both pick the socket directory, so dropping either loses a running helper and its live tabs. +const SOCKET_LOCATION_KEYS = new Set(['AGENT_BROWSER_SOCKET_DIR', 'AGENT_BROWSER_NAMESPACE']) + +// No idle timeout: this daemon owns the user’s remote Chromium and all its live tabs. +// agent-browser 0.33+ reads an unset timeout as one hour, so only "0" keeps it unbounded. +export function externalChromiumAgentBrowserEnvironment(options: { + inheritedEnv: NodeJS.ProcessEnv + executablePath: string + profilePath: string + sessionName: string + configPath: string + browserArgs?: readonly string[] +}): NodeJS.ProcessEnv { + // Only the socket location is inherited: a user's AGENT_BROWSER_HEADED or _EXTENSIONS would open a + // visible window. Windows env keys ignore case. + const env = Object.fromEntries( + Object.entries(options.inheritedEnv).filter(([key]) => { + const upper = key.toUpperCase() + return !upper.startsWith('AGENT_BROWSER_') || SOCKET_LOCATION_KEYS.has(upper) + }) + ) + return { + ...env, + AGENT_BROWSER_IDLE_TIMEOUT_MS: + options.inheritedEnv.AGENT_BROWSER_IDLE_TIMEOUT_MS?.trim() || '0', + AGENT_BROWSER_EXECUTABLE_PATH: options.executablePath, + AGENT_BROWSER_PROFILE: options.profilePath, + AGENT_BROWSER_SESSION: options.sessionName, + // An explicit config skips ~/.agent-browser/config.json and ./agent-browser.json. + AGENT_BROWSER_CONFIG: options.configPath, + AGENT_BROWSER_ARGS: options.browserArgs?.join('\n') ?? '' + } +} diff --git a/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts index 144fd9edec3..a25b07c0164 100644 --- a/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts @@ -12,7 +12,8 @@ vi.mock('node:fs/promises', () => ({ readFile: vi.fn(async () => Buffer.from('')), realpath: vi.fn(async (path: string) => path), access: vi.fn(async () => undefined), - rm: vi.fn(async () => undefined) + rm: vi.fn(async () => undefined), + writeFile: vi.fn(async () => undefined) })) import { ExternalChromiumBrowserSession } from './external-chromium-browser-session' @@ -41,6 +42,37 @@ describe('orcad external-chromium agent-browser environment', () => { vi.mocked(mkdir).mockClear() }) + it('launches headless with only Orca agent-browser settings', async () => { + runProcessMock.mockResolvedValue({ + code: 0, + signal: null, + stdout: JSON.stringify([{ success: true, result: { url: 'about:blank' } }]), + stderr: '', + timedOut: false + }) + vi.stubEnv('AGENT_BROWSER_HEADED', '1') + vi.stubEnv('agent_browser_extensions', '/ext') + vi.stubEnv('AGENT_BROWSER_SOCKET_DIR', '/tmp/ab-sockets') + try { + await new ExternalChromiumBrowserSession( + '/opt/orca/agent-browser', + { executablePath: BASE.executablePath, provider: 'chromium' }, + '/state' + ).run(['get', 'url']) + } finally { + vi.unstubAllEnvs() + } + const [spec] = runProcessMock.mock.calls[0] + const headed = spec.args?.indexOf('--headed') ?? -1 + expect(spec.args?.slice(headed, headed + 2)).toEqual(['--headed', 'false']) + expect(spec.env).toMatchObject({ + AGENT_BROWSER_SOCKET_DIR: '/tmp/ab-sockets', + AGENT_BROWSER_CONFIG: join('/state', 'agent-browser-config.json') + }) + expect(spec.env).not.toHaveProperty('AGENT_BROWSER_HEADED') + expect(spec.env).not.toHaveProperty('agent_browser_extensions') + }) + it('reports a ref whose element is gone as stale', async () => { runProcessMock.mockResolvedValue({ code: 1, diff --git a/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts index c014d87e5a7..fdcfc730f51 100644 --- a/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from 'node:crypto' -import { chmod, mkdir, readFile, rm } from 'node:fs/promises' +import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { z } from 'zod' import { BrowserError } from '../../../browser/browser-error' @@ -17,6 +17,7 @@ import { } from '../../../browser/agent-browser/observation/agent-browser-screenshot-arguments' import { runProcess } from '@orca/process-host' import { resolveExternalChromiumProfilePath } from './external-chromium-profile-path' +import { externalChromiumAgentBrowserEnvironment } from './external-chromium-agent-browser-environment' const COMMAND_TIMEOUT_MS = 90_000 const MAX_OUTPUT_BYTES = 50 * 1024 * 1024 @@ -73,26 +74,6 @@ function classifyAgentBrowserError(message: string): string { return 'browser_error' } -// No idle timeout: this daemon owns the user’s remote Chromium and all its live tabs. -// agent-browser 0.33+ reads an unset timeout as one hour, so only "0" keeps it unbounded. -export function externalChromiumAgentBrowserEnvironment(options: { - inheritedEnv: NodeJS.ProcessEnv - executablePath: string - profilePath: string - sessionName: string - browserArgs?: readonly string[] -}): NodeJS.ProcessEnv { - return { - ...options.inheritedEnv, - AGENT_BROWSER_IDLE_TIMEOUT_MS: - options.inheritedEnv.AGENT_BROWSER_IDLE_TIMEOUT_MS?.trim() || '0', - AGENT_BROWSER_EXECUTABLE_PATH: options.executablePath, - AGENT_BROWSER_PROFILE: options.profilePath, - AGENT_BROWSER_SESSION: options.sessionName, - AGENT_BROWSER_ARGS: options.browserArgs?.join('\n') ?? '' - } -} - // A profile held by another Chromium also fails ProcessSingleton; only an access failure means unwritable. function unwritableProfileLockLine(message: string): string | undefined { return message @@ -105,6 +86,7 @@ export class ExternalChromiumBrowserSession { private readonly identity: string private readonly sessionName: string private profilePathResolution: Promise | null = null + private configPathWrite: Promise | null = null constructor( private readonly agentBrowserPath: string, @@ -127,6 +109,26 @@ export class ExternalChromiumBrowserSession { return this.profilePathResolution } + // Empty, so agent-browser's defaults (headless, no extensions) apply instead of a user's config. + private configPath(): Promise { + if (!this.configPathWrite) { + const write = (async () => { + const path = join(this.statePath, 'agent-browser-config.json') + await mkdir(this.statePath, { recursive: true, mode: 0o700 }) + await writeFile(path, '{}\n', { mode: 0o600 }) + return path + })() + // A failed write retries on the next command instead of failing every later one. + write.catch(() => { + if (this.configPathWrite === write) { + this.configPathWrite = null + } + }) + this.configPathWrite = write + } + return this.configPathWrite + } + async start(signal?: AbortSignal): Promise { signal?.throwIfAborted() const profilePath = await this.profilePath() @@ -267,7 +269,10 @@ export class ExternalChromiumBrowserSession { signal?.throwIfAborted() const profilePath = await this.profilePath() signal?.throwIfAborted() - const args = ['--session', this.sessionName, '--profile', profilePath] + const configPath = await this.configPath() + signal?.throwIfAborted() + // Pinned per command so a daemon started headed by an older environment relaunches headless. + const args = ['--session', this.sessionName, '--profile', profilePath, '--headed', 'false'] if (this.launch.browserArgs?.length) { args.push('--args', this.launch.browserArgs.join('\n')) } @@ -277,6 +282,7 @@ export class ExternalChromiumBrowserSession { executablePath: this.launch.executablePath, profilePath, sessionName: this.sessionName, + configPath, browserArgs: this.launch.browserArgs }) const result = await runProcess({ diff --git a/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts b/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts index 8f7fa05b8d7..1fcdad2e183 100644 --- a/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts @@ -1,69 +1,9 @@ -import { BrowserError } from '../../../browser/browser-error' import { agentBrowserSetMediaArguments } from '../../../browser/agent-browser/protocol/agent-browser-set-media-arguments' import { agentBrowserWaitArguments } from '../../../browser/agent-browser/protocol/agent-browser-wait-arguments' -const TARGET_OVERRIDE_FLAGS: Record = { - '--args': true, - '--cdp': true, - '--executable-path': true, - '--profile': true, - '--session': true -} -const TARGET_OVERRIDE_FLAG_PREFIXES = Object.keys(TARGET_OVERRIDE_FLAGS).map((flag) => `${flag}=`) - -function parseExecArguments(input: string): string[] { - const args: string[] = [] - let value = '' - let quote: '"' | "'" | null = null - let escaped = false - for (const char of input.trim()) { - if (escaped) { - value += char - escaped = false - } else if (char === '\\' && quote !== "'") { - escaped = true - } else if (quote) { - if (char === quote) { - quote = null - } else { - value += char - } - } else if (char === '"' || char === "'") { - quote = char - } else if (/\s/.test(char)) { - if (value) { - args.push(value) - value = '' - } - } else { - value += char - } - } - if (escaped) { - value += '\\' - } - if (quote) { - throw new BrowserError('invalid_argument', 'Browser command has an unclosed quote.') - } - if (value) { - args.push(value) - } - return args -} -function stripTargetOverrideArguments(args: string[]): string[] { - const stripped: string[] = [] - for (let index = 0; index < args.length; index++) { - const arg = args[index] - if (TARGET_OVERRIDE_FLAGS[arg]) { - index++ - continue - } - if (TARGET_OVERRIDE_FLAG_PREFIXES.some((prefix) => arg.startsWith(prefix))) { - continue - } - stripped.push(arg) - } - return stripped -} +import { + assertAgentBrowserPassthroughStaysOnPage, + splitAgentBrowserCommandLine +} from '../../../browser/agent-browser/protocol/agent-browser-passthrough-arguments' export function externalChromiumWaitCommand( params: Record @@ -214,8 +154,11 @@ export function externalChromiumCommandArguments( return ['network', 'har', 'start'] case 'browserCaptureStop': return ['network', 'har', 'stop'] - case 'browserExec': - return stripTargetOverrideArguments(parseExecArguments(text('command'))) + case 'browserExec': { + const args = splitAgentBrowserCommandLine(text('command')) + assertAgentBrowserPassthroughStaysOnPage(args) + return args + } case 'browserSetViewport': if ( params.mobile === true || From 62b22aeab0931c9abc277c1397efb0fbdf5ded86 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:58:33 +0000 Subject: [PATCH 16/52] fix(computer-use): read minimized, hidden and other-Space macOS windows without --restore-window (#42182) * fix(computer-use): observe minimized, hidden and other-Space windows on macOS without a restore macOS only enumerated on-screen windows and dropped minimized AX windows, so an app whose window was minimized, hidden or on another Space (any full-screen app) could not be observed, and agents fell back to --restore-window, which activated every window of the app and switched the user's Space. Enumerate every window, keep the off-screen ones accessibility can still read (other-Space windows by remote token, closed windows dropped by their Space membership), and report their real minimized and off-screen state. Background pointer and key input on such a window refuses before sending anything. --restore-window now raises only the target window, once per request, and delivery is measured from whether the target became frontmost. * fix(computer-use): pin the restored window and prefer visible windows by default * fix(computer-use): keep window-index cache keys and stale-element checks across a restore * fix(computer-use): restore only this app's resolved window and refuse a closed target before raising * docs(computer-use): say macOS reads minimized, hidden and other-Space windows --- docs/site/content/docs/cli/computer-use.mdx | 2 +- .../Sources/OrcaComputerUseMacOS/main.swift | 405 +++++++++++++----- .../ForegroundDelivery.swift | 27 ++ .../RemoteAccessibilityWindows.swift | 56 +++ .../WindowSpaces.swift | 40 ++ .../ForegroundDeliveryTests.swift | 25 ++ skill-guides/orca-computer-use.md | 2 +- src/cli/skills/bundled-skill-guides.ts | 2 +- src/shared/computer-use-error-recovery.ts | 4 +- 9 files changed, 446 insertions(+), 117 deletions(-) create mode 100644 native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ForegroundDelivery.swift create mode 100644 native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/RemoteAccessibilityWindows.swift create mode 100644 native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/WindowSpaces.swift create mode 100644 native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ForegroundDeliveryTests.swift diff --git a/docs/site/content/docs/cli/computer-use.mdx b/docs/site/content/docs/cli/computer-use.mdx index 55abc66c7ce..d49e6db2151 100644 --- a/docs/site/content/docs/cli/computer-use.mdx +++ b/docs/site/content/docs/cli/computer-use.mdx @@ -116,7 +116,7 @@ On Linux and Windows, action payloads also pass briefly through a local operatio ## Screenshots -`get-app-state` returns an accessibility tree and, by default, a screenshot. With `--json`, the image bytes are written to disk and the path is returned in `screenshot.path` rather than embedded in the response. Pass `--no-screenshot` when pixels aren't needed (faster, smaller payload). On macOS, a window that is minimized, hidden or on another Space can't be read; bring it on screen, or pass `--restore-window` to have Orca bring it forward. +`get-app-state` returns an accessibility tree and, by default, a screenshot. With `--json`, the image bytes are written to disk and the path is returned in `screenshot.path` rather than embedded in the response. Pass `--no-screenshot` when pixels aren't needed (faster, smaller payload). On macOS, a window that is minimized or hidden has no pixels, so the screenshot fails while the accessibility tree still comes back; a window on another Space is captured. On Wayland, screenshots work on KDE Plasma, Hyprland and Sway. On Hyprland and Sway they need `grim`, GdkPixbuf, and `hyprctl` or `swaymsg`; Orca finds the target window by process ID and title and captures its region, so overlapping windows can show in the image. diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift index 32fd7405f3b..c3cc58c2c3f 100644 --- a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift @@ -156,6 +156,7 @@ struct Snapshot { let windowBounds: CGRect let windowId: CGWindowID let windowLayer: Int + let windowVisibility: WindowVisibility let treeText: String let focusedElementId: Int? let screenshot: ScreenshotPayload? @@ -173,6 +174,7 @@ struct Snapshot { func showsSameState(as other: Snapshot) -> Bool { treeText == other.treeText && windowBounds == other.windowBounds && appWindowIds == other.appWindowIds + && windowVisibility == other.windowVisibility } func withoutScreenshotPayload() -> Snapshot { @@ -183,6 +185,7 @@ struct Snapshot { windowBounds: windowBounds, windowId: windowId, windowLayer: windowLayer, + windowVisibility: windowVisibility, treeText: treeText, focusedElementId: focusedElementId, screenshot: nil, @@ -212,6 +215,31 @@ struct CapturedImage { let engine: String } +/// Where an observed window is; only an on-screen one can take background pointer or key input. +enum WindowVisibility { + case onScreen + case minimized + case appHidden + case otherSpace + + var reason: String { + switch self { + case .onScreen: "is on screen" + case .minimized: "is minimized" + case .appHidden: "belongs to a hidden app" + case .otherSpace: "is on another Space" + } + } +} + +/// A window an agent can observe: on screen, or off screen with an accessibility element it can still read. +private struct ObservableWindow { + let candidate: WindowCandidate + /// Off-screen windows carry the element found for them; on-screen ones are matched later. + let element: AXUIElement? + let visibility: WindowVisibility +} + enum ScreenshotStatus { case captured case skipped @@ -224,9 +252,25 @@ private struct CachedSnapshotEntry { let createdAt: Date } +private struct OtherSpaceLookups { + var elements: [CGWindowID: AXUIElement] = [:] + var misses: [CGWindowID: Date] = [:] +} + +/// The app's observable windows, plus other-Space windows that exist but accessibility can't read yet. +private struct WindowInventory { + let windows: [ObservableWindow] + let unreadableOtherSpace: Set + /// Every window the app has, closed-but-kept ones included. + let windowIds: Set +} + final class Provider { private var snapshots: [String: Snapshot] = [:] private var snapshotEntries: [CachedSnapshotEntry] = [] + /// Per app, window elements already read (valid while the window lives) for when a window moves to another Space, + /// and when a remote-token lookup last missed, since a window becomes findable only once some client reads it. + private var otherSpaceLookups: [pid_t: OtherSpaceLookups] = [:] init() { // Why: the system-wide element sets the wait for every AX call in this process, so a hung app costs one bounded timeout whatever the macOS default. @@ -242,50 +286,60 @@ final class Provider { case "listWindows": return try listWindows(params: params) case "getAppState": + let params = isForegroundRequest(params) ? try recoverRequestedWindow(params: params) : params return try renderSnapshot(observe(params: params)) case "click": - return try actionResult(params: params) { try click(params: params) } + return try actionResult(params: params) { try click(params: $0) } case "performSecondaryAction": - return try actionResult(params: params) { try performSecondaryAction(params: params) } + return try actionResult(params: params) { try performSecondaryAction(params: $0) } case "setValue": - return try actionResult(params: params) { try setValue(params: params) } + return try actionResult(params: params) { try setValue(params: $0) } case "typeText": - return try actionResult(params: params) { try typeText(params: params) } + return try actionResult(params: params) { try typeText(params: $0) } case "pressKey": - return try actionResult(params: params) { try pressKey(params: params) } + return try actionResult(params: params) { try pressKey(params: $0) } case "hotkey": - return try actionResult(params: params) { try hotkey(params: params) } + return try actionResult(params: params) { try hotkey(params: $0) } case "pasteText": - return try actionResult(params: params) { try pasteText(params: params) } + return try actionResult(params: params) { try pasteText(params: $0) } case "scroll": - return try actionResult(params: params) { try scroll(params: params) } + return try actionResult(params: params) { try scroll(params: $0) } case "drag": - return try actionResult(params: params) { try drag(params: params) } + return try actionResult(params: params) { try drag(params: $0) } default: throw ProviderError.coded("invalid_argument", "unknown method '\(method)'") } } - private func actionResult(params: [String: JSONValue], action runAction: () throws -> [String: Any]) throws -> [String: Any] { - var action = try runAction() - // Why: only --restore-window activates the app or posts to the HID tap; every other route leaves the user's desktop alone. - action["delivery"] = isForegroundRequest(params) ? "foreground" : "background" + private func actionResult(params requestParams: [String: JSONValue], action runAction: ([String: JSONValue]) throws -> [String: Any]) throws -> [String: Any] { + let app = try resolveApp(try requiredString(requestParams, "app")) + // Why: the main run loop keeps NSRunningApplication current while requests run on connection threads. + let frontBefore = ForegroundDelivery.Observation( + frontmost: app.app.isActive, + focusedWindowID: app.app.isActive ? focusedWindowId(of: app) : nil + ) + // Why: raise once, before the action's reads, so the pre and post observations never raise again. + let params = isForegroundRequest(requestParams) ? try recoverRequestedWindow(params: requestParams) : requestParams + var action = try runAction(params) // Why: the action's currentSnapshot just cached this target's tree from before the action; // a subtree read can't be compared with the whole-window read that follows. let before = action["path"] as? String == "accessibility" && action["verification"] == nil ? (try? cachedSnapshot(params: params)).flatMap { $0.scope == nil ? $0 : nil } : nil + let snapshot: Snapshot do { let after = try observe(params: params) - guard let before, after.showsSameState(as: before) else { - return renderActionResult(action: action, snapshot: after) + if let before, after.showsSameState(as: before) { + if let changed = try observeLateChange(before: before, params: params) { + snapshot = changed + } else { + // Why: an AX call can succeed and do nothing, as AXPress does on many web controls (#31758). + action["verification"] = unverifiedAction(reason: "suspected_noop") + snapshot = after + } + } else { + snapshot = after } - if let changed = try observeLateChange(before: before, params: params) { - return renderActionResult(action: action, snapshot: changed) - } - // Why: an AX call can succeed and do nothing, as AXPress does on many web controls (#31758). - action["verification"] = unverifiedAction(reason: "suspected_noop") - return renderActionResult(action: action, snapshot: after) } catch let error as ProviderError where (error.code == "window_not_found" || error.code == "window_stale") && hasRequestedWindowSelector(params) { var fallbackParams = params fallbackParams.removeValue(forKey: "windowId") @@ -293,35 +347,130 @@ final class Provider { if action["verification"] == nil { action["verification"] = ["state": "unverified", "reason": "window_changed"] } - return try renderActionResult(action: action, snapshot: observe(params: fallbackParams)) + snapshot = try observe(params: fallbackParams) } + // Why: measured after the settle reads, since apps that activate themselves on AXPress (Electron, sheet openers) do it a turn later. + let frontAfter = frontmostObservation(of: app) + let tookForeground = ForegroundDelivery.tookForeground( + before: frontBefore, + after: frontAfter, + targetWindowID: snapshot.windowId, + restoreRequested: isForegroundRequest(params) + ) + action["delivery"] = tookForeground ? "foreground" : "background" + return renderActionResult(action: action, snapshot: snapshot) } /// Re-reads the target for about a second, since apps often apply an action on a later run-loop turn. /// Returns the observation to report once something changed, or nil if nothing did. private func observeLateChange(before: Snapshot, params: [String: JSONValue]) throws -> Snapshot? { - let settleParams = params.merging(["restoreWindow": .bool(false)]) { _, replacement in replacement } - let quietParams = settleParams.merging(["noScreenshot": .bool(true)]) { _, replacement in replacement } + let quietParams = params.merging(["noScreenshot": .bool(true)]) { _, replacement in replacement } let deadline = Date().addingTimeInterval(1) while Date() < deadline { Thread.sleep(forTimeInterval: 0.2) let polled = try observe(params: quietParams) if !polled.showsSameState(as: before) { if params["noScreenshot"]?.bool == true { return polled } - return try observe(params: settleParams) + return try observe(params: params) } } return nil } + /// Brings the requested window forward for --restore-window, once per request, and returns the params pinned + /// to that window: raising reorders the window list, so a --window-index could name another window afterwards. + private func recoverRequestedWindow(params: [String: JSONValue]) throws -> [String: JSONValue] { + let app = try resolveApp(try requiredString(params, "app")) + // Why: the window-index cache keys are not per app, so another app's snapshot can sit under the same index. + let cached = try cachedSnapshot(params: params).flatMap { $0.app.pid == app.pid ? $0 : nil } + // Why: a stale index fails after the raise, which would take over the user's screen for nothing. + try requireCachedElements(cached: cached, requestedIndexes: try requestedElementIndexes(params)) + let windows = windowInventory(app: app, appElement: AXUIElementCreateApplication(app.pid)).windows + let byIndex = try requestedWindowIndex(params).flatMap { index in + windows.filter { $0.candidate.layer == 0 }.dropFirst(index).first?.candidate.windowId + } + // Why: the cached snapshot is the window the agent's element indexes were read from, even if the index now names another. + let windowId = try requestedWindowId(params) ?? cached?.windowId ?? byIndex + let target = windowId.flatMap { id in windows.first { $0.candidate.windowId == id } } + if let requested = try requestedWindowId(params), target == nil { + throw ProviderError.coded("window_not_found", "window \(Int(requested)) of \(app.name) is closed or cannot be read, so nothing was raised; run list-windows and pick a listed window") + } + recoverWindow(app, windowId: windowId, windowBounds: target?.candidate.bounds ?? cached?.windowBounds, fallback: target?.element) + guard let windowId else { return params } + // Why: the raise reorders windows and focus, so later reads must not pick the target again; the id wins over + // the index when both are set, and the index still keys the snapshot cache. + var pinned = params + pinned["windowId"] = .number(Double(windowId)) + return pinned + } + + /// On-screen windows, plus minimized, hidden and other-Space windows that accessibility can still read. + private func windowInventory(app: AppDescriptor, appElement: AXUIElement) -> WindowInventory { + let all = WindowCapture.candidates(pid: app.pid, includeOffScreen: true) + let offScreen = all.filter { !$0.isOnScreen && $0.layer == 0 } + var elements: [CGWindowID: AXUIElement] = [:] + var unreadable = Set() + if !offScreen.isEmpty { + var listed: CFTypeRef? + let status = AXUIElementCopyAttributeValue(appElement, kAXWindowsAttribute as CFString, &listed) + for window in (listed as? [AXUIElement]) ?? [] { + if let id = windowNumber(window) { elements[id] = window } + } + let unlisted = offScreen.map(\.windowId).filter { elements[$0] == nil } + // Why: closed windows the app keeps belong to no Space; without SkyLight, try them all. + let inSpaces = WindowSpaces.windowsInAnySpace(unlisted) ?? Set(unlisted) + // Why: kAXWindowsAttribute leaves out windows on other Spaces; skip the lookup when the app stopped answering. + if status != .cannotComplete { + let live = Set(all.map(\.windowId)) + elements.merge(otherSpaceWindows(pid: app.pid, windowIds: inSpaces, live: live)) { listed, _ in listed } + } + unreadable = inSpaces.subtracting(elements.keys) + } + var appHidden: Bool? + let windows = all.compactMap { candidate -> ObservableWindow? in + if candidate.isOnScreen { + return ObservableWindow(candidate: candidate, element: nil, visibility: .onScreen) + } + guard candidate.layer == 0, let element = elements[candidate.windowId] else { return nil } + let visibility: WindowVisibility + if boolAttribute(element, kAXMinimizedAttribute as String) == true { + visibility = .minimized + } else { + if appHidden == nil { appHidden = boolAttribute(appElement, kAXHiddenAttribute as String) == true } + visibility = appHidden == true ? .appHidden : .otherSpace + } + return ObservableWindow(candidate: candidate, element: element, visibility: visibility) + } + return WindowInventory(windows: windows, unreadableOtherSpace: unreadable, windowIds: Set(all.map(\.windowId))) + } + + private func otherSpaceWindows(pid: pid_t, windowIds: Set, live: Set) -> [CGWindowID: AXUIElement] { + var lookups = otherSpaceLookups[pid] ?? OtherSpaceLookups() + lookups.elements = lookups.elements.filter { live.contains($0.key) && windowNumber($0.value) == $0.key } + lookups.misses = lookups.misses.filter { live.contains($0.key) } + let wanted = windowIds.filter { id in + lookups.elements[id] == nil && lookups.misses[id].map { Date().timeIntervalSince($0) >= 10 } ?? true + } + if !wanted.isEmpty { + let found = RemoteAccessibilityWindows.windows(pid: pid, wanted: wanted) + for id in wanted { + if let element = found[id] { + lookups.elements[id] = element + } else { + lookups.misses[id] = Date() + } + } + } + otherSpaceLookups = otherSpaceLookups.filter { pidIsLive($0.key) } + otherSpaceLookups[pid] = lookups + return lookups.elements.filter { windowIds.contains($0.key) } + } + private func observe(params: [String: JSONValue]) throws -> Snapshot { let query = try requiredString(params, "app") let windowId = try requestedWindowId(params) let windowIndex = try requestedWindowIndex(params) let app = try resolveApp(query) - if params["restoreWindow"]?.bool == true { - recoverWindow(app) - } let namespace = snapshotNamespace(params) pruneSnapshotCache() let subtree = try requestedSubtree(params: params, app: app) @@ -330,7 +479,6 @@ final class Provider { includeScreenshot: params["noScreenshot"]?.bool != true, windowId: subtree.map(\.base.windowId) ?? windowId, windowIndex: subtree == nil ? windowIndex : nil, - restoreWindow: params["restoreWindow"]?.bool == true, subtree: subtree, previousSnapshot: { [snapshots] resolvedWindowId in // Why: indexes carry over from this caller's own last view of exactly this window. @@ -511,11 +659,19 @@ final class Provider { } } - private func validateRequestedElements(cached: Snapshot?, current: Snapshot, requestedIndexes: [Int]) throws { + private func requireCachedElements(cached: Snapshot?, requestedIndexes: [Int]) throws { guard !requestedIndexes.isEmpty else { return } guard let cached else { throw ProviderError.coded("element_not_found", "element indexes require a fresh get-app-state snapshot for this app/window") } + for index in requestedIndexes where cached.elements[index] == nil { + throw ProviderError.coded("element_not_found", "element \(index) is stale; run get-app-state again and use a fresh element index") + } + } + + private func validateRequestedElements(cached: Snapshot?, current: Snapshot, requestedIndexes: [Int]) throws { + try requireCachedElements(cached: cached, requestedIndexes: requestedIndexes) + guard let cached else { return } for index in requestedIndexes { // Why: a subtree read also carries the window's earlier records, which prove nothing about the element now. guard let expected = cached.elements[index], @@ -648,11 +804,12 @@ final class Provider { private func listWindows(params: [String: JSONValue]) throws -> [String: Any] { let app = try resolveApp(try requiredString(params, "app")) - let windows = WindowCapture.candidates(pid: app.pid) - .filter { $0.layer == 0 } + let windows = windowInventory(app: app, appElement: AXUIElementCreateApplication(app.pid)).windows + .filter { $0.candidate.layer == 0 } .enumerated() - .map { index, candidate -> [String: Any] in - [ + .map { index, window -> [String: Any] in + let candidate = window.candidate + return [ "index": index, "app": [ "name": app.name, @@ -665,8 +822,8 @@ final class Provider { "y": Int(candidate.bounds.origin.y.rounded()), "width": Int(candidate.bounds.width.rounded()), "height": Int(candidate.bounds.height.rounded()), - "isMinimized": false, - "isOffscreen": !candidate.isOnScreen, + "isMinimized": window.visibility == .minimized, + "isOffscreen": window.visibility != .onScreen, "screenIndex": jsonNullable(screenIndex(for: candidate.bounds)), "isMain": NSNull(), "platform": [ @@ -696,7 +853,6 @@ final class Provider { includeScreenshot: Bool, windowId: CGWindowID?, windowIndex: Int?, - restoreWindow: Bool, subtree: (root: ElementRecord, base: Snapshot)?, previousSnapshot: (CGWindowID) -> Snapshot? ) throws -> Snapshot { @@ -716,27 +872,36 @@ final class Provider { throw AccessibilityMessaging.appNotResponding(app.name) } enableManualAccessibilityIfNeeded(appElement, app: app) - let windowCandidates = WindowCapture.candidates(pid: app.pid) - let focused = try focusedWindow( - appElement: appElement, - app: app, - visibleWindowCount: windowCandidates.count, - allowRecovery: restoreWindow - ) + let inventory = windowInventory(app: app, appElement: appElement) + let observable = inventory.windows + let focused = try focusedWindow(appElement: appElement, app: app, inventory: inventory) let focusedTitle = stringAttribute(focused, kAXTitleAttribute as String) ?? app.name let canCaptureScreenshot = includeScreenshot && screenCaptureTrustedSettled() guard let capture = WindowCapture.resolve( - candidates: windowCandidates, + candidates: observable.map(\.candidate), titleHint: focusedTitle, windowId: windowId, windowIndex: windowIndex, captureImage: canCaptureScreenshot ) else { - throw ProviderError.coded("window_not_found", "app '\(app.name)' has no on-screen window") + if let windowId, inventory.unreadableOtherSpace.contains(windowId) { + throw unreadableOtherSpaceError(app) + } + let reason = windowId != nil || windowIndex != nil ? "no window matching the requested selector; run list-windows and pick a listed one" : "no window to observe" + throw ProviderError.coded("window_not_found", "app '\(app.name)' has \(reason)") } - guard let window = matchingWindow(appElement: appElement, capture: capture, focused: focused, explicitTarget: windowId != nil || windowIndex != nil) else { + let target = observable.first { $0.candidate.windowId == capture.windowId } + let visibility = target?.visibility ?? .onScreen + guard let window = target?.element ?? matchingWindow(appElement: appElement, capture: capture, focused: focused, explicitTarget: windowId != nil || windowIndex != nil) else { throw ProviderError.coded("window_not_found", "could not match accessibility window to requested window; run get-app-state again or retry without a window selector") } + // Why: a window first read after a large tree walk gets a remote-token id past the lookup's range, so keep the element + // for when the window moves to another Space. + otherSpaceLookups = otherSpaceLookups.filter { pidIsLive($0.key) } + var lookups = otherSpaceLookups[app.pid] ?? OtherSpaceLookups() + lookups.elements = lookups.elements.filter { inventory.windowIds.contains($0.key) } + lookups.elements[capture.windowId] = window + otherSpaceLookups[app.pid] = lookups let title = stringAttribute(window, kAXTitleAttribute as String) ?? capture.title ?? app.name let renderer = TreeRenderer( windowBounds: capture.bounds, @@ -771,6 +936,8 @@ final class Provider { .captured } else if includeScreenshot && !canCaptureScreenshot { .failed("Screen Recording permission is required for Orca Computer Use; grant permission or pass --no-screenshot to inspect accessibility state only.") + } else if includeScreenshot && visibility != .onScreen { + .failed("the window \(visibility.reason), so it has no pixels to capture; the accessibility tree is still current. Pass --no-screenshot to skip the capture.") } else if includeScreenshot { .failed("window screenshot capture returned no image; retry with --no-screenshot if accessibility state is sufficient.") } else { @@ -783,6 +950,7 @@ final class Provider { windowBounds: capture.bounds, windowId: capture.windowId, windowLayer: capture.layer, + windowVisibility: visibility, treeText: renderTreeText(app: app, title: title, rootIndex: subtree?.root.index, lines: renderer.lines, focused: renderer.focusedSummary), focusedElementId: renderer.focusedElementId, screenshot: screenshot, @@ -795,7 +963,7 @@ final class Provider { truncated: renderer.truncated, maxDepthReached: renderer.maxDepthReached, scope: subtree.map { SnapshotScope(rootIndex: $0.root.index, walkedIndexes: Set(indexes.order)) }, - appWindowIds: windowCandidates.map(\.windowId).sorted() + appWindowIds: observable.filter { $0.visibility == .onScreen }.map(\.candidate.windowId).sorted() ) } @@ -824,8 +992,8 @@ final class Provider { "y": Int(snapshot.windowBounds.origin.y.rounded()), "width": Int(snapshot.windowBounds.width.rounded()), "height": Int(snapshot.windowBounds.height.rounded()), - "isMinimized": false, - "isOffscreen": false, + "isMinimized": snapshot.windowVisibility == .minimized, + "isOffscreen": snapshot.windowVisibility != .onScreen, "screenIndex": jsonNullable(screenIndex(for: snapshot.windowBounds)), "platform": [ "layer": snapshot.windowLayer, @@ -872,9 +1040,6 @@ final class Provider { } let modifiers = try KeyMap.parseModifiers(params["modifiers"]?.string) let foreground = isForegroundRequest(params) - if foreground { - recoverWindow(snapshot.app, windowId: snapshot.windowId, windowBounds: snapshot.windowBounds) - } if let elementIndex = try optionalInteger(params, "elementIndex") { let record = try element(snapshot, elementIndex) try requireEnabled(record, snapshot: snapshot) @@ -897,6 +1062,9 @@ final class Provider { actionName: actionName ) } + if !foreground { + try requireBackgroundInputReachable(snapshot, input: "pointer click") + } let point = try pointerTarget(record, snapshot: snapshot) try clickPointer(at: point, button: button, count: count, modifiers: modifiers, snapshot: snapshot, foreground: foreground, element: record.element) guard unselectedRow else { @@ -912,6 +1080,9 @@ final class Provider { actionName: nil ) } + if !foreground { + try requireBackgroundInputReachable(snapshot, input: "pointer click") + } let point = try coordinatePoint(params: params, xKey: "x", yKey: "y", snapshot: snapshot) try clickPointer(at: point, button: button, count: count, modifiers: modifiers, snapshot: snapshot, foreground: foreground) return actionMetadata( @@ -1125,6 +1296,10 @@ final class Provider { return actionMetadata(path: "accessibility", actionName: "AXReplaceSelection", verification: verification) } let pasteKeys = try Input.keyEvents("cmd+v") + if !isForegroundRequest(params) { + // Why: refuse before the clipboard is replaced, so clipboard history never records text that was not sent. + try requireBackgroundInputReachable(snapshot, input: "paste") + } let insertion = TextInput.Insertion(into: focused, text: text) try Input.withPasteboardText(text) { try deliverKeys(pasteKeys, snapshot: snapshot, params: params) @@ -1186,6 +1361,7 @@ final class Provider { try requireTargetWindowFocused(snapshot, restoreWindowRequested: true) try Input.drag(from: start, to: end, targetWindow: snapshot) } else { + try requireBackgroundInputReachable(snapshot, input: "drag") // Why: the mouse-down lands on whatever is under the start point, which can open a menu over the user. guard let startElement = elementAtPoint(start, pid: snapshot.app.pid) ?? fromRecord?.element else { throw unidentifiedBackgroundTarget @@ -1357,18 +1533,13 @@ private func enableManualAccessibilityIfNeeded(_ appElement: AXUIElement, app: A } } -private func focusedWindow(appElement: AXUIElement, app: AppDescriptor, visibleWindowCount: Int, allowRecovery: Bool) throws -> AXUIElement { +private func focusedWindow(appElement: AXUIElement, app: AppDescriptor, inventory: WindowInventory) throws -> AXUIElement { + let observable = inventory.windows let systemWide = AXUIElementCreateSystemWide() if let window = lookupUsableWindow(systemWide: systemWide, appElement: appElement, app: app) { return window } - if allowRecovery { - recoverWindow(app) - if let window = lookupUsableWindow(systemWide: systemWide, appElement: appElement, app: app) { - return window - } - } - if visibleWindowCount > 0 { + if observable.contains(where: { $0.visibility == .onScreen }) { var settledWindow: AXUIElement? let outcome = PermissionTrustSettling.settle { settledWindow = lookupUsableWindow( @@ -1381,12 +1552,26 @@ private func focusedWindow(appElement: AXUIElement, app: AppDescriptor, visibleW if let window = settledWindow, outcome.settled { return window } - throw ProviderError.coded("permission_denied", "app '\(app.name)' has visible windows but no accessibility window (AX reads stayed blocked for \(outcome.waitedMs)ms after retries). macOS Accessibility may need Orca Computer Use toggled off and on again in System Settings.") + var windows: CFTypeRef? + if AXUIElementCopyAttributeValue(appElement, kAXWindowsAttribute as CFString, &windows) == .apiDisabled { + throw ProviderError.coded("permission_denied", "app '\(app.name)' has visible windows but macOS refuses accessibility reads (AX reads stayed blocked for \(outcome.waitedMs)ms after retries). macOS Accessibility may need Orca Computer Use toggled off and on again in System Settings.") + } } - if allowRecovery { - throw ProviderError.coded("window_not_found", "app '\(app.name)' has no accessibility window even after --restore-window; ask the user to open or show one of its windows.") + let offScreen = observable.filter { $0.element != nil } + if let window = (offScreen.first { $0.visibility != .minimized } ?? offScreen.first)?.element { + return window } - throw ProviderError.coded("window_not_found", "app '\(app.name)' has no accessibility window; it may have none open, or they may be minimized, hidden or on another Space. Ask the user to bring one on screen, or ask the user before retrying with --restore-window.") + if observable.contains(where: { $0.visibility == .onScreen }) { + throw ProviderError.coded("window_not_found", "app '\(app.name)' has visible windows but exposes no accessibility window; it may still be starting up. Run get-app-state again shortly.") + } + if !inventory.unreadableOtherSpace.isEmpty { + throw unreadableOtherSpaceError(app) + } + throw ProviderError.coded("window_not_found", "app '\(app.name)' has no open window, counting minimized, hidden and other-Space windows; open one in the app first.") +} + +private func unreadableOtherSpaceError(_ app: AppDescriptor) -> ProviderError { + .coded("window_not_found", "app '\(app.name)' has a window on another Space that accessibility cannot read yet: macOS leaves other-Space windows (full-screen ones included) out of accessibility until something has read them once. Ask the user to show that window (switch to its Space) and run get-app-state while it is showing, or ask the user before retrying with --restore-window.") } private func lookupUsableWindow( @@ -1628,6 +1813,21 @@ private func isForegroundRequest(_ params: [String: JSONValue]) -> Bool { params["restoreWindow"]?.bool == true } +/// Refuses, before anything is sent, background pointer or key input the window cannot receive while off screen. +private func requireBackgroundInputReachable(_ snapshot: Snapshot, input: String) throws { + guard snapshot.windowVisibility != .onScreen else { return } + throw ProviderError.coded("background_unavailable", "window \(Int(snapshot.windowId)) of \(snapshot.app.name) \(snapshot.windowVisibility.reason), so background \(input) cannot reach it without bringing it forward; nothing was sent. Use its elements instead (click --element-index, set-value, type-text --element-index). Ask the user before retrying with --restore-window.") +} + +private func frontmostObservation(of app: AppDescriptor) -> ForegroundDelivery.Observation { + let frontmost = boolAttribute(AXUIElementCreateApplication(app.pid), kAXFrontmostAttribute as String) == true + return ForegroundDelivery.Observation(frontmost: frontmost, focusedWindowID: frontmost ? focusedWindowId(of: app) : nil) +} + +private func focusedWindowId(of app: AppDescriptor) -> CGWindowID? { + copyElement(AXUIElementCreateApplication(app.pid), kAXFocusedWindowAttribute as String).flatMap(windowNumber) +} + private func backgroundTarget(_ snapshot: Snapshot) -> BackgroundInputTransport.Target { BackgroundInputTransport.Target(pid: snapshot.app.pid, windowID: snapshot.windowId, windowFrame: snapshot.windowBounds) } @@ -1737,6 +1937,7 @@ private func scrollPointer(at point: CGPoint, direction: String, pages: Double, try Input.scroll(at: point, wheel1: wheel1, wheel2: wheel2, targetWindow: snapshot) return } + try requireBackgroundInputReachable(snapshot, input: "scroll") try withTransportErrors { try BackgroundInputTransport.scroll(backgroundTarget(snapshot), at: point, wheel1: wheel1, wheel2: wheel2) } @@ -1750,6 +1951,7 @@ private func deliverKeys(_ events: [CGEvent], snapshot: Snapshot, params: [Strin } return } + try requireBackgroundInputReachable(snapshot, input: "key input") try withTransportErrors { try BackgroundInputTransport.sendKeys(events, to: backgroundTarget(snapshot)) } @@ -1786,16 +1988,14 @@ private func matchingWindow(appElement: AXUIElement, capture: WindowCapture, foc } ?? focused } +/// Brings only the target window forward: no other window of the app, and no LaunchServices reopen that can open a new one. private func recoverWindow( _ app: AppDescriptor, - windowId: CGWindowID? = nil, - windowBounds: CGRect? = nil + windowId: CGWindowID?, + windowBounds: CGRect?, + fallback: AXUIElement? ) { _ = app.app.unhide() - _ = app.app.activate(options: [.activateAllWindows]) - if let bundleId = app.bundleId { - openBundle(bundleId) - } let appElement = AXUIElementCreateApplication(app.pid) let focusedWindow = copyElement(appElement, kAXFocusedWindowAttribute as String) var cachedWindows: [AXUIElement]? @@ -1805,26 +2005,23 @@ private func recoverWindow( cachedWindows = value return value } - let targetWindow: AXUIElement? - if let focusedWindow, - (windowId == nil && windowBounds == nil || windowMatchesCapture( - focusedWindow, - windowId: windowId, - windowBounds: windowBounds - )) { - targetWindow = focusedWindow - } else { - let exactWindow = windowId.flatMap { targetId in - windows().first { windowNumber($0) == targetId } - } - targetWindow = exactWindow ?? windowBounds.flatMap { targetBounds in - windows().first { window in - absoluteFrame(window).map { windowFramesMatch($0, targetBounds) } == true - } + // Why: an exact id wins over a frame match, since full-screen and minimized windows can share the focused window's frame. + let exactWindow = windowId.flatMap { targetId in + windows().first { windowNumber($0) == targetId } + } ?? fallback + let sameFrameWindow = windowBounds.flatMap { targetBounds in + windows().first { window in + absoluteFrame(window).map { windowFramesMatch($0, targetBounds) } == true } } - if let window = targetWindow ?? focusedWindow ?? windows().first { + let window = exactWindow ?? sameFrameWindow ?? focusedWindow ?? windows().first + if let window { + // Why: un-minimize first, so activating the app has the target to bring forward. _ = AXUIElementSetAttributeValue(window, kAXMinimizedAttribute as CFString, kCFBooleanFalse) + } + _ = app.app.activate(options: []) + _ = AXUIElementSetAttributeValue(appElement, kAXFrontmostAttribute as CFString, kCFBooleanTrue) + if let window { _ = AXUIElementPerformAction(window, kAXRaiseAction as CFString) _ = AXUIElementSetAttributeValue(window, kAXMainAttribute as CFString, kCFBooleanTrue) _ = AXUIElementSetAttributeValue(window, kAXFocusedAttribute as CFString, kCFBooleanTrue) @@ -1832,16 +2029,6 @@ private func recoverWindow( Thread.sleep(forTimeInterval: 0.4) } -private func windowMatchesCapture( - _ window: AXUIElement, - windowId: CGWindowID?, - windowBounds: CGRect? -) -> Bool { - if let windowId, windowNumber(window) == windowId { return true } - guard let windowBounds, let frame = absoluteFrame(window) else { return false } - return windowFramesMatch(frame, windowBounds) -} - private func windowFramesMatch(_ lhs: CGRect, _ rhs: CGRect) -> Bool { let tolerance: CGFloat = 2 return abs(lhs.minX - rhs.minX) <= tolerance && @@ -1850,16 +2037,6 @@ private func windowFramesMatch(_ lhs: CGRect, _ rhs: CGRect) -> Bool { abs(lhs.height - rhs.height) <= tolerance } -private func openBundle(_ bundleId: String) { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/open") - process.arguments = ["-b", bundleId] - process.standardOutput = Pipe() - process.standardError = Pipe() - try? process.run() - process.waitUntilExit() -} - private func hasRequestedWindowSelector(_ params: [String: JSONValue]) -> Bool { params["windowId"] != nil || params["windowIndex"] != nil } @@ -2969,7 +3146,6 @@ private struct WindowCandidate { var value = Int(bounds.width * bounds.height) if layer == 0 { value += 1_000_000_000 } if title != nil && title?.isEmpty == false { value += 10_000_000 } - if isOnScreen { value += 1_000_000 } if alpha >= 0.99 { value += 100_000 } return value } @@ -3015,6 +3191,8 @@ private struct WindowCapture { return WindowCapture(candidate: visibleWindows[windowIndex], captureImage: captureImage) } guard let best = candidates.sorted(by: { lhs, rhs in + // Why: the focused window's title can name a window on another Space; a visible window still comes first. + if lhs.isOnScreen != rhs.isOnScreen { return lhs.isOnScreen } if let titleHint, lhs.title == titleHint, rhs.title != titleHint { return true } if let titleHint, rhs.title == titleHint, lhs.title != titleHint { return false } return lhs.score > rhs.score @@ -3038,8 +3216,10 @@ private struct WindowCapture { } } - static func candidates(pid: pid_t) -> [WindowCandidate] { - guard let infos = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] else { + /// Off-screen windows include minimized, hidden and other-Space ones, but also closed windows apps keep; see `windowInventory`. + static func candidates(pid: pid_t, includeOffScreen: Bool = false) -> [WindowCandidate] { + let options: CGWindowListOption = includeOffScreen ? [.optionAll, .excludeDesktopElements] : [.optionOnScreenOnly] + guard let infos = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else { return [] } return infos.compactMap { info in @@ -3057,7 +3237,8 @@ private struct WindowCapture { guard alpha > 0.01 else { return nil } let sharing = (info[kCGWindowSharingState as String] as? NSNumber).map { $0.intValue } if sharing == 0 { return nil } - let isOnScreen = (info[kCGWindowIsOnscreen as String] as? Bool) ?? true + // Why: CoreGraphics omits the key for off-screen windows, and every window of an on-screen-only list is on screen. + let isOnScreen = (info[kCGWindowIsOnscreen as String] as? Bool) ?? !includeOffScreen return WindowCandidate( windowId: CGWindowID(number.uint32Value), layer: layer, diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ForegroundDelivery.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ForegroundDelivery.swift new file mode 100644 index 00000000000..8609214b27a --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ForegroundDelivery.swift @@ -0,0 +1,27 @@ +import CoreGraphics + +/// Decides from what happened, not from the request, whether an action put the target in front of the user. +public enum ForegroundDelivery { + public struct Observation: Equatable { + public let frontmost: Bool + /// Read only while the app is frontmost, since only then is its key window the user's. + public let focusedWindowID: CGWindowID? + + public init(frontmost: Bool, focusedWindowID: CGWindowID?) { + self.frontmost = frontmost + self.focusedWindowID = focusedWindowID + } + } + + public static func tookForeground( + before: Observation, + after: Observation, + targetWindowID: CGWindowID, + restoreRequested: Bool + ) -> Bool { + guard after.frontmost else { return false } + // Why: --restore-window input goes through the HID tap, which lands in whatever is in front. + if restoreRequested || !before.frontmost { return true } + return before.focusedWindowID != targetWindowID && after.focusedWindowID == targetWindowID + } +} diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/RemoteAccessibilityWindows.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/RemoteAccessibilityWindows.swift new file mode 100644 index 00000000000..131030b1b87 --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/RemoteAccessibilityWindows.swift @@ -0,0 +1,56 @@ +import ApplicationServices +import CoreGraphics +import Darwin +import Foundation + +/// Finds an app's accessibility windows on other Spaces, which `kAXWindowsAttribute` leaves out, +/// by rebuilding element references from remote tokens (the technique AltTab uses). +/// Only finds windows some accessibility client has read before: an app numbers its elements in the order it first hands them out. +public enum RemoteAccessibilityWindows { + /// Windows are usually handed out first (ids 42-73 measured in apps open for days); a window first read after + /// a large tree walk gets a later id. + static let elementIdLimit: UInt64 = 20_000 + /// About 12 µs per id; the budget bounds a slow app. + static let scanBudgetSeconds: CFAbsoluteTime = 0.5 + + /// The windows of `pid` whose window ids are in `wanted`. + public static func windows(pid: pid_t, wanted: Set) -> [CGWindowID: AXUIElement] { + guard let createWithRemoteToken, !wanted.isEmpty else { return [:] } + let deadline = CFAbsoluteTimeGetCurrent() + scanBudgetSeconds + var found: [CGWindowID: AXUIElement] = [:] + for elementId in 0.. Data { + var token = Data() + withUnsafeBytes(of: pid.littleEndian) { token.append(contentsOf: $0) } + withUnsafeBytes(of: Int32(0)) { token.append(contentsOf: $0) } + withUnsafeBytes(of: Int32(0x636F_636F).littleEndian) { token.append(contentsOf: $0) } + withUnsafeBytes(of: elementId.littleEndian) { token.append(contentsOf: $0) } + return token + } + + private typealias CreateWithRemoteToken = @convention(c) (CFData) -> Unmanaged? + + private static let createWithRemoteToken: CreateWithRemoteToken? = { + guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_AXUIElementCreateWithRemoteToken") else { return nil } + // SAFETY: HIServices exports AXUIElementRef _AXUIElementCreateWithRemoteToken(CFDataRef), returning a +1 reference. + return unsafeBitCast(symbol, to: CreateWithRemoteToken.self) + }() +} diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/WindowSpaces.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/WindowSpaces.swift new file mode 100644 index 00000000000..91a9889454a --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/WindowSpaces.swift @@ -0,0 +1,40 @@ +import CoreGraphics +import Darwin +import Foundation + +/// Which windows belong to a Space. Minimized, hidden and other-Space windows do; a closed window an app keeps around does not. +public enum WindowSpaces { + /// Nil when SkyLight's lookup is missing, so closed windows can't be told apart from other-Space ones. + public static func windowsInAnySpace(_ windowIDs: [CGWindowID]) -> Set? { + guard let symbols else { return nil } + let connection = symbols.mainConnection() + return Set(windowIDs.filter { windowID in + let spaces = symbols.copySpacesForWindows(connection, allSpacesMask, [NSNumber(value: windowID)] as CFArray)? + .takeRetainedValue() as? [NSNumber] + return spaces?.isEmpty == false + }) + } + + private static let allSpacesMask: Int32 = 0x7 + + private typealias MainConnectionID = @convention(c) () -> Int32 + private typealias CopySpacesForWindows = @convention(c) (Int32, Int32, CFArray) -> Unmanaged? + + private struct Symbols { + let mainConnection: MainConnectionID + let copySpacesForWindows: CopySpacesForWindows + } + + private static let symbols: Symbols? = { + let skyLight = dlopen("/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_LAZY) + guard let main = dlsym(skyLight, "SLSMainConnectionID"), + let copy = dlsym(skyLight, "SLSCopySpacesForWindows") + else { return nil } + // SAFETY: SkyLight exports CGSConnectionID SLSMainConnectionID(void) and + // CFArrayRef SLSCopySpacesForWindows(CGSConnectionID, CGSSpaceMask, CFArrayRef), returning a +1 array (as yabai uses them). + return Symbols( + mainConnection: unsafeBitCast(main, to: MainConnectionID.self), + copySpacesForWindows: unsafeBitCast(copy, to: CopySpacesForWindows.self) + ) + }() +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ForegroundDeliveryTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ForegroundDeliveryTests.swift new file mode 100644 index 00000000000..193b6f5f727 --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ForegroundDeliveryTests.swift @@ -0,0 +1,25 @@ +import CoreGraphics +import XCTest +@testable import OrcaComputerUseMacOSCore + +final class ForegroundDeliveryTests: XCTestCase { + private func observation(_ frontmost: Bool, _ focusedWindowID: CGWindowID? = nil) -> ForegroundDelivery.Observation { + ForegroundDelivery.Observation(frontmost: frontmost, focusedWindowID: focusedWindowID) + } + + func testBackgroundActionThatActivatesTheAppReportsForeground() { + XCTAssertTrue(ForegroundDelivery.tookForeground(before: observation(false), after: observation(true, 7), targetWindowID: 7, restoreRequested: false)) + XCTAssertFalse(ForegroundDelivery.tookForeground(before: observation(false), after: observation(false), targetWindowID: 7, restoreRequested: false)) + } + + func testActiveAppCountsOnlyWhenTheTargetWindowBecameKey() { + XCTAssertTrue(ForegroundDelivery.tookForeground(before: observation(true, 3), after: observation(true, 7), targetWindowID: 7, restoreRequested: false)) + XCTAssertFalse(ForegroundDelivery.tookForeground(before: observation(true, 7), after: observation(true, 7), targetWindowID: 7, restoreRequested: false)) + XCTAssertFalse(ForegroundDelivery.tookForeground(before: observation(true, 3), after: observation(true, 3), targetWindowID: 7, restoreRequested: false)) + } + + func testRestoreReportsWhatHappenedNotWhatWasAsked() { + XCTAssertTrue(ForegroundDelivery.tookForeground(before: observation(true, 7), after: observation(true, 7), targetWindowID: 7, restoreRequested: true)) + XCTAssertFalse(ForegroundDelivery.tookForeground(before: observation(false), after: observation(false), targetWindowID: 7, restoreRequested: true)) + } +} diff --git a/skill-guides/orca-computer-use.md b/skill-guides/orca-computer-use.md index 5a6158e40a4..a4abb8fa5cd 100644 --- a/skill-guides/orca-computer-use.md +++ b/skill-guides/orca-computer-use.md @@ -149,7 +149,7 @@ These need the foreground, so ask the user first: - On Windows, keyboard input (`press-key`, `hotkey`, `paste-text` and `type-text`) needs the target window focused; otherwise it is refused with `window_not_focused` and nothing is sent. For editable fields use `set-value`. - On Linux and Windows, actions that need the real pointer, and on Linux keys sent while the target window is not active (Return in a focused GTK text field works). They are refused with `background_unavailable`; see below. -On macOS, a window that is minimized, hidden (Cmd+H) or on another Space cannot be read, so `get-app-state` fails with `window_not_found`. Ask the user to bring it on screen. +On macOS, `list-windows` and `get-app-state` also read windows that are minimized, hidden (Cmd+H) or on another Space, full-screen ones included; `isMinimized` and `isOffscreen` say which. Element actions work there (`click --element-index`, `set-value`, `type-text --element-index`, secondary actions), while coordinate clicks, scrolls, drags, keys and pastes are refused with `background_unavailable` and nothing is sent. Minimized and hidden windows have no screenshot. A window on another Space that nothing has read yet fails with `window_not_found`; ask the user to show it once. On macOS, background actions that would open a menu or dialog over the user are refused before anything is sent: right-clicks and Control-clicks, clicks or drags that start on popup menus, menu buttons, native combo boxes and web ``, set the option with `set-value` on that element. diff --git a/src/cli/skills/bundled-skill-guides.ts b/src/cli/skills/bundled-skill-guides.ts index 10764a41b49..8b8964631fe 100644 --- a/src/cli/skills/bundled-skill-guides.ts +++ b/src/cli/skills/bundled-skill-guides.ts @@ -1170,7 +1170,7 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "- On Windows, keyboard input (`press-key`, `hotkey`, `paste-text` and `type-text`) needs the target window focused; otherwise it is refused with `window_not_focused` and nothing is sent. For editable fields use `set-value`.", "- On Linux and Windows, actions that need the real pointer, and on Linux keys sent while the target window is not active (Return in a focused GTK text field works). They are refused with `background_unavailable`; see below.", "", - "On macOS, a window that is minimized, hidden (Cmd+H) or on another Space cannot be read, so `get-app-state` fails with `window_not_found`. Ask the user to bring it on screen.", + "On macOS, `list-windows` and `get-app-state` also read windows that are minimized, hidden (Cmd+H) or on another Space, full-screen ones included; `isMinimized` and `isOffscreen` say which. Element actions work there (`click --element-index`, `set-value`, `type-text --element-index`, secondary actions), while coordinate clicks, scrolls, drags, keys and pastes are refused with `background_unavailable` and nothing is sent. Minimized and hidden windows have no screenshot. A window on another Space that nothing has read yet fails with `window_not_found`; ask the user to show it once.", "", "On macOS, background actions that would open a menu or dialog over the user are refused before anything is sent: right-clicks and Control-clicks, clicks or drags that start on popup menus, menu buttons, native combo boxes and web ``, set the option with `set-value` on that element.", "", diff --git a/src/shared/computer-use-error-recovery.ts b/src/shared/computer-use-error-recovery.ts index 249aaeffb27..f441c1ad7ec 100644 --- a/src/shared/computer-use-error-recovery.ts +++ b/src/shared/computer-use-error-recovery.ts @@ -30,8 +30,8 @@ export function computerUseErrorRecoveryData( case 'window_not_found': return recoverWith( 'Run `orca computer list-windows --app --json` and target one of the listed windows.', - 'If the app is listed but has no usable window, ask the user to open or show one; on macOS a window that is minimized, hidden or on another Space cannot be read in the background. Do not add `--restore-window` on your own, not even just to observe.', - 'If no window is listed, the app may have none open or, on macOS, only minimized, hidden or other-Space windows; ask the user to show one. `orca computer` does not launch desktop apps: start a closed one on macOS with `open -g -a `; on Windows and Linux ask the user to.' + 'If the app is listed but has no usable window, ask the user to open or show one. Do not add `--restore-window` on your own, not even just to observe.', + 'If no window is listed, the app may have none open; ask the user to open one. `orca computer` does not launch desktop apps: start a closed one on macOS with `open -g -a `; on Windows and Linux ask the user to.' ) case 'window_not_focused': if (message?.includes('may already have been delivered')) { From 4d3cfb7dccab1d359a2d9a0b1ee3a264bc2e4191 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:58:47 -0800 Subject: [PATCH 17/52] fix(notifications): remap accent/input/border onto the notice surface (#42207) Outline and ghost buttons in toasts and corner cards painted dark:bg-input/30 and hover:bg-accent from the app palette under popover text, and panels and buttons drew edges from the app's --border and --input. For app themes the notice scope now remaps --accent, --accent-foreground and --input onto the readable secondary fill, and --border onto a popover-text edge. Dark outline buttons get an inset edge, and --notice-border now follows the popover text. Built-in themes paint as before. --- .../appearance/notice-surface-tokens.test.ts | 27 ++++++++++++++++--- .../appearance/notice-surface-tokens.ts | 17 +++++++++++- src/renderer/src/assets/main.css | 22 ++++++++++++--- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts b/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts index e9c4e7936e4..4f6fc8267f8 100644 --- a/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts +++ b/src/renderer/src/app-shell/appearance/notice-surface-tokens.test.ts @@ -7,7 +7,9 @@ const DARK_BUILT_INS = { '--popover': '#171717', '--popover-foreground': '#f0f0f0', '--muted': '#262626', - '--muted-foreground': '#acacac' + '--muted-foreground': '#acacac', + '--accent': '#404040', + '--accent-foreground': '#f0f0f0' } const probe = (value: string): Rgba | null => (value.startsWith('#') ? hexToRgb(value) : null) @@ -66,18 +68,37 @@ function expectReadable(themeTokens: Record): void { expect(wcagContrast(panel, muted)).toBeGreaterThanOrEqual(4.5) expect(wcagContrast(panel, text)).toBeGreaterThanOrEqual(4.5) } + // Hover fills (bg-accent, ghost dark:hover:bg-accent/50) paint accent-foreground or, for ghost + // buttons with hover:text-foreground, popover text. Without notice tokens, main.css paints the + // palette's --accent and --accent-foreground. + const accent = notice['--notice-accent'] ?? palette['--accent'] + const accentText = notice['--notice-accent-foreground'] ?? palette['--accent-foreground'] + for (const alpha of [0.5, 1]) { + const hover = composite(accent, surface, alpha) + expect(wcagContrast(hover, accentText)).toBeGreaterThanOrEqual(4.5) + expect(wcagContrast(hover, text)).toBeGreaterThanOrEqual(4.5) + } + // Dark outline buttons fill with dark:bg-input/30, /50 on hover, under popover text. + const input = notice['--notice-input'] ?? palette['--input'] + if (input?.startsWith('#')) { + for (const alpha of [0.3, 0.5]) { + expect(wcagContrast(composite(input, surface, alpha), text)).toBeGreaterThanOrEqual(4.5) + } + } } describe('noticeSurfaceTokens', () => { // Popovers the theme validator accepts that once painted notice text under 4.5:1: #5a5a5a // through Chromium's color-mix rounding and an over-lifted 80% description, #383838 through hex - // rounding, white-on-dark-base through dark muted panels, the rest unlifted. + // rounding, white-on-dark-base through dark muted panels, hover and outline fills, the rest + // unlifted. it.each>([ { '--popover': '#5a5a5a' }, { '--popover': '#383838' }, { '--popover': '#444444' }, { '--popover': '#303030', '--popover-foreground': '#a0a0a0' }, - { '--popover': '#ffffff', '--popover-foreground': '#111111' } + { '--popover': '#ffffff', '--popover-foreground': '#111111' }, + { '--popover': '#ffffff', '--popover-foreground': '#747474', '--input': '#262626' } ])('keeps notice text 4.5:1 for an accepted %o', (themeTokens) => { expectReadable(themeTokens) }) diff --git a/src/renderer/src/app-shell/appearance/notice-surface-tokens.ts b/src/renderer/src/app-shell/appearance/notice-surface-tokens.ts index 7afca6bb419..5b87a6966fe 100644 --- a/src/renderer/src/app-shell/appearance/notice-surface-tokens.ts +++ b/src/renderer/src/app-shell/appearance/notice-surface-tokens.ts @@ -13,6 +13,11 @@ export const NOTICE_SECONDARY_TOKEN = '--notice-secondary' export const NOTICE_MUTED_FOREGROUND_TOKEN = '--notice-muted-foreground' export const NOTICE_SECONDARY_EDGE_TOKEN = '--notice-secondary-edge' export const NOTICE_MUTED_TOKEN = '--notice-muted' +export const NOTICE_ACCENT_TOKEN = '--notice-accent' +export const NOTICE_ACCENT_FOREGROUND_TOKEN = '--notice-accent-foreground' +export const NOTICE_INPUT_TOKEN = '--notice-input' +export const NOTICE_EDGE_TOKEN = '--notice-edge' +export const NOTICE_OUTLINE_EDGE_TOKEN = '--notice-outline-edge' // Keep in sync with the built-in notice mixes in main.css. const NOTICE_LIFT = { light: 0, dark: 7 } as const const NOTICE_SECONDARY_MIX = { light: 6, dark: 10 } as const @@ -102,7 +107,17 @@ export function noticeSurfaceTokensFor( // Why: built-in palettes set --muted equal to --secondary; keeping that here keeps muted panels // on the notice surface's polarity when a theme's popover and app polarity differ. [NOTICE_MUTED_TOKEN]: secondaryHex, - [NOTICE_MUTED_FOREGROUND_TOKEN]: rgbaToHex(muted) + [NOTICE_MUTED_FOREGROUND_TOKEN]: rgbaToHex(muted), + // Why: hover (bg-accent, bg-accent/50) and outline fills (dark:bg-input/30, /50) paint under + // popover text in the notice scope; the secondary fill is the deepest one it stays readable on. + [NOTICE_ACCENT_TOKEN]: secondaryHex, + [NOTICE_ACCENT_FOREGROUND_TOKEN]: rgbaToHex(text), + [NOTICE_INPUT_TOKEN]: secondaryHex, + // Why: edges never sit under text, so they follow the popover text like the card border does; + // the theme's own --border/--input can be on the app's polarity, not the popover's. + [NOTICE_EDGE_TOKEN]: 'var(--notice-border)', + // Why: --input now only fills, so dark outline buttons (border-input) need the edge drawn. + [NOTICE_OUTLINE_EDGE_TOKEN]: 'var(--notice-border)' } } diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 88a4063759d..560b4dd83a7 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -552,20 +552,25 @@ } /* One lifted surface for toasts and corner notification cards; the default card/popover blends into the app. - App themes replace the surface, secondary and muted colors with readable hex (notice-surface-tokens.ts). */ + App themes replace the surface, fill and edge colors with readable ones (notice-surface-tokens.ts). */ :root { + --notice-accent: var(--accent); + --notice-accent-foreground: var(--accent-foreground); + --notice-edge: var(--border); + --notice-input: var(--input); --notice-muted: var(--muted); --notice-muted-foreground: var(--muted-foreground); + --notice-outline-edge: transparent; --notice-secondary-edge: transparent; --notice-surface: var(--popover); - --notice-border: color-mix(in srgb, var(--foreground) 14%, transparent); + --notice-border: color-mix(in srgb, var(--popover-foreground) 14%, transparent); --notice-secondary: color-mix(in srgb, var(--foreground) 6%, var(--notice-surface)); --notice-shadow: 0 11px 32px -6px rgb(0 0 0 / 0.2), 0 2px 6px rgb(0 0 0 / 0.08); } .dark { --notice-surface: color-mix(in srgb, var(--foreground) 7%, var(--popover)); - --notice-border: color-mix(in srgb, var(--foreground) 15%, transparent); + --notice-border: color-mix(in srgb, var(--popover-foreground) 15%, transparent); --notice-secondary: color-mix(in srgb, var(--foreground) 10%, var(--notice-surface)); --notice-shadow: 0 11px 32px -6px rgb(0 0 0 / 0.55), 0 2px 6px rgb(0 0 0 / 0.22), @@ -585,6 +590,10 @@ --muted-foreground: var(--notice-muted-foreground); --secondary: var(--notice-secondary); --secondary-foreground: var(--popover-foreground); + --accent: var(--notice-accent); + --accent-foreground: var(--notice-accent-foreground); + --input: var(--notice-input); + --border: var(--notice-edge); } /* Why inset outline: an edge for themes that leave secondary buttons unfilled, without moving layout. */ @@ -597,6 +606,13 @@ outline-offset: -1px; } +.dark + :is([data-sonner-toaster], .notification-card-stack) + [data-slot='button'][data-variant='outline'] { + outline: 1px solid var(--notice-outline-edge); + outline-offset: -1px; +} + [data-sonner-toaster] { font-family: var(--font-sans); /* Why: above the floating workspace (z-45 panel, z-46 launcher), which parks in the toasts' corner. */ From 6a0d446ccf63373878326253114650fe1ba93c95 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:01:54 -0800 Subject: [PATCH 18/52] fix(release): build Linux x64 on ubuntu-24.04 to keep node-pty baseline x86-64 (#42210) ubuntu-latest now resolves to the Ubuntu 26.04 image, which installs the amd64v3 package variant. Its GCC defaults to -march=x86-64-v3, so the Electron-ABI node-pty in 1.4.257 shipped AVX instructions and the terminal daemon died with SIGILL on CPUs without AVX. Pin the Linux x64 release build to ubuntu-24.04, the image that produced the working 1.4.256. Fixes #41637 --- .github/workflows/release-cut.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index 7ad27fefb3c..31b23e40ac3 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -1121,7 +1121,9 @@ jobs: eb_cache_path: | ~\AppData\Local\electron\Cache ~\AppData\Local\electron-builder\Cache - - os: ubuntu-latest + # Why: ubuntu-latest moved to the amd64v3 Ubuntu 26.04 image, whose GCC + # defaults to -march=x86-64-v3 and ships AVX in node-pty (#41637). + - os: ubuntu-24.04 platform: linux-x64 release_command: node "$(if [ -f config/scripts/native-build/node-addons/ensure-native-runtime.mjs ]; then printf %s config/scripts/native-build/node-addons/ensure-native-runtime.mjs; else printf %s config/scripts/ensure-native-runtime.mjs; fi)" --runtime=electron && pnpm exec electron-builder --config config/electron-builder.config.cjs --linux AppImage deb rpm --x64 --publish always -c.publish.releaseType=draft unpacked_dir: dist/linux-unpacked From e5e4f6f4c9b95e875a7c128fc092ff1d36f4cb8d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:03:58 -0800 Subject: [PATCH 19/52] perf(pickers): window the Automations and Skill install workspace pickers (#41396) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * perf(pickers): window workspace comboboxes and the Cmd+J result list The Automations and Skill install workspace comboboxes mounted one cmdk row per workspace while open, and the Cmd+J result list mounted every capped section row plus each See more page. cmdk moves the highlight, runs Enter and publishes aria-activedescendant by querying mounted rows, so these lists could not be windowed while cmdk owned selection. Each surface now owns its highlight over the full ordered result list: movement keys follow cmdk's bindings over every result, Enter and click share one activation path, and the input's aria-activedescendant names the highlighted option, which stays mounted. Rows render as plain listbox options outside cmdk's registry and only the visible window mounts (TanStack virtualizer; Cmd+J keeps natural layout below 50 rows). Filtering, ranking, section caps and See more are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) * refactor(pickers): share the windowed command virtualizer and keep the compiler gate Move the active-option pin and command-list reveal padding into one hook used by all three surfaces, keep virtualizer consumers out of React Compiler like the other TanStack lists, and express the dialog row styles and the flush skill rows as command variants. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(pickers): record the windowed command virtualizer hook's compiler bailout Co-Authored-By: Claude Opus 5.5 (1M context) * fix(pickers): keep virtualizer geometry across scrolls and match prior highlight/IME behavior - Stable per-list key/size getters so scrolling and hovering no longer rebuild every row's virtual geometry. - Moving the pointer over the already-highlighted option does no work. - Jump to… numbers every rendered option, disabled ones included. - The task Cmd/Ctrl+Enter shortcut ignores IME composition keys. - The skill install workspace picker opened with nothing chosen highlights the first workspace again. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(pickers): let the shared virtualizer own row key identity Callers now pass their ordered row keys; the shared hook keeps one key array per ordered sequence and derives the key getter from it, so a list rebuilt with the same rows (for example after an unrelated workspace metadata update) no longer forces a full geometry rebuild, while real reorder, insert, remove and filter changes still do. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(pickers): keep the row See more selects in view when Jump to… starts windowing Crossing 50 rows through See more switches the list to windowed rendering; reveal the newly highlighted row after that commit so it stays on screen as it did before. Co-Authored-By: Claude Opus 5.5 (1M context) * perf(pickers): keep Jump to… on its original list; window only the two workspace pickers The real-app benchmark showed no meaningful gain for the Jump to… results (they rarely reach 50 rows), and windowing them changed the See more behaviour at the threshold. Restore Jump to… exactly as on main and keep the windowed list, model-owned selection and option primitive for the Automations and Skill install workspace pickers, which measured clear wins. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- config/react-compiler-bailout-baseline.txt | 1 + config/react-compiler-uncompiled-files.txt | 2 + .../authoring/WorkspaceCombobox.tsx | 206 +++++++++--- .../SkillInstallWorkspaceCombobox.tsx | 307 +++++++++++++----- src/renderer/src/components/ui/command.tsx | 54 ++- .../use-windowed-command-virtualizer.ts | 82 +++++ .../windowed-command-navigation.test.ts | 72 ++++ .../windowed-command-navigation.ts | 82 +++++ 8 files changed, 690 insertions(+), 116 deletions(-) create mode 100644 src/renderer/src/lib/list-interaction/use-windowed-command-virtualizer.ts create mode 100644 src/renderer/src/lib/list-interaction/windowed-command-navigation.test.ts create mode 100644 src/renderer/src/lib/list-interaction/windowed-command-navigation.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 06b3aed8c79..b2c752cee6c 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -703,6 +703,7 @@ 6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts 1 src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts 1 src/renderer/src/lib/files/search/quick-open-file-history.ts +1 src/renderer/src/lib/list-interaction/use-windowed-command-virtualizer.ts 2 src/renderer/src/runtime/agent-orchestration/worker-auto-close.ts 1 src/renderer/src/runtime/native-chat/naming/structured-chat-name-observation.ts 1 src/renderer/src/store/plugins/appearance/plugin-icon-themes.ts diff --git a/config/react-compiler-uncompiled-files.txt b/config/react-compiler-uncompiled-files.txt index c1570bdeeab..fcb82cc9f86 100644 --- a/config/react-compiler-uncompiled-files.txt +++ b/config/react-compiler-uncompiled-files.txt @@ -33,6 +33,8 @@ src/renderer/src/components/native-chat/tools/runs/use-native-chat-tool-run-wind src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorerVirtualRows.tsx src/renderer/src/components/right-sidebar/file-explorer/tree/FileExplorerFilesTreePane.tsx src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx +src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx +src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx # The workbench subtree relies on the shell re-rendering on every app render. src/renderer/src/app-shell/AppWorkspaceShell.tsx diff --git a/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx index a6126592095..10a7a1dfe98 100644 --- a/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx +++ b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx @@ -1,18 +1,164 @@ import React from 'react' +import { defaultFilter } from 'cmdk' import { Check, ChevronsUpDown } from 'lucide-react' import { Button } from '@/components/ui/button' -import { - Command, - CommandEmpty, - CommandInput, - CommandItem, - CommandList -} from '@/components/ui/command' +import { Command, CommandInput, CommandList, CommandOption } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { cn } from '@/lib/class-names' +import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' +import { + getWindowedCommandNavigation, + useCommandInputActiveDescendant +} from '@/lib/list-interaction/windowed-command-navigation' +import { useWindowedCommandVirtualizer } from '@/lib/list-interaction/use-windowed-command-virtualizer' import type { Worktree } from '../../../../../shared/worktree/types' import { useTranslate } from '@/i18n/use-translate' +// Why: `py-1.5` around a 20px text line; fixed so rows never need measuring. +const WORKSPACE_OPTION_HEIGHT = 32 +const WORKSPACE_OPTION_OVERSCAN = 8 +// Why: matches `max-h-72`; seeds the first paint before the popover measures. +const WORKSPACE_LIST_MAX_HEIGHT = 288 + +function estimateWorkspaceOptionSize(): number { + return WORKSPACE_OPTION_HEIGHT +} + +/** cmdk's own ranking, run over every worktree so windowing never drops a match. */ +function filterWorkspaces(worktrees: readonly Worktree[], query: string): readonly Worktree[] { + if (!query) { + return worktrees + } + return worktrees + .map((worktree) => ({ worktree, score: defaultFilter(worktree.displayName.trim(), query, []) })) + .filter((scored) => scored.score > 0) + .sort((a, b) => b.score - a.score) + .map((scored) => scored.worktree) +} + +function WorkspaceComboboxList({ + worktrees, + value, + setInputNode, + onSelect +}: { + worktrees: Worktree[] + value: string + setInputNode: (node: HTMLInputElement | null) => void + onSelect: (workspaceId: string) => void +}): React.JSX.Element { + const t = useTranslate() + const listRef = React.useRef(null) + const inputRef = React.useRef(null) + const optionIdPrefix = `${React.useId()}option` + const [query, setQuery] = React.useState('') + const [highlightedId, setHighlightedId] = React.useState(null) + + const filtered = React.useMemo(() => filterWorkspaces(worktrees, query), [worktrees, query]) + const itemIds = React.useMemo(() => filtered.map((worktree) => worktree.id), [filtered]) + const indexById = React.useMemo(() => new Map(itemIds.map((id, index) => [id, index])), [itemIds]) + // A highlight that left the results falls back to the first match, as cmdk does. + const activeId = + highlightedId !== null && indexById.has(highlightedId) ? highlightedId : (itemIds[0] ?? null) + const activeIndex = activeId === null ? -1 : (indexById.get(activeId) ?? -1) + + const virtualizer = useWindowedCommandVirtualizer({ + itemKeys: itemIds, + scrollElement: () => listRef.current, + estimateSize: estimateWorkspaceOptionSize, + activeIndex, + overscan: WORKSPACE_OPTION_OVERSCAN, + initialRect: { width: 0, height: WORKSPACE_LIST_MAX_HEIGHT } + }) + + const setInputRef = React.useCallback( + (node: HTMLInputElement | null) => { + inputRef.current = node + setInputNode(node) + }, + [setInputNode] + ) + useCommandInputActiveDescendant( + inputRef, + activeIndex >= 0 ? `${optionIdPrefix}-${activeIndex}` : null + ) + + const handleQueryChange = (nextQuery: string): void => { + setQuery(nextQuery) + setHighlightedId(null) + virtualizer.scrollToOffset(0) + } + + const handleKeyDown = (event: React.KeyboardEvent): void => { + const navigation = getWindowedCommandNavigation(event, itemIds, activeId) + if (navigation) { + event.preventDefault() + if (navigation.targetId !== null) { + setHighlightedId(navigation.targetId) + virtualizer.scrollToIndex(indexById.get(navigation.targetId) ?? 0, { align: 'auto' }) + } + return + } + if (event.key === 'Enter' && !isImeOwnedKeyboardEvent(event) && activeId !== null) { + event.preventDefault() + onSelect(activeId) + } + } + + return ( + + + + {filtered.length === 0 ? ( +
+ {t('auto.components.automations.WorkspaceCombobox.ee5b280eba', 'No workspaces found.')} +
+ ) : ( +
+ {virtualizer.getVirtualItems().map((virtualRow) => { + const worktree = filtered[virtualRow.index] + if (!worktree) { + return null + } + return ( + setHighlightedId(worktree.id)} + onSelect={() => onSelect(worktree.id)} + className="absolute left-0 top-0 w-full" + style={{ + height: virtualRow.size, + transform: `translateY(${virtualRow.start}px)` + }} + > + + {worktree.displayName} + + ) + })} +
+ )} +
+
+ ) +} + export function WorkspaceCombobox({ worktrees, value, @@ -65,6 +211,14 @@ export function WorkspaceCombobox({ [cancelFocusFrame] ) + const handleSelect = React.useCallback( + (workspaceId: string) => { + onValueChange(workspaceId) + setOpen(false) + }, + [onValueChange] + ) + return ( @@ -90,38 +244,12 @@ export function WorkspaceCombobox({ focusSearchInput() }} > - - - - - {t( - 'auto.components.automations.WorkspaceCombobox.ee5b280eba', - 'No workspaces found.' - )} - - {worktrees.map((worktree) => ( - { - onValueChange(worktree.id) - setOpen(false) - }} - > - - {worktree.displayName} - - ))} - - + ) diff --git a/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx b/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx index 43dc6c919ec..516c93c1e4e 100644 --- a/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx +++ b/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx @@ -1,20 +1,26 @@ -import React, { useCallback, useMemo, useRef, useState } from 'react' +import React, { useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' import { Check, ChevronsUpDown } from 'lucide-react' import { Button } from '@/components/ui/button' -import { - Command, - CommandEmpty, - CommandInput, - CommandItem, - CommandList -} from '@/components/ui/command' +import { Command, CommandInput, CommandList, CommandOption } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { TooltipProvider } from '@/components/ui/tooltip' import { FilePathCursorTooltip } from '@/components/file-path-cursor-tooltip' import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' +import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' +import { + getWindowedCommandNavigation, + useCommandInputActiveDescendant +} from '@/lib/list-interaction/windowed-command-navigation' +import { useWindowedCommandVirtualizer } from '@/lib/list-interaction/use-windowed-command-virtualizer' import type { SkillInstallWorkspaceChoice } from './skill-install-workspace-choices' +// Why: `py-2` around a 20px text line; fixed so rows never need measuring. +const CHOICE_OPTION_HEIGHT = 36 +const CHOICE_OPTION_OVERSCAN = 8 +// Why: matches `max-h-72`; seeds the first paint before the popover measures. +const CHOICE_LIST_MAX_HEIGHT = 288 + export type SkillInstallWorkspaceComboboxProps = { id?: string value: string @@ -25,6 +31,18 @@ export type SkillInstallWorkspaceComboboxProps = { triggerClassName?: string } +/** Opening on the current choice highlights it (nothing when it is gone, the first choice when none is set); typing highlights the first match. */ +type ChoiceHighlight = { kind: 'choice'; key: string } | { kind: 'none' } | { kind: 'first-match' } + +function estimateChoiceOptionSize(): number { + return CHOICE_OPTION_HEIGHT +} + +// Worktree and folder ids are separate namespaces; the kind keeps option keys injective. +function choiceKey(choice: SkillInstallWorkspaceChoice): string { + return `${choice.kind}:${choice.id}` +} + function searchChoices( choices: readonly SkillInstallWorkspaceChoice[], query: string @@ -41,6 +59,180 @@ function searchChoices( }) } +function SkillInstallWorkspaceChoiceList({ + choices, + value, + query, + highlight, + setInputNode, + onQueryChange, + onHighlightChange, + onSelect +}: { + choices: readonly SkillInstallWorkspaceChoice[] + value: string + query: string + highlight: ChoiceHighlight + setInputNode: (node: HTMLInputElement | null) => void + onQueryChange: (query: string) => void + onHighlightChange: (highlight: ChoiceHighlight) => void + onSelect: (choiceId: string) => void +}): React.JSX.Element { + const t = useTranslate() + const inputRef = useRef(null) + const listRef = useRef(null) + const optionIdPrefix = `${useId()}option` + + const filteredChoices = useMemo(() => searchChoices(choices, query), [choices, query]) + const choiceKeys = useMemo(() => filteredChoices.map(choiceKey), [filteredChoices]) + const indexByKey = useMemo( + () => new Map(choiceKeys.map((key, index) => [key, index])), + [choiceKeys] + ) + // A highlighted choice that left the results falls back to the first match, as cmdk does. + const activeKey = + highlight.kind === 'none' + ? null + : highlight.kind === 'choice' && indexByKey.has(highlight.key) + ? highlight.key + : (choiceKeys[0] ?? null) + const activeIndex = activeKey === null ? -1 : (indexByKey.get(activeKey) ?? -1) + + const virtualizer = useWindowedCommandVirtualizer({ + itemKeys: choiceKeys, + scrollElement: () => listRef.current, + estimateSize: estimateChoiceOptionSize, + activeIndex, + overscan: CHOICE_OPTION_OVERSCAN, + initialRect: { width: 0, height: CHOICE_LIST_MAX_HEIGHT } + }) + + // Content mounts per open; reveal the choice it opened on once. + const [openedOnIndex] = useState(activeIndex) + useLayoutEffect(() => { + if (openedOnIndex > 0) { + virtualizer.scrollToIndex(openedOnIndex, { align: 'auto' }) + } + }, [openedOnIndex, virtualizer]) + + const setInputRef = useCallback( + (node: HTMLInputElement | null) => { + inputRef.current = node + setInputNode(node) + }, + [setInputNode] + ) + useCommandInputActiveDescendant( + inputRef, + activeIndex >= 0 ? `${optionIdPrefix}-${activeIndex}` : null + ) + + const handleQueryChange = (nextQuery: string): void => { + onQueryChange(nextQuery) + virtualizer.scrollToOffset(0) + } + + const handleKeyDown = (event: React.KeyboardEvent): void => { + const navigation = getWindowedCommandNavigation(event, choiceKeys, activeKey) + if (navigation) { + event.preventDefault() + if (navigation.targetId !== null) { + onHighlightChange({ kind: 'choice', key: navigation.targetId }) + virtualizer.scrollToIndex(indexByKey.get(navigation.targetId) ?? 0, { align: 'auto' }) + } + return + } + const activeChoice = activeIndex >= 0 ? filteredChoices[activeIndex] : undefined + if (event.key === 'Enter' && !isImeOwnedKeyboardEvent(event) && activeChoice) { + event.preventDefault() + onSelect(activeChoice.id) + } + } + + return ( + + + + + {filteredChoices.length === 0 ? ( +
+ {t( + 'auto.components.skills.SkillInstallWorkspaceCombobox.empty', + 'No workspaces found.' + )} +
+ ) : ( +
+ {virtualizer.getVirtualItems().map((virtualRow) => { + const choice = filteredChoices[virtualRow.index] + if (!choice) { + return null + } + const key = choiceKey(choice) + const isSelected = choice.id === value + const kindLabel = + choice.kind === 'worktree' + ? t( + 'auto.components.skills.SkillInstallTargetFields.d628c416a2', + 'Git worktree' + ) + : t('auto.components.skills.SkillInstallTargetFields.7a366323e7', 'Folder') + const fullLabel = `${choice.label} · ${kindLabel}` + + return ( + onHighlightChange({ kind: 'choice', key })} + onSelect={() => onSelect(choice.id)} + density="flush" + className="absolute left-0 top-0 w-full min-w-0 cursor-pointer" + style={{ + height: virtualRow.size, + transform: `translateY(${virtualRow.start}px)` + }} + > + +
+ + + {choice.label} ·{' '} + {kindLabel} + +
+
+
+ ) + })} +
+ )} +
+
+
+ ) +} + export function SkillInstallWorkspaceCombobox({ id, value, @@ -53,7 +245,7 @@ export function SkillInstallWorkspaceCombobox({ const t = useTranslate() const [open, setOpen] = useState(false) const [query, setQuery] = useState('') - const [commandValue, setCommandValue] = useState(value) + const [highlight, setHighlight] = useState({ kind: 'none' }) const inputRef = useRef(null) const focusFrameRef = useRef(null) @@ -62,8 +254,6 @@ export function SkillInstallWorkspaceCombobox({ [choices, value] ) - const filteredChoices = useMemo(() => searchChoices(choices, query), [choices, query]) - const cancelFocusFrame = useCallback((): void => { if (focusFrameRef.current !== null) { cancelAnimationFrame(focusFrameRef.current) @@ -95,19 +285,35 @@ export function SkillInstallWorkspaceCombobox({ }) }, [cancelFocusFrame]) + // With no choice yet the first one is armed, as cmdk did; a stale choice highlights nothing. + const highlightCurrentChoice = useCallback(() => { + setHighlight( + selectedChoice + ? { kind: 'choice', key: choiceKey(selectedChoice) } + : value === '' + ? { kind: 'first-match' } + : { kind: 'none' } + ) + }, [selectedChoice, value]) + const handleOpenChange = useCallback( (nextOpen: boolean) => { setOpen(nextOpen) if (nextOpen) { - setCommandValue(value) + highlightCurrentChoice() return } cancelFocusFrame() setQuery('') }, - [cancelFocusFrame, value] + [cancelFocusFrame, highlightCurrentChoice] ) + const handleQueryChange = useCallback((nextQuery: string) => { + setQuery(nextQuery) + setHighlight({ kind: 'first-match' }) + }, []) + const handleSelect = useCallback( (choiceId: string) => { onValueChange(choiceId) @@ -124,7 +330,7 @@ export function SkillInstallWorkspaceCombobox({ } if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault() - setCommandValue(value) + highlightCurrentChoice() setOpen(true) return } @@ -133,12 +339,12 @@ export function SkillInstallWorkspaceCombobox({ } if (event.key.length === 1 && /\S/.test(event.key)) { event.preventDefault() - setCommandValue(value) + setHighlight({ kind: 'first-match' }) setQuery(event.key) setOpen(true) } }, - [open, value] + [highlightCurrentChoice, open] ) const defaultPlaceholder = t( @@ -192,65 +398,16 @@ export function SkillInstallWorkspaceCombobox({ focusSearchInput() }} > - - - - - - {t( - 'auto.components.skills.SkillInstallWorkspaceCombobox.empty', - 'No workspaces found.' - )} - - {filteredChoices.map((choice) => { - const isSelected = choice.id === value - const kindLabel = - choice.kind === 'worktree' - ? t( - 'auto.components.skills.SkillInstallTargetFields.d628c416a2', - 'Git worktree' - ) - : t('auto.components.skills.SkillInstallTargetFields.7a366323e7', 'Folder') - const fullLabel = `${choice.label} · ${kindLabel}` - - return ( - handleSelect(choice.id)} - className="min-w-0 !p-0 cursor-pointer" - > - -
- - - {choice.label} ·{' '} - {kindLabel} - -
-
-
- ) - })} -
-
-
+ ) diff --git a/src/renderer/src/components/ui/command.tsx b/src/renderer/src/components/ui/command.tsx index 56381a08f30..705ef7026da 100644 --- a/src/renderer/src/components/ui/command.tsx +++ b/src/renderer/src/components/ui/command.tsx @@ -268,10 +268,13 @@ function CommandGroup({ ) } +const COMMAND_ITEM_BASE_CLASS = + 'relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4' + const commandItemVariants = cva('', { variants: { selection: { default: '', palette: 'jump-palette-item' }, - density: { default: '', workspace: 'px-3 py-2 text-xs' }, + density: { default: '', workspace: 'px-3 py-2 text-xs', flush: 'p-0' }, // Cmd+J's workspace row box: titles share one column across row kinds. shape: { default: '', @@ -297,7 +300,53 @@ function CommandItem({ ref={ref} data-slot="command-item" className={cn( - 'relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4', + COMMAND_ITEM_BASE_CLASS, + commandItemVariants({ selection, density, emphasis, shape }), + className + )} + {...props} + /> + ) +} + +type CommandOptionProps = Omit, 'onSelect'> & + VariantProps & { + selected: boolean + /** Rendered as `data-value`, the identity automation reads from command rows. */ + value?: string + disabled?: boolean + onHighlight?: () => void + onSelect?: () => void + } + +/** A listbox option cmdk never sees, for windowed lists that own selection; omitting `cmdk-item` keeps cmdk's DOM queries off it. */ +function CommandOption({ + className, + selection, + density, + emphasis, + shape, + selected, + value, + disabled = false, + onHighlight, + onSelect, + ...props +}: CommandOptionProps): React.JSX.Element { + return ( +
HTMLDivElement | null + estimateSize: (index: number) => number + activeIndex: number + overscan: number + initialRect: Rect +}): Virtualizer { + const keys = useRetainedKeySequence(itemKeys) + const count = keys.length + const getItemKey = useCallback((index: number) => keys[index] ?? index, [keys]) + const rangeExtractor = useCallback( + (range: Range) => { + const indexes = defaultRangeExtractor(range) + if (activeIndex >= 0 && activeIndex < count && !indexes.includes(activeIndex)) { + indexes.push(activeIndex) + indexes.sort((a, b) => a - b) + } + return indexes + }, + [activeIndex, count] + ) + return useVirtualizer({ + count, + getScrollElement: scrollElement, + estimateSize, + getItemKey, + overscan, + rangeExtractor, + initialRect, + scrollPaddingStart: COMMAND_LIST_SCROLL_PADDING, + scrollPaddingEnd: COMMAND_LIST_SCROLL_PADDING + }) +} diff --git a/src/renderer/src/lib/list-interaction/windowed-command-navigation.test.ts b/src/renderer/src/lib/list-interaction/windowed-command-navigation.test.ts new file mode 100644 index 00000000000..9bc04378d3f --- /dev/null +++ b/src/renderer/src/lib/list-interaction/windowed-command-navigation.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import { getWindowedCommandNavigation } from './windowed-command-navigation' + +const ids = ['a', 'b', 'c', 'd'] + +function key( + keyName: string, + modifiers: Partial<{ ctrlKey: boolean; metaKey: boolean; isComposing: boolean }> = {} +) { + return { + key: keyName, + ctrlKey: modifiers.ctrlKey ?? false, + metaKey: modifiers.metaKey ?? false, + defaultPrevented: false, + nativeEvent: { isComposing: modifiers.isComposing ?? false } + } +} + +describe('getWindowedCommandNavigation', () => { + it('steps through the full list and stops at the ends', () => { + expect(getWindowedCommandNavigation(key('ArrowDown'), ids, 'b')).toEqual({ targetId: 'c' }) + expect(getWindowedCommandNavigation(key('ArrowUp'), ids, 'b')).toEqual({ targetId: 'a' }) + expect(getWindowedCommandNavigation(key('ArrowDown'), ids, 'd')).toEqual({ targetId: null }) + }) + + it('matches cmdk when nothing is highlighted: down goes first, up goes nowhere', () => { + expect(getWindowedCommandNavigation(key('ArrowDown'), ids, null)).toEqual({ targetId: 'a' }) + expect(getWindowedCommandNavigation(key('ArrowUp'), ids, null)).toEqual({ targetId: null }) + }) + + it('jumps to the ends with Home/End and Meta+Arrow', () => { + expect(getWindowedCommandNavigation(key('End'), ids, 'a')).toEqual({ targetId: 'd' }) + expect(getWindowedCommandNavigation(key('Home'), ids, 'c')).toEqual({ targetId: 'a' }) + expect(getWindowedCommandNavigation(key('ArrowDown', { metaKey: true }), ids, 'a')).toEqual({ + targetId: 'd' + }) + expect(getWindowedCommandNavigation(key('ArrowUp', { metaKey: true }), ids, 'c')).toEqual({ + targetId: 'a' + }) + }) + + it('treats Ctrl+N/J and Ctrl+P/K as movement, plain letters as typing', () => { + expect(getWindowedCommandNavigation(key('n', { ctrlKey: true }), ids, 'a')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('j', { ctrlKey: true }), ids, 'a')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('p', { ctrlKey: true }), ids, 'c')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('k', { ctrlKey: true }), ids, 'c')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('n'), ids, 'a')).toBeNull() + }) + + it('leaves composition, handled and non-movement keys alone', () => { + expect( + getWindowedCommandNavigation(key('ArrowDown', { isComposing: true }), ids, 'a') + ).toBeNull() + expect( + getWindowedCommandNavigation({ ...key('ArrowDown'), defaultPrevented: true }, ids, 'a') + ).toBeNull() + expect(getWindowedCommandNavigation(key('Enter'), ids, 'a')).toBeNull() + }) + + it('claims movement keys on an empty list without a target', () => { + expect(getWindowedCommandNavigation(key('End'), [], null)).toEqual({ targetId: null }) + expect(getWindowedCommandNavigation(key('ArrowDown'), [], null)).toEqual({ targetId: null }) + }) +}) diff --git a/src/renderer/src/lib/list-interaction/windowed-command-navigation.ts b/src/renderer/src/lib/list-interaction/windowed-command-navigation.ts new file mode 100644 index 00000000000..595171089a1 --- /dev/null +++ b/src/renderer/src/lib/list-interaction/windowed-command-navigation.ts @@ -0,0 +1,82 @@ +import { useEffect, type RefObject } from 'react' +import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' + +type CommandNavigationKeyEvent = { + key: string + ctrlKey: boolean + metaKey: boolean + defaultPrevented: boolean + keyCode?: number + nativeEvent?: { isComposing?: boolean; keyCode?: number } +} + +/** Resolves cmdk's movement keys over the full logical list, because cmdk only sees a windowed list's mounted rows. + * Returns null for keys cmdk would not treat as movement; `targetId` null means movement with nowhere to go. */ +export function getWindowedCommandNavigation( + event: CommandNavigationKeyEvent, + itemIds: readonly string[], + activeItemId: string | null | undefined +): { targetId: string | null } | null { + if (event.defaultPrevented || isImeOwnedKeyboardEvent(event)) { + return null + } + const last = itemIds.length - 1 + const move = (delta: 1 | -1): number | null => { + if (event.metaKey) { + return delta === 1 ? last : 0 + } + const currentIndex = activeItemId ? itemIds.indexOf(activeItemId) : -1 + const next = currentIndex + delta + return next < 0 || next > last ? null : next + } + let targetIndex: number | null + switch (event.key) { + case 'ArrowDown': + targetIndex = move(1) + break + case 'ArrowUp': + targetIndex = move(-1) + break + case 'n': + case 'j': + if (!event.ctrlKey) { + return null + } + targetIndex = move(1) + break + case 'p': + case 'k': + if (!event.ctrlKey) { + return null + } + targetIndex = move(-1) + break + case 'Home': + targetIndex = 0 + break + case 'End': + targetIndex = last + break + default: + return null + } + return { targetId: targetIndex === null ? null : (itemIds[targetIndex] ?? null) } +} + +/** cmdk derives `aria-activedescendant` from its own item registry; point it at the surface-owned active option after each commit. */ +export function useCommandInputActiveDescendant( + inputRef: RefObject, + activeOptionId: string | null +): void { + useEffect(() => { + const input = inputRef.current + if (!input) { + return + } + if (activeOptionId) { + input.setAttribute('aria-activedescendant', activeOptionId) + } else { + input.removeAttribute('aria-activedescendant') + } + }) +} From 2d6c923126ea1be55ab5760498abff9c11e6cd1e Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 13 Nov 2026 17:04:28 -0800 Subject: [PATCH 20/52] test: remove low-value terminal, tray, and updater coverage (#42213) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../orcagziputf8codec/BoundedGunzipTest.kt | 1 - .../tests/GzipUtf8CodecChecks.swift | 3 +- .../tests/gunzip-vectors.json | 35 - src/main/tray/system-tray.test.ts | 649 ------------------ .../linux-package-update-recovery.test.ts | 97 --- .../input/terminal-composer-draft.test.ts | 97 +-- ...rminal-kitty-keyboard-mode-tracker.test.ts | 18 +- .../plugins/overlays/plugin-overlay.test.ts | 176 +---- .../transport/publication/dispatcher.test.ts | 71 -- 9 files changed, 4 insertions(+), 1143 deletions(-) delete mode 100644 src/main/tray/system-tray.test.ts diff --git a/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/BoundedGunzipTest.kt b/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/BoundedGunzipTest.kt index a55caf16d6f..7afe5a4ae18 100644 --- a/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/BoundedGunzipTest.kt +++ b/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/BoundedGunzipTest.kt @@ -6,7 +6,6 @@ import org.junit.Assert.assertEquals import org.junit.Test class BoundedGunzipTest { - // Shared with the Swift checks and the JS tests, which pin fflate's answer to the same inputs. private val vectors = JSONArray(File("../tests/gunzip-vectors.json").readText()) @Test diff --git a/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift b/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift index 1910ae7748e..08967de0d19 100644 --- a/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift +++ b/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift @@ -26,11 +26,10 @@ import Foundation } static func main() throws { - // Shared with the Kotlin tests and the JS tests, which pin fflate's answer to the same inputs. let url = URL(fileURLWithPath: "tests/gunzip-vectors.json") let vectors = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [[String: Any]] for vector in vectors where [ - "one member", "reaches the limit", "bomb", "bad CRC", "trailing data", "truncated body" + "one member", "reaches the limit", "bad CRC", "trailing data", "truncated body" ].contains(vector["name"] as? String ?? "") { let name = vector["name"] as! String let expected = (vector["native"] as? String).map { bytes(hex: $0) } diff --git a/mobile/modules/orca-gzip-utf8-codec/tests/gunzip-vectors.json b/mobile/modules/orca-gzip-utf8-codec/tests/gunzip-vectors.json index bd1f6f5e321..0692e2e52fe 100644 --- a/mobile/modules/orca-gzip-utf8-codec/tests/gunzip-vectors.json +++ b/mobile/modules/orca-gzip-utf8-codec/tests/gunzip-vectors.json @@ -6,13 +6,6 @@ "native": "77696e646f7720303a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720313a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720323a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720333a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720343a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720353a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a", "js": "77696e646f7720303a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720313a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720323a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720333a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720343a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720353a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a" }, - { - "name": "empty member", - "gzipHex": "1f8b080000000000001303000000000000000000", - "outputLimit": 1, - "native": "", - "js": "" - }, { "name": "reaches the limit", "gzipHex": "1f8b08000000000000132bcfcc4bc92f5730b052a8562a482cc950b2524a2c2e4e2d29d64fd4cb2a56d251cacf56b22a292a4dd5513ab70728f968cee40ff3673629d5729543741a92add3886c9dc664eb34215ba729e93a01177932565c010000", @@ -20,13 +13,6 @@ "native": "77696e646f7720303a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720313a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720323a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720333a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720343a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f772035", "js": "77696e646f7720303a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720313a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720323a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720333a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720343a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f772035" }, - { - "name": "bomb", - "gzipHex": "1f8b0800000000000013edc13101000000c2a0f54f6d085fa000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e031cea38a700001000", - "outputLimit": 1025, - "native": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "js": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - }, { "name": "name, comment and header CRC", "gzipHex": "1f8b081a000000000003612e6a73006e6f74650071bc2bcfcc4bc92f5730b052a8562a482cc950b2524a2c2e4e2d29d64fd4cb2a56d251cacf56b22a292a4dd5513ab70728f968cee40ff3673629d5729543741a92add3886c9dc664eb34215ba729e93a01177932565c010000", @@ -69,13 +55,6 @@ "native": null, "js": "77696e646f7720303a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720313a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720323a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720333a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720343a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720353a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a" }, - { - "name": "second member", - "gzipHex": "1f8b08000000000000132bcfcc4bc92f5730b052a8562a482cc950b2524a2c2e4e2d29d64fd4cb2a56d251cacf56b22a292a4dd5513ab70728f968cee40ff3673629d5729543741a92add3886c9dc664eb34215ba729e93a01177932565c0100001f8b08000000000000132bcfcc4bc92f5730b052a8562a482cc950b2524a2c2e4e2d29d64fd4cb2a56d251cacf56b22a292a4dd5513ab70728f968cee40ff3673629d5729543741a92add3886c9dc664eb34215ba729e93a01177932565c010000", - "outputLimit": 697, - "native": null, - "js": "77696e646f7720303a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720313a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720323a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720333a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720343a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a77696e646f7720353a207b2270617468223a226173736574732f612e6a73222c226f6b223a747275652c22cebc223a22e29c93f09f9982227d0a" - }, { "name": "truncated body", "gzipHex": "1f8b08000000000000132bcfcc4bc92f5730b052a8562a482cc950b2524a", @@ -97,20 +76,6 @@ "native": null, "js": null }, - { - "name": "unknown method", - "gzipHex": "1f8b09000000000000132bcfcc4bc92f5730b052a8562a482cc950b2524a2c2e4e2d29d64fd4cb2a56d251cacf56b22a292a4dd5513ab70728f968cee40ff3673629d5729543741a92add3886c9dc664eb34215ba729e93a01177932565c010000", - "outputLimit": 349, - "native": null, - "js": null - }, - { - "name": "header only", - "gzipHex": "1f8b0800000000000013", - "outputLimit": 349, - "native": null, - "js": null - }, { "name": "empty input", "gzipHex": "", diff --git a/src/main/tray/system-tray.test.ts b/src/main/tray/system-tray.test.ts deleted file mode 100644 index 6f146f1f144..00000000000 --- a/src/main/tray/system-tray.test.ts +++ /dev/null @@ -1,649 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as SystemTrayModule from './system-tray' - -const { - attentionImage, - baseMacImage, - composeAttentionMock, - createAppIconImageMock, - createFromPathMock, - devBadgeImage, - devBadgeRetinaImage, - menuFromTemplateMock, - nativeThemeMock, - resizedImage, - retinaMacImage, - stampDevBadgeMock, - themeState, - tintedMacImage, - tintTemplateMock, - trayInstances -} = vi.hoisted(() => { - const makeImage = (name: string) => ({ - name, - addRepresentation: vi.fn(), - getScaleFactors: vi.fn(() => [1, 2]), - getSize: vi.fn(() => ({ width: 16, height: 16 })), - setTemplateImage: vi.fn(), - toBitmap: vi.fn(() => Buffer.alloc(16 * 16 * 4)), - toDataURL: vi.fn(() => `data:image/png;base64,${name}`) - }) - const resizedImage = makeImage('windows') - const baseMacImage = makeImage('mac-base') - const retinaMacImage = makeImage('mac-retina') - const tintedMacImage = makeImage('mac-tinted') - const attentionImage = makeImage('attention') - const devBadgeImage = makeImage('dev-badge') - const devBadgeRetinaImage = makeImage('dev-badge-retina') - const themeState = { updatedListener: null as (() => void) | null } - const nativeThemeMock = { - shouldUseDarkColors: false, - on: vi.fn((_event: string, listener: () => void) => { - themeState.updatedListener = listener - }), - removeListener: vi.fn((_event: string, listener: () => void) => { - if (themeState.updatedListener === listener) { - themeState.updatedListener = null - } - }) - } - return { - attentionImage, - baseMacImage, - composeAttentionMock: vi.fn(() => attentionImage), - createAppIconImageMock: vi.fn(), - createFromPathMock: vi.fn(), - devBadgeImage, - devBadgeRetinaImage, - menuFromTemplateMock: vi.fn((template: unknown) => ({ template })), - nativeThemeMock, - resizedImage, - retinaMacImage, - stampDevBadgeMock: vi.fn((_base: unknown, scaleFactor?: number) => - scaleFactor === 2 ? devBadgeRetinaImage : devBadgeImage - ), - themeState, - tintedMacImage, - tintTemplateMock: vi.fn(() => tintedMacImage), - trayInstances: [] as FakeTray[] - } -}) - -class FakeTray { - setToolTip = vi.fn() - setTitle = vi.fn() - setContextMenu = vi.fn() - setImage = vi.fn() - on = vi.fn() - destroy = vi.fn() - isDestroyed = vi.fn(() => false) - constructor(public readonly image: unknown) { - trayInstances.push(this) - } -} - -vi.mock('electron', () => ({ - Tray: FakeTray, - Menu: { buildFromTemplate: menuFromTemplateMock }, - nativeImage: { createFromPath: createFromPathMock }, - nativeTheme: nativeThemeMock -})) - -vi.mock('../../../resources/tray/orca-menu-barTemplate.png?asset&asarUnpack', () => ({ - default: '/assets/orca-menu-barTemplate.png' -})) - -vi.mock('../../../resources/tray/orca-menu-barTemplate@2x.png?asset&asarUnpack', () => ({ - default: '/assets/orca-menu-barTemplate@2x.png' -})) - -vi.mock('../window/desktop-integration/app-icon', () => ({ - createAppIconImage: createAppIconImageMock -})) - -vi.mock('./tray-attention-icon', () => ({ - composeTrayAttentionIcon: composeAttentionMock, - tintTrayTemplateForAttention: tintTemplateMock -})) - -vi.mock('./tray-dev-badge', () => ({ - stampTrayDevBadge: stampDevBadgeMock -})) - -type TrayModule = typeof SystemTrayModule -type MenuItem = { label?: string; type?: string; click?: () => void } - -const originalPlatform = process.platform - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) -} - -async function loadModule(): Promise { - vi.resetModules() - return import('./system-tray') -} - -function createOptions( - overrides: { isDevInstance?: boolean; devInstanceLabel?: string | null } = {} -) { - return { - appIcon: 'classic', - isDevInstance: overrides.isDevInstance ?? false, - devInstanceLabel: overrides.devInstanceLabel ?? null, - onOpen: vi.fn(), - onOpenSettings: vi.fn(), - onCheckForUpdates: vi.fn(), - onQuit: vi.fn() - } -} - -function builtMenuItems(): MenuItem[] { - return menuFromTemplateMock.mock.calls.at(-1)?.[0] as MenuItem[] -} - -// Flush the deferred native scene mutation after the AppKit caller stack returns. -function flushTraySceneMutation(): void { - vi.advanceTimersByTime(0) -} - -beforeEach(() => { - vi.useFakeTimers() - trayInstances.length = 0 - menuFromTemplateMock.mockClear() - composeAttentionMock.mockClear() - tintTemplateMock.mockClear() - createAppIconImageMock.mockReset() - createAppIconImageMock.mockReturnValue({ resize: vi.fn(() => resizedImage) }) - createFromPathMock.mockReset() - createFromPathMock.mockImplementation((path: string) => - path.includes('@2x') ? retinaMacImage : baseMacImage - ) - stampDevBadgeMock.mockClear() - stampDevBadgeMock.mockImplementation((_base: unknown, scaleFactor?: number) => - scaleFactor === 2 ? devBadgeRetinaImage : devBadgeImage - ) - for (const image of [ - baseMacImage, - retinaMacImage, - tintedMacImage, - attentionImage, - devBadgeImage, - devBadgeRetinaImage - ]) { - image.addRepresentation.mockClear() - image.getScaleFactors.mockReset().mockReturnValue([1, 2]) - image.getSize.mockReset().mockReturnValue({ width: 16, height: 16 }) - image.setTemplateImage.mockClear() - image.toBitmap.mockClear() - image.toDataURL.mockClear().mockReturnValue(`data:image/png;base64,${image.name}`) - } - nativeThemeMock.shouldUseDarkColors = false - nativeThemeMock.on.mockClear() - nativeThemeMock.removeListener.mockClear() - themeState.updatedListener = null -}) - -afterEach(() => { - setPlatform(originalPlatform) - vi.useRealTimers() - vi.restoreAllMocks() -}) - -describe('createSystemTray', () => { - it('keeps the Windows icon, Open/Quit menu, and left-click behavior', async () => { - setPlatform('win32') - const { createSystemTray } = await loadModule() - const options = createOptions() - - createSystemTray(options) - - expect(trayInstances).toHaveLength(1) - expect(trayInstances[0].image).toBe(resizedImage) - expect(trayInstances[0].setToolTip).toHaveBeenCalledWith('Orca') - expect(builtMenuItems().map((item) => item.label)).toEqual(['Open Orca', undefined, 'Quit']) - const clickHandler = trayInstances[0].on.mock.calls.find((call) => call[0] === 'click')?.[1] - expect(clickHandler).toBeTypeOf('function') - - builtMenuItems()[0].click?.() - ;(clickHandler as () => void)() - builtMenuItems()[2].click?.() - expect(options.onOpen).toHaveBeenCalledTimes(2) - expect(options.onQuit).toHaveBeenCalledOnce() - }) - - it('creates a macOS template status item with the full native menu', async () => { - setPlatform('darwin') - const { createSystemTray } = await loadModule() - const options = createOptions() - - createSystemTray(options) - - expect(trayInstances).toHaveLength(1) - expect(trayInstances[0].image).toBe(baseMacImage) - expect(baseMacImage.setTemplateImage).toHaveBeenCalledWith(true) - expect(baseMacImage.addRepresentation).toHaveBeenCalledWith({ - scaleFactor: 2, - dataURL: 'data:image/png;base64,mac-retina' - }) - expect(builtMenuItems().map((item) => item.label)).toEqual([ - 'Open Orca', - undefined, - 'Settings', - 'Check for Updates...', - undefined, - 'Quit' - ]) - expect(trayInstances[0].on).not.toHaveBeenCalled() - expect(nativeThemeMock.on).toHaveBeenCalledWith('updated', expect.any(Function)) - - for (const [label, callback] of [ - ['Open Orca', options.onOpen], - ['Settings', options.onOpenSettings], - ['Check for Updates...', options.onCheckForUpdates], - ['Quit', options.onQuit] - ] as const) { - builtMenuItems() - .find((item) => item.label === label) - ?.click?.() - expect(callback).toHaveBeenCalledOnce() - } - }) - - it.each(['win32', 'darwin'] as const)( - 'offers Quit Completely directly above Quit on %s when a handler is supplied', - async (platform) => { - setPlatform(platform) - const { createSystemTray } = await loadModule() - const options = { ...createOptions(), onQuitAndStopAllSessions: vi.fn() } - - createSystemTray(options) - - expect(builtMenuItems().map((item) => item.label)).toEqual( - platform === 'darwin' - ? [ - 'Open Orca', - undefined, - 'Settings', - 'Check for Updates...', - undefined, - 'Quit Completely...', - 'Quit' - ] - : ['Open Orca', undefined, 'Quit Completely...', 'Quit'] - ) - builtMenuItems().at(-2)?.click?.() - expect(options.onQuitAndStopAllSessions).toHaveBeenCalledOnce() - expect(options.onQuit).not.toHaveBeenCalled() - } - ) - - it('does not create a blank macOS item when the template asset fails to load', async () => { - setPlatform('darwin') - baseMacImage.getSize.mockReturnValue({ width: 0, height: 0 }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { createSystemTray } = await loadModule() - - expect(createSystemTray(createOptions())).toBeNull() - expect(trayInstances).toHaveLength(0) - expect(warn).toHaveBeenCalledWith('[system-tray] macOS menu bar icon could not be loaded') - }) - - it('is idempotent and remains disabled on Linux', async () => { - setPlatform('darwin') - const { createSystemTray } = await loadModule() - const options = createOptions() - expect(createSystemTray(options)).toBe(createSystemTray(options)) - expect(trayInstances).toHaveLength(1) - - setPlatform('linux') - const linuxModule = await loadModule() - expect(linuxModule.createSystemTray(options)).toBeNull() - }) -}) - -describe('dev instance indicator', () => { - it('falls back to the plain icon when badge stamping fails', async () => { - setPlatform('darwin') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - stampDevBadgeMock.mockImplementation(() => { - throw new Error('bitmap failure') - }) - const { createSystemTray } = await loadModule() - - expect(createSystemTray(createOptions({ isDevInstance: true }))).not.toBeNull() - expect(trayInstances[0].image).toBe(baseMacImage) - expect(warn).toHaveBeenCalledWith( - '[system-tray] dev badge could not be stamped; showing plain icon', - expect.any(Error) - ) - }) -}) - -describe('macOS visibility', () => { - it('creates and destroys the item as the setting toggles', async () => { - setPlatform('darwin') - const { setMacMenuBarIconVisible } = await loadModule() - const options = createOptions() - - expect(setMacMenuBarIconVisible(false, options)).toBeNull() - expect(trayInstances).toHaveLength(0) - expect(setMacMenuBarIconVisible(true, options)).not.toBeNull() - expect(trayInstances).toHaveLength(1) - - setMacMenuBarIconVisible(false, options) - setMacMenuBarIconVisible(false, options) - expect(trayInstances[0].destroy).toHaveBeenCalledOnce() - }) -}) - -describe('setTrayAttention', () => { - it('preserves the Windows attention swap behavior', async () => { - setPlatform('win32') - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - - setTrayAttention(true) - flushTraySceneMutation() - expect(composeAttentionMock).toHaveBeenCalledWith(resizedImage) - expect(created.setImage).toHaveBeenCalledWith(attentionImage) - setTrayAttention(false) - flushTraySceneMutation() - expect(created.setImage).toHaveBeenLastCalledWith(resizedImage) - }) - - it('uses a literal theme-aware glyph for macOS attention, then restores template mode', async () => { - setPlatform('darwin') - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - created.setToolTip.mockClear() - - setTrayAttention(true) - flushTraySceneMutation() - expect(tintTemplateMock).toHaveBeenCalledWith(baseMacImage, false) - expect(composeAttentionMock).toHaveBeenCalledWith(tintedMacImage) - // Bitmap rebuild starts at 1x; re-add 2x or attention glyphs blur on Retina. - expect(tintTemplateMock).toHaveBeenCalledWith(baseMacImage, false, 2) - expect(attentionImage.addRepresentation).toHaveBeenCalledWith({ - scaleFactor: 2, - dataURL: 'data:image/png;base64,attention' - }) - expect(attentionImage.setTemplateImage).toHaveBeenCalledWith(false) - expect(created.setImage).toHaveBeenCalledWith(attentionImage) - expect(created.setToolTip).toHaveBeenCalledWith('Orca - activity waiting') - - setTrayAttention(false) - flushTraySceneMutation() - expect(baseMacImage.setTemplateImage).toHaveBeenLastCalledWith(true) - expect(created.setImage).toHaveBeenLastCalledWith(baseMacImage) - expect(created.setToolTip).toHaveBeenLastCalledWith('Orca') - }) - - it('recomposes active macOS attention when the system appearance changes', async () => { - setPlatform('darwin') - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - setTrayAttention(true) - flushTraySceneMutation() - tintTemplateMock.mockClear() - nativeThemeMock.shouldUseDarkColors = true - - themeState.updatedListener?.() - // Appearance events also arrive from AppKit; defer their native writes. - expect(tintTemplateMock).not.toHaveBeenCalled() - - flushTraySceneMutation() - expect(tintTemplateMock).toHaveBeenCalledWith(baseMacImage, true) - }) - - it('reflects attention requested before deferred macOS creation', async () => { - setPlatform('darwin') - const { createSystemTray, setTrayAttention } = await loadModule() - setTrayAttention(true) - createSystemTray(createOptions()) - - expect(trayInstances[0].setImage).toHaveBeenCalledWith(attentionImage) - }) - - it('ignores repeated same-state attention calls', async () => { - setPlatform('win32') - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - - setTrayAttention(true) - setTrayAttention(true) - flushTraySceneMutation() - - expect(created.setImage).toHaveBeenCalledTimes(1) - }) - - it('never touches the NSStatusItem scene inside the caller stack', async () => { - setPlatform('darwin') - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - created.setToolTip.mockClear() - - // Native scene writes inside AppKit window-state dispatch can deadlock main on macOS 26. - setTrayAttention(true) - expect(created.setImage).not.toHaveBeenCalled() - expect(created.setToolTip).not.toHaveBeenCalled() - - flushTraySceneMutation() - expect(created.setImage).toHaveBeenCalledWith(attentionImage) - }) - - it('collapses a burst of toggles into one deferred repaint', async () => { - setPlatform('darwin') - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - - setTrayAttention(true) - setTrayAttention(false) - setTrayAttention(true) - flushTraySceneMutation() - - expect(created.setImage).toHaveBeenCalledTimes(1) - expect(created.setImage).toHaveBeenCalledWith(attentionImage) - }) - - it('still dedupes after the deferred repaint has run', async () => { - setPlatform('darwin') - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - - setTrayAttention(true) - flushTraySceneMutation() - setTrayAttention(true) - flushTraySceneMutation() - - expect(created.setImage).toHaveBeenCalledTimes(1) - }) - - it('does not throw when the tray is destroyed before the deferred repaint runs', async () => { - setPlatform('darwin') - const { createSystemTray, destroySystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - - setTrayAttention(true) - destroySystemTray() - - expect(() => flushTraySceneMutation()).not.toThrow() - expect(created.setImage).not.toHaveBeenCalled() - }) - - it('keeps a pending attention dot across a macOS hide/show toggle', async () => { - setPlatform('darwin') - const { setMacMenuBarIconVisible, setTrayAttention } = await loadModule() - const options = createOptions() - setMacMenuBarIconVisible(true, options) - setTrayAttention(true) - - setMacMenuBarIconVisible(false, options) - setMacMenuBarIconVisible(true, options) - - expect(trayInstances).toHaveLength(2) - expect(trayInstances[1].setImage).toHaveBeenCalledWith(attentionImage) - }) -}) - -describe('destroySystemTray', () => { - it('destroys idempotently and removes the macOS appearance listener', async () => { - setPlatform('darwin') - const { createSystemTray, destroySystemTray } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - const listener = themeState.updatedListener - - destroySystemTray() - destroySystemTray() - - expect(created.destroy).toHaveBeenCalledOnce() - expect(nativeThemeMock.removeListener).toHaveBeenCalledWith('updated', listener) - }) -}) - -describe('macOS hardening', () => { - it('warns but still creates the item when only the @2x asset fails to load', async () => { - setPlatform('darwin') - retinaMacImage.getSize.mockReturnValue({ width: 0, height: 0 }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { createSystemTray } = await loadModule() - - expect(createSystemTray(createOptions())).not.toBeNull() - expect(trayInstances).toHaveLength(1) - expect(baseMacImage.addRepresentation).not.toHaveBeenCalled() - expect(warn).toHaveBeenCalledWith( - '[system-tray] macOS retina menu bar icon could not be loaded' - ) - }) - - it('degrades to the plain icon instead of throwing when attention composition fails', async () => { - setPlatform('darwin') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { createSystemTray, setTrayAttention } = await loadModule() - createSystemTray(createOptions()) - const created = trayInstances[0] - created.setImage.mockClear() - composeAttentionMock.mockImplementationOnce(() => { - throw new Error('native image failure') - }) - - setTrayAttention(true) - expect(() => flushTraySceneMutation()).not.toThrow() - expect(created.setImage).toHaveBeenLastCalledWith(baseMacImage) - expect(created.setToolTip).toHaveBeenLastCalledWith('Orca') - expect(warn).toHaveBeenCalledWith( - '[system-tray] macOS attention icon failed; showing plain icon', - expect.any(Error) - ) - }) - - it('contains a throwing menu-item callback instead of crashing', async () => { - setPlatform('darwin') - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { createSystemTray } = await loadModule() - const options = createOptions() - options.onOpenSettings.mockImplementation(() => { - throw new Error('boom') - }) - createSystemTray(options) - - const settingsItem = builtMenuItems().find((item) => item.label === 'Settings') - expect(() => settingsItem?.click?.()).not.toThrow() - expect(error).toHaveBeenCalledWith('[system-tray] menu action failed', expect.any(Error)) - }) -}) - -describe('language changes', () => { - it.each(['darwin', 'win32'] as const)( - 'refreshes the existing %s menu and keeps its actions', - async (platform) => { - setPlatform(platform) - const { createSystemTray, rebuildSystemTrayMenu } = await loadModule() - const { setMainUiLanguage } = await import('../i18n/main-i18n') - await setMainUiLanguage('en') - const options = { ...createOptions(), onQuitAndStopAllSessions: vi.fn() } - createSystemTray(options) - expect(builtMenuItems()[0].label).toBe('Open Orca') - - await setMainUiLanguage('ja') - rebuildSystemTrayMenu() - expect(builtMenuItems()[0].label).toBe('Open Orca') - flushTraySceneMutation() - - expect(trayInstances).toHaveLength(1) - expect(trayInstances[0].setContextMenu).toHaveBeenCalledTimes(2) - expect(builtMenuItems()[0].label).toBe('Orca を開く') - expect(builtMenuItems().at(-2)?.label).toBe('完全に終了…') - expect(builtMenuItems().at(-1)?.label).toBe('終了') - builtMenuItems()[0].click?.() - builtMenuItems().at(-2)?.click?.() - builtMenuItems().at(-1)?.click?.() - expect(options.onOpen).toHaveBeenCalledOnce() - expect(options.onQuitAndStopAllSessions).toHaveBeenCalledOnce() - expect(options.onQuit).toHaveBeenCalledOnce() - if (platform === 'darwin') { - expect(builtMenuItems()[2].label).toBe('設定') - expect(builtMenuItems()[3].label).toBe('アップデートを確認…') - builtMenuItems()[2].click?.() - builtMenuItems()[3].click?.() - expect(options.onOpenSettings).toHaveBeenCalledOnce() - expect(options.onCheckForUpdates).toHaveBeenCalledOnce() - expect(nativeThemeMock.on).toHaveBeenCalledTimes(1) - } else { - expect(trayInstances[0].on).toHaveBeenCalledTimes(1) - } - } - ) - - it('refreshes the attention tooltip and replacements in the active language catalog', async () => { - setPlatform('darwin') - const { createSystemTray, rebuildSystemTrayMenu, setTrayAttention } = await loadModule() - const { mainI18n, setMainUiLanguage } = await import('../i18n/main-i18n') - await setMainUiLanguage('en') - createSystemTray(createOptions({ isDevInstance: true, devInstanceLabel: 'language-test' })) - setTrayAttention(true) - flushTraySceneMutation() - await setMainUiLanguage('ja') - rebuildSystemTrayMenu() - flushTraySceneMutation() - expect(trayInstances[0].setToolTip).toHaveBeenLastCalledWith( - 'Orca DEV (language-test) - 件のアクティビティが待機中' - ) - expect(builtMenuItems()[0].label).toBe('Orca DEV (language-test)') - expect(composeAttentionMock).toHaveBeenCalled() - - mainI18n.addResource('ja', 'translation', 'tray.openOrca', 'Orca を表示') - rebuildSystemTrayMenu() - flushTraySceneMutation() - expect(builtMenuItems()[2].label).toBe('Orca を表示') - }) - - it('does nothing without a tray or when destroyed before the deferred refresh', async () => { - setPlatform('darwin') - const { createSystemTray, destroySystemTray, rebuildSystemTrayMenu } = await loadModule() - rebuildSystemTrayMenu() - flushTraySceneMutation() - expect(menuFromTemplateMock).not.toHaveBeenCalled() - createSystemTray(createOptions()) - rebuildSystemTrayMenu() - destroySystemTray() - menuFromTemplateMock.mockClear() - flushTraySceneMutation() - expect(menuFromTemplateMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/updater/linux-package/linux-package-update-recovery.test.ts b/src/main/updater/linux-package/linux-package-update-recovery.test.ts index b6a745edf35..b0c94fea8a5 100644 --- a/src/main/updater/linux-package/linux-package-update-recovery.test.ts +++ b/src/main/updater/linux-package/linux-package-update-recovery.test.ts @@ -156,18 +156,6 @@ describe('captureLinuxPackageArtifact', () => { expect(capture({ files: [{ url: 'orca.deb', sha512: 'not-a-digest' }] })).toBeNull() expect(recovery.getTrackedLinuxPackageArtifact()?.sha512).toBe(SHA512) }) - - it('does not arm recovery from a download with no usable digest', () => { - capture({ files: [{ url: 'orca.deb' }] }) - capture({ files: [{ url: 'orca%ZZ.deb', sha512: SHA512 }] }) - capture({ - files: [ - { url: 'orca.deb', sha512: SHA512 }, - { url: 'https://mirror.example.com/orca.deb', sha512: 'conflicting-digest' } - ] - }) - expect(recovery.getTrackedLinuxPackageArtifact()).toBeNull() - }) }) describePosix('resolveLinuxPackageInstallInstructions', () => { @@ -222,16 +210,6 @@ describePosix('digest validation', () => { }) describePosix('cache containment', () => { - it('rejects a path that traverses out of the cache', async () => { - const filePath = path.join(outsideDir, 'orca.deb') - await fsp.writeFile(filePath, PAYLOAD) - capture({ downloadedFile: path.join(downloadDir, '..', '..', '..', 'outside', 'orca.deb') }) - await expect(recovery.resolveLinuxPackageInstallInstructions(recoveryFor())).resolves.toEqual({ - ok: false, - reason: 'not-regular' - }) - }) - it('rejects a directory in place of the package', async () => { await fsp.mkdir(path.join(downloadDir, 'orca.deb')) capture() @@ -251,60 +229,10 @@ describePosix('cache containment', () => { reason: 'not-regular' }) }) - - it('rejects a package whose parent symlink escapes the cache', async () => { - await fsp.writeFile(path.join(outsideDir, 'orca.deb'), PAYLOAD) - await fsp.symlink(outsideDir, path.join(cacheRoot, 'escape')) - capture({ downloadedFile: path.join(cacheRoot, 'escape', 'orca.deb') }) - await expect(recovery.resolveLinuxPackageInstallInstructions(recoveryFor())).resolves.toEqual({ - ok: false, - reason: 'not-regular' - }) - }) - - it('rejects a subdirectory of the pending directory', async () => { - const nested = path.join(downloadDir, 'nested') - await fsp.mkdir(nested) - const filePath = path.join(nested, 'orca.deb') - await fsp.writeFile(filePath, PAYLOAD) - capture({ downloadedFile: filePath }) - await expect(recovery.resolveLinuxPackageInstallInstructions(recoveryFor())).resolves.toEqual({ - ok: false, - reason: 'not-regular' - }) - }) - - it('uses the home cache when XDG_CACHE_HOME is unset', async () => { - const homeCache = path.join(tempRoot, 'home') - const homeDownloadDir = path.join(homeCache, '.cache', 'orca-updater', 'pending') - await fsp.mkdir(homeDownloadDir, { recursive: true }) - const filePath = path.join(homeDownloadDir, 'orca.deb') - await fsp.writeFile(filePath, PAYLOAD) - vi.stubEnv('XDG_CACHE_HOME', '') - vi.spyOn(os, 'homedir').mockReturnValue(homeCache) - capture({ downloadedFile: filePath }) - await expect(recovery.resolveLinuxPackageInstallInstructions(recoveryFor())).resolves.toEqual({ - ok: true, - command: 'installed command', - packageFileName: 'orca.deb' - }) - }) }) // Pending-directory shape is defense in depth; cache-root containment excludes other users’ swap locations. describePosix('pending-directory anchoring', () => { - it('rejects a package in an attacker-owned directory under the cache root', async () => { - const evilDir = path.join(cacheRoot, 'evil') - await fsp.mkdir(evilDir) - const filePath = path.join(evilDir, 'orca.deb') - await fsp.writeFile(filePath, PAYLOAD) - capture({ downloadedFile: filePath }) - await expect(recovery.resolveLinuxPackageInstallInstructions(recoveryFor())).resolves.toEqual({ - ok: false, - reason: 'not-regular' - }) - }) - it('rejects a pending directory buried deeper than one level under the cache root', async () => { const deepPending = path.join(cacheRoot, 'evil', 'nested', 'pending') await fsp.mkdir(deepPending, { recursive: true }) @@ -317,19 +245,6 @@ describePosix('pending-directory anchoring', () => { }) }) - it('accepts any updater directory name that holds the pending directory', async () => { - const otherPending = path.join(cacheRoot, 'orca-updater-next', 'pending') - await fsp.mkdir(otherPending, { recursive: true }) - const filePath = path.join(otherPending, 'orca.deb') - await fsp.writeFile(filePath, PAYLOAD) - capture({ downloadedFile: filePath }) - await expect(recovery.resolveLinuxPackageInstallInstructions(recoveryFor())).resolves.toEqual({ - ok: true, - command: 'installed command', - packageFileName: 'orca.deb' - }) - }) - it('accepts a pending directory reached through a symlink that stays in the cache', async () => { await writePackage('orca.deb') await fsp.symlink(updaterDir, path.join(cacheRoot, 'link-to-updater')) @@ -341,15 +256,3 @@ describePosix('pending-directory anchoring', () => { }) }) }) - -describePosix('resolveLinuxPackageRevealTarget', () => { - it('rejects a package that fails validation', async () => { - const filePath = await writePackage('orca.deb') - capture() - await fsp.writeFile(filePath, 'tampered payload') - await expect(recovery.resolveLinuxPackageRevealTarget(recoveryFor())).resolves.toEqual({ - ok: false, - reason: 'hash-mismatch' - }) - }) -}) diff --git a/src/shared/terminal/input/terminal-composer-draft.test.ts b/src/shared/terminal/input/terminal-composer-draft.test.ts index c1070364202..c75ba23ba60 100644 --- a/src/shared/terminal/input/terminal-composer-draft.test.ts +++ b/src/shared/terminal/input/terminal-composer-draft.test.ts @@ -153,24 +153,7 @@ describe('detectTerminalComposerDraft', () => { expect(hasTerminalComposerPlaceholder(context)).toBe(false) }) - it('preserves a shell prompt that happens to use the Claude glyph', () => { - expect( - detectTerminalComposerDraft({ - rows: ['last command output', '❯ git status'], - typedRows: ['last command output', '❯ git status'], - promptGlyphBoldRows: [false, false], - rowsBelow: [], - typedRowsBelow: [], - beforeCursor: '❯ git status', - afterCursor: '', - rawAfterCursor: '', - cursorHidden: false, - cursorViewportRow: 7 - }) - ).toBeNull() - }) - - it.each(['gpt-5.4 high · ~/repo', 'gpt-5.4 high Fast · ~/repo'])( + it.each(['gpt-5.4 high Fast · ~/repo'])( 'recognizes a Codex composer whose undimmed footer reads %s', (footer) => { expect( @@ -285,25 +268,6 @@ describe('detectTerminalComposerDraft', () => { ).toBeNull() }) - it('keeps a draft continuation containing a middle dot', () => { - expect( - detectTerminalComposerDraft({ - rows: ['────────', '❯ proceed '], - typedRows: ['────────', '❯'], - promptGlyphBoldRows: [false, false], - rowsWrapped: [false, false], - rowsBelow: ['deploy · verify', '────────'], - typedRowsBelow: ['', '────────'], - rowsBelowWrapped: [true, false], - beforeCursor: '❯ ', - afterCursor: 'proceed ', - rawAfterCursor: 'proceed ', - cursorHidden: false, - cursorViewportRow: 8 - })?.text - ).toBe('proceed deploy · verify') - }) - it('keeps a model-like continuation before the Codex status footer', () => { expect( detectTerminalComposerDraft({ @@ -341,25 +305,6 @@ describe('detectTerminalComposerDraft', () => { ).toBe('proceed with the release') }) - it('keeps typed hard-newline rows below a restored cursor in the draft', () => { - expect( - detectTerminalComposerDraft({ - rows: ['────────', '❯ first line'], - typedRows: ['────────', '❯ first line'], - promptGlyphBoldRows: [false, false], - rowsWrapped: [false, false], - rowsBelow: [' second line', '────────'], - typedRowsBelow: [' second line', '────────'], - rowsBelowWrapped: [false, false], - beforeCursor: '❯ first', - afterCursor: ' line', - rawAfterCursor: ' line', - cursorHidden: false, - cursorViewportRow: 8 - })?.text - ).toBe('first line\nsecond line') - }) - it('keeps typed continuation rows after an intentional blank draft line', () => { expect( detectTerminalComposerDraft({ @@ -379,25 +324,6 @@ describe('detectTerminalComposerDraft', () => { ).toMatchObject({ text: 'first line\n\nsecond line', endRow: 10 }) }) - it('keeps a model-like Claude paragraph above the bottom composer frame', () => { - expect( - detectTerminalComposerDraft({ - rows: ['────────', '❯ compare models'], - typedRows: ['────────', '❯ compare models'], - promptGlyphBoldRows: [false, false], - rowsWrapped: [false, false], - rowsBelow: ['', 'gpt-5 · verify', '────────'], - typedRowsBelow: ['', 'gpt-5 · verify', '────────'], - rowsBelowWrapped: [false, false, false], - beforeCursor: '❯ ', - afterCursor: 'compare models', - rawAfterCursor: 'compare models', - cursorHidden: false, - cursorViewportRow: 8 - })?.text - ).toBe('compare models\n\ngpt-5 · verify') - }) - it('stops before a blank row that only precedes the composer frame', () => { expect( detectTerminalComposerDraft({ @@ -430,21 +356,6 @@ describe('readTerminalComposerTypedText', () => { cursorViewportRow: 8 } - it('reads a composer showing only a dim suggestion as empty', () => { - expect(readTerminalComposerTypedText(suggestionOnly)).toBe('') - }) - - it('keeps typed text and drops the dim suggestion rows after it', () => { - expect( - readTerminalComposerTypedText({ - ...suggestionOnly, - rows: ['────────', '❯ ship it'], - typedRows: ['────────', '❯ ship it'], - beforeCursor: '❯ ship it' - }) - ).toBe('ship it') - }) - it("finds the closing frame past dim suggestion rows under Claude's hidden caret", () => { const hidden = { ...suggestionOnly, cursorHidden: true, activeBuffer: 'normal' as const } expect(readTerminalComposerTypedText(hidden)).toBe('') @@ -482,10 +393,4 @@ describe('readTerminalComposerTypedText', () => { }) ).toBe('def f():\n return 1') }) - - it('returns null when no composer is visible', () => { - expect( - readTerminalComposerTypedText({ ...suggestionOnly, rows: ['Do you want to proceed?'] }) - ).toBeNull() - }) }) diff --git a/src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts b/src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts index fb395a24287..48d670b24bf 100644 --- a/src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts +++ b/src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts @@ -127,13 +127,7 @@ describe('TerminalKittyKeyboardModeTracker', () => { expect(tracker.flags).toBe(0) }) - it('replay scans arm a fresh tracker and honor pops inside the window', () => { - const fresh = new TerminalKittyKeyboardModeTracker() - fresh.scanReplay('\x1b[>1u') - expect(fresh.flags).toBe(1) - fresh.scan('\x1b[ { const ranAndExited = new TerminalKittyKeyboardModeTracker() ranAndExited.scanReplay('\x1b[>1uoutput\x1b[ { // flags is an input fallback; only snapshotFlags proves state. Republishing an unproven 0 would break bit-3 Preview input. describe('snapshot provenance', () => { - it("separates a fresh PTY's known zero from a snapshot's unproven zero", () => { - const fresh = new TerminalKittyKeyboardModeTracker() - expect(fresh.flags).toBe(0) - expect(fresh.snapshotFlags).toBe(0) - - fresh.resetForSnapshot() - expect(fresh.flags).toBe(0) - expect(fresh.snapshotFlags).toBeUndefined() - }) - it('re-proves state on an absolute set but not on a relative update', () => { const relative = new TerminalKittyKeyboardModeTracker() relative.resetForSnapshot() diff --git a/src/wsl-guest/plugins/overlays/plugin-overlay.test.ts b/src/wsl-guest/plugins/overlays/plugin-overlay.test.ts index fdfbd4d3221..a192eddb8d7 100644 --- a/src/wsl-guest/plugins/overlays/plugin-overlay.test.ts +++ b/src/wsl-guest/plugins/overlays/plugin-overlay.test.ts @@ -13,7 +13,7 @@ import { writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { basename, join } from 'node:path' +import { join } from 'node:path' import { PluginOverlayManager } from './plugin-overlay' import { resolvePiSourceAgentDir } from './plugin-overlay-env' @@ -30,48 +30,6 @@ describe('PluginOverlayManager', () => { rmSync(homeDir, { recursive: true, force: true }) }) - it('installs OpenCode plugins in the canonical XDG config roots', () => { - manager.setSources({ - opencodePluginSource: 'v1 plugin', - opencode2PluginSource: 'v2 plugin' - }) - - expect( - manager.installOpenCodePlugin('opencode', { XDG_CONFIG_HOME: join(homeDir, 'xdg') }) - ).toBe(true) - expect( - manager.installOpenCodePlugin('opencode2', { XDG_CONFIG_HOME: join(homeDir, 'xdg') }) - ).toBe(true) - expect( - readFileSync(join(homeDir, 'xdg', 'opencode', 'plugins', 'orca-opencode-status.js'), 'utf8') - ).toBe('v1 plugin') - expect( - readFileSync(join(homeDir, 'xdg', 'opencode', 'plugins', 'orca-opencode2-status.js'), 'utf8') - ).toBe('v2 plugin') - const tuiEntry = join( - homeDir, - 'xdg', - 'opencode', - 'plugins', - 'orca-opencode2-status-tui', - 'tui.js' - ) - expect(readFileSync(tuiEntry, 'utf8')).toBe('v2 plugin') - expect( - readFileSync( - join(homeDir, 'xdg', 'opencode', 'plugins', 'orca-opencode-status-tui', 'tui.js'), - 'utf8' - ) - ).toBe('v1 plugin') - - // Why: OpenCode 2 reloads plugins when a plugins/ entry is rewritten, so an unchanged - // TUI copy must not be touched on the next launch. - const past = new Date('2020-01-01T00:00:00Z') - utimesSync(tuiEntry, past, past) - manager.installOpenCodePlugin('opencode2', { XDG_CONFIG_HOME: join(homeDir, 'xdg') }) - expect(statSync(tuiEntry).mtimeMs).toBe(past.getTime()) - }) - // Why: OpenCode 2 reloads a plugin whose file mtime changed, even with unchanged bytes. it('leaves a current canonical plugin untouched and replaces a stale one', () => { const env = { XDG_CONFIG_HOME: join(homeDir, 'xdg') } @@ -181,12 +139,6 @@ describe('PluginOverlayManager', () => { } ) - it('does not override a missing preexisting OpenCode config dir', () => { - manager.setSources({ opencodePluginSource: 'orca plugin' }) - - expect(manager.materializeOpenCode('tab-missing:0', join(homeDir, 'missing'))).toBeNull() - }) - it("does not overwrite a user's same-named remote Pi extension file", () => { const piAgentDir = join(homeDir, '.pi', 'agent') const extensionFile = join(piAgentDir, 'extensions', 'orca-agent-status.ts') @@ -198,25 +150,6 @@ describe('PluginOverlayManager', () => { expect(readFileSync(extensionFile, 'utf8')).toBe('user-owned remote status extension') }) - it('uses the kind-specific Pi-compatible extension source when available', () => { - manager.setSources({ - piExtensionSource: '// pi extension', - ompExtensionSource: '// omp extension' - }) - - const piResult = manager.materializePi('tab-kind-pi:0', undefined, 'pi') - const ompResult = manager.materializePi('tab-kind-omp:0', undefined, 'omp') - - expect(piResult?.sourceAgentDir).toBeDefined() - expect(ompResult?.sourceAgentDir).toBeDefined() - expect( - readFileSync(join(piResult!.sourceAgentDir!, 'extensions', 'orca-agent-status.ts'), 'utf8') - ).toContain('// pi extension') - expect( - readFileSync(join(ompResult!.sourceAgentDir!, 'extensions', 'orca-agent-status.ts'), 'utf8') - ).toContain('// omp extension') - }) - it('uses only the Prime-specific source in the default Prime agent dir', () => { manager.setSources({ piExtensionSource: '// pi extension' }) expect(manager.materializePi('tab-prime-missing:0', undefined, 'prime-agent')).toBeNull() @@ -228,59 +161,6 @@ describe('PluginOverlayManager', () => { expect(readFileSync(result!.statusExtensionPath!, 'utf8')).not.toContain('// pi extension') }) - it('installs Orca status extension into the remote default Pi agent dir', () => { - const piAgentDir = join(homeDir, '.pi', 'agent') - mkdirSync(join(piAgentDir, 'skills', 'my-skill'), { recursive: true }) - mkdirSync(join(piAgentDir, 'extensions', 'user-ext'), { recursive: true }) - writeFileSync(join(piAgentDir, 'auth.json'), 'secret token') - writeFileSync(join(piAgentDir, 'skills', 'my-skill', 'SKILL.md'), 'critical user skill') - writeFileSync(join(piAgentDir, 'extensions', 'user-ext', 'ext.ts'), 'user extension') - writeFileSync( - join(piAgentDir, 'settings.json'), - JSON.stringify({ - defaultProvider: 'amazon-bedrock', - hideThinkingBlock: false, - terminal: { - showImages: false, - clearOnShrink: false - } - }) - ) - - manager.setSources({ piExtensionSource: '// pi extension' }) - const result = manager.materializePi('tab-pi:0') - const dir = result?.sourceAgentDir - - expect(dir).toBeDefined() - expect(readFileSync(join(dir!, 'auth.json'), 'utf8')).toBe('secret token') - expect(readFileSync(join(dir!, 'skills', 'my-skill', 'SKILL.md'), 'utf8')).toBe( - 'critical user skill' - ) - expect(readFileSync(join(dir!, 'extensions', 'user-ext', 'ext.ts'), 'utf8')).toBe( - 'user extension' - ) - expect(readdirSync(join(dir!, 'extensions')).sort()).toEqual([ - 'orca-agent-status.ts', - 'user-ext' - ]) - expect(JSON.parse(readFileSync(join(dir!, 'settings.json'), 'utf8'))).toEqual({ - defaultProvider: 'amazon-bedrock', - hideThinkingBlock: false, - terminal: { - showImages: false, - clearOnShrink: false - } - }) - expect(JSON.parse(readFileSync(join(piAgentDir, 'settings.json'), 'utf8'))).toEqual({ - defaultProvider: 'amazon-bedrock', - hideThinkingBlock: false, - terminal: { - showImages: false, - clearOnShrink: false - } - }) - }) - it('mirrors a preexisting remote Pi agent dir instead of the default', () => { const defaultAgentDir = join(homeDir, '.pi', 'agent') const customAgentDir = join(homeDir, 'custom-pi-agent') @@ -302,28 +182,6 @@ describe('PluginOverlayManager', () => { ) }) - it('leaves lazy OMP agent.db in the real remote home on the relay', () => { - manager.setSources({ piExtensionSource: '// pi extension' }) - const sourceDir = join(homeDir, '.omp', 'agent') - const first = manager.materializePi('tab-relay-omp-sqlite:0', undefined, 'omp') - - expect(first?.sourceAgentDir).toBe(sourceDir) - const sourcePath = join(sourceDir, 'agent.db') - const content = 'agent.db relay credentials' - - expect(existsSync(sourcePath)).toBe(false) - expect(existsSync(join(homeDir, '.orca-relay', 'omp-overlays'))).toBe(false) - expect(existsSync(join(sourceDir, 'history.db'))).toBe(false) - writeFileSync(sourcePath, content) - - expect(readFileSync(sourcePath, 'utf8')).toBe(content) - - const second = manager.materializePi('tab-relay-omp-sqlite:0', undefined, 'omp') - - expect(second?.sourceAgentDir).toBe(first?.sourceAgentDir) - expect(readFileSync(join(second!.sourceAgentDir!, 'agent.db'), 'utf8')).toBe(content) - }) - // Use the launch-selected Pi/OMP home; disk-presence guessing can shadow user extensions when both exist. describe('per-agent default source dir (no cross-agent fallback)', () => { function seedAgentDir(dotDir: '.pi' | '.omp', tag: string): string { @@ -334,22 +192,6 @@ describe('PluginOverlayManager', () => { return agentDir } - it('launching pi with both ~/.pi/agent and ~/.omp/agent present installs into ~/.pi/agent', () => { - seedAgentDir('.pi', 'pi') - seedAgentDir('.omp', 'omp') - - manager.setSources({ piExtensionSource: '// pi extension' }) - const result = manager.materializePi('tab-relay-pi-both:0', undefined, 'pi') - const dir = result?.sourceAgentDir - - expect(dir).toBe(join(homeDir, '.pi', 'agent')) - expect(readFileSync(join(dir!, 'auth.json'), 'utf8')).toBe('pi token') - const extensions = readdirSync(join(dir!, 'extensions')).sort() - expect(extensions).toContain('pi-ext') - expect(extensions).toContain('orca-agent-status.ts') - expect(extensions).not.toContain('omp-ext') - }) - it('launching omp with both ~/.pi/agent and ~/.omp/agent present installs into ~/.omp/agent', () => { seedAgentDir('.pi', 'pi') seedAgentDir('.omp', 'omp') @@ -418,12 +260,6 @@ describe('PluginOverlayManager', () => { }) }) - it('does not override a missing preexisting Pi agent dir', () => { - manager.setSources({ piExtensionSource: '// pi extension' }) - - expect(manager.materializePi('tab-missing-pi:0', join(homeDir, 'missing-pi'))).toBeNull() - }) - it('clearOverlay removes OpenCode overlays without deleting real Pi/OMP homes', () => { manager.setSources({ opencodePluginSource: 'opencode', @@ -478,16 +314,6 @@ describe('PluginOverlayManager', () => { expect(dirA).toBe(dirB) expect(readFileSync(join(dirA, 'plugins', 'orca-opencode-status.js'), 'utf8')).toBe('second') }) - - it('hashes unsafe pane ids into portable overlay directory names', () => { - manager.setSources({ opencodePluginSource: 'plugin' }) - const dir = manager.materializeOpenCode('tab/with\\unsafe:chars\n0') - - expect(dir).not.toBeNull() - expect(basename(dir!)).toMatch(/^[a-f0-9]{32}$/) - expect(dir).not.toContain('tab/with') - expect(existsSync(join(dir!, 'plugins', 'orca-opencode-status.js'))).toBe(true) - }) }) describe('resolvePiSourceAgentDir', () => { diff --git a/src/wsl-guest/transport/publication/dispatcher.test.ts b/src/wsl-guest/transport/publication/dispatcher.test.ts index 2f57601b83c..68d470ad3bc 100644 --- a/src/wsl-guest/transport/publication/dispatcher.test.ts +++ b/src/wsl-guest/transport/publication/dispatcher.test.ts @@ -35,49 +35,6 @@ describe('RelayDispatcher', () => { vi.useRealTimers() }) - it('sends keepalive frames on interval', () => { - expect(written.length).toBe(0) - - vi.advanceTimersByTime(5_000) - expect(written.length).toBe(1) - - const frame = decodeFirstFrame(written[0]) - expect(frame.type).toBe(MessageType.KeepAlive) - expect(frame.id).toBe(1) - }) - - it('sends error response when handler throws', async () => { - dispatcher.onRequest('fail.method', async () => { - throw new Error('boom') - }) - - const req: JsonRpcRequest = { - jsonrpc: '2.0', - id: 5, - method: 'fail.method' - } - dispatcher.feed(encodeJsonRpcFrame(req, 1, 0)) - await vi.advanceTimersByTimeAsync(0) - - const errors = written.filter((buf) => { - const f = decodeFirstFrame(buf) - if (f.type !== MessageType.Regular) { - return false - } - try { - const msg = JSON.parse(f.payload.toString('utf-8')) - return 'error' in msg - } catch { - return false - } - }) - expect(errors.length).toBe(1) - - const resp = JSON.parse(decodeFirstFrame(errors[0]).payload.toString('utf-8')) - expect(resp.error.message).toBe('boom') - expect(resp.id).toBe(5) - }) - it('sends method-not-found for unknown methods', async () => { const req: JsonRpcRequest = { jsonrpc: '2.0', @@ -139,34 +96,6 @@ describe('RelayDispatcher', () => { expect(secondWritten).toHaveLength(0) }) - it('forwards relay-originated requests to an owning socket client instead of the caller', async () => { - dispatcher.invalidateClient() - const ownerWritten: Buffer[] = [] - const ownerId = dispatcher.attachClient((data) => { - ownerWritten.push(Buffer.from(data)) - }) - const cliId = dispatcher.attachClient(() => {}) - - const pending = dispatcher.requestAnyClient( - 'orca.cli', - { argv: ['status'] }, - { excludeClientId: cliId } - ) - - expect(ownerWritten).toHaveLength(1) - const requestFrame = decodeFirstFrame(ownerWritten[0]) - const request = JSON.parse(requestFrame.payload.toString('utf-8')) as JsonRpcRequest - expect(request.method).toBe('orca.cli') - expect(request.params).toEqual({ argv: ['status'] }) - - dispatcher.feedClient( - ownerId, - encodeJsonRpcFrame({ jsonrpc: '2.0', id: request.id, result: { exitCode: 0 } }, 1, 0) - ) - - await expect(pending).resolves.toEqual({ exitCode: 0 }) - }) - it('prefers an owning socket client over the synthetic primary client', async () => { const ownerWritten: Buffer[] = [] const ownerId = dispatcher.attachClient((data) => { From b8507d4d4abd230fdab8abf0c2892f281580ffa9 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:07:08 -0800 Subject: [PATCH 21/52] fix(settings): give unnamed Settings controls accessible names (#42216) Add aria-labels to the UI zoom and terminal font size steppers and the word separators input, name the scroll speed slider thumbs, and link the visible Branch prefix, Arguments and Command template labels to their fields via htmlFor/id. Fixes #41604 --- .../agent/launch-settings/AgentChoiceOptionField.tsx | 6 +++++- .../components/settings/appearance/UIZoomControl.tsx | 2 ++ .../RepositorySourceControlAiActionRows.tsx | 5 ++++- .../components/settings/source-control/GitPane.tsx | 8 ++++++-- .../source-control/SourceControlActionRecipeRow.tsx | 7 ++++++- .../settings/terminal/TerminalAdvancedSection.tsx | 9 +++++++-- .../settings/terminal/TerminalScrollSpeedSlider.tsx | 1 + .../terminal/appearance/TerminalFontSizeSetting.tsx | 11 +++++++++-- src/renderer/src/i18n/locales/en.json | 8 ++++++++ 9 files changed, 48 insertions(+), 9 deletions(-) diff --git a/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx b/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx index 476815e0c6b..597556d28f6 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentChoiceOptionField.tsx @@ -6,15 +6,19 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip' export function SourceControlActionOptionField({ label, hint, + controlId, children }: { label: ReactNode hint?: ReactNode + controlId?: string children: ReactNode }): React.JSX.Element { return (
- + {children} {hint ?

{hint}

: null}
diff --git a/src/renderer/src/components/settings/appearance/UIZoomControl.tsx b/src/renderer/src/components/settings/appearance/UIZoomControl.tsx index 426fcd7e90a..3f8c1e497e8 100644 --- a/src/renderer/src/components/settings/appearance/UIZoomControl.tsx +++ b/src/renderer/src/components/settings/appearance/UIZoomControl.tsx @@ -36,6 +36,7 @@ export function UIZoomControl(): React.JSX.Element { size="icon-sm" onClick={() => applyZoom(zoomLevel - ZOOM_STEP)} disabled={zoomLevel <= ZOOM_MIN} + aria-label={t('settings.appearance.uiZoom.zoomOut', 'Zoom out')} > @@ -45,6 +46,7 @@ export function UIZoomControl(): React.JSX.Element { size="icon-sm" onClick={() => applyZoom(zoomLevel + ZOOM_STEP)} disabled={zoomLevel >= ZOOM_MAX} + aria-label={t('settings.appearance.uiZoom.zoomIn', 'Zoom in')} > diff --git a/src/renderer/src/components/settings/repository/source-control/RepositorySourceControlAiActionRows.tsx b/src/renderer/src/components/settings/repository/source-control/RepositorySourceControlAiActionRows.tsx index c79cdf6c962..a0d44e86f65 100644 --- a/src/renderer/src/components/settings/repository/source-control/RepositorySourceControlAiActionRows.tsx +++ b/src/renderer/src/components/settings/repository/source-control/RepositorySourceControlAiActionRows.tsx @@ -311,8 +311,10 @@ const SelectedRepositoryActionRows = memo( {!isLaunchAction ? ( onActionAgentArgsChange(actionId, event.target.value)} disabled={!hasOverride} @@ -324,13 +326,14 @@ const SelectedRepositoryActionRows = memo( ) : null}
-