diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index dfecf68829a..7a85324765e 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -110,7 +110,6 @@ 1 src/renderer/src/components/editor/editor-header-file-rename.ts 1 src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx 1 src/renderer/src/components/editor/git-graph/git-graph-filter.tsx -1 src/renderer/src/components/editor/git-graph/git-graph-tab.tsx 1 src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx 1 src/renderer/src/components/editor/markdown-preview/review/MarkdownPreviewAnnotationComposer.tsx 1 src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.tsx diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index 214d50ab346..8054472ea82 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -72,7 +72,6 @@ 1 src/renderer/src/app-shell/use-app-session-persistence.ts 1 src/renderer/src/components/browser-pane/browser-client-page-position-driver.ts 1 src/renderer/src/components/contextual-tours/use-contextual-tour.ts -1 src/renderer/src/components/editor/setup-contextual-copy.ts 1 src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog.ts 1 src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx 1 src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.tsx diff --git a/config/tsconfig.node.json b/config/tsconfig.node.json index b03af050cf3..e871e791659 100644 --- a/config/tsconfig.node.json +++ b/config/tsconfig.node.json @@ -38,7 +38,8 @@ "../src/types/**/*" ], "exclude": [ - "../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts" + "../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts", + "../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts" ], "compilerOptions": { "composite": true, diff --git a/config/tsconfig.test.pane-launch.json b/config/tsconfig.test.pane-launch.json index cdffd47c2df..07117e2ab40 100644 --- a/config/tsconfig.test.pane-launch.json +++ b/config/tsconfig.test.pane-launch.json @@ -2,6 +2,7 @@ "extends": "./tsconfig.web.json", "include": [ "../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts", + "../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", "../src/renderer/src/runtime/observed-provider-accounts.test.tsx", "../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx", diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 2b2dab9d5db..8035a86a0b8 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -15,7 +15,8 @@ const contracts = [ 'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts', 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', - 'src/main/claude-usage/scanner-incremental-append.test.ts' + 'src/main/claude-usage/scanner-incremental-append.test.ts', + 'src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts' ] for (const contract of contracts) { if (!existsSync(resolve(contract))) { diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx index 9ea090b89aa..ae3c41cfb47 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx @@ -71,7 +71,7 @@ export function screenModuleMocks(dependencies: ScreenDependencies) { View: 'View', useWindowDimensions: () => ({ width: 390, height: 844 }) }), - // Stub Expo-dependent native handlers; native-clipboard.test.ts covers their behavior. + // Stub Expo-dependent native handlers. 'expo-clipboard': () => ({ setStringAsync: () => Promise.resolve(true), getStringAsync: () => Promise.resolve('') diff --git a/mobile/src/navigation/workspace-route-handoff.test.tsx b/mobile/src/navigation/workspace-route-handoff.test.tsx index 2a30994865e..f1c67061279 100644 --- a/mobile/src/navigation/workspace-route-handoff.test.tsx +++ b/mobile/src/navigation/workspace-route-handoff.test.tsx @@ -84,9 +84,4 @@ describe('a workspace screen’s router', () => { ['back'] ]) }) - - it('is the plain router in the desktop’s own workspaces', async () => { - const router = await workspaceRouterFor({}) - expect(router).toBe(route.router) - }) }) diff --git a/mobile/src/notifications/native-push-dismissal.test.ts b/mobile/src/notifications/native-push-dismissal.test.ts deleted file mode 100644 index 73c96495300..00000000000 --- a/mobile/src/notifications/native-push-dismissal.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' - -const requireNativeModule = vi.hoisted(() => vi.fn()) -vi.mock('expo-modules-core', () => ({ requireNativeModule })) - -beforeEach(() => { - vi.resetModules() - requireNativeModule.mockReset() -}) - -it('requires the iOS ledger and surfaces a missing native module as a build defect', async () => { - requireNativeModule.mockImplementation(() => { - throw new Error('Cannot find native module OrcaNotificationDismissal') - }) - await expect(import('./native-push-dismissal.ios')).rejects.toThrow( - 'Cannot find native module OrcaNotificationDismissal' - ) -}) - -it('does not load an iOS module on the default Android/web path', async () => { - expect((await import('./native-push-dismissal')).nativePushDismissal).toBeNull() - expect(requireNativeModule).not.toHaveBeenCalled() -}) diff --git a/mobile/src/onboarding/MobileOnboardingPage.test.ts b/mobile/src/onboarding/MobileOnboardingPage.test.ts index c2dd34aa2ab..48612248143 100644 --- a/mobile/src/onboarding/MobileOnboardingPage.test.ts +++ b/mobile/src/onboarding/MobileOnboardingPage.test.ts @@ -2,7 +2,7 @@ import { createElement, type ReactNode } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import { MobileOnboardingPage } from './MobileOnboardingPage' -import { findAllByHostType, findByHostType } from '../test-support/react-test-renderer-host-nodes' +import { findByHostType } from '../test-support/react-test-renderer-host-nodes' vi.mock('react-native', async () => { const React = await import('react') @@ -87,12 +87,6 @@ describe('MobileOnboardingPage', () => { ) } - function collectText(): string { - return findAllByHostType(renderer!.root, 'Text') - .flatMap((node) => node.props.children) - .join(' ') - } - it('renders the session choices and sends exactly one selected view', async () => { const callbacks = await renderPage('session-view') @@ -109,19 +103,6 @@ describe('MobileOnboardingPage', () => { expect(callbacks.onSessionChoice).not.toHaveBeenCalled() }) - it('explains that alerts cover finished work and waiting agents, even if the app is closed', async () => { - await renderPage('notifications') - const copy = collectText() - - expect(copy).toContain('Don’t miss when an agent needs you') - expect(copy).toContain('finishes or is waiting') - expect(copy).toContain('using the app') - expect(copy).toContain('Enable notifications') - expect(copy).toContain('Codex finished') - expect(copy).toContain('Claude needs input') - expect(renderer!.root.findByProps({ testID: 'notification-onboarding-preview' })).toBeTruthy() - }) - it('disables both notification choices while permission is pending', async () => { await renderPage('notifications', { busyChoice: 'enable' }) const enable = button('Enable agent notifications') diff --git a/mobile/src/platform/external-link.test.ts b/mobile/src/platform/external-link.test.ts index 3e5d3bdcebf..42c79d6b949 100644 --- a/mobile/src/platform/external-link.test.ts +++ b/mobile/src/platform/external-link.test.ts @@ -26,28 +26,14 @@ afterEach(() => { }) describe('opening a URL from a phone screen', () => { - it('hands it straight to the app, unchanged', () => { - openExternalLink('https://github.com/stablyai/orca/pull/1') - expect(linking.openURL.mock.calls).toEqual([['https://github.com/stablyai/orca/pull/1']]) - }) - it('does not throw out of a tap handler when nothing can open the URL', async () => { linking.openURL.mockImplementation(() => Promise.reject(new Error('no activity found'))) expect(() => openExternalLink('mailto:someone@example.com')).not.toThrow() await Promise.resolve() }) - - it('checks no scheme of its own, because on a phone this is what every call site already did', () => { - openExternalLink('orca://x') - expect(linking.openURL.mock.calls).toEqual([['orca://x']]) - }) }) describe('a URL the platform refuses before it returns a promise', () => { - it('does not throw out of a tap handler for an empty string', () => { - expect(() => openExternalLink('')).not.toThrow() - }) - it('names the refusal rather than failing silently', () => { const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) openExternalLink('') diff --git a/mobile/src/platform/haptics.web.test.ts b/mobile/src/platform/haptics.web.test.ts deleted file mode 100644 index a8e198520dd..00000000000 --- a/mobile/src/platform/haptics.web.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { BRIDGE_HAPTICS_KINDS } from '../mobile-web-shell/bridge/bridge-haptics-notify' -import { - publishHapticsNotifier, - triggerEdgeBump, - triggerError, - triggerMediumImpact, - triggerSelection, - triggerSuccess -} from './haptics.web' - -const asked: string[] = [] - -beforeEach(() => { - asked.length = 0 - publishHapticsNotifier((kind) => { - asked.push(kind) - return true - }) -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('the haptic each page function asks the shell for', () => { - it.each([ - ['mediumImpact', triggerMediumImpact], - ['selection', triggerSelection], - ['success', triggerSuccess], - ['error', triggerError], - ['edgeBump', triggerEdgeBump] - ] as const)('posts exactly one notify, carrying %s', (kind, trigger) => { - trigger() - expect(asked).toEqual([kind]) - }) - - it('covers every kind the notify accepts, so no name is left on a no-op', () => { - // Check export/kind parity so adding a native haptic cannot silently leave page taps inert. - for (const trigger of [ - triggerMediumImpact, - triggerSelection, - triggerSuccess, - triggerError, - triggerEdgeBump - ]) { - trigger() - } - expect([...asked].sort()).toEqual([...BRIDGE_HAPTICS_KINDS].sort()) - }) - - it('posts one frame per call, because a scrolling list calls once per row', () => { - for (let row = 0; row < 12; row += 1) { - triggerSelection() - } - expect(asked).toHaveLength(12) - }) -}) - -describe('a shell that will not play it', () => { - it('says nothing, because nobody reads the answer and every row tap would say it again', () => { - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - publishHapticsNotifier(() => false) - expect(() => triggerSelection()).not.toThrow() - expect(warned).not.toHaveBeenCalled() - }) - - it('asks nothing at all in a document that published no notifier', async () => { - // Reload the module to clear notifiers published by earlier cases. - vi.resetModules() - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const fresh: typeof import('./haptics.web') = await import('./haptics.web') - expect(() => fresh.triggerError()).not.toThrow() - expect(asked).toEqual([]) - expect(warned).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/platform/keyboard-close-blur.web.test.ts b/mobile/src/platform/keyboard-close-blur.web.test.ts index 62b14b1021f..52de9babec7 100644 --- a/mobile/src/platform/keyboard-close-blur.web.test.ts +++ b/mobile/src/platform/keyboard-close-blur.web.test.ts @@ -37,7 +37,7 @@ function focusedField(userAgent: string): HTMLInputElement { describe('a keyboard the phone closes', () => { beforeEach(() => { - vi.useFakeTimers({ toFake: ['setTimeout', 'performance'] }) + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) publishShellKeyboardSource({ read: () => shellHeight, subscribe: (listener) => { @@ -62,10 +62,24 @@ describe('a keyboard the phone closes', () => { expect(document.activeElement).toBe(field) shellReports(0) + vi.advanceTimersByTime(1000) expect(document.activeElement).not.toBe(field) }) + it('keeps the field focused when the keyboard closes and reopens for a switch to a voice IME', () => { + const field = focusedField(ANDROID) + startBlurringOnKeyboardClose() + shellReports(300) + + shellReports(0) + vi.advanceTimersByTime(250) + shellReports(200) + vi.advanceTimersByTime(5000) + + expect(document.activeElement).toBe(field) + }) + // The second case is tapping the underlined word after Back: that tap both focuses the field and opens the menu. it.each([ ['already focused', false], @@ -105,7 +119,7 @@ describe('a keyboard the phone closes', () => { target.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })) vi.advanceTimersByTime(waitMs) shellReports(0) - vi.advanceTimersByTime(100) + vi.advanceTimersByTime(1000) expect(document.activeElement).not.toBe(field) }) diff --git a/mobile/src/platform/keyboard-close-blur.web.ts b/mobile/src/platform/keyboard-close-blur.web.ts index 2611184750e..54087c6929e 100644 --- a/mobile/src/platform/keyboard-close-blur.web.ts +++ b/mobile/src/platform/keyboard-close-blur.web.ts @@ -5,6 +5,8 @@ import { subscribeSoftKeyboard } from './keyboard-occlusion.web' // Chromium hides the IME itself to show a tapped autocorrected word's menu; Back comes with no touch. const FIELD_TAP_HIDE_WINDOW_MS = 1000 const KEYBOARD_REOPEN_DELAY_MS = 50 +// A keyboard's mic switches to a voice IME, which closes the keyboard and opens again ~250 ms later; Back opens none. +const IME_SWITCH_WINDOW_MS = 1000 // Android raises the IME only for a new focus session, as for the terminal live input. function reopenKeyboard(field: HTMLElement): void { @@ -14,12 +16,13 @@ function reopenKeyboard(field: HTMLElement): void { } } -// Android Back hides the IME without blurring; blur now so the next terminal touch cannot reopen it. +// Android Back hides the IME without blurring; blur once it stays closed so the next terminal touch cannot reopen it. export function startBlurringOnKeyboardClose(): void { if (hostOs() !== 'android') { return } let lastTouch: { target: Node; at: number } | null = null + let pendingBlur: ReturnType | undefined document.addEventListener( 'pointerdown', (event) => { @@ -29,7 +32,7 @@ export function startBlurringOnKeyboardClose(): void { { capture: true } ) subscribeSoftKeyboard( - () => {}, + () => clearTimeout(pendingBlur), () => { const field = document.activeElement const touch = lastTouch @@ -42,7 +45,12 @@ export function startBlurringOnKeyboardClose(): void { ) { setTimeout(() => reopenKeyboard(field), KEYBOARD_REOPEN_DELAY_MS) } else { - Keyboard.dismiss() + // Leave alone a field focus moved to meanwhile. + pendingBlur = setTimeout(() => { + if (document.activeElement === field) { + Keyboard.dismiss() + } + }, IME_SWITCH_WINDOW_MS) } } ) diff --git a/mobile/src/platform/live-input-composing-range.test.ts b/mobile/src/platform/live-input-composing-range.test.ts index 1d2e923c19b..307cdc5eed3 100644 --- a/mobile/src/platform/live-input-composing-range.test.ts +++ b/mobile/src/platform/live-input-composing-range.test.ts @@ -26,9 +26,4 @@ describe('the composing range a live input reports', () => { undefined ]) }) - - it('passes the range through where there is no navigator', () => { - vi.stubGlobal('navigator', undefined) - expect(reportedLiveInputComposing(true)).toBe(true) - }) }) diff --git a/mobile/src/platform/microphone-screen-lock.test.ts b/mobile/src/platform/microphone-screen-lock.test.ts index 6a23892e557..cd6b41eda40 100644 --- a/mobile/src/platform/microphone-screen-lock.test.ts +++ b/mobile/src/platform/microphone-screen-lock.test.ts @@ -37,15 +37,6 @@ async function flush(): Promise { } describe('the lock a microphone holds', () => { - it('takes the tag once and gives it back once', async () => { - const { device, calls } = createTestDevice() - const lock = createMicrophoneScreenLock(device, 'orca-mic') - lock.hold() - lock.release() - await flush() - expect(calls).toEqual(['+orca-mic', '-orca-mic']) - }) - it('asks the device nothing for a hold it already has', async () => { const { device, calls } = createTestDevice() const lock = createMicrophoneScreenLock(device, 'orca-mic') diff --git a/mobile/src/platform/native-clipboard.test.ts b/mobile/src/platform/native-clipboard.test.ts deleted file mode 100644 index e6366525a42..00000000000 --- a/mobile/src/platform/native-clipboard.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ZodError } from 'zod' - -const clipboard = vi.hoisted(() => ({ - setStringAsync: vi.fn(() => Promise.resolve(true)), - getStringAsync: vi.fn(() => Promise.resolve('')) -})) - -vi.mock('expo-clipboard', () => clipboard) - -import { serveNativeClipboardVerb } from './native-clipboard' - -beforeEach(() => { - clipboard.setStringAsync.mockReset() - clipboard.setStringAsync.mockImplementation(() => Promise.resolve(true)) - clipboard.getStringAsync.mockReset() - clipboard.getStringAsync.mockImplementation(() => Promise.resolve('on the pasteboard')) -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('serving a clipboard verb', () => { - it('writes text and answers whether the pasteboard took it', async () => { - await expect( - serveNativeClipboardVerb('native.clipboard.write', { mime: 'text', value: 'copied' }) - ).resolves.toEqual({ written: true }) - expect(clipboard.setStringAsync.mock.calls).toEqual([['copied']]) - }) - - it('carries a pasteboard refusal through rather than reporting success', async () => { - clipboard.setStringAsync.mockImplementation(() => Promise.resolve(false)) - await expect( - serveNativeClipboardVerb('native.clipboard.write', { mime: 'text', value: 'copied' }) - ).resolves.toEqual({ written: false }) - }) - - it('reads text off the pasteboard', async () => { - await expect( - serveNativeClipboardVerb('native.clipboard.read', { mime: 'text' }) - ).resolves.toEqual({ value: 'on the pasteboard' }) - }) - - it('does not take an image at all, because the media verbs stage one instead', async () => { - // Images use staged media handles; clipboard.read rejects their MIME before reaching the device. - for (const verb of ['native.clipboard.write', 'native.clipboard.read'] as const) { - const params = - verb === 'native.clipboard.write' ? { mime: 'image', value: 'x' } : { mime: 'image' } - // Require the params refusal code so a pasteboard error cannot satisfy this assertion. - await expect(serveNativeClipboardVerb(verb, params)).rejects.toSatisfy( - (error: unknown) => - error instanceof ZodError && error.issues.some((issue) => issue.path[0] === 'mime') - ) - } - expect(clipboard.setStringAsync).not.toHaveBeenCalled() - expect(clipboard.getStringAsync).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/platform/native-media-stage-cleanup.test.ts b/mobile/src/platform/native-media-stage-cleanup.test.ts index 2391954c187..9f77bef6a60 100644 --- a/mobile/src/platform/native-media-stage-cleanup.test.ts +++ b/mobile/src/platform/native-media-stage-cleanup.test.ts @@ -117,16 +117,6 @@ function heldBytes(): number { return [...storage.files.values()].reduce((total, bytes) => total + bytes.byteLength, 0) } -it('preserves the successful staged URI, base64 options and bytes without deleting it', () => { - const uri = device().stageBase64('AQID') - expect(uri).toBe('file:///cache/orca-media-1234-0.25.png') - expect(storage.events).toEqual([ - { operation: 'create', uri, options: { overwrite: true } }, - { operation: 'write', uri, content: 'AQID', options: { encoding: 'base64' } } - ]) - expect(storage.files.get(uri)).toEqual(Uint8Array.from([1, 2, 3])) -}) - it.each([0, 4096])('releases an unreturned file after a write fails with %i bytes', (bytes) => { const original = new Error('partial native write') storage.writeFailure = original @@ -150,13 +140,6 @@ it('preserves the write failure when best-effort deletion also fails', () => { expect(heldBytes()).toBe(4096) }) -it('preserves creation failure and its original operation order', () => { - const original = new Error('native create failed') - storage.createFailure = original - expect(thrownBy(() => device().stageBase64('AQID'))).toBe(original) - expect(storage.events.map((event) => event.operation)).toEqual(['create']) -}) - it('deletes only the failed file while a prior successful file remains readable', () => { vi.spyOn(Math, 'random').mockReturnValueOnce(0.1).mockReturnValueOnce(0.2) const successfulUri = device().stageBase64('AQID') diff --git a/mobile/src/platform/random-v4-uuid.test.ts b/mobile/src/platform/random-v4-uuid.test.ts index 8dd36f8b92b..1f31a1212c5 100644 --- a/mobile/src/platform/random-v4-uuid.test.ts +++ b/mobile/src/platform/random-v4-uuid.test.ts @@ -13,13 +13,6 @@ afterEach(() => { }) describe('randomV4Uuid', () => { - it('uses crypto.randomUUID where the platform has it', () => { - const randomUUID = vi.fn(() => '11111111-1111-4111-8111-111111111111') - vi.stubGlobal('crypto', { randomUUID }) - expect(randomV4Uuid()).toBe('11111111-1111-4111-8111-111111111111') - expect(secure.getRandomBytes).not.toHaveBeenCalled() - }) - it('falls back to the secure byte source, never Math.random, and stamps v4', () => { vi.stubGlobal('crypto', {}) const insecure = vi.spyOn(Math, 'random') diff --git a/mobile/src/session/session-panel-host.test.ts b/mobile/src/session/session-panel-host.test.ts deleted file mode 100644 index 7756e35e4ca..00000000000 --- a/mobile/src/session/session-panel-host.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { - canDockSessionPanel, - nextActivePanel, - resolvePanelAction, - panelRouteDescriptor, - shouldShowSessionHeaderChecksAction, - type ActivePanel -} from './session-panel-host' - -const PANELS = ['sourceControl', 'files', 'pr'] as const - -describe('nextActivePanel', () => { - it('opens a panel from the closed state', () => { - for (const panel of PANELS) { - expect(nextActivePanel(null, panel)).toBe(panel) - } - }) - - it('closes the panel when tapping the active one', () => { - for (const panel of PANELS) { - expect(nextActivePanel(panel, panel)).toBeNull() - } - }) - - it('swaps to a different panel', () => { - expect(nextActivePanel('sourceControl', 'files')).toBe('files') - expect(nextActivePanel('files', 'pr')).toBe('pr') - expect(nextActivePanel('pr', 'sourceControl')).toBe('sourceControl') - }) -}) - -describe('resolvePanelAction', () => { - it('docks with the opened panel on wide layouts (open)', () => { - expect(resolvePanelAction({ canDock: true, tapped: 'files', current: null })).toEqual({ - kind: 'dock', - next: 'files' - }) - }) - - it('docks with null on wide layouts when tapping the active panel (close)', () => { - expect(resolvePanelAction({ canDock: true, tapped: 'pr', current: 'pr' })).toEqual({ - kind: 'dock', - next: null - }) - }) - - it('docks with the new panel on wide layouts (swap)', () => { - expect( - resolvePanelAction({ canDock: true, tapped: 'sourceControl', current: 'files' }) - ).toEqual({ kind: 'dock', next: 'sourceControl' }) - }) - - it('pushes the tapped panel when docking is unavailable regardless of current', () => { - const currents: ActivePanel[] = [null, 'sourceControl', 'files', 'pr'] - for (const panel of PANELS) { - for (const current of currents) { - expect(resolvePanelAction({ canDock: false, tapped: panel, current })).toEqual({ - kind: 'push', - panel - }) - } - } - }) -}) - -describe('canDockSessionPanel', () => { - it('requires a wide layout and enough measured content-row width', () => { - expect(canDockSessionPanel({ isWideLayout: true, availableWidth: 700, dockWidth: 340 })).toBe( - true - ) - expect(canDockSessionPanel({ isWideLayout: true, availableWidth: 699, dockWidth: 340 })).toBe( - false - ) - expect(canDockSessionPanel({ isWideLayout: false, availableWidth: 900, dockWidth: 340 })).toBe( - false - ) - }) -}) - -describe('shouldShowSessionHeaderChecksAction', () => { - it('shows Checks on git worktree routes once a checks-capable provider is confirmed', () => { - expect( - shouldShowSessionHeaderChecksAction({ - isFolderWorkspaceRoute: false, - repoContextLoaded: true, - hostedChecksSupported: true - }) - ).toBe(true) - }) - - it('hides Checks for providers without hosted checks (pr-panel guard would no-op it)', () => { - expect( - shouldShowSessionHeaderChecksAction({ - isFolderWorkspaceRoute: false, - repoContextLoaded: true, - hostedChecksSupported: false - }) - ).toBe(false) - }) - - it('hides Checks until the provider probe resolves', () => { - expect( - shouldShowSessionHeaderChecksAction({ - isFolderWorkspaceRoute: false, - repoContextLoaded: false, - hostedChecksSupported: true - }) - ).toBe(false) - }) - - it('hides Checks on folder workspace session routes', () => { - expect( - shouldShowSessionHeaderChecksAction({ - isFolderWorkspaceRoute: true, - repoContextLoaded: true, - hostedChecksSupported: true - }) - ).toBe(false) - }) -}) - -describe('panelRouteDescriptor', () => { - it('maps each panel to its expo-router pathname', () => { - expect(panelRouteDescriptor('sourceControl')).toEqual({ - pathname: '/h/[hostId]/source-control/[worktreeId]' - }) - expect(panelRouteDescriptor('files')).toEqual({ - pathname: '/h/[hostId]/files/[worktreeId]' - }) - expect(panelRouteDescriptor('pr')).toEqual({ - pathname: '/h/[hostId]/source-control/[worktreeId]', - params: { tab: 'pr' } - }) - }) -}) diff --git a/mobile/src/session/session-view-opt-in-gate.test.ts b/mobile/src/session/session-view-opt-in-gate.test.ts deleted file mode 100644 index 8a31f466e8a..00000000000 --- a/mobile/src/session/session-view-opt-in-gate.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { readDefaultSessionViewPreference } from '../storage/session-view-preferences' -import { shouldPresentSessionViewOptIn } from './session-view-opt-in-gate' - -vi.mock('../storage/session-view-preferences', () => ({ - readDefaultSessionViewPreference: vi.fn() -})) - -describe('session view opt-in gate', () => { - beforeEach(() => { - vi.mocked(readDefaultSessionViewPreference).mockReset() - }) - - it('presents when no default has ever been saved', async () => { - vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({ - value: null, - loaded: true, - hasStoredValue: false - }) - await expect(shouldPresentSessionViewOptIn()).resolves.toBe(true) - }) - - it.each(['terminal', 'chat'] as const)('preserves an existing %s choice', async (value) => { - vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({ - value, - loaded: true, - hasStoredValue: true - }) - await expect(shouldPresentSessionViewOptIn()).resolves.toBe(false) - }) - - it('does not overwrite an unknown stored value', async () => { - vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({ - value: null, - loaded: true, - hasStoredValue: true - }) - await expect(shouldPresentSessionViewOptIn()).resolves.toBe(false) - }) - - it('does not block startup when storage is unreadable', async () => { - vi.mocked(readDefaultSessionViewPreference).mockResolvedValue({ - value: null, - loaded: false, - hasStoredValue: false - }) - await expect(shouldPresentSessionViewOptIn()).resolves.toBe(false) - }) -}) diff --git a/mobile/src/source-control/mobile-history-screen-state.test.ts b/mobile/src/source-control/mobile-history-screen-state.test.ts deleted file mode 100644 index 45115e52ac1..00000000000 --- a/mobile/src/source-control/mobile-history-screen-state.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveMobileHistoryScreenView } from './mobile-history-screen-state' -import type { MobileCommitRow } from './mobile-git-history' - -const row: MobileCommitRow = { - id: 'abc123', - shortId: 'abc123', - subject: 'commit', - author: 'author', - parentId: null, - relativeTime: '1m' -} - -describe('resolveMobileHistoryScreenView', () => { - it('shows waiting (not an endless spinner) when disconnected with nothing loaded', () => { - // Offline cold loads cannot run; show Retry instead of an endless spinner. - expect(resolveMobileHistoryScreenView({ connected: false, rows: null, error: null })).toEqual({ - kind: 'waiting' - }) - }) - - it('spins only while connected and loading', () => { - expect(resolveMobileHistoryScreenView({ connected: true, rows: null, error: null })).toEqual({ - kind: 'loading' - }) - }) - - it('keeps already-loaded rows visible across a connection drop', () => { - expect(resolveMobileHistoryScreenView({ connected: false, rows: [row], error: null })).toEqual({ - kind: 'rows', - rows: [row] - }) - }) - - it('prefers the error state over waiting so failures stay actionable', () => { - expect(resolveMobileHistoryScreenView({ connected: false, rows: null, error: 'boom' })).toEqual( - { kind: 'error', message: 'boom' } - ) - }) - - it('distinguishes an empty history from a pending load', () => { - expect(resolveMobileHistoryScreenView({ connected: true, rows: [], error: null })).toEqual({ - kind: 'empty' - }) - }) -}) diff --git a/mobile/src/source-control/mobile-open-pr-prefill.test.ts b/mobile/src/source-control/mobile-open-pr-prefill.test.ts index cf977b0b2b2..a3f67fde7f1 100644 --- a/mobile/src/source-control/mobile-open-pr-prefill.test.ts +++ b/mobile/src/source-control/mobile-open-pr-prefill.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { getMobilePrEligibilityReadiness, readFreshGitStatus } from './mobile-open-pr-prefill' +import { readFreshGitStatus } from './mobile-open-pr-prefill' import type { MobileGitStatusResult } from './mobile-git-status' const fallback = { branch: 'old', entries: [] } as unknown as MobileGitStatusResult @@ -33,23 +33,3 @@ describe('readFreshGitStatus', () => { expect(out).toBe(fallback) }) }) - -describe('getMobilePrEligibilityReadiness', () => { - it('keeps readiness fields absent when git status is unknown', () => { - expect(getMobilePrEligibilityReadiness(null)).toEqual({}) - }) - - it('derives dirty and upstream readiness from git status', () => { - const status = { - entries: [{ path: 'a.ts' }], - upstreamStatus: { hasUpstream: true, ahead: 2, behind: 1 } - } as unknown as MobileGitStatusResult - - expect(getMobilePrEligibilityReadiness(status)).toEqual({ - hasUncommittedChanges: true, - hasUpstream: true, - ahead: 2, - behind: 1 - }) - }) -}) diff --git a/mobile/src/source-control/mobile-source-control-conflict-abort.test.ts b/mobile/src/source-control/mobile-source-control-conflict-abort.test.ts deleted file mode 100644 index fa9e40a4746..00000000000 --- a/mobile/src/source-control/mobile-source-control-conflict-abort.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - isMobileConflictAborting, - mobileConflictAbortLabel -} from './mobile-source-control-conflict-abort' - -describe('isMobileConflictAborting', () => { - it('is true only for the matching abort action', () => { - expect(isMobileConflictAborting('abort-merge', 'merge')).toBe(true) - expect(isMobileConflictAborting('abort-rebase', 'rebase')).toBe(true) - }) - - it('is false for other busy actions (stage/commit must not look like abort)', () => { - expect(isMobileConflictAborting('stage-all', 'merge')).toBe(false) - expect(isMobileConflictAborting('commit', 'rebase')).toBe(false) - expect(isMobileConflictAborting(null, 'merge')).toBe(false) - expect(isMobileConflictAborting('abort-merge', 'rebase')).toBe(false) - expect(isMobileConflictAborting('abort-merge', 'unknown')).toBe(false) - }) -}) - -describe('mobileConflictAbortLabel', () => { - it('shows Aborting only while abort is in flight', () => { - expect(mobileConflictAbortLabel('merge', true)).toBe('Aborting…') - expect(mobileConflictAbortLabel('merge', false)).toBe('Abort merge') - expect(mobileConflictAbortLabel('rebase', false)).toBe('Abort rebase') - }) -}) diff --git a/mobile/src/source-control/mobile-source-control-hub-tab.test.ts b/mobile/src/source-control/mobile-source-control-hub-tab.test.ts deleted file mode 100644 index c3331d18943..00000000000 --- a/mobile/src/source-control/mobile-source-control-hub-tab.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { parseSourceControlHubTab } from './mobile-source-control-hub-tab' - -describe('parseSourceControlHubTab', () => { - it('accepts each known tab', () => { - for (const tab of ['changes', 'pr', 'history']) { - expect(parseSourceControlHubTab(tab)).toBe(tab) - } - }) - - it('reads the first element of an array param', () => { - expect(parseSourceControlHubTab(['pr', 'history'])).toBe('pr') - }) - - it('falls back to changes for unknown, empty, or missing values', () => { - expect(parseSourceControlHubTab('nope')).toBe('changes') - expect(parseSourceControlHubTab('')).toBe('changes') - expect(parseSourceControlHubTab(undefined)).toBe('changes') - expect(parseSourceControlHubTab(null)).toBe('changes') - expect(parseSourceControlHubTab([])).toBe('changes') - }) -}) diff --git a/mobile/src/source-control/mobile-source-control-oversized-stage-all.test.tsx b/mobile/src/source-control/mobile-source-control-oversized-stage-all.test.tsx index ea763ad08fc..680730b022a 100644 --- a/mobile/src/source-control/mobile-source-control-oversized-stage-all.test.tsx +++ b/mobile/src/source-control/mobile-source-control-oversized-stage-all.test.tsx @@ -28,7 +28,6 @@ vi.mock('../platform/haptics', () => ({ triggerImpact: () => undefined })) -import { BRIDGE_MAX_MESSAGE_BYTES } from '../mobile-web-shell/bridge/bridge-caps' import { useRouteHandoff } from '../navigation/route-handoff' import { useMobileGitRequests } from './use-mobile-git-requests' import { useMobileSourceControlRunners } from './use-mobile-source-control-runners' @@ -68,33 +67,6 @@ function idleRunnerParams() { } describe('stage-all over the outbound frame cap', () => { - it('refuses the frame at the page rather than posting one the shell drops', async () => { - const pair = createFakeBridgePortPair() - await pair.flush() - const postedBefore = pair.toShell.length - - const rejection = await pair.client - .sendRequest('git.bulkStage', { worktree: 'id:wt-1', filePaths: STAGEABLE_PATHS }) - .then( - () => null, - (error: unknown) => error - ) - await pair.flush() - - expect(rejection).toBeInstanceOf(Error) - expect(rejection instanceof Error ? rejection.name : String(rejection)).toBe( - 'BridgeRequestOversizedError' - ) - // The frame never left, so this is definite failure and a smaller retry cannot duplicate host work. - expect(pair.toShell.length).toBe(postedBefore) - expect(pair.hostDiagnostics).toEqual([]) - expect(pair.diagnostics.map((entry) => entry.kind)).toEqual(['send-oversized']) - const [diagnostic] = pair.diagnostics - expect(diagnostic.kind === 'send-oversized' ? diagnostic.bytes : 0).toBeGreaterThan( - BRIDGE_MAX_MESSAGE_BYTES - ) - }) - it('reports the oversized action and suggests fewer files, then stops being busy', async () => { const pair = createFakeBridgePortPair() await pair.flush() diff --git a/mobile/src/source-control/use-mobile-hosted-review-eligibility.test.ts b/mobile/src/source-control/use-mobile-hosted-review-eligibility.test.ts index f1017bfe127..db7dfcc8304 100644 --- a/mobile/src/source-control/use-mobile-hosted-review-eligibility.test.ts +++ b/mobile/src/source-control/use-mobile-hosted-review-eligibility.test.ts @@ -61,46 +61,6 @@ describe('mobile hosted review eligibility loader core', () => { }) ).toBe(false) }) - - it('builds distinct keys for different branches', () => { - const first = buildMobileHostedReviewEligibilityLoadKey({ - hostId: 'host-1', - worktreeId: 'wt-1', - branch: 'feature-a', - hasUpstream: true, - ahead: 0, - behind: 0, - hasUncommittedChanges: false - }) - const second = buildMobileHostedReviewEligibilityLoadKey({ - hostId: 'host-1', - worktreeId: 'wt-1', - branch: 'feature-b', - hasUpstream: true, - ahead: 0, - behind: 0, - hasUncommittedChanges: false - }) - - expect(first.identity).not.toBe(second.identity) - expect(first.fetch).not.toBe(second.fetch) - }) - - it('scopes load identity to the paired host', () => { - const input = { - worktreeId: 'repo-1::/workspace', - branch: 'feature', - hasUpstream: true, - ahead: 0, - behind: 0, - hasUncommittedChanges: false - } - const local = buildMobileHostedReviewEligibilityLoadKey({ ...input, hostId: 'local' }) - const ssh = buildMobileHostedReviewEligibilityLoadKey({ ...input, hostId: 'ssh-builder' }) - - expect(local.identity).not.toBe(ssh.identity) - expect(local.fetch).not.toBe(ssh.fetch) - }) }) // Fetch-imminent must render loading immediately; an idle frame would shift the list when Create PR appears. @@ -124,31 +84,6 @@ describe('rendered eligibility state', () => { ).toEqual({ kind: 'loading', eligibility: null }) }) - it('passes resolved and refetch states through untouched', () => { - const key = buildMobileHostedReviewEligibilityLoadKey({ - hostId: 'host-1', - worktreeId: 'wt-1', - branch: 'feature', - hasUpstream: true, - ahead: 0, - behind: 0, - hasUncommittedChanges: false - }) - const ready = { kind: 'ready', eligibility: eligibility() } as const - const refetch = { kind: 'loading', eligibility: eligibility() } as const - const error = { kind: 'error' } as const - - for (const state of [ready, refetch, error]) { - expect( - renderedMobileHostedReviewEligibilityState({ - snapshot: loadSnapshot(key, state), - key, - shouldFetch: true - }) - ).toBe(state) - } - }) - it('renders idle when a fetch is not possible, hiding stale snapshots in the same render', () => { const key = buildMobileHostedReviewEligibilityLoadKey({ hostId: 'host-1', @@ -271,55 +206,4 @@ describe('eligibility request ordering', () => { }) expect(renderedState).toMatchObject({ kind: 'loading', eligibility: ready }) }) - - it('keeps remounted hook state separate from a prior instance’s pending request', async () => { - type Response = { ok: true; result: MobileHostedReviewEligibilityReply } - const requests: ReturnType>[] = [] - const client = { - sendRequest: vi.fn(() => { - const request = deferred() - requests.push(request) - return request.promise - }) - } - const newest = eligibility({ canCreate: false, blockedReason: 'existing_review' }) - - function Harness(): null { - renderedState = useMobileHostedReviewEligibility({ - client: client as never, - connState: 'connected', - hostId: 'host-1', - worktreeId: 'wt-1', - branch: 'feature', - hasUpstream: true, - ahead: 0, - behind: 0, - hasUncommittedChanges: false - }) - return null - } - - await act(async () => { - renderer = create(createElement(Harness)) - await Promise.resolve() - }) - act(() => renderer?.unmount()) - renderer = null - await act(async () => { - renderer = create(createElement(Harness)) - await Promise.resolve() - }) - expect(requests).toHaveLength(2) - - await act(async () => { - requests[1]!.resolve({ ok: true, result: newest }) - await Promise.resolve() - }) - await act(async () => { - requests[0]!.resolve({ ok: true, result: eligibility() }) - await Promise.resolve() - }) - - expect(renderedState).toMatchObject({ kind: 'ready', eligibility: newest }) - }) }) diff --git a/mobile/src/tasks/github-work-item-source-errors.test.ts b/mobile/src/tasks/github-work-item-source-errors.test.ts deleted file mode 100644 index 86d39472089..00000000000 --- a/mobile/src/tasks/github-work-item-source-errors.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - extractGitHubIssueSourceError, - extractGitHubIssueSourceFallback -} from './github-work-item-source-errors' - -describe('extractGitHubIssueSourceError', () => { - it('keeps the failing issue source slug with the repo that produced it', () => { - expect( - extractGitHubIssueSourceError( - { id: 'repo-1', path: '/work/orca' }, - { - sources: { issues: { owner: 'upstream', repo: 'orca' } }, - errors: { issues: { message: 'HTTP 403: resource not accessible' } } - } - ) - ).toEqual({ - repoId: 'repo-1', - repoPath: '/work/orca', - source: { owner: 'upstream', repo: 'orca' }, - message: 'HTTP 403: resource not accessible' - }) - }) - - it('drops issue errors when the source slug is unavailable', () => { - expect( - extractGitHubIssueSourceError( - { id: 'repo-1', path: '/work/orca' }, - { - sources: { issues: null }, - errors: { issues: { message: 'failed' } } - } - ) - ).toBeNull() - }) - - it('returns null when the envelope has no issue-side error', () => { - expect( - extractGitHubIssueSourceError( - { id: 'repo-1', path: '/work/orca' }, - { - sources: { issues: { owner: 'stablyai', repo: 'orca' } } - } - ) - ).toBeNull() - }) -}) - -describe('extractGitHubIssueSourceFallback', () => { - it('reports the repo whose upstream issue source fell back to origin', () => { - expect( - extractGitHubIssueSourceFallback( - { id: 'repo-1', path: '/work/orca', displayName: 'orca' }, - { - issueSourceFellBack: true, - sources: { - issues: { owner: 'stablyai', repo: 'orca-fork' }, - prs: { owner: 'stablyai', repo: 'orca' } - } - } - ) - ).toEqual({ - repoId: 'repo-1', - repoPath: '/work/orca', - repoLabel: 'stablyai/orca' - }) - }) - - it('uses the Orca repo display name when the PR source is unavailable', () => { - expect( - extractGitHubIssueSourceFallback( - { id: 'repo-1', path: '/work/orca', displayName: 'orca' }, - { - issueSourceFellBack: true, - sources: { issues: null, prs: null } - } - ) - ).toEqual({ - repoId: 'repo-1', - repoPath: '/work/orca', - repoLabel: 'orca' - }) - }) - - it('returns null when the source resolver did not fall back', () => { - expect( - extractGitHubIssueSourceFallback( - { id: 'repo-1', path: '/work/orca', displayName: 'orca' }, - { - sources: { issues: { owner: 'stablyai', repo: 'orca' } } - } - ) - ).toBeNull() - }) -}) diff --git a/mobile/src/tasks/host-repo-list.test.ts b/mobile/src/tasks/host-repo-list.test.ts index 7bd0da4c6c6..025aaa5f85c 100644 --- a/mobile/src/tasks/host-repo-list.test.ts +++ b/mobile/src/tasks/host-repo-list.test.ts @@ -41,12 +41,6 @@ describe('hostRepoListReducer', () => { const loaded = reduce(idle, { type: 'resolved', repos: [{ id: 'a' }] }) expect(reduce(loaded, { type: 'reset' })).toEqual(idle) }) - - it('returns the identical state when a reset or repeat request changes nothing', () => { - expect(hostRepoListReducer(idle, { type: 'reset' })).toBe(idle) - const loading = reduce(idle, { type: 'requested' }) - expect(hostRepoListReducer(loading, { type: 'requested' })).toBe(loading) - }) }) describe('host repo list readiness', () => { diff --git a/mobile/src/tasks/hosted-repo-selection.test.ts b/mobile/src/tasks/hosted-repo-selection.test.ts index 2d6bb5d4059..840a96c965b 100644 --- a/mobile/src/tasks/hosted-repo-selection.test.ts +++ b/mobile/src/tasks/hosted-repo-selection.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { isHostedTaskRepo, reconcileRepoSelection } from './hosted-repo-selection' +import { reconcileRepoSelection } from './hosted-repo-selection' const repos = [ { id: 'a', kind: 'worktree' }, @@ -7,27 +7,11 @@ const repos = [ { id: 'folder', kind: 'folder' } ] -describe('isHostedTaskRepo', () => { - it('excludes folder workspaces and keeps everything else', () => { - expect(repos.filter(isHostedTaskRepo).map((repo) => repo.id)).toEqual(['a', 'b']) - expect(isHostedTaskRepo({ id: 'no-kind' })).toBe(true) - }) -}) - describe('reconcileRepoSelection', () => { - it('treats an absent or empty persisted selection as "all repos"', () => { - expect(reconcileRepoSelection(repos, null)).toEqual(new Set()) - expect(reconcileRepoSelection(repos, [])).toEqual(new Set()) - }) - it('drops ids this host no longer has', () => { expect(reconcileRepoSelection(repos, ['a', 'gone'])).toEqual(new Set(['a'])) }) - it('widens back to all repos when nothing in the selection survives', () => { - expect(reconcileRepoSelection(repos, ['gone'])).toEqual(new Set()) - }) - it('never selects a folder workspace', () => { expect(reconcileRepoSelection(repos, ['folder'])).toEqual(new Set()) }) diff --git a/mobile/src/tasks/hosted-review-start-point.test.ts b/mobile/src/tasks/hosted-review-start-point.test.ts deleted file mode 100644 index 32c2769d7aa..00000000000 --- a/mobile/src/tasks/hosted-review-start-point.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { shouldResolveHostedReviewStartPoint } from './hosted-review-start-point' - -describe('shouldResolveHostedReviewStartPoint', () => { - it('resolves PR and MR start points when no explicit base branch was selected', () => { - expect(shouldResolveHostedReviewStartPoint({ type: 'pr' })).toBe(true) - expect(shouldResolveHostedReviewStartPoint({ type: 'mr', baseBranchOverride: '' })).toBe(true) - }) - - it('does not resolve a hosted review start point when the user selected a base branch', () => { - expect( - shouldResolveHostedReviewStartPoint({ - type: 'pr', - baseBranchOverride: 'origin/feature/manual' - }) - ).toBe(false) - expect( - shouldResolveHostedReviewStartPoint({ - type: 'mr', - baseBranchOverride: 'origin/release' - }) - ).toBe(false) - }) - - it('never resolves start points for issues', () => { - expect(shouldResolveHostedReviewStartPoint({ type: 'issue' })).toBe(false) - }) -}) diff --git a/mobile/src/tasks/jira-mobile-issue-read.test.ts b/mobile/src/tasks/jira-mobile-issue-read.test.ts deleted file mode 100644 index 12888d54349..00000000000 --- a/mobile/src/tasks/jira-mobile-issue-read.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { toJiraDetailComments } from './jira-mobile-issue-read' - -describe('toJiraDetailComments', () => { - it('maps the author and avatar off the nested user', () => { - expect( - toJiraDetailComments([ - { - id: '10', - body: 'hi', - createdAt: '2026-01-01T00:00:00Z', - user: { accountId: 'a', displayName: 'Dana', avatarUrl: 'https://x/y.png' } - } - ]) - ).toEqual([ - { - id: '10', - author: 'Dana', - authorAvatarUrl: 'https://x/y.png', - body: 'hi', - createdAt: '2026-01-01T00:00:00Z' - } - ]) - }) - - it('degrades to an empty list instead of breaking the detail sheet', () => { - expect(toJiraDetailComments(null)).toEqual([]) - expect(toJiraDetailComments({ error: 'nope' })).toEqual([]) - }) - - it('drops entries without a usable id', () => { - expect( - toJiraDetailComments([{ id: 5, body: 'x' }, { body: 'y' }, { id: '7', body: 'z' }]) - ).toEqual([ - { id: '7', author: undefined, authorAvatarUrl: undefined, body: 'z', createdAt: undefined } - ]) - }) -}) diff --git a/mobile/src/tasks/mobile-linear-group-sorted.test.ts b/mobile/src/tasks/mobile-linear-group-sorted.test.ts deleted file mode 100644 index 21ec710cdac..00000000000 --- a/mobile/src/tasks/mobile-linear-group-sorted.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { LinearIssue } from './mobile-tasks-provider-detail-types' -import { - sortLinearIssues, - groupLinearIssues, - groupSortedLinearIssues -} from './mobile-tasks-reviewer-linear' - -vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme')) -afterEach(() => vi.restoreAllMocks()) - -const issues: LinearIssue[] = Array.from({ length: 60 }, (_, i) => ({ - id: `${i}`, - identifier: ['ENG-10', 'ENG-2', 'Ä-1', 'Å-1', 'é-2', 'e\u0301-2', 'İ-3'][i % 7], - title: 'Task', - url: '', - labels: [], - priority: i % 5, - updatedAt: ['2026-02-01', 'invalid', '1970-01-01', '2026-02-01', '2025-01-01'][ - Math.floor(i / 5) % 5 - ], - state: { name: i % 2 ? 'Todo' : 'Done', type: 'started', color: '' }, - team: { id: `${i % 3}`, name: `Team ${i % 3}`, key: 'ENG' } -})) - -describe('mobile Linear grouping of sorted issues', () => { - it('does no date parsing or collation after ordering has been established', () => { - const sorted = sortLinearIssues(issues, 'updated') - const parse = vi.spyOn(Date, 'parse') - const compare = vi.spyOn(String.prototype, 'localeCompare') - groupSortedLinearIssues(sorted, 'none') - groupSortedLinearIssues(sorted, 'status') - expect(parse).not.toHaveBeenCalled() - expect(compare).not.toHaveBeenCalled() - groupLinearIssues(sorted, 'status', 'updated') - expect(parse).toHaveBeenCalled() - }) - - it('returns independent issue arrays for empty, singleton and ungrouped inputs', () => { - for (const input of [[], [issues[0]], issues]) { - const sorted = Object.freeze([...input]) - const first = groupSortedLinearIssues(sorted, 'none') - const second = groupSortedLinearIssues(sorted, 'none') - expect(first).toEqual(second) - expect(first[0].issues).not.toBe(second[0].issues) - first[0].issues.pop() - expect(second[0].issues).toEqual(sorted) - } - expect(groupSortedLinearIssues([], 'status')).toEqual([]) - }) -}) diff --git a/mobile/src/tasks/mobile-linear-sort.test.ts b/mobile/src/tasks/mobile-linear-sort.test.ts deleted file mode 100644 index 7e2149e1e84..00000000000 --- a/mobile/src/tasks/mobile-linear-sort.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { LinearIssue } from './mobile-tasks-provider-detail-types' -import { sortLinearIssues } from './mobile-tasks-reviewer-linear' - -vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme')) -afterEach(() => vi.restoreAllMocks()) - -const issues: LinearIssue[] = Array.from({ length: 60 }, (_, i) => ({ - id: `${i}`, - identifier: ['ENG-10', 'ENG-2', 'Ä-1', 'Å-1', 'é-2', 'e\u0301-2', 'İ-3'][i % 7], - title: 'Task', - url: '', - labels: [], - priority: i % 5, - updatedAt: ['2026-02-01', 'invalid', '1970-01-01', '2026-02-01', '2025-01-01'][ - Math.floor(i / 5) % 5 - ], - state: { name: i % 2 ? 'Todo' : 'Done', type: 'started', color: '' }, - team: { id: `${i % 3}`, name: `Team ${i % 3}`, key: 'ENG' } -})) -describe('mobile Linear sorting', () => { - it.each(['updated', 'identifier', 'priority'] as const)('bounds %s setup to one pass', (mode) => { - const parse = vi.spyOn(Date, 'parse') - const NativeCollator = Intl.Collator - const collator = vi.spyOn(Intl, 'Collator').mockImplementation(function (locales, options) { - return new NativeCollator(locales, options) - }) - const compare = vi.spyOn(String.prototype, 'localeCompare') - const before = [...issues] - const actual = sortLinearIssues(issues, mode) - const expectedFirstIds = { - updated: ['0', '1', '2'], - priority: ['1', '16', '26'], - identifier: ['1', '8', '15'] - } - const ordered = - mode === 'identifier' ? actual.filter((issue) => issue.identifier.startsWith('ENG-')) : actual - expect(ordered.slice(0, 3).map((issue) => issue.id)).toEqual(expectedFirstIds[mode]) - expect(actual).toHaveLength(issues.length) - expect(issues).toEqual(before) - expect(parse).toHaveBeenCalledTimes(mode === 'identifier' ? 0 : issues.length) - expect(collator).toHaveBeenCalledTimes(mode === 'identifier' ? 1 : 0) - expect(compare).not.toHaveBeenCalled() - }) - - it('skips setup for empty and singleton inputs and returns fresh arrays', () => { - const parse = vi.spyOn(Date, 'parse') - const NativeCollator = Intl.Collator - const collator = vi.spyOn(Intl, 'Collator').mockImplementation(function (locales, options) { - return new NativeCollator(locales, options) - }) - for (const mode of ['updated', 'identifier', 'priority'] as const) { - for (const input of [[], [issues[0]]]) { - const actual = sortLinearIssues(input, mode) - expect(actual).toEqual(input) - expect(actual).not.toBe(input) - } - } - expect(parse).not.toHaveBeenCalled() - expect(collator).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/tasks/mobile-smart-source-modes.test.ts b/mobile/src/tasks/mobile-smart-source-modes.test.ts deleted file mode 100644 index d4a2fb269b4..00000000000 --- a/mobile/src/tasks/mobile-smart-source-modes.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - normalizeSmartMode, - resolveAvailableSmartModes, - resolveDefaultSmartMode -} from './mobile-smart-source-modes' - -const fullyAvailable = { - textOnly: false, - tasksSupported: true, - hasRepo: true, - githubAvailable: true, - gitlabAvailable: true, - linearAvailable: true, - jiraAvailable: true -} - -describe('resolveAvailableSmartModes', () => { - it('lists every mode in desktop order when all are available', () => { - expect(resolveAvailableSmartModes(fullyAvailable)).toEqual([ - 'smart', - 'github', - 'linear', - 'jira', - 'gitlab', - 'branches', - 'text' - ]) - }) - - it('collapses to Name for a non-git (text-only) repo', () => { - expect(resolveAvailableSmartModes({ ...fullyAvailable, textOnly: true })).toEqual(['text']) - }) - - it('drops provider + smart modes when the tasks RPC surface is missing', () => { - expect(resolveAvailableSmartModes({ ...fullyAvailable, tasksSupported: false })).toEqual([ - 'branches', - 'text' - ]) - }) - - it('gates provider tabs on their availability and a selected repo', () => { - expect( - resolveAvailableSmartModes({ - ...fullyAvailable, - githubAvailable: false, - gitlabAvailable: false - }) - ).toEqual(['smart', 'linear', 'jira', 'branches', 'text']) - expect(resolveAvailableSmartModes({ ...fullyAvailable, hasRepo: false })).toEqual([ - 'smart', - 'linear', - 'jira', - 'text' - ]) - }) - - it('keeps the Jira tab repo-independent but hides it when Jira is disconnected', () => { - expect(resolveAvailableSmartModes({ ...fullyAvailable, hasRepo: false })).toContain('jira') - expect(resolveAvailableSmartModes({ ...fullyAvailable, jiraAvailable: false })).not.toContain( - 'jira' - ) - }) -}) - -describe('resolveDefaultSmartMode', () => { - it('defaults to smart for a git repo with search', () => { - expect(resolveDefaultSmartMode(fullyAvailable)).toBe('smart') - }) - - it('defaults to text for a non-git repo', () => { - expect(resolveDefaultSmartMode({ ...fullyAvailable, textOnly: true })).toBe('text') - }) - - it('defaults to branches for a git repo without the tasks surface', () => { - expect(resolveDefaultSmartMode({ ...fullyAvailable, tasksSupported: false })).toBe('branches') - }) -}) - -describe('normalizeSmartMode', () => { - it('keeps a valid mode and snaps an unavailable one back to default', () => { - expect(normalizeSmartMode('gitlab', fullyAvailable)).toBe('gitlab') - expect(normalizeSmartMode('gitlab', { ...fullyAvailable, gitlabAvailable: false })).toBe( - 'smart' - ) - }) -}) diff --git a/mobile/src/tasks/mobile-task-copy-feedback-timer.test.ts b/mobile/src/tasks/mobile-task-copy-feedback-timer.test.ts index 687bb76f3ed..2f6f6d27bab 100644 --- a/mobile/src/tasks/mobile-task-copy-feedback-timer.test.ts +++ b/mobile/src/tasks/mobile-task-copy-feedback-timer.test.ts @@ -39,20 +39,6 @@ describe('mobile task copy feedback timer', () => { expect(timerRef.current).toBeNull() }) - it('replaces stale copy feedback timers', () => { - vi.useFakeTimers() - const timerRef = createTimerRef() - const copied = createCopiedKeyState('task:one') - - scheduleMobileTaskCopyFeedbackReset(timerRef, 'task:one', copied.setCopiedKey) - copied.setCopiedKey(() => 'task:two') - scheduleMobileTaskCopyFeedbackReset(timerRef, 'task:two', copied.setCopiedKey) - vi.runOnlyPendingTimers() - - expect(copied.value).toBeNull() - expect(timerRef.current).toBeNull() - }) - it('cancels pending copy feedback work', () => { vi.useFakeTimers() const timerRef = createTimerRef() diff --git a/mobile/src/tasks/mobile-task-sort.test.ts b/mobile/src/tasks/mobile-task-sort.test.ts deleted file mode 100644 index fd65884028d..00000000000 --- a/mobile/src/tasks/mobile-task-sort.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { TaskItem } from './mobile-tasks-project-workspace-types' -import type { RepoSummary } from './mobile-tasks-provider-detail-types' -import { sortMobileTaskItems } from './mobile-tasks-repository-presentation' - -vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme')) - -function task( - provider: TaskItem['provider'], - label: string, - updatedAt: string, - key: string -): TaskItem { - const source = - provider === 'linear' - ? { team: { id: label, name: label }, state: { color: '' } } - : provider === 'gitlabTodo' - ? { projectPath: label } - : { repoId: label, repoName: label } - return { provider, source, updatedAt, key, title: key, subtitle: '', status: '' } as TaskItem -} -const repos = new Map([ - ['alias', { id: 'alias', displayName: 'Álpha', path: '/repo' }] -]) -const items = [ - task('github', 'alias', '2026-01-01', 'a'), - task('gitlab', 'alpha', '2026-02-01', 'b'), - task('gitlabTodo', 'Zeta', 'invalid', 'c'), - task('linear', 'Älpha', '2026-02-01', 'd'), - task('github', 'alpha', '2026-02-01', 'e'), - task('linear', 'Zeta', '1970-01-01', 'f') -] - -describe('mobile task sorting', () => { - it.each(['repository', 'updated'] as const)('computes %s keys only once per item', (sort) => { - const parse = vi.spyOn(Date, 'parse') - const getRepo = vi.spyOn(repos, 'get') - const localeCompare = vi.spyOn(String.prototype, 'localeCompare') - try { - const before = [...items] - const actual = sortMobileTaskItems(items, sort, repos) - expect(actual.map((item) => item.key)).toEqual(['b', 'd', 'e', 'a', 'c', 'f']) - expect(items).toEqual(before) - expect(parse).toHaveBeenCalledTimes(items.length) - expect(getRepo).toHaveBeenCalledTimes(sort === 'repository' ? 3 : 0) - expect(localeCompare).not.toHaveBeenCalled() - } finally { - parse.mockRestore() - getRepo.mockRestore() - localeCompare.mockRestore() - } - }) - - it('skips setup for empty/singleton arrays while returning a fresh array', () => { - const parse = vi.spyOn(Date, 'parse') - const collator = vi.spyOn(Intl, 'Collator') - try { - expect(sortMobileTaskItems([], 'repository', repos)).toEqual([]) - const one = [items[0]] - expect(sortMobileTaskItems(one, 'repository', repos)).toEqual(one) - expect(sortMobileTaskItems(one, 'updated', repos)).not.toBe(one) - expect(parse).not.toHaveBeenCalled() - expect(collator).not.toHaveBeenCalled() - } finally { - parse.mockRestore() - collator.mockRestore() - } - }) -}) diff --git a/mobile/src/tasks/mobile-tasks-reviewer-linear.test.ts b/mobile/src/tasks/mobile-tasks-reviewer-linear.test.ts deleted file mode 100644 index 4fc2ce654e9..00000000000 --- a/mobile/src/tasks/mobile-tasks-reviewer-linear.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('./mobile-tasks-dependencies', () => import('../theme/mobile-theme')) -import { reconcileTeamSelection } from './mobile-tasks-reviewer-linear' -import type { LinearTeam } from './mobile-tasks-provider-detail-types' - -function team(id: string): LinearTeam { - return { id, name: id, key: id.toUpperCase() } -} - -describe('reconcileTeamSelection', () => { - it('selects every team for sticky-all', () => { - expect([...reconcileTeamSelection([team('a'), team('b')], null)]).toEqual(['a', 'b']) - }) - - it('keeps saved teams that still exist', () => { - expect([...reconcileTeamSelection([team('a'), team('b')], ['b'])]).toEqual(['b']) - }) - - // Older hosts may publish persisted selection as a string; keep that compatible. - it('reads a saved value of the wrong shape as sticky-all instead of throwing', () => { - expect([...reconcileTeamSelection([team('a'), team('b')], 'a')]).toEqual(['a', 'b']) - expect([...reconcileTeamSelection([team('a'), team('b')], { 0: 'a' })]).toEqual(['a', 'b']) - }) -}) diff --git a/mobile/src/tasks/sparse-preset-draft.test.ts b/mobile/src/tasks/sparse-preset-draft.test.ts index 852dd874f72..9fd7c493894 100644 --- a/mobile/src/tasks/sparse-preset-draft.test.ts +++ b/mobile/src/tasks/sparse-preset-draft.test.ts @@ -15,13 +15,6 @@ describe('parseSparsePresetDirectories', () => { }) }) - it('requires at least one directory', () => { - expect(parseSparsePresetDirectories(' \n ')).toEqual({ - directories: [], - error: 'Add at least one directory.' - }) - }) - it('rejects root and parent path entries', () => { expect(parseSparsePresetDirectories('.')).toEqual({ directories: [], diff --git a/mobile/src/tasks/task-item-comment-reply-schema.test.ts b/mobile/src/tasks/task-item-comment-reply-schema.test.ts deleted file mode 100644 index e37c4397b84..00000000000 --- a/mobile/src/tasks/task-item-comment-reply-schema.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { z } from 'zod' -import { - linearCommentWrittenSchema, - reviewThreadResolvedSchema, - taskCommentWrittenSchema -} from './task-item-comment-reply-schema' - -function reads(schema: z.ZodType, value: unknown): T { - const parsed = schema.safeParse(value) - if (!parsed.success) { - throw new Error(`expected a readable reply: ${parsed.error.message}`) - } - return parsed.data -} - -function refuses(schema: z.ZodType, value: unknown): boolean { - return !schema.safeParse(value).success -} - -describe('the five writes that answer with a comment', () => { - it('reads the representative GitHub, GitLab and review-reply envelopes unchanged', () => { - for (const comment of [ - { id: 902, author: 'You', body: 'a comment', createdAt: '2020-01-01T00:00:00.000Z' }, - { - id: 903, - author: 'You', - body: 'a reply', - createdAt: '2020-01-01T00:00:00.000Z', - path: 'src/index.ts', - line: 12, - threadId: 'thread-1' - } - ]) { - expect(reads(taskCommentWrittenSchema, { ok: true, comment }).comment).toMatchObject(comment) - } - }) - - it('keeps ok tri-state and leaves the refusal wording to the call site', () => { - expect(reads(taskCommentWrittenSchema, { ok: false }).error).toBeUndefined() - expect(reads(taskCommentWrittenSchema, { ok: false, error: 'no' }).error).toBe('no') - expect(reads(taskCommentWrittenSchema, {}).ok).toBeUndefined() - }) - - it('names a reply that is not the envelope, which main read members off', () => { - expect(refuses(taskCommentWrittenSchema, null)).toBe(true) - expect(refuses(taskCommentWrittenSchema, 'posted')).toBe(true) - }) -}) - -describe('the Linear comment write', () => { - it('reads the representative reply and leaves a missing id to the local echo', () => { - expect(reads(linearCommentWrittenSchema, { ok: true, id: 'comment-9' }).id).toBe('comment-9') - expect(reads(linearCommentWrittenSchema, { ok: true }).id).toBeUndefined() - expect(refuses(linearCommentWrittenSchema, null)).toBe(true) - }) -}) - -describe('resolving a review thread', () => { - it('keeps a real false, and names a reply that is not a boolean', () => { - expect(reads(reviewThreadResolvedSchema, true)).toBe(true) - expect(reads(reviewThreadResolvedSchema, false)).toBe(false) - expect(refuses(reviewThreadResolvedSchema, 'true')).toBe(true) - expect(refuses(reviewThreadResolvedSchema, undefined)).toBe(true) - }) -}) diff --git a/mobile/src/tasks/task-item-state-reply-schema.test.ts b/mobile/src/tasks/task-item-state-reply-schema.test.ts deleted file mode 100644 index 032ad6e2db8..00000000000 --- a/mobile/src/tasks/task-item-state-reply-schema.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { z } from 'zod' -import { - githubPullRequestChecksSchema, - githubPullRequestFileContentsSchema, - hostedIssueCreatedSchema, - linearIssueCreatedSchema, - linearIssueUpdatedSchema, - taskMutationConfirmationSchema -} from './task-item-state-reply-schema' - -function reads(schema: z.ZodType, value: unknown): T { - const parsed = schema.safeParse(value) - if (!parsed.success) { - throw new Error(`expected a readable reply: ${parsed.error.message}`) - } - return parsed.data -} - -function refuses(schema: z.ZodType, value: unknown): boolean { - return !schema.safeParse(value).success -} - -describe('creating an item', () => { - it('reads a GitHub issue create reply', () => { - const created = reads(hostedIssueCreatedSchema, { - ok: true, - number: 11, - url: 'https://github.com/owner/repo/issues/11' - }) - expect(created).toMatchObject({ ok: true, number: 11 }) - }) - - it('reads a number the composer would not have accepted as absent', () => { - expect(reads(hostedIssueCreatedSchema, { ok: true, number: '11' }).number).toBeUndefined() - }) - - it('leaves id and identifier to the Linear call site, which words that refusal itself', () => { - expect(reads(linearIssueCreatedSchema, { ok: true }).id).toBeUndefined() - expect( - reads(linearIssueCreatedSchema, { ok: true, id: 'issue-3', identifier: 'ENG-3' }).identifier - ).toBe('ENG-3') - expect(refuses(linearIssueCreatedSchema, null)).toBe(true) - }) -}) - -describe('the checks read', () => { - it('reads the representative reply and refuses a payload that is not a list', () => { - expect( - reads(githubPullRequestChecksSchema, [ - { name: 'build', status: 'COMPLETED', conclusion: 'SUCCESS', url: '' } - ]) - ).toHaveLength(1) - expect(refuses(githubPullRequestChecksSchema, { checks: [] })).toBe(true) - expect(refuses(githubPullRequestChecksSchema, null)).toBe(true) - }) -}) - -describe('the file-contents read', () => { - it('reads the representative reply, which is now the shape getPRFileContents returns', () => { - const recorded = { - original: 'a', - modified: 'b', - originalIsBinary: false, - modifiedIsBinary: false - } - expect(reads(githubPullRequestFileContentsSchema, recorded)).toEqual(recorded) - }) - - it('keeps the too-large flags a skipped side carries', () => { - const skipped = { original: '', modified: '', originalTooLarge: true, modifiedTooLarge: true } - expect(reads(githubPullRequestFileContentsSchema, skipped)).toMatchObject(skipped) - }) - - it('still names a payload that is not the container', () => { - expect(refuses(githubPullRequestFileContentsSchema, null)).toBe(true) - expect(refuses(githubPullRequestFileContentsSchema, 'a\nb')).toBe(true) - }) - - it('reads a payload carrying none of the six, because no member is required', () => { - expect(reads(githubPullRequestFileContentsSchema, {})).toEqual({}) - }) -}) - -describe('the two unread replies', () => { - it('reads anything for the Linear state write, whose body no call site looks at', () => { - expect(refuses(linearIssueUpdatedSchema, null)).toBe(false) - expect(refuses(linearIssueUpdatedSchema, 'accepted')).toBe(false) - }) -}) - -describe('the viewed-state confirmation', () => { - it('keeps a real false, which is the refusal the call site words', () => { - expect(reads(taskMutationConfirmationSchema, true)).toBe(true) - expect(reads(taskMutationConfirmationSchema, false)).toBe(false) - }) - - it('names a non-boolean instead of reading it as "not confirmed"', () => { - expect(refuses(taskMutationConfirmationSchema, 'true')).toBe(true) - expect(refuses(taskMutationConfirmationSchema, { ok: true })).toBe(true) - expect(refuses(taskMutationConfirmationSchema, null)).toBe(true) - }) -}) diff --git a/mobile/src/tasks/task-list-reply-schema.test.ts b/mobile/src/tasks/task-list-reply-schema.test.ts deleted file mode 100644 index d5b402de1ba..00000000000 --- a/mobile/src/tasks/task-list-reply-schema.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { z } from 'zod' -import { - githubWorkItemCountSchema, - gitlabTodoListSchema, - linearAccountConnectedSchema, - linearAccountStatusSchema, - taskRepoPreferenceWrittenSchema -} from './task-list-reply-schema' - -function reads(schema: z.ZodType, value: unknown): T { - const parsed = schema.safeParse(value) - if (!parsed.success) { - throw new Error(`expected a readable reply: ${parsed.error.message}`) - } - return parsed.data -} - -function refuses(schema: z.ZodType, value: unknown): boolean { - return !schema.safeParse(value).success -} - -describe('Linear account status', () => { - it('reads the representative reply, workspace row included', () => { - const status = reads(linearAccountStatusSchema, { - connected: true, - workspaces: [{ id: 'linear-workspace', name: 'Workspace' }], - selectedWorkspaceId: 'linear-workspace' - }) - expect(status.connected).toBe(true) - expect(status.workspaces?.[0]).toMatchObject({ id: 'linear-workspace', name: 'Workspace' }) - }) - - it('reads a disconnected host the same way every settings family records it', () => { - expect(reads(linearAccountStatusSchema, { connected: false }).connected).toBe(false) - }) - - it('names the null main read `connected` off, which the screen showed as its load error', () => { - expect(refuses(linearAccountStatusSchema, null)).toBe(true) - expect(refuses(linearAccountStatusSchema, 'connected')).toBe(true) - }) - - it('keeps an explicit selectedWorkspaceId null, which the ?? ladder is what interprets', () => { - const status = reads(linearAccountStatusSchema, { - connected: true, - selectedWorkspaceId: null, - activeWorkspaceId: null - }) - expect(status.selectedWorkspaceId).toBeNull() - expect(status.activeWorkspaceId).toBeNull() - }) - - it('drops only the workspace row with no id, which can be neither selected nor matched', () => { - expect(reads(linearAccountStatusSchema, { workspaces: [{ name: 'W' }] }).workspaces).toEqual([]) - expect( - reads(linearAccountStatusSchema, { workspaces: [{ id: 'w-1' }, { name: 'W' }] }).workspaces - ).toEqual([{ id: 'w-1' }]) - expect(reads(linearAccountStatusSchema, { workspaces: 'none' }).workspaces).toBeUndefined() - }) -}) - -describe('the GitHub item count', () => { - it('reads the representative number and names anything else', () => { - expect(reads(githubWorkItemCountSchema, 4)).toBe(4) - expect(refuses(githubWorkItemCountSchema, '4')).toBe(true) - expect(refuses(githubWorkItemCountSchema, { count: 4 })).toBe(true) - expect(refuses(githubWorkItemCountSchema, null)).toBe(true) - }) -}) - -describe('the GitLab to-do inbox', () => { - const RECORDED_TODO = { - id: 1, - actionName: 'review_requested', - targetType: 'Issue', - targetIid: 4, - targetTitle: 'A GitLab todo', - targetUrl: 'https://gitlab.example.com/group/project/-/issues/4', - projectPath: 'group/project', - authorUsername: 'octocat', - authorAvatarUrl: '', - updatedAt: '2020-01-01T00:00:00.000Z', - state: 'pending' - } - - it('reads the representative row through untouched, unread members included', () => { - expect(reads(gitlabTodoListSchema, [RECORDED_TODO])).toEqual([RECORDED_TODO]) - }) - - it('reads nullish as the empty inbox the call site already read', () => { - expect(reads(gitlabTodoListSchema, null)).toBeNull() - expect(reads(gitlabTodoListSchema, undefined)).toBeUndefined() - }) - - it('names a reply that is neither, which the screen showed as ".map is not a function"', () => { - expect(refuses(gitlabTodoListSchema, { todos: [] })).toBe(true) - expect(refuses(gitlabTodoListSchema, 'none')).toBe(true) - }) - - it('drops a row missing a member the screen reads with no guard', () => { - for (const key of ['id', 'actionName', 'targetUrl', 'projectPath', 'updatedAt']) { - const partial: Record = { ...RECORDED_TODO } - delete partial[key] - expect(reads(gitlabTodoListSchema, [partial, RECORDED_TODO])).toEqual([RECORDED_TODO]) - } - }) - - it('keeps a row whose guarded members are absent, because each has a fallback', () => { - const guarded: Record = { ...RECORDED_TODO } - for (const key of ['targetTitle', 'targetType', 'targetIid', 'authorUsername', 'state']) { - delete guarded[key] - } - expect(reads(gitlabTodoListSchema, [guarded])).toEqual([guarded]) - }) - - it('drops a malformed guarded member to absent rather than the whole row', () => { - const row = reads(gitlabTodoListSchema, [ - { ...RECORDED_TODO, targetIid: 'four', state: 'archived' } - ])?.[0] - expect(row).toMatchObject({ id: 1, actionName: 'review_requested' }) - expect(row?.targetIid).toBeUndefined() - expect(row?.state).toBeUndefined() - }) - - it('keeps an explicit targetIid null, which gitLabTodoTargetRef reads as no ref', () => { - expect( - reads(gitlabTodoListSchema, [{ ...RECORDED_TODO, targetIid: null }])?.[0]?.targetIid - ).toBe(null) - }) -}) - -describe('the two writes on this surface', () => { - it('reads the connect envelope and names a reply that is not one', () => { - expect(reads(linearAccountConnectedSchema, { ok: true }).ok).toBe(true) - expect(reads(linearAccountConnectedSchema, { ok: false, error: 'bad key' }).error).toBe( - 'bad key' - ) - expect(refuses(linearAccountConnectedSchema, null)).toBe(true) - }) - - it('reads anything for the repo preference write, whose body the screen never looks at', () => { - expect(refuses(taskRepoPreferenceWrittenSchema, null)).toBe(false) - expect(refuses(taskRepoPreferenceWrittenSchema, 'written')).toBe(false) - }) -}) diff --git a/mobile/src/tasks/task-provider-entity-reply-schema.test.ts b/mobile/src/tasks/task-provider-entity-reply-schema.test.ts deleted file mode 100644 index 7a46f2bca1d..00000000000 --- a/mobile/src/tasks/task-provider-entity-reply-schema.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { z } from 'zod' -import { - assignableUserListSchema, - detailCheckListSchema, - detailCommentListSchema, - detailFileListSchema, - reviewSummaryListSchema, - taskCommentWriteEnvelopeSchema, - taskMutationEnvelopeSchema -} from './task-provider-entity-reply-schema' - -function reads(schema: z.ZodType, value: unknown): T { - const parsed = schema.safeParse(value) - if (!parsed.success) { - throw new Error(`expected a readable reply: ${parsed.error.message}`) - } - return parsed.data -} - -function refuses(schema: z.ZodType, value: unknown): boolean { - return !schema.safeParse(value).success -} - -const COMMENT = { id: 902, author: 'You', body: 'a comment', createdAt: '2020-01-01T00:00:00.000Z' } - -describe('the mutation envelope', () => { - it('keeps ok tri-state, so absent is the success main read and false is a refusal', () => { - expect(reads(taskMutationEnvelopeSchema, {}).ok).toBeUndefined() - expect(reads(taskMutationEnvelopeSchema, { ok: true }).ok).toBe(true) - expect(reads(taskMutationEnvelopeSchema, { ok: false }).ok).toBe(false) - }) - - it('reads a non-boolean ok as absent, which is the success main read for it', () => { - expect(reads(taskMutationEnvelopeSchema, { ok: 'false' }).ok).toBeUndefined() - }) - - it('requires the container, which is the property read main died on', () => { - expect(refuses(taskMutationEnvelopeSchema, null)).toBe(true) - expect(refuses(taskMutationEnvelopeSchema, 'accepted')).toBe(true) - expect(refuses(taskMutationEnvelopeSchema, 7)).toBe(true) - }) - - it('drops an error that is not text, so the call site shows its own copy', () => { - expect(reads(taskMutationEnvelopeSchema, { ok: false, error: 'boom' }).error).toBe('boom') - expect( - reads(taskMutationEnvelopeSchema, { ok: false, error: { message: 'boom' } }).error - ).toBeUndefined() - }) - - it('passes members it does not declare straight through', () => { - expect(reads(taskMutationEnvelopeSchema, { ok: true, number: 11 })).toMatchObject({ - number: 11 - }) - }) -}) - -describe('a comment row', () => { - it('requires the id it is keyed by and the body it renders', () => { - expect(reads(detailCommentListSchema, [COMMENT])).toHaveLength(1) - expect(reads(detailCommentListSchema, [{ ...COMMENT, id: 'c-1' }])[0]?.id).toBe('c-1') - expect(reads(detailCommentListSchema, [{ ...COMMENT, id: undefined }])).toEqual([]) - expect(reads(detailCommentListSchema, [{ ...COMMENT, body: undefined }])).toEqual([]) - }) - - it('drops the unreadable row rather than the whole list', () => { - expect(reads(detailCommentListSchema, [COMMENT, { id: 1 }])).toHaveLength(1) - }) - - it('refuses a list that is not one', () => { - expect(refuses(detailCommentListSchema, { comments: [] })).toBe(true) - expect(refuses(detailCommentListSchema, 'none')).toBe(true) - }) - - it('forwards every provider reaction, including the two vocabularies mobile never declared', () => { - const github = [ - { content: '+1', count: 3 }, - { content: '-1', count: 1 }, - { content: 'heart', count: 1 } - ] - expect( - reads(detailCommentListSchema, [{ ...COMMENT, reactions: github }])[0]?.reactions - ).toEqual(github) - const gitlab = [{ name: 'thumbsup', count: 2 }] - expect( - reads(detailCommentListSchema, [{ ...COMMENT, reactions: gitlab }])[0]?.reactions - ).toMatchObject([{ count: 2 }]) - }) - - it('keeps the count the chip filters on and lets a malformed content read as absent', () => { - const row = reads(detailCommentListSchema, [ - { ...COMMENT, reactions: [{ content: 7, count: 2 }] } - ])[0] - expect(row?.reactions).toEqual([{ count: 2 }]) - expect( - reads(detailCommentListSchema, [{ ...COMMENT, reactions: [{ content: '+1' }] }])[0]?.reactions - ).toEqual([]) - }) - - it('leaves every guarded member exactly as the host sent it', () => { - const row = reads(detailCommentListSchema, [ - { ...COMMENT, path: 'src/a.ts', line: 12, threadId: 't-1', isResolved: false } - ])[0] - expect(row).toMatchObject({ path: 'src/a.ts', line: 12, threadId: 't-1', isResolved: false }) - }) -}) - -describe('the comment write envelope', () => { - it('drops a comment the timeline could not key, leaving the local echo in place', () => { - expect( - reads(taskCommentWriteEnvelopeSchema, { ok: true, comment: COMMENT }).comment - ).toMatchObject({ id: 902 }) - expect( - reads(taskCommentWriteEnvelopeSchema, { ok: true, comment: { id: 902 } }).comment - ).toBeUndefined() - expect(reads(taskCommentWriteEnvelopeSchema, { ok: true }).comment).toBeUndefined() - }) -}) - -describe('a user row', () => { - it('requires the login every reader trims, and keeps an explicit null beside it', () => { - const rows = reads(assignableUserListSchema, [ - { login: 'octocat', name: 'Octo', avatarUrl: null } - ]) - expect(rows[0]).toMatchObject({ login: 'octocat', name: 'Octo', avatarUrl: null }) - expect(reads(assignableUserListSchema, [{ name: 'Octo' }])).toEqual([]) - }) - - it('keeps a review row own null state rather than defaulting it', () => { - expect(reads(reviewSummaryListSchema, [{ login: 'octocat', state: null }])[0]?.state).toBeNull() - expect(reads(reviewSummaryListSchema, [{ state: 'APPROVED' }])).toEqual([]) - }) -}) - -describe('a check row and a file row', () => { - it('keeps the host casing the tasks surface actually sends', () => { - const checks = reads(detailCheckListSchema, [ - { name: 'build', status: 'COMPLETED', conclusion: 'SUCCESS', url: '' } - ]) - expect(checks[0]).toMatchObject({ name: 'build', status: 'COMPLETED', conclusion: 'SUCCESS' }) - }) - - it('drops a check with no name or no status', () => { - expect(reads(detailCheckListSchema, [{ status: 'completed' }])).toEqual([]) - expect(reads(detailCheckListSchema, [{ name: 'build' }])).toEqual([]) - }) - - it('requires the path a file row is matched by', () => { - expect(reads(detailFileListSchema, [{ path: 'src/a.ts' }])).toHaveLength(1) - expect(reads(detailFileListSchema, [{ oldPath: 'src/a.ts' }])).toEqual([]) - }) - - it('carries every file status the host will accept back and drops one it would refuse', () => { - for (const status of [ - 'added', - 'modified', - 'removed', - 'renamed', - 'copied', - 'changed', - 'unchanged' - ]) { - expect(reads(detailFileListSchema, [{ path: 'a', status }])[0]?.status).toBe(status) - } - // Absent status uses modified; forwarding an unknown arm would fail the host’s params validation. - expect(reads(detailFileListSchema, [{ path: 'a', status: 'ADDED' }])[0]?.status).toBeUndefined() - }) - - it('forwards a viewed state the host has and one this build predates', () => { - for (const viewerViewedState of ['DISMISSED', 'VIEWED', 'UNVIEWED', 'PENDING']) { - expect( - reads(detailFileListSchema, [{ path: 'a', viewerViewedState }])[0]?.viewerViewedState - ).toBe(viewerViewedState) - } - }) - - it('salvages a malformed viewed state to absent and keeps the row', () => { - const row = reads(detailFileListSchema, [{ path: 'a', viewerViewedState: { v: 'VIEWED' } }])[0] - expect(row?.path).toBe('a') - expect(row?.viewerViewedState).toBeUndefined() - }) -}) diff --git a/mobile/src/tasks/task-runtime-reply-schema.test.ts b/mobile/src/tasks/task-runtime-reply-schema.test.ts index ff9f8f92d6f..63e54afde4a 100644 --- a/mobile/src/tasks/task-runtime-reply-schema.test.ts +++ b/mobile/src/tasks/task-runtime-reply-schema.test.ts @@ -1,63 +1,11 @@ import { describe, expect, it } from 'vitest' import { taskLinearStatusSchema, - taskPreferenceWriteSchema, taskPreflightSchema, - taskRuntimeStatusSchema, taskUiStateSchema } from './task-runtime-reply-schema' -describe('the runtime status', () => { - it('reads the representative capability lists', () => { - for (const capabilities of [['mobile.tasks.v1'], ['files.mutation-ownership.v1']]) { - const parsed = taskRuntimeStatusSchema.safeParse({ capabilities }) - expect(parsed.success && parsed.data).toMatchObject({ capabilities }) - } - }) - - it('requires the container main read `.capabilities` off', () => { - expect(taskRuntimeStatusSchema.safeParse(null).success).toBe(false) - expect(taskRuntimeStatusSchema.safeParse('ok').success).toBe(false) - expect(taskRuntimeStatusSchema.safeParse({}).success).toBe(true) - }) - - it('drops a non-string capability, which `includes` could never have matched', () => { - const parsed = taskRuntimeStatusSchema.safeParse({ capabilities: ['push.v1', 7] }) - expect(parsed.success && parsed.data).toMatchObject({ capabilities: ['push.v1'] }) - }) - - it('leaves worktreeCreateIdempotency untouched in all four states the probe triages', () => { - for (const advertised of [undefined, null, 'nonsense', { dedupeTtlMs: 45_000 }]) { - const parsed = taskRuntimeStatusSchema.safeParse({ worktreeCreateIdempotency: advertised }) - expect(parsed.success).toBe(true) - expect(parsed.success ? parsed.data.worktreeCreateIdempotency : 'unparsed').toEqual( - advertised - ) - } - }) -}) - describe('the persisted UI state', () => { - it('answers the `ui` member, which is what the member reader it replaces did', () => { - const parsed = taskUiStateSchema.safeParse({ - ui: { sortBy: 'name', trustedOrcaHooks: { 'repo-1': { all: { approvedAt: 1 } } } } - }) - expect(parsed.success && parsed.data).toMatchObject({ - sortBy: 'name', - trustedOrcaHooks: { 'repo-1': { all: { approvedAt: 1 } } } - }) - }) - - it('reads the representative empty ui as an empty record, not as absent', () => { - const parsed = taskUiStateSchema.safeParse({ ui: {} }) - expect(parsed.success && parsed.data).toEqual({}) - }) - - it('answers undefined for a payload with no ui, where main read undefined off the object', () => { - const parsed = taskUiStateSchema.safeParse({}) - expect(parsed.success && parsed.data).toBeUndefined() - }) - it.each([null, undefined, 'ok', 7, [], true])( 'answers undefined for %j, so the other hydration legs survive an unreadable ui reply', (payload) => { @@ -69,28 +17,6 @@ describe('the persisted UI state', () => { }) describe('the two advisory probes', () => { - it('reads the representative preflight and linear replies', () => { - expect(taskPreflightSchema.safeParse({ glab: { installed: false } }).success).toBe(true) - expect(taskLinearStatusSchema.safeParse({ connected: false }).success).toBe(true) - }) - - it('requires nothing, because every consumer compares the leaf to `true`', () => { - expect(taskPreflightSchema.safeParse({}).success).toBe(true) - expect(taskLinearStatusSchema.safeParse({}).success).toBe(true) - }) - - it('drops a malformed glab rather than reading it as installed', () => { - const parsed = taskPreflightSchema.safeParse({ glab: 'yes' }) - expect(parsed.success ? parsed.data.glab : 'unparsed').toBeUndefined() - }) - - it('passes a host member no mobile consumer reads straight through', () => { - const parsed = taskPreflightSchema.safeParse({ gh: { installed: true, authenticated: true } }) - expect(parsed.success && parsed.data).toMatchObject({ - gh: { installed: true, authenticated: true } - }) - }) - // Advisory acceptance still decodes absent/null results; total readers must retain hydration defaults instead of throwing. it.each([ ['absent', undefined], @@ -106,11 +32,3 @@ describe('the two advisory probes', () => { expect(linear.success && linear.data.connected).toBeUndefined() }) }) - -describe('the three preference writes', () => { - it('accept every payload, because no call site reads their body', () => { - for (const reply of [null, undefined, 0, 'written', { ok: true }, []]) { - expect(taskPreferenceWriteSchema.safeParse(reply).success).toBe(true) - } - }) -}) diff --git a/mobile/src/tasks/use-host-repo-list.test.tsx b/mobile/src/tasks/use-host-repo-list.test.tsx index ad3ad51c6f5..85135329500 100644 --- a/mobile/src/tasks/use-host-repo-list.test.tsx +++ b/mobile/src/tasks/use-host-repo-list.test.tsx @@ -203,26 +203,6 @@ describe('useHostRepoList', () => { expect(probe.resource.state.status).toBe('idle') }) - // Keep resource/callback identities stable so consumer effects cannot form a render loop. - it('keeps a stable identity across renders that change nothing', async () => { - const probe = mountResource() - const first = probe.resource - probe.rerender() - expect(probe.resource).toBe(first) - expect(probe.resource.ensureLoaded).toBe(first.ensureLoaded) - expect(probe.resource.reload).toBe(first.reload) - - await act(async () => { - void probe.resource.ensureLoaded() - }) - await probe.settle(0, [{ id: 'a' }]) - expect(probe.resource.ensureLoaded).toBe(first.ensureLoaded) - expect(probe.resource.reload).toBe(first.reload) - const loaded = probe.resource - probe.rerender() - expect(probe.resource).toBe(loaded) - }) - it('re-reads the host on an explicit reload', async () => { const probe = mountResource() await act(async () => { diff --git a/mobile/src/tasks/work-item-lookup-text.test.ts b/mobile/src/tasks/work-item-lookup-text.test.ts deleted file mode 100644 index bd37f46d606..00000000000 --- a/mobile/src/tasks/work-item-lookup-text.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { isWorkItemLookupText } from './work-item-lookup-text' - -describe('isWorkItemLookupText', () => { - it('treats references as lookup text, not names', () => { - expect(isWorkItemLookupText('#42')).toBe(true) - expect(isWorkItemLookupText('https://github.com/o/r/issues/1')).toBe(true) - expect(isWorkItemLookupText('https://gitlab.com/g/p/-/merge_requests/2')).toBe(true) - expect(isWorkItemLookupText('https://linear.app/acme/issue/ENG-9')).toBe(true) - expect(isWorkItemLookupText('ENG-9')).toBe(false) - }) - - it('treats plain names as non-lookup text', () => { - expect(isWorkItemLookupText('')).toBe(false) - expect(isWorkItemLookupText('fix the login bug')).toBe(false) - expect(isWorkItemLookupText('https://linear.app/acme/project/mobile')).toBe(false) - }) -}) diff --git a/mobile/src/tasks/workspace-agent-selection.test.ts b/mobile/src/tasks/workspace-agent-selection.test.ts index 18202d5dc71..e07b16074a8 100644 --- a/mobile/src/tasks/workspace-agent-selection.test.ts +++ b/mobile/src/tasks/workspace-agent-selection.test.ts @@ -1,61 +1,8 @@ import { describe, expect, it } from 'vitest' -import { - normalizeWorkspaceAgent, - pickWorkspaceAgent, - resolveWorkspaceAgentSelection, - workspaceAgentLabel -} from './workspace-agent-selection' +import { resolveWorkspaceAgentSelection } from './workspace-agent-selection' describe('workspace agent selection', () => { - it('uses an installed explicit default agent', () => { - expect(pickWorkspaceAgent({ defaultTuiAgent: 'codex' }, new Set(['claude', 'codex']))).toBe( - 'codex' - ) - }) - - it('falls back by desktop auto-pick order when the default is unavailable on the target host', () => { - expect(pickWorkspaceAgent({ defaultTuiAgent: 'codex' }, new Set(['claude']))).toBe('claude') - }) - - it('skips disabled preferred and fallback agents', () => { - expect( - pickWorkspaceAgent( - { defaultTuiAgent: 'codex', disabledTuiAgents: ['codex'] }, - new Set(['claude', 'codex']) - ) - ).toBe('claude') - expect( - pickWorkspaceAgent( - { defaultTuiAgent: null, disabledTuiAgents: ['claude', 'codex', 'not-real'] }, - new Set(['claude', 'codex']) - ) - ).toBe('blank') - }) - - it('honors blank terminal as an explicit no-agent preference', () => { - expect(pickWorkspaceAgent({ defaultTuiAgent: 'blank' }, new Set(['claude', 'codex']))).toBe( - 'blank' - ) - }) - - it('returns blank when detection completed and no known agent exists', () => { - expect(pickWorkspaceAgent({ defaultTuiAgent: null }, new Set(['unknown-agent']))).toBe('blank') - }) - - it('uses the preferred/default display value while detection is still pending', () => { - expect(pickWorkspaceAgent({ defaultTuiAgent: 'codex' }, null)).toBe('codex') - expect(pickWorkspaceAgent({ defaultTuiAgent: null }, null)).toBe('claude') - expect( - pickWorkspaceAgent({ defaultTuiAgent: 'codex', disabledTuiAgents: ['codex'] }, null) - ).toBe('claude') - }) - - it('normalizes legacy blank sentinel and labels known choices', () => { - expect(normalizeWorkspaceAgent('__blank__')).toBe('blank') - expect(workspaceAgentLabel('codex')).toBe('Codex') - }) - it('keeps automatic selection current while create selection is active', () => { expect( resolveWorkspaceAgentSelection({ diff --git a/mobile/src/tasks/workspace-create-params.test.ts b/mobile/src/tasks/workspace-create-params.test.ts index 55989e9ded9..6f03031749c 100644 --- a/mobile/src/tasks/workspace-create-params.test.ts +++ b/mobile/src/tasks/workspace-create-params.test.ts @@ -1,18 +1,5 @@ import { describe, expect, it } from 'vitest' -import { startupAgentCreateFields, buildTaskWorkspaceCreateParams } from './workspace-create-params' - -describe('startupAgentCreateFields', () => { - it('sends startupAgent + createdWithAgent so the host resolves launch args', () => { - expect(startupAgentCreateFields('claude')).toEqual({ - startupAgent: 'claude', - createdWithAgent: 'claude' - }) - }) - - it('launches no agent when none was picked', () => { - expect(startupAgentCreateFields(undefined)).toEqual({}) - }) -}) +import { buildTaskWorkspaceCreateParams } from './workspace-create-params' describe('task workspace create params', () => { it('passes a GitHub PR URL as an agent draft and links the PR', () => { @@ -226,23 +213,4 @@ describe('task workspace create params', () => { // A stray linkedLinearIssue would relink the workspace to the wrong provider. expect(params).not.toHaveProperty('linkedLinearIssue') }) - - it('keeps a user-edited workspace name over the derived Jira name', () => { - expect( - buildTaskWorkspaceCreateParams({ - item: { - provider: 'jira', - source: { - key: 'ORCA-9', - title: 'Rename me', - url: 'https://acme.atlassian.net/browse/ORCA-9' - } - }, - targetRepoId: 'repo-jira', - setupDecision: 'inherit', - workspaceName: 'my-branch', - nameIsAutoManaged: false - }) - ).toMatchObject({ name: 'my-branch' }) - }) }) diff --git a/mobile/src/tasks/workspace-create-reply-schema.test.ts b/mobile/src/tasks/workspace-create-reply-schema.test.ts deleted file mode 100644 index 2d53178d91f..00000000000 --- a/mobile/src/tasks/workspace-create-reply-schema.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - agentLaunchCreateReceiptSchema, - worktreeCreateReceiptSchema, - worktreeHostedBaseSchema -} from './workspace-create-reply-schema' - -// Preserve receipt fields and keep empty ids and soft-error messages reachable. - -describe('the worktree create receipt', () => { - it('reads every representative create', () => { - for (const result of [ - { worktree: { id: 'wt-1', displayName: 'ORC-1 Recorded issue' } }, - { worktree: { id: 'wt-2' }, warning: 'shallow clone' }, - { worktree: { id: 'repo-1::/w' }, warning: ' startup terminal failed ' } - ]) { - expect(worktreeCreateReceiptSchema.safeParse(result)).toMatchObject({ success: true }) - } - }) - - it('keeps the warning untrimmed, because both readers trim it themselves', () => { - const parsed = worktreeCreateReceiptSchema.safeParse({ - worktree: { id: 'w' }, - warning: ' startup terminal failed ' - }) - expect(parsed.success && parsed.data).toMatchObject({ warning: ' startup terminal failed ' }) - }) - - it('leaves the empty-id arm reachable rather than making it a decode failure', () => { - const parsed = worktreeCreateReceiptSchema.safeParse({ worktree: { id: '' } }) - expect(parsed.success && parsed.data).toMatchObject({ worktree: { id: '' } }) - }) - - it('names a receipt with no worktree record, which routed the phone to /session/undefined', () => { - expect(worktreeCreateReceiptSchema.safeParse({ warning: 'x' }).success).toBe(false) - expect(worktreeCreateReceiptSchema.safeParse({ worktree: {} }).success).toBe(false) - expect(worktreeCreateReceiptSchema.safeParse(null).success).toBe(false) - }) -}) - -describe('the agent.launch receipt', () => { - it('reads the representative structured receipt whole', () => { - const result = { - outcome: { kind: 'structured', sessionId: 'sess-1', handle: 't-1' }, - worktreeId: 'repo-1::/w', - warning: ' startup terminal failed ', - receipt: { - mode: 'structured', - preferred: 'structured', - reason: 'user_default', - detail: 'Structured session created.' - } - } - expect(agentLaunchCreateReceiptSchema.safeParse(result)).toMatchObject({ - success: true, - data: result - }) - }) - - it('requires nothing under the container, because the reader guards every member', () => { - expect(agentLaunchCreateReceiptSchema.safeParse({}).success).toBe(true) - }) - - it('names a receipt that is not an object at all', () => { - for (const result of [null, 'launched', 7, true]) { - expect(agentLaunchCreateReceiptSchema.safeParse(result).success).toBe(false) - } - }) -}) - -describe('the hosted base resolvers', () => { - it('reads both representative successes', () => { - expect(worktreeHostedBaseSchema.safeParse({ baseBranch: 'main' }).success).toBe(true) - expect( - worktreeHostedBaseSchema.safeParse({ baseBranch: 'main', compareBaseRef: 'origin/main' }) - .success - ).toBe(true) - }) - - it('preserves a soft error beside a base branch', () => { - const parsed = worktreeHostedBaseSchema.safeParse({ - error: 'pull request not found', - baseBranch: 'main' - }) - expect(parsed.success && parsed.data).toMatchObject({ error: 'pull request not found' }) - }) - - it('keeps an empty soft-error message, which the create replaces with its own copy', () => { - const parsed = worktreeHostedBaseSchema.safeParse({ error: '' }) - expect(parsed.success && parsed.data).toMatchObject({ error: '' }) - }) - - it('forwards the rest of a start point the create spreads into its params', () => { - const parsed = worktreeHostedBaseSchema.safeParse({ - baseBranch: 'main', - pushTarget: { remoteName: 'origin', branchName: 'feature' }, - branchNameOverride: 'pr-12', - maintainerCanModify: false - }) - expect(parsed.success && parsed.data).toMatchObject({ - pushTarget: { remoteName: 'origin', branchName: 'feature' }, - branchNameOverride: 'pr-12', - maintainerCanModify: false - }) - }) - - it('names a reply that is neither arm, where `in` was a TypeError', () => { - expect(worktreeHostedBaseSchema.safeParse({}).success).toBe(false) - expect(worktreeHostedBaseSchema.safeParse('main').success).toBe(false) - expect(worktreeHostedBaseSchema.safeParse(null).success).toBe(false) - }) -}) diff --git a/mobile/src/tasks/workspace-ssh-gate.test.ts b/mobile/src/tasks/workspace-ssh-gate.test.ts index 6f5ed54d94f..4725c6c11ad 100644 --- a/mobile/src/tasks/workspace-ssh-gate.test.ts +++ b/mobile/src/tasks/workspace-ssh-gate.test.ts @@ -1,27 +1,7 @@ import { describe, expect, it } from 'vitest' -import { - deriveWorkspaceSshGate, - workspaceSshStatusLabel, - type WorkspaceSshRecord -} from './workspace-ssh-gate' +import { deriveWorkspaceSshGate, type WorkspaceSshRecord } from './workspace-ssh-gate' describe('workspace SSH gate', () => { - it('does not gate local repositories', () => { - expect( - deriveWorkspaceSshGate({ - connectionId: null, - state: null, - connecting: false - }) - ).toEqual({ - status: null, - requiresConnection: false, - connectInProgress: false, - error: null, - needsDesktopServerRecovery: false - }) - }) - it('requires connection for remote repos until the matching target is connected', () => { expect( deriveWorkspaceSshGate({ @@ -56,38 +36,6 @@ describe('workspace SSH gate', () => { }) }) - it('marks connecting, relay deploy, and reconnect states as in progress', () => { - for (const status of ['connecting', 'deploying-relay', 'reconnecting'] as const) { - expect( - deriveWorkspaceSshGate({ - connectionId: 'ssh-1', - state: { targetId: 'ssh-1', status, error: null, reconnectAttempt: 0 }, - connecting: false - }) - ).toMatchObject({ requiresConnection: true, connectInProgress: true }) - } - }) - - it('keeps auth and relay errors visible in the drawer', () => { - expect( - deriveWorkspaceSshGate({ - connectionId: 'ssh-1', - state: { - targetId: 'ssh-1', - status: 'auth-failed', - error: 'Permission denied', - reconnectAttempt: 0 - }, - connecting: false - }) - ).toMatchObject({ - status: 'auth-failed', - requiresConnection: true, - connectInProgress: false, - error: 'Permission denied' - }) - }) - it('asks for the desktop recovery only for the refusal the desktop offers it on', () => { const named = 'run `orcad --reclaim-stale-lock --data-root /home/dev/.orca` there' const gate = (managedServer: WorkspaceSshRecord['managedServer']) => @@ -104,11 +52,4 @@ describe('workspace SSH gate', () => { expect(gate({ ...refused, kind: 'relay' })).toBe(false) expect(gate({ ...refused, serving: { detail: named } })).toBe(false) }) - - it('labels user-visible SSH states', () => { - expect(workspaceSshStatusLabel(null)).toBe('Disconnected') - expect(workspaceSshStatusLabel('deploying-relay')).toBe('Deploying relay') - expect(workspaceSshStatusLabel('auth-failed')).toBe('Authentication failed') - expect(workspaceSshStatusLabel('connected')).toBe('Connected') - }) }) diff --git a/mobile/src/terminal/document/document-frame-registry.test.ts b/mobile/src/terminal/document/document-frame-registry.test.ts deleted file mode 100644 index dd874a61408..00000000000 --- a/mobile/src/terminal/document/document-frame-registry.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it, vi } from 'vitest' -import { createTerminalDocumentScope } from './document-scope' -import { cancelDocumentFrames, scheduleDocumentFrame } from './document-frame-registry' - -// Disposal can call back into document modules; cancellation must remove pending frames and refuse new ones. -describe('the document frame registry', () => { - it('holds a frame until it runs, then forgets it', () => { - const scope = createTerminalDocumentScope() - const frames: FrameRequestCallback[] = [] - vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation((callback) => { - frames.push(callback) - return frames.length - }) - - const callback = vi.fn() - const id = scheduleDocumentFrame(scope, callback) - expect(callback).not.toHaveBeenCalled() - expect(scope.scheduledFrames).toEqual([id]) - frames[0]!(123) - expect(callback).toHaveBeenCalledExactlyOnceWith(123) - expect(scope.scheduledFrames).toEqual([]) - vi.restoreAllMocks() - }) - - it('takes back every pending frame and then refuses to schedule', () => { - const scope = createTerminalDocumentScope() - const cancelled: number[] = [] - let next = 0 - vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation(() => { - next += 1 - return next - }) - vi.spyOn(globalThis, 'cancelAnimationFrame').mockImplementation((id) => cancelled.push(id)) - - const first = scheduleDocumentFrame(scope, () => {}) - const second = scheduleDocumentFrame(scope, () => {}) - cancelDocumentFrames(scope) - expect(cancelled).toEqual([first, second]) - expect(scope.scheduledFrames).toEqual([]) - - const requests = vi.mocked(globalThis.requestAnimationFrame).mock.calls.length - expect(scheduleDocumentFrame(scope, () => {})).toBe(-1) - expect(vi.mocked(globalThis.requestAnimationFrame).mock.calls.length).toBe(requests) - expect(scope.scheduledFrames).toEqual([]) - vi.restoreAllMocks() - }) - - it('refuses for good, and the next document starts from a scope that does not know', () => { - const scope = createTerminalDocumentScope() - vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation(() => 7) - vi.spyOn(globalThis, 'cancelAnimationFrame').mockImplementation(() => {}) - - cancelDocumentFrames(scope) - expect(scope.framesStopped).toBe(true) - // Stopped scopes never restart; a new document gets a fresh scope. - const next = createTerminalDocumentScope() - expect(next.framesStopped).toBe(false) - expect(scheduleDocumentFrame(next, () => {})).toBe(7) - expect(next.scheduledFrames).toEqual([7]) - vi.restoreAllMocks() - }) -}) diff --git a/mobile/src/terminal/document/document-host-root.test.ts b/mobile/src/terminal/document/document-host-root.test.ts index 72bc8ea13f1..07d6f366036 100644 --- a/mobile/src/terminal/document/document-host-root.test.ts +++ b/mobile/src/terminal/document/document-host-root.test.ts @@ -122,23 +122,6 @@ describe('two terminal documents on one page', () => { two.started.stop() }) - // The same event inside this host must still reach it, ruling out an inert dispatcher. - it('cancels its own selection when the two fingers land in its own host', () => { - const first = plantHost('first-host') - const second = plantHost('second-host') - const one = startDocumentIn(first) - const two = startDocumentIn(second) - selectAllInBoth(one, two) - - fireTwoFingerTouchStart(surfaceOf(first)) - - expect(pinchCancels(one.posted)).toHaveLength(1) - expect(pinchCancels(two.posted)).toHaveLength(0) - - one.started.stop() - two.started.stop() - }) - // Event ownership is not enough: page-wide touches must also exclude fingers in the other terminal. it("does not read another host's finger as its own second one", () => { const first = plantHost('first-host') @@ -278,20 +261,6 @@ describe('keyboard-avoidance metrics across a pinch', () => { doc.started.stop() }) - it('reports a release that changes the preset once, through the refit', async () => { - const doc = startMeasuredDocument() - await settle() - const before = metricsOf(doc.posted).length - - pinchTo(doc, 30) - const afterWrite = metricsOf(doc.posted).length - await settle() - - expect(afterWrite).toBe(before + 1) - expect(metricsOf(doc.posted).length).toBe(afterWrite + 1) - doc.started.stop() - }) - it('never reports the pre-refit pitch when a release lands while a refit is pending', async () => { const doc = startMeasuredDocument() await settle() diff --git a/mobile/src/terminal/document/document-parse-time-effects.test.ts b/mobile/src/terminal/document/document-parse-time-effects.test.ts deleted file mode 100644 index d272ec0ba8b..00000000000 --- a/mobile/src/terminal/document/document-parse-time-effects.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - documentModuleNames, - documentModuleSource, - exportedLifecycleFunctions, - parseTimeEffects, - sequenceCalls, - topLevelDeclarationsReachAnElement -} from '../../test-support/webview-document-census' - -// Module-level effects would bind mounts before lifecycle startup and evade stop; require declarations with inert initializers. -// Factory-local state declarations remain safe because each document call gets fresh bindings. -const DIRECTORY = import.meta.dirname - -const ENTRY = 'native-document-entry' - -const THE_SEQUENCE = 'create-terminal-document' - -const MODULES = documentModuleNames(DIRECTORY, [ENTRY]) - -const moduleSource = (name: string) => documentModuleSource(DIRECTORY, name) - -const sequenceCallsTo = (functionName: string) => - sequenceCalls(moduleSource(THE_SEQUENCE), functionName, [ - 'startTerminalDocument', - 'stopTerminalDocument' - ]) - -describe('the document modules at parse time', () => { - it('do no work: every effect is in a start function the hosts call', () => { - expect(MODULES.length).toBeGreaterThan(30) - expect(MODULES.flatMap((name) => parseTimeEffects(name, moduleSource(name)))).toEqual([]) - }) - - it('declare nothing that reaches an element', () => { - // Element reads in declaration initializers are still effects; check every module. - for (const name of MODULES) { - expect({ - name, - reaches: topLevelDeclarationsReachAnElement(name, moduleSource(name)) - }).toEqual({ name, reaches: false }) - } - }) - - it('start and stop: the sequence calls every one there is, and undoes them in reverse', () => { - // Compare start/stop names, not counts, so exported-but-unused lifecycle hooks cannot pass. - // stopEdgeScroll is owned by stopSelectionOverlay rather than the top-level sequence. - const exported = (keyword: 'start' | 'stop') => - MODULES.filter((name) => name !== THE_SEQUENCE).flatMap((name) => - exportedLifecycleFunctions(moduleSource(name), keyword, 'TerminalDocumentScope') - ) - - const started = sequenceCallsTo('startTerminalDocument') - const stopped = sequenceCallsTo('stopTerminalDocument').filter( - (name) => name !== 'cancelDocumentFrames' - ) - expect([...started].sort()).toEqual(exported('start').sort()) - expect([...stopped].sort()).toEqual( - exported('stop') - .filter((name) => name !== 'stopEdgeScroll') - .sort() - ) - - const paired = started.filter((name) => stopped.includes(name.replace(/^start/, 'stop'))) - expect(paired.map((name) => name.replace(/^start/, 'stop'))).toEqual( - stopped.filter((name) => paired.includes(name.replace(/^stop/, 'start'))).toReversed() - ) - expect(sequenceCallsTo('stopTerminalDocument').at(-1)).toBe('cancelDocumentFrames') - }) -}) diff --git a/mobile/src/terminal/document/laid-out-cell-box.test.ts b/mobile/src/terminal/document/laid-out-cell-box.test.ts index 4014e661afd..6b88bde535b 100644 --- a/mobile/src/terminal/document/laid-out-cell-box.test.ts +++ b/mobile/src/terminal/document/laid-out-cell-box.test.ts @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import { afterEach, describe, expect, it, vi } from 'vitest' -import { laidOutCellBox, reportLaidOutCellBox } from './laid-out-cell-box' +import { reportLaidOutCellBox } from './laid-out-cell-box' import { createTerminalDocumentScope, type TerminalDocumentScope } from './document-scope' import { startTerminalDocument, stopTerminalDocument } from './create-terminal-document' import type { TerminalDocumentHost } from './document-host-seams' @@ -31,15 +31,6 @@ describe('laidOutCellBox', () => { return scope } - it('reads the box xterm laid out at the current text scale, with its grid', () => { - const scope = scopeWithCell({ width: 29 / 3, height: 21 }, 16) - expect(laidOutCellBox(scope)).toEqual({ - cellBox: { fontScale: 1.25, cellWidth: 29 / 3, cellHeight: 21 }, - cols: 55, - rows: 47 - }) - }) - it('tells the host each new box once, and refits only a box that changed at a kept grid', () => { const posted: Record[] = [] const cell = { width: 29 / 3, height: 21 } @@ -125,41 +116,6 @@ describe('a started document', () => { const reflowTo = (scope: TerminalDocumentScope, cols: number) => handleMsg(scope, { type: 'reflow', cols, rows: 47 }) - it('takes the frame the app laid out from init, resize and reflow', () => { - const { scope } = started() - try { - handleMsg(scope, { - type: 'init', - cols: 55, - rows: 47, - initialData: '', - preserveScroll: false, - frame: { width: 427.5, height: 710 } - }) - expect(scope.hostFrame).toEqual({ width: 427.5, height: 710 }) - handleMsg(scope, { type: 'resize', cols: 54, rows: 47, frame: { width: 420, height: 700 } }) - expect(scope.hostFrame).toEqual({ width: 420, height: 700 }) - handleMsg(scope, { type: 'reflow', cols: 53, rows: 46, frame: { width: 410, height: 690 } }) - expect(scope.hostFrame).toEqual({ width: 410, height: 690 }) - } finally { - stopTerminalDocument(scope) - } - }) - - it('reports ready with the box its own terminal laid out, at the app text scale', () => { - const { scope, posted, built } = started({ start: () => ({ textScale: 1.25, shown: true }) }) - try { - expect(built).toHaveLength(1) - expect(built[0].options.fontSize).toBe(16) - expect(posted[0]).toEqual({ - type: 'web-ready', - cellBox: { fontScale: 1.25, cellWidth: (23 / 3) * (16 / 13), cellHeight: 15 * (16 / 13) } - }) - } finally { - stopTerminalDocument(scope) - } - }) - it('leaves no live terminal when opening the one it builds before ready throws', () => { const double = terminalDocumentDouble() double.terminal.open = () => { @@ -185,21 +141,6 @@ describe('a started document', () => { } }) - it('reuses that terminal for the first init, so an open builds one xterm', async () => { - const { scope, posted, built, init } = started() - try { - const prepared = scope.term - init() - await untilReady(posted) - expect(built).toHaveLength(1) - expect(scope.term).toBe(prepared) - expect(scope.term?.cols).toBe(55) - expect(scope.term?.rows).toBe(47) - } finally { - stopTerminalDocument(scope) - } - }) - it('keeps the terminal built before ready out of sight until the first init has replayed', async () => { const { scope, posted, init } = started() try { @@ -254,19 +195,6 @@ describe('a started document', () => { } }) - it('reports a changed cell width on the next render', async () => { - const { scope, cell, posted, render, init } = started() - try { - init() - await untilReady(posted) - cell.width = 7.8 - render() - expect(boxes(posted).at(-1)).toEqual({ fontScale: 1, cellWidth: 7.8, cellHeight: 15 }) - } finally { - stopTerminalDocument(scope) - } - }) - it("refits a DOM first init once, and not again on the refit's own report", async () => { const { scope, cell, posted, render, init } = started() try { @@ -283,42 +211,6 @@ describe('a started document', () => { } }) - it('never refits a box that came with a new grid, so the DOM renderer cannot loop', async () => { - const { scope, cell, posted, render, init } = started() - try { - init() - await untilReady(posted) - for (const [cols, width] of [ - [50, 7.9], - [55, 7.8], - [54, 8] - ]) { - cell.width = width - reflowTo(scope, cols) - render() - } - expect(refits(posted)).toEqual([false, false, false]) - } finally { - stopTerminalDocument(scope) - } - }) - - it('refits a renderer swap at a grid applied in place', async () => { - const { scope, cell, posted, render, init } = started() - try { - init() - await untilReady(posted) - reflowTo(scope, 50) - render() - expect(refits(posted)).toEqual([]) - cell.width = 7.8 - render() - expect(refits(posted)).toEqual([true]) - } finally { - stopTerminalDocument(scope) - } - }) - it('refits a re-init at the same grid with a different renderer', async () => { const { scope, cell, posted, init } = started() try { diff --git a/mobile/src/terminal/document/message-bridge-fonts.test.ts b/mobile/src/terminal/document/message-bridge-fonts.test.ts index 2aed18fc06d..52572b997b1 100644 --- a/mobile/src/terminal/document/message-bridge-fonts.test.ts +++ b/mobile/src/terminal/document/message-bridge-fonts.test.ts @@ -154,15 +154,6 @@ describe('the terminal waits for its bundled glyphs', () => { stopMessageBridge(fonts.scope) }) - it('still starts the terminal if font decoding fails', async () => { - const fonts = pendingFonts() - startMessageBridge(fonts.scope) - fonts.fail() - await fonts.loaded.catch(() => {}) - expect(fonts.postToHost).toHaveBeenCalledWith({ type: 'web-ready', cellBox: null }) - stopMessageBridge(fonts.scope) - }) - it('unwinds the document and reports an error if deferred startup fails', async () => { const fonts = pendingFonts() document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP @@ -186,13 +177,4 @@ describe('the terminal waits for its bundled glyphs', () => { message: expect.stringContaining('readiness transport failed') }) }) - - it('does not revive a document stopped during the font load', async () => { - const fonts = pendingFonts() - startMessageBridge(fonts.scope) - stopMessageBridge(fonts.scope) - fonts.finish() - await fonts.loaded - expect(fonts.postToHost).not.toHaveBeenCalled() - }) }) diff --git a/mobile/src/terminal/document/native-document-bundle.test.ts b/mobile/src/terminal/document/native-document-bundle.test.ts index 2e00a9d0781..a253e26dec5 100644 --- a/mobile/src/terminal/document/native-document-bundle.test.ts +++ b/mobile/src/terminal/document/native-document-bundle.test.ts @@ -152,25 +152,6 @@ describe('the bundled native document', () => { expect(document.getElementById('terminal-surface')?.contains(opened[0]!)).toBe(true) }) - it('answers a ping through the bridge, which is what native readiness reads', () => { - document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP - const posted: Record[] = [] - const { Terminal } = engineDouble() - Object.assign(globalThis, { - ReactNativeWebView: { - postMessage: (message: string) => posted.push(JSON.parse(message)) - }, - Terminal, - __engineErrors: [] - }) - evaluateBundle() - - window.dispatchEvent( - new MessageEvent('message', { data: JSON.stringify({ type: 'ping', id: 9 }) }) - ) - expect(posted).toContainEqual({ type: 'pong', pingId: 9 }) - }) - it('takes a theme and a write before init, and init is what decides they are stale', async () => { // Early writes must be superseded by init’s snapshot and theme, not replayed underneath it. document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP diff --git a/mobile/src/terminal/mock-server-terminal-stream-cancellation.test.ts b/mobile/src/terminal/mock-server-terminal-stream-cancellation.test.ts index 26a06c9411d..e7b4f7fe90c 100644 --- a/mobile/src/terminal/mock-server-terminal-stream-cancellation.test.ts +++ b/mobile/src/terminal/mock-server-terminal-stream-cancellation.test.ts @@ -1,28 +1,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { WebSocket } from 'ws' -import { handleMockTerminalRequest } from '../../scripts/mock-server-terminal-stream' import { handleRequest, type RpcRequest, - type RpcRespond, type RpcResponse } from '../../scripts/mock-server-rpc-handlers' -type DeferredResponse = { - response: RpcResponse - shouldSend?: () => boolean -} - -function success(id: string, result: unknown, streaming?: boolean): RpcResponse { - return { - id, - ok: true, - result, - ...(streaming ? { streaming: true as const } : {}), - _meta: { runtimeId: 'test' } - } -} - function request(id: string, method: string): RpcRequest { return { id, method, params: { terminal: 'term-1', viewport: { cols: 80, rows: 24 } } } } @@ -33,31 +16,6 @@ describe('mock terminal stream cancellation', () => { vi.unstubAllEnvs() }) - it('invalidates delayed frames after resubscribe and unsubscribe', () => { - vi.useFakeTimers() - const ws = { OPEN: 1, readyState: 1 } as unknown as WebSocket - const deferred: DeferredResponse[] = [] - const respond: RpcRespond = (response, shouldSend) => { - deferred.push({ response, shouldSend }) - } - const handle = (rpcRequest: RpcRequest) => - handleMockTerminalRequest(rpcRequest, respond, success, ws, () => 'wt') - - expect(handle(request('old', 'terminal.subscribe'))).toBe(true) - vi.advanceTimersByTime(500) - expect(deferred.filter(({ response }) => response.id === 'old')).toHaveLength(2) - - expect(handle(request('new', 'terminal.subscribe'))).toBe(true) - const oldResponses = deferred.filter(({ response }) => response.id === 'old') - const newResponses = deferred.filter(({ response }) => response.id === 'new') - expect(newResponses).toHaveLength(1) - expect(oldResponses.every(({ shouldSend }) => shouldSend?.() === false)).toBe(true) - expect(newResponses.every(({ shouldSend }) => shouldSend?.() === true)).toBe(true) - - expect(handle(request('stop', 'terminal.unsubscribe'))).toBe(true) - expect(newResponses.every(({ shouldSend }) => shouldSend?.() === false)).toBe(true) - }) - it('drops queued delayed frames after stream cancellation', () => { vi.useFakeTimers() vi.stubEnv('MOCK_RPC_DELAY_TERMINAL_SUBSCRIBE_MS', '1000') diff --git a/mobile/src/terminal/terminal-auto-restore-fit-state.test.ts b/mobile/src/terminal/terminal-auto-restore-fit-state.test.ts index 1b942283184..ebd5588d29a 100644 --- a/mobile/src/terminal/terminal-auto-restore-fit-state.test.ts +++ b/mobile/src/terminal/terminal-auto-restore-fit-state.test.ts @@ -1,8 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { readTerminalAutoRestoreFitMs, - saveTerminalAutoRestoreFitMs, - setTerminalAutoRestoreFitMsForHost + saveTerminalAutoRestoreFitMs } from './terminal-auto-restore-fit-state' describe('terminal auto restore fit state', () => { @@ -35,19 +34,4 @@ describe('terminal auto restore fit state', () => { await expect(readTerminalAutoRestoreFitMs({ sendRequest })).resolves.toBeNull() await expect(saveTerminalAutoRestoreFitMs({ sendRequest }, 60_000)).resolves.toBeNull() }) - - it('returns the existing state object when a host value is unchanged', () => { - const current = { hostA: 60_000, hostB: null } - - expect(setTerminalAutoRestoreFitMsForHost(current, 'hostA', 60_000)).toBe(current) - expect(setTerminalAutoRestoreFitMsForHost(current, 'hostB', null)).toBe(current) - }) - - it('updates one host while preserving other host values', () => { - const current = { hostA: 60_000, hostB: null } - const next = setTerminalAutoRestoreFitMsForHost(current, 'hostA', 300_000) - - expect(next).not.toBe(current) - expect(next).toEqual({ hostA: 300_000, hostB: null }) - }) }) diff --git a/mobile/src/terminal/terminal-caret-rendering-oracle.test.ts b/mobile/src/terminal/terminal-caret-rendering-oracle.test.ts deleted file mode 100644 index 10719bb35d4..00000000000 --- a/mobile/src/terminal/terminal-caret-rendering-oracle.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -// @vitest-environment happy-dom -import { Terminal, type ITerminalInitOnlyOptions, type ITerminalOptions } from '@xterm/xterm' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { MOBILE_TERMINAL_CARET_OPTIONS } from './terminal-webview-html' - -type CursorCoreService = { - isCursorHidden: boolean - isCursorInitialized: boolean -} - -type ListenerOwner = Pick - -function cursorCoreService(terminal: Terminal): CursorCoreService { - const core = (terminal as unknown as { _core?: { coreService?: CursorCoreService } })._core - expect(core, 'xterm private _core compatibility').toBeDefined() - expect(core?.coreService, 'xterm private coreService compatibility').toBeDefined() - expect(typeof core?.coreService?.isCursorHidden).toBe('boolean') - expect(typeof core?.coreService?.isCursorInitialized).toBe('boolean') - return core!.coreService! -} - -function listenerOwner(target: EventTarget): ListenerOwner { - let owner = target as ListenerOwner | null - while (owner) { - if (Object.hasOwn(owner, 'addEventListener') && Object.hasOwn(owner, 'removeEventListener')) { - return owner - } - owner = Object.getPrototypeOf(owner) as ListenerOwner | null - } - throw new Error(`No event-listener owner for ${target.constructor.name}`) -} - -function eventListenerOwners(): ListenerOwner[] { - const targets: EventTarget[] = [ - document, - document.defaultView!, - document.documentElement, - document.body, - document.createElement('div'), - document.createElement('textarea'), - document.createElement('canvas') - ] - return [...new Set(targets.map(listenerOwner))] -} - -function trackEventListenerCleanup(): () => { - added: number - removed: number - unreleased: string[] -} { - const registrations: Array<{ - capture: boolean - listener: EventListenerOrEventListenerObject - removed: boolean - target: EventTarget - type: string - }> = [] - const capture = (options?: boolean | AddEventListenerOptions | EventListenerOptions): boolean => - typeof options === 'boolean' ? options : (options?.capture ?? false) - const activeRegistration = ( - target: EventTarget, - type: string, - listener: EventListenerOrEventListenerObject | null, - options?: boolean | AddEventListenerOptions | EventListenerOptions - ) => - registrations.find( - (entry) => - !entry.removed && - entry.target === target && - entry.type === type && - entry.listener === listener && - entry.capture === capture(options) - ) - - for (const owner of eventListenerOwners()) { - const addEventListener = owner.addEventListener - const removeEventListener = owner.removeEventListener - vi.spyOn(owner, 'addEventListener').mockImplementation(function ( - this: EventTarget, - type: string, - listener: EventListenerOrEventListenerObject | null, - options?: boolean | AddEventListenerOptions - ) { - addEventListener.call(this, type, listener, options) - if (listener && !activeRegistration(this, type, listener, options)) { - registrations.push({ - capture: capture(options), - listener, - removed: false, - target: this, - type - }) - } - }) - vi.spyOn(owner, 'removeEventListener').mockImplementation(function ( - this: EventTarget, - type: string, - listener: EventListenerOrEventListenerObject | null, - options?: boolean | EventListenerOptions - ) { - removeEventListener.call(this, type, listener, options) - const registration = listener && activeRegistration(this, type, listener, options) - if (registration) { - registration.removed = true - } - }) - } - - return () => ({ - added: registrations.length, - removed: registrations.filter((registration) => registration.removed).length, - unreleased: registrations - .filter((registration) => !registration.removed) - .map((registration) => registration.type) - }) -} - -function write(terminal: Terminal, data: string): Promise { - return new Promise((resolve) => terminal.write(data, resolve)) -} - -describe('xterm caret rendering oracle', () => { - beforeEach(() => { - vi.stubGlobal( - 'OffscreenCanvas', - class { - getContext(): Pick { - return { font: '', measureText: () => ({ width: 8 }) as TextMetrics } - } - } - ) - }) - - afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() - }) - - it('renders and hides an unfocused main-buffer caret', async () => { - const listenerCleanup = trackEventListenerCleanup() - const options: ITerminalOptions & ITerminalInitOnlyOptions = MOBILE_TERMINAL_CARET_OPTIONS - const terminal = new Terminal(options) - const container = document.createElement('div') - document.body.append(container) - - try { - terminal.open(container) - await vi.waitFor(() => expect(cursorCoreService(terminal).isCursorInitialized).toBe(true)) - await write(terminal, '\x1b[?25h\x1b[2K\x1b[1G> hello\x1b[?2004h\x1b[1;3H') - terminal.refresh(0, terminal.rows - 1) - await vi.waitFor(() => expect(container.textContent).toContain('hello')) - const coreService = cursorCoreService(terminal) - expect({ - initialized: coreService.isCursorInitialized, - rendered: container.querySelector('.xterm-cursor') !== null - }).toEqual({ initialized: true, rendered: true }) - - await write(terminal, '\x1b[?25l') - terminal.refresh(0, terminal.rows - 1) - await vi.waitFor(() => expect(container.querySelector('.xterm-cursor')).toBeNull()) - expect({ - hidden: coreService.isCursorHidden, - rendered: container.querySelector('.xterm-cursor') !== null - }).toEqual({ hidden: true, rendered: false }) - } finally { - // Teardown only: assertions here could mask the body failure and strand the container. - terminal.dispose() - container.remove() - } - - expect(container.querySelector('.xterm')).toBeNull() - const cleanup = listenerCleanup() - expect(cleanup.added).toBeGreaterThan(0) - expect(cleanup.removed).toBe(cleanup.added) - expect(cleanup.unreleased).toEqual([]) - }) -}) diff --git a/mobile/src/terminal/terminal-cell-box.test.ts b/mobile/src/terminal/terminal-cell-box.test.ts index d1c7e39a45b..06569b2af30 100644 --- a/mobile/src/terminal/terminal-cell-box.test.ts +++ b/mobile/src/terminal/terminal-cell-box.test.ts @@ -4,10 +4,6 @@ import { readTerminalCellBox } from './terminal-cell-box' const CELL_1X = { fontScale: 1, cellWidth: 23 / 3, cellHeight: 15 } describe('readTerminalCellBox', () => { - it('reads nothing from a notify without a cell box', () => { - expect(readTerminalCellBox({ type: 'web-ready' })).toBeNull() - }) - it('reads a well-formed box and rejects a malformed one', () => { expect(readTerminalCellBox({ cellBox: CELL_1X })).toEqual(CELL_1X) expect(readTerminalCellBox({ cellBox: { ...CELL_1X, cellWidth: 0 } })).toBeNull() diff --git a/mobile/src/terminal/terminal-grid-fit.test.ts b/mobile/src/terminal/terminal-grid-fit.test.ts index 26daa3d7445..28c70569e84 100644 --- a/mobile/src/terminal/terminal-grid-fit.test.ts +++ b/mobile/src/terminal/terminal-grid-fit.test.ts @@ -1,17 +1,7 @@ import { describe, expect, it } from 'vitest' import { fitDimensionsFromCell } from './terminal-grid-fit' -const CELL_1X = { cellWidth: 23 / 3, cellHeight: 15 } - describe('fitDimensionsFromCell', () => { - it('fits the frame React Native laid out', () => { - expect(fitDimensionsFromCell(CELL_1X, 427, 710)).toEqual({ cols: 55, rows: 47 }) - }) - - it('answers null for a frame too narrow to fit', () => { - expect(fitDimensionsFromCell(CELL_1X, 100, 710)).toBeNull() - }) - it('keeps an exact fit at a fractional pixel ratio whole', () => { // An exact device-pixel fit can divide to 49.999… after pixel-ratio conversion. const cell = { cellWidth: 18 / 2.75, cellHeight: 40 / 2.75 } diff --git a/mobile/src/terminal/terminal-input-connection-gate.test.ts b/mobile/src/terminal/terminal-input-connection-gate.test.ts deleted file mode 100644 index 764b6f0b313..00000000000 --- a/mobile/src/terminal/terminal-input-connection-gate.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveMobileTerminalInputGate } from './terminal-input-connection-gate' -import { buildTerminalSendParams, TERMINAL_INPUT_SEND_OPTIONS } from './terminal-send-request' - -describe('terminal input connection gate', () => { - it('Given a live connection on a terminal tab Then composing and sending are both allowed', () => { - expect( - resolveMobileTerminalInputGate({ - connState: 'connected', - activeHandle: 'terminal-a', - activeSessionTabType: 'terminal' - }) - ).toEqual({ canCompose: true, canSend: true }) - }) - - it('Given a cut connection Then composing stays available while sending is blocked', () => { - for (const connState of [ - 'connecting', - 'handshaking', - 'disconnected', - 'reconnecting', - 'auth-failed' - ] as const) { - expect( - resolveMobileTerminalInputGate({ - connState, - activeHandle: 'terminal-a', - activeSessionTabType: 'terminal' - }) - ).toEqual({ canCompose: true, canSend: false }) - } - }) - - it('Given a non-terminal tab or no handle Then neither composing nor sending is allowed', () => { - for (const activeSessionTabType of ['markdown', 'file', 'browser']) { - expect( - resolveMobileTerminalInputGate({ - connState: 'connected', - activeHandle: 'terminal-a', - activeSessionTabType - }) - ).toEqual({ canCompose: false, canSend: false }) - } - expect( - resolveMobileTerminalInputGate({ - connState: 'connected', - activeHandle: null, - activeSessionTabType: 'terminal' - }) - ).toEqual({ canCompose: false, canSend: false }) - }) - - it('Given a lagging tab list yielding no tab Then the gate treats the type as unknown, not non-terminal', () => { - expect( - resolveMobileTerminalInputGate({ - connState: 'disconnected', - activeHandle: 'terminal-a', - activeSessionTabType: undefined - }) - ).toEqual({ canCompose: true, canSend: false }) - }) -}) - -describe('terminal send request shape', () => { - it('keeps every keystroke-grade terminal send now-or-never so nothing replays after reconnect', () => { - expect(TERMINAL_INPUT_SEND_OPTIONS).toEqual({ failWhenDisconnected: true }) - }) - - it('tags terminal sends with the device presence lock only when a token exists', () => { - expect( - buildTerminalSendParams({ terminal: 't1', text: 'ls', enter: true, deviceToken: 'tok' }) - ).toEqual({ terminal: 't1', text: 'ls', enter: true, client: { id: 'tok', type: 'mobile' } }) - expect( - buildTerminalSendParams({ terminal: 't1', text: 'ls', enter: false, deviceToken: null }) - ).toEqual({ terminal: 't1', text: 'ls', enter: false }) - }) -}) diff --git a/mobile/src/terminal/terminal-key-chord-input.test.ts b/mobile/src/terminal/terminal-key-chord-input.test.ts index f3392d434eb..c62498fdb0e 100644 --- a/mobile/src/terminal/terminal-key-chord-input.test.ts +++ b/mobile/src/terminal/terminal-key-chord-input.test.ts @@ -10,26 +10,8 @@ const chord = (key: string, modifiers: { ctrl?: boolean; alt?: boolean; shift?: }) describe('createTerminalKeyChordInput', () => { - it('encodes keyboard chords as the bytes a terminal expects', () => { - expect(chord('c', { ctrl: true })).toEqual({ bytes: '\x03' }) - expect(chord('[', { ctrl: true })).toEqual({ bytes: '\x1b' }) - expect(chord('space', { ctrl: true })).toEqual({ bytes: '\x00' }) - expect(chord('b', { alt: true })).toEqual({ bytes: '\x1bb' }) - expect(chord('B', { alt: true })).toEqual({ bytes: '\x1bB' }) - expect(chord('C', { ctrl: true })).toEqual({ bytes: '\x03' }) - expect(chord('/', { ctrl: true })).toEqual({ bytes: '\x1f' }) - expect(chord('enter', { alt: true })).toEqual({ bytes: '\x1b\r' }) - expect(chord('tab', { shift: true })).toEqual({ bytes: '\x1b[Z' }) - expect(chord('arrowUp', { ctrl: true })).toEqual({ bytes: '\x1b[1;5A' }) - expect(chord('escape')).toEqual({ bytes: '\x1b' }) - }) - it('keeps the accessory Del local-edit rule for a bare forward delete only', () => { expect(chord('delete')).toEqual({ bytes: '\x1b[3~', localEdit: 'delete' }) expect(chord('delete', { ctrl: true })).toEqual({ bytes: '\x1b[3;5~' }) }) - - it('drops chords with no terminal encoding', () => { - expect(chord('1', { ctrl: true })).toBeNull() - }) }) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts index 3872248dd4a..5441080461c 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts @@ -15,53 +15,6 @@ function metrics( } describe('computeActiveTerminalKeyboardLift', () => { - it('returns 0 when the keyboard is closed', () => { - expect( - computeActiveTerminalKeyboardLift({ - keyboardLift: 0, - metrics: metrics({ cursorY: 30, contentBottomRow: 34 }), - terminalFrameHeight: FRAME_HEIGHT - }) - ).toBe(0) - }) - - it('falls back to the full lift when metrics are missing', () => { - expect( - computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: undefined, - terminalFrameHeight: FRAME_HEIGHT - }) - ).toBe(KEYBOARD_LIFT) - }) - - it('falls back to the full lift when rows or frame height are unmeasured', () => { - expect( - computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics({ rows: 0 }), - terminalFrameHeight: FRAME_HEIGHT - }) - ).toBe(KEYBOARD_LIFT) - expect( - computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics(), - terminalFrameHeight: 0 - }) - ).toBe(KEYBOARD_LIFT) - }) - - it('lifts fully for alt-screen TUIs', () => { - expect( - computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics({ cursorY: 10, contentBottomRow: 10, altScreen: true }), - terminalFrameHeight: FRAME_HEIGHT - }) - ).toBe(KEYBOARD_LIFT) - }) - it('clears a main-buffer footer while an old payload retains cursor-only behavior', () => { const candidate = computeActiveTerminalKeyboardLift({ keyboardLift: KEYBOARD_LIFT, @@ -77,40 +30,6 @@ describe('computeActiveTerminalKeyboardLift', () => { expect({ candidate, cursorOnly }).toEqual({ candidate: 220, cursorOnly: 140 }) }) - it('keeps short output near the top put (no lift)', () => { - expect( - computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics({ cursorY: 2, contentBottomRow: 5 }), - terminalFrameHeight: FRAME_HEIGHT - }) - ).toBe(0) - }) - - it('matches cursor-clearing behavior for a scrolled shell (prompt at the bottom)', () => { - const lift = computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics({ cursorY: 38, contentBottomRow: 38 }), - terminalFrameHeight: FRAME_HEIGHT - }) - expect(lift).toBe(KEYBOARD_LIFT) - }) - - it('never exceeds the keyboard lift', () => { - const lift = computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics({ cursorY: 39, contentBottomRow: 39 }), - terminalFrameHeight: FRAME_HEIGHT - }) - expect(lift).toBeLessThanOrEqual(KEYBOARD_LIFT) - const taller = computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics({ rows: 60, rowPitch: 18, cursorY: 59, contentBottomRow: 59 }), - terminalFrameHeight: FRAME_HEIGHT - }) - expect(taller).toBe(KEYBOARD_LIFT) - }) - it('applies the supplied keyboard coverage to the lift', () => { const tuiMetrics = metrics({ cursorY: 30, contentBottomRow: 34 }) const android = computeActiveTerminalKeyboardLift({ @@ -150,12 +69,6 @@ describe('computeActiveTerminalKeyboardLift', () => { expect(lift(312, { ...drawn425, cursorY: 45, contentBottomRow: 45 })).toBe(0) }) - it('lifts nothing for a keyboard that is open and covers nothing', () => { - expect(lift(0, metrics({ rows: 50, rowPitch: 17, cursorY: 49, contentBottomRow: 49 }))).toBe( - 0 - ) - }) - it('stays under the strip while stale rows outlast a rotation or a text-size change', () => { const rotated = metrics({ rows: 47, rowPitch: 15, cursorY: 46, contentBottomRow: 46 }) expect(lift(150, rotated, 300)).toBe(150) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts index ae2b733a7fc..4a80fb6f2c4 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts @@ -1,10 +1,9 @@ // @vitest-environment happy-dom import { Terminal } from '@xterm/xterm' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { createTerminalDocumentScope } from './document/document-scope' import { emitKeyboardAvoidanceMetrics } from './document/keyboard-avoidance-metrics' import { commitFitScale } from './document/fit-scale' -import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' function runMetricsOver(term: unknown, fitScale = 1): Record[] { const notifications: Record[] = [] @@ -17,8 +16,6 @@ function runMetricsOver(term: unknown, fitScale = 1): Record[] emitKeyboardAvoidanceMetrics(scope) return notifications } - -type Cell = { isBgDefault: () => boolean; isInverse: () => number } type MetricsNotification = { type: string cursorY: number @@ -47,31 +44,6 @@ function checkedMetrics(value: Record | undefined): MetricsNoti } } -function makeLine(text = '', styledColumns: number[] = []) { - const styled = new Set(styledColumns) - return { - isWrapped: false, - length: 10, - translateToString: vi.fn(() => text), - getCell: (column: number): Cell => ({ - isBgDefault: () => !styled.has(column), - isInverse: () => 0 - }) - } -} - -function runMetrics(lines: (ReturnType | undefined)[], altScreen = false) { - const buffer = { - cursorY: 2, - viewportY: 3, - type: altScreen ? 'alternate' : 'normal', - getLine: (index: number) => lines[index - 3], - getNullCell: () => ({}) - } - const notified = runMetricsOver({ buffer: { active: buffer }, cols: 10, rows: lines.length }) - return checkedMetrics(notified[0]) -} - function runTerminalMetrics(term: Terminal) { return checkedMetrics(runMetricsOver(term)[0]) } @@ -81,21 +53,6 @@ function write(term: Terminal, data: string): Promise { } describe('terminal keyboard-avoidance WebView metrics', () => { - it('finds text on wrapped rows using the visible viewport offset', () => { - const lines = [makeLine('header'), makeLine(''), makeLine('wrapped footer')] - lines[2]!.isWrapped = true - expect(runMetrics(lines)).toMatchObject({ contentBottomRow: 2 }) - }) - - it('keeps background-only ANSI chrome visible', () => { - expect(runMetrics([makeLine('header'), makeLine(''), makeLine('')])).toMatchObject({ - contentBottomRow: 0 - }) - expect(runMetrics([makeLine('header'), makeLine(''), makeLine('', [4])])).toMatchObject({ - contentBottomRow: 2 - }) - }) - it('classifies real xterm text and styled whitespace by rendered visibility', async () => { const cases = [ { name: 'default spaces', data: ' ', expected: 0 }, @@ -148,38 +105,6 @@ describe('terminal keyboard-avoidance WebView metrics', () => { } }) - it('keeps real xterm metrics compatible with old payloads', async () => { - const term = new Terminal({ cols: 10, rows: 8 }) - try { - await write(term, '\x1b[8;1Hfooter\x1b[2;1H') - const { cursorY, rows, altScreen } = runTerminalMetrics(term) - expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY, rows, altScreen })).toEqual({ - cursorY: 1, - contentBottomRow: 1, - rows: 8, - altScreen: false - }) - } finally { - term.dispose() - } - }) - - it('stops at the first bottom-up match and skips scans on alternate screen', () => { - const footer = makeLine('footer') - const header = makeLine('header') - expect(runMetrics([header, makeLine(''), footer])).toMatchObject({ contentBottomRow: 2 }) - expect(footer.translateToString).toHaveBeenCalledTimes(1) - expect(header.translateToString).not.toHaveBeenCalled() - - footer.translateToString.mockImplementation(() => { - throw new Error('alternate screen must not scan') - }) - expect(runMetrics([header, makeLine(''), footer], true)).toMatchObject({ - altScreen: true, - contentBottomRow: 0 - }) - }) - it('reports the row pitch as drawn, fit scale included, and none before a cell is measured', () => { const buffer = { cursorY: 0, viewportY: 0, type: 'normal', getLine: () => undefined } const measuredTerm = { diff --git a/mobile/src/terminal/terminal-live-accessory-raw-send-target.test.ts b/mobile/src/terminal/terminal-live-accessory-raw-send-target.test.ts deleted file mode 100644 index 15bc86d9eb0..00000000000 --- a/mobile/src/terminal/terminal-live-accessory-raw-send-target.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getTerminalLiveAccessoryRawSendTarget } from './terminal-live-accessory-raw-send-target' - -describe('terminal live accessory raw send target', () => { - it('Given the original terminal is still active When raw fallback resumes Then returns that handle', () => { - const targetHandle = 'terminal-a' - - const sendTarget = getTerminalLiveAccessoryRawSendTarget({ - targetHandle, - activeHandle: targetHandle, - activeSessionTabType: 'terminal' - }) - - expect(sendTarget).toBe(targetHandle) - }) - - it('Given the active terminal changed while waiting When raw fallback resumes Then suppresses the send', () => { - const targetHandle = 'terminal-a' - - const sendTarget = getTerminalLiveAccessoryRawSendTarget({ - targetHandle, - activeHandle: 'terminal-b', - activeSessionTabType: 'terminal' - }) - - expect(sendTarget).toBeNull() - }) - - it('Given the target is not an active terminal tab When raw fallback resumes Then suppresses the send', () => { - const targetHandle = 'terminal-a' - - const inactiveTabTarget = getTerminalLiveAccessoryRawSendTarget({ - targetHandle, - activeHandle: targetHandle, - activeSessionTabType: 'browser' - }) - - expect(inactiveTabTarget).toBeNull() - }) -}) diff --git a/mobile/src/terminal/terminal-live-input-keyboard-reopen.test.ts b/mobile/src/terminal/terminal-live-input-keyboard-reopen.test.ts deleted file mode 100644 index c70880c1642..00000000000 --- a/mobile/src/terminal/terminal-live-input-keyboard-reopen.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const host = vi.hoisted(() => ({ os: 'android' })) -vi.mock('react-native', () => ({ Platform: { OS: 'web' } })) -vi.mock('../platform/host-os', () => ({ hostOs: () => host.os })) - -const { reopensFocusedInputWhenKeyboardHidden } = - await import('./terminal-live-input-keyboard-reopen') - -describe('reopening a focused live input whose keyboard is hidden', () => { - it("follows the phone's OS on the page, which runs as web", () => { - host.os = 'android' - expect(reopensFocusedInputWhenKeyboardHidden()).toBe(true) - host.os = 'ios' - expect(reopensFocusedInputWhenKeyboardHidden()).toBe(false) - }) -}) diff --git a/mobile/src/terminal/terminal-live-input-text-write.web.test.ts b/mobile/src/terminal/terminal-live-input-text-write.web.test.ts index 1cbb2329fae..ea02b00e99e 100644 --- a/mobile/src/terminal/terminal-live-input-text-write.web.test.ts +++ b/mobile/src/terminal/terminal-live-input-text-write.web.test.ts @@ -4,7 +4,6 @@ import { act, createElement, createRef, type ComponentType, type RefObject } fro import { createRoot } from 'react-dom/client' import { describe, expect, it } from 'vitest' import type { TextInput } from 'react-native' -import { writeTerminalLiveInputText } from './terminal-live-input-text-write' import { writeTerminalLiveInputText as writeTerminalLiveInputTextOnWeb } from './terminal-live-input-text-write.web' const refTo = (node: unknown): RefObject => ({ @@ -12,29 +11,7 @@ const refTo = (node: unknown): RefObject => ({ current: node as TextInput | null }) -function mountInput(): HTMLInputElement { - const input = document.createElement('input') - document.body.append(input) - return input -} - -describe('the native live-input write with an unmounted ref', () => { - // The no-terminal route never reaches this write, so its render check alone could miss the native-method defect. - it('writes nothing at all when the field has not mounted', () => { - expect(() => writeTerminalLiveInputText(refTo(null), '')).not.toThrow() - }) -}) - describe('the web sibling', () => { - it('puts the text on the node the field is', () => { - const input = mountInput() - input.value = 'ime-preedit' - - writeTerminalLiveInputTextOnWeb(refTo(input), '') - - expect(input.value).toBe('') - }) - it('writes a multiline field too, which RN Web renders as a textarea', () => { const area = document.createElement('textarea') document.body.append(area) @@ -43,19 +20,6 @@ describe('the web sibling', () => { expect(area.value).toBe('edited') }) - - it('tolerates a field that has unmounted between the edit and the write', () => { - expect(() => writeTerminalLiveInputTextOnWeb(refTo(null), '')).not.toThrow() - }) - - // Do not add value to unknown wrappers; future RN Web changes must not silently pretend to update the field. - it('leaves a node that is not a field alone', () => { - const div = document.createElement('div') - - writeTerminalLiveInputTextOnWeb(refTo(div), 'edited') - - expect(Object.hasOwn(div, 'value')).toBe(false) - }) }) // Check the actual RN Web TextInput ref too; a hand-built input would miss component shape changes. diff --git a/mobile/src/terminal/terminal-settings-scroll-lock.web.test.ts b/mobile/src/terminal/terminal-settings-scroll-lock.web.test.ts deleted file mode 100644 index 9636e115888..00000000000 --- a/mobile/src/terminal/terminal-settings-scroll-lock.web.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// @vitest-environment happy-dom -import { createRequire } from 'node:module' -import { act, createElement, createRef, type ComponentType, type RefObject } from 'react' -import { createRoot } from 'react-dom/client' -import { describe, expect, it } from 'vitest' -import type { ScrollView } from 'react-native' -import { setTerminalSettingsScrollEnabled } from './terminal-settings-scroll-lock' -import { setTerminalSettingsScrollEnabled as setTerminalSettingsScrollEnabledOnWeb } from './terminal-settings-scroll-lock.web' - -const refTo = (node: unknown): RefObject => ({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the point of these cases is that a DOM node is what the native signature receives on RN Web, which is the mismatch this sibling exists for. - current: node as ScrollView | null -}) - -describe('the native scroll-lock write against an RN Web ref', () => { - it('throws, because a DOM node has no setNativeProps', () => { - expect(() => - setTerminalSettingsScrollEnabled(refTo(document.createElement('div')), false) - ).toThrow(/setNativeProps is not a function/) - }) - - it('writes nothing at all when the view has not mounted', () => { - expect(() => setTerminalSettingsScrollEnabled(refTo(null), false)).not.toThrow() - }) -}) - -describe('the web sibling', () => { - it('locks the scroll with overflow, which stops a wheel as well as a touch drag', () => { - const node = document.createElement('div') - - setTerminalSettingsScrollEnabledOnWeb(refTo(node), false) - - expect(node.style.overflowY).toBe('hidden') - }) - - it('tolerates a view that has unmounted between the gesture and the write', () => { - expect(() => setTerminalSettingsScrollEnabledOnWeb(refTo(null), true)).not.toThrow() - }) - - it('leaves a node that is not an element alone', () => { - expect(() => setTerminalSettingsScrollEnabledOnWeb(refTo({}), false)).not.toThrow() - }) -}) - -// Test RN Web’s real class-driven overflow: a bare div cannot prove clearing inline overflow restores scrolling. -describe('against a real react-native-web ScrollView', () => { - // Require RN Web because its missing type declarations would make a direct import escape the tests-typecheck ratchet. - const { - ScrollView: ReactNativeWebScrollView - }: { - ScrollView: ComponentType<{ - ref: RefObject - }> - } = createRequire(import.meta.url)('react-native-web') - - async function renderScroller(): Promise<{ - node: HTMLElement - unmount: () => void - }> { - Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true) - const container = document.createElement('div') - document.body.append(container) - const root = createRoot(container) - const ref: RefObject = createRef() - await act(async () => { - root.render(createElement(ReactNativeWebScrollView, { ref })) - }) - const node = ref.current - if (!(node instanceof HTMLElement)) { - throw new Error('react-native-web put no element in the ScrollView ref') - } - return { - node, - unmount: () => { - root.unmount() - container.remove() - } - } - } - - it('is handed the DOM node itself, which is why the native write cannot land', async () => { - const { node, unmount } = await renderScroller() - try { - expect(node.tagName).toBe('DIV') - expect('setNativeProps' in node).toBe(false) - } finally { - unmount() - } - }) - - it('locks and then hands the scroller back to the class RN Web styles it with', async () => { - const { node, unmount } = await renderScroller() - try { - expect(node.getAttribute('style')).toBeNull() - expect(node.className).toContain('overflowY') - - setTerminalSettingsScrollEnabledOnWeb(refTo(node), false) - expect(node.style.overflowY).toBe('hidden') - - setTerminalSettingsScrollEnabledOnWeb(refTo(node), true) - expect(node.style.overflowY).toBe('') - expect(node.className).toContain('overflowY') - } finally { - unmount() - } - }) -}) diff --git a/mobile/src/terminal/terminal-text-input-normalization.test.ts b/mobile/src/terminal/terminal-text-input-normalization.test.ts index c5213013e31..8bd9b39c105 100644 --- a/mobile/src/terminal/terminal-text-input-normalization.test.ts +++ b/mobile/src/terminal/terminal-text-input-normalization.test.ts @@ -7,8 +7,4 @@ describe('normalizeTerminalTextInput', () => { expect(normalizeTerminalTextInput('git checkout – file')).toBe('git checkout -- file') expect(normalizeTerminalTextInput('git checkout — file')).toBe('git checkout -- file') }) - - it('keeps ASCII hyphens unchanged', () => { - expect(normalizeTerminalTextInput('git checkout -- file')).toBe('git checkout -- file') - }) }) diff --git a/mobile/src/terminal/terminal-webview-cell-box.test.ts b/mobile/src/terminal/terminal-webview-cell-box.test.ts index 18484a37d81..5d4071bea7d 100644 --- a/mobile/src/terminal/terminal-webview-cell-box.test.ts +++ b/mobile/src/terminal/terminal-webview-cell-box.test.ts @@ -81,14 +81,6 @@ const cellBoxNotify = (cellWidth: number, refit: boolean) => ({ }) describe('the cell box xterm laid out', () => { - it('sizes a fit from web-ready, which the document sends once its terminal is built', () => { - const { handle, notify } = mount() - expect(handle().fitDimensions(FRAME)).toBeNull() - notify({ type: 'web-ready', cellBox: cellAt(scale) }) - expect(handle().fitDimensions(FRAME)).toEqual({ cols: 55, rows: 47 }) - expect(postedTypes()).not.toContain('measure') - }) - it('fits each box the document reports, and refits only when the document says so', () => { const { handle, notify, onCellBoxChange } = mount() notify({ type: 'web-ready', cellBox: cellAt(scale) }) @@ -142,14 +134,6 @@ describe('the cell box xterm laid out', () => { expect(postedTypes()).not.toContain('init') }) - it('reloads the same view when its content process ends', () => { - const { webView } = mount() - const view = webView() - act(() => view.props.onContentProcessDidTerminate({ nativeEvent: {} })) - expect(nativeWebViewMethods.reload).toHaveBeenCalledTimes(1) - expect(webView()).toBe(view) - }) - it('drops queued and coalesced commands on a reload or a lost content process', () => { vi.useFakeTimers() const { handle, notify, webView } = mount() @@ -169,30 +153,4 @@ describe('the cell box xterm laid out', () => { }) expect(postedTypes()).toContain('write') }) - - it('tells the document the app text scale before it builds its terminal', () => { - const { webView } = mount(1.25) - const html: string = webView().props.source.html - const start = html.indexOf('window.__orcaTerminalTextScale = 1.25;') - expect(start).toBeGreaterThan(-1) - // Put initial settings in page source so no platform can inject them after document startup. - expect(start).toBeLessThan(html.indexOf('startTerminalDocument')) - }) - - it('keeps the source it mounted with across renders, so a new text scale does not reload', () => { - const { webView } = mount(1) - const source = webView().props.source - act(() => renderers[0]!.update(createElement(TerminalWebView, { textScale: 1.5 }))) - expect(webView().props.source).toBe(source) - }) - - it('tells a document whose view was hidden at mount not to build before ready', () => { - let renderer: ReactTestRenderer | undefined - act(() => { - renderer = create(createElement(TerminalWebView, { shownAtMount: false })) - }) - renderers.push(renderer!) - const webView = renderer!.root.find((node) => typeof node.props.onMessage === 'function') - expect(webView.props.source.html).toContain('window.__orcaTerminalShown = false;') - }) }) diff --git a/mobile/src/terminal/terminal-webview-contract.test.ts b/mobile/src/terminal/terminal-webview-contract.test.ts index 4cd3ce47dfa..cde678336f8 100644 --- a/mobile/src/terminal/terminal-webview-contract.test.ts +++ b/mobile/src/terminal/terminal-webview-contract.test.ts @@ -1,23 +1,8 @@ import { describe, expect, it } from 'vitest' -import { - parseTerminalKeyboardAvoidanceMetrics, - sameTerminalKeyboardAvoidanceMetrics, - type TerminalKeyboardAvoidanceMetrics -} from './terminal-webview-contract' +import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' describe('parseTerminalKeyboardAvoidanceMetrics', () => { - it('parses a full payload', () => { - expect( - parseTerminalKeyboardAvoidanceMetrics({ - cursorY: 30, - contentBottomRow: 34, - rows: 40, - altScreen: true - }) - ).toEqual({ cursorY: 30, contentBottomRow: 34, rows: 40, altScreen: true }) - }) - it('defaults contentBottomRow to cursorY when absent (older WebView bundles)', () => { expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY: 12, rows: 40 })).toEqual({ cursorY: 12, @@ -27,15 +12,6 @@ describe('parseTerminalKeyboardAvoidanceMetrics', () => { }) }) - it('defaults non-numeric fields to zero', () => { - expect(parseTerminalKeyboardAvoidanceMetrics({})).toEqual({ - cursorY: 0, - contentBottomRow: 0, - rows: 0, - altScreen: false - }) - }) - it('bounds untrusted numeric fields to the reported viewport', () => { expect( parseTerminalKeyboardAvoidanceMetrics({ @@ -65,30 +41,3 @@ describe('parseTerminalKeyboardAvoidanceMetrics', () => { } }) }) - -describe('sameTerminalKeyboardAvoidanceMetrics', () => { - const metrics: Required = { - cursorY: 38, - contentBottomRow: 38, - rows: 40, - altScreen: false, - rowPitch: 15 - } - const variants: [keyof typeof metrics, TerminalKeyboardAvoidanceMetrics][] = [ - ['cursorY', { ...metrics, cursorY: 39 }], - ['contentBottomRow', { ...metrics, contentBottomRow: 39 }], - ['rows', { ...metrics, rows: 41 }], - ['altScreen', { ...metrics, altScreen: true }], - ['rowPitch', { ...metrics, rowPitch: 6.96 }] - ] - - it('tells apart metrics that differ in any one field', () => { - expect(sameTerminalKeyboardAvoidanceMetrics(metrics, { ...metrics })).toBe(true) - expect(variants.map(([key]) => key).sort()).toEqual(Object.keys(metrics).sort()) - for (const [key, variant] of variants) { - expect(sameTerminalKeyboardAvoidanceMetrics(metrics, variant), key).toBe(false) - } - const { rowPitch: _rowPitch, ...older } = metrics - expect(sameTerminalKeyboardAvoidanceMetrics(metrics, older)).toBe(false) - }) -}) diff --git a/mobile/src/terminal/terminal-webview-engine.test.ts b/mobile/src/terminal/terminal-webview-engine.test.ts index 84c79e49df2..bae8c70c67a 100644 --- a/mobile/src/terminal/terminal-webview-engine.test.ts +++ b/mobile/src/terminal/terminal-webview-engine.test.ts @@ -1,15 +1,12 @@ // @vitest-environment happy-dom -import { readFileSync } from 'node:fs' -import path from 'node:path' import { Script } from 'node:vm' import { parse } from 'acorn' import { describe, expect, it, vi } from 'vitest' -import { TERMINAL_NERD_FONT_CSS, XTERM_ENGINE_CSS } from './terminal-webview-engine-css.generated' +import { XTERM_ENGINE_CSS } from './terminal-webview-engine-css.generated' import { XTERM_ENGINE_JS } from './terminal-webview-engine.generated' import { createTerminalDocumentScope } from './document/document-scope' -import { attachWebglAddon, startWebglRecovery } from './document/webgl-recovery' +import { attachWebglAddon } from './document/webgl-recovery' import { XTERM_HTML } from './terminal-webview-html' -import { applyTerminalTheme } from './document/terminal-theme' function createWebglRecoveryHarness(failSecondAttach = false) { const timers: Array<() => void> = [] @@ -43,7 +40,6 @@ function createWebglRecoveryHarness(failSecondAttach = false) { }) } const logged: Record[] = [] - const terminalThemeInput = { mode: 'dark' } vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback: TimerHandler) => { if (typeof callback === 'function') { timers.push(() => { @@ -60,20 +56,11 @@ function createWebglRecoveryHarness(failSecondAttach = false) { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the double implements the members the recovery path reaches, which is what each case asserts about. scope.term = term as unknown as typeof scope.term scope.terminalGeneration = 1 - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recovery only re-applies this value through the theme path; its shape is that path's own input. - scope.terminalThemeInput = terminalThemeInput as unknown as typeof scope.terminalThemeInput - startWebglRecovery(scope) attachWebglAddon(scope, true) return { addons, - appliedThemes: () => term.options.theme, - fireVisibilityChange: () => { - document.dispatchEvent(new Event('visibilitychange')) - }, logged, - scope, term, - terminalThemeInput, timers } } @@ -86,33 +73,6 @@ describe('terminal WebView bundled engine', () => { expect(XTERM_HTML).not.toContain('rel="stylesheet" href=') }) - it('ships the licensed desktop symbol font offline without covering normal text', () => { - const encoded = TERMINAL_NERD_FONT_CSS.match(/base64,([^']+)'/)?.[1] - expect(encoded).toBeTruthy() - const bundled = readFileSync( - path.resolve(import.meta.dirname, '../../assets/fonts/SymbolsNerdFontMono-Regular.woff2') - ) - expect(Buffer.from(encoded ?? '', 'base64').equals(bundled)).toBe(true) - expect( - bundled.equals( - readFileSync( - path.resolve( - import.meta.dirname, - '../../../src/renderer/src/assets/fonts/SymbolsNerdFontMono-Regular.woff2' - ) - ) - ) - ).toBe(true) - expect(TERMINAL_NERD_FONT_CSS).toContain( - 'unicode-range:U+E000-F8FF,U+F0000-FFFFD,U+100000-10FFFD' - ) - expect(XTERM_HTML).toContain(``) - expect(XTERM_HTML).toContain( - '"Liberation Mono", "Orca Nerd Font Symbols", "Symbols Nerd Font Mono"' - ) - expect(TERMINAL_NERD_FONT_CSS).not.toMatch(/<\/style/i) - }) - it('parses the bundled engine at the Chrome 74 syntax floor', () => { expect(() => parse(XTERM_ENGINE_JS, { ecmaVersion: 2019 })).not.toThrow() }) @@ -226,21 +186,4 @@ describe('terminal WebView bundled engine', () => { expect(addons[1]?.dispose).toHaveBeenCalledTimes(1) expect(term.refresh).toHaveBeenCalledTimes(2) }) - - it('reapplies theme, clears the active atlas, and refreshes when visible', () => { - const harness = createWebglRecoveryHarness() - applyTerminalTheme(harness.scope, harness.scope.terminalThemeInput) - const firstTheme = harness.term.options.theme - - // Stub only hidden state; Happy DOM’s visible default exercises real recovery. - vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden') - harness.fireVisibilityChange() - expect(harness.term.options.theme).toBe(firstTheme) - vi.restoreAllMocks() - - harness.fireVisibilityChange() - expect(harness.term.options.theme).not.toBe(firstTheme) - expect(harness.addons[0]?.clearTextureAtlas).toHaveBeenCalledTimes(1) - expect(harness.term.refresh).toHaveBeenCalledTimes(1) - }) }) diff --git a/mobile/src/terminal/terminal-webview-html/document-style.test.ts b/mobile/src/terminal/terminal-webview-html/document-style.test.ts index 0aae8e56fdb..00363128aa3 100644 --- a/mobile/src/terminal/terminal-webview-html/document-style.test.ts +++ b/mobile/src/terminal/terminal-webview-html/document-style.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' -import { documentLevelRules, scopeStyleToHost } from '../../style-scoping/document-style-scoping' +import { scopeStyleToHost } from '../../style-scoping/document-style-scoping' import { XTERM_ENGINE_CSS } from '../terminal-webview-engine-css.generated' -import { TERMINAL_DOCUMENT_ELEMENT_STYLE, TERMINAL_DOCUMENT_ROOT_STYLE } from './document-style' +import { TERMINAL_DOCUMENT_ELEMENT_STYLE } from './document-style' // Verify native root rules remain separate while page-injected rules can reach only terminal-owned elements. const PREFIX = '.orca-terminal-document-host' @@ -13,11 +13,6 @@ function selectorsOf(css: string): string[] { } describe('the terminal document stylesheet', () => { - it('keeps every document-level rule out of the half the page takes', () => { - expect(documentLevelRules(TERMINAL_DOCUMENT_ROOT_STYLE)).toEqual(['*', 'html, body']) - expect(documentLevelRules(TERMINAL_DOCUMENT_ELEMENT_STYLE)).toEqual([]) - }) - it('holds every selector of both injected sheets under the host', () => { for (const sheet of [TERMINAL_DOCUMENT_ELEMENT_STYLE, XTERM_ENGINE_CSS]) { const scoped = scopeStyleToHost(sheet, PREFIX) @@ -26,9 +21,4 @@ describe('the terminal document stylesheet', () => { expect(selectors.filter((one) => !one.startsWith(`${PREFIX} `))).toEqual([]) } }) - - it('drops a document-level rule rather than prefixing it', () => { - const scoped = scopeStyleToHost(TERMINAL_DOCUMENT_ROOT_STYLE, PREFIX) - expect(scoped.trim()).toBe('') - }) }) diff --git a/mobile/src/terminal/terminal-webview-mouse-click.test.ts b/mobile/src/terminal/terminal-webview-mouse-click.test.ts index 06efd3a2501..0191c49119a 100644 --- a/mobile/src/terminal/terminal-webview-mouse-click.test.ts +++ b/mobile/src/terminal/terminal-webview-mouse-click.test.ts @@ -47,41 +47,6 @@ describe('terminal WebView external mouse click', () => { expect(document.getElementById('selection-overlay')?.classList.contains('active')).toBe(false) }) - it('routes a plain mouse click to the tap pipeline for keyboard focus', () => { - mouse.boot() - - mouse.mouseClick(40, 60) - - const messages = mouse.postedMessages() - expect(messages.filter((message) => message.type === 'terminal-tap')).toHaveLength(1) - expect(mouse.terminalInputBytes()).toBe('') - }) - - it('ignores non-mouse pointers and non-left buttons', () => { - mouse.boot() - mouse.activeTerminal().modes.mouseTrackingMode = 'vt200' - - mouse.dispatchPointer('pointerdown', { - pointerType: 'touch', - x: 40, - y: 60, - button: 0, - buttons: 1 - }) - mouse.dispatchPointer('pointerup', { - pointerType: 'touch', - x: 40, - y: 60, - button: 0, - buttons: 0 - }) - mouse.dispatchPointer('pointerdown', { x: 40, y: 60, button: 2, buttons: 2 }) - mouse.dispatchPointer('pointerup', { x: 40, y: 60, button: 2, buttons: 0 }) - - expect(mouse.terminalInputBytes()).toBe('') - expect(mouse.postedMessages().filter((message) => message.type === 'terminal-tap')).toEqual([]) - }) - it('lets the touch dispatcher own a gesture when touch events follow pointerdown', () => { mouse.boot() mouse.writeLegacyMouseEncoding() diff --git a/mobile/src/terminal/terminal-webview-mouse-drag.test.ts b/mobile/src/terminal/terminal-webview-mouse-drag.test.ts index f3ff6c54fc0..1747d3a5176 100644 --- a/mobile/src/terminal/terminal-webview-mouse-drag.test.ts +++ b/mobile/src/terminal/terminal-webview-mouse-drag.test.ts @@ -39,20 +39,6 @@ describe('terminal WebView external mouse drag', () => { expect(bytes).toHaveLength(6) }) - it('selects character-anchored text on a mouse drag outside tracking mode', () => { - mouse.boot() - // Discard init’s selection reset so assertions observe only the drag. - mouse.clearPostedMessages() - - mouse.mouseDrag(40, 60, 160, 90) - - expect(mouse.terminalInputBytes()).toBe('') - expect(mouse.selectionSpy()).toHaveBeenCalled() - expect(document.getElementById('selection-overlay')?.classList.contains('active')).toBe(true) - const modes = mouse.postedMessages().filter((message) => message.type === 'set-select-mode') - expect(modes).toEqual([{ type: 'set-select-mode', enabled: true }]) - }) - it('selects text instead of reporting a drag while the encoding is unproven', () => { mouse.boot(`${ESC}[?1002h`) mouse.activeTerminal().modes.mouseTrackingMode = 'drag' @@ -81,17 +67,4 @@ describe('terminal WebView external mouse drag', () => { expect(mouse.terminalInputBytes()).toBe('') }) - - it('releases a tracked drag when the pointer is cancelled mid-gesture', () => { - mouse.boot() - mouse.writeLegacyMouseEncoding() - mouse.activeTerminal().modes.mouseTrackingMode = 'drag' - - mouse.dispatchPointer('pointerdown', { x: 40, y: 60, button: 0, buttons: 1 }) - mouse.dispatchPointer('pointermove', { x: 160, y: 60, button: 0, buttons: 1 }) - mouse.dispatchPointer('pointercancel', { x: 160, y: 60 }) - - const reports = mouse.terminalInputBytes().match(DEFAULT_MOUSE_REPORT_RE) ?? [] - expect(reports.at(-1)?.charCodeAt(3)).toBe(35) - }) }) diff --git a/mobile/src/terminal/terminal-webview-notification-dispatch.test.ts b/mobile/src/terminal/terminal-webview-notification-dispatch.test.ts deleted file mode 100644 index 24b8a9c8130..00000000000 --- a/mobile/src/terminal/terminal-webview-notification-dispatch.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { dispatchTerminalWebViewNotification } from './terminal-webview-notification-dispatch' - -describe('dispatchTerminalWebViewNotification', () => { - it('preserves bounded keyboard metrics through the dispatcher', () => { - const onKeyboardAvoidanceMetrics = vi.fn() - dispatchTerminalWebViewNotification( - { - type: 'keyboard-avoidance-metrics', - cursorY: 30, - contentBottomRow: 99, - rows: 40, - altScreen: true - }, - { onKeyboardAvoidanceMetrics, reportEngineError: vi.fn() } - ) - expect(onKeyboardAvoidanceMetrics).toHaveBeenCalledWith({ - cursorY: 30, - contentBottomRow: 39, - rows: 40, - altScreen: true - }) - }) - - it('keeps old WebView payloads cursor-compatible', () => { - const onKeyboardAvoidanceMetrics = vi.fn() - dispatchTerminalWebViewNotification( - { type: 'keyboard-avoidance-metrics', cursorY: 12, rows: 40 }, - { onKeyboardAvoidanceMetrics, reportEngineError: vi.fn() } - ) - expect(onKeyboardAvoidanceMetrics).toHaveBeenCalledWith({ - cursorY: 12, - contentBottomRow: 12, - rows: 40, - altScreen: false - }) - }) - - it('passes a tap click on and keeps other terminal input bytes-only', () => { - const onTerminalInput = vi.fn() - const handlers = { onTerminalInput, reportEngineError: vi.fn() } - const click = '\x1b[<0;9;31M\x1b[<0;9;31m' - const wheel = '\x1b[<64;9;31M' - dispatchTerminalWebViewNotification( - { type: 'terminal-input', bytes: click, click: true }, - handlers - ) - dispatchTerminalWebViewNotification({ type: 'terminal-input', bytes: wheel }, handlers) - expect(onTerminalInput.mock.calls).toEqual([[click, { click: true }], [wheel]]) - }) -}) diff --git a/mobile/src/terminal/terminal-webview-replay-coast.test.ts b/mobile/src/terminal/terminal-webview-replay-coast.test.ts index 13f1708bb4c..445d0cc056e 100644 --- a/mobile/src/terminal/terminal-webview-replay-coast.test.ts +++ b/mobile/src/terminal/terminal-webview-replay-coast.test.ts @@ -225,19 +225,6 @@ describe('snapshot replacement ends the previous terminal scroll', () => { expect(scrolls).toEqual([]) }) - it('cancels a pending long press when its terminal is replaced', () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - boot(false) - touch('touchstart', 400) - init() - settle() - messages.length = 0 - vi.advanceTimersByTime(500) - expect( - messages.filter((message) => message.type === 'set-select-mode' && message.enabled) - ).toEqual([]) - }) - it('does not launch an old finger’s velocity after snapshot replacement', () => { boot(false) touch('touchstart', 400) diff --git a/mobile/src/terminal/terminal-webview-touch-scroll.test.ts b/mobile/src/terminal/terminal-webview-touch-scroll.test.ts index a7c55408b30..bfe618b6672 100644 --- a/mobile/src/terminal/terminal-webview-touch-scroll.test.ts +++ b/mobile/src/terminal/terminal-webview-touch-scroll.test.ts @@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { terminalDocumentDouble } from './document/document-terminal-double.test-support' import type { TerminalDocumentTerminal } from './document/document-terminal-shape' -import { createTerminalDocument } from './document/create-terminal-document' import { TERMINAL_DOCUMENT_SCRIPT } from './terminal-webview-document-script.generated' import { TERMINAL_DOCUMENT_MARKUP } from './terminal-webview-html' @@ -62,16 +61,10 @@ describe('terminal WebView touch scrolling', () => { let now: number let postMessage: ReturnType void>> let scrollLines: ReturnType void>> - let stopDocument: (() => void) | undefined - function boot(importedDocument = false): void { + function boot(): void { document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP - if (importedDocument) { - const terminalDocument = createTerminalDocument() - stopDocument = () => terminalDocument.stop() - } else { - new Function(TERMINAL_DOCUMENT_SCRIPT)() - } + new Function(TERMINAL_DOCUMENT_SCRIPT)() window.dispatchEvent( new MessageEvent('message', { data: JSON.stringify({ type: 'init', cols: 40, rows: 24, initialData: '' }) @@ -166,8 +159,6 @@ describe('terminal WebView touch scrolling', () => { }) afterEach(() => { - stopDocument?.() - stopDocument = undefined for (const [type, listener, options] of vi.mocked(window.addEventListener).mock.calls) { window.removeEventListener(type, listener, options) } @@ -179,15 +170,6 @@ describe('terminal WebView touch scrolling', () => { vi.useRealTimers() }) - it('scrolls scrollback for a drag slower than one pixel per frame', () => { - boot() - - fireTouch('touchstart', { x: 40, y: 400 }) - dragUp(400, 0.5, 200) - - expect(scrolledRows()).toBe(6) - }) - it('carries the sub-row remainder of a fast drag into the next move', () => { boot() @@ -199,18 +181,6 @@ describe('terminal WebView touch scrolling', () => { expect(scrolledRows()).toBe(7) }) - it('coasts when the finger lifts mid-drag', () => { - boot() - - fireTouch('touchstart', { x: 40, y: 400 }) - dragUp(400, 20, 5) - const rowsWhileTouching = scrolledRows() - fireTouch('touchend', null) - runFrames(30) - - expect(scrolledRows()).toBeGreaterThan(rowsWhileTouching) - }) - it('does not coast when the finger rested before lifting', () => { boot() @@ -288,19 +258,6 @@ describe('terminal WebView touch scrolling', () => { expect(terminalInputBytes()).toBe(bytesBeforeCancel) }) - it('retires queued scroll and momentum when the document is disposed', () => { - boot(true) - fireTouch('touchstart', { x: 40, y: 400 }) - now += FRAME_MS - fireTouch('touchmove', { x: 40, y: 320 }) - fireTouch('touchend', null) - stopDocument?.() - runFrames(30) - - expect(scrolledRows()).toBe(0) - expect(terminalInputBytes()).toBe('') - }) - it('retires subthreshold scroll velocity when a long press enters selection', () => { boot() vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) diff --git a/mobile/src/terminal/terminal-webview-wheel-scroll.test.ts b/mobile/src/terminal/terminal-webview-wheel-scroll.test.ts index e20be29943c..33f0c635258 100644 --- a/mobile/src/terminal/terminal-webview-wheel-scroll.test.ts +++ b/mobile/src/terminal/terminal-webview-wheel-scroll.test.ts @@ -260,15 +260,6 @@ describe('terminal WebView external pointer wheel scrolling', () => { expect(event.defaultPrevented).toBe(true) }) - it('claims the wheel so xterm does not double-apply it', () => { - buffer = { baseY: 20, type: 'normal', viewportY: 20 } - boot() - - const event = dispatchWheel(-CELL_HEIGHT) - - expect(event.defaultPrevented).toBe(true) - }) - it('clears fractional wheel state when the terminal is recreated', () => { buffer = { baseY: 0, type: 'alternate', viewportY: 0 } boot() diff --git a/mobile/src/terminal/terminal-write-coalescer.test.ts b/mobile/src/terminal/terminal-write-coalescer.test.ts index 685adbaa8fd..5cc20d8fef1 100644 --- a/mobile/src/terminal/terminal-write-coalescer.test.ts +++ b/mobile/src/terminal/terminal-write-coalescer.test.ts @@ -22,31 +22,6 @@ describe('terminal write coalescer', () => { vi.useRealTimers() }) - it('delivers the first write after construction synchronously (leading edge)', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - coalescer.write('a') - - // Idle keystroke echo must never wait for a batching timer. - expect(sink.delivered).toEqual(['a']) - expect(vi.getTimerCount()).toBe(0) - }) - - it('takes the leading edge again after clear()', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - coalescer.write('a') - coalescer.write('b') - coalescer.clear() - coalescer.write('c') - - expect(sink.delivered).toEqual(['a', 'c']) - }) - it('batches writes inside the trailing window preserving byte order', () => { vi.useFakeTimers() const sink = createDeliverySink() @@ -61,40 +36,6 @@ describe('terminal write coalescer', () => { expect(sink.delivered).toEqual(['a', 'bc']) }) - it('buffers a write landing inside the window even when the buffer is empty', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - coalescer.write('a') - vi.advanceTimersByTime(40) - coalescer.write('b') - expect(sink.delivered).toEqual(['a']) - - vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS - 40 - 1) - expect(sink.delivered).toEqual(['a']) - vi.advanceTimersByTime(1) - expect(sink.delivered).toEqual(['a', 'b']) - }) - - it('flushes at most once per window for a sustained stream', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - for (let i = 0; i < 200; i += 1) { - coalescer.write(`c${i};`) - // Check live timer count too; one timer per chunk could preserve flush counts while wasting work. - expect(vi.getTimerCount()).toBeLessThanOrEqual(1) - vi.advanceTimersByTime(5) - } - vi.runOnlyPendingTimers() - - const maxFlushes = Math.ceil((200 * 5) / TERMINAL_WRITE_FLUSH_WINDOW_MS) + 1 - expect(sink.delivered.length).toBeLessThanOrEqual(maxFlushes) - expect(sink.delivered.join('')).toBe(Array.from({ length: 200 }, (_, i) => `c${i};`).join('')) - }) - it('flushes within one window even when the wall clock jumps backwards mid-stream', () => { vi.useFakeTimers() vi.setSystemTime(100_000) @@ -125,22 +66,6 @@ describe('terminal write coalescer', () => { expect(sink.delivered).toHaveLength(2) }) - it('treats write("") as a no-op: no delivery, no buffer append, no timer', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - coalescer.write('') - expect(sink.delivered).toEqual([]) - expect(vi.getTimerCount()).toBe(0) - - coalescer.write('a') - coalescer.write('') - coalescer.write('b') - vi.runOnlyPendingTimers() - expect(sink.delivered).toEqual(['a', 'b']) - }) - it('flushNow() delivers the joined pending buffer synchronously and cancels the timer', () => { vi.useFakeTimers() const sink = createDeliverySink() @@ -157,44 +82,6 @@ describe('terminal write coalescer', () => { expect(sink.delivered).toEqual(['a', 'bc']) }) - it('flushNow() with an empty buffer delivers nothing', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - coalescer.flushNow() - expect(sink.delivered).toEqual([]) - }) - - it('clear() drops pending data without delivering and cancels the timer', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - coalescer.write('a') - coalescer.write('stale') - coalescer.clear() - - expect(vi.getTimerCount()).toBe(0) - vi.runOnlyPendingTimers() - expect(sink.delivered).toEqual(['a']) - }) - - it('delivers nothing further after a flush is followed by clear()', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - - coalescer.write('a') - coalescer.write('b') - vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS) - expect(sink.delivered).toEqual(['a', 'b']) - - coalescer.clear() - vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS * 4) - expect(sink.delivered).toEqual(['a', 'b']) - }) - it('shortens an existing output wait when a scroll gesture arrives', () => { vi.useFakeTimers() const sink = createDeliverySink() @@ -225,21 +112,6 @@ describe('terminal write coalescer', () => { expect(vi.getTimerCount()).toBe(0) }) - it('returns sustained unattended output to the original batching window', () => { - vi.useFakeTimers() - const sink = createDeliverySink() - const coalescer = createTerminalWriteCoalescer(sink.deliver) - coalescer.markInteractive() - coalescer.write('gesture') - vi.advanceTimersByTime(TERMINAL_INTERACTIVE_WRITE_DURATION_MS) - coalescer.write('idle-leading') - coalescer.write('idle-trailing') - vi.advanceTimersByTime(TERMINAL_INTERACTIVE_WRITE_WINDOW_MS) - expect(sink.delivered).toEqual(['gesture', 'idle-leading']) - vi.advanceTimersByTime(TERMINAL_WRITE_FLUSH_WINDOW_MS - TERMINAL_INTERACTIVE_WRITE_WINDOW_MS) - expect(sink.delivered).toEqual(['gesture', 'idle-leading', 'idle-trailing']) - }) - it('clears interactive state and pending output when a document is replaced', () => { vi.useFakeTimers() const sink = createDeliverySink() diff --git a/mobile/src/test-support/census-source-files.test.ts b/mobile/src/test-support/census-source-files.test.ts deleted file mode 100644 index 404a77fbcb6..00000000000 --- a/mobile/src/test-support/census-source-files.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join, relative } from 'node:path' -import { fileURLToPath } from 'node:url' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { censusSourceFiles, isGeneratedSource } from './census-source-files' - -const mobileRoot = fileURLToPath(new URL('../..', import.meta.url)) - -let scratch = '' - -beforeEach(() => { - scratch = mkdtempSync(join(tmpdir(), 'orca-census-source-files-')) -}) - -afterEach(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function plant(relativePath: string, source: string): void { - const absolute = join(scratch, relativePath) - mkdirSync(join(absolute, '..'), { recursive: true }) - writeFileSync(absolute, source, 'utf8') -} - -describe('the source files a census reads', () => { - it('leaves out build output that would be read as a violating import', () => { - // Generated vendor text can match source rules without any editable repository call site. - const violating = "import { requiredString } from '../../src/shared/rpc-contract/params'\n" - plant('src/components/engine.generated.ts', violating) - plant('src/components/Diagram.tsx', violating) - - const walked = censusSourceFiles(join(scratch, 'src')).map((path) => relative(scratch, path)) - expect(walked).toEqual([join('src', 'components', 'Diagram.tsx')]) - }) - - it('leaves out node_modules, and keeps everything else', () => { - plant('src/a.ts', '') - plant('src/node_modules/dep/index.ts', '') - plant('src/deep/b.tsx', '') - plant('src/notes.md', '') - expect( - censusSourceFiles(join(scratch, 'src')) - .map((path) => relative(scratch, path)) - .sort() - ).toEqual([join('src', 'a.ts'), join('src', 'deep', 'b.tsx'), join('src', 'notes.md')].sort()) - }) - - it('names build output by the suffix the generators write, and nothing else', () => { - expect(isGeneratedSource('mermaid-page-engine.generated.ts')).toBe(true) - expect(isGeneratedSource('route-manifest.generated.tsx')).toBe(true) - expect(isGeneratedSource('generated.ts')).toBe(false) - expect(isGeneratedSource('rpc-client.ts')).toBe(false) - expect(isGeneratedSource('generated-goldens.ts')).toBe(false) - }) - - it('covers every artifact the tree generates, read from the ignore file that lists them', () => { - // Use gitignore as the generated-artifact authority; new names must not silently reintroduce megabytes into source censuses. - const ignored = readFileSync(join(mobileRoot, '.gitignore'), 'utf8') - .split('\n') - .map((line) => line.trim()) - .filter((line) => line.endsWith('.generated.ts')) - expect(ignored.length).toBeGreaterThan(0) - for (const entry of ignored) { - expect(isGeneratedSource(entry), entry).toBe(true) - } - }) -}) diff --git a/mobile/src/test-support/rpc-recording/README.md b/mobile/src/test-support/rpc-recording/README.md index cb81daaa812..e74fc6aedb5 100644 --- a/mobile/src/test-support/rpc-recording/README.md +++ b/mobile/src/test-support/rpc-recording/README.md @@ -42,8 +42,6 @@ inert. It renders its children and keeps its props where a projection can read t nothing else: no callback it is handed is ever invoked, nothing is measured and no navigation happens. `renderedElementProps` is the consequence — an inert list never calls `renderItem`, so the data it was handed is the only record of what the screen would have drawn. -`screen-native-substitutes.test.ts` is the census; it renders every element with a callback prop and -a render callback as children and fails if either is called. Nothing is listed ahead of a reader, and that is a rule rather than an oversight. A member provisioned before any recording reads it converts a refusal that would have forced a decision into @@ -315,8 +313,7 @@ only the uncommitted ones. Recording is deterministic and carries no header, so an unchanged behaviour re-records to the same bytes on any machine: recording everything is always safe, and `git diff` shows only what moved. -Without `--prune`, a golden the manifest stopped deriving is listed and the census test -(`derived-goldens.test.ts`) keeps failing on it; deleting coverage is always explicit. +Without `--prune`, a golden the manifest stopped deriving is listed and remains on disk. Mutants are the defect evidence. `mutants/operation-mutations.ts` holds one anchored source edit per adapter family, and every family's recording must change visible state when its mutant is diff --git a/mobile/src/test-support/rpc-recording/adapter-load-deferral.test.ts b/mobile/src/test-support/rpc-recording/adapter-load-deferral.test.ts deleted file mode 100644 index 49b2cb03fa8..00000000000 --- a/mobile/src/test-support/rpc-recording/adapter-load-deferral.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { MOUNTED_OPERATION_MODULES } from './adapters/mounted-operation-modules' -import type { operationModuleLoader } from './operation-module-loader' - -// Defer product loads until hook mount; registration-time loads apply shared-file mutants repeatedly and obscure adapter failures. -function refusingLoader(): ReturnType { - return { - load: (path: string) => { - throw new Error(`loaded ${path} before a mount ran`) - }, - mutationsApplied: () => 0 - } -} - -describe('adapter mount tables', () => { - it('reads no product source until a mount runs', () => { - const eager = MOUNTED_OPERATION_MODULES.flatMap(({ source, mounts }) => { - try { - mounts(refusingLoader(), {}) - return [] - } catch (error) { - return [`${source} ${error instanceof Error ? error.message : String(error)}`] - } - }) - expect(eager).toEqual([]) - }) -}) diff --git a/mobile/src/test-support/rpc-recording/derived-goldens.test.ts b/mobile/src/test-support/rpc-recording/derived-goldens.test.ts deleted file mode 100644 index c84b52f28cc..00000000000 --- a/mobile/src/test-support/rpc-recording/derived-goldens.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { readdirSync } from 'node:fs' -import { resolve } from 'node:path' -import { describe, expect, it } from 'vitest' -import { derivedGoldens } from './derived-goldens' -import { readScenarios } from './scenario-input' - -const root = resolve(import.meta.dirname, '../../../..') -const input = readScenarios( - process.env.RPC_FOUNDATION_SCENARIOS ?? - resolve(root, 'mobile/rpc-foundation/pilot-scenarios.json') -) -const directory = - process.env.RPC_FOUNDATION_GOLDENS ?? resolve(root, 'mobile/rpc-foundation/goldens') - -describe('derived goldens', () => { - // Check both directions: missing derivations leave orphan files, and missing files leave unrecorded scenarios. - it('derives exactly the goldens on disk', () => { - const derived = derivedGoldens(input.scenarios).map((golden) => golden.id) - const onDisk = readdirSync(directory) - .filter((file) => file.endsWith('.json')) - .map((file) => file.replace(/\.json$/, '')) - expect( - derived.sort(), - 'Record new goldens with `pnpm --dir mobile rpc:record`; delete ones the manifest no longer derives with `pnpm --dir mobile rpc:record --prune`' - ).toEqual(onDisk.sort()) - }) -}) diff --git a/mobile/src/test-support/rpc-recording/native-mounting-substitutes.test.ts b/mobile/src/test-support/rpc-recording/native-mounting-substitutes.test.ts deleted file mode 100644 index cb1c02dd4a3..00000000000 --- a/mobile/src/test-support/rpc-recording/native-mounting-substitutes.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { nativeMountingSubstitutes } from './native-mounting-substitutes' - -/** TypeScript's emitted interop helper, verbatim: what every `import X from` in a mounted module runs. */ -function importDefault(module: unknown): { default?: unknown } { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: mirrors the emit, which reads the marker off an untyped module record. - const record = module as { __esModule?: unknown; default?: unknown } - return record?.__esModule ? record : { default: module } -} - -function substitute(name: string): unknown { - const found = nativeMountingSubstitutes().get(name) - if (found === undefined) { - throw new Error(`no substitute for ${name}`) - } - return found -} - -describe('nativeMountingSubstitutes', () => { - it('names the module and member a recording reached instead of failing on a missing function', () => { - const store = importDefault(substitute('@react-native-async-storage/async-storage')).default - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the member is a function by construction; the test asserts what calling it throws. - const getItem = (store as { getItem: () => unknown }).getItem - expect(() => getItem()).toThrow( - 'Native store reached during recording: @react-native-async-storage/async-storage.getItem' - ) - }) - - it('throws on a member nobody substituted rather than recording an undefined native API', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the read itself is the assertion; the proxy has no declared shape. - expect(() => (substitute('expo-crypto') as { randomUUID?: unknown }).randomUUID).toThrow( - 'Unsubstituted native member: expo-crypto.randomUUID' - ) - }) -}) diff --git a/mobile/src/test-support/rpc-recording/operation-module-loader-work-budget.test.ts b/mobile/src/test-support/rpc-recording/operation-module-loader-work-budget.test.ts deleted file mode 100644 index f57e295cf04..00000000000 --- a/mobile/src/test-support/rpc-recording/operation-module-loader-work-budget.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { nativeMountingSubstitutes } from './native-mounting-substitutes' -import type * as NativeSubstitutesModule from './native-mounting-substitutes' -import { operationModuleLoader } from './operation-module-loader' - -vi.mock('./native-mounting-substitutes', async (original) => { - const module = await original() - return { ...module, nativeMountingSubstitutes: vi.fn(module.nativeMountingSubstitutes) } -}) - -const roots: string[] = [] - -function sourceTree(files: Record): string { - const root = mkdtempSync(join(tmpdir(), 'rpc-loader-work-budget-')) - roots.push(root) - mkdirSync(join(root, 'mobile', 'src'), { recursive: true }) - for (const [name, source] of Object.entries(files)) { - writeFileSync(join(root, 'mobile', 'src', name), source) - } - return root -} - -afterEach(() => { - for (const root of roots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } - vi.clearAllMocks() -}) - -it('builds device substitutes only for a used loader and keeps their state per loader', async () => { - const root = sourceTree({ - 'operation.ts': ` - import * as clipboard from 'expo-clipboard' - export const read = () => clipboard.getStringAsync() - export const write = () => clipboard.setStringAsync('first recording') - ` - }) - const loaders = Array.from({ length: 64 }, () => operationModuleLoader(root)) - expect(nativeMountingSubstitutes).not.toHaveBeenCalled() - type ClipboardOperation = { read: () => Promise; write: () => Promise } - const first = loaders[0].load('mobile/src/operation.ts') - await first.write() - expect(await first.read()).toBe('first recording') - expect(nativeMountingSubstitutes).toHaveBeenCalledTimes(1) - const second = loaders[1].load('mobile/src/operation.ts') - expect(await second.read()).toBe('') - expect(await first.read()).toBe('first recording') - expect(nativeMountingSubstitutes).toHaveBeenCalledTimes(2) -}) diff --git a/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts b/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts index b4877620867..ae8df85b317 100644 --- a/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts +++ b/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts @@ -29,19 +29,6 @@ afterAll(() => { }) describe('the mounted module loader', () => { - it('preserves constants through a star reexport in an evaluated module', () => { - const modules = loaderOver({ - 'constants.ts': `export const CAPABILITY = 'files.mutation-ownership.v1'`, - 'protocol.ts': `export * from './constants'`, - 'operation.ts': ` - import { CAPABILITY } from './protocol' - export const read = () => CAPABILITY - ` - }) - const { read } = modules.load<{ read: () => string }>('mobile/src/operation.ts') - expect(read()).toBe('files.mutation-ownership.v1') - }) - it('follows named reexports reached through the task foundation barrel', () => { const modules = loaderOver({ 'mobile-tasks-legacy-foundation.tsx': `export * from './mapping'`, @@ -152,19 +139,6 @@ describe('the mounted module loader', () => { ) }) - it('refuses a named import of an unlisted package on the read', () => { - const modules = loaderOver({ - 'uses-named.ts': ` - import { thing } from 'expo-not-substituted' - export const read = () => thing - ` - }) - const { read } = modules.load<{ read: () => unknown }>('mobile/src/uses-named.ts') - expect(() => read()).toThrow( - 'Unspecified native mounting dependency: expo-not-substituted.thing' - ) - }) - // Default dependencies may reference native members before an adapter overrides them; import alone must remain possible. it('lets a namespace import of an unlisted package load, and refuses the member it reads', () => { const modules = loaderOver({ diff --git a/mobile/src/test-support/rpc-recording/screen-native-substitutes.test.ts b/mobile/src/test-support/rpc-recording/screen-native-substitutes.test.ts deleted file mode 100644 index 4cc6388b045..00000000000 --- a/mobile/src/test-support/rpc-recording/screen-native-substitutes.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { createElement, type ElementType } from 'react' -import { act, create } from 'react-test-renderer' -import { describe, expect, it } from 'vitest' -import { nativeMountingSubstitutes } from './native-mounting-substitutes' -import { reactNativeScreenMembers } from './screen-native-substitutes' - -function member(module: string, name: string): unknown { - const substitute = nativeMountingSubstitutes().get(module) - if (substitute === undefined) { - throw new Error(`no substitute for ${module}`) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the read is the assertion; a substitute proxy has no declared shape. - return (substitute as Record)[name] -} - -const INERT_ELEMENTS: readonly (readonly [string, string])[] = [ - ...Object.entries(reactNativeScreenMembers()) - .filter(([, value]) => typeof value === 'function') - .map(([name]): readonly [string, string] => ['react-native', name]), - ['react-native-safe-area-context', 'SafeAreaView'] -] - -describe('the inert screen substitutes', () => { - // Preserve children/props while never invoking device callbacks, including render-callback children. - it.each(INERT_ELEMENTS)('renders %s.%s inertly', (module, name) => { - let invoked = 0 - const element = member(module, name) - let rendered: ReturnType | undefined - act(() => { - rendered = create( - createElement( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: every entry above is an inert element component by construction. - element as ElementType, - { testID: name, onPress: () => invoked++, renderItem: () => invoked++ }, - 'child' - ) - ) - }) - const tree = rendered?.toJSON() - expect(invoked).toBe(0) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a rendered host node carries exactly these fields. - const node = tree as { type: string; props: Record; children: unknown } - expect(node.props.testID).toBe(name) - expect(typeof node.props.onPress).toBe('function') - expect(node.children).toEqual(['child']) - }) - - it('drops a render callback passed as children rather than calling it', () => { - let invoked = 0 - let rendered: ReturnType | undefined - act(() => { - rendered = create( - createElement( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the substitute is an inert element component by construction. - member('react-native', 'Pressable') as ElementType, - {}, - // @ts-expect-error -- deliberately invalid function children; asserts the substitute drops them - () => { - invoked++ - return null - } - ) - ) - }) - expect(invoked).toBe(0) - const tree = rendered?.toJSON() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a rendered host node carries exactly these fields. - expect((tree as { children: unknown }).children).toBeNull() - }) -}) diff --git a/mobile/src/test-support/rpc-recording/vitest-recording-scheduler.test.ts b/mobile/src/test-support/rpc-recording/vitest-recording-scheduler.test.ts index cadfa18984e..d0cf2fed5f7 100644 --- a/mobile/src/test-support/rpc-recording/vitest-recording-scheduler.test.ts +++ b/mobile/src/test-support/rpc-recording/vitest-recording-scheduler.test.ts @@ -50,10 +50,4 @@ describe('recording scheduler randomness', () => { const expected = [{ name: 'draw', ordinal: 1, value: SEEDED_FIRST_DRAW }] expect([first, later]).toEqual([expected, expected]) }) - - it('draws the same seeded value before the first drain as after it', async () => { - expect(await record('draw-before-drain', false)).toEqual([ - { name: 'draw', ordinal: 1, value: SEEDED_FIRST_DRAW } - ]) - }) }) diff --git a/mobile/src/test-support/webview-document-census.ts b/mobile/src/test-support/webview-document-census.ts deleted file mode 100644 index 0748aacb943..00000000000 --- a/mobile/src/test-support/webview-document-census.ts +++ /dev/null @@ -1,289 +0,0 @@ -import { readdirSync, readFileSync } from 'node:fs' -import { join } from 'node:path' -import { parseSync } from 'oxc-parser' - -// Census every WebView document with AST readers: module evaluation can retain the first mount’s nodes across remounts. -// Declarations can run work too, while literal shape alone implies no effect. - -const DECLARATION_KINDS = new Set([ - 'ImportDeclaration', - 'ExportNamedDeclaration', - 'ExportDefaultDeclaration', - 'ExportAllDeclaration', - 'FunctionDeclaration', - 'ClassDeclaration', - 'VariableDeclaration', - 'TSTypeAliasDeclaration', - 'TSInterfaceDeclaration', - 'TSEnumDeclaration', - 'TSModuleDeclaration', - 'TSDeclareFunction', - 'TSImportEqualsDeclaration', - 'EmptyStatement' -]) - -const RUNS_NOW = new Set([ - 'CallExpression', - 'NewExpression', - 'AwaitExpression', - 'TaggedTemplateExpression' -]) - -/** What an initialiser *is* rather than what it does: its body runs later, not now. */ -const RUNS_LATER = new Set(['FunctionExpression', 'ArrowFunctionExpression', 'ClassExpression']) - -function fieldsOf(node: unknown): [string, unknown][] { - return node !== null && typeof node === 'object' && !Array.isArray(node) - ? Object.entries(node) - : [] -} - -function stringField(node: unknown, key: string): string { - const found = fieldsOf(node).find(([name]) => name === key)?.[1] - return typeof found === 'string' ? found : '' -} - -function field(node: unknown, key: string): unknown { - return fieldsOf(node).find(([name]) => name === key)?.[1] -} - -function isElementGlobal(node: unknown): boolean { - const name = stringField(node, 'name') - return stringField(node, 'type') === 'Identifier' && (name === 'document' || name === 'window') -} - -function initialiserRuns(node: unknown): boolean { - if (Array.isArray(node)) { - return node.some(initialiserRuns) - } - const type = stringField(node, 'type') - if (RUNS_NOW.has(type)) { - return true - } - if (RUNS_LATER.has(type)) { - return false - } - if (type === 'MemberExpression' && isElementGlobal(field(node, 'object'))) { - return true - } - return fieldsOf(node).some(([key, value]) => key !== 'type' && initialiserRuns(value)) -} - -function readsTheDocument(node: unknown): boolean { - if (Array.isArray(node)) { - return node.some(readsTheDocument) - } - if (isElementGlobal(node)) { - return true - } - return fieldsOf(node).some(([key, value]) => key !== 'type' && readsTheDocument(value)) -} - -function parseModule(name: string, source: string) { - const { program, errors } = parseSync(`${name}.ts`, source, { lang: 'ts' }) - if (errors.length > 0) { - throw new Error(`[webview-document-census] ${name}.ts did not parse: ${errors[0]?.message}`) - } - return program -} - -// Do not descend into default-exported function bodies; declaration alone does not execute their calls. -const DECLARES_WITHOUT_RUNNING = new Set(['FunctionDeclaration', 'TSDeclareFunction']) - -// Detect evaluated declaration initializers, static class members and default-export expressions as module work. -export function parseTimeEffects(name: string, source: string): string[] { - const effects: string[] = [] - const report = (node: unknown) => { - effects.push(`${name}: ${source.slice(numberField(node, 'start'), numberField(node, 'end'))}`) - } - - for (const statement of parseModule(name, source).body) { - if (!DECLARATION_KINDS.has(statement.type)) { - effects.push(`${name}: ${statement.type}`) - continue - } - const exported = - statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportDefaultDeclaration' - const declared = exported ? (field(statement, 'declaration') ?? statement) : statement - const declaredType = stringField(declared, 'type') - - if (declaredType === 'VariableDeclaration') { - for (const declarator of arrayField(declared, 'declarations')) { - const init = field(declarator, 'init') - if (init && initialiserRuns(init)) { - report(declarator) - } - } - continue - } - - if (declaredType === 'ClassDeclaration' || declaredType === 'ClassExpression') { - for (const member of arrayField(field(declared, 'body'), 'body')) { - // Static blocks/fields run with class evaluation; instance fields run later at construction. - if (stringField(member, 'type') === 'StaticBlock') { - report(member) - } else if (field(member, 'static') === true && initialiserRuns(field(member, 'value'))) { - report(member) - } - } - continue - } - - if ( - statement.type === 'ExportDefaultDeclaration' && - !DECLARES_WITHOUT_RUNNING.has(declaredType) && - initialiserRuns(declared) - ) { - report(declared) - } - } - return effects -} - -export function topLevelDeclarationsReachAnElement(name: string, source: string): boolean { - return parseModule(name, source) - .body.filter( - (statement) => - statement.type === 'VariableDeclaration' || - (statement.type === 'ExportNamedDeclaration' && - statement.declaration?.type === 'VariableDeclaration') - ) - .some(readsTheDocument) -} - -// Read ordered lifecycle calls from the AST so unwind mentions cannot count as starts. -export function sequenceCalls(source: string, functionName: string, ignore: string[]): string[] { - const declaration = parseModule('sequence', source) - .body.map((statement) => - statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement - ) - .find( - (node) => - node?.type === 'FunctionDeclaration' && - stringField(field(node, 'id'), 'name') === functionName - ) - const called: string[] = [] - const walk = (node: unknown): void => { - if (Array.isArray(node)) { - node.forEach(walk) - return - } - if (stringField(node, 'type') === 'CallExpression') { - const name = stringField(field(node, 'callee'), 'name') - if (name !== '' && !ignore.includes(name)) { - called.push(name) - } - } - fieldsOf(node).forEach(([key, value]) => { - if (key !== 'type') { - walk(value) - } - }) - } - walk(declaration) - return called -} - -// Stop at function-owned bindings, which belong to calls; blocks still belong to the module. -const OWNS_ITS_BINDINGS = new Set([ - 'FunctionDeclaration', - 'FunctionExpression', - 'ArrowFunctionExpression', - 'ClassDeclaration', - 'ClassExpression', - 'TSDeclareFunction' -]) - -function arrayField(node: unknown, key: string): unknown[] { - const found = field(node, key) - return Array.isArray(found) ? found : [] -} - -function numberField(node: unknown, key: string): number { - const found = field(node, key) - return typeof found === 'number' ? found : -1 -} - -// Walk top-level mutable bindings through exports, blocks and loops; stop at function scopes. -export function moduleLevelMutableBindings(name: string, source: string): string[] { - const found: string[] = [] - const walk = (node: unknown): void => { - if (Array.isArray(node)) { - node.forEach(walk) - return - } - const type = stringField(node, 'type') - if (OWNS_ITS_BINDINGS.has(type)) { - return - } - if (type === 'VariableDeclaration') { - const kind = stringField(node, 'kind') - if (kind === 'let' || kind === 'var') { - const declarations = field(node, 'declarations') - for (const declarator of Array.isArray(declarations) ? declarations : []) { - const id = field(declarator, 'id') - found.push( - `${name}: ${kind} ${source.slice(numberField(id, 'start'), numberField(id, 'end'))}` - ) - } - } - return - } - fieldsOf(node).forEach(([key, value]) => { - if (key !== 'type') { - walk(value) - } - }) - } - walk(parseModule(name, source).body) - return found -} - -// Find lifecycle exports by name and scope parameter, including async/wrapped declarations; textual matching can silently miss both sides of a set comparison. -export function exportedLifecycleFunctions( - source: string, - keyword: 'start' | 'stop', - scopeType: string -): string[] { - const names: string[] = [] - for (const statement of parseModule('lifecycle', source).body) { - if (statement.type !== 'ExportNamedDeclaration') { - continue - } - const declared = field(statement, 'declaration') - if (stringField(declared, 'type') !== 'FunctionDeclaration') { - continue - } - const name = stringField(field(declared, 'id'), 'name') - if (!name.startsWith(keyword)) { - continue - } - // Lifecycle starts take only scope; startEdgeScroll(scope, dir) is an action, not module startup. - const params = arrayField(declared, 'params') - const [first] = params - if (params.length !== 1 || stringField(first, 'name') !== 'scope') { - continue - } - const annotation = field(first, 'typeAnnotation') - const written = source - .slice(numberField(annotation, 'start'), numberField(annotation, 'end')) - .replace(/^:\s*/, '') - if (written === scopeType) { - names.push(name) - } - } - return names -} - -// Discover modules from the directory so unlisted files cannot evade lifecycle rules. -export function documentModuleNames(directory: string, except: string[]): string[] { - return readdirSync(directory) - .filter((name) => name.endsWith('.ts') && !name.includes('.test')) - .map((name) => name.replace(/\.ts$/, '')) - .filter((name) => !except.includes(name)) - .sort() -} - -export function documentModuleSource(directory: string, name: string): string { - return readFileSync(join(directory, `${name}.ts`), 'utf8') -} diff --git a/mobile/src/worktree/agent-row-lineage-parity.test.ts b/mobile/src/worktree/agent-row-lineage-parity.test.ts index 0606afc53ba..1710805c7c4 100644 --- a/mobile/src/worktree/agent-row-lineage-parity.test.ts +++ b/mobile/src/worktree/agent-row-lineage-parity.test.ts @@ -1,6 +1,6 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { flattenAgentRowLineage, type AgentRowNode } from './agent-row-lineage' +import { flattenAgentRowLineage } from './agent-row-lineage' function row(paneKey: string, parentPaneKey: string | null): RuntimeWorktreeAgentRow { return { @@ -42,34 +42,4 @@ describe('agent lineage traversal', () => { [3, 2] ]) }) - - it('copies no ancestor members while traversing a long lineage', () => { - const rows = Array.from({ length: 512 }, (_, index) => - row(`pane-${index}`, index === 0 ? null : `pane-${index - 1}`) - ) - const NativeSet = globalThis.Set - let copiedMembers = 0 - class ObservedSet extends NativeSet { - constructor(values?: Iterable | null) { - super() - if (values) { - for (const value of values) { - copiedMembers += 1 - this.add(value) - } - } - } - } - vi.stubGlobal('Set', ObservedSet) - let actual: AgentRowNode[] - try { - actual = flattenAgentRowLineage(rows) - } finally { - vi.unstubAllGlobals() - } - expect(copiedMembers).toBe(0) - expect(actual.map((node) => [node.row.paneKey, node.depth])).toEqual( - rows.map((agent, index) => [agent.paneKey, index]) - ) - }) }) diff --git a/src/cli/chat-history.ts b/src/cli/chat-history.ts index db4c70730cd..aad6b96ddeb 100644 --- a/src/cli/chat-history.ts +++ b/src/cli/chat-history.ts @@ -2,6 +2,7 @@ import type { AgentSessionHistoryPage, AgentSessionHistoryResult } from '../shared/agent-session/agent-session-wire' +import type { AgentSessionWorkState } from '../shared/agent-session/agent-session-work-state' import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../shared/agent-session/agent-session-wire' import { AGENT_SESSION_UNATTACHED_REFUSAL_CODE, @@ -56,8 +57,45 @@ export async function readTranscript( return { ...response, result: { session, entries, cursor: page.window.newest, truncated } } } -export function requireWorkingFlag(page: AgentSessionHistoryPage): void { - if (page.working === undefined) { +/** Older hosts' history pages may omit `working`. */ +export type ChatWorkState = Omit & { working?: boolean } + +/** One command's reads of the facts a send or wait decides from. Hosts without + * `agentSession.workState` answer from a history page for the rest of the command. */ +export function chatWorkStateReader( + client: RuntimeClient, + session: string +): () => Promise { + let historyOnly = false + return async () => { + if (!historyOnly) { + try { + const response = await client.call('agentSession.workState', { + sessionId: session + }) + return response.result + } catch (error) { + if (!(error instanceof RuntimeClientError && error.code === 'method_not_found')) { + throw explainChatRefusal(error, session, 'read') + } + historyOnly = true + } + } + const { page } = (await readHistory(client, session, 1)).result + return { + ...(page.working !== undefined ? { working: page.working } : {}), + actionablePrompt: (page.actionablePromptIds?.length ?? 0) > 0, + ...(page.queuedMessages !== undefined + ? { queuedMessageIds: (page.queuedMessages ?? []).map((m) => m.messageId) } + : {}), + nextQueuedMessageId: page.nextQueuedMessageId ?? null, + ...(page.fence !== undefined ? { fence: page.fence } : {}) + } + } +} + +export function requireWorkingFlag(state: { working?: boolean }): void { + if (state.working === undefined) { throw new RuntimeClientError( 'incompatible_runtime', 'This Orca host does not report when a chat is working, so it cannot wait. Update Orca on the host.' @@ -67,26 +105,26 @@ export function requireWorkingFlag(page: AgentSessionHistoryPage): void { // Settled means no running turn or unanswered send, or a question/approval waiting for the user. export async function waitForChat( - client: RuntimeClient, - session: string, + readWorkState: () => Promise, timeoutMs: number | undefined, queuedMessageId?: string ): Promise { const deadline = timeoutMs === undefined ? Infinity : Date.now() + timeoutMs for (;;) { - const { page } = (await readHistory(client, session, 1)).result - requireWorkingFlag(page) - if ((page.actionablePromptIds?.length ?? 0) > 0) { + const state = await readWorkState() + requireWorkingFlag(state) + if (state.actionablePrompt) { return 'blocked' } // Between turns the host names its next automatic send while working is briefly false. const sendsNext = structuredAgentSessionQueueSendsNext( - page.nextQueuedMessageId, - page.working === true + state.nextQueuedMessageId, + state.working === true ) - if (!page.working && !sendsNext) { + if (!state.working && !sendsNext) { // Still queued with nothing running or about to send: stopped, failed or held across a reopen. - const held = page.queuedMessages?.some((m) => m.messageId === queuedMessageId) === true + const held = + queuedMessageId !== undefined && state.queuedMessageIds?.includes(queuedMessageId) === true return held ? 'held' : 'done' } if (Date.now() >= deadline) { diff --git a/src/cli/handlers/chat.test.ts b/src/cli/handlers/chat.test.ts index 177a839ad13..5b13aa1559d 100644 --- a/src/cli/handlers/chat.test.ts +++ b/src/cli/handlers/chat.test.ts @@ -35,6 +35,10 @@ function historyPage( }) } +function workState(fields: Record) { + return ok({ working: false, actionablePrompt: false, ...fields }) +} + function item(body: unknown) { return { itemId: 'i', revision: 1, sequence: 1, observedAt: 1, body } } @@ -90,7 +94,7 @@ afterEach(() => { describe('chat send', () => { it('sends a host-valid message fenced to the chat it read, queued while the agent works', async () => { const client = fakeClient([ - historyPage([], 7), + workState({ fence: 7 }), ok({ ok: true, replayed: false, @@ -122,7 +126,7 @@ describe('chat send', () => { it('reports a host refusal as an error instead of a sent message', async () => { const client = fakeClient([ - historyPage([], 2), + workState({ fence: 2 }), ok({ ok: false, refusal: { code: 'agent_session_fence_mismatch', message: 'The chat restarted.' } @@ -136,7 +140,7 @@ describe('chat send', () => { it('with --wait, waits for its queued message to run and returns that turn', async () => { vi.useFakeTimers() const client = fakeClient([ - historyPage([], 7, { working: true }), + workState({ fence: 7, working: true }), ok({ ok: true, replayed: false, @@ -148,13 +152,9 @@ describe('chat send', () => { } }), // The earlier turn ended, but the queued message has not been handed to the agent yet. - historyPage([], 7, { - working: false, - queuedMessages: [{ messageId: 'q-1' }], - nextQueuedMessageId: 'q-1' - }), - historyPage([], 7, { working: true, queuedMessages: [] }), - historyPage([], 7, { working: false, queuedMessages: [], actionablePromptIds: [] }), + workState({ fence: 7, queuedMessageIds: ['q-1'], nextQueuedMessageId: 'q-1' }), + workState({ fence: 7, working: true, queuedMessageIds: [] }), + workState({ fence: 7, queuedMessageIds: [] }), historyPage([ item({ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Earlier' }] }), item({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Old reply' }] }), diff --git a/src/cli/handlers/chat.ts b/src/cli/handlers/chat.ts index 51d6a8dbc0f..f1c2322f312 100644 --- a/src/cli/handlers/chat.ts +++ b/src/cli/handlers/chat.ts @@ -17,9 +17,9 @@ import { AGENT_STATUS_STATES } from '../../shared/agent-status/contracts/agent-s import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env' import { DEFAULT_READ_LIMIT, + chatWorkStateReader, explainChatRefusal, formatSettled, - readHistory, readSettledTurn, readTranscript, requireWorkingFlag, @@ -122,7 +122,7 @@ export const CHAT_HANDLERS: Record = { 'chat wait': async ({ flags, client, json }) => { const session = readSession(flags, client) const timeoutMs = getOptionalPositiveIntegerFlag(flags, 'timeout-ms') - const settled = await waitForChat(client, session, timeoutMs) + const settled = await waitForChat(chatWorkStateReader(client, session), timeoutMs) printResult(await readSettledTurn(client, session, settled), json, formatSettled) }, 'chat send': async ({ flags, client, cwd, json }) => { @@ -146,11 +146,12 @@ export const CHAT_HANDLERS: Record = { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY ) === true // The send is fenced to the session's current runtime, so a restarted chat refuses it. - const { page } = (await readHistory(client, session, 1)).result + const readWorkState = chatWorkStateReader(client, session) + const state = await readWorkState() if (wait) { - requireWorkingFlag(page) + requireWorkingFlag(state) } - const { fence } = page + const { fence } = state if (fence === undefined) { throw new RuntimeClientError( 'agent_session_not_running', @@ -188,7 +189,7 @@ export const CHAT_HANDLERS: Record = { return } const queuedId = 'queued' in value ? value.queued.messageId : undefined - const settled = await waitForChat(client, session, timeoutMs, queuedId) + const settled = await waitForChat(readWorkState, timeoutMs, queuedId) const turn = await readSettledTurn(client, session, settled) printResult({ ...turn, result: { ...sent, ...turn.result } }, json, formatSettled) } diff --git a/src/main/acp/session/acp-structured-startup-diagnostic.test.ts b/src/main/acp/session/acp-structured-startup-diagnostic.test.ts new file mode 100644 index 00000000000..70efb7b0e77 --- /dev/null +++ b/src/main/acp/session/acp-structured-startup-diagnostic.test.ts @@ -0,0 +1,150 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { closeProviderTimelineRigs } from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { collectBundle } from '../../observability/bundle' +import { createLocalFileSink } from '../../observability/local-file-sink' +import { setActiveSink } from '../../observability/tracer' +import { acpLaunchSpecFor } from '../launch/acp-launch-registry' +import { GROK, openAcpAdapterRig } from './testing/acp-structured-adapter.test-support' + +afterEach(async () => { + setActiveSink(null) + vi.restoreAllMocks() + await closeProviderTimelineRigs() +}) + +it.each(['initialize', 'session/new', 'authenticate'])( + 'keeps a live %s rejection and stderr in the startup failure', + async (method) => { + const rig = await openAcpAdapterRig({ + spec: acpLaunchSpecFor('antigravity')!, + initialize: { authMethods: [{ id: 'oauth-personal', name: 'Google' }] }, + script: (agent) => { + if (method === 'authenticate') { + agent.on('session/new', (frame) => agent.fail(frame, -32000, 'Sign in')) + } + agent.on(method, (frame) => { + rig.child().stderr = 'harness: Permission denied {"token":"stderr-private"}' + agent.fail(frame, -32603, 'Internal error', { + details: '{"error":"Cannot execute localharness","authorization":"Bearer rpc-private"}' + }) + }) + } + }) + await rig.acquire() + expect(rig.openVerdict()).toMatchObject({ + retry: 'never', + cause: { + name: 'AcpAgentError', + code: -32603, + data: { + details: '{"error":"Cannot execute localharness","authorization":"Bearer rpc-private"}' + } + }, + fact: { + kind: 'startFailed', + detail: { + audience: 'log', + text: '{"error":"Cannot execute localharness",[redacted:labeled-kv]}\nharness: Permission denied {[redacted:labeled-kv]}' + } + } + }) + } +) + +it('reserves space for long RPC details and the newest redacted stderr', async () => { + const rig = await openAcpAdapterRig({ + script: (agent) => + agent.on('session/new', (frame) => { + rig.child().stderr = `${'old stderr\n'.repeat(100)}recent harness failure token=private` + agent.fail(frame, -32603, 'Internal error', { details: `RPC evidence ${'x'.repeat(700)}` }) + }) + }) + await rig.acquire() + const detail = rig.openVerdict()?.fact.detail?.text + expect(detail).toHaveLength(512) + expect(detail).toContain('RPC evidence') + expect(detail).toContain('recent harness failure [redacted:labeled-kv]') + expect(detail).not.toContain('private') +}) + +it('keeps existing sign-in failure wording free of preceding stderr', async () => { + const rig = await openAcpAdapterRig({ + script: (agent) => + agent.on('session/new', (frame) => { + rig.child().stderr = 'unrelated preceding stderr' + agent.fail(frame, -32000, 'Please sign in') + }) + }) + await rig.acquire() + expect(rig.openVerdict()?.fact.kind).toBe('notSignedIn') + expect(rig.openVerdict()?.fact.detail?.text).not.toContain('preceding stderr') +}) + +it.each(['load', 'resume'] as const)( + 'retains a rejected %s in the trace and exported bundle after fallback succeeds', + async (method) => { + const directory = await mkdtemp(join(tmpdir(), 'acp-start-diagnostic-')) + const traceFile = join(directory, 'main.trace.ndjson') + const sink = createLocalFileSink({ filePath: traceFile }) + onTestFinished(async () => { + setActiveSink(null) + sink.close() + await rm(directory, { recursive: true, force: true }) + }) + setActiveSink(sink) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const rig = await openAcpAdapterRig({ + spec: { ...GROK, resumePreference: method === 'resume' ? 'resume' : undefined }, + initialize: { + agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } } + }, + launch: { + resume: { + sessionId: 'saved-session', + key: 'acp:grok:saved', + mayBeUnsaved: async () => false, + lossKeys: [] + } + }, + deps: { logger: createStructuredAgentSessionLogger() }, + script: (agent) => + agent.on(`session/${method}`, (frame) => { + rig.child().stderr = + 'saved database unavailable "authorization":"Bearer stderr-private" refresh_token="opaque-oauth-proof" harness evidence' + agent.fail( + frame, + -32603, + 'Internal error', + method === 'load' + ? { reason: 'database open failed', token: 'rpc-private' } + : { details: '{"error":"database open failed","token":"rpc-private"}' } + ) + }) + }) + await rig.acquire() + expect(rig.openVerdict()).toBeUndefined() + expect(rig.started().link?.origin).toBe('created') + await sink.flushAsync() + const bundle = collectBundle({ + traceFilePath: traceFile, + maxFiles: 1, + appVersion: '1', + platform: 'darwin', + arch: 'arm64', + osRelease: '24', + orcaChannel: 'dev' + }) + expect(bundle.payload).toContain('agentSession.acp-restore-failed') + expect(bundle.payload).toContain('providerDetail') + expect(bundle.payload).toContain('database open failed') + expect(bundle.payload).toContain('saved database unavailable [redacted:labeled-kv]') + expect(bundle.payload).not.toContain('rpc-private') + expect(bundle.payload).not.toContain('stderr-private') + expect(bundle.payload).toContain('harness evidence') + expect(bundle.payload).not.toContain('opaque-oauth-proof') + } +) diff --git a/src/main/acp/session/start/acp-startup-diagnostic.ts b/src/main/acp/session/start/acp-startup-diagnostic.ts new file mode 100644 index 00000000000..149ac403dd9 --- /dev/null +++ b/src/main/acp/session/start/acp-startup-diagnostic.ts @@ -0,0 +1,41 @@ +import { + MAX_PROVIDER_DIAGNOSTIC_CHARS, + providerDiagnostic, + providerDiagnosticOf, + withProviderDiagnostic +} from '../../../../shared/agent-session/failures/agent-session-failure' +import { redactString, redactValue } from '../../../observability/redactor' +import { providerStderrForDisplay } from '../../../provider-process/provider-spawn-failure-report' +import type { AcpDialect } from '../../acp-dialects/acp-dialect' +import type { AcpStructuredConnection } from '../../process/acp-structured-connection' +import { AcpAgentError, acpErrorDataWords } from '../../transport/acp-errors' +import { acpAuthenticationRequired, acpPromptErrorDetail } from '../../turns/acp-prompt-failure' + +/** Keep the rejection's type and retry meaning; diagnostics belong to the existing Details. */ +export function withAcpStartupDiagnostic( + error: unknown, + connection: AcpStructuredConnection, + dialect: AcpDialect +): void { + if ( + !(error instanceof AcpAgentError) || + acpAuthenticationRequired(dialect, error) || + providerDiagnosticOf(error) + ) { + return + } + let words = acpPromptErrorDetail(dialect, error) + if (error.data != null && acpErrorDataWords(error.data) === undefined) { + try { + words = dialect.promptErrorDetail?.(error) ?? JSON.stringify(redactValue(error.data)) ?? words + } catch { + // Diagnostic formatting must never replace the agent's rejection. + } + } + const rpc = redactString(words).trim() + const stderr = redactString(providerStderrForDisplay(connection.stderrTail())).trim() + const limit = MAX_PROVIDER_DIAGNOSTIC_CHARS + const reply = rpc.slice(0, stderr ? Math.floor(limit / 2) : limit) + const tail = stderr.slice(-(limit - (reply ? reply.length + 1 : 0))) + withProviderDiagnostic(error, providerDiagnostic([reply, tail].filter(Boolean).join('\n'), 'log')) +} diff --git a/src/main/acp/session/start/acp-structured-handshake.ts b/src/main/acp/session/start/acp-structured-handshake.ts index 77807512031..1aa4d5c8450 100644 --- a/src/main/acp/session/start/acp-structured-handshake.ts +++ b/src/main/acp/session/start/acp-structured-handshake.ts @@ -1,5 +1,6 @@ import { withStructuredHistoryInvocation } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-invocation' import { observeAcpForkSupport } from '../../capabilities/acp-fork-support' +import { withAcpStartupDiagnostic } from './acp-startup-diagnostic' // An ACP child's handshake, run after the host has published it: initialize, reopen the chat's // session or start a new one, then return its protocol facts to the host. A saved session the // agent cannot reopen is replaced by a new one, with a warning row that any later start writes if @@ -109,6 +110,7 @@ export async function initializeAcpStructuredSession( replayed = input.lanes.finishLoad() attaching.translator.finishLoad() } catch (error) { + withAcpStartupDiagnostic(error, connection, spec.dialect) takeover = await acpReopenTakeover(error, resume, { // An agent already exited, its output still draining, has no session to take over in. over: connection.closed || connection.exited || input.abandoned(), diff --git a/src/main/acp/session/start/acp-structured-start-open.ts b/src/main/acp/session/start/acp-structured-start-open.ts index b82964e81bc..5dbebf5d397 100644 --- a/src/main/acp/session/start/acp-structured-start-open.ts +++ b/src/main/acp/session/start/acp-structured-start-open.ts @@ -7,6 +7,7 @@ import { acpAgentName } from '../acp-structured-agent-definitions' import { acpStartupFailure } from '../children/acp-structured-child' import type { AcpStructuredChildren } from '../children/acp-structured-child-lifecycle' import { acpStartFailure } from './acp-startup-outcome' +import { withAcpStartupDiagnostic } from './acp-startup-diagnostic' /** A start's open answers with the agent's verdict; a child that already ended answers with how * it ended, and an answer its own exit followed is still worded as that exit. */ @@ -40,6 +41,9 @@ export async function openAcpStart( throw failure.detail ? withProviderDiagnostic(refusal, failure.detail) : refusal }) } catch (error) { + if (child) { + withAcpStartupDiagnostic(error, child.connection, child.spec.dialect) + } throw acpStartFailure(error, child?.connection.exited === true && !child.closeRequested) } } diff --git a/src/main/native-chat/agent-session-journal/journal-sql-status-context.ts b/src/main/native-chat/agent-session-journal/journal-sql-status-context.ts index f6f9cf05186..671112da65e 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-status-context.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-status-context.ts @@ -2,7 +2,7 @@ import type { AgentJournalRenderItem, AgentJournalSubmission } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/agent-session/view/structured-agent-session-live-turn' +import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record' import type { JournalLatestStop } from './context-epochs/journal-stop-turn-end' import { journalContextEpoch } from './context-epochs/journal-context-epoch' import type { JournalSqlScope } from './journal-sql-scope' @@ -173,8 +173,9 @@ export class JournalSqlStatusContext { itemFence = (id: string) => this.current(id)?.fence runningTurn = () => { - const boundary = this.select({ kind: 'boundary', raw: true })[Symbol.iterator]().next().value - return boundary ? runningStructuredAgentSessionTurnItemBySequence([boundary.item]) : null + const item = this.select({ kind: 'boundary', raw: true })[Symbol.iterator]().next().value?.item + const turn = item ? readAgentJournalTurn(item.body) : null + return item && turn?.state === 'running' ? { item, turnId: turn.turnId } : null } recoverableSubmissions = (): AgentJournalSubmission[] => { diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts index b71ae0cc265..20266116bf6 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts @@ -59,7 +59,8 @@ export class StructuredAgentSessionHost { private readonly lifetime: HostTypes.StructuredAgentSessionConversationLifetime private readonly conversationDelivery: conversation.StructuredAgentSessionConversationDelivery private readonly eventRecovery: EventRecovery - private readonly backgroundTasks: BackgroundTasks + /** History and work-state reads, which open a chat at rest without starting its agent. */ + readonly backgroundTasks: BackgroundTasks readonly restartResume: StructuredAgentSessionRestartResume readonly usageLimitContinue: ReturnType diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-logger.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-logger.ts index 784ba71ffe4..42c33363d1f 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-logger.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-logger.ts @@ -1,6 +1,11 @@ // Require failure reporting for errors hidden from UI; production writes local traces and console. import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' +import { + providerDiagnostic, + providerDiagnosticOf +} from '../../../../shared/agent-session/failures/agent-session-failure' +import { redactString } from '../../../observability/redactor' import { startSpan } from '../../../observability/tracer' import { createStructuredAgentSessionLogRepeats } from './structured-agent-session-log-repeats' @@ -78,7 +83,7 @@ export function createStructuredAgentSessionLogger(options?: { ...errorAttributes(error) } // Exclude stack and timing so equivalent failures share a repeat key. - const { openMs: _openMs, ...keyed } = attributes + const { openMs: _openMs, providerDetail: _providerDetail, ...keyed } = attributes const suppressed = repeats.admit( stableJson([ scope, @@ -130,7 +135,11 @@ function errorAttributes(error: unknown): Record { // Refusal messages contain only the code; wire-safe reason distinguishes them. const details = isAgentSessionRefusalError(error) ? error.refusal.details : undefined const reason = details && 'reason' in details ? details.reason : undefined + const diagnostic = providerDiagnosticOf(error) + const detail = + diagnostic && providerDiagnostic(redactString(diagnostic.text), diagnostic.audience) return { + ...(detail ? { providerDetail: detail.text } : {}), ...(code !== undefined ? { errorCode: code } : {}), ...(sqliteCode !== undefined ? { errorErrcode: sqliteCode } : {}), ...(typeof reason === 'string' ? { refusalReason: reason } : {}), diff --git a/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts b/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts index ae920faf495..b234e410a17 100644 --- a/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts +++ b/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-background-task-channel.ts @@ -1,11 +1,15 @@ import { readForkMarker } from '../history/agent-session-fork-marker' import { structuredAgentSessionOwnerStatus } from '../../host/structured-agent-session-owner-status' +import { heldStructuredAgentSessionCurrentWork } from '../../observations/structured-agent-session-host-current-work' import type { AgentSessionCurrentRequestsRead } from '../../../../../shared/agent-session/requests/agent-session-current-requests-wire' import { readCurrentRequestsPiece } from '../../observations/agent-session-current-requests' import type { AgentSessionHistoryRequest, AgentSessionHistoryResult } from '../../../../../shared/agent-session/agent-session-wire' +import type { AgentSessionWorkState } from '../../../../../shared/agent-session/agent-session-work-state' +import { AgentSessionRefusalError } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals' +import { AGENT_SESSION_NOT_ATTACHED } from '../../operations/structured-agent-session-mutation-refusals' import type { AgentSessionBackgroundTaskState } from '../../../../../shared/agent-session/agent-session-background-task-wire' import type { AgentChildWorkView } from '../../../../../shared/agent-status/child-work/agent-status-child-work-view' import { structuredChildWorkLegacyTasks } from '../../../../../shared/agent-session/structured-agent-session-child-work-legacy' @@ -106,6 +110,37 @@ export class StructuredAgentSessionBackgroundTaskChannel { } } + /** What a waiter decides from, from the sources history pages state, without building a page. */ + async workState(sessionId: string): Promise { + await this.conversation(sessionId) + let work = await this.currentWork(sessionId) + if (!work) { + const session = this.sessions.get(sessionId) + if (!session) { + throw new AgentSessionRefusalError(AGENT_SESSION_NOT_ATTACHED) + } + work = await heldStructuredAgentSessionCurrentWork( + this.deps.store, + sessionId, + session.journal, + session + ) + } + const queue = await this.subscribers.readQueuePublication(sessionId) + const fence = this.deps.store.getConversation(sessionId)?.currentFence + return { + working: work.working(), + actionablePrompt: work.hasActionablePrompt(), + ...(queue !== undefined + ? { + queuedMessageIds: (queue.queuedMessages ?? []).map((card) => card.messageId), + nextQueuedMessageId: queue.nextQueuedMessageId + } + : {}), + ...(fence !== undefined ? { fence } : {}) + } + } + async currentRequests(request: AgentSessionCurrentRequestsRead) { await this.conversation(request.sessionId) const work = await this.currentWork(request.sessionId) diff --git a/src/main/observability/credential-assignment-redaction.ts b/src/main/observability/credential-assignment-redaction.ts new file mode 100644 index 00000000000..ed378777fd5 --- /dev/null +++ b/src/main/observability/credential-assignment-redaction.ts @@ -0,0 +1,71 @@ +const CREDENTIAL_ASSIGNMENT = /(? { expect(out).toContain('after') expect(out).not.toContain('xyz') }) + + it.each([ + { + name: 'compound OAuth names and ordinary quoted escapes', + text: String.raw`{"refresh_token":"synthetic-refresh","accessToken":"synthetic-access","client_secret":"synthetic-client","token":"synthetic-token\"private-suffix","max_tokens":42,"token_count":3,"tokenCount":4,"cause":"harness unavailable"}`, + secrets: ['synthetic-refresh', 'synthetic-access', 'synthetic-client', 'private-suffix'], + keep: ['"max_tokens":42', '"token_count":3', '"tokenCount":4', 'harness unavailable'] + }, + { + name: 'one serialization layer of quoted labels and values', + text: String.raw`body: {\"token\":\"synthetic-token\\\"private-suffix\",\"refresh_token\":\"synthetic-escaped\"} harness unavailable`, + secrets: ['synthetic-token', 'private-suffix', 'synthetic-escaped'], + keep: ['body:', 'harness unavailable'] + }, + { + name: 'unterminated quoted values', + text: 'refresh_token="synthetic with private spaces\nharness unavailable tokenCount=4', + secrets: ['synthetic', 'private spaces'], + keep: ['harness unavailable tokenCount=4'] + }, + { + name: 'complete authorization schemes and standalone Bearer', + text: 'denied Authorization: Basic c3ludGhldGlj next Authorization=Token synthetic-token next Bearer opaque~+/=; harness unavailable; token expired', + secrets: ['c3ludGhldGlj', 'synthetic-token', 'opaque~+/='], + keep: ['denied', 'harness unavailable', 'token expired'] + } + ])('redacts $name without losing evidence', ({ text, secrets, keep }) => { + const out = redactString(text) + for (const secret of secrets) { + expect(out).not.toContain(secret) + } + for (const evidence of keep) { + expect(out).toContain(evidence) + } + expect(redactString(out)).toBe(out) + }) }) describe('redactor — URL userinfo strip', () => { @@ -37,6 +73,54 @@ describe('redactor — URL userinfo strip', () => { }) }) +describe('redactor — complete credential spans', () => { + it.each([ + { + name: 'unquoted, bare and adjacent complete private keys', + text: 'private_key: -----BEGIN PRIVATE KEY-----\nsynthetic-private-body\n-----END PRIVATE KEY-----\nbetween evidence\nsecret: -----BEGIN RSA PRIVATE KEY-----\nsynthetic-bare-body\n-----END RSA PRIVATE KEY-----\n-----BEGIN PRIVATE KEY-----\nsynthetic-unlabelled-body\n-----END PRIVATE KEY-----\nharness evidence', + secrets: ['synthetic-private-body', 'synthetic-bare-body', 'synthetic-unlabelled-body'], + keep: ['between evidence', 'harness evidence'] + }, + { + name: 'Node inspect concatenation', + text: String.raw`{ secretKey: '-----BEGIN PRIVATE KEY-----\n' + + 'synthetic-inspect-body\n' + + '-----END PRIVATE KEY-----\n', cause: 'harness evidence' }`, + secrets: ['synthetic-inspect-body'], + keep: ['harness evidence'] + }, + { + name: 'a quoted key with actual line breaks', + text: '{"privateKey":"-----BEGIN RSA PRIVATE KEY-----\nsynthetic-quoted-body\n-----END RSA PRIVATE KEY-----","cause":"harness evidence"}', + secrets: ['synthetic-quoted-body'], + keep: ['harness evidence'] + }, + { + name: 'an AWS secret nested in an outer assignment', + text: 'harness evidence token: aws_secret_access_key=\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA next evidence', + secrets: ['AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'], + keep: ['harness evidence', 'next evidence'] + } + ])('removes $name without losing surrounding evidence', ({ text, secrets, keep }) => { + const out = redactString(text) + for (const secret of secrets) { + expect(out).not.toContain(secret) + } + for (const evidence of keep) { + expect(out).toContain(evidence) + } + expect(redactString(out)).toBe(out) + }) + + it('removes an unfinished private key through the actual input end', () => { + const out = redactString( + 'harness evidence private_key: -----BEGIN PRIVATE KEY-----\nsynthetic-unfinished-body\nsynthetic-final-line\n' + ) + expect(out).toBe('harness evidence private_key: [redacted:labeled-kv]') + expect(redactString(out)).toBe(out) + }) +}) + describe('redactor — .env-shape line', () => { it('handles multi-line .env dumps', () => { const out = redactString(['DB_HOST=db.local', 'DB_PASSWORD=hunter2', '# comment'].join('\n')) diff --git a/src/main/observability/redactor.ts b/src/main/observability/redactor.ts index fa2ebb00973..ee8f964ad6b 100644 --- a/src/main/observability/redactor.ts +++ b/src/main/observability/redactor.ts @@ -1,10 +1,10 @@ +import { redactCredentialAssignments } from './credential-assignment-redaction' + // Apply idempotent redaction at sink write, bundle collection and server ingest. // Server mode also strips product-telemetry identity keys. // Envelope bounds limit size; truncating attributes would lose diagnostic stack tails. -// Word boundaries preserve FOO_SECRET matches; consume full Bearer/Token values. -const LABELED_KV = - /\b(?:api[-_]?key|token|secret|password|bearer|authorization)\b\s*[:=]\s*(?:Bearer\s+\S+|Token\s+\S+|\S+)/gi +const STANDALONE_BEARER = /\bBearer\s+[A-Za-z0-9._~+/=-]+/gi // Match specific providers first so sk-ant- retains its Anthropic tag. const PROVIDER_PATTERNS: { tag: string; re: RegExp }[] = [ @@ -23,8 +23,8 @@ const PROVIDER_PATTERNS: { tag: string; re: RegExp }[] = [ { tag: 'slack-token', re: /xox[baprsoe]-[A-Za-z0-9-]{10,}/g }, { tag: 'pem', - // Lazy matching redacts adjacent PEM blocks independently. - re: /-----BEGIN [A-Z ]+-----[\s\S]+?-----END [A-Z ]+-----/g + // Keep complete blocks independent and remove unfinished secret suffixes. + re: /-----BEGIN [A-Z ]+-----[\s\S]*?(?:-----END [A-Z ]+-----|(?![\s\S]))/g } ] @@ -95,13 +95,14 @@ export function redactString(input: string): string { } let out = input - out = out.replace(LABELED_KV, '[redacted:labeled-kv]') - + // Assignment rewrites can otherwise erase the markers identifying whole credentials. // Redaction tags are stable identifiers used by external NDJSON tools. for (const { tag, re } of PROVIDER_PATTERNS) { out = out.replace(re, `[redacted:${tag}]`) } + out = redactCredentialAssignments(out).replace(STANDALONE_BEARER, '[redacted:labeled-kv]') + // Provider shapes run first to retain specific tags in URL userinfo. out = out.replace(URL_USERINFO, '$1[redacted]@') diff --git a/src/main/persistence/host-qualified-worktree-meta.ts b/src/main/persistence/host-qualified-worktree-meta.ts index 02c993d24e9..0ce97c1ff14 100644 --- a/src/main/persistence/host-qualified-worktree-meta.ts +++ b/src/main/persistence/host-qualified-worktree-meta.ts @@ -1,4 +1,7 @@ -import { getRepoRegistrationHostIds } from '../../shared/repo-host-identity' +import { + createRepoRowExecutionHostLookup, + type RepoRowExecutionHostLookup +} from '../../shared/execution-host/worktree-execution-host-resolution' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID, @@ -75,16 +78,18 @@ export function resolveWorktreeMetaOwner( getWorktreeMeta: (worktreeId: string) => { hostId?: ExecutionHostId } | undefined getRepos: () => readonly Repo[] }, - worktreeId: string + worktreeId: string, + repoLookup?: RepoRowExecutionHostLookup ): HostWorktreeTarget | undefined { // Local-only IDs have no backing repo from which to infer an owner. if (isLocalOnlyWorktreeMetaId(worktreeId)) { return hostWorktreeTarget({ id: worktreeId, hostId: LOCAL_EXECUTION_HOST_ID }) } + const repos = repoLookup ?? createRepoRowExecutionHostLookup(store.getRepos()) const repoId = getRepoIdFromWorktreeId(worktreeId) - const owners = store.getRepos().filter((repo) => repo.id === repoId) + const owners = repos.rowsFor(repoId) // The first writer stamp cannot disambiguate same-id repos on multiple hosts. - if (getRepoRegistrationHostIds(owners, repoId).size > 1) { + if (repos.registrationHostsFor(repoId).size > 1) { return undefined } const stamped = store.getWorktreeMeta(worktreeId)?.hostId diff --git a/src/main/persistence/worktree-sort-order-write.ts b/src/main/persistence/worktree-sort-order-write.ts index 5c43cfeef87..25040fcf86b 100644 --- a/src/main/persistence/worktree-sort-order-write.ts +++ b/src/main/persistence/worktree-sort-order-write.ts @@ -1,8 +1,4 @@ -import { - getRepoExecutionHostId, - parseExecutionHostId, - type ExecutionHostId -} from '../../shared/execution-host' +import { parseExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' import type { Repo } from '../../shared/repo-types' import type { WorktreeMeta } from '../../shared/worktree/meta-types' @@ -15,6 +11,7 @@ import { type WorktreeSortOrderUpdate } from '../../shared/worktree/sort-order-update' import { resolveWorktreeMetaOwner } from './host-qualified-worktree-meta' +import { createRepoRowExecutionHostLookup } from '../../shared/execution-host/worktree-execution-host-resolution' export type WorktreeSortOrderRequest = { orderedIds: readonly string[] @@ -32,25 +29,13 @@ type SortOrderStore = { setWorktreeMeta: (target: HostWorktreeTarget, updates: Partial) => unknown } -function knownHost( - store: SortOrderStore, - worktreeId: string, - hostId: ExecutionHostId -): ExecutionHostId | null { - const repoId = getRepoIdFromWorktreeId(worktreeId) - return store - .getRepos() - .some((repo) => repo.id === repoId && getRepoExecutionHostId(repo) === hostId) - ? hostId - : null -} - /** Unqualified IDs require unique ownership; return only written updates so same-ID siblings keep their order. */ export function writeWorktreeSortOrder( store: SortOrderStore, request: WorktreeSortOrderRequest, isBlocked: (worktreeId: string) => boolean, - now: number + now: number, + repos = createRepoRowExecutionHostLookup(store.getRepos()) ): WorktreeSortOrderUpdate[] { const hostIds = request.hostIds?.length === request.orderedIds.length ? request.hostIds : undefined @@ -65,11 +50,14 @@ export function writeWorktreeSortOrder( return } if (!hostIds) { - targets.set(worktreeId, resolveWorktreeMetaOwner(store, worktreeId)) + targets.set(worktreeId, resolveWorktreeMetaOwner(store, worktreeId, repos)) return } const named = parseExecutionHostId(hostIds[index]) - const hostId = named ? knownHost(store, worktreeId, named.id) : null + const hostId = + named && repos.registrationHostsFor(getRepoIdFromWorktreeId(worktreeId)).has(named.id) + ? named.id + : null if (hostId) { targets.set(worktreeId, hostWorktreeTarget({ id: worktreeId, hostId })) return @@ -77,7 +65,7 @@ export function writeWorktreeSortOrder( // Client-local may mean this server; use unique-owner fallback, while unknown remote hosts stay skipped. targets.set( worktreeId, - named?.kind === 'local' ? resolveWorktreeMetaOwner(store, worktreeId) : undefined + named?.kind === 'local' ? resolveWorktreeMetaOwner(store, worktreeId, repos) : undefined ) }) const metaFor = (worktreeId: string): WorktreeMeta | undefined => { diff --git a/src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts b/src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts new file mode 100644 index 00000000000..d3088a9a715 --- /dev/null +++ b/src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts @@ -0,0 +1,258 @@ +// `orca chat send --wait` through the real host: each check while the turn runs reads only work +// state, never a history page, a running-turn scan or the turn's text. + +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { RpcResponse } from '../rpc/core' +import type * as HistoryPage from '../../native-chat/agent-session-wire/publication/history/agent-session-history-page' +import type * as LiveTurn from '../../../shared/agent-session/view/structured-agent-session-live-turn' +import { StructuredAgentSessionJournalProjections } from '../../native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection' +import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../../shared/agent-session/agent-session-runtime-capabilities' +import { RuntimeClient, RuntimeClientError } from '../../../cli/runtime-client' +import { CHAT_HANDLERS } from '../../../cli/handlers/chat' +import { + openStructuredCodexRpcHarness, + SESSION, + THREAD, + TURN, + type StructuredCodexRpcHarness +} from '../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness' + +const work = vi.hoisted(() => ({ historyPages: 0, turnScans: 0 })) + +vi.mock( + '../../native-chat/agent-session-wire/publication/history/agent-session-history-page', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readAgentSessionHistory: (...args: Parameters) => { + work.historyPages += 1 + return actual.readAgentSessionHistory(...args) + } + } + } +) + +vi.mock( + '../../../shared/agent-session/view/structured-agent-session-live-turn', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + runningStructuredAgentSessionTurnItemBySequence: ( + ...args: Parameters + ) => { + work.turnScans += 1 + return actual.runningStructuredAgentSessionTurnItemBySequence(...args) + } + } + } +) + +const NEWEST_MARKER = 'newest-row-marker' + +let harness: StructuredCodexRpcHarness | undefined + +afterEach(async () => { + vi.useRealTimers() + vi.restoreAllMocks() + await harness?.dispose() + harness = undefined +}) + +/** The CLI's own client, answered by the host's dispatcher in the local CLI's caller context. */ +function cliClient(open: StructuredCodexRpcHarness) { + const client = new RuntimeClient('/tmp/orca-chat-wait-test', 60_000, null, null) + const replies: { method: string; json: string }[] = [] + const onReply = new Set<() => void>() + vi.spyOn(client, 'getCliStatus').mockResolvedValue({ + id: 'status', + ok: true, + result: { + app: { running: true, pid: 1 }, + runtime: { + state: 'ready', + reachable: true, + runtimeId: 'runtime-1', + capabilities: [AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY] + }, + graph: { state: 'ready' } + }, + _meta: { runtimeId: 'runtime-1' } + }) + vi.spyOn(client, 'call').mockImplementation(async (method: string, params?: unknown) => { + const response: RpcResponse = await open.call(method, params) + replies.push({ method, json: JSON.stringify(response) }) + for (const notify of onReply) { + notify() + } + if (!response.ok) { + throw new RuntimeClientError(response.error.code, response.error.message) + } + return response + }) + const waitForReplies = (method: string, after: number, count: number) => { + const completed = Promise.withResolvers() + const notify = () => { + if (replies.slice(after).filter((reply) => reply.method === method).length >= count) { + onReply.delete(notify) + completed.resolve() + } + } + onReply.add(notify) + notify() + return completed.promise + } + return { client, replies, waitForReplies } +} + +function agentMessage(id: string, text: string): void { + harness!.codex.notify('item/completed', { + threadId: THREAD, + turnId: TURN, + item: { type: 'agentMessage', id, text } + }) +} + +/** A running turn holding `rows` earlier replies and one newest reply of `newestBytes`. */ +async function seedRunningTurn(rows: number, newestBytes: number): Promise { + harness!.codex.notify('turn/started', { threadId: THREAD, turn: { id: TURN } }) + for (let index = 0; index < rows; index += 1) { + agentMessage(`older-${index}`, `Older reply ${index}.`) + } + agentMessage('newest', `${NEWEST_MARKER} ${'x'.repeat(newestBytes)}`) + await vi.waitFor(async () => { + const page = await harness!.call('agentSession.history', { + sessionId: SESSION, + direction: 'tail', + limit: 1 + }) + expect(JSON.stringify(page)).toContain(NEWEST_MARKER) + }) +} + +/** Runs `chat send --wait`, completes the turn after two checks, and returns what each check cost. */ +async function sendAndWait(rows: number, newestBytes: number) { + harness = await openStructuredCodexRpcHarness([], {}, { localCli: true }) + await harness.ok('agentSession.create', harness.createIntentParams()) + const { client, replies, waitForReplies } = cliClient(harness) + const flags = new Map([ + ['session', SESSION], + ['text', 'Run the tests'], + ['wait', true] + ]) + const logs: string[] = [] + vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line)) + const sending = CHAT_HANDLERS['chat send']!({ flags, client, cwd: '/tmp', json: true }) + await vi.waitFor(() => + expect(harness!.codex.live().calls.map((c) => c.method)).toContain('turn/start') + ) + await seedRunningTurn(rows, newestBytes) + const before = replies.length + work.historyPages = 0 + work.turnScans = 0 + const checks = () => replies.slice(before).filter((r) => r.method === 'agentSession.workState') + await Promise.race([waitForReplies('agentSession.workState', before, 2), sending]) + expect(checks()).toHaveLength(2) + const during = { ...work, checks: checks().map((r) => r.json) } + work.historyPages = 0 + harness.codex.notify('turn/completed', { + threadId: THREAD, + turn: { id: TURN, status: 'completed' } + }) + await sending + const printed: { result: { entries: unknown[] } } = JSON.parse(logs.join('\n')) + return { during, finalPages: work.historyPages, result: printed.result } +} + +describe('chat send --wait over the real host', () => { + it('returns SQL work state when an attached chat projection is invalidated', async () => { + harness = await openStructuredCodexRpcHarness([], {}, { localCli: true }) + await harness.ok('agentSession.create', harness.createIntentParams()) + await seedRunningTurn(1, 16) + vi.spyOn(StructuredAgentSessionJournalProjections.prototype, 'readSql').mockResolvedValue(null) + work.historyPages = 0 + const response = await harness.call('agentSession.workState', { sessionId: SESSION }) + expect(response).toMatchObject({ + ok: true, + result: { + working: true, + actionablePrompt: false, + queuedMessageIds: [], + nextQueuedMessageId: null, + fence: expect.any(Number) + } + }) + expect(work.historyPages).toBe(0) + }) + + it.each([ + { rows: 15, newestBytes: 64 * 1024 }, + { rows: 150, newestBytes: 640 * 1024 } + ])( + 'checks a running turn without history pages, turn scans or its text ($rows rows, $newestBytes byte newest reply)', + async ({ rows, newestBytes }) => { + const { during, finalPages, result } = await sendAndWait(rows, newestBytes) + expect(during.historyPages).toBe(0) + expect(during.turnScans).toBe(0) + for (const check of during.checks) { + expect(check).not.toContain(NEWEST_MARKER) + expect(JSON.parse(check).result).toEqual({ + working: true, + actionablePrompt: false, + queuedMessageIds: [], + nextQueuedMessageId: null, + fence: expect.any(Number) + }) + } + expect(finalPages).toBe(1) + expect(result).toMatchObject({ delivery: 'submitted', settled: 'done', truncated: false }) + expect(result.entries).toEqual([ + ...Array.from({ length: rows }, (_, index) => ({ + kind: 'message', + role: 'assistant', + text: `Older reply ${index}.` + })), + { kind: 'message', role: 'assistant', text: `${NEWEST_MARKER} ${'x'.repeat(newestBytes)}` } + ]) + } + ) + + it('reads history pages from a host without agentSession.workState, asking it only once', async () => { + harness = await openStructuredCodexRpcHarness( + [], + {}, + { localCli: true, omitMethods: ['agentSession.workState'] } + ) + await harness.ok('agentSession.create', harness.createIntentParams()) + const { client, replies, waitForReplies } = cliClient(harness) + const logs: string[] = [] + vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line)) + const sending = CHAT_HANDLERS['chat send']!({ + flags: new Map([ + ['session', SESSION], + ['text', 'Run the tests'], + ['wait', true] + ]), + client, + cwd: '/tmp', + json: true + }) + await vi.waitFor(() => + expect(harness!.codex.live().calls.map((c) => c.method)).toContain('turn/start') + ) + await seedRunningTurn(1, 16) + await Promise.race([waitForReplies('agentSession.history', replies.length, 1), sending]) + harness.codex.notify('turn/completed', { + threadId: THREAD, + turn: { id: TURN, status: 'completed' } + }) + await sending + expect(replies.filter((r) => r.method === 'agentSession.workState')).toHaveLength(1) + expect(JSON.parse(logs.join('\n')).result).toMatchObject({ + delivery: 'submitted', + settled: 'done', + entries: [{ text: 'Older reply 0.' }, { text: `${NEWEST_MARKER} ${'x'.repeat(16)}` }] + }) + }) +}) diff --git a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts index dfd87d389f6..b0bd869bc4a 100644 --- a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts +++ b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts @@ -78,7 +78,9 @@ export function acknowledgeAgentPromptSubmit( } } -const electronMocks = vi.hoisted(() => { +const electronMocks = await vi.hoisted(async () => { + const { fakeAppEnvironment } = + await import('../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup') type Listener = (...args: unknown[]) => void const listeners = new Map>() const ipcMain = { @@ -103,7 +105,7 @@ const electronMocks = vi.hoisted(() => { BrowserWindow: { fromId: vi.fn((_id: number): unknown => null) }, webContents: { fromId: vi.fn((_id: number): unknown => null) }, ipcMain, - app: { getPath: vi.fn(() => '/tmp'), isPackaged: false } + app: { getPath: vi.fn(() => fakeAppEnvironment().getPath('userData')), isPackaged: false } } }) diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts index 02c12808101..548e4c0e9c2 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts @@ -85,7 +85,9 @@ import { _resetTerminalViewAttributesForTest } from '../terminal/view/terminal-v import { addSparseWorktree } from '../../git/worktrees/creation/worktree-sparse-add' import { addWorktree } from '../../git/worktrees/creation/worktree-add' import { advertisedUrlWatcher } from '../../ports/advertised-url-watcher' -import { afterEach, beforeEach, vi } from 'vitest' +import { afterAll, afterEach, beforeEach, vi } from 'vitest' +import { initOrcaProfilePaths } from '../../orca-profiles/profile-storage-paths' +import { stopStructuredAgentSessionRuntime } from '../agent-session/structured-agent-session-runtime' import { assertWorktreeCleanForRemoval } from '../../git/worktrees/removal/worktree-removal-preflight' import { __cancelLegacyWorkerTerminalRecoveryRetriesForTests as cancelLegacyWorkerTerminalRecoveryRetriesForTests } from '../orchestration/terminal-authority/runtime-legacy-worker-terminal-recovery-controller' import { clearConfiguredWorktreeSharedDirectoriesCacheForTests } from '../../git/worktrees/content-paths/worktree-shared-directories' @@ -154,6 +156,7 @@ function resetRuntimeTestMocks(): void { getPath: () => electronMocks.app.getPath(), isPackaged: () => electronMocks.app.isPackaged }) + initOrcaProfilePaths() // Deferred worker recovery re-arms forever; cancel it before shared git stubs leak across cases. cancelLegacyWorkerTerminalRecoveryRetriesForTests() clearConfiguredWorktreeSharedDirectoriesCacheForTests() @@ -399,3 +402,7 @@ afterEach(async () => { }) export { resetRuntimeTestMocks } + +afterAll(async () => { + await stopStructuredAgentSessionRuntime() +}) diff --git a/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts b/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts index 6ae64ac2c10..9d7d6ea608d 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session.ts @@ -45,6 +45,7 @@ import { CreateParams, CreateSupportParams, HistoryParams, + WorkStateParams, RewindParams, SendParams, SleepWorkspaceParams, @@ -191,6 +192,16 @@ export const STRUCTURED_AGENT_SESSION_METHODS = [ ) } }), + // Waiters poll this instead of history: no history page or running-turn scan, and no transcript in the reply. + defineMethod({ + name: 'agentSession.workState', + permission: 'workspace', + params: WorkStateParams, + handler: async (params, ctx) => + (await requireInstalledHost(ctx, params.sessionId)).backgroundTasks.workState( + params.sessionId + ) + }), STRUCTURED_AGENT_SESSION_SUBSCRIBE_METHOD, defineMethod({ name: 'agentSession.unsubscribe', diff --git a/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts b/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts index c79a9ea0382..bd438af388c 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts @@ -179,11 +179,13 @@ export type StructuredCodexRpcHarness = { export async function openStructuredCodexRpcHarness( clientCapabilities: readonly RuntimeCapability[] = DEFAULT_CLIENT_CAPABILITIES, /** What the transport stamps, as a paired device's authenticated socket does. */ - transport: { clientId?: string; pairedDeviceId?: string } = {} + transport: { clientId?: string; pairedDeviceId?: string } = {}, + /** The local CLI names no client kind; an older host lacks newer methods. */ + options: { localCli?: boolean; omitMethods?: readonly string[] } = {} ): Promise { const client = { clientId: 'device-a', - clientKind: 'runtime' as const, + ...(options.localCli ? {} : { clientKind: 'runtime' as const }), clientCapabilities, ...transport } @@ -245,7 +247,9 @@ export async function openStructuredCodexRpcHarness( } const dispatcher = new RpcDispatcher({ runtime: runtime as unknown as OrcaRuntimeService, - methods: STRUCTURED_AGENT_SESSION_METHODS + methods: STRUCTURED_AGENT_SESSION_METHODS.filter( + (method) => !options.omitMethods?.includes(method.name) + ) }) const call: StructuredCodexRpcHarness['call'] = async (method, params) => { const replies: RpcResponse[] = [] diff --git a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts index 44542d4fff1..980b21d816c 100644 --- a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts +++ b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts @@ -23,6 +23,7 @@ import type { Repo } from '../../../../shared/repo-types' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import type { ProjectExecutionRuntimeResolution } from '../../../../shared/execution-host/project-execution-runtime' import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { createRepoRowExecutionHostLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' import { areWorktreePathsEqual } from '../../../git/worktrees/catalog/worktree-path-comparison' import { mergeWorktree } from '../../../ipc/worktree-metadata-merge' @@ -241,8 +242,9 @@ export async function resolveScopedWorktreeIdRow( if (!parsed?.repoId || !parsed.worktreePath) { return null } - const owners = store - .getRepos() + const repoOwners = createRepoRowExecutionHostLookup(store.getRepos()) + const owners = repoOwners + .rowsFor(parsed.repoId) .filter( (repo) => repo.id === parsed.repoId && @@ -257,7 +259,8 @@ export async function resolveScopedWorktreeIdRow( deps, repo, store.getAllWorktreeMeta() ?? {}, - resolveLocalProjectRuntimesForRepos(store, [repo]) + resolveLocalProjectRuntimesForRepos(store, [repo]), + repoOwners.rowsFor(repo.id).length ) // Accept one normalized equivalent id; multiple path matches remain ambiguous (#16243). const comparisonKey = worktreeIdentityKey(worktreeId) @@ -278,12 +281,11 @@ export async function resolveScopedWorktreeIdRow( ) relatedRepoIds.delete(repo.id) const hostId = getRepoExecutionHostId(repo) - const relatedRepos = store - .getRepos() - .filter( - (candidate) => - relatedRepoIds.has(candidate.id) && getRepoExecutionHostId(candidate) === hostId - ) + const registered = store.getRepos() + const relatedOwners = createRepoRowExecutionHostLookup(registered) + const relatedRepos = registered.filter( + (candidate) => relatedRepoIds.has(candidate.id) && getRepoExecutionHostId(candidate) === hostId + ) if (new Set(relatedRepos.map((candidate) => candidate.id)).size !== relatedRepos.length) { return null } @@ -291,7 +293,13 @@ export async function resolveScopedWorktreeIdRow( const projectRuntimeByRepoId = resolveLocalProjectRuntimesForRepos(store, relatedRepos) const otherRows = await Promise.all( relatedRepos.map((relatedRepo) => - resolveRepoWorktreeRows(deps, relatedRepo, metaById, projectRuntimeByRepoId) + resolveRepoWorktreeRows( + deps, + relatedRepo, + metaById, + projectRuntimeByRepoId, + relatedOwners.rowsFor(relatedRepo.id).length + ) ) ) const projected = projectResolvedWorktreeLineage([...ownerRows, ...otherRows.flat()], lineageById) diff --git a/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts b/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts index 271f34aa01d..a9b2f8aed0c 100644 --- a/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts +++ b/src/main/runtime/workspaces/catalog/resolved-worktree-scan-join.ts @@ -1,4 +1,5 @@ import type { Repo } from '../../../../shared/repo-types' +import { createRepoRowExecutionHostLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' import { isFolderRepo } from '../../../../shared/repo-kind' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import type { ProjectExecutionRuntimeResolution } from '../../../../shared/execution-host/project-execution-runtime' @@ -65,12 +66,19 @@ export async function scanResolvedWorktreeRepos( if (!store) { return scans } - const repos = store.getRepos().filter((repo) => !isFolderRepo(repo)) + const registered = store.getRepos() + const repoOwners = createRepoRowExecutionHostLookup(registered) + const repos = registered.filter((repo) => !isFolderRepo(repo)) const projectRuntimeByRepoId = resolveLocalProjectRuntimesForRepos(store, repos) const deps = rowDeps() await Promise.all( repos.map(async (repo) => { - const scan = await scanRepoWorktreeRows(deps, repo, projectRuntimeByRepoId) + const scan = await scanRepoWorktreeRows( + deps, + repo, + projectRuntimeByRepoId, + repoOwners.rowsFor(repo.id).length + ) // The key listRepoWorktreesForResolution caches under. const gitRun = scanCacheEntry(`${repo.id}\0${getRepoExecutionHostId(repo)}`) ?? null scans.set(resolvedWorktreeRepoScanKey(repo), { ...scan, gitRun }) @@ -89,13 +97,14 @@ export function joinResolvedWorktreeScans( const platformByRepoId = store ? platformsByRepoId(repos, resolveLocalProjectRuntimesForRepos(store, repos)) : new Map() - return { ...joinRows(store, rowDeps, scans), platformByRepoId } + return { ...joinRows(store, rowDeps, scans, repos), platformByRepoId } } function joinRows( store: RuntimeStore | null, rowDeps: () => RepoWorktreeRowDeps, - scans: ResolvedWorktreeRepoScans + scans: ResolvedWorktreeRepoScans, + repos: readonly Repo[] ): ResolvedWorktreeRowsJoin { if (!store) { return { @@ -106,17 +115,24 @@ function joinRows( } } const metaById = store.getAllWorktreeMeta() ?? {} + const repoOwners = createRepoRowExecutionHostLookup(repos) const deps = rowDeps() const unscannedRepoKeys = new Set() const gitRunById = new Map() const scannedRepoKeys = new Set() - const perRepoWorktrees = store.getRepos().map((repo) => { + const perRepoWorktrees = repos.map((repo) => { const key = resolvedWorktreeRepoScanKey(repo) const scan = scans.get(key) ?? null if (!scan && !isFolderRepo(repo)) { unscannedRepoKeys.add(key) } - const rows = joinRepoWorktreeRows(deps, repo, scan, metaById) + const rows = joinRepoWorktreeRows( + deps, + repo, + scan, + metaById, + repoOwners.rowsFor(repo.id).length + ) if (scan?.ok) { scannedRepoKeys.add(key) for (const row of rows) { diff --git a/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts b/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts index eff460beecd..0435d44b176 100644 --- a/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts +++ b/src/main/runtime/workspaces/catalog/runtime-listing-metadata.ts @@ -3,6 +3,25 @@ import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import type { WorkspaceMetadataCursor } from '../../../../shared/worktree/workspace-metadata-set' import type { RuntimeStore } from '../../construction/runtime-store-contract' import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership' +import { readWorktreeMetaForHost } from '../../../persistence/host-qualified-worktree-meta' +import { getRepoExecutionHostId } from '../../../../shared/execution-host' + +export function readRuntimeWorktreeMetadata( + store: RuntimeStore, + repo: Repo, + worktreeId: string, + repoOwnerCount?: number +): WorktreeMeta | undefined { + return ( + readWorktreeMetaForHost(store, worktreeId, getRepoExecutionHostId(repo)) ?? + getRepoOwnedWorktreeMeta( + repo, + worktreeId, + store.getAllWorktreeMeta(), + repoOwnerCount ?? store.getRepos().filter((row) => row.id === repo.id).length + ) + ) +} /** * The metadata a listing reads, with the store's workspaceMetadata cursor taken in the same turn, so diff --git a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts index 63f4308ea41..5d0c79c73b9 100644 --- a/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts +++ b/src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.ts @@ -1,4 +1,4 @@ -import { readRuntimeListingMetadata } from './runtime-listing-metadata' +import { readRuntimeListingMetadata, readRuntimeWorktreeMetadata } from './runtime-listing-metadata' import type { RuntimeManagedWorktreeQueryDependencies } from './runtime-managed-worktree-query-dependencies' import { resolveWorktreeHostRouting } from './worktree-launch-host-repo' import { createRepoRowExecutionHostLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' @@ -19,7 +19,6 @@ import type { RuntimeWorktreeListResult } from '../../../../shared/runtime-workt import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { buildWorktreeListingPage, listingKnownHostIds } from './worktree-listing-host-scope' import { readWorktreeMetaForHost } from '../../../persistence/host-qualified-worktree-meta' -import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import { isFolderRepo } from '../../../../shared/repo-kind' import { @@ -65,10 +64,6 @@ export class RuntimeManagedWorktreeQueries { const scopedRepo = repoSelector ? await this.deps.resolveRepo(repoSelector) : null const repos = this.deps.getStore()?.getRepos() ?? [] const repoLookup = createRepoRowExecutionHostLookup(repos) - const repoOwnerCounts = new Map() - for (const repo of repos) { - repoOwnerCounts.set(repo.id, (repoOwnerCounts.get(repo.id) ?? 0) + 1) - } const matchers = buildRuntimeWorktreeVisibilityMatchers( repos, resolved, @@ -96,7 +91,7 @@ export class RuntimeManagedWorktreeQueries { defaultsSupported, undefined, undefined, - repoOwnerCounts.get(routing.repo.id) + repoLookup.rowsFor(routing.repo.id).length ).visible }) // Scoped reads must name requested hosts even without rows; hidden retained repos must never reenter scope. @@ -220,12 +215,21 @@ export class RuntimeManagedWorktreeQueries { worktree: Worktree, matcher?: WorktreeVisibilitySourceMatcher, defaultsSupported = true, - settingsOverride?: ReturnType + settingsOverride?: ReturnType, + repoLookup = createRepoRowExecutionHostLookup(this.deps.getStore()?.getRepos() ?? []) ): boolean { - const routing = resolveWorktreeHostRouting(this.deps.getStore()?.getRepos() ?? [], worktree) + const routing = resolveWorktreeHostRouting([], worktree, repoLookup) const repo = routing.kind === 'resolved' ? routing.repo : undefined return repo - ? this.toDetected(repo, worktree, matcher, defaultsSupported, settingsOverride).visible + ? this.toDetected( + repo, + worktree, + matcher, + defaultsSupported, + settingsOverride, + undefined, + repoLookup.rowsFor(repo.id).length + ).visible : true } @@ -267,13 +271,7 @@ export class RuntimeManagedWorktreeQueries { meta: providedMeta === undefined ? store - ? (readWorktreeMetaForHost(store, worktree.id, getRepoExecutionHostId(repo)) ?? - getRepoOwnedWorktreeMeta( - repo, - worktree.id, - store.getAllWorktreeMeta(), - repoOwnerCount ?? store.getRepos().filter((row) => row.id === repo.id).length - )) + ? readRuntimeWorktreeMetadata(store, repo, worktree.id, repoOwnerCount) : undefined : (providedMeta ?? undefined), settings: { ...settings, worktreeVisibilityDefaults: visibilityDefaults }, diff --git a/src/main/runtime/workspaces/catalog/workspace-catalog.ts b/src/main/runtime/workspaces/catalog/workspace-catalog.ts index 63f9a666def..b48f767182e 100644 --- a/src/main/runtime/workspaces/catalog/workspace-catalog.ts +++ b/src/main/runtime/workspaces/catalog/workspace-catalog.ts @@ -4,6 +4,7 @@ import type { ResolvedWorktree } from './runtime-worktree-path-identity' import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' import { isPathInsideOrEqual } from '../../../../shared/cross-platform-path' import type { ResolvedWorktreeSnapshot } from './runtime-resolved-worktree-cache' +import { createRepoRowExecutionHostLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' import { getWorktreeScanMutationRevision } from '../../../workspaces/catalog/local-worktree-scan-generation' import { resolveLocalProjectRuntimesForRepos } from '../../../workspaces/execution-host/local-project-runtime-resolution' @@ -68,11 +69,12 @@ export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFi worktreeIds.add(targetWorktreeId) const resolved: ResolvedWorktree[] = [] + const repos = createRepoRowExecutionHostLookup(this.store.getRepos()) for (const worktreeId of worktreeIds) { const worktree = worktreeId === targetWorktreeId ? targetWorktree - : this.buildResolvedWorktreeFromId(worktreeId) + : this.buildResolvedWorktreeFromId(worktreeId, repos) if (worktree) { resolved.push(worktree) } @@ -106,12 +108,20 @@ export abstract class RuntimeWorkspaceCatalog extends OrcaRuntimeWithReadKittyFi } const metaById = this.store.getAllWorktreeMeta() ?? {} const repos = this.store.getRepos() + const repoOwners = createRepoRowExecutionHostLookup(repos) const projectRuntimeByRepoId = resolveLocalProjectRuntimesForRepos(this.requireStore(), repos) const platformByRepoId = platformsByRepoId(repos, projectRuntimeByRepoId) const deps = this.repoWorktreeRowDeps() const perRepoWorktrees = await Promise.all( repos.map( - async (repo) => await resolveRepoWorktreeRows(deps, repo, metaById, projectRuntimeByRepoId) + async (repo) => + await resolveRepoWorktreeRows( + deps, + repo, + metaById, + projectRuntimeByRepoId, + repoOwners.rowsFor(repo.id).length + ) ) ) const lineageById = this.store?.getAllWorktreeLineage?.() ?? {} diff --git a/src/main/runtime/workspaces/catalog/worktree-launch-host-repo.ts b/src/main/runtime/workspaces/catalog/worktree-launch-host-repo.ts index c9f6b18bc0b..ecb11c29cf3 100644 --- a/src/main/runtime/workspaces/catalog/worktree-launch-host-repo.ts +++ b/src/main/runtime/workspaces/catalog/worktree-launch-host-repo.ts @@ -1,7 +1,8 @@ import { createRepoRowExecutionHostLookup, resolveWorktreeExecutionHost, - type ExecutionHostOwnerRow + type ExecutionHostOwnerRow, + type ExecutionHostOwnerLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' import { getSshTargetIdForExecutionHost, @@ -27,7 +28,7 @@ export type WorktreeHostRouting = export function resolveWorktreeHostRouting( repos: readonly T[], worktree: { repoId: string; hostId?: string | null }, - lookup = createRepoRowExecutionHostLookup(repos) + lookup: ExecutionHostOwnerLookup = createRepoRowExecutionHostLookup(repos) ): WorktreeHostRouting { const resolution = resolveWorktreeExecutionHost(lookup, worktree) if (resolution.kind === 'unresolved') { diff --git a/src/main/runtime/workspaces/known-workspace-file-target.ts b/src/main/runtime/workspaces/known-workspace-file-target.ts index f66931883b2..4806b08c4ca 100644 --- a/src/main/runtime/workspaces/known-workspace-file-target.ts +++ b/src/main/runtime/workspaces/known-workspace-file-target.ts @@ -50,6 +50,7 @@ export abstract class OrcaRuntimeWithResolveKnownWorkspaceFileTarget extends Run const repos = this.store?.getRepos() ?? [] const repoOwners = createRepoRowExecutionHostLookup(repos) const resolvedWorktrees = await this.listResolvedWorktrees() + const visibilityOwners = createRepoRowExecutionHostLookup(this.store?.getRepos() ?? []) const visibilitySourceMatchersByRepoId = this.buildRuntimeVisibilitySourceMatchersByRepoId(resolvedWorktrees) for (const worktree of resolvedWorktrees) { @@ -64,7 +65,10 @@ export abstract class OrcaRuntimeWithResolveKnownWorkspaceFileTarget extends Run ? visibilitySourceMatchersByRepoId.get( getRepoHostIdentityForParts(worktree.repoId, routing.hostId) ) - : undefined + : undefined, + true, + undefined, + visibilityOwners ) ) { continue diff --git a/src/main/runtime/workspaces/managed-workspace-operations.ts b/src/main/runtime/workspaces/managed-workspace-operations.ts index 4fb319982a7..cf501b5048d 100644 --- a/src/main/runtime/workspaces/managed-workspace-operations.ts +++ b/src/main/runtime/workspaces/managed-workspace-operations.ts @@ -4,6 +4,7 @@ import type { OrcaRuntimeWithResolveBrowserNetworkExecutionHostForWorktree } fro import type { RuntimeWorktreeListResult } from '../../../shared/runtime-worktree-contracts' import type { DetectedWorktreeListResult, Worktree } from '../../../shared/worktree/types' import type { Repo } from '../../../shared/repo-types' +import type { RepoRowExecutionHostLookup } from '../../../shared/execution-host/worktree-execution-host-resolution' import { stopMissingWorktreeTerminals } from './removal/missing-worktree-terminal-reconciliation' import type { WorktreeVisibilitySourceMatcher } from '../../../shared/worktree/visibility-sources' import type { RuntimeStore } from '../construction/runtime-store-contract' @@ -92,13 +93,15 @@ export abstract class OrcaRuntimeWithListManagedWorktrees extends RuntimeWorkspa worktree: Worktree, worktreeVisibilitySourceMatcher?: WorktreeVisibilitySourceMatcher, sourceDefaultsSupported = true, - providedSettings?: ReturnType + providedSettings?: ReturnType, + repoLookup?: RepoRowExecutionHostLookup ): boolean { return this.managedWorktreeQueries.isVisible( worktree, worktreeVisibilitySourceMatcher, sourceDefaultsSupported, - providedSettings + providedSettings, + repoLookup ) } diff --git a/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts b/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts index ffb672c291f..06e4aa6a71f 100644 --- a/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts +++ b/src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata.ts @@ -1,4 +1,4 @@ -import { getRepoRegistrationHostIds } from '../../../../shared/repo-host-identity' +import { createRepoRowExecutionHostLookup } from '../../../../shared/execution-host/worktree-execution-host-resolution' import type { GitPushTarget, Worktree } from '../../../../shared/worktree/types' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import { @@ -183,12 +183,14 @@ export function persistRuntimeManagedWorktreeSortOrder(args: { /** `sortOrders` omitted: the repo has same-id copies, which an id-keyed patch cannot tell apart. */ notifyChanged: (repoId: string, sortOrders?: WorktreeSortOrderUpdate[]) => void }): { updated: number } { + const repos = createRepoRowExecutionHostLookup(args.store.getRepos()) // Skip moving projects but save/publish the rest; report only written orders. const updates = writeWorktreeSortOrder( args.store, { orderedIds: args.orderedIds, hostIds: args.hostIds }, (worktreeId) => isWslMoveWorkspaceBlocked(args.store, worktreeId), - Date.now() + Date.now(), + repos ) if (updates.length === 0) { return { updated: 0 } @@ -202,7 +204,7 @@ export function persistRuntimeManagedWorktreeSortOrder(args: { } } for (const [repoId, sortOrders] of updatesByRepo) { - const isTwin = getRepoRegistrationHostIds(args.store.getRepos(), repoId).size > 1 + const isTwin = repos.registrationHostsFor(repoId).size > 1 args.notifyChanged(repoId, isTwin ? undefined : sortOrders) } return { updated: updates.length } diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 92c38427682..165a5d9f6cd 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -176,7 +176,8 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven ? sourceMatchersByRepoId.get(getRepoHostIdentityForParts(worktree.repoId, owner.hostId)) : undefined, sourceDefaultsSupported, - visibilitySettings + visibilitySettings, + repoOwners ) }) } diff --git a/src/main/runtime/workspaces/workspace-selectors.ts b/src/main/runtime/workspaces/workspace-selectors.ts index 1ecdc202f8b..23498c26bba 100644 --- a/src/main/runtime/workspaces/workspace-selectors.ts +++ b/src/main/runtime/workspaces/workspace-selectors.ts @@ -21,7 +21,10 @@ import type { RuntimeWorkspaceCatalog } from './catalog/workspace-catalog' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { resolveWorktreeMetaOwner } from '../../persistence/host-qualified-worktree-meta' import { resolveWorktreeHostRouting } from './catalog/worktree-launch-host-repo' -import { createRepoRowExecutionHostLookup } from '../../../shared/execution-host/worktree-execution-host-resolution' +import { + createRepoRowExecutionHostLookup, + type RepoRowExecutionHostLookup +} from '../../../shared/execution-host/worktree-execution-host-resolution' import { mergeWorktree } from '../../ipc/worktree-metadata-merge' import { RuntimeProjectLaunchContext } from './startup/runtime-project-launch-context' import { folderIdOfSelector } from '../../../shared/workspace-scope' @@ -270,19 +273,21 @@ export abstract class RuntimeWorkspaceSelectors extends RuntimeProjectLaunchCont return this.store } - protected buildResolvedWorktreeFromId(worktreeId: string): ResolvedWorktree | null { + protected buildResolvedWorktreeFromId( + worktreeId: string, + repos: RepoRowExecutionHostLookup = createRepoRowExecutionHostLookup( + this.store?.getRepos() ?? [] + ) + ): ResolvedWorktree | null { const parsed = splitWorktreeIdForFilesystem(worktreeId) if (!parsed?.repoId || !parsed.worktreePath) { return null } - const owner = this.store && resolveWorktreeMetaOwner(this.store, worktreeId) + const owner = this.store && resolveWorktreeMetaOwner(this.store, worktreeId, repos) if (!owner) { return null } - const repo = createRepoRowExecutionHostLookup(this.store?.getRepos() ?? []).byHost( - parsed.repoId, - owner.hostId - ) + const repo = repos.byHost(parsed.repoId, owner.hostId) const git = { path: parsed.worktreePath, head: '', diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index e72c21251f4..0ec1032f1f5 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -77,7 +77,7 @@ export function AgentLaunchSetupPanel({ const argumentsKnown = agentPickerArgumentsKnown(entry, draft) const effective = agentPickerEffectiveChoices(entry, draft) const argumentsView = agentPickerPanelArguments(entry, draft) - const models = agentPickerModels(entry) + const models = agentPickerModels(entry, draft.surface) const defaultsPending = draft.surface === 'chat' ? entry.structuredDefaultsPending : entry.defaultsPending const seed = getAgentSessionOptionLaunchCatalog(entry.agent) diff --git a/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts b/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts index 01314c130a2..ce07b04ae45 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-acquisition.ts @@ -1,22 +1,23 @@ -import { useAppViewExternalStore } from '@/store/retained-views/app-state-view' +import { + agentPickerCatalogJobs, + agentPickerCatalogFailure, + updateAgentPickerCatalog, + type AgentPickerCatalogJob +} from './agent-picker-catalog-jobs' +export { + createAgentPickerInventorySource, + useAgentPickerInventoryEntries, + type AgentPickerInventorySource +} from './agent-picker-inventory-source' import { shallow } from 'zustand/shallow' import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { + AgentPickerAcquisitionObserver as Observer, + AgentPickerAcquisitionReads as Reads +} from './agent-picker-inventory-source' /** Pending local IPC outlives observers; matching menus must retain its physical owner. */ const pending = new Map() -type Observer = { - publish: (entries: AgentPickerEntry[]) => void - selected: () => TuiAgent | undefined -} -type Reads = { - settings?: () => Promise - catalog: ( - entry: AgentPickerEntry, - waitForListing: boolean - ) => Promise - support: (entry: AgentPickerEntry) => Promise -} type ReadKind = 'catalog' | 'refresh' | 'support' type SupportRead = { state: 'queued' | 'pending' | 'settled' @@ -27,21 +28,25 @@ class AgentPickerAcquisition { readonly observers = new Set() entries: AgentPickerEntry[] settingsPending = false + private demand?: AbortController private outstanding = { catalog: 0, refresh: 0, support: 0 } private queued: Record> private supports = new Map() + private jobs: AgentPickerCatalogJob[] private defaults: AgentPickerEntry[] + private stopInvalidation?: () => void + private physicalCatalogs = 0 constructor( readonly key: string, private initial: AgentPickerEntry[], private reads: Reads ) { - this.entries = initial.map((entry) => ({ - ...entry, - catalogRead: - entry.surfaces.length && entry.catalogRead !== 'unsupported' ? 'pending' : 'unsupported' - })) + this.entries = initial + this.jobs = agentPickerCatalogJobs(initial) + for (const job of this.jobs) { + this.entries = updateAgentPickerCatalog(this.entries, job, { catalogRead: 'pending' }) + } this.defaults = initial for (const [i, entry] of initial.entries()) { if (entry.structuredDefaultsPending) { @@ -49,9 +54,7 @@ class AgentPickerAcquisition { } } this.queued = { - catalog: new Set( - this.entries.flatMap((entry, i) => (entry.catalogRead === 'pending' ? [i] : [])) - ), + catalog: new Set(this.jobs.map((_, index) => index)), refresh: new Set(), support: new Set(this.supports.keys()) } @@ -61,19 +64,40 @@ class AgentPickerAcquisition { const first = this.observers.size === 0 this.observers.add(observer) if (first) { - for (const [i, entry] of this.entries.entries()) { + if (this.demand) { + this.jobs = this.jobs.map((job) => ({ ...job })) + } + this.demand = new AbortController() + this.outstanding = { catalog: 0, refresh: 0, support: this.outstanding.support } + this.stopInvalidation = this.reads.subscribeInvalidation?.(() => { + this.outstanding = { catalog: 0, refresh: 0, support: this.outstanding.support } + this.jobs = this.jobs.map((job, index) => { + if (this.reads.refreshOnInvalidation?.(this.entries[job.index]) === false) { + return job + } + this.queued.refresh.delete(index) + this.entries = updateAgentPickerCatalog(this.entries, job, { + catalog: { origin: 'unknown' }, + catalogRead: 'pending' + }) + this.queued.catalog.add(index) + return { ...job } + }) + this.publish() + this.admit('catalog') + }) + for (const [index, job] of this.jobs.entries()) { + const view = this.entries[job.index] if ( - this.initial[i].catalogRead !== 'unsupported' && - entry.surfaces.length && - entry.catalogRead !== 'pending' && - (entry.catalog.origin === 'unknown' || - entry.catalogRead === 'failed' || - entry.catalogRead === 'unsupported' || - entry.catalog.unavailable !== undefined || - entry.catalog.listingInProgress) + view.catalogRead !== 'pending' && + (view.catalog.origin === 'unknown' || + view.catalogRead === 'failed' || + view.catalogRead === 'unsupported' || + view.catalog.unavailable !== undefined || + view.catalog.listingInProgress) ) { - this.queued.catalog.add(i) - this.entries[i] = { ...entry, catalogRead: 'pending' } + this.queued.catalog.add(index) + this.entries = updateAgentPickerCatalog(this.entries, job, { catalogRead: 'pending' }) } } for (const [i, read] of this.supports) { @@ -94,6 +118,13 @@ class AgentPickerAcquisition { this.admit('support') return () => { this.observers.delete(observer) + if (!this.observers.size) { + this.demand?.abort() + this.stopInvalidation?.() + this.stopInvalidation = undefined + this.queued.refresh.clear() + this.jobs.forEach((_, index) => this.queued.catalog.add(index)) + } this.retire() } } @@ -149,59 +180,58 @@ class AgentPickerAcquisition { } private async readCatalog(entry: AgentPickerEntry, index: number, waitForListing: boolean) { - const catalog = await this.reads.catalog(entry, waitForListing) + const job = this.jobs[index] + const signal = this.demand!.signal + const catalog = await this.reads.catalog(entry, waitForListing, signal) + if (job !== this.jobs[index] || (signal.aborted && this.observers.size > 0) || !catalog) { + return + } // An open picker waits on a running listing, and again when a wait used its whole budget. const refresh = + !signal.aborted && this.observers.size > 0 && - (waitForListing ? catalog?.waitExpired : catalog?.listingInProgress) === true + (waitForListing ? catalog.waitExpired : catalog.listingInProgress) === true if (refresh) { this.queued.refresh.add(index) } - this.entries = this.entries.map((e, i) => - i === index - ? { - ...e, - ...(catalog ? { catalog } : {}), - catalogRead: !catalog ? 'failed' : refresh ? 'pending' : 'settled' - } - : e - ) + this.entries = updateAgentPickerCatalog(this.entries, job, { + catalog, + catalogRead: refresh ? 'pending' : 'settled' + }) } private admit(kind: ReadKind) { while (this.observers.size && this.outstanding[kind] < 2 && this.queued[kind].size) { + const usable = [...this.queued[kind]] const priorities = [...this.observers].map((o) => o.selected()) - const preferred = this.entries.findIndex((e) => priorities.includes(e.agent)) - const index = this.queued[kind].has(preferred) - ? preferred - : this.queued[kind].values().next().value + const index = + usable.find((index) => + priorities.includes( + this.entries[kind !== 'support' ? this.jobs[index].index : index].agent + ) + ) ?? usable[0] if (index === undefined) { break } this.queued[kind].delete(index) - this.outstanding[kind]++ - const entry = this.entries[index] + const outstanding = this.outstanding + outstanding[kind]++ + const entry = this.entries[kind !== 'support' ? this.jobs[index].index : index] if (kind === 'support') { this.supports.set(index, { state: 'pending' }) + } else { + this.physicalCatalogs++ } + const job = this.jobs[index] + const signal = this.demand!.signal const read = kind !== 'support' ? this.readCatalog(entry, index, kind === 'refresh').catch((error: unknown) => { - const unsupported = - typeof error === 'object' && - error !== null && - 'code' in error && - (error.code === 'method_not_found' || - error.code === 'structured_agent_session_unsupported' || - error.code === 'forbidden') - this.entries = this.entries.map((e, i) => - i === index - ? { - ...e, - catalogRead: unsupported ? 'unsupported' : 'failed' - } - : e - ) + if (job === this.jobs[index] && !signal.aborted) { + this.entries = updateAgentPickerCatalog(this.entries, job, { + catalogRead: agentPickerCatalogFailure(error) + }) + } }) : this.reads .support(entry) @@ -213,11 +243,16 @@ class AgentPickerAcquisition { void read .catch(() => undefined) .then(() => { - this.outstanding[kind]-- + if (kind === 'support') { + this.outstanding.support-- + } else { + outstanding[kind]-- + this.physicalCatalogs-- + } this.publish() this.admit(kind) - if (kind === 'catalog') { - this.admit('refresh') + if (kind !== 'support') { + this.admit(kind === 'catalog' ? 'refresh' : 'catalog') } this.retire() }) @@ -228,11 +263,12 @@ class AgentPickerAcquisition { if ( !this.observers.size && !this.settingsPending && - !this.outstanding.catalog && - !this.outstanding.refresh && + !this.physicalCatalogs && !this.outstanding.support ) { - pending.delete(this.key) + if (pending.get(this.key) === this) { + pending.delete(this.key) + } } } @@ -267,47 +303,3 @@ export function currentAgentPickerAcquisition(key: string) { export function agentPickerAcquisitionDiagnostics() { return [...pending.values()].map((resource) => ({ key: resource.key, ...resource.diagnostics() })) } - -/** - * Live picker entries for one (inventory key, open) generation. Catalog and seed reads land one - * at a time for several seconds after the menu opens; holding them here instead of in the - * owner's React state lets only the components that render entries re-render as they land. - */ -export type AgentPickerInventorySource = { - getSnapshot: () => AgentPickerEntry[] - subscribe: (listener: () => void) => () => void -} - -type WritableAgentPickerInventorySource = AgentPickerInventorySource & { - publish: (entries: readonly AgentPickerEntry[]) => void -} - -export function createAgentPickerInventorySource( - initial: AgentPickerEntry[] -): WritableAgentPickerInventorySource { - let entries = initial - const listeners = new Set<() => void>() - return { - getSnapshot: () => entries, - subscribe: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) - }, - publish: (next) => { - // Why: a read that changed nothing (e.g. an unavailable catalog) must not re-render the menu. - if (next.length === entries.length && next.every((entry, i) => entry === entries[i])) { - return - } - entries = [...next] - for (const listener of listeners) { - listener() - } - } - } -} - -export function useAgentPickerInventoryEntries( - source: AgentPickerInventorySource -): AgentPickerEntry[] { - return useAppViewExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot) -} diff --git a/src/renderer/src/components/agent/agent-launch-picker-host-reads.ts b/src/renderer/src/components/agent/agent-launch-picker-host-reads.ts new file mode 100644 index 00000000000..7259f78686a --- /dev/null +++ b/src/renderer/src/components/agent/agent-launch-picker-host-reads.ts @@ -0,0 +1,79 @@ +import type { AgentSessionModelCatalogResult } from '../../../../shared/agent-session/agent-session-wire' +import type { RuntimeGitContext } from '@/runtime/source-control/git/runtime-git-client-context' +import { + agentPickerListsCliModels, + readAgentPickerCliModelCatalog +} from './agent-launch-picker-cli-model-catalog' +import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' +import { + readModelMenuCatalog, + type ModelMenuReadScope +} from '@/runtime/native-chat/model-catalogs/model-menu-catalog-read' +import { subscribeModelMenuInvalidation } from '@/runtime/native-chat/model-catalogs/model-menu-invalidation' +import { parseStructuredLaunchSeedOptions } from '../../../../shared/native-chat/input/native-chat-session-option-defaults' +import { isAgentChatPermissionChoice } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' +import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' + +export function agentPickerModelCatalogReads( + input: Omit & { + target: RuntimeClientTarget | null + cliDiscoveryRuntime?: RuntimeGitContext | null + } +) { + const { target, cliDiscoveryRuntime } = input + return { + catalog: async (entry: AgentPickerEntry, waitForListing: boolean, signal: AbortSignal) => + cliDiscoveryRuntime && agentPickerListsCliModels(entry) + ? readAgentPickerCliModelCatalog(entry.agent, cliDiscoveryRuntime) + : !target + ? undefined + : entry.agent === 'antigravity' + ? callStructuredAgentSession( + target, + 'agentSession.modelCatalog', + { + ...(input.worktree ? { worktree: input.worktree } : {}), + agent: entry.agent, + ...(waitForListing ? { waitForListing } : {}) + } + ) + : readModelMenuCatalog( + { ...input, target, agent: entry.agent }, + waitForListing, + signal + ), + refreshOnInvalidation: (entry: Pick) => + !!target && + !(cliDiscoveryRuntime && agentPickerListsCliModels(entry)) && + entry.agent !== 'antigravity', + subscribeInvalidation: target + ? (listener: () => void) => subscribeModelMenuInvalidation(target, listener) + : undefined + } +} + +export async function readAgentPickerLaunchSupport( + target: RuntimeClientTarget | null, + selector: string | undefined, + agent: AgentPickerEntry['agent'] +): Promise { + if (!selector || !target) { + return undefined + } + const support = await callStructuredAgentSession<{ seedOptions?: Record }>( + target, + 'agentSession.createSupport', + { worktree: selector, agent } + ) + const parsed = parseStructuredLaunchSeedOptions(support?.seedOptions) + if (!parsed) { + return undefined + } + const { model, permissionMode, ...options } = parsed + return { + ...(model ? { model } : {}), + options, + ...(isAgentChatPermissionChoice(permissionMode) ? { permissionMode } : {}) + } +} diff --git a/src/renderer/src/components/agent/agent-launch-picker-inventory-freshness.test.tsx b/src/renderer/src/components/agent/agent-launch-picker-inventory-freshness.test.tsx new file mode 100644 index 00000000000..b1a10e51f28 --- /dev/null +++ b/src/renderer/src/components/agent/agent-launch-picker-inventory-freshness.test.tsx @@ -0,0 +1,187 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { getDefaultSettings } from '../../../../shared/constants' +import { useAgentLaunchPickerInventory } from './use-agent-launch-picker-inventory' +import type { UseDetectedAgentsResult } from '@/hooks/useDetectedAgents' +import type { NewTabAgentMenuModel } from '../tab-bar/new-tab-agent-menu-model' +import { + loadHostStructuredAgents, + resetHostStructuredAgentsForTests +} from '@/runtime/native-chat/agent-catalogs/host-structured-agents' +import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY as REGISTERED } from '../../../../shared/agent-session/structured-agent-session-surface-capabilities' +import { TEST_REPO } from '@/store/repos/repo.test-fixture' +const transport = vi.hoisted(() => ({ call: vi.fn(), rpc: vi.fn(), defaults: vi.fn() })) +vi.mock('@/runtime/native-chat/requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: transport.call +})) +vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: transport.rpc })) +vi.mock('@/runtime/agent-launch-settings/agent-launch-settings-transport', () => ({ + readHostAgentLaunchDefaults: transport.defaults +})) +const initial = useAppStore.getState() +const previousApi = Object.getOwnPropertyDescriptor(window, 'api') +afterEach(() => { + cleanup() + useAppStore.setState(initial, true) + resetHostStructuredAgentsForTests() + vi.resetAllMocks() + if (previousApi) { + Object.defineProperty(window, 'api', previousApi) + } else { + Reflect.deleteProperty(window, 'api') + } +}) +const detection: UseDetectedAgentsResult = { + detectedIds: ['codex'], + isLoading: false, + isRefreshing: false, + detectionFailed: false, + needsServerUpdate: false, + refresh: async () => ['codex'] +} + +it('reads a paired unknown-platform catalog before launch defaults and keeps it after defaults fail', async () => { + useAppStore.setState({ settings: getDefaultSettings('/synthetic') }) + transport.rpc.mockResolvedValue({ agents: [] }) + await loadHostStructuredAgents('runtime:unknown-platform', [REGISTERED], 'server-runtime') + const defaults = Promise.withResolvers() + transport.defaults.mockReturnValue(defaults.promise) + transport.call.mockResolvedValue({ + origin: 'probe', + fetchedAt: 1, + models: [{ id: 'server-only', label: 'Server', isDefault: false, efforts: [] }] + }) + const model: NewTabAgentMenuModel = { + state: 'settled', + rows: [{ agent: 'codex', kind: 'cli' }], + detection, + pickerContext: { + workspace: { + kind: 'git-worktree', + repoId: 'future', + executionHostId: 'runtime:unknown-platform' + }, + executionHostId: 'runtime:unknown-platform', + runtimeId: 'server-runtime', + settings: null, + key: 'unknown-platform' + } + } + const hook = renderHook(() => useAgentLaunchPickerInventory(undefined, model, true)) + await waitFor(() => + expect(hook.result.current[0]).toMatchObject({ + catalogRead: 'settled', + defaultsPending: true, + catalog: { models: [{ id: 'server-only' }] } + }) + ) + await act(async () => { + defaults.reject(new Error('defaults offline')) + }) + expect(hook.result.current[0]).toMatchObject({ + catalogRead: 'settled', + catalog: { models: [{ id: 'server-only' }] } + }) +}) + +it('reads the structured host list for a local UNC workspace instead of gating on its terminal route', async () => { + Object.defineProperty(window, 'api', { + configurable: true, + value: { platform: { get: () => ({ platform: 'win32' }) } } + }) + useAppStore.setState({ + settings: getDefaultSettings('/synthetic'), + repos: [ + { + ...TEST_REPO, + id: 'unc', + path: '\\\\wsl.localhost\\Ubuntu\\home\\app', + executionHostId: 'local' + } + ] + }) + transport.call.mockResolvedValue({ + origin: 'probe', + fetchedAt: 1, + models: [{ id: 'host-only', label: 'Host', isDefault: false, efforts: [] }] + }) + const model: NewTabAgentMenuModel = { + state: 'settled', + rows: [{ agent: 'codex', kind: 'cli' }], + detection, + pickerContext: { + workspace: { kind: 'git-worktree', repoId: 'unc' }, + executionHostId: 'local', + settings: {}, + key: 'local-unc' + } + } + const hook = renderHook(() => useAgentLaunchPickerInventory(undefined, model, true)) + await waitFor(() => + expect(hook.result.current[0]).toMatchObject({ + catalogRead: 'settled', + catalog: { models: [{ id: 'host-only' }] } + }) + ) +}) + +it('reloads paired launch defaults when reopening while the old catalog request drains', async () => { + useAppStore.setState({ settings: getDefaultSettings('/synthetic') }) + const catalog = Promise.withResolvers() + const admitted = Promise.withResolvers() + const defaults = Promise.withResolvers<{ + settings: { agentDefaultArgs: { codex: string } } + structuredKnown: boolean + }>() + transport.call.mockImplementation(() => { + admitted.resolve() + return catalog.promise + }) + transport.defaults.mockReturnValueOnce(defaults.promise).mockResolvedValue({ + settings: { + agentDefaultArgs: { codex: '--add-dir fresh' }, + nativeChatSessionOptions: { + codex: { model: 'fresh-default', valuesByModel: { 'fresh-default': { effort: 'high' } } } + } + }, + structuredKnown: true + }) + const model: NewTabAgentMenuModel = { + state: 'settled', + rows: [{ agent: 'codex', kind: 'cli' }], + detection, + pickerContext: { + workspace: { kind: 'floating', executionHostId: 'runtime:defaults-reopen' }, + executionHostId: 'runtime:defaults-reopen', + runtimeId: 'defaults-server', + settings: null, + key: 'defaults-reopen' + } + } + const hook = renderHook(({ open }) => useAgentLaunchPickerInventory(undefined, model, open), { + initialProps: { open: true } + }) + await act(async () => admitted.promise) + hook.rerender({ open: false }) + await act(async () => { + defaults.resolve({ + settings: { agentDefaultArgs: { codex: '--add-dir old' } }, + structuredKnown: true + }) + }) + hook.rerender({ open: true }) + try { + await waitFor(() => + expect(hook.result.current[0]).toMatchObject({ + defaultsPending: false, + arguments: '--add-dir fresh', + structured: { model: 'fresh-default', options: { effort: 'high' } } + }) + ) + } finally { + hook.unmount() + await act(async () => catalog.reject(new Error('closed catalog'))) + } +}) diff --git a/src/renderer/src/components/agent/agent-launch-picker-queued-waits.test.ts b/src/renderer/src/components/agent/agent-launch-picker-queued-waits.test.ts new file mode 100644 index 00000000000..d74867b94ca --- /dev/null +++ b/src/renderer/src/components/agent/agent-launch-picker-queued-waits.test.ts @@ -0,0 +1,185 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' +import type { AgentSessionModelCatalogResult } from '../../../../shared/agent-session/agent-session-wire' +import { useAppStore } from '@/store' +import { agentPickerModelCatalogReads } from './agent-launch-picker-host-reads' +import { observeAgentPickerAcquisition } from './agent-launch-picker-acquisition' +const transport = vi.hoisted(() => ({ call: vi.fn() })) +vi.mock('@/runtime/native-chat/requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: transport.call +})) +const initial = useAppStore.getState() +afterEach(() => { + useAppStore.setState(initial, true) + transport.call.mockReset() +}) +const entry: AgentPickerEntry = { + agent: 'codex', + label: 'Codex', + rows: [], + surfaces: ['chat'], + defaultSurface: 'chat', + terminal: {}, + structured: {}, + catalog: { origin: 'unknown' } +} + +it('keeps last-good display failed and retries on reopen while support is still pending', async () => { + const refresh = Promise.withResolvers() + const support = Promise.withResolvers() + transport.call.mockImplementation((_target, _method, params) => + params.waitForListing + ? refresh.promise + : { + origin: 'probe', + fetchedAt: 1, + listingInProgress: true, + models: [{ id: 'last-good', label: 'Last good', isDefault: false, efforts: [] }] + } + ) + let published: AgentPickerEntry[] = [] + const observe = () => + observeAgentPickerAcquisition( + 'retry-after-failure', + [{ ...entry, structuredDefaultsPending: true }], + { + ...agentPickerModelCatalogReads({ target: { kind: 'local' }, worktree: 'id:retry' }), + support: () => support.promise + }, + { + selected: () => 'codex', + publish: (next) => { + published = next + } + } + ) + const close = observe() + await expect.poll(() => published[0]?.catalog).toMatchObject({ models: [{ id: 'last-good' }] }) + refresh.reject(new Error('offline')) + await expect + .poll(() => published[0]) + .toMatchObject({ catalogRead: 'failed', catalog: { models: [{ id: 'last-good' }] } }) + close() + transport.call.mockResolvedValue({ + origin: 'probe', + fetchedAt: 2, + models: [{ id: 'recovered', label: 'Recovered', isDefault: false, efforts: [] }] + }) + const reopened = observe() + try { + await expect + .poll(() => published[0]) + .toMatchObject({ catalogRead: 'settled', catalog: { models: [{ id: 'recovered' }] } }) + } finally { + reopened() + support.resolve(undefined) + } +}) + +it('ignores obsolete success and rejection after a real account change while the replacement is pending', async () => { + const old = Promise.withResolvers() + const middle = Promise.withResolvers() + const replacement = Promise.withResolvers() + const admitted = Promise.withResolvers(), + middleAdmitted = Promise.withResolvers(), + replacementAdmitted = Promise.withResolvers() + transport.call + .mockImplementationOnce(() => { + admitted.resolve() + return old.promise + }) + .mockImplementationOnce(() => { + middleAdmitted.resolve() + return middle.promise + }) + .mockImplementationOnce(() => { + replacementAdmitted.resolve() + return replacement.promise + }) + let published: AgentPickerEntry[] = [] + const done = Promise.withResolvers() + const reads: Promise[] = [] + const host = agentPickerModelCatalogReads({ target: { kind: 'local' }, worktree: 'id:replace' }) + const close = observeAgentPickerAcquisition( + 'account-cycle-fence', + [entry], + { + ...host, + catalog: (...args) => { + const read = host.catalog(...args) + reads.push(read) + return read + }, + support: async () => undefined + }, + { + selected: () => 'codex', + publish: (next) => { + published = next + if (next[0].catalogRead === 'settled') { + done.resolve() + } + } + } + ) + try { + await admitted.promise + useAppStore.setState((state) => ({ + settings: { ...state.settings!, activeCodexManagedAccountId: 'middle' } + })) + await middleAdmitted.promise + useAppStore.setState((state) => ({ + settings: { ...state.settings!, activeCodexManagedAccountId: 'new-account' } + })) + await replacementAdmitted.promise + old.resolve({ + origin: 'probe', + fetchedAt: 1, + models: [{ id: 'old-account', label: 'Old', isDefault: false, efforts: [] }] + }) + middle.reject(new Error('old transport failed')) + await Promise.allSettled(reads.slice(0, 2)) + expect(published[0]).toMatchObject({ catalogRead: 'pending', catalog: { origin: 'unknown' } }) + replacement.resolve({ + origin: 'probe', + fetchedAt: 2, + models: [{ id: 'new-account', label: 'New', isDefault: false, efforts: [] }] + }) + await done.promise + expect(published[0]).toMatchObject({ + catalogRead: 'settled', + catalog: { models: [{ id: 'new-account' }] } + }) + } finally { + close() + old.resolve({ origin: 'unknown' }) + middle.resolve({ origin: 'unknown' }) + replacement.resolve({ origin: 'unknown' }) + } +}) + +it('preserves unsupported transport classification instead of settling an unknown answer', async () => { + transport.call.mockRejectedValue({ code: 'method_not_found' }) + let published: AgentPickerEntry[] = [] + const close = observeAgentPickerAcquisition( + 'unsupported-read', + [entry], + { + ...agentPickerModelCatalogReads({ target: { kind: 'local' }, worktree: 'id:unsupported' }), + support: async () => undefined + }, + { + selected: () => 'codex', + publish: (next) => { + published = next + } + } + ) + try { + await expect + .poll(() => published[0]) + .toMatchObject({ catalogRead: 'unsupported', catalog: { origin: 'unknown' } }) + } finally { + close() + } +}) diff --git a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts index e20461a08e3..ced76c6ecfa 100644 --- a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts +++ b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts @@ -1,3 +1,7 @@ +import { + agentPickerModelMenu, + agentPickerUsesComposerModelMenu +} from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog' import { TEXT_ACTION_DEFAULT_MODEL, textActionArgumentsOwnEffort @@ -90,80 +94,98 @@ export function agentLaunchSetupOptionRows( argumentsOwnedRow('effort', options[0]?.label ?? 'Reasoning effort', 'thought_level', t) ] } - return options.map((option) => { - const effortInArguments = - entry.textGeneration?.effortInArguments && - (!draft.textChanges?.includes('effort') || entry.textGeneration.effortArgumentsUnrecognized) - const liveModel = models.find((model) => model.id === currentModel) - const current = - argumentsView.choices.options?.[option.id] ?? - (currentModel && !defaultsPending && !draft.delegated?.includes(option.id) - ? option.kind.type === 'boolean' - ? String(option.kind.defaultValue) - : option.id === 'effort' - ? liveModel?.defaultEffort - : option.kind.defaultIsCliDefault - ? option.kind.defaultValue - : undefined - : undefined) - if (argumentsView.context.analysis.opaqueKeys.has(option.id)) { - return argumentsOwnedRow(option.id, option.label, option.category, t) - } - const valueKnown = - current !== undefined || - (option.id === 'serviceTier' && - entry.catalog.origin !== 'unknown' && - Boolean(liveModel?.serviceTiers?.length)) - return { - id: option.id, - label: option.label, - category: option.category, - kind: - option.kind.type === 'boolean' - ? { type: 'boolean', currentValue: current === 'true' } - : { - type: 'select', - choices: entry.textGeneration - ? [ - ...(effortInArguments - ? [ - { - value: 'arguments', - label: t('agentPicker.setByArguments', 'Set by your Arguments') - } - ] - : []), - ...(entry.textGeneration.defaultLabel !== undefined - ? [ - { - value: TEXT_ACTION_DEFAULT_MODEL, - label: textEffortDefaultLabel(option.kind, t) - } - ] - : []), - ...option.kind.choices - ] - : option.id !== 'serviceTier' && - current && - !option.kind.choices.some((choice) => choice.value === current) - ? [...option.kind.choices, { value: current, label: current }] - : option.kind.choices, - currentValue: effortInArguments ? 'arguments' : current - }, - valueSource: valueKnown ? 'default' : 'unknown', - transport: 'agent-session', - settable: - !disabled && - !defaultsPending && - // A settled level the agent picks itself shows unselected but stays pickable. - (valueKnown || - option.kind.type === 'select' || - Boolean(currentModel && draft.delegated?.includes(option.id))) && - (!(option.id === 'fastMode' || option.id === 'serviceTier') || - !entry.surfaces.includes('terminal') || - argumentsKnown) - } - }) + const effort = agentPickerModelMenu(entry, draft.surface, { + ...(currentModel ? { model: currentModel } : {}), + ...argumentsView.choices.options + }).descriptors.find((row) => row.id === 'effort') + const sharedEffort = agentPickerUsesComposerModelMenu(entry, draft.surface) ? effort : undefined + const rows: SessionOptionDescriptor[] = options + .filter((option) => !sharedEffort || option.id !== 'effort') + .map((option) => { + const effortInArguments = + entry.textGeneration?.effortInArguments && + (!draft.textChanges?.includes('effort') || entry.textGeneration.effortArgumentsUnrecognized) + const liveModel = models.find((model) => model.id === currentModel) + const current = + argumentsView.choices.options?.[option.id] ?? + (currentModel && !defaultsPending && !draft.delegated?.includes(option.id) + ? option.kind.type === 'boolean' + ? String(option.kind.defaultValue) + : option.id === 'effort' + ? liveModel?.defaultEffort + : option.kind.defaultIsCliDefault + ? option.kind.defaultValue + : undefined + : undefined) + if (argumentsView.context.analysis.opaqueKeys.has(option.id)) { + return argumentsOwnedRow(option.id, option.label, option.category, t) + } + const valueKnown = + current !== undefined || + (option.id === 'serviceTier' && + entry.catalog.origin !== 'unknown' && + Boolean(liveModel?.serviceTiers?.length)) + return { + id: option.id, + label: option.label, + category: option.category, + kind: + option.kind.type === 'boolean' + ? { type: 'boolean', currentValue: current === 'true' } + : { + type: 'select', + choices: entry.textGeneration + ? [ + ...(effortInArguments + ? [ + { + value: 'arguments', + label: t('agentPicker.setByArguments', 'Set by your Arguments') + } + ] + : []), + ...(entry.textGeneration.defaultLabel !== undefined + ? [ + { + value: TEXT_ACTION_DEFAULT_MODEL, + label: textEffortDefaultLabel(option.kind, t) + } + ] + : []), + ...option.kind.choices + ] + : option.id !== 'serviceTier' && + current && + !option.kind.choices.some((choice) => choice.value === current) + ? [...option.kind.choices, { value: current, label: current }] + : option.kind.choices, + currentValue: effortInArguments ? 'arguments' : current + }, + valueSource: valueKnown ? 'default' : 'unknown', + transport: 'agent-session', + settable: + !disabled && + !defaultsPending && + // A settled level the agent picks itself shows unselected but stays pickable. + (valueKnown || + option.kind.type === 'select' || + Boolean(currentModel && draft.delegated?.includes(option.id))) && + (!(option.id === 'fastMode' || option.id === 'serviceTier') || + !entry.surfaces.includes('terminal') || + argumentsKnown) + } + }) + if (sharedEffort) { + rows.push( + argumentsView.context.analysis.opaqueKeys.has('effort') + ? argumentsOwnedRow('effort', sharedEffort.label, sharedEffort.category, t) + : { + ...sharedEffort, + settable: sharedEffort.settable && !disabled && !defaultsPending + } + ) + } + return rows } /** Speed rows sit apart from the rest; launch also lifts level rows onto speed's line. */ diff --git a/src/renderer/src/components/agent/agent-picker-catalog-jobs.ts b/src/renderer/src/components/agent/agent-picker-catalog-jobs.ts new file mode 100644 index 00000000000..39ac2a7614b --- /dev/null +++ b/src/renderer/src/components/agent/agent-picker-catalog-jobs.ts @@ -0,0 +1,30 @@ +import { shallow } from 'zustand/shallow' +import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' + +export type AgentPickerCatalogJob = { index: number } +export function agentPickerCatalogJobs(entries: AgentPickerEntry[]): AgentPickerCatalogJob[] { + return entries.flatMap((entry, index) => + entry.surfaces.length && entry.catalogRead !== 'unsupported' ? [{ index }] : [] + ) +} +export function agentPickerCatalogFailure(error: unknown): 'unsupported' | 'failed' { + return typeof error === 'object' && + error !== null && + 'code' in error && + (error.code === 'method_not_found' || + error.code === 'structured_agent_session_unsupported' || + error.code === 'forbidden') + ? 'unsupported' + : 'failed' +} +export function updateAgentPickerCatalog( + entries: AgentPickerEntry[], + job: AgentPickerCatalogJob, + patch: Partial> +) { + const before = entries[job.index] + const next = { ...before, ...patch } + return shallow(before, next) + ? entries + : entries.map((row, index) => (index === job.index ? next : row)) +} diff --git a/src/renderer/src/components/agent/agent-picker-inventory-source.ts b/src/renderer/src/components/agent/agent-picker-inventory-source.ts new file mode 100644 index 00000000000..3ae6424ec27 --- /dev/null +++ b/src/renderer/src/components/agent/agent-picker-inventory-source.ts @@ -0,0 +1,63 @@ +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import { useAppViewExternalStore } from '@/store/retained-views/app-state-view' +import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' + +/** + * Live picker entries for one (inventory key, open) generation. Catalog and seed reads land one + * at a time for several seconds after the menu opens; holding them here instead of in the + * owner's React state lets only the components that render entries re-render as they land. + */ +export type AgentPickerInventorySource = { + getSnapshot: () => AgentPickerEntry[] + subscribe: (listener: () => void) => () => void +} + +type WritableAgentPickerInventorySource = AgentPickerInventorySource & { + publish: (entries: readonly AgentPickerEntry[]) => void +} + +export function createAgentPickerInventorySource( + initial: AgentPickerEntry[] +): WritableAgentPickerInventorySource { + let entries = initial + const listeners = new Set<() => void>() + return { + getSnapshot: () => entries, + subscribe: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + publish: (next) => { + // Why: a read that changed nothing (e.g. an unavailable catalog) must not re-render the menu. + if (next.length === entries.length && next.every((entry, i) => entry === entries[i])) { + return + } + entries = [...next] + for (const listener of listeners) { + listener() + } + } + } +} + +export function useAgentPickerInventoryEntries( + source: AgentPickerInventorySource +): AgentPickerEntry[] { + return useAppViewExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot) +} + +export type AgentPickerAcquisitionObserver = { + publish: (entries: AgentPickerEntry[]) => void + selected: () => TuiAgent | undefined +} +export type AgentPickerAcquisitionReads = { + settings?: () => Promise + catalog: ( + entry: AgentPickerEntry, + waitForListing: boolean, + signal: AbortSignal + ) => Promise + refreshOnInvalidation?: (entry: AgentPickerEntry) => boolean + subscribeInvalidation?: (listener: () => void) => () => void + support: (entry: AgentPickerEntry) => Promise +} diff --git a/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx b/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx index 0d4430a5021..4b78263a6cc 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentChoiceControls.tsx @@ -1,3 +1,4 @@ +import { modelMenuOptions } from '../../../../../shared/agent-session/options/model-menu-options' import type { AgentChoicePatch, AgentDedicatedChoices @@ -88,8 +89,20 @@ export function AgentChoiceFields({ liveCatalog && liveCatalog.origin !== 'unknown' && liveCatalog.models.length ? { agent, catalog: liveCatalog, terminal: {} } : null + const menu = + live && catalog && agent !== 'antigravity' + ? modelMenuOptions(live.catalog, { + agent, + surface: 'terminal', + seed: catalog, + newLaunch: true, + seedsModel: false, + saved: { ...(selected?.model ? { model: selected.model } : {}), ...selected?.options } + }) + : undefined + const effort = menu?.descriptors.find(({ id }) => id === 'effort') const listedModels = live - ? agentPickerModels(live).filter(({ hidden }) => !hidden) + ? (menu?.rows ?? agentPickerModels(live)).filter((row) => !('hidden' in row && row.hidden)) : (catalog?.models ?? []) const unlistedModel = selected?.model && !(live ? listedModels.some(({ id }) => id === selected.model) : model) @@ -98,6 +111,12 @@ export function AgentChoiceFields({ const liveEffort = live ? agentPickerEntryOptions(live, selected?.model, 'terminal').find(({ id }) => id === 'effort') : undefined + const effortKind = + menu && selected?.model + ? effort?.kind.type === 'select' + ? { ...effort.kind, defaultValue: '' } + : undefined + : liveEffort?.kind const options = sourceControlActionOptions(agent, selected?.model ?? '').flatMap((row) => { // CLI carrier mappings remain available to Args badges without advertising a mode control. if ( @@ -110,7 +129,7 @@ export function AgentChoiceFields({ return [row] } // A listed model with no reasoning levels gets no effort menu. - return liveEffort ? [{ ...row, option: { ...row.option, kind: liveEffort.kind } }] : [] + return effortKind ? [{ ...row, option: { ...row.option, kind: effortKind } }] : [] }) const defaultLabel = t('settings.sourceControl.actionModel.effortDefault', 'Default') return ( @@ -165,7 +184,7 @@ export function AgentChoiceFields({ row={layout === 'rows'} hint={sourceControlActionRouteHint(route, t)} value={current ?? AGENT_DEFAULT_VALUE} - disabled={disabled} + disabled={disabled || (option.id === 'effort' && effort?.settable === false)} onOpenChange={onOpenChange} choices={[ { diff --git a/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts b/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts index f30e32b0467..40cf89e20e8 100644 --- a/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts +++ b/src/renderer/src/components/agent/use-agent-launch-picker-inventory.ts @@ -1,4 +1,20 @@ -import { useAppStateView, useAppStateViewActive } from '@/store/retained-views/app-state-view' +import { getAgentSessionOptionLaunchCatalog } from '../../../../shared/agent-session/options/agent-session-option-catalog' +import { recomputeOn } from '@/lib/recompute-on' +import { useHostStructuredAgentsVersion } from '@/runtime/native-chat/agent-catalogs/chat-provider-agents' +import { + createAgentPickerInventorySource, + useAgentPickerInventoryEntries, + type AgentPickerInventorySource +} from './agent-picker-inventory-source' +import { + useAppStateView, + useAppStateViewActive, + useAppViewExternalStore +} from '@/store/retained-views/app-state-view' +import { + readLocalRuntimeCapabilityObservation, + subscribeLocalRuntimeCapabilityObservation +} from '@/runtime/hosts/capabilities/local-runtime-capabilities' import { hostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' import { parseExecutionHostId } from '../../../../shared/execution-host' import { selectWorkspaceByHostTarget } from '@/store/workspaces/selection/workspace-host-target' @@ -12,38 +28,30 @@ import type { NewTabAgentMenuModel } from '../tab-bar/use-new-tab-agent-menu-row import { buildAgentLaunchRouteInput } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { workspaceKindForWorktreeId } from '../../../../shared/agent-launch/contracts/workspace-launch-kind' import { structuredAgentSessionTargetForHost } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' -import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' import { readHostStructuredAgentsForRuntime } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' import type { RuntimeGitContext } from '@/runtime/source-control/git/runtime-git-client-context' import { resolveWorktreeModelDiscoveryRuntime } from '../native-chat/session/options/catalog/native-chat-session-option-discovery' +import { agentPickerListsCliModels } from './agent-launch-picker-cli-model-catalog' import { - agentPickerListsCliModels, - readAgentPickerCliModelCatalog -} from './agent-launch-picker-cli-model-catalog' -import { getAgentSessionOptionLaunchCatalog } from '../../../../shared/agent-session/options/agent-session-option-catalog' + agentPickerModelCatalogReads, + readAgentPickerLaunchSupport +} from './agent-launch-picker-host-reads' +import { AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY } from '../../../../shared/agent-session/structured-agent-session-surface-capabilities' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' -import type { AgentSessionModelCatalogResult } from '../../../../shared/agent-session/agent-session-wire' -import { parseStructuredLaunchSeedOptions } from '../../../../shared/native-chat/input/native-chat-session-option-defaults' import { - createAgentPickerInventorySource, - useAgentPickerInventoryEntries, currentAgentPickerAcquisition, - observeAgentPickerAcquisition, - type AgentPickerInventorySource + observeAgentPickerAcquisition } from './agent-launch-picker-acquisition' import { agentPickerChoiceSeeds, type AgentPickerDefaultSettings } from '../../../../shared/agent-launch/picker/agent-launch-picker-defaults' -import { isAgentChatPermissionChoice } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' import { agentPickerEntriesFromRows, type AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' export { useAgentPickerInventoryEntries, type AgentPickerInventorySource } - -/** Forms consume entries; menu owners can retain the source without subscribing. */ export function useAgentLaunchPickerInventory( worktreeId: string | undefined, model: NewTabAgentMenuModel, @@ -54,8 +62,6 @@ export function useAgentLaunchPickerInventory( useAgentLaunchPickerInventorySource(worktreeId, model, open, selected) ) } - -/** Owns acquisition for the menu without subscribing its caller to the entries it publishes. */ export function useAgentLaunchPickerInventorySource( worktreeId: string | undefined, model: NewTabAgentMenuModel, @@ -64,6 +70,11 @@ export function useAgentLaunchPickerInventorySource( ): AgentPickerInventorySource { const store = useAppStateView() const viewActive = useAppStateViewActive() + const localCapabilities = useAppViewExternalStore( + subscribeLocalRuntimeCapabilityObservation, + readLocalRuntimeCapabilityObservation, + readLocalRuntimeCapabilityObservation + ) const selectedRef = useRef(selected) useLayoutEffect(() => { selectedRef.current = selected @@ -80,9 +91,14 @@ export function useAgentLaunchPickerInventorySource( } }).executionHostId const target = structuredAgentSessionTargetForHost(executionHostId) - const registeredAgents = readHostStructuredAgentsForRuntime( - executionHostId, - target?.kind === 'local' ? null : context?.runtimeId + const agentsVersion = useHostStructuredAgentsVersion() + const registeredAgents = recomputeOn( + [agentsVersion, executionHostId, target?.kind, context?.runtimeId], + () => + readHostStructuredAgentsForRuntime( + executionHostId, + target?.kind === 'local' ? null : context?.runtimeId + ) ) const repo = context?.workspace.repoId ? store.getState().repos.find((candidate) => candidate.id === context.workspace.repoId) @@ -93,18 +109,31 @@ export function useAgentLaunchPickerInventorySource( const hostId = parseExecutionHostId(executionHostId)?.id const worktrees = selectWorktreesByRepo(state) const folders = selectFolderWorkspaces(state) - const concreteWorkspace = useMemo( + const selectedWorkspace = useMemo( () => - !!( - workspaceId && - hostId && - selectWorkspaceByHostTarget( - { worktreesByRepo: worktrees ?? {}, folderWorkspaces: folders ?? [] }, - hostWorktreeTarget({ id: workspaceId, hostId }) - ) + workspaceId && + hostId && + selectWorkspaceByHostTarget( + { worktreesByRepo: worktrees ?? {}, folderWorkspaces: folders ?? [] }, + hostWorktreeTarget({ id: workspaceId, hostId }) ), [workspaceId, hostId, worktrees, folders] ) + const concreteWorkspace = !!selectedWorkspace + const hostCapabilities = + target?.kind === 'local' + ? localCapabilities.state === 'known' + ? localCapabilities.capabilities + : null + : buildAgentLaunchRouteInput(state, { + agent: 'claude', + workspace: context?.workspace ?? { + kind: worktreeId ? workspaceKindForWorktreeId(worktreeId) : 'floating', + ...(worktreeId ? { worktreeId } : {}) + } + }).hostCapabilities + const coherentCatalog = + hostCapabilities?.includes(AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY) === true const draftTarget = useMemo( () => ({ key: JSON.stringify([ @@ -132,6 +161,22 @@ export function useAgentLaunchPickerInventorySource( concreteWorkspace ] ) + // Without a concrete workspace, CLI discovery can only ask this machine, so other hosts keep the seed. + // SSH discovery has no route yet, so SSH workspaces keep it too. + const discoveryWorktreeId = draftTarget.worktreeId ?? null + const ownerRuntime = + discoveryWorktreeId || target?.kind === 'local' + ? resolveWorktreeModelDiscoveryRuntime(store.getState(), discoveryWorktreeId) + : null + const cliDiscoveryRuntime: RuntimeGitContext | null = + !ownerRuntime || ownerRuntime.connectionId + ? null + : discoveryWorktreeId + ? ownerRuntime + : { ...ownerRuntime, worktreePath: repo?.path ?? '' } + const reads = agentPickerModelCatalogReads({ target, worktree: selector, cliDiscoveryRuntime }) + const observesHostCatalog = + model.state === 'settled' && model.rows.some(reads.refreshOnInvalidation) const key = useMemo( () => JSON.stringify([ @@ -139,6 +184,7 @@ export function useAgentLaunchPickerInventorySource( context?.workspace, context?.pairingRevision, context?.runtimeId, + ...(observesHostCatalog ? [registeredAgents, coherentCatalog] : []), worktreeId, selector, executionHostId, @@ -154,21 +200,18 @@ export function useAgentLaunchPickerInventorySource( nativeChatPermissionMode: settings.nativeChatPermissionMode } ]), - [context, worktreeId, selector, executionHostId, model, settings] + [ + context, + worktreeId, + selector, + executionHostId, + model, + settings, + registeredAgents, + coherentCatalog, + observesHostCatalog + ] ) - // Without a concrete workspace, CLI discovery can only ask this machine, so other hosts keep the seed. - // SSH discovery has no route yet, so SSH workspaces keep it too. - const discoveryWorktreeId = draftTarget.worktreeId ?? null - const ownerRuntime = - discoveryWorktreeId || target?.kind === 'local' - ? resolveWorktreeModelDiscoveryRuntime(store.getState(), discoveryWorktreeId) - : null - const cliDiscoveryRuntime: RuntimeGitContext | null = - !ownerRuntime || ownerRuntime.connectionId - ? null - : discoveryWorktreeId - ? ownerRuntime - : { ...ownerRuntime, worktreePath: repo?.path ?? '' } const build = (defaults: AgentPickerDefaultSettings | null | undefined) => model.state === 'settled' ? agentPickerEntriesFromRows( @@ -179,6 +222,7 @@ export function useAgentLaunchPickerInventorySource( model.defaultTuiAgent ).map((entry) => ({ ...entry, + coherentCatalog, ...((!target && !(cliDiscoveryRuntime && agentPickerListsCliModels(entry))) || !entry.surfaces.length || (registeredAgents && @@ -247,41 +291,9 @@ export function useAgentLaunchPickerInventorySource( })) : undefined }, - catalog: async (entry, waitForListing) => - cliDiscoveryRuntime && agentPickerListsCliModels(entry) - ? readAgentPickerCliModelCatalog(entry.agent, cliDiscoveryRuntime) - : target - ? callStructuredAgentSession( - target, - 'agentSession.modelCatalog', - { - ...(selector ? { worktree: selector } : {}), - agent: entry.agent, - ...(waitForListing ? { waitForListing } : {}) - } - ) - : undefined, - support: async (entry) => { - if (!selector || !target) { - return undefined - } - const support = await callStructuredAgentSession<{ - seedOptions?: Record - }>(target, 'agentSession.createSupport', { - worktree: selector, - agent: entry.agent - }) - const parsed = parseStructuredLaunchSeedOptions(support?.seedOptions) - if (!parsed) { - return undefined - } - const { model, permissionMode, ...options } = parsed - return { - ...(model ? { model } : {}), - options, - ...(isAgentChatPermissionChoice(permissionMode) ? { permissionMode } : {}) - } - } + ...reads, + subscribeInvalidation: observesHostCatalog ? reads.subscribeInvalidation : undefined, + support: (entry) => readAgentPickerLaunchSupport(target, selector, entry.agent) }, { selected: () => selectedRef.current, diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx index bab415abcf3..c1d7ab35d97 100644 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx +++ b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx @@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({ attach: vi.fn(), publishMetadata: vi.fn(), createBrowserTab: vi.fn(async () => true), + restoredPageUnrecovered: false, addressBar: { current: null as { value: string @@ -36,6 +37,10 @@ vi.mock('./browser-client-page-renderer-installation', () => ({ attachBrowserClientPageToViewport: mocks.attach })) +vi.mock('./restored-client-hosted-recovery-window', () => ({ + useRestoredClientHostedRecoveryWindow: () => mocks.restoredPageUnrecovered +})) + vi.mock('./assemble-chrome/BrowserAddressBar', () => ({ // Keep the shared bar’s own behavior out of this suite; preserve the ref targeted by pane focus rules. default: (props: { @@ -61,6 +66,7 @@ function render(ui: React.ReactElement) { describe('ClientHostedBrowserPagePane', () => { beforeEach(() => { mocks.attach.mockReset() + mocks.restoredPageUnrecovered = false mocks.publishMetadata.mockReset().mockResolvedValue({ status: 'published', accepted: true }) // Download, popup and permission notices subscribe on mount; each has its own suite. installClientHostedPaneApi({ browser: { publishClientPageMetadata: mocks.publishMetadata } }) @@ -172,6 +178,47 @@ describe('ClientHostedBrowserPagePane', () => { expect(webview.src).toBe(normalizeBrowserNavigationUrl(loadError.validatedUrl)) }) + it('offers Reopen without a stale load-failure surface until the restored page attaches', () => { + mocks.restoredPageUnrecovered = true + const browserTab = { + ...page(), + url: 'https://remote.internal/failed', + loadError: { + code: -120, + description: 'ERR_SOCKS_CONNECTION_FAILED', + validatedUrl: 'https://remote.internal/failed' + } + } + const pane = (placement: typeof PLACEMENT | null) => ( + + ) + const view = render(pane(null)) + + expect( + screen.getByRole('button', { name: 'Reopen on server' }).disabled + ).toBe(false) + expect(screen.queryByText('Retry', { selector: 'button' })).toBeNull() + + const { webview, setUrl } = createWebview() + setUrl(browserTab.url) + mocks.attach.mockReturnValue(retainedAttachment(webview)) + mocks.restoredPageUnrecovered = false + view.rerender(pane(PLACEMENT)) + + expect(screen.queryByRole('button', { name: 'Reopen on server' })).toBeNull() + expect(screen.getByText('Retry', { selector: 'button' })).toBeTruthy() + }) + it('shows exact-generation unavailability without creating a fallback guest', () => { mocks.attach.mockReturnValue(null) diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx index d2f5727e213..e863ff5e03c 100644 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx +++ b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx @@ -281,7 +281,8 @@ export function ClientHostedBrowserPagePane({ setAddressBarValueFromPage ]) - const showFailureOverlay = !attachmentError && Boolean(browserTab.loadError) + const unavailable = Boolean(attachmentError) || restoredPageUnrecovered + const showFailureOverlay = !unavailable && Boolean(browserTab.loadError) const markup = useClientHostedBrowserMarkup({ webviewRef, @@ -289,7 +290,7 @@ export function ClientHostedBrowserPagePane({ runtimeEnvironmentId, placement, isActive, - unavailable: Boolean(attachmentError) || restoredPageUnrecovered, + unavailable, showFailureOverlay }) @@ -371,7 +372,7 @@ export function ClientHostedBrowserPagePane({ onRetry={() => reload.runReloadTrigger('reload')} /> ) : null} - {attachmentError || restoredPageUnrecovered ? ( + {unavailable ? ( boolean, + update: () => void +): { refresh: () => void; dispose: () => void } { + let copyHintFrame: number | null = null + let disposed = false + let stopLabelSubscriptions: (() => void) | null = null + const cancelCopyHintFrame = (): void => { + if (copyHintFrame !== null) { + window.cancelAnimationFrame(copyHintFrame) + copyHintFrame = null + } + } + + const refreshCopyHint = (): void => { + cancelCopyHintFrame() + if (!disposed) { + update() + } + } + + const scheduleCopyHintRefresh = (): void => { + if (disposed || copyHintFrame !== null || !editorInstance.hasTextFocus() || !isVisible()) { + return + } + copyHintFrame = window.requestAnimationFrame(() => { + copyHintFrame = null + if (!disposed && editorInstance.hasTextFocus() && isVisible()) { + update() + } + }) + } + + const subscribeCopyHintLabels = (): void => { + if (stopLabelSubscriptions !== null) { + return + } + let keybindings = useAppStore.getState().keybindings + const unsubscribeKeybindings = useAppStore.subscribe((state) => { + if (state.keybindings !== keybindings) { + keybindings = state.keybindings + scheduleCopyHintRefresh() + } + }) + const unsubscribeTranslation = subscribeTranslationScope(scheduleCopyHintRefresh) + stopLabelSubscriptions = () => { + unsubscribeKeybindings() + unsubscribeTranslation() + stopLabelSubscriptions = null + } + } + + const stop = (): void => { + cancelCopyHintFrame() + stopLabelSubscriptions?.() + } + + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Monaco 0.55.1 exposes this event at runtime but omits it from its public declaration. + const viewZoneEditor = editorInstance as editor.IStandaloneCodeEditor & { + readonly onDidChangeViewZones: IEvent + } + const listeners = [ + editorInstance.onDidFocusEditorText(subscribeCopyHintLabels), + editorInstance.onDidBlurEditorText(stop), + editorInstance.onDidLayoutChange(scheduleCopyHintRefresh), + editorInstance.onDidChangeModel(scheduleCopyHintRefresh), + editorInstance.onDidChangeModelContent(scheduleCopyHintRefresh), + editorInstance.onDidChangeConfiguration(scheduleCopyHintRefresh), + editorInstance.onDidContentSizeChange(scheduleCopyHintRefresh), + editorInstance.onDidChangeHiddenAreas(scheduleCopyHintRefresh), + editorInstance.onDidChangeModelDecorations(scheduleCopyHintRefresh), + viewZoneEditor.onDidChangeViewZones(scheduleCopyHintRefresh) + ] + + if (editorInstance.hasTextFocus()) { + subscribeCopyHintLabels() + } + return { + refresh: refreshCopyHint, + dispose: () => { + disposed = true + stop() + for (const listener of listeners) { + listener.dispose() + } + } + } +} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-model.test.ts b/src/renderer/src/components/editor/git-graph/git-graph-model.test.ts new file mode 100644 index 00000000000..16e94e19af3 --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-model.test.ts @@ -0,0 +1,100 @@ +import { expect, it } from 'vitest' +import { GitGraphModel } from './git-graph-model' +import type { + GitHistoryItem, + GitHistoryResult +} from '../../../../../shared/git/history/git-history-types' + +const item = (id: string, parentIds: string[] = []): GitHistoryItem => ({ + id, + parentIds, + subject: id, + message: id +}) +const page = (items: GitHistoryItem[]): GitHistoryResult => ({ + items, + hasMore: false, + hasIncomingChanges: false, + hasOutgoingChanges: false, + limit: 50 +}) +const currentRef = { id: 'refs/heads/main', name: 'main', revision: 'M' } + +it('recolors a late side parent and all later rotating colors without changing published rows', () => { + const model = new GitGraphModel() + const merge = item('M', ['A', 'B']) + const later = item('X', ['Y']) + const first = { ...page([merge, later]), currentRef } + model.update(first) + const published = model.rows + const expected = [ + { id: 'A', color: 'git-graph-lane-1' }, + { id: 'B', color: 'git-graph-lane-2' } + ] + expect(published[0]?.outputSwimlanes).toEqual(expected) + expect(published[1]?.outputSwimlanes).toEqual([ + ...expected, + { id: 'Y', color: 'git-graph-lane-3' } + ]) + const parent = { ...item('B'), references: [currentRef] } + model.update({ ...first, items: [merge, later, parent] }) + expect(model.rows[0]?.outputSwimlanes).toEqual([ + { id: 'A', color: 'git-graph-lane-1' }, + { id: 'B', color: 'git-graph-ref' } + ]) + expect(model.rows[1]?.outputSwimlanes).toEqual([ + { id: 'A', color: 'git-graph-lane-1' }, + { id: 'B', color: 'git-graph-ref' }, + { id: 'Y', color: 'git-graph-lane-2' } + ]) + expect(published[0]?.outputSwimlanes).toEqual(expected) + expect(published[1]?.outputSwimlanes).toEqual([ + ...expected, + { id: 'Y', color: 'git-graph-lane-3' } + ]) + model.update(first) + model.update({ ...first, items: [merge, later, item('C')] }) + expect(model.rows[0]?.outputSwimlanes).toEqual(expected) + expect(model.rows[1]?.outputSwimlanes).toEqual([ + ...expected, + { id: 'Y', color: 'git-graph-lane-3' } + ]) +}) + +it('resolves same-batch parents first-wins, keeps roots separate and updates raw details and HEAD', () => { + const model = new GitGraphModel() + const merge = item('M', ['A', 'B']) + const parent = { ...item('B'), references: [currentRef] } + const lead = item('lead') + model.update({ ...page([lead]), currentRef }) + model.update({ + ...page([lead, merge, parent, item('B'), item('A', ['C']), item('C')]), + currentRef: { ...currentRef } + }) + expect(model.rows[1]?.outputSwimlanes).toEqual([ + { id: 'A', color: 'git-graph-lane-1' }, + { id: 'B', color: 'git-graph-ref' } + ]) + expect(model.rows[2]?.outputSwimlanes).toEqual([{ id: 'A', color: 'git-graph-lane-1' }]) + expect(model.rows.at(-1)?.outputSwimlanes).toEqual([]) + expect(model.find('B')?.item).toEqual({ + id: 'B', + subject: 'B', + message: 'B', + parentIds: [], + references: [currentRef] + }) + expect(model.find('B')?.index).toBe(2) + const refreshed = { ...parent, subject: 'Updated', message: 'New body' } + model.update({ ...page([merge, refreshed]), currentRef: { ...currentRef, revision: 'B' } }) + expect(model.rows.map((row) => row.kind)).toEqual(['node', 'HEAD']) + expect(model.find('B')?.item.subject).toBe('Updated') + expect(model.find('B')?.item.references?.[0]?.color).toBeUndefined() + model.update(undefined) + expect(model.rows).toEqual([]) + expect(model.find('B')).toBeUndefined() + model.update(page([item('fresh')])) + model.update(page([])) + expect(model.rows).toEqual([]) + expect(model.find('fresh')).toBeUndefined() +}) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-model.ts b/src/renderer/src/components/editor/git-graph/git-graph-model.ts new file mode 100644 index 00000000000..f8e81400ab9 --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-model.ts @@ -0,0 +1,108 @@ +import { + appendGitHistoryViewModels, + buildDefaultGitHistoryColorMap, + getGitHistoryLabelColor, + type GitHistoryGraphState, + type GitHistoryItemViewModel +} from '../../../../../shared/git/history/git-history-graph' +import type { + GitHistoryGraphColorId, + GitHistoryItem, + GitHistoryResult +} from '../../../../../shared/git/history/git-history-types' + +// Owned by a mounted pane; callers publish immutable input arrays. +export class GitGraphModel { + rows: GitHistoryItemViewModel[] = [] + maxWidth = 132 + private items: GitHistoryItem[] = [] + private index = new Map() + private pending = new Set() + private state: GitHistoryGraphState = { colorIndex: -1, frontier: [] } + private colors = new Map() + private refs: (string | undefined)[] = [] + + find(id: string | undefined): { item: GitHistoryItem; index: number } | undefined { + return id === undefined ? undefined : this.index.get(id) + } + + private snapshot(selectedId?: string, revealId?: string) { + return { + rows: this.rows, + maxWidth: this.maxWidth, + selected: this.find(selectedId)?.item, + revealIndex: this.find(revealId)?.index + } + } + + update(result: GitHistoryResult | undefined, selectedId?: string, revealId?: string) { + const items = result?.items ?? [] + const colors = buildDefaultGitHistoryColorMap(result ?? {}) + const refs = [result?.currentRef?.id, result?.currentRef?.revision] + const sameConfig = + refs.every((ref, i) => ref === this.refs[i]) && + colors.size === this.colors.size && + [...colors].every(([id, color]) => this.colors.has(id) && this.colors.get(id) === color) + if (items === this.items && sameConfig) { + return this.snapshot(selectedId, revealId) + } + + let append = + sameConfig && + items.length >= this.items.length && + this.items.every((item, i) => item === items[i]) + let start = append ? this.items.length : 0 + if (append && start === items.length) { + this.items = items + return this.snapshot(selectedId, revealId) + } + if (append) { + for (let i = start; i < items.length; i++) { + const item = items[i]! + if (this.pending.has(item.id) && getGitHistoryLabelColor(item, colors)) { + append = false + start = 0 + break + } + } + } + if (!append || items.length === 0) { + this.rows = [] + this.maxWidth = 132 + this.index.clear() + this.pending.clear() + this.state = { colorIndex: -1, frontier: [] } + } + for (let i = start; i < items.length; i++) { + const item = items[i]! + if (!this.index.has(item.id)) { + this.index.set(item.id, { item, index: i }) + } + this.pending.delete(item.id) + } + const added = appendGitHistoryViewModels( + items.slice(start), + this.state, + (id) => { + const item = this.index.get(id)?.item + if (!item) { + this.pending.add(id) + } + return item + }, + colors, + result?.currentRef + ) + for (const row of added) { + this.maxWidth = Math.max( + this.maxWidth, + (Math.max(row.inputSwimlanes.length, row.outputSwimlanes.length) + 1) * 11 + ) + } + this.rows = start ? this.rows.concat(added) : added + this.items = items + this.colors = colors + this.refs = refs + return this.snapshot(selectedId, revealId) + } +} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx index e483429ff2d..e3c1357ca3b 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -8,13 +8,13 @@ import { createRoot } from 'react-dom/client' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' import { GitGraphTab } from './git-graph-tab' - +import * as graphSvg from '@/components/right-sidebar/source-control/sync/git-history-graph-svg' import type { GitHistoryResult } from '../../../../../shared/git/history/git-history-types' const { getHistory, getRefs, viewport } = vi.hoisted(() => ({ getHistory: vi.fn(), getRefs: vi.fn(), - viewport: { rows: 20, rendered: Infinity } + viewport: { rows: 20 } })) vi.mock('@/runtime/source-control/git/runtime-git-status-client', async (original) => ({ ...(await original()), @@ -25,33 +25,39 @@ vi.mock('@/runtime/source-control/git/runtime-git-diff-client', async (original) ...(await original()), getRuntimeGitCommitCompare: vi.fn(async () => ({ summary: { status: 'ready' }, entries: [] })) })) -vi.mock('@tanstack/react-virtual', () => ({ - useVirtualizer: (options: { count: number; getScrollElement: () => HTMLElement | null }) => ({ - getTotalSize: () => options.count * 28, - getVirtualItems: () => - Array.from({ length: Math.min(options.count, viewport.rendered) }, (_, index) => ({ - index, - start: index * 28 - })), - get range() { - return options.count - ? { startIndex: 0, endIndex: Math.min(options.count, viewport.rows) - 1 } - : null - }, - measureElement: () => {}, - scrollToIndex: (index: number) => { - const element = options.getScrollElement() - if (element) { - element.scrollTop = index * 28 - } - } - }) -})) const container = document.createElement('div') document.body.appendChild(container) let root = createRoot(container) +let resize: (() => void) | undefined const initialState = useAppStore.getState() beforeEach(() => { + vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation( + () => viewport.rows * 24 + ) + vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(function ( + this: HTMLElement + ) { + return ( + Number.parseFloat( + this.firstElementChild?.getAttribute('style')?.match(/height: ([\d.]+)px/)?.[1] ?? '0' + ) + 48 + ) + }) + vi.stubGlobal( + 'ResizeObserver', + class { + constructor(private readonly callback: () => void) { + resize = callback + } + observe() {} + disconnect() { + if (resize === this.callback) { + resize = undefined + } + } + unobserve() {} + } + ) useAppStore.setState({ repos: [repo], worktreesByRepo: { r: [local] }, @@ -64,7 +70,6 @@ afterEach(async () => { await act(async () => root.unmount()) root = createRoot(container) viewport.rows = 20 - viewport.rendered = Infinity disposeGitGraphHistory(`${workspaceId}::git-graph`) useAppStore.setState(initialState, true) vi.restoreAllMocks() @@ -76,6 +81,7 @@ const result: GitHistoryResult = { hasOutgoingChanges: false, limit: 50 } + const renderTab = () => act(async () => root.render( @@ -86,11 +92,11 @@ const renderTab = () => ) const loadedCount = () => gitGraphHistoryForTab(workspaceId).view.getState().result?.items.length -it.each([50_000])( +it.each([50_000, 500_000])( 'releases %i commits of replaced history while the pane stays mounted', async (count) => { - viewport.rows = Infinity - viewport.rendered = 40 + viewport.rows = 40 + const renderedGraph = vi.spyOn(graphSvg, 'GitHistoryGraphSvg') getHistory .mockReset() .mockImplementationOnce(async () => ({ @@ -107,10 +113,22 @@ it.each([50_000])( .mockRejectedValueOnce(new Error('network down')) .mockResolvedValue({ ...result, refs: 'head' }) await renderTab() + await act(async () => { + const scroll = container.querySelector('div.overflow-y-auto')! + scroll.scrollTop = (count - 40) * 24 + scroll.dispatchEvent(new Event('scroll')) + }) + expect(getHistory).toHaveBeenCalledTimes(2) + expect(container.textContent).toContain('network down') const replaced = (() => { const loaded = gitGraphHistoryForTab(workspaceId).view.getState().result! expect(loaded.items).toHaveLength(count) - return new WeakRef(loaded) + return [ + new WeakRef(renderedGraph.mock.calls[0]![0].viewModel), + new WeakRef(loaded), + new WeakRef(loaded.items), + new WeakRef(loaded.items[count - 1]!) + ] })() await act(async () => useAppStore.setState({ gitGraphFiltersByWorktree: { [workspaceId]: 'head' } }) @@ -120,13 +138,81 @@ it.each([50_000])( }) expect(loadedCount()).toBe(1) getHistory.mockReset() - if (typeof globalThis.gc !== 'function') { - throw new Error('Run with the repository Vitest --expose-gc config') + renderedGraph.mockClear() + await expectReleased(replaced) + if (count === 500_000) { + let controller = gitGraphHistoryForTab(workspaceId) + const loadDisposable = async () => { + getHistory.mockImplementationOnce(async () => ({ + ...result, + items: [{ id: 'disposable', subject: 'Disposable', message: 'Body', parentIds: [] }] + })) + await act(async () => { + await controller.refresh() + }) + const payload = controller.view.getState().result!.items[0]! + const row = renderedGraph.mock.calls.find( + ([props]) => props.viewModel.historyItem.id === 'disposable' + )![0].viewModel + const weak = [new WeakRef(payload), new WeakRef(row)] + getHistory.mockReset() + renderedGraph.mockClear() + return weak + } + const empty = await loadDisposable() + getHistory.mockResolvedValueOnce({ ...result, items: [] }) + await act(async () => { + await controller.refresh() + }) + // A normal refresh commits past React's previous-render snapshot. + getHistory.mockRejectedValueOnce(new Error('Empty refresh failed')) + await act(async () => { + await controller.refresh() + }) + expect(container.textContent).toContain('Empty refresh failed') + expect(loadedCount()).toBe(0) + getHistory.mockReset() + renderedGraph.mockClear() + await expectReleased(empty) + const missing = await loadDisposable() + getHistory.mockRejectedValueOnce(new Error('failed filter')) + await act(async () => + useAppStore.setState({ gitGraphFiltersByWorktree: { [workspaceId]: 'all' } }) + ) + await act(async () => { + await controller.settledResult() + }) + expect(loadedCount()).toBeUndefined() + getHistory.mockRejectedValueOnce(new Error('Missing refresh failed')) + await act(async () => { + await controller.refresh() + }) + expect(container.textContent).toContain('Missing refresh failed') + expect(loadedCount()).toBeUndefined() + getHistory.mockReset() + renderedGraph.mockClear() + await expectReleased(missing) + const unmounted = await loadDisposable() + await act(async () => { + disposeGitGraphHistory(`${workspaceId}::git-graph`) + root.unmount() + }) + root = createRoot(container) + controller = gitGraphHistoryForTab(workspaceId) + await expectReleased(unmounted) } - for (let round = 0; round < 3; round++) { - await new Promise((resolve) => setImmediate(resolve)) - globalThis.gc() - } - expect(replaced.deref()).toBeUndefined() } ) + +async function expectReleased(obsolete: WeakRef[]) { + if (typeof globalThis.gc !== 'function') { + throw new Error('Run with the repository Vitest --expose-gc config') + } + for (let round = 0; round < 3; round++) { + await new Promise((resolve) => setImmediate(resolve)) + globalThis.gc() + } + for (const value of obsolete) { + expect(value.deref()).toBeUndefined() + } +} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-tab-controllers.ts b/src/renderer/src/components/editor/git-graph/git-graph-tab-controllers.ts index 7c8f789ed38..9175143d8de 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-tab-controllers.ts +++ b/src/renderer/src/components/editor/git-graph/git-graph-tab-controllers.ts @@ -15,3 +15,18 @@ export function disposeGitGraphHistory(tabId: string): void { controllers.get(tabId)?.dispose() controllers.delete(tabId) } + +export function setGitGraphViewport( + controller: GitGraphHistoryController, + field: 'scrollOffset' | 'graphWidth', + value: number +): void { + controller[field] = value +} + +export function getGitGraphViewport( + controller: GitGraphHistoryController, + field: 'scrollOffset' | 'graphWidth' +): number { + return controller[field] +} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx index 359c7035182..e757ce5cf02 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx @@ -1,11 +1,11 @@ +import { getGitGraphViewport, setGitGraphViewport } from './git-graph-tab-controllers' import { useGitCommitActionsSupport } from '@/runtime/source-control/git/git-commit-actions-capability' import { GitGraphCommitActionControls, GitGraphCommitConfirmStrip } from './git-graph-commit-action-controls' -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useLayoutEffect, useState } from 'react' import { useSidebarResize } from '@/hooks/useSidebarResize' -import { useVirtualizer } from '@tanstack/react-virtual' import { RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' @@ -14,10 +14,8 @@ import { GitHistoryCommitContextMenu } from '@/components/right-sidebar/source-c import { GitHistoryGraphSvg } from '@/components/right-sidebar/source-control/sync/git-history-graph-svg' import { useGitHistoryCommitActions } from '@/components/right-sidebar/source-control/sync/use-git-history-commit-actions' import { formatGitHistoryTimestamp } from '@/components/right-sidebar/source-control/sync/git-history-format' -import { - buildDefaultGitHistoryColorMap, - buildGitHistoryViewModels -} from '../../../../../shared/git/history/git-history-graph' +import { GitGraphModel } from './git-graph-model' +import { useGitGraphViewport } from './use-git-graph-viewport' import { useGitGraphHistory, gitGraphFilterSupported } from './use-git-graph-history' import { GitGraphFilter } from './git-graph-filter' import { loadMoreInView } from './git-graph-viewport-paging' @@ -40,34 +38,18 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { scope?.route.executionHostId ?? undefined ) const workspaces = useGitGraphWorkspaces(scope) - const rows = useMemo( - () => - result - ? buildGitHistoryViewModels( - result.items, - buildDefaultGitHistoryColorMap(result), - result.currentRef - ) - : [], - [result] - ) - const maxGraphWidth = useMemo( - () => - rows.reduce( - (width, row) => - Math.max( - width, - (Math.max(row.inputSwimlanes.length, row.outputSwimlanes.length) + 1) * 11 - ), - 132 - ), - [rows] - ) + const [model] = useState(() => new GitGraphModel()) + const { + rows, + maxWidth: maxGraphWidth, + selected, + revealIndex + } = model.update(result, selectedId, revealId) const [graphWidth, setGraphWidth] = useState(controller.graphWidth) const [draftGraphWidth, setDraftGraphWidth] = useState(graphWidth) const commitGraphWidth = useCallback( (width: number) => { - controller.graphWidth = width + setGitGraphViewport(controller, 'graphWidth', width) setGraphWidth(width) }, [controller] @@ -82,18 +64,22 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { onDraftWidthChange: setDraftGraphWidth }) const columns = `160px ${draftGraphWidth}px minmax(200px,1fr) 120px 100px` - const scroll = useRef(null) - const virtualizer = useVirtualizer({ - count: rows.length, - initialOffset: () => history.controller.scrollOffset, - getScrollElement: () => scroll.current, - estimateSize: () => 24, - overscan: 12, - getItemKey: (index) => rows[index]!.historyItem.id - }) - const virtualItems = virtualizer.getVirtualItems() - // Null while the pane has no height; read after getVirtualItems() recomputes it. - const lastVisibleIndex = virtualizer.range?.endIndex ?? -1 + const getScrollOffset = useCallback( + () => getGitGraphViewport(controller, 'scrollOffset'), + [controller] + ) + const saveScrollOffset = useCallback( + (offset: number) => setGitGraphViewport(controller, 'scrollOffset', offset), + [controller] + ) + const { + scroll: scrollRef, + items: virtualRows, + lastVisible: lastVisibleIndex, + height: virtualHeight, + onScroll, + reveal: revealRow + } = useGitGraphViewport(rows.length, getScrollOffset, saveScrollOffset) const endInView = lastVisibleIndex >= 0 && lastVisibleIndex >= rows.length - 1 - PAGE_AHEAD_ROWS useEffect(() => { // Viewport demand, not scroll events: page whenever the end of loaded rows is in view. @@ -101,22 +87,12 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { loadMoreInView(controller, result) } }, [endInView, result, loading, controller]) - const selected = result?.items.find((item) => item.id === selectedId) useLayoutEffect(() => { - if (scroll.current) { - scroll.current.scrollTop = controller.scrollOffset - } - }, [controller]) - useLayoutEffect(() => { - if (!revealId) { - return - } - const index = rows.findIndex((row) => row.historyItem.id === revealId) - if (index !== -1) { - virtualizer.scrollToIndex(index) + if (revealIndex !== undefined) { + revealRow(revealIndex) controller.clearReveal() } - }, [rows, revealId, virtualizer, controller]) + }, [revealIndex, revealRow, controller]) const actions = useGitHistoryCommitActions({ activeWorktreeId: worktreeId, worktreePath: scope?.worktree.path ?? null, @@ -195,20 +171,15 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { {t('gitGraph.date', 'Date')}
{ - const element = scroll.current - if (element) { - controller.scrollOffset = element.scrollTop - } - }} + onScroll={onScroll} >
- {virtualItems.map((virtualRow) => { + {virtualRows.map((virtualRow) => { const viewModel = rows[virtualRow.index]! const item = viewModel.historyItem return ( @@ -238,7 +209,10 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { />
- +