diff --git a/src/main/browser/sessions/profiles/browser-session-registry.test.ts b/src/main/browser/sessions/profiles/browser-session-registry.test.ts index 23c38b85923..eabc72c18b7 100644 --- a/src/main/browser/sessions/profiles/browser-session-registry.test.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry.test.ts @@ -64,11 +64,6 @@ import { deleteManagedBrowserProfile, ensureManagedBrowserProfile } from './browser-managed-session-profiles' -import { - configureBrowserSitePermissionStore, - listBrowserSitePermissions, - setBrowserSitePermissionDecisions -} from '../../site-settings/permissions/browser-site-permission-store' import { setBrowserNetworkProxySettingsResolver } from '../proxy/browser-session-proxy' import { handleElectronProxyLogin } from '../../../network/electron-proxy-credentials' import { applyProxySettingsToSession } from '../../../network/proxy-settings' @@ -208,19 +203,6 @@ describe('BrowserSessionRegistry', () => { ).rejects.toThrow('retired') }) - it('deletes a non-default profile and its remembered site answers', async () => { - configureBrowserSitePermissionStore(mkdtempSync(join(tmpdir(), 'orca-site-permissions-'))) - const profile = await browserSessionRegistry.createProfile('isolated', 'Delete Test') - expect(profile).not.toBeNull() - expect(browserSessionRegistry.isAllowedPartition(profile!.partition)).toBe(true) - setBrowserSitePermissionDecisions(profile!.id, 'https://example.com', ['camera'], 'allow') - const deleted = await browserSessionRegistry.deleteProfile(profile!.id) - expect(deleted).toBe(true) - expect(browserSessionRegistry.isAllowedPartition(profile!.partition)).toBe(false) - expect(browserSessionRegistry.getProfile(profile!.id)).toBeNull() - expect(listBrowserSitePermissions(profile!.id)).toEqual([]) - }) - // Electron Sessions outlive deleted profiles; their header hooks must be retired. it('creates one managed profile per owner and a fresh one after its owner is removed', async () => { @@ -245,32 +227,4 @@ describe('BrowserSessionRegistry', () => { const recreated = await ensureManagedBrowserProfile(owner, 'Workspace: feature') expect(recreated?.partition).not.toBe(first.partition) }) - - it('announces each profile change after the list reflects it', async () => { - const seen: string[][] = [] - browserSessionRegistry.onProfilesChanged = () => - seen.push(browserSessionRegistry.listProfiles().map((profile) => profile.label)) - try { - const made = await browserSessionRegistry.createProfile('isolated', 'Made by CLI') - const managed = await ensureManagedBrowserProfile({ kind: 'repo', id: 'announce' }, 'Repo') - if (!made || !managed) { - throw new Error('Expected created profiles') - } - browserSessionRegistry.updateProfileSource(made.id, { - browserFamily: 'manual', - importedAt: 1 - }) - await browserSessionRegistry.deleteProfile(made.id) - await browserSessionRegistry.deleteProfile('default') - await browserSessionRegistry.createProfile('default', 'Refused') - - expect(seen).toHaveLength(4) - expect(seen[0]).toContain('Made by CLI') - expect(seen[1]).toContain('Repo') - expect(seen[2]).toContain('Made by CLI') - expect(seen[3]).not.toContain('Made by CLI') - } finally { - browserSessionRegistry.onProfilesChanged = null - } - }) }) diff --git a/src/main/browser/sessions/proxy/browser-session-proxy.test.ts b/src/main/browser/sessions/proxy/browser-session-proxy.test.ts index 7f5a406d072..ff182459a9d 100644 --- a/src/main/browser/sessions/proxy/browser-session-proxy.test.ts +++ b/src/main/browser/sessions/proxy/browser-session-proxy.test.ts @@ -28,33 +28,11 @@ vi.mock('electron', () => ({ import { applyBrowserSessionProxies, - awaitBrowserSessionProxies, applyProxyToBrowserSession, invalidateBrowserSessionProxyApplication, setBrowserNetworkProxySettingsResolver } from './browser-session-proxy' -import { - applyProxySettingsToSession, - releaseProxySessionApplication -} from '../../../network/proxy-settings' -import type { NetworkProxySettings } from '../../../../shared/network-proxy' - -const PROFILES = [ - { - id: 'default', - scope: 'default' as const, - partition: 'persist:orca-browser', - label: 'Default', - source: null - }, - { - id: 'iso', - scope: 'isolated' as const, - partition: 'persist:orca-browser-session-iso', - label: 'Isolated', - source: null - } -] +import { releaseProxySessionApplication } from '../../../network/proxy-settings' describe('browser session proxy', () => { beforeEach(() => { @@ -112,129 +90,4 @@ describe('browser session proxy', () => { [{ mode: 'system' }] ]) }) - - describe('startup readiness', () => { - beforeEach(() => { - for (const key of [ - 'http_proxy', - 'https_proxy', - 'all_proxy', - 'HTTP_PROXY', - 'HTTPS_PROXY', - 'ALL_PROXY' - ]) { - vi.stubEnv(key, '') - } - setBrowserNetworkProxySettingsResolver(() => ({})) - }) - - afterEach(() => vi.unstubAllEnvs()) - - it('awaits installed policies without reapplying them and keeps later system probes fresh', async () => { - const sessions = PROFILES.map((profile) => fromPartition(profile.partition)) - const finishResolutions: (() => void)[] = [] - for (const sess of sessions) { - sess.resolveProxy.mockImplementationOnce( - () => - new Promise((resolve) => { - finishResolutions.push(() => resolve('DIRECT')) - }) - ) - } - const installations = sessions.map((sess) => applyProxySettingsToSession(sess, {})) - let settled = false - const startup = awaitBrowserSessionProxies(PROFILES).then(() => (settled = true)) - - await vi.waitFor(() => expect(finishResolutions).toHaveLength(PROFILES.length)) - expect(settled).toBe(false) - for (const finish of finishResolutions) { - finish() - } - await Promise.all([...installations, startup]) - await awaitBrowserSessionProxies(PROFILES) - - for (const sess of sessions) { - expect(sess.resolveProxy).toHaveBeenCalledOnce() - expect(sess.setProxy).not.toHaveBeenCalled() - sess.resolveProxy.mockResolvedValue('PROXY changed-system.example:8080') - } - await applyBrowserSessionProxies(PROFILES, {}) - for (const sess of sessions) { - expect(sess.resolveProxy).toHaveBeenCalledTimes(2) - } - }) - - it('awaits every installation and preserves failed-partition warnings and retry budget', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const failed = fromPartition('persist:orca-browser') - failed.resolveProxy.mockRejectedValue(new Error('native proxy failure')) - await expect(applyProxySettingsToSession(failed, {})).rejects.toThrow('native proxy failure') - const healthy = fromPartition('persist:orca-browser-session-iso') - let finishHealthy: (() => void) | undefined - healthy.resolveProxy.mockImplementationOnce( - () => new Promise((resolve) => (finishHealthy = () => resolve('DIRECT'))) - ) - const installation = applyProxySettingsToSession(healthy, {}) - let settled = false - const startup = awaitBrowserSessionProxies(PROFILES).finally(() => (settled = true)) - const failure = expect(startup).rejects.toThrow('persist:orca-browser') - - await vi.waitFor(() => expect(failed.resolveProxy).toHaveBeenCalledTimes(6)) - expect(settled).toBe(false) - finishHealthy?.() - await Promise.all([installation, failure]) - - expect(healthy.resolveProxy).toHaveBeenCalledOnce() - expect(warn).toHaveBeenCalledExactlyOnceWith( - '[proxy] Failed to apply proxy to browser partition', - 'persist:orca-browser' - ) - }) - - it.each([false, true])( - 'awaits the newest settings write when the initial policy fails=%s', - async (initialFails) => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const profiles = PROFILES.slice(0, 1) - const sess = fromPartition('persist:orca-browser') - let settings: NetworkProxySettings = {} - setBrowserNetworkProxySettingsResolver(() => settings) - let finishInitial: (() => void) | undefined - sess.resolveProxy.mockImplementationOnce( - () => - new Promise((resolve, reject) => { - finishInitial = () => - initialFails ? reject(new Error('native proxy failure')) : resolve('DIRECT') - }) - ) - if (initialFails) { - sess.resolveProxy.mockRejectedValueOnce(new Error('native proxy failure')) - sess.resolveProxy.mockRejectedValueOnce(new Error('native proxy failure')) - } - let finishWrite: (() => void) | undefined - sess.setProxy.mockImplementationOnce( - () => new Promise((resolve) => (finishWrite = resolve)) - ) - const installation = applyProxySettingsToSession(sess, {}).catch((error: unknown) => error) - let settled = false - const startup = awaitBrowserSessionProxies(profiles).then(() => (settled = true)) - await vi.waitFor(() => expect(sess.resolveProxy).toHaveBeenCalledOnce()) - settings = { httpProxyUrl: 'http://fresh.example:8080' } - const sweep = applyBrowserSessionProxies(profiles, settings) - finishInitial?.() - - await vi.waitFor(() => expect(sess.setProxy).toHaveBeenCalledOnce()) - expect(settled).toBe(false) - finishWrite?.() - await Promise.all([installation, startup, sweep]) - - expect(sess.resolveProxy).toHaveBeenCalledTimes(initialFails ? 3 : 1) - expect(sess.setProxy).toHaveBeenCalledExactlyOnceWith({ - mode: 'fixed_servers', - proxyRules: 'http://fresh.example:8080' - }) - expect(warn).not.toHaveBeenCalled() - } - ) - }) }) diff --git a/src/main/browser/site-settings/display/browser-site-display-controller.test.ts b/src/main/browser/site-settings/display/browser-site-display-controller.test.ts index 9f304231229..8ef505bf2d9 100644 --- a/src/main/browser/site-settings/display/browser-site-display-controller.test.ts +++ b/src/main/browser/site-settings/display/browser-site-display-controller.test.ts @@ -178,9 +178,7 @@ describe('BrowserSiteDisplayController color scheme', () => { it.each([ { order: 'read-first', profileId: 'work', colorScheme: 'light', saved: 'dark' }, - { order: 'registration-first', profileId: 'work', colorScheme: 'light', saved: 'dark' }, - { order: 'read-first', profileId: 'default', colorScheme: 'dark', saved: 'light' }, - { order: 'registration-first', profileId: 'default', colorScheme: 'dark', saved: 'light' } + { order: 'registration-first', profileId: 'work', colorScheme: 'light', saved: 'dark' } ] as const)( 'keeps actual $profileId precedence across $order, reload and debugger loss', ({ order, profileId, colorScheme, saved }) => { diff --git a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts index d56582aeb35..7cde14c097e 100644 --- a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts @@ -2,7 +2,6 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { CONNECTOR_REPLY_UNAVAILABLE } from '../../../../shared/rpc-contract/connector-params' import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' import '../../../../shared/ssh-remote-cli-control' import { OrcaRuntimeService } from '../../../runtime/orca-runtime' @@ -12,11 +11,7 @@ import '../../../runtime/orchestration/db/messages/mailbox-routing-page' import '../../../runtime/orchestration/db/dispatch-row-writer' import '../../../runtime/orchestration/db/attempt-outcome-projection' import { LEGACY_RELAY_CLI_UNVERIFIED } from './legacy-relay-cli-caller' -import { - createLegacyRelayCliServer, - LEGACY_RELAY_CLI_CONTROL_OFF, - LEGACY_RELAY_CLI_UNSUPPORTED -} from './legacy-relay-cli-server' +import { createLegacyRelayCliServer, LEGACY_RELAY_CLI_CONTROL_OFF } from './legacy-relay-cli-server' import type { LegacyRelayLivePane } from '../bridge/legacy-relay-bridge-leases' const TARGET = 'target-1' @@ -143,16 +138,6 @@ describe('the relay-era orca CLI on the desktop runtime', () => { expect(db.getTask(ids.taskId)?.status).toBe('dispatched') }) - it('refuses commands outside orchestration', async () => { - await expect(run(['worktree', 'list'])).rejects.toThrow(LEGACY_RELAY_CLI_UNSUPPORTED) - await expect(run(['terminal', 'send', '--terminal', COORDINATOR])).rejects.toThrow( - LEGACY_RELAY_CLI_UNSUPPORTED - ) - await expect(run(['connector', 'reply', '--text', 'done'])).rejects.toThrow( - CONNECTOR_REPLY_UNAVAILABLE - ) - }) - it.each([ ['a pane the bridge does not run', () => panes.clear(), ENV], [ diff --git a/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts index ab23d5622cc..4a24bdf0326 100644 --- a/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts @@ -82,11 +82,6 @@ describe('the connect-time relay census on a Windows host', () => { countRelayPtysOverBridge.mockReset().mockResolvedValue(0) }) - it('finds none on a host that never ran a relay', async () => { - listing = '' - await expect(census()).resolves.toEqual({ verdict: 'none', count: 0 }) - }) - // Two desktops, two target ids, one Windows account: B's live shell must block A's conversion. it("asks another desktop's relay on this account, with that relay's own credential", async () => { const [bPrimary] = pipesOf('desktop-b') @@ -105,22 +100,6 @@ describe('the connect-time relay census on a Windows host', () => { ) }) - it('maps a pipe through its active-pipe marker when its credential is gone', async () => { - const [, bFallback] = pipesOf('desktop-b') - inventory = { - pipes: [bare(bFallback)], - dirs: { - [VERSION]: { - credentials: [], - markers: { [`.windows-active-pipe-${sockOf('desktop-b')}`]: bFallback } - } - } - } - countRelayPtysOverBridge.mockResolvedValue(2) - - await expect(census()).resolves.toEqual({ verdict: 'live', count: 1 }) - }) - it("is unverifiable for a pipe no directory here accounts for, unless it is another account's", async () => { inventory = { pipes: ['orca-relay-0123456789abcdef0123', 'orca-relay-fedcba9876543210fedc'], @@ -136,27 +115,6 @@ describe('the connect-time relay census on a Windows host', () => { await expect(census()).resolves.toEqual({ verdict: 'idle', count: 0 }) }) - it.each([ - [ - 'the inventory could not run', - () => - execCommand.mockImplementation(async (_conn: unknown, command: string) => { - if (command === 'LIST') { - return listing - } - throw new Error('channel closed') - }) - ], - ['the pipe listing failed', () => (inventory = { pipes: null, dirs: {} })], - [ - 'a version directory could not be read', - () => (inventory = { pipes: [], dirs: { [VERSION]: null } }) - ] - ])('is unverifiable when %s', async (_label, arrange) => { - arrange() - await expect(census()).resolves.toMatchObject({ verdict: 'unverifiable' }) - }) - it('never converts under an owned pipe it cannot ask', async () => { const [aPrimary] = pipesOf('desktop-a') inventory = { pipes: [bare(aPrimary)], dirs: { [VERSION]: { credentials: [], markers: {} } } } @@ -164,13 +122,4 @@ describe('the connect-time relay census on a Windows host', () => { await expect(census()).resolves.toEqual({ verdict: 'unverifiable', count: 1 }) }) - - it('reads relays that answer with no PTYs, or no relay pipes at all, as idle', async () => { - const [aPrimary] = pipesOf('desktop-a') - inventory = { pipes: [bare(aPrimary)], dirs: { [VERSION]: { credentials: [], markers: {} } } } - await expect(census()).resolves.toEqual({ verdict: 'idle', count: 0 }) - - inventory = { pipes: [], dirs: { [VERSION]: { credentials: [], markers: {} } } } - await expect(census()).resolves.toEqual({ verdict: 'idle', count: 0 }) - }) }) diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts index 8392f41cba9..0c7395df839 100644 --- a/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts @@ -146,19 +146,6 @@ describe('system SSH forward process', () => { expect(spawnMock).not.toHaveBeenCalled() }) - it('rejects startup when ssh exits early with stderr', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - const socket = createFakeSocket() - connectMock.mockReturnValue(socket) - - const pending = waitForSystemSshForwardStartup(child as never, 3000) - child.stderr.emit('data', Buffer.from('bind: Address already in use\n')) - child.emit('exit', 255) - - await expect(pending).rejects.toThrow('bind: Address already in use') - }) - it("rejects startup and stops ssh when it cannot listen on this forward's own port", async () => { const child = createFakeProcess() spawnMock.mockReturnValue(child) @@ -201,17 +188,6 @@ describe('system SSH forward process', () => { expect(child.kill).not.toHaveBeenCalled() }) - it('rejects startup when the ssh process emits an error', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - connectMock.mockReturnValue(createFakeSocket()) - - const pending = waitForSystemSshForwardStartup(child as never, 3000) - child.emit('error', new Error('spawn failed')) - - await expect(pending).rejects.toThrow('spawn failed') - }) - it('rejects when no listener appears within the listener timeout', async () => { vi.useFakeTimers() const child = createFakeProcess() diff --git a/src/main/ssh/targets/ssh-connection-store.test.ts b/src/main/ssh/targets/ssh-connection-store.test.ts index e2212b0bb6c..72704ff7c61 100644 --- a/src/main/ssh/targets/ssh-connection-store.test.ts +++ b/src/main/ssh/targets/ssh-connection-store.test.ts @@ -41,72 +41,6 @@ describe('SshConnectionStore', () => { } } - it('adopts a legacy unsourced target into config-sync', async () => { - mockStore.addSshTarget({ - id: 'ssh-legacy', - label: 'cluster', - configHost: 'cluster', - host: '10.0.0.5', - port: 2200, - username: 'dev' - // no source — predates the field - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'cluster' }]) - sshConfigHostsToTargetsMock.mockReturnValue([ - candidate({ configHost: 'cluster', host: '10.0.0.5', port: 2222, username: 'dev' }) - ]) - - const result = (await sshStore.importFromSshConfig()).targets - - expect(mockStore.updateSshTarget).toHaveBeenCalledWith( - 'ssh-legacy', - expect.objectContaining({ port: 2222, source: 'ssh-config' }) - ) - expect(result[0].source).toBe('ssh-config') - }) - - it('does not overwrite a legacy unsourced manual target with the same alias', async () => { - mockStore.addSshTarget({ - id: 'ssh-legacy-manual', - label: 'cluster', - configHost: 'cluster', - host: 'cluster', - port: 2200, - username: 'me' - // no source — predates the field, but does not look like a config import - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'cluster' }]) - sshConfigHostsToTargetsMock.mockReturnValue([ - candidate({ configHost: 'cluster', host: '10.0.0.5', port: 2222, username: 'dev' }) - ]) - - const result = (await sshStore.importFromSshConfig()).targets - - expect(mockStore.updateSshTarget).not.toHaveBeenCalled() - expect(mockStore.addSshTarget).toHaveBeenCalledTimes(1) - expect(result).toEqual([]) - }) - - // Import alias ownership must use the picker's case-insensitive Host matching. - it('treats a case-only alias variant as owned by the existing manual target', async () => { - mockStore.addSshTarget({ - id: 'ssh-m', - label: 'Prod', - configHost: 'Prod', - host: 'manual.example.com', - port: 22, - username: 'me', - source: 'manual' - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'prod' }]) - sshConfigHostsToTargetsMock.mockReturnValue([candidate({ configHost: 'prod' })]) - - const result = (await sshStore.importFromSshConfig()).targets - - expect(mockStore.addSshTarget).toHaveBeenCalledTimes(1) - expect(result).toEqual([]) - }) - it('keeps a case-only alias variant suppressed after the host was deleted', async () => { const added = sshStore.addTarget({ label: 'Prod', @@ -172,27 +106,4 @@ describe('SshConnectionStore', () => { expect(result).toHaveLength(1) }) }) - - describe('re-adoption of orphaned workspaces', () => { - it('does not re-adopt when the re-added host identity differs', () => { - mockStore.addRemovedSshTargetTombstone({ - oldTargetId: 'ssh-old', - host: 'other.example.com', - port: 22, - username: 'root', - label: 'Other', - removedAt: 1 - }) - - sshStore.addTarget({ - label: 'Dev', - host: 'dev.example.com', - port: 22, - username: 'tim' - }) - - expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled() - expect(sshStore.lastRepoReadoptions).toEqual([]) - }) - }) }) diff --git a/src/renderer/src/components/terminal-cold-activation-unbound-tabs.test.ts b/src/renderer/src/components/terminal-cold-activation-unbound-tabs.test.ts deleted file mode 100644 index e2f4fe7a5e4..00000000000 --- a/src/renderer/src/components/terminal-cold-activation-unbound-tabs.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { useAppStore } from '../store' -import { applyTerminalColdActivation } from './terminal-cold-activation' -import type { TerminalParkingFoundation } from './use-terminal-parking-foundation' -import type { TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types' -import { - isActivationAdmissionEligible, - pickNextActivationDeferredTabId -} from './terminal/activation-deferred-tab-admission' -import { isUnboundRestoredTerminalTab } from './terminal/unbound-restored-terminal-tab' - -const WORKTREE = 'repo::/wt' - -function tab(id: string, extra: Partial = {}): TerminalTab { - return { - id, - ptyId: null, - worktreeId: WORKTREE, - title: id, - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 0, - ...extra - } -} - -function controllerFor( - tabs: TerminalTab[], - overrides: Partial> = {} -): TerminalParkingFoundation { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: cold activation reads only the fields listed here; the rest of the hook controller is React state it never touches. - return { - activationDeferralPlanRevisionRef: { current: 0 }, - activationDeferredMountTabIdsByWorktreeRef: { current: new Map() }, - activeGroupIdByWorktree: {}, - activeTabId: tabs[0]?.id ?? null, - activeTabIdByWorktree: {}, - activeWorktreeDeferralHostId: 'local', - activityTerminalPortals: [], - backgroundMountTabIdsByWorktreeRef: { current: new Map() }, - groupsByWorktree: {}, - hydrationSucceeded: true, - lastActivationWorktreeIdRef: { current: null }, - layoutByWorktree: {}, - mountedWorktreeIdsRef: { current: new Set() }, - pairedRuntimeParkingEnvironmentIds: new Set(), - pendingStartupByTabId: {}, - renderedActiveWorktreeId: WORKTREE, - startupTerminalTabHoldRef: { current: null }, - startupWorktreeRefreshCompleted: true, - tabsByWorktree: { [WORKTREE]: tabs }, - terminalParkingEnabled: false, - terminalTitleSnapshotAuthorityEnabled: false, - workspaceSessionReady: true, - workspaceSurfaceIds: [WORKTREE], - workspaceSurfaceIdSet: new Set([WORKTREE]), - ...overrides - } as unknown as TerminalParkingFoundation -} - -function deadAgentTabs(count: number): TerminalTab[] { - return Array.from({ length: count }, (_, index) => - tab(`tab-${index}`, { launchAgent: 'claude', restoredFromSession: true }) - ) -} - -function mountableTabIds(controller: TerminalParkingFoundation): string[] { - const allowed = controller.backgroundMountTabIdsByWorktreeRef.current.get(WORKTREE) - const tabs = controller.tabsByWorktree[WORKTREE] ?? [] - return tabs.filter((t) => !allowed || allowed.has(t.id)).map((t) => t.id) -} - -describe('cold activation of a worktree with unbound saved tabs (#39166)', () => { - beforeEach(() => { - useAppStore.setState({ - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {}, - pendingStartupByTabId: {}, - unifiedTabsByWorktree: {} - }) - }) - - it('mounts only the visible tab when many saved agent tabs have no PTY', () => { - const tabs = deadAgentTabs(97) - useAppStore.setState({ tabsByWorktree: { [WORKTREE]: tabs } }) - const controller = controllerFor(tabs) - - applyTerminalColdActivation(controller) - - expect(mountableTabIds(controller)).toEqual(['tab-0']) - const deferred = controller.activationDeferredMountTabIdsByWorktreeRef.current.get(WORKTREE) - expect(deferred?.size).toBe(96) - // Over the cap, the idle pass admits none; each waits until the user opens it. - expect(isActivationAdmissionEligible(deferred?.size ?? 0)).toBe(false) - }) - - it('opening a held tab mounts it without releasing the others', () => { - const tabs = deadAgentTabs(10) - useAppStore.setState({ tabsByWorktree: { [WORKTREE]: tabs } }) - const controller = controllerFor(tabs) - applyTerminalColdActivation(controller) - - const clicked = controllerFor(tabs, { - activeTabId: 'tab-7', - backgroundMountTabIdsByWorktreeRef: controller.backgroundMountTabIdsByWorktreeRef, - activationDeferredMountTabIdsByWorktreeRef: - controller.activationDeferredMountTabIdsByWorktreeRef, - lastActivationWorktreeIdRef: controller.lastActivationWorktreeIdRef, - mountedWorktreeIdsRef: controller.mountedWorktreeIdsRef - }) - applyTerminalColdActivation(clicked) - - expect(mountableTabIds(clicked)).toEqual(['tab-0', 'tab-7']) - }) - - it('keeps the capped idle warm-up for a few unbound tabs', () => { - const tabs = deadAgentTabs(3) - useAppStore.setState({ tabsByWorktree: { [WORKTREE]: tabs } }) - const controller = controllerFor(tabs) - applyTerminalColdActivation(controller) - - const deferred = controller.activationDeferredMountTabIdsByWorktreeRef.current.get(WORKTREE) - expect(isActivationAdmissionEligible(deferred?.size ?? 0)).toBe(true) - expect( - pickNextActivationDeferredTabId( - tabs.map((t) => t.id), - deferred - ) - ).toBe('tab-1') - }) - - it('mounts a held tab once its PTY binds', () => { - const tabs = deadAgentTabs(6) - useAppStore.setState({ tabsByWorktree: { [WORKTREE]: tabs } }) - const controller = controllerFor(tabs) - applyTerminalColdActivation(controller) - - const bound = tabs.map((t) => - t.id === 'tab-3' ? { ...t, ptyId: 'pty-3', restoredFromSession: undefined } : t - ) - useAppStore.setState({ tabsByWorktree: { [WORKTREE]: bound } }) - const next = controllerFor(bound, { - backgroundMountTabIdsByWorktreeRef: controller.backgroundMountTabIdsByWorktreeRef, - activationDeferredMountTabIdsByWorktreeRef: - controller.activationDeferredMountTabIdsByWorktreeRef, - lastActivationWorktreeIdRef: controller.lastActivationWorktreeIdRef, - mountedWorktreeIdsRef: controller.mountedWorktreeIdsRef - }) - applyTerminalColdActivation(next) - - expect(mountableTabIds(next)).toEqual(['tab-0', 'tab-3']) - }) - - it('leaves worktrees without unbound saved tabs fully mounted', () => { - const tabs = [tab('a'), tab('b'), tab('c', { ptyId: 'pty-c', launchAgent: 'claude' })] - useAppStore.setState({ tabsByWorktree: { [WORKTREE]: tabs } }) - const controller = controllerFor(tabs) - - applyTerminalColdActivation(controller) - - expect(controller.backgroundMountTabIdsByWorktreeRef.current.has(WORKTREE)).toBe(false) - expect(mountableTabIds(controller)).toEqual(['a', 'b', 'c']) - }) -}) - -describe('isUnboundRestoredTerminalTab', () => { - const empty = { ptyIdsByTabId: {}, terminalLayoutsByTabId: {}, pendingStartupByTabId: {} } - - it('holds saved shells and agent tabs that have no PTY anywhere', () => { - expect(isUnboundRestoredTerminalTab(tab('a', { restoredFromSession: true }), empty)).toBe(true) - expect(isUnboundRestoredTerminalTab(tab('b', { launchAgent: 'codex' }), empty)).toBe(true) - }) - - it('never holds a tab that is new this session, starting, or bound to a PTY', () => { - expect(isUnboundRestoredTerminalTab(tab('fresh'), empty)).toBe(false) - expect( - isUnboundRestoredTerminalTab(tab('queued', { launchAgent: 'claude' }), { - ...empty, - pendingStartupByTabId: { queued: { command: 'claude' } } - }) - ).toBe(false) - expect( - isUnboundRestoredTerminalTab( - tab('launch', { launchAgent: 'claude', agentLaunchPane: { leafId: 'leaf' } }), - empty - ) - ).toBe(false) - expect( - isUnboundRestoredTerminalTab(tab('live', { restoredFromSession: true }), { - ...empty, - ptyIdsByTabId: { live: ['pty-1'] } - }) - ).toBe(false) - expect( - isUnboundRestoredTerminalTab(tab('saved-leaf', { restoredFromSession: true }), { - ...empty, - terminalLayoutsByTabId: { - 'saved-leaf': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { l: 'pty-9' } - } - } - }) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode-2031-subscriptions.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode-2031-subscriptions.spec.ts index 00f51c81ff3..e00f298909f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode-2031-subscriptions.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode-2031-subscriptions.spec.ts @@ -104,19 +104,6 @@ export function registerPtyConnectionMode2031SubscriptionsTests(): void { const replies = (transport: { sendInput: { mock: { calls: unknown[][] } } }): unknown[] => transport.sendInput.mock.calls.flat().filter((arg) => String(arg).includes('997')) - it('registers a chunk that ends subscribed, then retires it when the next withdraws', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - // Two separate PTY chunks. xterm would parse both in one batch and see only the net result. - emit('\x1b[?2031h') - expect(deps.paneMode2031Ref.current.get(1)).toBe(true) - expect(deps.paneLastThemeModeRef.current.get(1)).toBe('light') - emit('\x1b[?2031l') - expect(deps.paneMode2031Ref.current.get(1)).toBeUndefined() - expect(deps.paneLastThemeModeRef.current.get(1)).toBeUndefined() - expect(replies(transport)).toEqual([]) - dispose() - }) - it('catches a subscribed pane up once per mode change across repeated reconnects', async () => { const { transport, emit, reconnect, dispose } = await connectVisiblePane() emit('\x1b[?2031h') @@ -166,201 +153,6 @@ export function registerPtyConnectionMode2031SubscriptionsTests(): void { expect(replies(transport)).toEqual(['\x1b[?997;1n', '\x1b[?997;2n', '\x1b[?997;2n']) dispose() }) - - it('re-registers a chunk that withdraws and subscribes again', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - emit('\x1b[?2031h') - emit('\x1b[?2031l\x1b[?2031h') - expect(deps.paneMode2031Ref.current.get(1)).toBe(true) - expect(replies(transport)).toEqual([]) - dispose() - }) - - it('registers nothing when one chunk both subscribes and withdraws', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - // The fish prompt case: the subscription is gone before the program could read anything. - emit('\x1b[?2031h prompt \x1b[?2031l') - expect(deps.paneMode2031Ref.current.get(1)).toBeUndefined() - expect(replies(transport)).toEqual([]) - dispose() - }) - - it('registers nothing when the withdrawal is split across two chunks', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - emit('\x1b[?2031h prompt \x1b[?20') - emit('31l') - expect(deps.paneMode2031Ref.current.get(1)).toBeUndefined() - expect(replies(transport)).toEqual([]) - dispose() - }) - - it('registers nothing when an unrelated private mode appends a split withdrawal', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - emit('\x1b[?2031h prompt \x1b[?25') - emit(';2031l') - expect(deps.paneMode2031Ref.current.get(1)).toBeUndefined() - expect(replies(transport)).toEqual([]) - dispose() - }) - - it('registers the subscription once an ambiguous tail resolves to another mode', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - emit('\x1b[?2031h drawing \x1b[?20') - expect(deps.paneMode2031Ref.current.get(1)).toBeUndefined() - emit('25h') - expect(deps.paneMode2031Ref.current.get(1)).toBe(true) - expect(replies(transport)).toEqual([]) - dispose() - }) - - // One fish prompt cycle, exactly as fish's tty_handoff.rs emits it. - const FISH_PROMPT_HANDOFF = '\x1b[?2031h\x1b[0m~/orca \x1b[32m❯\x1b[0m \x1b[?2031l' - - it('stays silent across three fish prompts', async () => { - const { transport, emit, dispose } = await connectVisiblePane() - emit(FISH_PROMPT_HANDOFF) - emit(FISH_PROMPT_HANDOFF) - emit(FISH_PROMPT_HANDOFF) - expect(replies(transport)).toEqual([]) - dispose() - }) - - it('leaves no stale subscription behind after a fish prompt cycle', async () => { - const { deps, emit, dispose } = await connectVisiblePane() - emit(FISH_PROMPT_HANDOFF) - // A later theme flip must not push CSI 997 at a shell that unsubscribed. - expect(deps.paneMode2031Ref.current.get(1)).toBeUndefined() - dispose() - }) - - it('registers a TUI that subscribes at the end of a fish prompt chunk', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - emit(`${FISH_PROMPT_HANDOFF}\x1b[?2031h`) - expect(deps.paneMode2031Ref.current.get(1)).toBe(true) - expect(replies(transport)).toEqual([]) - dispose() - }) - - it('keeps a subscription whose withdrawal never arrives', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - // A real TUI: subscribe now, unsubscribe minutes later on exit. - emit('\x1b[?2031h') - emit('painting the ui') - expect(deps.paneMode2031Ref.current.get(1)).toBe(true) - expect(replies(transport)).toEqual([]) - dispose() - }) - - it('discards a half-read escape prefix when the pane swaps PTYs', async () => { - const { transport, deps, emit, dispose } = await connectVisiblePane() - // Discard old stream tails on PTY replacement so concatenation cannot fabricate a subscription. - transport.serializeBuffer = vi.fn().mockResolvedValue(null) - emit('\x1b[?20') - // droppedOutput latches the hidden-restore PTY id, which is what detects the swap. - emit('', { droppedOutput: true }) - transport.getPtyId.mockReturnValue('pty-id-2') - - emit('31h') - - expect(deps.paneMode2031Ref.current.get(1)).toBeUndefined() - expect(replies(transport)).toEqual([]) - dispose() - }) - }) - - it('records hidden Codex mode 2031 subscribes split across becoming visible', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = await vi.importMock( - '@/lib/agent-status/aggregation/worktree-agent-status' - ) - const transport = createMockTransport('pty-id') - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - mockStoreState = { - ...mockStoreState, - settings: { ...mockStoreState.settings, theme: 'light' } - } - - const isVisibleRef = { current: false } - const paneMode2031Ref = { current: new Map() } - const paneLastThemeModeRef = { current: new Map() } - const pane = createPane(1) - const manager = createManager(1) - const binding = connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks( - createDeps({ - isVisibleRef, - paneMode2031Ref, - paneLastThemeModeRef, - startup: { command: 'codex' } - }) as never, - agentTitleMocks2 - ) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('\x1b[?20') - isVisibleRef.current = true - capturedDataCallback.current?.('31h') - - expect(transport.sendInputImmediate).not.toHaveBeenCalledWith(expect.stringMatching(/\?997/)) - expect(paneMode2031Ref.current.get(1)).toBe(true) - // Seeded so the next appearance re-apply only pushes on a real color-mode flip. - expect(paneLastThemeModeRef.current.get(1)).toBe('light') - expect(pane.terminal.write).not.toHaveBeenCalledWith('31h', expect.any(Function)) - - binding.dispose() - }) - - it('does not keep mode 2031 subscribed when a skipped hidden chunk unsubscribes last', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks3 = await vi.importMock( - '@/lib/agent-status/aggregation/worktree-agent-status' - ) - const transport = createMockTransport('pty-id') - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const paneMode2031Ref = { current: new Map() } - const paneLastThemeModeRef = { current: new Map() } - const pane = createPane(1) - const manager = createManager(1) - const binding = connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks( - createDeps({ - isVisibleRef: { current: false }, - paneMode2031Ref, - paneLastThemeModeRef, - startup: { command: 'codex' } - }) as never, - agentTitleMocks3 - ) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('\x1b[?2031h\x1b[?2031l') - - expect(transport.sendInput).not.toHaveBeenCalledWith(expect.stringMatching(/\?997/)) - expect(paneMode2031Ref.current.has(1)).toBe(false) - expect(paneLastThemeModeRef.current.has(1)).toBe(false) - - binding.dispose() }) }) } diff --git a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-output-side-effects.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-output-side-effects.test.ts index 7384431392b..13bb0d53fdd 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-output-side-effects.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-output-side-effects.test.ts @@ -44,25 +44,6 @@ describe('createIpcPtyTransport', () => { transport.disconnect() }) - it('runs title side effects even when the data callback does not render the chunk', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const onTitleChange = vi.fn() - const onDataCallback = vi.fn() - const transport = createIpcPtyTransport({ onTitleChange }) - - await transport.connect({ url: '', callbacks: { onData: onDataCallback } }) - - onData?.({ id: 'pty-1', data: '\u001b]0;hidden-title\u0007' }) - - expect(onDataCallback).toHaveBeenCalledWith('\u001b]0;hidden-title\u0007') - expect(onTitleChange).not.toHaveBeenCalled() - - await flushPtySideEffects() - - expect(onTitleChange).toHaveBeenCalledWith('hidden-title', 'hidden-title') - transport.disconnect() - }) - it('drops the OSC-9999 cross-chunk carry on resetAgentStatusCarry', async () => { // Why: a restore marker means bytes dropped, so a carried partial OSC-9999 prefix would eat the next chunk's head. const { createPtyOutputProcessor } = await import('../output/pty-output-processor') @@ -78,48 +59,6 @@ describe('createIpcPtyTransport', () => { expect(callbacks.onData).toHaveBeenLastCalledWith('plain output after the gap') }) - it('does not schedule PTY side-effect drains for ordinary output with no working title', async () => { - vi.useFakeTimers() - try { - const { createPtyOutputProcessor } = await import('../output/pty-output-processor') - const onTitleChange = vi.fn() - const onBell = vi.fn() - const processor = createPtyOutputProcessor({ onTitleChange, onBell }) - const callbacks = { onData: vi.fn() } - - processor.processData('plain command output\r\n'.repeat(50), callbacks) - - expect(callbacks.onData).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - expect(onTitleChange).not.toHaveBeenCalled() - expect(onBell).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) - - it('compacts ignored Cursor native titles into one deferred drain', async () => { - vi.useFakeTimers() - try { - const { createPtyOutputProcessor } = await import('../output/pty-output-processor') - const onTitleChange = vi.fn() - const processor = createPtyOutputProcessor({ onTitleChange }) - const callbacks = { onData: vi.fn() } - const ignoredTitles = Array.from({ length: 4_096 }, () => '\x1b]0;Cursor Agent\x07').join('') - - processor.processData(ignoredTitles, callbacks) - - expect(vi.getTimerCount()).toBe(1) - await vi.runOnlyPendingTimersAsync() - - expect(vi.getTimerCount()).toBe(0) - // Why: the literal is the pane's identity once (#10258); the redraw repeats stay ignored. - expect(onTitleChange.mock.calls).toEqual([['Cursor Agent', 'Cursor Agent']]) - } finally { - vi.useRealTimers() - } - }) - it('lets an ignored Cursor native title clear a pending stale-title fallback', async () => { vi.useFakeTimers() try { @@ -204,79 +143,6 @@ describe('createIpcPtyTransport', () => { } }) - it('limits deferred PTY side-effect work per timer tick', async () => { - vi.useFakeTimers() - try { - const { createPtyOutputProcessor } = await import('../output/pty-output-processor') - const onTitleChange = vi.fn() - const processor = createPtyOutputProcessor({ onTitleChange }) - const callbacks = { onData: vi.fn() } - - for (let i = 0; i < 200; i++) { - processor.processData(`\x1b]0;title-${i}\x07`, callbacks) - } - - expect(onTitleChange).not.toHaveBeenCalled() - await vi.runOnlyPendingTimersAsync() - - expect(onTitleChange.mock.calls.length).toBeGreaterThan(0) - expect(onTitleChange.mock.calls.length).toBeLessThan(200) - - await vi.runAllTimersAsync() - expect(onTitleChange).toHaveBeenCalledTimes(200) - expect(onTitleChange).toHaveBeenLastCalledWith('title-199', 'title-199') - } finally { - vi.useRealTimers() - } - }) - - it('limits coalesced OSC titles in one PTY chunk per timer tick', async () => { - vi.useFakeTimers() - try { - const { createPtyOutputProcessor } = await import('../output/pty-output-processor') - const onTitleChange = vi.fn() - const processor = createPtyOutputProcessor({ onTitleChange }) - const callbacks = { onData: vi.fn() } - const titles = Array.from({ length: 200 }, (_, i) => `\x1b]0;chunk-title-${i}\x07`).join('') - - processor.processData(titles, callbacks) - await vi.runOnlyPendingTimersAsync() - - expect(onTitleChange.mock.calls.length).toBeGreaterThan(0) - expect(onTitleChange.mock.calls.length).toBeLessThan(200) - - await vi.runAllTimersAsync() - expect(onTitleChange).toHaveBeenCalledTimes(200) - expect(onTitleChange).toHaveBeenLastCalledWith('chunk-title-199', 'chunk-title-199') - } finally { - vi.useRealTimers() - } - }) - - it('flushes all remaining PTY side effects after a partial bounded drain', async () => { - vi.useFakeTimers() - try { - const { createPtyOutputProcessor } = await import('../output/pty-output-processor') - const onTitleChange = vi.fn() - const processor = createPtyOutputProcessor({ onTitleChange }) - const callbacks = { onData: vi.fn() } - - for (let i = 0; i < 200; i++) { - processor.processData(`\x1b]0;flush-title-${i}\x07`, callbacks) - } - - await vi.runOnlyPendingTimersAsync() - expect(onTitleChange.mock.calls.length).toBeLessThan(200) - - processor.flushPendingSideEffects() - - expect(onTitleChange).toHaveBeenCalledTimes(200) - expect(onTitleChange).toHaveBeenLastCalledWith('flush-title-199', 'flush-title-199') - } finally { - vi.useRealTimers() - } - }) - it('bounds the deferred side-effect queue under a stalled drain, keeping the newest title and a pending bell', async () => { vi.useFakeTimers() try { @@ -348,32 +214,6 @@ describe('createIpcPtyTransport', () => { } }) - it('delivers the side-effect count and final title when the queue stays below the cap', async () => { - vi.useFakeTimers() - try { - const { createPtyOutputProcessor } = await import('../output/pty-output-processor') - const onTitleChange = vi.fn() - const onBell = vi.fn() - const onAgentStatus = vi.fn() - const processor = createPtyOutputProcessor({ onTitleChange, onBell, onAgentStatus }) - const callbacks = { onData: vi.fn() } - - processor.processData('\x07', callbacks) - for (let i = 0; i < 100; i++) { - processor.processData(`\x1b]0;under-cap-${i}\x07`, callbacks) - } - processor.processData('\x1b]9999;{"state":"done","prompt":"done"}\x07', callbacks) - await vi.runAllTimersAsync() - - expect(onBell).toHaveBeenCalledTimes(1) - expect(onTitleChange).toHaveBeenCalledTimes(100) - expect(onTitleChange).toHaveBeenLastCalledWith('under-cap-99', 'under-cap-99') - expect(onAgentStatus).toHaveBeenCalledWith({ state: 'done', prompt: 'done' }) - } finally { - vi.useRealTimers() - } - }) - it('still runs stale-title detection when an OSC status chunk has no title', async () => { vi.useFakeTimers() try { diff --git a/src/renderer/src/components/terminal-pane/titles/TerminalPaneHeaderOverlay.test.tsx b/src/renderer/src/components/terminal-pane/titles/TerminalPaneHeaderOverlay.test.tsx index 3b527222e55..a11fca6cb56 100644 --- a/src/renderer/src/components/terminal-pane/titles/TerminalPaneHeaderOverlay.test.tsx +++ b/src/renderer/src/components/terminal-pane/titles/TerminalPaneHeaderOverlay.test.tsx @@ -195,123 +195,6 @@ afterEach(() => { }) describe('TerminalPaneHeaderOverlay', () => { - it('offers Continue in Chat UI instead of a chat view switch, on the active pane only', () => { - const { container } = renderOverlay({ paneTitles: {}, canResumeInNewNativeChat: true }) - - const resumeButtons = [...container.querySelectorAll('button')].filter( - (button) => button.textContent === 'Continue in Chat UI' - ) - expect(resumeButtons).toHaveLength(1) - expect(resumeButtons[0]?.closest('.pane-title-bar')?.hasAttribute('data-active-pane')).toBe( - true - ) - expect(container.querySelector('button[aria-label="Show chat view"]')).toBeNull() - expect(container.querySelector('button[aria-label="Chat settings"]')).toBeNull() - }) - - it('keeps Show terminal as the way back from chat view', () => { - const { container } = renderOverlay({ - paneTitles: {}, - canShowTerminal: true, - canResumeInNewNativeChat: true - }) - - expect(container.querySelector('button[aria-label="Show terminal"]')).not.toBeNull() - expect(container.querySelectorAll('button[aria-label="Chat settings"]')).toHaveLength(1) - expect( - container.querySelector( - '.pane-title-bar[data-active-pane] button[aria-label="Chat settings"]' - ) - ).not.toBeNull() - expect(container.textContent).not.toContain('Continue in Chat UI') - }) - - it('keeps the titled split-pane X as remove-title only', () => { - const { container, onClosePane, onRemoveTitle } = renderOverlay({ - paneTitles: { 1: 'server', 2: '' } - }) - - const removeTitle = container.querySelector( - 'button[aria-label="Remove pane title: server"]' - ) - expect(removeTitle).not.toBeNull() - expect( - container.querySelector('.pane-title-bar[data-active-pane] button[aria-label="Close Pane"]') - ).toBeNull() - - act(() => removeTitle?.click()) - - expect(onRemoveTitle).toHaveBeenCalledWith(1) - expect(onClosePane).not.toHaveBeenCalled() - }) - - it('offers close tab beside remove-title for a titled single pane', () => { - const { container, onClosePane, onRemoveTitle } = renderOverlay({ - paneTitles: { 1: 'server' }, - paneCount: 1 - }) - - expect(container.querySelector('button[aria-label="Remove pane title: server"]')).not.toBeNull() - const closeTab = container.querySelector('button[aria-label="Close tab"]') - expect(closeTab).not.toBeNull() - - act(() => closeTab?.click()) - - expect(onClosePane).toHaveBeenCalledWith(1) - expect(onRemoveTitle).not.toHaveBeenCalled() - }) - - it('keeps split and close-pane controls available for untitled split pane headers', () => { - const { container, onClosePane } = renderOverlay({ - paneTitles: { 1: '', 2: '' } - }) - - expect(container.querySelector('button[aria-label="Split Terminal Right"]')).not.toBeNull() - expect(container.querySelector('.pane-title-drag-handle')).toBeNull() - const closePane = container.querySelector('button[aria-label="Close Pane"]') - expect(closePane).not.toBeNull() - - act(() => closePane?.click()) - - expect(onClosePane).toHaveBeenCalledWith(1) - }) - - it('offers close tab for an untitled single pane', () => { - const { container, onClosePane } = renderOverlay({ paneTitles: { 1: '' }, paneCount: 1 }) - - const closeTab = container.querySelector('button[aria-label="Close tab"]') - expect(closeTab).not.toBeNull() - expect(container.querySelector('button[aria-label="Close Pane"]')).toBeNull() - - act(() => closeTab?.click()) - - expect(onClosePane).toHaveBeenCalledWith(1) - }) - - it.each([ - { label: 'untitled', title: '' }, - { label: 'titled', title: 'server' } - ])('keeps a pinned $label single-pane tab without a close button', ({ title }) => { - const { container } = renderOverlay({ - paneTitles: { 1: title }, - paneCount: 1, - isTabPinned: true - }) - - expect(container.querySelector('button[aria-label="Close tab"]')).toBeNull() - }) - - it('omits the split control when the header affordance is hidden', () => { - const { container } = renderOverlay({ - paneTitles: { 1: '', 2: '' }, - paneCount: 1, - showSplitButton: false - }) - - expect(container.querySelector('button[aria-label="Split Terminal Right"]')).toBeNull() - expect(container.querySelector('button[aria-label="Close tab"]')).toBeNull() - }) - it('ignores IME composition Enter before submitting a pane title rename', () => { const { container, onRenameSubmit } = renderOverlay({ paneTitles: { 1: 'server', 2: '' }, @@ -330,25 +213,6 @@ describe('TerminalPaneHeaderOverlay', () => { expect(onRenameSubmit).toHaveBeenCalledTimes(1) }) - - it('shows new-session continuation on the active agent pane header', () => { - const onContinueAgentSessionInNewSession = vi.fn() - const { container } = renderOverlay({ - paneTitles: { 1: '', 2: '' }, - canContinueAgentSessionInNewSession: true, - onContinueAgentSessionInNewSession - }) - const handoff = container.querySelector( - 'button[aria-label="Hand Off to Another Agent"]' - ) - - expect(handoff).not.toBeNull() - act(() => handoff?.click()) - - expect(onContinueAgentSessionInNewSession).toHaveBeenCalledWith( - expect.objectContaining({ id: 1 }) - ) - }) }) function dispatchFileDrag(target: Element, type: 'dragover' | 'drop', internal: boolean): void { diff --git a/src/renderer/src/store/slices/browser/annotations/browser-annotation-retention.test.ts b/src/renderer/src/store/slices/browser/annotations/browser-annotation-retention.test.ts index 212e6c5c836..d9983e5fcca 100644 --- a/src/renderer/src/store/slices/browser/annotations/browser-annotation-retention.test.ts +++ b/src/renderer/src/store/slices/browser/annotations/browser-annotation-retention.test.ts @@ -1,6 +1,4 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' -import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture' import { createBrowserMockApi } from '../browser-slice-test-harness' import { createTestStoreDrawnFromMain } from '../browser-slice-drawn-from-main.test-fixture' import { makeAnnotation } from './browser-annotation-test-fixture' @@ -63,45 +61,4 @@ describe('saved browser note lifetime and marker eligibility', () => { expect(store.getState().browserAnnotationsByPageId[pageId]).toBeUndefined() expect(store.getState().browserAnnotationMarkerIdsByPageId[pageId]).toBeUndefined() }) - - it.each([ - ['page', 'closeBrowserPage'], - ['workspace', 'closeTabs'], - ['conversion', 'replaceBrowserPage'], - ['hydration', null] - ] as const)('cleans up note and marker authority on %s teardown', async (mode, mainCommand) => { - const { store, main, workspace, pageId } = await createAnnotatedPage() - if (mode === 'page') { - store.getState().closeBrowserPage(pageId) - } - if (mode === 'workspace') { - store.getState().closeBrowserTab(workspace.id) - } - if (mode === 'conversion') { - store.getState().convertBrowserPage(pageId, { - kind: 'workspace-doc', - docLocation: { - kind: 'workspace-doc', - worktreeId: 'wt-1', - filePath: '/workspace/index.html' - } - }) - } - if (mode === 'hydration') { - store.getState().hydrateBrowserSession({ - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - }) - } - await main.settle() - // A layout-owner build's teardown is main's, drawn from its frame. - expect(layoutApplyTestTransport.sent.map((command) => command.type)).toEqual( - ORCA_LAYOUT_OWNER_IS_MAIN ? ['openBrowserTab', ...(mainCommand ? [mainCommand] : [])] : [] - ) - expect(store.getState().browserAnnotationsByPageId[pageId]).toBeUndefined() - expect(store.getState().browserAnnotationMarkerIdsByPageId[pageId]).toBeUndefined() - }) })