From e623372cdb9942d3ba48fccc1ae38dfe4bffcb78 Mon Sep 17 00:00:00 2001 From: Nikolatesla-lj <34672324+Nikolatesla-lj@users.noreply.github.com> Date: Tue, 5 May 2026 14:46:23 +0800 Subject: [PATCH] feat(cli): add tab profile controls and automation primitives (#1396) * feat(cli): add browser tab profile controls * feat(cli): add tab profile automation primitives * refactor(cli): narrow tab profile automation scope * chore: retrigger PR checks * review: harden tab profile automation CLI - Wait for tab re-registration after browser.tabSetProfile so a follow-up tab list --show-profile reads the new sessionProfileId from BrowserManager instead of the stale one from the previous webview - Wait for tab registration after browser.tabProfileClone, matching browser.tabCreate, so the cloned browserPageId is operable when the CLI returns - Short-circuit browser.tabSetProfile when the tab is already on the requested profile so we do not tear down and remount the webview for a no-op switch - Switch TabShow.worktree from OptionalPlainString to OptionalString to match every other tab schema; empty --worktree should fall back to the active worktree, not pass through as the empty string - Add max-lines disable to browser.test.ts (file grew past 300 lines after adding the new tab-profile and tab-show tests) * review: fix useIpcEvents test setup for tab profile API CI failure: useIpcEvents.test.ts threw at module load with TypeError: window.addEventListener is not a function. The chain: the rebased useIpcEvents.ts imports destroyPersistentWebview from webview-registry, which calls window.addEventListener at module load. The test stubs window via vi.stubGlobal as a plain object without addEventListener, so the typeof window check passes but the call throws. - webview-registry.ts: tighten the module-load guard to also check that window.addEventListener is callable, so importing this module from a non-DOM-ish test env (vitest node env with stubbed window) does not throw at module load - useIpcEvents.test.ts: add the new onRequestTabSetProfile and replyTabSetProfile stubs to all 8 window.api.ui mocks so the new IPC subscription registered by useIpcEvents resolves * review: restore profile CRUD lost during rebase onto 1397-merged main The rebase brought commit 3242aa27 (refactor: narrow tab profile automation scope) onto a main that already had the lifecycle CRUD from 1397. The refactor commit removes BrowserProfileList/Create/Delete types, runtime methods, RPC registrations and schemas, plus the help/specs entries, because those were the precursor versions in commit 1 of this branch. Post-rebase those removals land on the hardened versions inherited from main, breaking 1397. Restore: - runtime-types.ts: BrowserSessionProfile import; ProfileList/Create/Delete result types - orca-runtime.ts: ProfileList/Create/Delete result type imports; browserProfileList/Create/Delete methods - browser-core.ts: ProfileCreate, ProfileDelete schema imports; browser.profileList/profileCreate/profileDelete RPC registrations - browser-schemas.ts: ProfileCreate, ProfileDelete zod schemas - help.ts: list/create/delete subcommand lines under Browser Automation - specs/browser-basic.ts: list/create/delete spec entries --------- Co-authored-by: Nikolatesla-lj Co-authored-by: Jinwoo-H --- src/cli/args.ts | 6 +- src/cli/browser.test.ts | 218 +++++++++++++ src/cli/format.ts | 39 ++- src/cli/handlers/browser-profile.ts | 49 ++- src/cli/handlers/browser-tab.ts | 36 ++- src/cli/help.ts | 17 +- src/cli/specs/browser-basic.ts | 42 ++- src/main/browser/browser-manager.test.ts | 26 ++ src/main/browser/browser-manager.ts | 10 + src/main/ipc/browser.ts | 1 + src/main/runtime/orca-runtime.ts | 291 +++++++++++++++--- src/main/runtime/rpc/methods/browser-core.ts | 29 ++ .../runtime/rpc/methods/browser-schemas.ts | 52 +++- src/preload/api-types.ts | 12 +- src/preload/index.ts | 23 +- .../components/browser-pane/BrowserPane.tsx | 1 + .../browser-pane/webview-registry.ts | 6 +- src/renderer/src/hooks/useIpcEvents.test.ts | 16 + src/renderer/src/hooks/useIpcEvents.ts | 36 ++- src/shared/runtime-types.ts | 31 ++ 20 files changed, 855 insertions(+), 86 deletions(-) diff --git a/src/cli/args.ts b/src/cli/args.ts index f61cfb751..b97308b32 100644 --- a/src/cli/args.ts +++ b/src/cli/args.ts @@ -64,7 +64,11 @@ export function supportsBrowserPageFlag(commandPath: string[]): boolean { if (['repo', 'worktree', 'terminal'].includes(commandPath[0])) { return false } - return !['tab list', 'tab create'].includes(joined) + return ![ + 'tab list', + 'tab create', + 'tab current' + ].includes(joined) } export function isCommandGroup(commandPath: string[]): boolean { diff --git a/src/cli/browser.test.ts b/src/cli/browser.test.ts index b1fddb8bb..c84a0f7e7 100644 --- a/src/cli/browser.test.ts +++ b/src/cli/browser.test.ts @@ -127,6 +127,224 @@ describe('orca cli browser page targeting', () => { worktree: `path:${path.resolve('/tmp/repo/feature')}` }) }) + + it('passes explicit profile ids to tab create', async () => { + queueFixtures(callMock, okFixture('req_create', { browserPageId: 'page-3' })) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + [ + 'tab', + 'create', + '--url', + 'https://example.com', + '--profile', + 'work', + '--worktree', + 'all', + '--json' + ], + '/tmp/not-an-orca-worktree' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith( + 'browser.tabCreate', + { + url: 'https://example.com', + worktree: undefined, + profileId: 'work' + }, + { timeoutMs: 60_000 } + ) + }) + + it('passes tab profile updates through by page id', async () => { + queueFixtures( + callMock, + okFixture('req_set_profile', { + browserPageId: 'page-2', + profileId: 'work', + profileLabel: 'Work' + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + ['tab', 'profile', 'set', '--page', 'page-2', '--profile', 'work', '--json'], + '/tmp/repo/feature/src' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabSetProfile', { + page: 'page-2', + profileId: 'work' + }) + }) + + it('shows tab profile labels in text mode when requested', async () => { + queueFixtures( + callMock, + okFixture('req_list', { + tabs: [ + { + browserPageId: 'page-1', + index: 0, + url: 'https://example.com', + title: 'Example', + active: true, + profileId: 'default', + profileLabel: 'Default' + }, + { + browserPageId: 'page-2', + index: 1, + url: 'https://mail.example.com', + title: 'Mail', + active: false, + profileId: 'work', + profileLabel: 'Work' + } + ] + }) + ) + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['tab', 'list', '--show-profile', '--worktree', 'all'], '/tmp/not-an-orca-worktree') + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabList', { worktree: undefined }) + expect(logSpy).toHaveBeenCalledWith( + '* [0] page-1 Example — https://example.com [Default]\n' + + ' [1] page-2 Mail — https://mail.example.com [Work]' + ) + }) + + it('shows a single tab by page id', async () => { + queueFixtures( + callMock, + okFixture('req_tab_show', { + tab: { + browserPageId: 'page-1', + index: 0, + url: 'https://example.com', + title: 'Example', + active: true, + worktreeId: 'repo::/tmp/repo/feature', + profileId: 'work', + profileLabel: 'Work' + } + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['tab', 'show', '--page', 'page-1', '--json'], '/tmp/not-an-orca-worktree') + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabShow', { page: 'page-1' }) + }) + + it('resolves the current tab in a worktree', async () => { + queueFixtures( + callMock, + okFixture('req_tab_current', { + tab: { + browserPageId: 'page-2', + index: 1, + url: 'https://mail.example.com', + title: 'Mail', + active: true, + worktreeId: 'repo::/tmp/repo/feature', + profileId: 'default', + profileLabel: 'Default' + } + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main(['tab', 'current', '--worktree', 'all', '--json'], '/tmp/not-an-orca-worktree') + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabCurrent', { worktree: undefined }) + }) +}) + +describe('orca cli browser tab profiles', () => { + beforeEach(() => { + callMock.mockReset() + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('shows the profile bound to a tab', async () => { + queueFixtures( + callMock, + okFixture('req_profile_show', { + browserPageId: 'page-2', + worktreeId: 'repo::/tmp/repo/feature', + profileId: 'work', + profileLabel: 'Work' + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + ['tab', 'profile', 'show', '--page', 'page-2', '--json'], + '/tmp/not-an-orca-worktree' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabProfileShow', { page: 'page-2' }) + }) + + it('switches a tab back to the default profile', async () => { + queueFixtures( + callMock, + okFixture('req_profile_default', { + browserPageId: 'page-2', + profileId: 'default', + profileLabel: 'Default' + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + ['tab', 'profile', 'use-default', '--page', 'page-2', '--json'], + '/tmp/not-an-orca-worktree' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabSetProfile', { + page: 'page-2', + profileId: 'default' + }) + }) + + it('clones a tab into a different profile', async () => { + queueFixtures( + callMock, + okFixture('req_profile_clone', { + browserPageId: 'page-9', + sourceBrowserPageId: 'page-2', + profileId: 'work', + profileLabel: 'Work' + }) + ) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await main( + ['tab', 'profile', 'clone', '--page', 'page-2', '--profile', 'work', '--json'], + '/tmp/not-an-orca-worktree' + ) + + expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledWith('browser.tabProfileClone', { + page: 'page-2', + profileId: 'work' + }) + }) }) describe('orca cli browser tab profiles', () => { diff --git a/src/cli/format.ts b/src/cli/format.ts index aacad3fbc..2ea429e13 100644 --- a/src/cli/format.ts +++ b/src/cli/format.ts @@ -1,8 +1,12 @@ import type { BrowserProfileListResult, + BrowserTabCurrentResult, BrowserScreenshotResult, BrowserSnapshotResult, BrowserTabListResult, + BrowserTabProfileCloneResult, + BrowserTabProfileShowResult, + BrowserTabShowResult, CliStatusResult, RuntimeRepoList, RuntimeRepoSearchRefs, @@ -238,13 +242,21 @@ export function formatScreenshot(result: BrowserScreenshotResult): string { } export function formatTabList(result: BrowserTabListResult): string { + return formatTabListWithProfiles(result, false) +} + +export function formatTabListWithProfiles( + result: BrowserTabListResult, + showProfile: boolean +): string { if (result.tabs.length === 0) { return 'No browser tabs open.' } return result.tabs .map((t) => { const marker = t.active ? '* ' : ' ' - return `${marker}[${t.index}] ${t.browserPageId} ${t.title} — ${t.url}` + const profile = showProfile ? ` [${t.profileLabel ?? t.profileId ?? 'Unknown'}]` : '' + return `${marker}[${t.index}] ${t.browserPageId} ${t.title} — ${t.url}${profile}` }) .join('\n') } @@ -261,3 +273,28 @@ export function formatBrowserProfileList(result: BrowserProfileListResult): stri }) .join('\n') } + +export function formatTabShow(result: BrowserTabShowResult | BrowserTabCurrentResult): string { + const tab = result.tab + return [ + `page: ${tab.browserPageId}`, + `title: ${tab.title}`, + `url: ${tab.url}`, + `active: ${tab.active}`, + `worktree: ${tab.worktreeId ?? 'unknown'}`, + `profile: ${tab.profileLabel ?? tab.profileId ?? 'unknown'}` + ].join('\n') +} + +export function formatTabProfileShow(result: BrowserTabProfileShowResult): string { + return [ + `page: ${result.browserPageId}`, + `worktree: ${result.worktreeId ?? 'unknown'}`, + `profileId: ${result.profileId ?? 'default'}`, + `profile: ${result.profileLabel ?? result.profileId ?? 'default'}` + ].join('\n') +} + +export function formatTabProfileClone(result: BrowserTabProfileCloneResult): string { + return `Cloned ${result.sourceBrowserPageId} to ${result.browserPageId} (${result.profileLabel ?? result.profileId ?? 'default'})` +} diff --git a/src/cli/handlers/browser-profile.ts b/src/cli/handlers/browser-profile.ts index 0e4eefac2..4dc8ad731 100644 --- a/src/cli/handlers/browser-profile.ts +++ b/src/cli/handlers/browser-profile.ts @@ -1,12 +1,21 @@ import type { BrowserProfileCreateResult, BrowserProfileDeleteResult, - BrowserProfileListResult + BrowserProfileListResult, + BrowserTabProfileCloneResult, + BrowserTabProfileShowResult, + BrowserTabSetProfileResult } from '../../shared/runtime-types' import type { CommandHandler } from '../dispatch' import { getOptionalStringFlag, getRequiredStringFlag } from '../flags' -import { formatBrowserProfileList, printResult } from '../format' +import { + formatBrowserProfileList, + formatTabProfileClone, + formatTabProfileShow, + printResult +} from '../format' import { RuntimeClientError } from '../runtime-client' +import { getBrowserCommandTarget } from '../selectors' function parseScopeFlag(flags: Map): 'isolated' | 'imported' { const raw = getOptionalStringFlag(flags, 'scope') @@ -57,5 +66,41 @@ export const BROWSER_PROFILE_HANDLERS: Record = { ? `Deleted profile ${value.profileId}` : `Profile ${value.profileId} was not deleted` ) + }, + 'tab profile set': async ({ flags, client, cwd, json }) => { + const profileId = getRequiredStringFlag(flags, 'profile') + const target = await getBrowserCommandTarget(flags, cwd, client) + const result = await client.call('browser.tabSetProfile', { + ...target, + profileId + }) + printResult( + result, + json, + (value) => + `Switched ${value.browserPageId} to ${value.profileLabel ?? value.profileId ?? 'default'}` + ) + }, + 'tab profile show': async ({ flags, client, cwd, json }) => { + const target = await getBrowserCommandTarget(flags, cwd, client) + const result = await client.call('browser.tabProfileShow', target) + printResult(result, json, formatTabProfileShow) + }, + 'tab profile use-default': async ({ flags, client, cwd, json }) => { + const target = await getBrowserCommandTarget(flags, cwd, client) + const result = await client.call('browser.tabSetProfile', { + ...target, + profileId: 'default' + }) + printResult(result, json, (value) => `Switched ${value.browserPageId} to Default`) + }, + 'tab profile clone': async ({ flags, client, cwd, json }) => { + const profileId = getRequiredStringFlag(flags, 'profile') + const target = await getBrowserCommandTarget(flags, cwd, client) + const result = await client.call('browser.tabProfileClone', { + ...target, + profileId + }) + printResult(result, json, formatTabProfileClone) } } diff --git a/src/cli/handlers/browser-tab.ts b/src/cli/handlers/browser-tab.ts index e842cd33c..01d6a6e51 100644 --- a/src/cli/handlers/browser-tab.ts +++ b/src/cli/handlers/browser-tab.ts @@ -1,11 +1,17 @@ -import type { BrowserTabListResult, BrowserTabSwitchResult } from '../../shared/runtime-types' +import type { + BrowserTabCurrentResult, + BrowserTabListResult, + BrowserTabShowResult, + BrowserTabSwitchResult +} from '../../shared/runtime-types' import type { CommandHandler } from '../dispatch' -import { formatTabList, printResult } from '../format' import { - getOptionalNonNegativeIntegerFlag, - getOptionalStringFlag, - getRequiredStringFlag -} from '../flags' + formatTabList, + formatTabListWithProfiles, + formatTabShow, + printResult +} from '../format' +import { getOptionalNonNegativeIntegerFlag, getOptionalStringFlag, getRequiredStringFlag } from '../flags' import { RuntimeClientError } from '../runtime-client' import { getBrowserCommandTarget, getBrowserWorktreeSelector } from '../selectors' @@ -13,7 +19,20 @@ export const BROWSER_TAB_HANDLERS: Record = { 'tab list': async ({ flags, client, cwd, json }) => { const worktree = await getBrowserWorktreeSelector(flags, cwd, client) const result = await client.call('browser.tabList', { worktree }) - printResult(result, json, formatTabList) + const showProfile = flags.has('show-profile') + printResult(result, json, (value) => + showProfile ? formatTabListWithProfiles(value, true) : formatTabList(value) + ) + }, + 'tab show': async ({ flags, client, cwd, json }) => { + const target = await getBrowserCommandTarget(flags, cwd, client) + const result = await client.call('browser.tabShow', target) + printResult(result, json, formatTabShow) + }, + 'tab current': async ({ flags, client, cwd, json }) => { + const worktree = await getBrowserWorktreeSelector(flags, cwd, client) + const result = await client.call('browser.tabCurrent', { worktree }) + printResult(result, json, formatTabShow) }, 'tab switch': async ({ flags, client, cwd, json }) => { const index = getOptionalNonNegativeIntegerFlag(flags, 'index') @@ -34,10 +53,11 @@ export const BROWSER_TAB_HANDLERS: Record = { }, 'tab create': async ({ flags, client, cwd, json }) => { const url = getOptionalStringFlag(flags, 'url') + const profileId = getOptionalStringFlag(flags, 'profile') const worktree = await getBrowserWorktreeSelector(flags, cwd, client) const result = await client.call<{ browserPageId: string }>( 'browser.tabCreate', - { url, worktree }, + { url, worktree, profileId }, { timeoutMs: 60_000 } ) printResult(result, json, (v) => `Created tab ${v.browserPageId}`) diff --git a/src/cli/help.ts b/src/cli/help.ts index 2ad77f9db..3adb9cc98 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -59,9 +59,15 @@ Orchestration: Browser Automation: tab create Create a new browser tab (navigates to --url) tab list List open browser tabs + tab show Show one browser tab by page id + tab current Show the current browser tab tab profile list List browser session profiles tab profile create Create a browser session profile tab profile delete Delete a browser session profile + tab profile set Switch a browser tab to a different profile + tab profile show Show the profile bound to a browser tab + tab profile use-default Switch a browser tab back to the default profile + tab profile clone Clone a browser tab into another profile tab switch Switch the active browser tab by --index or --page tab close Close a browser tab by --index/--page or the current tab snapshot Accessibility snapshot with element refs (e.g. @e1, @e2) @@ -186,7 +192,8 @@ Browser Options: --amount Scroll distance in pixels (default: viewport height) --index Tab index (from \`tab list\`) --page Stable browser page id (preferred for concurrent workflows) - --profile Browser profile id (see \`orca tab profile list\`) + --profile Browser profile id + --show-profile Include the tab's browser profile in text output --format Screenshot image format --from Drag source element ref --to Drag target element ref @@ -206,9 +213,10 @@ Examples: $ orca terminal list --worktree path:/Users/me/orca/workspaces/orca/cli-test-1 --json $ orca terminal send --terminal term_123 --text "hi" --enter $ orca terminal wait --terminal term_123 --for exit --timeout-ms 60000 --json - $ orca tab profile list - $ orca tab profile create --label Work - $ orca tab create --url https://example.com + $ orca tab current --json + $ orca tab show --page page_123 --json + $ orca tab create --url https://example.com --profile work + $ orca tab profile clone --page page_123 --profile work --json $ orca snapshot $ orca click --element e3 $ orca fill --element e5 --value "hello" @@ -313,6 +321,7 @@ export function formatFlagHelp(flag: string): string { index: '--index Tab index to switch to', page: '--page Stable browser page id from `orca tab list --json`', profile: '--profile Browser profile id', + 'show-profile': '--show-profile Include tab profile in text output', format: '--format Screenshot image format' } diff --git a/src/cli/specs/browser-basic.ts b/src/cli/specs/browser-basic.ts index 9466a18fc..42af901ab 100644 --- a/src/cli/specs/browser-basic.ts +++ b/src/cli/specs/browser-basic.ts @@ -154,7 +154,19 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = [ { path: ['tab', 'list'], summary: 'List open browser tabs', - usage: 'orca tab list [--worktree ] [--json]', + usage: 'orca tab list [--worktree ] [--show-profile] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'show-profile'] + }, + { + path: ['tab', 'show'], + summary: 'Show one browser tab by page id', + usage: 'orca tab show --page [--worktree ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree'] + }, + { + path: ['tab', 'current'], + summary: 'Show the current browser tab', + usage: 'orca tab current [--worktree ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'worktree'] }, { @@ -166,8 +178,8 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = [ { path: ['tab', 'create'], summary: 'Create a new browser tab in the current worktree', - usage: 'orca tab create [--url ] [--worktree ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'url', 'worktree'] + usage: 'orca tab create [--url ] [--worktree ] [--profile ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'url', 'worktree', 'profile'] }, { path: ['tab', 'profile', 'list'], @@ -187,6 +199,30 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = [ usage: 'orca tab profile delete --profile [--json]', allowedFlags: [...GLOBAL_FLAGS, 'profile'] }, + { + path: ['tab', 'profile', 'set'], + summary: 'Switch a browser tab to a different browser profile', + usage: 'orca tab profile set (--page | --worktree ) --profile [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'profile', 'worktree'] + }, + { + path: ['tab', 'profile', 'show'], + summary: 'Show the browser profile bound to a tab', + usage: 'orca tab profile show --page [--worktree ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree'] + }, + { + path: ['tab', 'profile', 'use-default'], + summary: 'Switch a browser tab back to the default browser profile', + usage: 'orca tab profile use-default --page [--worktree ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree'] + }, + { + path: ['tab', 'profile', 'clone'], + summary: 'Clone a browser tab into a different browser profile', + usage: 'orca tab profile clone --profile [--page ] [--worktree ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'profile', 'worktree'] + }, { path: ['tab', 'close'], summary: 'Close a browser tab', diff --git a/src/main/browser/browser-manager.test.ts b/src/main/browser/browser-manager.test.ts index 308a48347..8fc225b78 100644 --- a/src/main/browser/browser-manager.test.ts +++ b/src/main/browser/browser-manager.test.ts @@ -131,6 +131,32 @@ describe('browserManager', () => { }) }) + it('remembers the registered session profile for a browser page', () => { + const guest = { + id: 104, + isDestroyed: vi.fn(() => false), + getType: vi.fn(() => 'webview'), + setBackgroundThrottling: guestSetBackgroundThrottlingMock, + setWindowOpenHandler: guestSetWindowOpenHandlerMock, + on: guestOnMock, + off: guestOffMock, + openDevTools: guestOpenDevToolsMock + } + webContentsFromIdMock.mockReturnValue(guest) + + browserManager.attachGuestPolicies(guest as never) + browserManager.registerGuest({ + browserPageId: 'browser-1', + workspaceId: 'workspace-1', + worktreeId: 'wt-1', + webContentsId: guest.id, + rendererWebContentsId, + sessionProfileId: 'work' + }) + + expect(browserManager.getSessionProfileIdForTab('browser-1')).toBe('work') + }) + it('falls back to opening popup URLs externally before a guest is registered', () => { const guest = { id: 105, diff --git a/src/main/browser/browser-manager.ts b/src/main/browser/browser-manager.ts index 1a5996d1e..fb89bbd6b 100644 --- a/src/main/browser/browser-manager.ts +++ b/src/main/browser/browser-manager.ts @@ -55,6 +55,7 @@ export type BrowserGuestRegistration = { browserTabId?: string workspaceId?: string worktreeId?: string + sessionProfileId?: string | null webContentsId: number rendererWebContentsId: number } @@ -97,6 +98,7 @@ export class BrowserManager { // visibility/focus state is keyed by browser workspace id. Screenshot prep // has to bridge that mismatch to activate the right tab before capture. private readonly workspaceIdByPageId = new Map() + private readonly sessionProfileIdByPageId = new Map() private readonly rendererWebContentsIdByTabId = new Map() // Why: chain setViewportOverride calls per tab so rapid toggles don't // interleave CDP commands. Without serialization, two concurrent calls can @@ -543,6 +545,7 @@ export class BrowserManager { browserTabId: legacyBrowserTabId, workspaceId, worktreeId, + sessionProfileId, webContentsId, rendererWebContentsId }: BrowserGuestRegistration): void { @@ -592,6 +595,7 @@ export class BrowserManager { if (workspaceId) { this.workspaceIdByPageId.set(browserTabId, workspaceId) } + this.sessionProfileIdByPageId.set(browserTabId, sessionProfileId ?? null) this.rendererWebContentsIdByTabId.set(browserTabId, rendererWebContentsId) if (worktreeId) { this.worktreeIdByTabId.set(browserTabId, worktreeId) @@ -655,6 +659,7 @@ export class BrowserManager { this.webContentsIdByTabId.delete(browserTabId) this.rendererWebContentsIdByTabId.delete(browserTabId) this.workspaceIdByPageId.delete(browserTabId) + this.sessionProfileIdByPageId.delete(browserTabId) this.worktreeIdByTabId.delete(browserTabId) // Why: drop any pending viewport-op chain for this tab so the Map doesn't // retain a resolved promise keyed to a destroyed guest. @@ -681,6 +686,7 @@ export class BrowserManager { this.policyCleanupByGuestId.clear() this.tabIdByWebContentsId.clear() this.worktreeIdByTabId.clear() + this.sessionProfileIdByPageId.clear() this.pendingLoadFailuresByGuestId.clear() this.pendingPermissionEventsByGuestId.clear() this.pendingPopupEventsByGuestId.clear() @@ -699,6 +705,10 @@ export class BrowserManager { return this.worktreeIdByTabId.get(browserTabId) } + getSessionProfileIdForTab(browserTabId: string): string | null { + return this.sessionProfileIdByPageId.get(browserTabId) ?? null + } + notifyPermissionDenied(args: { guestWebContentsId: number permission: string diff --git a/src/main/ipc/browser.ts b/src/main/ipc/browser.ts index 2aa42699d..e2424648b 100644 --- a/src/main/ipc/browser.ts +++ b/src/main/ipc/browser.ts @@ -103,6 +103,7 @@ export function registerBrowserHandlers(): void { browserPageId: string workspaceId: string worktreeId: string + sessionProfileId?: string | null webContentsId: number } ) => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index e6d3b115c..8c8ce9e42 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -53,13 +53,18 @@ import type { BrowserScrollResult, BrowserBackResult, BrowserReloadResult, - BrowserScreenshotResult, - BrowserEvalResult, - BrowserTabListResult, - BrowserTabSwitchResult, BrowserProfileCreateResult, BrowserProfileDeleteResult, BrowserProfileListResult, + BrowserScreenshotResult, + BrowserEvalResult, + BrowserTabCurrentResult, + BrowserTabListResult, + BrowserTabProfileCloneResult, + BrowserTabProfileShowResult, + BrowserTabSetProfileResult, + BrowserTabShowResult, + BrowserTabSwitchResult, BrowserHoverResult, BrowserDragResult, BrowserUploadResult, @@ -84,6 +89,7 @@ import type { } from '../../shared/runtime-types' import { BrowserWindow, ipcMain } from 'electron' import type { AgentBrowserBridge } from '../browser/agent-browser-bridge' +import { browserManager } from '../browser/browser-manager' import { BrowserError } from '../browser/cdp-bridge' import { browserSessionRegistry } from '../browser/browser-session-registry' import { waitForTabRegistration } from '../ipc/browser' @@ -4452,7 +4458,24 @@ export class OrcaRuntimeService { async browserTabList(params: { worktree?: string }): Promise { const worktreeId = await this.resolveBrowserWorktreeId(params.worktree) - return this.requireAgentBrowserBridge().tabList(worktreeId) + const result = this.requireAgentBrowserBridge().tabList(worktreeId) + return { + tabs: result.tabs.map((tab) => this.enrichBrowserTabInfo(tab)) + } + } + + async browserTabShow(params: { page: string; worktree?: string }): Promise { + const worktreeId = await this.resolveBrowserWorktreeId(params.worktree) + return { tab: this.describeBrowserTab(params.page, worktreeId) } + } + + async browserTabCurrent(params: { worktree?: string }): Promise { + const worktreeId = await this.resolveBrowserWorktreeId(params.worktree) + const browserPageId = this.requireAgentBrowserBridge().getActivePageId(worktreeId) + if (!browserPageId) { + throw new BrowserError('browser_no_tab', 'No browser tab open in this worktree') + } + return { tab: this.describeBrowserTab(browserPageId, worktreeId) } } async browserTabSwitch( @@ -5104,51 +5127,17 @@ export class OrcaRuntimeService { async browserTabCreate(params: { url?: string worktree?: string + profileId?: string }): Promise<{ browserPageId: string }> { - const win = this.getAuthoritativeWindow() - const requestId = randomUUID() const url = params.url ?? 'about:blank' - - // Why: the renderer's Zustand store keys browser tabs by worktreeId in - // "repoId::path" format. The CLI sends a selector (e.g. "path:/Users/..."). - // Resolve it here so the renderer receives the store-compatible ID. const worktreeId = params.worktree ? (await this.resolveWorktreeSelector(params.worktree)).id : undefined - - // Why: browser webviews only mount when their worktree is active in the UI. - // Switch to it before creating the tab so the webview attaches immediately. - if (worktreeId) { - await this.ensureBrowserWorktreeActive(worktreeId) - } - - // Why: tab creation is a renderer-side Zustand store operation. The main process - // sends a request, the renderer creates the tab and replies with the workspace ID - // (which is the browserPageId used by registerGuest and the bridge). - const browserPageId = await new Promise((resolve, reject) => { - const timer = setTimeout(() => { - ipcMain.removeListener('browser:tabCreateReply', handler) - reject(new Error('Tab creation timed out')) - }, 10_000) - - const handler = ( - _event: Electron.IpcMainEvent, - reply: { requestId: string; browserPageId?: string; error?: string } - ): void => { - if (reply.requestId !== requestId) { - return - } - clearTimeout(timer) - ipcMain.removeListener('browser:tabCreateReply', handler) - if (reply.error) { - reject(new Error(reply.error)) - } else { - resolve(reply.browserPageId!) - } - } - ipcMain.on('browser:tabCreateReply', handler) - win.webContents.send('browser:requestTabCreate', { requestId, url, worktreeId }) - }) + const { browserPageId } = await this.createBrowserTabInRenderer( + url, + worktreeId, + params.profileId + ) // Why: the renderer creates the Zustand tab immediately, but the webview must // mount and fire dom-ready before registerGuest runs. Waiting here ensures the @@ -5189,6 +5178,140 @@ export class OrcaRuntimeService { return { browserPageId } } + async browserTabSetProfile( + params: { + profileId: string + } & BrowserCommandTargetParams + ): Promise { + const target = await this.resolveBrowserCommandTarget(params) + const browserPageId = + target.browserPageId ?? this.requireAgentBrowserBridge().getActivePageId(target.worktreeId) + if (!browserPageId) { + throw new BrowserError('browser_no_tab', 'No browser tab open in this worktree') + } + const profile = browserSessionRegistry.getProfile(params.profileId) + if (!profile) { + throw new BrowserError( + 'invalid_argument', + `Browser profile ${params.profileId} was not found` + ) + } + + // Why: short-circuit no-op switches so the renderer doesn't tear down and + // remount the webview when the tab is already on the requested profile. + const currentProfileId = browserManager.getSessionProfileIdForTab(browserPageId) ?? 'default' + if (currentProfileId === profile.id) { + return { + browserPageId, + profileId: profile.id, + profileLabel: profile.label + } + } + + const win = this.getAuthoritativeWindow() + const requestId = randomUUID() + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + ipcMain.removeListener('browser:tabSetProfileReply', handler) + reject(new Error('Tab profile update timed out')) + }, 10_000) + + const handler = ( + _event: Electron.IpcMainEvent, + reply: { requestId: string; error?: string } + ): void => { + if (reply.requestId !== requestId) { + return + } + clearTimeout(timer) + ipcMain.removeListener('browser:tabSetProfileReply', handler) + if (reply.error) { + reject(new Error(reply.error)) + } else { + resolve() + } + } + ipcMain.on('browser:tabSetProfileReply', handler) + win.webContents.send('browser:requestTabSetProfile', { + requestId, + browserPageId, + profileId: profile.id + }) + }) + + // Why: the renderer destroys the old webview and remounts on the new + // partition. Wait for the re-register so a follow-up tab list + // --show-profile reads the updated sessionProfileId from BrowserManager + // instead of stale data, and so subsequent CLI ops (snapshot, click, etc.) + // hit a guest that's already attached. + try { + await waitForTabRegistration(browserPageId) + } catch { + // Best-effort: re-register won't fire if the worktree is hidden. The + // store already reflects the new profile; downstream commands retry + // once the pane re-mounts. + } + + return { + browserPageId, + profileId: profile.id, + profileLabel: profile.label + } + } + + async browserTabProfileShow(params: { + page: string + worktree?: string + }): Promise { + const worktreeId = await this.resolveBrowserWorktreeId(params.worktree) + const tab = this.describeBrowserTab(params.page, worktreeId) + return { + browserPageId: tab.browserPageId, + worktreeId: tab.worktreeId ?? null, + profileId: tab.profileId ?? null, + profileLabel: tab.profileLabel ?? null + } + } + + async browserTabProfileClone( + params: { + profileId: string + } & BrowserCommandTargetParams + ): Promise { + const target = await this.resolveBrowserCommandTarget(params) + const sourceBrowserPageId = + target.browserPageId ?? this.requireAgentBrowserBridge().getActivePageId(target.worktreeId) + if (!sourceBrowserPageId) { + throw new BrowserError('browser_no_tab', 'No browser tab open in this worktree') + } + const sourceTab = this.describeBrowserTab(sourceBrowserPageId, target.worktreeId) + const profile = browserSessionRegistry.getProfile(params.profileId) + if (!profile) { + throw new BrowserError( + 'invalid_argument', + `Browser profile ${params.profileId} was not found` + ) + } + const created = await this.createBrowserTabInRenderer( + sourceTab.url, + sourceTab.worktreeId ?? target.worktreeId, + profile.id + ) + // Why: parity with browserTabCreate. Wait for the cloned tab's webview to + // register so the returned browserPageId is operable by the next CLI call. + try { + await waitForTabRegistration(created.browserPageId) + } catch { + // Best-effort: registration may not fire if the worktree is hidden. + } + return { + browserPageId: created.browserPageId, + sourceBrowserPageId, + profileId: profile.id, + profileLabel: profile.label + } + } + async browserProfileList(): Promise { return { profiles: browserSessionRegistry.listProfiles() } } @@ -5281,6 +5404,84 @@ export class OrcaRuntimeService { return { closed: true } } + private enrichBrowserTabInfo( + tab: BrowserTabListResult['tabs'][number] + ): BrowserTabListResult['tabs'][number] { + const rawProfileId = browserManager.getSessionProfileIdForTab(tab.browserPageId) + const profile = + browserSessionRegistry.getProfile(rawProfileId ?? 'default') ?? + browserSessionRegistry.getDefaultProfile() + return { + ...tab, + worktreeId: browserManager.getWorktreeIdForTab(tab.browserPageId) ?? null, + profileId: profile.id, + profileLabel: profile.label + } + } + + private describeBrowserTab( + browserPageId: string, + explicitWorktreeId?: string + ): BrowserTabListResult['tabs'][number] { + const worktreeId = explicitWorktreeId ?? browserManager.getWorktreeIdForTab(browserPageId) + const tab = this.requireAgentBrowserBridge() + .tabList(worktreeId) + .tabs.find((entry) => entry.browserPageId === browserPageId) + if (!tab) { + const scope = worktreeId ? ' in this worktree' : '' + throw new BrowserError( + 'browser_tab_not_found', + `Browser page ${browserPageId} was not found${scope}` + ) + } + return this.enrichBrowserTabInfo(tab) + } + + private async createBrowserTabInRenderer( + url: string, + worktreeId?: string, + profileId?: string + ): Promise<{ browserPageId: string }> { + const win = this.getAuthoritativeWindow() + const requestId = randomUUID() + + if (worktreeId) { + await this.ensureBrowserWorktreeActive(worktreeId) + } + + const browserPageId = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + ipcMain.removeListener('browser:tabCreateReply', handler) + reject(new Error('Tab creation timed out')) + }, 10_000) + + const handler = ( + _event: Electron.IpcMainEvent, + reply: { requestId: string; browserPageId?: string; error?: string } + ): void => { + if (reply.requestId !== requestId) { + return + } + clearTimeout(timer) + ipcMain.removeListener('browser:tabCreateReply', handler) + if (reply.error) { + reject(new Error(reply.error)) + } else { + resolve(reply.browserPageId!) + } + } + ipcMain.on('browser:tabCreateReply', handler) + win.webContents.send('browser:requestTabCreate', { + requestId, + url, + worktreeId, + sessionProfileId: profileId + }) + }) + + return { browserPageId } + } + private getAuthoritativeWindow(): BrowserWindow { if (this.authoritativeWindowId === null) { throw new Error('No renderer window available') diff --git a/src/main/runtime/rpc/methods/browser-core.ts b/src/main/runtime/rpc/methods/browser-core.ts index f68ea7971..b141c0b14 100644 --- a/src/main/runtime/rpc/methods/browser-core.ts +++ b/src/main/runtime/rpc/methods/browser-core.ts @@ -22,9 +22,13 @@ import { Scroll, Select, SelectorPath, + TabCurrent, + TabSetProfile, TabClose, TabCreate, TabList, + TabProfileClone, + TabShow, TabSwitch, Type, Upload, @@ -92,6 +96,16 @@ export const BROWSER_CORE_METHODS: RpcMethod[] = [ params: TabList, handler: async (params, { runtime }) => runtime.browserTabList(params) }), + defineMethod({ + name: 'browser.tabShow', + params: TabShow, + handler: async (params, { runtime }) => runtime.browserTabShow(params) + }), + defineMethod({ + name: 'browser.tabCurrent', + params: TabCurrent, + handler: async (params, { runtime }) => runtime.browserTabCurrent(params) + }), defineMethod({ name: 'browser.tabSwitch', params: TabSwitch, @@ -102,6 +116,21 @@ export const BROWSER_CORE_METHODS: RpcMethod[] = [ params: TabCreate, handler: async (params, { runtime }) => runtime.browserTabCreate(params) }), + defineMethod({ + name: 'browser.tabSetProfile', + params: TabSetProfile, + handler: async (params, { runtime }) => runtime.browserTabSetProfile(params) + }), + defineMethod({ + name: 'browser.tabProfileShow', + params: TabShow, + handler: async (params, { runtime }) => runtime.browserTabProfileShow(params) + }), + defineMethod({ + name: 'browser.tabProfileClone', + params: TabProfileClone, + handler: async (params, { runtime }) => runtime.browserTabProfileClone(params) + }), defineMethod({ name: 'browser.tabClose', params: TabClose, diff --git a/src/main/runtime/rpc/methods/browser-schemas.ts b/src/main/runtime/rpc/methods/browser-schemas.ts index 42693a19d..ab1190785 100644 --- a/src/main/runtime/rpc/methods/browser-schemas.ts +++ b/src/main/runtime/rpc/methods/browser-schemas.ts @@ -90,6 +90,16 @@ export const TabSwitch = BrowserTarget.extend({ export const TabCreate = z.object({ url: OptionalString, + worktree: OptionalString, + profileId: OptionalString +}) + +export const TabShow = z.object({ + page: requiredString('Missing required --page'), + worktree: OptionalString +}) + +export const TabCurrent = z.object({ worktree: OptionalString }) @@ -102,6 +112,31 @@ export const TabClose = z.object({ worktree: OptionalString }) +export const TabSetProfile = BrowserTarget.extend({ + profileId: requiredString('Missing required --profile') +}) + +export const TabProfileClone = BrowserTarget.extend({ + profileId: requiredString('Missing required --profile') +}) + +export const ProfileCreate = z.object({ + label: requiredString('Missing required --label'), + scope: z + .unknown() + .transform((value) => { + if (value === 'imported') { + return 'imported' + } + return 'isolated' + }) + .pipe(z.enum(['isolated', 'imported'])) +}) + +export const ProfileDelete = z.object({ + profileId: requiredString('Missing required --profile') +}) + export const Drag = BrowserTarget.extend({ from: requiredString('Missing required --from and --to element refs'), to: requiredString('Missing required --from and --to element refs') @@ -153,23 +188,6 @@ export const Exec = BrowserTarget.extend({ command: requiredString('Missing required --command') }) -export const ProfileCreate = z.object({ - label: requiredString('Missing required --label'), - scope: z - .unknown() - .transform((value) => { - if (value === 'imported') { - return 'imported' - } - return 'isolated' - }) - .pipe(z.enum(['isolated', 'imported'])) -}) - -export const ProfileDelete = z.object({ - profileId: requiredString('Missing required --profile') -}) - export const Get = BrowserTarget.extend({ what: requiredString('Missing required --what'), selector: OptionalString diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index a4214bf15..56b04fff3 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -154,6 +154,7 @@ export type BrowserApi = { browserPageId: string workspaceId: string worktreeId: string + sessionProfileId?: string | null webContentsId: number }) => Promise unregisterGuest: (args: { browserPageId: string }) => Promise @@ -942,9 +943,18 @@ export type PreloadApi = { onWorktreeHistoryNavigate: (callback: (direction: 'back' | 'forward') => void) => () => void onNewBrowserTab: (callback: () => void) => () => void onRequestTabCreate: ( - callback: (data: { requestId: string; url: string; worktreeId?: string }) => void + callback: (data: { + requestId: string + url: string + worktreeId?: string + sessionProfileId?: string + }) => void ) => () => void replyTabCreate: (reply: { requestId: string; browserPageId?: string; error?: string }) => void + onRequestTabSetProfile: ( + callback: (data: { requestId: string; browserPageId: string; profileId: string }) => void + ) => () => void + replyTabSetProfile: (reply: { requestId: string; error?: string }) => void onRequestTabClose: ( callback: (data: { requestId: string; tabId: string | null; worktreeId?: string }) => void ) => () => void diff --git a/src/preload/index.ts b/src/preload/index.ts index 8f91da197..4c63c877c 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -889,6 +889,7 @@ const api = { browserPageId: string workspaceId: string worktreeId: string + sessionProfileId?: string | null webContentsId: number }): Promise => ipcRenderer.invoke('browser:registerGuest', args), @@ -1504,11 +1505,16 @@ const api = { return () => ipcRenderer.removeListener('ui:newBrowserTab', listener) }, onRequestTabCreate: ( - callback: (data: { requestId: string; url: string; worktreeId?: string }) => void + callback: (data: { + requestId: string + url: string + worktreeId?: string + sessionProfileId?: string + }) => void ): (() => void) => { const listener = ( _event: Electron.IpcRendererEvent, - data: { requestId: string; url: string; worktreeId?: string } + data: { requestId: string; url: string; worktreeId?: string; sessionProfileId?: string } ) => callback(data) ipcRenderer.on('browser:requestTabCreate', listener) return () => ipcRenderer.removeListener('browser:requestTabCreate', listener) @@ -1520,6 +1526,19 @@ const api = { }): void => { ipcRenderer.send('browser:tabCreateReply', reply) }, + onRequestTabSetProfile: ( + callback: (data: { requestId: string; browserPageId: string; profileId: string }) => void + ): (() => void) => { + const listener = ( + _event: Electron.IpcRendererEvent, + data: { requestId: string; browserPageId: string; profileId: string } + ) => callback(data) + ipcRenderer.on('browser:requestTabSetProfile', listener) + return () => ipcRenderer.removeListener('browser:requestTabSetProfile', listener) + }, + replyTabSetProfile: (reply: { requestId: string; error?: string }): void => { + ipcRenderer.send('browser:tabSetProfileReply', reply) + }, onRequestTabClose: ( callback: (data: { requestId: string; tabId: string | null; worktreeId?: string }) => void ): (() => void) => { diff --git a/src/renderer/src/components/browser-pane/BrowserPane.tsx b/src/renderer/src/components/browser-pane/BrowserPane.tsx index a421e7273..113b580b1 100644 --- a/src/renderer/src/components/browser-pane/BrowserPane.tsx +++ b/src/renderer/src/components/browser-pane/BrowserPane.tsx @@ -953,6 +953,7 @@ function BrowserPagePane({ browserPageId: browserTab.id, workspaceId, worktreeId, + sessionProfileId, webContentsId }) } diff --git a/src/renderer/src/components/browser-pane/webview-registry.ts b/src/renderer/src/components/browser-pane/webview-registry.ts index e59c0c6a0..a3238f627 100644 --- a/src/renderer/src/components/browser-pane/webview-registry.ts +++ b/src/renderer/src/components/browser-pane/webview-registry.ts @@ -36,7 +36,11 @@ export function setWebviewsDragPassthrough(passthrough: boolean): void { const DRAG_LISTENER_KEY = '__orcaBrowserPaneDragListeners' -if (typeof window !== 'undefined') { +// Why: vitest 'node' env stubs `window` as a plain object via vi.stubGlobal, +// so `typeof window !== 'undefined'` is true but addEventListener is missing. +// Gate on the function we actually call so importing this module from a hook +// test (which transitively pulls us in) does not throw at module load. +if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') { type DragListenerRegistry = { dragstart: () => void dragend: () => void diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index 75d2817f6..748098a39 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -169,6 +169,8 @@ describe('useIpcEvents updater integration', () => { replyTabCreate: () => {}, onRequestTabClose: () => () => {}, replyTabClose: () => {}, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, @@ -366,6 +368,8 @@ describe('useIpcEvents updater integration', () => { replyTabCreate: () => {}, onRequestTabClose: () => () => {}, replyTabClose: () => {}, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, @@ -562,6 +566,8 @@ describe('useIpcEvents updater integration', () => { replyTabCreate: () => {}, onRequestTabClose: () => () => {}, replyTabClose: vi.fn(), + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, @@ -769,6 +775,8 @@ describe('useIpcEvents browser tab close routing', () => { return () => {} }, replyTabClose, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, @@ -961,6 +969,8 @@ describe('useIpcEvents browser tab close routing', () => { return () => {} }, replyTabClose, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, @@ -1148,6 +1158,8 @@ describe('useIpcEvents browser tab close routing', () => { return () => {} }, replyTabClose, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, @@ -1344,6 +1356,8 @@ describe('useIpcEvents shortcut hint clearing', () => { replyTabCreate: () => {}, onRequestTabClose: () => () => {}, replyTabClose: () => {}, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, @@ -1547,6 +1561,8 @@ describe('useIpcEvents CLI-created worktree activation', () => { replyTabCreate: () => {}, onRequestTabClose: () => () => {}, replyTabClose: () => {}, + onRequestTabSetProfile: () => () => {}, + replyTabSetProfile: () => {}, onNewTerminalTab: () => () => {}, onCloseActiveTab: () => () => {}, onSwitchTab: () => () => {}, diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 31e3bb5af..48b9832ba 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -25,6 +25,7 @@ import { isGitRepoKind } from '../../../shared/repo-kind' import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' import { setFitOverride, hydrateOverrides } from '@/lib/pane-manager/mobile-fit-overrides' import { setDriverForPty } from '@/lib/pane-manager/mobile-driver-state' +import { destroyPersistentWebview } from '@/components/browser-pane/webview-registry' export { resolveZoomTarget } from './resolve-zoom-target' @@ -442,7 +443,8 @@ export function useIpcEvents(): void { const workspace = store.createBrowserTab(worktreeId, data.url, { title: data.url, - targetGroupId: activeBrowserUnifiedTab?.groupId + targetGroupId: activeBrowserUnifiedTab?.groupId, + sessionProfileId: data.sessionProfileId }) // Why: registerGuest fires with the page ID (not workspace ID) as // browserPageId. Return the page ID so waitForTabRegistration can @@ -459,6 +461,38 @@ export function useIpcEvents(): void { }) ) + unsubs.push( + window.api.ui.onRequestTabSetProfile((data) => { + try { + const store = useAppStore.getState() + const owningWorkspace = Object.values(store.browserTabsByWorktree) + .flat() + .find((workspace) => { + if (workspace.id === data.browserPageId) { + return true + } + const pages = store.browserPagesByWorkspace[workspace.id] ?? [] + return pages.some((page) => page.id === data.browserPageId) + }) + if (!owningWorkspace) { + window.api.ui.replyTabSetProfile({ + requestId: data.requestId, + error: `Browser tab ${data.browserPageId} not found` + }) + return + } + destroyPersistentWebview(data.browserPageId) + store.switchBrowserTabProfile(owningWorkspace.id, data.profileId) + window.api.ui.replyTabSetProfile({ requestId: data.requestId }) + } catch (err) { + window.api.ui.replyTabSetProfile({ + requestId: data.requestId, + error: err instanceof Error ? err.message : 'Tab profile update failed' + }) + } + }) + ) + unsubs.push( window.api.ui.onRequestTabClose((data) => { try { diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index 9d222b78b..be8adc809 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -259,6 +259,9 @@ export type BrowserTabInfo = { url: string title: string active: boolean + worktreeId?: string | null + profileId?: string | null + profileLabel?: string | null } export type BrowserTabListResult = { @@ -270,6 +273,34 @@ export type BrowserTabSwitchResult = { browserPageId: string } +export type BrowserTabSetProfileResult = { + browserPageId: string + profileId: string | null + profileLabel: string | null +} + +export type BrowserTabShowResult = { + tab: BrowserTabInfo +} + +export type BrowserTabCurrentResult = { + tab: BrowserTabInfo +} + +export type BrowserTabProfileShowResult = { + browserPageId: string + worktreeId: string | null + profileId: string | null + profileLabel: string | null +} + +export type BrowserTabProfileCloneResult = { + browserPageId: string + sourceBrowserPageId: string + profileId: string | null + profileLabel: string | null +} + export type BrowserProfileListResult = { profiles: BrowserSessionProfile[] }