From 576a6c93420d2f07dd8fb924916cbc5612b8dea4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:38:19 -0800 Subject: [PATCH 01/40] Update browser navigation state without blocking page attachment (#41045) * Keep browser chrome metadata current without synchronous guest reads * Provide the guest Escape subscription in browser pane fixtures * Provide native navigation state in browser guest fixtures * Preserve browser navigation and loading across asynchronous metadata reads * Retire browser metadata when its actual guest is removed * Explain native identity casts in browser disposal fixtures * Preserve URL titles for untitled client browser pages * Preserve current browser navigation and untitled page labels * Keep merged browser failure type within lint limit * Keep merged browser failure type within lint limit * Bound published browser titles to the existing wire limit * Use template literals in browser title regression --- .../commands/cdp-bridge-integration.test.ts | 2 + ...owser-certificate-trust-controller.test.ts | 9 + .../browser-certificate-trust-controller.ts | 12 + ...rowser-client-page-profile-binding.test.ts | 2 + .../browser-manager-guest-visibility.test.ts | 3 + .../manager/browser-manager-test-harness.ts | 10 + ...rowser-manager-devtools-retirement.test.ts | 2 + ...er-manager-client-hosted-downloads.test.ts | 2 + .../grab/browser-manager-grab-test-harness.ts | 2 + ...rowser-manager-load-failure-replay.test.ts | 2 + .../browser-manager-popup-child.test.ts | 2 + .../browser-manager-popup-routing.test.ts | 4 + ...er-manager-destroyed-guest-test-fixture.ts | 10 + .../browser-manager-guest-policy.ts | 27 ++ ...rowser-manager-page-prompt-routing.test.ts | 3 + .../browser-manager-registration.ts | 2 + .../browser-manager-viewport-test-fixtures.ts | 2 + .../navigation/browser-guest-metadata.test.ts | 119 ++++++ .../navigation/browser-guest-metadata.ts | 193 +++++++++ src/main/ipc/browser/browser.ts | 26 ++ src/preload/api/browser/browser-api.ts | 6 + ...bridge-guest-registration-and-downloads.ts | 12 + ...edBrowserPagePane.failure-remount.test.tsx | 364 ++++++++++++++++- .../ClientHostedBrowserPagePane.test.tsx | 97 ++++- .../ClientHostedBrowserPagePane.tsx | 153 ++++--- .../ReopenBrowserPageOnServerButton.tsx | 8 +- .../browser-page-context-menu-items.tsx | 5 +- .../assemble-chrome/browser-page-pane.tsx | 5 +- .../assemble-chrome/browser-page-toolbar.tsx | 5 +- .../browser-client-page-guest-metadata.ts | 63 +-- ...ser-client-page-metadata-publisher.test.ts | 24 ++ .../browser-client-page-metadata-publisher.ts | 3 +- ...wser-client-page-retained-registry.test.ts | 45 +++ .../browser-client-page-retained-registry.ts | 11 +- .../browser-pane/browser-reopen-on-server.ts | 6 +- .../client-hosted-browser-pane-test-rig.ts | 40 ++ ...ient-hosted-browser-unavailable-notice.tsx | 6 +- .../describe-page/browser-page-url-display.ts | 19 +- .../host-guest/attach-browser-page-webview.ts | 5 +- .../bind-browser-page-webview-listeners.ts | 75 +++- .../browser-guest-metadata-cache.test.ts | 87 ++++ .../browser-guest-metadata-cache.ts | 299 ++++++++++++++ ...rowser-page-evicted-guest-recovery.test.ts | 1 - .../host-guest/browser-page-guest-recovery.ts | 3 +- .../host-guest/browser-page-metadata.test.ts | 372 ++++++++++++++++++ ...rowser-page-registration-ownership.test.ts | 1 - .../host-guest/browser-page-viewport.test.ts | 137 ++++++- .../host-guest/browser-page-viewport.ts | 16 + .../browser-page-webview-guest-session.ts | 3 - .../browser-page-webview-loading-handlers.ts | 79 ++-- ...rowser-page-webview-navigation-handlers.ts | 45 +-- ...use-browser-page-viewport-size-feedback.ts | 5 +- .../use-browser-page-webview-lifecycle.ts | 28 -- .../use-browser-page-webview-shortcuts.ts | 9 +- .../host-guest/webview-registry.ts | 2 + .../navigate/browser-reload-action.ts | 5 +- ...hromium-error-page-poll-visibility.test.ts | 87 ---- .../navigate/chromium-error-page-polling.ts | 6 - .../navigate/navigate-browser-page-url.ts | 5 +- .../use-browser-page-webview-url-sync.ts | 98 ++--- .../use-client-hosted-page-url-submission.ts | 24 +- .../remote-browser-page-viewport.tsx | 2 +- .../ipc-events/browser-state-ipc-bridge.ts | 15 +- .../browser/pages/browser-page-records.ts | 13 +- .../browser-workspace-doc-location.test.ts | 17 + src/shared/browser/browser-display-title.ts | 14 + .../guest-lifecycle/browser-guest-metadata.ts | 17 + 67 files changed, 2277 insertions(+), 499 deletions(-) create mode 100644 src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.test.ts create mode 100644 src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.ts create mode 100644 src/renderer/src/components/browser-pane/host-guest/browser-guest-metadata-cache.test.ts create mode 100644 src/renderer/src/components/browser-pane/host-guest/browser-guest-metadata-cache.ts create mode 100644 src/renderer/src/components/browser-pane/host-guest/browser-page-metadata.test.ts delete mode 100644 src/renderer/src/components/browser-pane/navigate/chromium-error-page-poll-visibility.test.ts delete mode 100644 src/renderer/src/components/browser-pane/navigate/chromium-error-page-polling.ts create mode 100644 src/shared/browser/browser-display-title.ts create mode 100644 src/shared/browser/guest-lifecycle/browser-guest-metadata.ts diff --git a/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts b/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts index 796522a2f81..a852f9d55dd 100644 --- a/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts +++ b/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts @@ -1,3 +1,4 @@ +import { guestNavigationMethods } from '../../guest-lifecycle/manager/browser-manager-test-harness' import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' import { mkdtempSync } from 'node:fs' @@ -201,6 +202,7 @@ function createMockGuest( const debuggerListeners = new Map void)[]>() const guest = { + ...guestNavigationMethods(), id, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/certificate-trust/browser-certificate-trust-controller.test.ts b/src/main/browser/certificate-trust/browser-certificate-trust-controller.test.ts index edf10dbb57c..9f4cb327c02 100644 --- a/src/main/browser/certificate-trust/browser-certificate-trust-controller.test.ts +++ b/src/main/browser/certificate-trust/browser-certificate-trust-controller.test.ts @@ -142,6 +142,15 @@ describe('BrowserCertificateTrustController', () => { controller.installSessionRequestGuard(browserSession) }) + it('keeps challenge ownership and expiry when reading a specific guest', () => { + certificateEvent({ controller, guest }) + expect(controller.hasFailureForGuest(guest.id)).toBe(true) + expect(controller.hasFailureForGuest(otherGuest.id)).toBe(false) + now += 300_000 + expect(controller.hasFailureForGuest(guest.id)).toBe(false) + expect(controller.proceed('page-1', 'challenge-1')).toEqual({ ok: false, reason: 'missing' }) + }) + it('blocks a session-cached certificate for sibling requests until that guest approves it', () => { certificateEvent({ controller, guest }) expect(controller.proceed('page-1', 'challenge-1')).toEqual({ ok: true }) diff --git a/src/main/browser/certificate-trust/browser-certificate-trust-controller.ts b/src/main/browser/certificate-trust/browser-certificate-trust-controller.ts index a8e8621dbe0..cf601c508ee 100644 --- a/src/main/browser/certificate-trust/browser-certificate-trust-controller.ts +++ b/src/main/browser/certificate-trust/browser-certificate-trust-controller.ts @@ -142,6 +142,18 @@ export class BrowserCertificateTrustController { this.requestGuard.revokeForCommittedNavigation(webContentsId, url) } + hasFailureForGuest(webContentsId: number): boolean { + const pending = this.pendingByGuestId.get(webContentsId) + if (!pending) { + return false + } + if (pending.expiresAt <= this.now()) { + this.clearPending(webContentsId, true) + return false + } + return true + } + getFailure(browserPageId: string): BrowserCertificateFailure | null { this.pruneExpired() for (const pending of this.pendingByGuestId.values()) { diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts index be6fd057434..ff5336821fe 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts @@ -32,6 +32,7 @@ vi.mock('../../guest-lifecycle/popups/presentation/popup-origin-bar-window', () import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { createBrowserClientPageGuestBinding } from './browser-client-page-guest-binding' import { + guestNavigationMethods, resetBrowserManagerMocks, resetBrowserManagerState } from '../../guest-lifecycle/manager/browser-manager-test-harness' @@ -73,6 +74,7 @@ describe('staged guest binding', () => { function createGuest(id: number) { return { + ...guestNavigationMethods(), id, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts index 51dff485ff3..5be8dc68670 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts @@ -42,6 +42,7 @@ vi.mock('../popups/presentation/popup-origin-bar-window', () => ({ import { browserManager } from './browser-manager' import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' import { + guestNavigationMethods, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState @@ -84,6 +85,7 @@ describe('browserManager', () => { it.each(['acquire'])('cleans capture ownership after renderer %s fails', (failure) => { vi.useFakeTimers() const guest = { + ...guestNavigationMethods(), id: 1711, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), @@ -141,6 +143,7 @@ describe('browserManager', () => { it('does not let a destroyed guest and renderer release a replacement page hold', () => { vi.useFakeTimers() const makeGuest = (id: number) => ({ + ...guestNavigationMethods(), id, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts index 6729d982e76..a3dca00ccb5 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts @@ -4,6 +4,16 @@ import { browserManager } from './browser-manager' export const rendererWebContentsId = 5001 export const guestBaseUserAgent = 'Mozilla/5.0 (Test) Chrome/140.0.0.0' +export const guestNavigationMethods = () => ({ + getURL: vi.fn(() => 'https://example.com/'), + getTitle: vi.fn(() => 'Example'), + isLoadingMainFrame: vi.fn(() => false), + navigationHistory: { + canGoBack: vi.fn(() => false), + canGoForward: vi.fn(() => false) + } +}) + export type GuestUserAgentMethods = { getUserAgent: Mock<() => string> setUserAgent: Mock<(userAgent: string) => void> diff --git a/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts b/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts index c83230f0d52..81b5cb0eb26 100644 --- a/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts +++ b/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts @@ -1,3 +1,4 @@ +import { guestNavigationMethods } from '../browser-manager-test-harness' // @orca-isolated-worker: cached Electron mocks can omit BrowserWindow across shared files. import { EventEmitter } from 'node:events' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -56,6 +57,7 @@ function createGuest(id: number) { let opened = false const frontend: { devToolsWebContents: DevToolsHost | null } = { devToolsWebContents: null } const guest = Object.assign(new EventEmitter(), frontend, { + ...guestNavigationMethods(), id, hostWebContents: {}, getType: () => 'webview', diff --git a/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts index eed58334674..f6b1fa38817 100644 --- a/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts +++ b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts @@ -44,6 +44,7 @@ import { import { createBrowserClientPageGuestBinding } from '../../../client-pages/lifecycle/browser-client-page-guest-binding' import { resetBrowserRouteGuestPopupOwnership } from '../../../routing/guest-authority/browser-route-guest-popup-ownership' import { + guestNavigationMethods, createDownloadItem, getDownloadItemEventHandler, rendererWebContentsId, @@ -176,6 +177,7 @@ describe('client-hosted downloads', () => { function createGuest(id: number) { return { + ...guestNavigationMethods(), id, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-test-harness.ts b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-test-harness.ts index 6cbc482dcf4..bf22d55c7dc 100644 --- a/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-test-harness.ts +++ b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-test-harness.ts @@ -1,3 +1,4 @@ +import { guestNavigationMethods } from '../browser-manager-test-harness' import { vi, type Mock } from 'vitest' import { browserManager } from '../browser-manager' @@ -24,6 +25,7 @@ export type GrabTestMocks = { export function makeGuest(id: number, mocks: GrabTestMocks): Electron.WebContents { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: grab tests drive only the guest members listed here. return { + ...guestNavigationMethods(), id, isDestroyed: mocks.guestIsDestroyedMock, isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts index cc171520ee3..632d5adea01 100644 --- a/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts @@ -48,6 +48,7 @@ vi.mock('../../../identity/browser-process-user-agent', () => ({ import { browserManager } from '../browser-manager' import { + guestNavigationMethods, guestUaMethods, rendererWebContentsId, resetBrowserManagerMocks, @@ -75,6 +76,7 @@ describe('browserManager', () => { it('restores a certificate failure when a retry navigation aborts before committing', () => { const guest = { + ...guestNavigationMethods(), id: 406, isDestroyed: vi.fn(() => false), getType: vi.fn(() => 'webview'), diff --git a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts index f8ca2dc42dc..c09228161d9 100644 --- a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts @@ -32,6 +32,7 @@ vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ import { browserManager } from '../browser-manager' import { createDownloadItem, + guestNavigationMethods, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState @@ -41,6 +42,7 @@ const { webContentsFromIdMock } = browserMocks let didCreateWindow: (window: { webContents: unknown }) => void = () => {} const fakeGuest = (id: number) => ({ + ...guestNavigationMethods(), id, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts index 49f30d15008..2b30397497a 100644 --- a/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts @@ -47,6 +47,7 @@ import { PAGE_INITIATED_TAB_WINDOW_MS } from '../../popups/browser-page-initiated-tab-budget' import { + guestNavigationMethods, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState @@ -79,6 +80,7 @@ describe('browserManager', () => { vi.useFakeTimers() const rendererSendMock = vi.fn() const guest = { + ...guestNavigationMethods(), id: 144, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), @@ -166,6 +168,7 @@ describe('browserManager', () => { it('shares the page-initiated tab budget across the whole opener popup tree', () => { const rendererSendMock = vi.fn() const guest = { + ...guestNavigationMethods(), id: 150, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), @@ -207,6 +210,7 @@ describe('browserManager', () => { const openNamedChild = (index: number): WindowOpenHandler => { const childSetWindowOpenHandlerMock = vi.fn() const child = { + ...guestNavigationMethods(), id: 1500 + index, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest-test-fixture.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest-test-fixture.ts index c830c844a27..de5dbf6209d 100644 --- a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest-test-fixture.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest-test-fixture.ts @@ -1,6 +1,7 @@ import { EventEmitter } from 'node:events' import type { WebContents } from 'electron' import { BrowserManager } from '../browser-manager' +import { guestNavigationMethods } from '../browser-manager-test-harness' const session = { getUserAgent: () => 'Chrome/140.0.0.0' } @@ -31,6 +32,7 @@ export class DestroyedGuestTestContents extends EventEmitter { sendCommand: async () => undefined }) readonly session = session + readonly navigationHistory = guestNavigationMethods().navigationHistory private destroyed = false constructor(readonly id: number) { @@ -54,6 +56,14 @@ export class DestroyedGuestTestContents extends EventEmitter { return 'https://example.test' } + getTitle(): string { + return 'Example' + } + + isLoadingMainFrame(): boolean { + return false + } + getUserAgent(): string { return session.getUserAgent() } diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts index 2385d90a432..121f0797a28 100644 --- a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts @@ -1,3 +1,4 @@ +import { installBrowserGuestMetadata } from '../../navigation/browser-guest-metadata' import { BROWSING_GUEST_POLICY } from './browser-guest-policy-profile' import type { BrowserGuestPolicy } from './browser-guest-policy-profile' import type { PopupOwnerContext } from '../../popups/browser-popup-ownership' @@ -33,6 +34,31 @@ export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestClean const disposeDetachTracking = this.trackDebuggerDetachForCdpOverrides(guest) const disposePopupPolicy = this.installGuestPopupPolicy(guest) const disposeNavigationPolicy = this.installGuestNavigationPolicy(guest) + const disposeMetadata = this.offscreenGuestIds.has(guest.id) + ? () => {} + : installBrowserGuestMetadata({ + guest, + resolveOwner: () => this.tabIdByWebContentsId.get(guest.id), + readLoadError: () => this.loadErrorsByGuestId.get(guest.id) ?? null, + hasCertificateFailure: () => + this.certificateTrustController?.hasFailureForGuest(guest.id) ?? false, + reportErrorPage: () => { + const attemptedUrl = + this.pendingNavigationByGuestId.get(guest.id)?.currentUrl ?? 'about:blank' + const loadError = this.buildLoadError( + -1, + 'This site could not be reached.', + attemptedUrl + ) + this.loadErrorsByGuestId.set(guest.id, loadError) + this.forwardOrQueueGuestLoadFailure(guest.id, loadError) + }, + send: (state) => + this.resolveRendererForBrowserTab(state.browserPageId)?.send( + 'browser:guest-metadata', + state + ) + }) const forwardAudioState = ( event: Electron.Event ): void => { @@ -61,6 +87,7 @@ export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestClean disposeDetachTracking() disposePopupPolicy() disposeNavigationPolicy() + disposeMetadata() disposeDevToolsCloseShortcut() disposeEscapeForwarding() if (!guest.isDestroyed()) { diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts index 35d74509c88..67f5ee5252e 100644 --- a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts @@ -45,6 +45,7 @@ import { browserManager } from '../browser-manager' import { respondToBrowserPagePrompt } from '../../prompts/browser-page-prompts' import { handleBrowserGuestLogin } from '../../prompts/browser-http-auth-prompt' import { + guestNavigationMethods, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState @@ -69,6 +70,7 @@ describe('browserManager page prompt routing', () => { it('asks before a page hands a link to another app, naming the frame that asked', () => { const rendererSendMock = vi.fn() const guest = { + ...guestNavigationMethods(), id: 107, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), @@ -161,6 +163,7 @@ describe('browserManager page prompt routing', () => { it("asks for a new tab's first sign-in once its window registers the tab", async () => { const rendererSendMock = vi.fn() const guest = { + ...guestNavigationMethods(), id: 109, isDestroyed: vi.fn(() => false), isCurrentlyAudible: vi.fn(() => false), diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts index 17fdd5904ef..55906091f9f 100644 --- a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts @@ -1,3 +1,4 @@ +import { publishBrowserGuestMetadata } from '../../navigation/browser-guest-metadata' import { webContents } from 'electron' import { browserDownloadDestinationReservations } from '../../../downloads/browser-download-destination' import { isWorkspaceDocPageId } from '../../../document-preview/doc-preview-guest-policy' @@ -83,6 +84,7 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli this.siteDisplayController?.onGuestRegistered(guest, sessionProfileId ?? null) // Earlier audio events had no page; this report also cues the renderer to re-apply a tab's mute. this.notifyAudioStateChanged(browserTabId, guest.isCurrentlyAudible()) + publishBrowserGuestMetadata(guest) this.setupContextMenu(browserTabId, guest) this.setupGrabShortcut(browserTabId, guest) diff --git a/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-test-fixtures.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-test-fixtures.ts index 0a40c69e6be..98b8840880e 100644 --- a/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-test-fixtures.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-test-fixtures.ts @@ -1,5 +1,6 @@ import { vi } from 'vitest' import type { BrowserManagerMocks } from '../browser-manager-test-harness' +import { guestNavigationMethods } from '../browser-manager-test-harness' export const GUEST_ELECTRON_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) orca/1.0.0 Chrome/134.0.0.0 Electron/30.0.0 Safari/537.36' @@ -76,6 +77,7 @@ export function createViewportGuestFactory( return result } const guest = { + ...guestNavigationMethods(), id, isDestroyed: vi.fn(() => false), isCrashed: vi.fn(() => rendererCrashed), diff --git a/src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.test.ts b/src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.test.ts new file mode 100644 index 00000000000..c73babff06c --- /dev/null +++ b/src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.test.ts @@ -0,0 +1,119 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import type { BrowserGuestMetadata } from '../../../../shared/browser/guest-lifecycle/browser-guest-metadata' +import type { BrowserLoadError } from '../../../../shared/browser-workspace-types' +import { + installBrowserGuestMetadata, + publishBrowserGuestMetadata, + readBrowserGuestMetadata +} from './browser-guest-metadata' + +function fixture() { + let url = 'https://example.test/start' + let title = 'Start' + let loading = false + let back = false + let loadError: BrowserLoadError | null = null + const emitter = new EventEmitter() + const guest = Object.assign(emitter, { + id: 42, + isDestroyed: () => false, + getURL: () => url, + getTitle: () => title, + isLoadingMainFrame: () => loading, + navigationHistory: { canGoBack: () => back, canGoForward: () => false } + }) + const reports: BrowserGuestMetadata[] = [] + const reportErrorPage = vi.fn(() => { + loadError = { + code: -1, + description: 'This site could not be reached.', + validatedUrl: 'https://broken.test/' + } + }) + const dispose = installBrowserGuestMetadata({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: native event emitter with every method read by the metadata projection. + guest: guest as unknown as Electron.WebContents, + resolveOwner: () => 'page', + readLoadError: () => loadError, + hasCertificateFailure: () => false, + reportErrorPage, + send: (state) => reports.push(state) + }) + return { + guest, + reports, + dispose, + reportErrorPage, + navigate: (nextUrl: string, nextTitle: string) => { + url = nextUrl + title = nextTitle + }, + setLoading: (value: boolean) => { + loading = value + }, + setBack: () => { + back = true + } + } +} + +describe('native guest metadata', () => { + it('samples native loading before navigation-start and keeps subsequent title reports current', () => { + const f = fixture() + f.setLoading(true) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies the native metadata methods. + const state = readBrowserGuestMetadata(f.guest as unknown as Electron.WebContents) + expect(state).toMatchObject({ + url: 'https://example.test/start', + loading: true, + navigationRevision: 0 + }) + f.guest.emit('page-title-updated', {}, 'Current title') + expect(f.reports.at(-1)).toMatchObject({ title: 'Current title', loading: true }) + f.setLoading(false) + f.guest.emit('did-stop-loading') + expect(f.reports.at(-1)).toMatchObject({ url: 'https://example.test/start', loading: false }) + f.dispose() + }) + + it('projects same-URL native history and retains it through a failed destination without publishing Chromium internals', () => { + const f = fixture() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies the production publisher native methods. + publishBrowserGuestMetadata(f.guest as unknown as Electron.WebContents) + f.guest.emit('did-start-navigation', {}, 'https://iframe.test/', false, false) + expect(f.reports.at(-1)?.loading).toBe(false) + f.setBack() + f.guest.emit('did-navigate-in-page', {}, 'https://example.test/start', true) + expect(f.reports.at(-1)?.canGoBack).toBe(true) + f.guest.emit('did-start-navigation', {}, 'https://broken.test/', false, true) + f.navigate('chrome-error://chromewebdata/', 'chrome-error://chromewebdata/') + f.guest.emit('page-title-updated', {}, 'chrome-error://chromewebdata/') + // Some builds omit did-fail-load: native settlement must still provide the error. + f.guest.emit('did-stop-loading') + expect(f.reports.at(-1)).toMatchObject({ + url: 'https://example.test/start', + title: 'Start', + loading: false, + canGoBack: true, + errorPage: true, + loadError: { code: -1, validatedUrl: 'https://broken.test/' } + }) + f.dispose() + }) + + it('delivers unchanged-field commits and the stop after an aborted navigation', () => { + const f = fixture() + f.guest.emit('did-start-navigation', {}, 'https://example.test/start', false, true) + f.guest.emit('did-navigate', {}, 'https://example.test/start') + expect(f.reports.at(-1)?.kind).toBe('navigation') + f.setBack() + f.guest.emit('did-navigate-in-page', {}, 'https://example.test/start', true) + f.guest.emit('did-navigate-in-page', {}, 'https://example.test/start', true) + expect(f.reports.slice(-2).map((state) => state.navigationRevision)).toEqual([2, 3]) + f.guest.emit('did-fail-load', {}, -3, 'ERR_ABORTED', 'https://download.test/file.zip', true) + f.guest.emit('did-stop-loading') + expect(f.reports.at(-1)).toMatchObject({ kind: 'stop', loading: false, loadError: null }) + f.dispose() + }) +}) diff --git a/src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.ts b/src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.ts new file mode 100644 index 00000000000..74c5aecdea3 --- /dev/null +++ b/src/main/browser/guest-lifecycle/navigation/browser-guest-metadata.ts @@ -0,0 +1,193 @@ +import type { BrowserLoadError } from '../../../../shared/browser-workspace-types' +import type { BrowserGuestMetadata } from '../../../../shared/browser/guest-lifecycle/browser-guest-metadata' +import { readGuestNavigationState } from './browser-guest-navigation-state' +import { isChromiumInternalErrorUrl } from '../manager/navigation/browser-main-frame-navigation' + +const projections = new WeakMap< + Electron.WebContents, + { + read: () => BrowserGuestMetadata | null + publish: () => void + } +>() + +export function readBrowserGuestMetadata(guest: Electron.WebContents): BrowserGuestMetadata | null { + return projections.get(guest)?.read() ?? null +} + +export function publishBrowserGuestMetadata(guest: Electron.WebContents): void { + projections.get(guest)?.publish() +} + +export function installBrowserGuestMetadata({ + guest, + resolveOwner, + readLoadError, + hasCertificateFailure, + reportErrorPage, + send +}: { + guest: Electron.WebContents + resolveOwner: () => string | undefined + readLoadError: () => BrowserLoadError | null + hasCertificateFailure: () => boolean + reportErrorPage: () => void + send: (state: BrowserGuestMetadata) => void +}): () => void { + let revision = 0 + let navigationRevision = 0 + let committedUrl = isChromiumInternalErrorUrl(guest.getURL()) ? '' : guest.getURL() + let title = committedUrl ? guest.getTitle() : '' + let loading = guest.isLoadingMainFrame() + let previous: BrowserGuestMetadata | null = null + const read = (kind: BrowserGuestMetadata['kind'] = 'snapshot'): BrowserGuestMetadata | null => { + const browserPageId = resolveOwner() + if (!browserPageId || guest.isDestroyed()) { + return null + } + const errorPage = isChromiumInternalErrorUrl(guest.getURL()) + return { + browserPageId, + webContentsId: guest.id, + revision, + navigationRevision, + kind, + url: committedUrl, + title, + loading, + errorPage, + loadError: readLoadError(), + hasCertificateFailure: hasCertificateFailure(), + ...readGuestNavigationState(guest) + } + } + const publish = ( + kind: BrowserGuestMetadata['kind'] = 'snapshot' + ): BrowserGuestMetadata | null => { + const next = read(kind) + if (!next) { + return null + } + if ( + previous && + kind !== 'snapshot' && + kind !== 'stop' && + kind !== 'failure' && + next.browserPageId === previous.browserPageId && + next.url === previous.url && + next.title === previous.title && + next.loading === previous.loading && + next.errorPage === previous.errorPage && + next.loadError === previous.loadError && + next.hasCertificateFailure === previous.hasCertificateFailure && + next.canGoBack === previous.canGoBack && + next.canGoForward === previous.canGoForward && + next.navigationRevision === previous.navigationRevision + ) { + return previous + } + next.revision = ++revision + previous = next + send(next) + return next + } + const onNavigate = (_event: Electron.Event, url: string): void => { + if (isChromiumInternalErrorUrl(url)) { + return + } + committedUrl = url + title = guest.getTitle() + navigationRevision++ + publish('navigation') + } + const onInPage = (_event: Electron.Event, url: string, isMainFrame: boolean): void => { + if (!isMainFrame || isChromiumInternalErrorUrl(url)) { + return + } + committedUrl = url + title = guest.getTitle() + navigationRevision++ + publish('in-page') + } + const onTitle = (_event: Electron.Event, nextTitle: string): void => { + if (isChromiumInternalErrorUrl(guest.getURL())) { + return + } + title = nextTitle + publish('title') + } + const onStart = ( + _event: Electron.Event, + url: string, + isInPlace: boolean, + isMainFrame: boolean + ): void => { + if (!isMainFrame || isInPlace || isChromiumInternalErrorUrl(url)) { + return + } + loading = true + publish('start') + } + const onStartLoading = (): void => { + if (guest.isLoadingMainFrame() && !isChromiumInternalErrorUrl(guest.getURL())) { + loading = true + publish('start') + } + } + const onStop = (): void => { + if ( + isChromiumInternalErrorUrl(guest.getURL()) && + !readLoadError() && + !hasCertificateFailure() + ) { + reportErrorPage() + } + loading = false + publish('stop') + } + const onFail = ( + _event: Electron.Event, + code: number, + _description: string, + _url: string, + isMainFrame: boolean + ): void => { + if (!isMainFrame || code === -3) { + return + } + loading = false + publish('failure') + } + projections.set(guest, { + read: () => { + if (guest.isDestroyed()) { + return null + } + loading = guest.isLoadingMainFrame() + return publish() + }, + publish: () => { + publish() + } + }) + guest.on('did-navigate', onNavigate) + guest.on('did-navigate-in-page', onInPage) + guest.on('page-title-updated', onTitle) + guest.on('did-start-navigation', onStart) + guest.on('did-start-loading', onStartLoading) + guest.on('did-stop-loading', onStop) + guest.on('did-fail-load', onFail) + return () => { + if (previous) { + send({ ...previous, revision: ++revision, kind: 'retired', loading: false }) + } + projections.delete(guest) + guest.off('did-navigate', onNavigate) + guest.off('did-navigate-in-page', onInPage) + guest.off('page-title-updated', onTitle) + guest.off('did-start-navigation', onStart) + guest.off('did-start-loading', onStartLoading) + guest.off('did-stop-loading', onStop) + guest.off('did-fail-load', onFail) + } +} diff --git a/src/main/ipc/browser/browser.ts b/src/main/ipc/browser/browser.ts index a48120f5118..d5791077926 100644 --- a/src/main/ipc/browser/browser.ts +++ b/src/main/ipc/browser/browser.ts @@ -1,3 +1,4 @@ +import { readBrowserGuestMetadata } from '../../browser/guest-lifecycle/navigation/browser-guest-metadata' import { ipcMain, webContents } from 'electron' import { browserCertificateTrustController, @@ -56,6 +57,7 @@ export function registerBrowserHandlers(store: BrowserPasswordsSettingsSource): resetGrabModeState() ipcMain.removeHandler('browser:registerGuest') ipcMain.removeHandler('browser:isGuestRegistered') + ipcMain.removeHandler('browser:getGuestMetadata') ipcMain.removeHandler('browser:repairGuestRegistration') ipcMain.removeHandler('browser:unregisterGuest') ipcMain.removeHandler('browser:activeTabChanged') @@ -113,6 +115,30 @@ export function registerBrowserHandlers(store: BrowserPasswordsSettingsSource): registerGuest(event, args, false) ) + ipcMain.handle( + 'browser:getGuestMetadata', + (event, args: { browserPageId: string; webContentsId: number }) => { + if ( + !isTrustedBrowserRenderer(event.sender) || + typeof args?.webContentsId !== 'number' || + typeof args.browserPageId !== 'string' + ) { + return undefined + } + const guest = webContents.fromId(args.webContentsId) + if (!guest || guest.isDestroyed()) { + return null + } + if ( + guest.hostWebContents?.id !== event.sender.id || + browserManager.getGuestWebContentsId(args.browserPageId) !== guest.id + ) { + return undefined + } + return readBrowserGuestMetadata(guest) + } + ) + // Block SSH webview mounting until its proxy-verified partition is ready. ipcMain.handle( 'browser:prepareSshWorkspacePartition', diff --git a/src/preload/api/browser/browser-api.ts b/src/preload/api/browser/browser-api.ts index d778966efc0..b161b7f910a 100644 --- a/src/preload/api/browser/browser-api.ts +++ b/src/preload/api/browser/browser-api.ts @@ -1,3 +1,4 @@ +import type { BrowserGuestMetadata } from '../../../shared/browser/guest-lifecycle/browser-guest-metadata' import type { BrowserSessionCookieApi } from './browser-session-cookie-api' import type { BrowserDevToolsDockBounds } from '../../../shared/browser/devtools/browser-devtools-dock' import type { BrowserSetAnnotationViewportBridgeArgs } from '../../../shared/browser/annotations/browser-annotation-viewport-bridge' @@ -84,6 +85,11 @@ export type BrowserApi = { request: BrowserClientPageRendererRequest ) => BrowserClientPageRendererOutcome | Promise ) => () => void + getGuestMetadata: (args: { + browserPageId: string + webContentsId: number + }) => Promise + onGuestMetadata: (callback: (state: BrowserGuestMetadata) => void) => () => void registerGuest: (args: { browserPageId: string workspaceId: string diff --git a/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts b/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts index a98e0308250..48d27c8f339 100644 --- a/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts +++ b/src/preload/api/browser/browser-bridge-guest-registration-and-downloads.ts @@ -1,3 +1,4 @@ +import type { BrowserGuestMetadata } from '../../../shared/browser/guest-lifecycle/browser-guest-metadata' import type { BrowserDevToolsDockBounds } from '../../../shared/browser/devtools/browser-devtools-dock' import { ipcRenderer } from 'electron' import type { BrowserViewportOverride } from '../../../shared/browser-workspace-types' @@ -22,6 +23,17 @@ import type { PreloadApi } from '../../api-types' export const browserGuestRegistrationAndDownloadsApi = { onClientPageRendererRequest: browserClientPageRendererRequests.subscribe, readClientHostId: (): string | null => readBrowserClientHostIdArgument(process.argv), + getGuestMetadata: (args: { + browserPageId: string + webContentsId: number + }): Promise => + ipcRenderer.invoke('browser:getGuestMetadata', args), + onGuestMetadata: (callback: (state: BrowserGuestMetadata) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, state: BrowserGuestMetadata): void => + callback(state) + ipcRenderer.on('browser:guest-metadata', listener) + return () => ipcRenderer.removeListener('browser:guest-metadata', listener) + }, registerGuest: (args: { browserPageId: string workspaceId: string diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx index 233528e9a16..ab8480f3ad7 100644 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx +++ b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx @@ -1,5 +1,10 @@ // @vitest-environment happy-dom -import { act, cleanup, render, screen } from '@testing-library/react' +import type { BrowserGuestMetadata } from '../../../../shared/browser/guest-lifecycle/browser-guest-metadata' +import { + cachedBrowserGuestMetadata, + clearBrowserGuestMetadata +} from './host-guest/browser-guest-metadata-cache' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { BrowserCertificateFailure, @@ -22,8 +27,12 @@ vi.mock('./browser-client-page-renderer-installation', () => ({ import { useAppStore } from '@/store' import { TooltipProvider } from '@/components/ui/tooltip' -import { installClientHostedPaneApi } from './client-hosted-browser-pane-test-rig' +import { + installClientHostedPaneApi, + reportClientHostedGuestMetadata +} from './client-hosted-browser-pane-test-rig' import { ClientHostedBrowserPagePane } from './ClientHostedBrowserPagePane' +import { clearBrowserPageDeferredNavigation } from './navigate/browser-page-deferred-navigation' const PLACEMENT = { kind: 'client' as const, @@ -38,6 +47,7 @@ let webview: ReturnType beforeEach(() => { installClientHostedPaneApi() webview = createWebview() + reportClientHostedGuestMetadata({ webContentsId: 42, url: FAILED_URL, title: 'Selfsigned' }) mocks.attach.mockReturnValue({ webview, detach: vi.fn(), @@ -48,11 +58,333 @@ beforeEach(() => { afterEach(() => { cleanup() + clearBrowserPageDeferredNavigation('page-a') vi.clearAllMocks() }) /** Worktree switches unmount chrome while retaining the guest; use the real store because clearing loadError also deletes its certificate record. */ describe('ClientHostedBrowserPagePane failure records across a remount', () => { + it('issues a staged request before native replay or an unanswered initial publication', async () => { + const idleA = reportClientHostedGuestMetadata({ + webContentsId: 42, + url: FAILED_URL, + title: 'Selfsigned', + loading: false + }) + mocks.attach.mockReturnValueOnce(null) + const staged = render() + submitUrl('https://requested.internal/b') + act(() => staged.unmount()) + vi.mocked(window.api.browser.publishClientPageMetadata).mockImplementation( + () => new Promise(() => {}) + ) + vi.mocked(window.api.browser.getGuestMetadata).mockResolvedValueOnce({ + ...idleA, + revision: idleA.revision + 1, + kind: 'snapshot', + loading: true + }) + await act(async () => { + render() + }) + expect(webview.loadURL).toHaveBeenCalledWith('https://requested.internal/b') + expect(storedPage()).toMatchObject({ + url: 'https://requested.internal/b', + title: 'https://requested.internal/b', + loading: true + }) + expect( + vi.mocked(window.api.browser.publishClientPageMetadata).mock.calls[0]?.[0].params + ).toMatchObject({ + url: 'https://requested.internal/b', + title: 'https://requested.internal/b', + loading: true + }) + }) + + it('keeps a requested page through old readback and a successor, then settles Stop at the native document', async () => { + const staleA = reportClientHostedGuestMetadata({ + webContentsId: 42, + url: FAILED_URL, + title: 'Selfsigned', + loading: false + }) + clearBrowserGuestMetadata() + let q1!: (state: BrowserGuestMetadata) => void + let q2!: (state: BrowserGuestMetadata) => void + vi.mocked(window.api.browser.getGuestMetadata) + .mockImplementationOnce( + () => + new Promise((resolve) => { + q1 = resolve + }) + ) + .mockImplementationOnce( + () => + new Promise((resolve) => { + q2 = resolve + }) + ) + let view!: ReturnType + await act(async () => { + view = render() + }) + submitUrl('https://requested.internal/b') + await act(async () => {}) + act(() => view.unmount()) + await act(async () => { + render() + }) + await act(async () => { + q1(staleA) + }) + expect(storedPage()).toMatchObject({ + url: 'https://requested.internal/b', + title: 'https://requested.internal/b', + loading: true + }) + const sample = reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'snapshot', + url: FAILED_URL, + title: 'Outgoing A', + loading: true + }) + await act(async () => { + q2(sample) + }) + act(() => + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'title', + title: 'Outgoing A tick', + loading: true + }) + ) + expect(storedPage()).toMatchObject({ + url: 'https://requested.internal/b', + title: 'https://requested.internal/b', + loading: true + }) + expect( + vi.mocked(window.api.browser.publishClientPageMetadata).mock.lastCall?.[0].params + ).toMatchObject({ + url: 'https://requested.internal/b', + title: 'https://requested.internal/b', + loading: true + }) + expect(cachedBrowserGuestMetadata(webview)?.url).toBe('https://selfsigned.internal/') + await act(async () => + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'stop', + title: 'Selfsigned', + loading: false + }) + ) + expect(storedPage()).toMatchObject({ + url: 'https://selfsigned.internal/', + title: 'Selfsigned', + loading: false + }) + }) + + it('revalidates a healthy Stop after a command read failed', async () => { + render() + vi.mocked(window.api.browser.getGuestMetadata).mockRejectedValueOnce( + new Error('metadata read failed') + ) + submitUrl('https://requested.internal/b') + await act(async () => {}) + expect(storedPage()).toMatchObject({ url: 'https://requested.internal/b', loading: true }) + await act(async () => + reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'stop', loading: false }) + ) + expect(storedPage()).toMatchObject({ + url: 'https://selfsigned.internal/', + title: 'Selfsigned', + loading: false + }) + }) + + it('adopts an already committed page on same-guest readiness after its read failed', async () => { + render() + let reject!: (error: Error) => void + vi.mocked(window.api.browser.getGuestMetadata).mockImplementationOnce( + () => + new Promise((_resolve, fail) => { + reject = fail + }) + ) + submitUrl('https://requested.internal/b') + await act(async () => {}) + act(() => + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'navigation', + url: 'https://requested.internal/b', + title: 'Committed B', + loading: true + }) + ) + await act(async () => { + reject(new Error('metadata read failed')) + }) + await act(async () => { + webview.dispatchEvent(new Event('dom-ready')) + }) + expect(storedPage()).toMatchObject({ + url: 'https://requested.internal/b', + title: 'Committed B', + loading: true + }) + }) + + it('shows a hidden committed document and its live title while another load is pending', async () => { + let resolve!: (state: BrowserGuestMetadata) => void + const view = render() + vi.mocked(window.api.browser.getGuestMetadata).mockImplementationOnce( + () => + new Promise((done) => { + resolve = done + }) + ) + submitUrl('https://requested.internal/b') + await act(async () => {}) + act(() => view.unmount()) + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'navigation', + url: 'https://current.internal/c', + title: 'Current C', + loading: true + }) + const sample = reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'snapshot', + loading: true + }) + await act(async () => { + resolve(sample) + }) + expect(storedPage().loading).toBe(true) + render() + expect(storedPage()).toMatchObject({ + url: 'https://current.internal/c', + title: 'Current C', + loading: true + }) + act(() => + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'title', + title: 'Current C live', + loading: true + }) + ) + expect(storedPage()).toMatchObject({ + url: 'https://current.internal/c', + title: 'Current C live', + loading: true + }) + }) + + it('keeps a useful local and published identity when the current document clears its title', async () => { + await act(async () => { + render() + }) + await act(async () => { + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'title', + title: '' + }) + }) + expect(storedPage()).toMatchObject({ + url: 'https://selfsigned.internal/', + title: 'https://selfsigned.internal/' + }) + expect( + vi.mocked(window.api.browser.publishClientPageMetadata).mock.calls.at(-1)?.[0].params + ).toMatchObject({ + url: 'https://selfsigned.internal/', + title: 'https://selfsigned.internal/' + }) + }) + + it('retains the saved title until a first committed document exists, including a failed first load', () => { + reportClientHostedGuestMetadata({ + webContentsId: 42, + navigationRevision: 0, + url: '', + title: '', + kind: 'snapshot', + loading: true + }) + render() + expect(storedPage().title).toBe('Selfsigned') + expect(storedPage().loading).toBe(true) + act(() => reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'start', loading: true })) + expect(storedPage().title).toBe('Selfsigned') + act(() => reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'stop', loading: false })) + expect(storedPage().url).toBe(FAILED_URL) + expect(storedPage().title).toBe('Selfsigned') + act(() => + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'failure', + loading: false, + loadError: { code: -105, description: 'ERR_NAME_NOT_RESOLVED', validatedUrl: FAILED_URL } + }) + ) + expect(storedPage().title).toBe('Selfsigned') + }) + + it('reconciles a hidden commit on settlement even when metadata publication never answers', () => { + vi.mocked(window.api.browser.publishClientPageMetadata).mockImplementation( + () => new Promise(() => {}) + ) + const view = render() + act(() => view.unmount()) + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'navigation', + url: 'https://example.internal/next', + loading: true, + navigationRevision: 2 + }) + render() + act(() => reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'stop', loading: false })) + expect(storedPage().url).toBe('https://example.internal/next') + expect(storedPage().loading).toBe(false) + expect(storedPage().loadError).toBeNull() + }) + + it('clears a standing failure after a successful same-URL reload', () => { + render() + failLoad() + act(() => + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'start', + loading: true, + loadError: null, + hasCertificateFailure: false + }) + ) + expect(storedPage().loadError?.validatedUrl).toBe(FAILED_URL) + act(() => + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'navigation', + navigationRevision: 2 + }) + ) + expect(storedPage().loadError).toBeNull() + expect(useAppStore.getState().browserCertificateFailuresByPageId['page-a']).toBeUndefined() + expect(screen.queryByRole('heading', { name: "Connection isn't secure" })).toBeNull() + }) + it('keeps the failure and the certificate record when the guest still sits on the failed page', () => { const view = render() failLoad() @@ -73,7 +405,7 @@ describe('ClientHostedBrowserPagePane failure records across a remount', () => { act(() => view.unmount()) // Failed guests report chrome-error://chromewebdata/, which matches neither recorded URL. - webview.getURL.mockReturnValue('chrome-error://chromewebdata/') + reportClientHostedGuestMetadata({ webContentsId: 42, errorPage: true }) render() expect(storedPage().loadError?.validatedUrl).toBe(FAILED_URL) @@ -87,7 +419,14 @@ describe('ClientHostedBrowserPagePane failure records across a remount', () => { act(() => view.unmount()) // A navigation while unmounted is observable only through remount sync. - webview.getURL.mockReturnValue('https://example.internal/recovered') + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'navigation', + url: 'https://example.internal/recovered', + loadError: null, + hasCertificateFailure: false, + errorPage: false + }) render() expect(storedPage().loadError).toBeNull() @@ -131,6 +470,13 @@ function failLoad(): void { }) act(() => { useAppStore.getState().setBrowserPageCertificateFailure('page-a', certificateFailure()) + reportClientHostedGuestMetadata({ + webContentsId: 42, + kind: 'failure', + loading: false, + hasCertificateFailure: true, + loadError: { code: -202, description: 'ERR_CERT_AUTHORITY_INVALID', validatedUrl: FAILED_URL } + }) }) } @@ -218,3 +564,13 @@ function createWebview(): Electron.WebviewTag & { getURL: ReturnType ({ import { useAppStore } from '@/store' import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' import { requestBrowserFocus } from './host-guest/browser-focus' -import { installClientHostedPaneApi } from './client-hosted-browser-pane-test-rig' +import { + installClientHostedPaneApi, + reportClientHostedGuestMetadata +} from './client-hosted-browser-pane-test-rig' import { ClientHostedBrowserPagePane } from './ClientHostedBrowserPagePane' -function render(ui: React.ReactElement) { +function render(ui: React.ReactElement<{ browserTab: BrowserPage }>) { + const current = ui.props.browserTab + useAppStore.setState({ browserPagesByWorkspace: { [current.workspaceId]: [current] } }) return renderWithProviders(ui, { wrapper: TooltipProvider }) } @@ -156,7 +161,9 @@ describe('ClientHostedBrowserPagePane', () => { expect(onUpdatePageState).toHaveBeenCalledWith('page-a', { loading: false, loadError }) // Why: did-stop-loading follows did-fail-load and must not wipe the failure. onUpdatePageState.mockClear() - act(() => webview.dispatchEvent(new Event('did-stop-loading'))) + act(() => + reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'stop', loadError, loading: false }) + ) expect(onUpdatePageState).toHaveBeenCalledWith('page-a', expect.objectContaining({ loadError })) view.rerender( @@ -178,6 +185,87 @@ describe('ClientHostedBrowserPagePane', () => { expect(webview.src).toBe(normalizeBrowserNavigationUrl(loadError.validatedUrl)) }) + it('keeps Find open across subframe settlement and closes it only on a full commit', () => { + const { webview } = createWebview() + mocks.attach.mockReturnValue(retainedAttachment(webview)) + let openFind = () => {} + installClientHostedPaneApi({ + ui: { + onFindInBrowserPage: (_target, listener) => { + openFind = listener + return () => {} + } + } + }) + reportClientHostedGuestMetadata({ + webContentsId: 7, + url: 'https://example.internal/', + title: 'Example' + }) + render( + + ) + act(() => openFind()) + expect(screen.getByPlaceholderText('Find in page...')).not.toBeNull() + act(() => reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'stop' })) + expect(screen.getByPlaceholderText('Find in page...')).not.toBeNull() + act(() => webview.dispatchEvent(new Event('did-navigate'))) + expect(screen.queryByPlaceholderText('Find in page...')).toBeNull() + }) + + it('restores the committed address after an attempted navigation is stopped', async () => { + const { webview } = createWebview() + reportClientHostedGuestMetadata({ + webContentsId: 7, + url: 'https://example.internal/a', + title: 'Example' + }) + mocks.attach.mockReturnValue(retainedAttachment(webview)) + const onSetUrl = vi.fn() + const onUpdatePageState = vi.fn() + render( + + ) + act(() => mocks.addressBar.current?.onNavigate('https://example.internal/b')) + act(() => reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'start', loading: true })) + expect(screen.getByLabelText('Address').value).toBe( + 'https://example.internal/b' + ) + act(() => screen.getByLabelText('Address').blur()) + onSetUrl.mockClear() + await act(async () => + reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'stop', loading: false }) + ) + expect(screen.getByLabelText('Address').value).toBe( + 'https://example.internal/a' + ) + expect(onSetUrl).not.toHaveBeenCalled() + expect(onUpdatePageState).toHaveBeenCalledWith( + 'page-a', + expect.objectContaining({ loading: false, loadError: null }) + ) + }) + it('offers Reopen without a stale load-failure surface until the restored page attaches', () => { mocks.restoredPageUnrecovered = true const browserTab = { @@ -425,15 +513,18 @@ function createWebview(): { reload: vi.fn(), loadURL: vi.fn(async () => {}) }) + reportClientHostedGuestMetadata({ webContentsId: 7, url, title }) return { webview, focus, blur, setUrl: (nextUrl) => { url = nextUrl + reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'navigation', url }) }, setTitle: (nextTitle) => { title = nextTitle + reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'title', title }) } } } diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx index e863ff5e03c..ccbf8b8594f 100644 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx +++ b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx @@ -1,14 +1,16 @@ +import type { BrowserGuestMetadata } from '../../../../shared/browser/guest-lifecycle/browser-guest-metadata' import { useCallback, useEffectEvent, useLayoutEffect, useRef, useState } from 'react' import { useBrowserAgentCursor } from './agent-cursor/use-browser-agent-cursor' import { BrowserPageFeedbackBadge } from './assemble-chrome/browser-page-feedback-badge' import { BrowserLinkStatusBubble } from './assemble-chrome/browser-link-status-bubble' import { useAppStore } from '@/store' -import type { BrowserLoadError } from '../../../../shared/browser-workspace-types' +import { createBrowserClientPageLoadFailureHandler } from './browser-client-page-guest-metadata' import { - readBrowserClientPageGuestMetadataIfLive, - createBrowserClientPageLoadFailureHandler, - bindBrowserClientPageGuestEvents -} from './browser-client-page-guest-metadata' + issueBrowserGuestNavigation, + browserGuestPreservesRequestedDocument, + subscribeBrowserGuestMetadata +} from './host-guest/browser-guest-metadata-cache' +import { redactKagiSessionToken } from '../../../../shared/browser-url' import { forgetBrowserClientPageMetadataReports, startBrowserClientPageMetadataPublisher @@ -32,7 +34,6 @@ import { useWebviewGuestFocus } from './assemble-chrome/browser-page-guest-focus import { RemoteRuntimeEgressIndicator } from './assemble-chrome/browser-egress-indicator' import { useBrowserPageWebviewShortcuts } from './host-guest/use-browser-page-webview-shortcuts' import { useBrowserPageZoomFeedback } from './host-guest/use-browser-page-zoom-feedback' -import { isPageDocumentNavigationStart } from './host-guest/browser-page-webview-navigation-handlers' import { ClientHostedBrowserLoadFailure } from './client-hosted-browser-load-failure' import { useClientHostedPageUrlSubmission } from './navigate/use-client-hosted-page-url-submission' import '@/lib/browser/documents/file-preview' @@ -40,7 +41,6 @@ import { convertBrowserPageToWorkspaceDoc } from '@/lib/browser/documents/file-p import { isBlankBrowserUrl } from '@/lib/browser/palette/browser-palette-search' import { BrowserNewTabPage } from './new-tab/BrowserNewTabPage' import { useBrowserPageReloadActions } from './navigate/use-browser-page-reload-actions' -import { resolveActiveBrowserLoadFailure } from './navigate/browser-load-failure-for-url' import { consumeBrowserPageDeferredNavigation } from './navigate/browser-page-deferred-navigation' import { getBrowserDisplayTitle, toDisplayUrl } from './describe-page/browser-page-url-display' import type { ClientHostedBrowserPagePaneProps } from './describe-page/browser-page-types' @@ -64,7 +64,7 @@ export function ClientHostedBrowserPagePane({ const webviewRef = useRef(null) const addressBarInputRef = useRef(null) // Seed retained failures from the page: a fresh null on remount would clear both the error and its certificate record. - const activeLoadFailureRef = useRef(browserTab.loadError ?? null) + const loadFailureRef = useRef(browserTab.loadError ?? null) const onUpdatePageStateRef = useRef(onUpdatePageState) const isActiveRef = useRef(isActive) const [attachmentError, setAttachmentError] = useState(null) @@ -117,7 +117,6 @@ export function ClientHostedBrowserPagePane({ useBrowserClientHostedPopupNotices(browserTab.id) useBrowserClientHostedPermissionNotices(browserTab.id) - // Only consume the one-time tour after placement and attachment make its controls usable. useClientHostedBrowserIntroTour(isActive && !attachmentError && placement !== null) useBrowserPageFindShortcuts({ ...shortcutOwner, setFindOpen }) useBrowserPageWebviewShortcuts({ @@ -132,11 +131,17 @@ export function ClientHostedBrowserPagePane({ browserTabId: browserTab.id, worktreeId, webviewRef, - activeLoadFailureRef, + activeLoadFailureRef: loadFailureRef, onUpdatePageState, + onSetUrl, setAddressBarValue }) const runDeferredNavigation = useEffectEvent(navigateToUrl) + const readCurrentPage = useEffectEvent(() => + useAppStore + .getState() + .browserPagesByWorkspace[workspaceId]?.find((page) => page.id === browserTab.id) + ) // The guest lives in a body-level host that paints above the pane, so the cursor joins it there. const getAgentCursorHost = useCallback( () => webviewRef.current?.parentElement ?? null, @@ -170,7 +175,7 @@ export function ClientHostedBrowserPagePane({ return } const webview = attachment.webview - // Guest loss uses the existing recovery notice and clears pending loading state. + let guestAvailable = true let releaseGuest = (): void => attachment.detach() const guestLoss = watchBrowserClientPageGuestLoss({ webview, @@ -178,16 +183,11 @@ export function ClientHostedBrowserPagePane({ browserPageId: browserTab.id, pageHostGeneration, onLost: () => { + guestAvailable = false releaseGuest() retryGuestRecoveryRef.current() } }) - // Main can destroy the guest while its tag still holds the stale id. - const attachedMetadata = readBrowserClientPageGuestMetadataIfLive(webview) - if (!attachedMetadata) { - guestLoss.lose('unreadable') - return guestLoss.dispose() - } const publisher = startBrowserClientPageMetadataPublisher({ browserPageId: browserTab.id, environmentId: runtimeEnvironmentId, @@ -201,76 +201,99 @@ export function ClientHostedBrowserPagePane({ }) webviewRef.current = webview setAttachmentError(null) - // Reconcile restored failures once; failed navigations this session may never commit a URL. - activeLoadFailureRef.current = resolveActiveBrowserLoadFailure( - activeLoadFailureRef.current, - attachedMetadata.url - ) - const syncNavigation = (event?: Event): void => { - const eventUrl = (event as (Event & { url?: string }) | undefined)?.url - const metadata = readBrowserClientPageGuestMetadataIfLive(webview, eventUrl) - if (!metadata) { + const receiveMetadata = (state: BrowserGuestMetadata | null): void => { + if (!state || state.kind === 'retired') { guestLoss.lose('unreadable') return } - // A commit is a successful load; did-stop-loading must preserve the preceding did-fail-load overlay. - if (event?.type === 'did-navigate') { - activeLoadFailureRef.current = null - setFindOpen(false) + const pending = readCurrentPage() + if (!pending) { + guestAvailable = false + releaseGuest() + return } - const activeLoadFailure = activeLoadFailureRef.current - // URL writes clear certificate challenges, so preserve them while a failure stands. - if (!activeLoadFailure) { - setUrlFromGuest(browserTab.id, metadata.url, { preserveLoadError: true }) + const url = redactKagiSessionToken(state.url) + const metadata = { + url, + title: + state.title || (url && !isBlankBrowserUrl(url) ? getBrowserDisplayTitle('', url) : url), + loading: state.loading, + canGoBack: state.canGoBack, + canGoForward: state.canGoForward + } + const validDocument = + Boolean(state.url) && !state.errorPage && !state.loadError && !state.hasCertificateFailure + const presentDocument = + validDocument && !browserGuestPreservesRequestedDocument(webview, state.url, pending.url) + if ( + state.kind === 'navigation' || + ((state.kind === 'stop' || (state.kind === 'snapshot' && !state.loading)) && validDocument) + ) { + loadFailureRef.current = null + } + if (state.loadError) { + loadFailureRef.current = state.loadError + } + const activeLoadFailure = loadFailureRef.current + const observeUrl = + presentDocument && + !activeLoadFailure && + (state.kind === 'navigation' || + state.kind === 'in-page' || + state.kind === 'stop' || + state.kind === 'snapshot') + if (observeUrl) { + if (pending.url !== metadata.url) { + setUrlFromGuest(browserTab.id, metadata.url, { preserveLoadError: true }) + } + setAddressBarValueFromPage(toDisplayUrl(metadata.url)) } updatePageStateFromGuest(browserTab.id, { - title: metadata.title, + ...(presentDocument && !activeLoadFailure ? { title: metadata.title } : {}), loading: metadata.loading, canGoBack: metadata.canGoBack, canGoForward: metadata.canGoForward, loadError: activeLoadFailure }) - publisher.publish(metadata) - // Address-bar suggestions use the client's URL history, including client-hosted pages. - recordHistoryFromGuest(metadata.url, getBrowserDisplayTitle(metadata.title, metadata.url)) - setAddressBarValueFromPage(toDisplayUrl(metadata.url)) - } - const onStart = (event: Electron.DidStartNavigationEvent): void => { - if (!isPageDocumentNavigationStart(event)) { + const current = readCurrentPage() + if (!current) { return } - // Why: a standing failure (and its auto-retry) stays up until a load commits or fails anew. - updatePageStateFromGuest(browserTab.id, { loading: true }) - const startMetadata = readBrowserClientPageGuestMetadataIfLive(webview, undefined, true) - if (!startMetadata) { - guestLoss.lose('unreadable') - return + publisher.publish({ + ...metadata, + ...(presentDocument && !activeLoadFailure ? {} : { url: current.url, title: current.title }) + }) + if (observeUrl || (state.kind === 'title' && presentDocument && !activeLoadFailure)) { + recordHistoryFromGuest(metadata.url, getBrowserDisplayTitle(metadata.title, metadata.url)) } - publisher.publish(startMetadata) } - const onFailLoad = createBrowserClientPageLoadFailureHandler( - webview, - () => guestLoss.lose('unreadable'), - (loadError) => { - activeLoadFailureRef.current = loadError - updatePageStateFromGuest(browserTab.id, { loading: false, loadError }) - } - ) - const unbind = bindBrowserClientPageGuestEvents(webview, onStart, syncNavigation, onFailLoad) + const onNavigate = (): void => setFindOpen(false) + webview.addEventListener('did-navigate', onNavigate) + const onFailLoad = createBrowserClientPageLoadFailureHandler(webview, (loadError) => { + loadFailureRef.current = loadError + updatePageStateFromGuest(browserTab.id, { loading: false, loadError }) + }) + webview.addEventListener('did-fail-load', onFailLoad) + let unsubscribeMetadata = (): void => {} const cleanupGuest = (): void => { - unbind() + unsubscribeMetadata() + webview.removeEventListener('did-fail-load', onFailLoad) + webview.removeEventListener('did-navigate', onNavigate) guestLoss.dispose() publisher.dispose() forgetBrowserClientPageMetadataReports(browserTab.id) attachment.detach() } releaseGuest = cleanupGuest - syncNavigation() - // Resume navigation submitted before host adoption. const deferredUrl = consumeBrowserPageDeferredNavigation(browserTab.id) if (deferredUrl) { runDeferredNavigation(deferredUrl) } + unsubscribeMetadata = subscribeBrowserGuestMetadata(browserTab.id, webview, receiveMetadata) + if (!guestAvailable) { + cleanupGuest() + return cleanupGuest + } return cleanupGuest }, [ browserTab.id, @@ -316,8 +339,10 @@ export function ClientHostedBrowserPagePane({ controls={{ canGoBack: browserTab.canGoBack, canGoForward: browserTab.canGoForward, - goBack: () => webviewRef.current?.goBack(), - goForward: () => webviewRef.current?.goForward(), + goBack: () => + issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goBack()), + goForward: () => + issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goForward()), reload: () => reload.runReloadTrigger('button'), navigate: navigateToUrl }} @@ -376,7 +401,7 @@ export function ClientHostedBrowserPagePane({ ) : isBlankBrowserUrl(browserTab.url) ? ( diff --git a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx b/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx index 207a94ae24c..b01733c1135 100644 --- a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx +++ b/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx @@ -25,12 +25,12 @@ export function reopenOnServerCaveat(t: Translate = translate): string { export function ReopenBrowserPageOnServerButton({ environmentId, worktreeId, - lastCommittedUrl, + reopenUrl, className }: { environmentId: string worktreeId: string - lastCommittedUrl: string | null | undefined + reopenUrl: string | null | undefined className?: string }): React.JSX.Element { const t = useTranslate() @@ -54,7 +54,7 @@ export function ReopenBrowserPageOnServerButton({ pendingTimerRef.current = null setShowPending(true) }, REOPEN_PENDING_FEEDBACK_DELAY_MS) - void reopenBrowserPageOnServer({ environmentId, worktreeId, lastCommittedUrl }) + void reopenBrowserPageOnServer({ environmentId, worktreeId, reopenUrl }) .then((created) => { if (!created) { toast.error( @@ -73,7 +73,7 @@ export function ReopenBrowserPageOnServerButton({ setShowPending(false) setPending(false) }) - }, [clearPendingTimer, environmentId, lastCommittedUrl, worktreeId]) + }, [clearPendingTimer, environmentId, reopenUrl, worktreeId]) return ( - - ) -})) - -const { default: WorkspaceKanbanLaneGrid } = await import('./WorkspaceKanbanLaneGrid') -await import('./workspace-kanban-lane-range') - -const STATUSES = Array.from({ length: 21 }, (_, index) => ({ - id: `state-${String(index + 1).padStart(2, '0')}`, - label: `State ${index + 1}` -})) -const REPO_MAP = new Map() - -function makeGrid(activeWorktreeIdentity: string | null = null): React.JSX.Element { - return ( - {}} - onDragLeave={() => {}} - onDrop={() => {}} - onActivate={() => {}} - onSelectionGesture={() => false} - onContextMenuSelect={() => []} - onCreateWorktree={() => {}} - onColumnResizeStart={() => {}} - onColumnResizeKeyDown={() => {}} - /> - ) -} - -function renderGrid(): ReturnType { - return render(makeGrid()) -} - -function mountedStatusIds(container: HTMLElement): string[] { - return Array.from(container.querySelectorAll('[data-workspace-status]')).map( - (lane) => lane.dataset.workspaceStatus ?? '' - ) -} - -beforeEach(() => { - animationFrames.clear() - nextAnimationFrameId = 1 - vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { - const id = nextAnimationFrameId - nextAnimationFrameId += 1 - animationFrames.set(id, callback) - return id - }) - vi.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => { - animationFrames.delete(id) - }) -}) - -afterEach(() => { - virtualWindow.startIndex = 0 - cleanup() - vi.restoreAllMocks() -}) - -describe('WorkspaceKanbanLaneGrid', () => { - it('keeps one focused lane mounted without unbounding the virtual window', () => { - const rendered = renderGrid() - fireEvent.focus(rendered.getByRole('button', { name: 'State 1' })) - - virtualWindow.startIndex = 17 - rendered.rerender(makeGrid()) - - expect(mountedStatusIds(rendered.container)).toEqual([ - 'state-01', - 'state-17', - 'state-18', - 'state-19', - 'state-20', - 'state-21' - ]) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/host-section-reveal.test.tsx b/src/renderer/src/components/sidebar/worktree-list/grouping/host-section-reveal.test.tsx deleted file mode 100644 index aea46b0141d..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/host-section-reveal.test.tsx +++ /dev/null @@ -1,151 +0,0 @@ -// @vitest-environment happy-dom -import { createRef } from 'react' -import { cleanup, renderHook } from '@testing-library/react' -import { Virtualizer } from '@tanstack/react-virtual' -import { afterEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import { makeRepo, makeWorktree } from '../listing/worktree-list-lineage-card-test-fixtures' -import { useSidebarSectionRows } from '../listing/use-section-rows' -import { expandGroupsForWorktreeReveal } from '../navigation/pending-reveal-inputs' -import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' -import type { ExecutionHostId } from '../../../../../../shared/execution-host' -import type { WorktreeGroupBy } from '../../../../../../shared/sidebar-list/row-types' -import type { Worktree } from '../../../../../../shared/worktree/types' -import { cloneDefaultWorkspaceStatuses } from '../../../../../../shared/workspace-statuses' - -afterEach(cleanup) -const projectGrouping = { projects: [], projectHostSetups: [] } -const settings = useAppStore.getState().settings -const workspaceStatuses = cloneDefaultWorkspaceStatuses() -const virtualizer = new Virtualizer({ - count: 0, - getScrollElement: () => null, - estimateSize: () => 40, - scrollToFn: vi.fn(), - observeElementRect: vi.fn(), - observeElementOffset: vi.fn() -}) - -function setup(hostId: ExecutionHostId) { - const localRepo = makeRepo() - const remoteRepo = { ...localRepo, id: 'remote-repo', executionHostId: hostId } - const repoMap = new Map([ - [localRepo.id, localRepo], - [remoteRepo.id, remoteRepo] - ]) - const local = { - ...makeWorktree({ - id: 'local', - displayName: 'Local', - branch: 'local', - sortOrder: 0, - instanceId: 'local-instance' - }), - hostId: 'local' as const - } - const remote = { - ...local, - id: 'remote', - instanceId: 'remote-instance', - repoId: remoteRepo.id, - hostId - } - return { localRepo, remoteRepo, repoMap, local, remote } -} - -function sections( - hostId: ExecutionHostId, - groupBy: WorktreeGroupBy, - worktrees: Worktree[], - collapsedGroups: Set, - lineageById: Record = {}, - visibleWorkspaceHostIds: ExecutionHostId[] | null = ['local', hostId] -) { - const { localRepo, remoteRepo, repoMap } = setup(hostId) - return renderHook(() => - useSidebarSectionRows({ - groupBy, - sortBy: 'smart', - projectOrderBy: 'manual', - pinnedDisplayPolicy: 'single-location', - defaultHostId: 'local', - worktrees, - repos: [localRepo, remoteRepo], - repoMap, - worktreeMap: new Map(worktrees.map((worktree) => [worktree.id, worktree])), - worktreeLineageById: lineageById, - prCache: null, - settings, - workspaceStatuses, - effectiveCollapsedGroups: collapsedGroups, - projectGrouping, - visibleReposForRows: [localRepo, remoteRepo], - visibleProjectGroupsForRows: [], - visibleFolderWorkspacesForRows: [], - importedWorktreesByRepo: new Map(), - newExternalWorktreesInboxByRepo: new Map(), - filterRepoIds: [], - visibleWorkspaceHostIds, - workspaceHostScope: 'all' - }) - ).result.current.sectionRows -} - -for (const hostId of ['ssh:builder', 'runtime:builder'] as const) { - for (const [groupBy, laneKey] of [ - ['none', 'all'], - ['workspace-status', 'workspace-status:in-progress'], - ['pr-status', 'pr:in-progress'] - ] as const) { - it(`${hostId} ${groupBy}: revealing remote should preserve collapsed local lane`, () => { - const { local, remote, repoMap } = setup(hostId) - const worktrees = [local, remote] - const collapsedGroups = new Set([laneKey, `${laneKey}:host:${hostId}`]) - const rows = sections(hostId, groupBy, worktrees, collapsedGroups) - expect(rows.filter((row) => row.type === 'header' && row.key === laneKey)).toHaveLength(2) - expect(rows.filter((row) => row.type === 'item')).toHaveLength(0) - expandGroupsForWorktreeReveal( - { - pendingRevealWorktree: null, - pendingRevealSidebarRow: null, - clearPendingRevealWorktreeId: vi.fn(), - clearPendingRevealSidebarRow: vi.fn(), - agentSendTargetWorktreeId: null, - renderRows: rows, - virtualizer, - scrollRef: createRef(), - worktrees, - folderWorkspaces: [], - repoMap, - worktreeMap: new Map(worktrees.map((worktree) => [worktree.id, worktree])), - worktreeLineageById: {}, - collapsedGroups, - toggleGroup: (key) => { - if (collapsedGroups.has(key)) { - collapsedGroups.delete(key) - } else { - collapsedGroups.add(key) - } - }, - groupBy, - pinnedDisplayPolicy: 'single-location', - defaultHostId: 'local', - prCache: null, - workspaceStatuses, - settings, - projectGroups: [], - projectGrouping, - flashRevealedRow: vi.fn(), - markRevealScroll: vi.fn(), - schedulePendingRevealFrame: vi.fn(), - cancelPendingRevealFrames: vi.fn() - }, - remote.id, - hostId - ) - const after = sections(hostId, groupBy, worktrees, collapsedGroups) - expect(after.some((row) => row.type === 'item' && row.worktree.id === remote.id)).toBe(true) - expect(after.some((row) => row.type === 'item' && row.worktree.id === local.id)).toBe(false) - }) - } -} diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/pinned-section-worktrees.test.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/pinned-section-worktrees.test.ts index 8154091bb3f..fd38f80c780 100644 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/pinned-section-worktrees.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/pinned-section-worktrees.test.ts @@ -1,10 +1,7 @@ import { describe, expect, it } from 'vitest' import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' import type { Worktree } from '../../../../../../shared/worktree/types' -import { - getPinnedSectionWorktrees, - isPinnedSectionWorktree -} from '../../../../../../shared/sidebar-list/pinned-section-worktrees' +import { getPinnedSectionWorktrees } from '../../../../../../shared/sidebar-list/pinned-section-worktrees' import { worktree, repoMap } from './worktree-list-groups-test-fixtures' import { buildRows } from './build-rows.test-fixture' @@ -124,24 +121,3 @@ describe('getPinnedSectionWorktrees', () => { expect(rows.filter((row) => row.type === 'item')).toHaveLength(depth) }) }) - -describe('isPinnedSectionWorktree', () => { - const parent = makeWorktree('parent', { isPinned: true }) - const child = makeWorktree('child') - const lineageById = { [child.id]: makeLineage(child, parent) } - const worktreeMap = new Map([ - [parent.id, parent], - [child.id, child] - ]) - - it('treats an unpinned child of a visible pinned parent as pinned-section membership', () => { - expect(isPinnedSectionWorktree(child, [parent, child], lineageById, worktreeMap)).toBe(true) - }) - - it('does not treat an unrelated unpinned workspace as pinned-section membership', () => { - const other = makeWorktree('other') - expect(isPinnedSectionWorktree(other, [parent, child, other], lineageById, worktreeMap)).toBe( - false - ) - }) -}) diff --git a/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-picker-contract.test.ts b/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-picker-contract.test.ts deleted file mode 100644 index fe3033628ac..00000000000 --- a/src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-picker-contract.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { - useAgentPickerSetup, - useAgentPickerDraftScope -} from '../../../../components/agent/agent-launch-picker-drafts' -// @vitest-environment happy-dom -import { afterEach, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render } from '@testing-library/react' -import { createElement } from 'react' -import { AgentLaunchSetupPanel } from '../../../../components/agent/AgentLaunchSetupPanel' -import { TooltipProvider } from '../../../../components/ui/tooltip' -import { useAgentLaunchPickerInventorySource } from '../../../../components/agent/use-agent-launch-picker-inventory' -import { useAgentPickerInventoryEntries } from '../../../../components/agent/agent-launch-picker-acquisition' -import type { NewTabAgentMenuModel } from '../../../../components/tab-bar/new-tab-agent-menu-model' - -import { - store, - mockCreateWebRuntimeSessionTerminal, - mockIsWebRuntimeSessionActive -} from './launch-agent-in-new-tab-test-fixture' - -vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) -afterEach(() => { - cleanup() - vi.restoreAllMocks() -}) -const inventory = vi.hoisted(() => ({ settings: vi.fn(), legacy: vi.fn(), session: vi.fn() })) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: async (...args: unknown[]) => - args[1] === 'settings.getAgentLaunch' - ? { settings: await inventory.settings(...args) } - : inventory.legacy(...args) -})) -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ - runtimeEnvironmentSupportsCapability: async () => true, - runtimeEnvironmentSupportsCapabilities: async () => [false, false] -})) -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: inventory.session -})) - -it('keeps pristine, edited and reopened historical-host picker launches free of desktop defaults', async () => { - const operation = - await import('@/runtime/hosted-terminals/creation/web-runtime-terminal-create-operation') - vi.spyOn(operation, 'createWebRuntimeSessionTerminalResult').mockImplementation( - async ({ legacyAgentLaunch, ...request }) => ({ - outcome: await mockCreateWebRuntimeSessionTerminal({ - ...request, - ...(request.preparedAgentCommand ? await legacyAgentLaunch?.() : {}) - }) - }) - ) - const { useTabAgentMenuLaunch } = await import('../../../../components/tab-bar/QuickLaunchButton') - const snapshot = { - defaultTuiAgent: 'claude', - disabledTuiAgents: [], - agentCmdOverrides: { claude: '/host/claude' }, - agentDefaultArgs: { claude: '--permission-mode auto' }, - environmentNames: {}, - permissionMode: 'mixed' as const - } - Object.assign(store.settings, { - agentCmdOverrides: { claude: '/desktop/claude' }, - agentDefaultArgs: { claude: '--model desktop-only-qa' }, - agentLaunchChoices: { claude: { model: 'desktop-only-qa' } }, - activeRuntimeEnvironmentId: 'web-runtime' - }) - Object.assign(store.repos[0], { executionHostId: 'runtime:web-runtime' }) - mockIsWebRuntimeSessionActive.mockReturnValue(true) - inventory.settings.mockResolvedValue(snapshot) - inventory.session.mockResolvedValue({ origin: 'unknown' }) - const row = { agent: 'claude', kind: 'cli', executionHostId: 'runtime:web-runtime' } as const - const menu: NewTabAgentMenuModel = { - state: 'settled', - rows: [row], - defaultTuiAgent: 'claude', - detection: { - detectedIds: ['claude'], - isLoading: false, - isRefreshing: false, - detectionFailed: false, - needsServerUpdate: false, - refresh: async () => ['claude'] - }, - pickerContext: { - workspace: { kind: 'git-worktree', worktreeId: 'wt-1' }, - executionHostId: row.executionHostId, - key: 'qa-history-host', - settings: null - } - } - function Panel({ open }: { open: boolean }) { - const entry = useAgentPickerInventoryEntries( - useAgentLaunchPickerInventorySource('wt-1', menu, open) - )[0] - const draftScope = useAgentPickerDraftScope() - const setup = useAgentPickerSetup({ entry, draftScope, open }) - const launch = useTabAgentMenuLaunch({ - worktreeId: 'wt-1', - groupId: 'group-1', - onFocusTerminal: () => {} - }) - return open && setup.ready - ? createElement( - TooltipProvider, - null, - // Select mode still edits Arguments and Permissions; the launch menu leaves them to settings. - createElement(AgentLaunchSetupPanel, { - entry, - mode: 'select', - draft: setup.draft, - getDraft: setup.getDraft, - onDraftChange: setup.change, - onUse: (draft) => { - if (setup.accept(draft)) { - launch(row, draft, entry) - } - } - }) - ) - : null - } - const view = render(createElement(Panel, { open: true })) - await act(async () => {}) - async function start() { - mockCreateWebRuntimeSessionTerminal.mockClear() - fireEvent.click(view.getByText('Launch terminal')) - await act(async () => {}) - const request = mockCreateWebRuntimeSessionTerminal.mock.calls[0]?.[0] - expect(request).toBeDefined() - expect(JSON.stringify(request)).not.toContain('desktop-only-qa') - expect(request).not.toHaveProperty('command') - return request! - } - const pristine = await start() - expect(pristine).not.toHaveProperty('agentArgs') - view.rerender(createElement(Panel, { open: false })) - view.rerender(createElement(Panel, { open: true })) - await act(async () => {}) - if (!view.queryByLabelText('Arguments')) { - fireEvent.click(view.getByLabelText('Toggle Arguments')) - } - fireEvent.change(view.getByLabelText('Arguments'), { target: { value: '--add-dir /tmp' } }) - const edited = await start() - expect(edited.agentArgs).toBe('--permission-mode auto --add-dir /tmp') - view.rerender(createElement(Panel, { open: false })) - view.rerender(createElement(Panel, { open: true })) - await act(async () => {}) - const reopened = await start() - expect(reopened.agentArgs).toBe('--permission-mode auto --add-dir /tmp') -}) From 654ca113d5b4c9d944e67b0ea4d7abe2a0081a41 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:27:32 +0000 Subject: [PATCH 03/40] fix(jcode): show a swarm helper's permission request on the main row (#41240) * fix(jcode): show a swarm helper's permission request on the main row Since helper hooks are fenced off the coordinator's row, a helper blocked on request_permission left the pane reading working while the swarm waited on a user who never saw the question. A helper's request now restates the coordinator's row as waiting with the helper's question, and its answer (or the helper's turn ending) puts the saved row back. A rested row comes back as a session boundary so the answer does not read as a second finished turn. The root's own next hook drops the saved row. * fix(jcode): restore helper permission waits onto the pane's current row Restore the saved status onto the row the pane has now, so a pane move between request and answer does not restore onto the old pane key. Ignore helpers from an earlier launch, keep the wait until the main agent's row actually replaces it rather than on any of its hooks, and show the next open question when one of several helpers settles. --- .../agent-hook-listener/listener-state.ts | 7 ++ .../agent-hook-listener-jcode-swarm.test.ts | 85 ++++++++++++++-- .../normalization/normalize-hook-payload.ts | 7 +- .../providers/jcode-events.ts | 11 --- .../providers/jcode-helper-permission-wait.ts | 96 +++++++++++++++++++ 5 files changed, 184 insertions(+), 22 deletions(-) create mode 100644 src/shared/agent-hook-listener/providers/jcode-helper-permission-wait.ts diff --git a/src/shared/agent-hook-listener/listener-state.ts b/src/shared/agent-hook-listener/listener-state.ts index 634cf60ce5b..78409182259 100644 --- a/src/shared/agent-hook-listener/listener-state.ts +++ b/src/shared/agent-hook-listener/listener-state.ts @@ -24,6 +24,7 @@ import { movePaneScopedSetEntries } from './pane-scoped-cache-entries' import type { JcodeUserPromptEvidence } from '../jcode-session-files' +import type { JcodeHelperPermissionWait } from './providers/jcode-helper-permission-wait' import type { HookRootAttempt } from './presence/hook-process-root-evidence' import { moveOpenCodeSessionBindings, @@ -47,6 +48,8 @@ export type HookListenerState = { antigravityChildWorkByPaneKey: Map }> /** Journal-backed prompt for each jcode pane's current turn; see readJcodeTurnPrompt. */ jcodeTurnPromptByPaneKey: Map + /** Open swarm-helper permission requests per jcode pane; see routeJcodeHelperHook. */ + jcodeHelperPermissionWaitByPaneKey: Map ampCompletedCacheKeys: Set /** Live subagents/teammates per Claude pane; survives turn boundaries since background children outlive the lead turn. */ claudeSubagentRosterByPaneKey: Map @@ -145,6 +148,7 @@ export function createHookListenerState( antigravityCompletedTranscriptByPaneKey: new Map(), antigravityChildWorkByPaneKey: new Map(), jcodeTurnPromptByPaneKey: new Map(), + jcodeHelperPermissionWaitByPaneKey: new Map(), ampCompletedCacheKeys: new Set(), claudeSubagentRosterByPaneKey: new Map(), claudeLeadStateByPaneKey: new Map(), @@ -220,6 +224,7 @@ export function clearPaneCacheState(state: HookListenerState, paneKey: string): deletePaneScopedCacheEntry(state.lastPromptByPaneKey, paneKey) deletePaneScopedCacheEntry(state.lastToolByPaneKey, paneKey) deletePaneScopedCacheEntry(state.jcodeTurnPromptByPaneKey, paneKey) + deletePaneScopedCacheEntry(state.jcodeHelperPermissionWaitByPaneKey, paneKey) deleteLegacyAgentStatus(state, paneKey) for (const key of state.lastStatusByPaneKey.keys()) { if (key.startsWith(`${paneKey}\0`)) { @@ -269,6 +274,7 @@ export function movePaneCacheState( movePaneScopedMapEntries(state.antigravityCompletedTranscriptByPaneKey, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.antigravityChildWorkByPaneKey, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.jcodeTurnPromptByPaneKey, fromPaneKey, toPaneKey) + movePaneScopedMapEntries(state.jcodeHelperPermissionWaitByPaneKey, fromPaneKey, toPaneKey) movePaneScopedSetEntries(state.ampCompletedCacheKeys, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.claudeConsumedCompactPromptIdByPaneKey, fromPaneKey, toPaneKey) movePaneScopedMapEntries(state.claudeSubagentRosterByPaneKey, fromPaneKey, toPaneKey) @@ -313,6 +319,7 @@ export function clearAllListenerCaches(state: HookListenerState): void { state.antigravityCompletedTranscriptByPaneKey.clear() state.antigravityChildWorkByPaneKey.clear() state.jcodeTurnPromptByPaneKey.clear() + state.jcodeHelperPermissionWaitByPaneKey.clear() state.ampCompletedCacheKeys.clear() state.claudeConsumedCompactPromptIdByPaneKey.clear() state.warnedVersions.clear() diff --git a/src/shared/agent-hook-listener/normalization/agent-hook-listener-jcode-swarm.test.ts b/src/shared/agent-hook-listener/normalization/agent-hook-listener-jcode-swarm.test.ts index 90eb444c5d2..3c2df8bdabf 100644 --- a/src/shared/agent-hook-listener/normalization/agent-hook-listener-jcode-swarm.test.ts +++ b/src/shared/agent-hook-listener/normalization/agent-hook-listener-jcode-swarm.test.ts @@ -10,6 +10,7 @@ import { normalizeAndAccept, PANE_KEY } from './agent-hook-listener-test-harness // swarm worker's hooks with the coordinator pane's ORCA_PANE_KEY; only session_id differs. const ROOT = 'session_tigress_1792603131095_636843aadc1b740b' const WORKER = 'session_retriever_1792603161400_81ad62e08be2201b' +const SECOND_WORKER = 'session_heron_1792603162400_5c1d2e3f4a5b6c7d' const CWD = '/tmp/jcapt-cwd' const capturedHooks: Record[] = [ { @@ -67,22 +68,34 @@ describe('Jcode swarm workers sharing the coordinator pane', () => { state = createHookListenerState() }) - afterEach(() => { - vi.unstubAllEnvs() - rmSync(home, { recursive: true, force: true }) - }) - - it("keeps the coordinator's row while its inline worker starts and finishes a turn", async () => { - // Jcode saves `id` then `parent_id` first; the worker is saved before it runs. + // Jcode saves `id` then `parent_id` first; the worker is saved before it runs. + function writeSessionFiles(): void { for (const [id, parentId] of [ [ROOT, null], - [WORKER, ROOT] + [WORKER, ROOT], + [SECOND_WORKER, ROOT] ]) { writeFileSync( join(home, 'sessions', `${id}.json`), JSON.stringify({ id, parent_id: parentId, title: 'captured', messages: [] }) ) } + } + + async function run(payload: Record) { + await checkHookOwnerPresence(state, 'jcode', { paneKey: PANE_KEY, payload }, 'production', () => + Promise.resolve() + ) + return normalizeAndAccept(state, 'jcode', payload) + } + + afterEach(() => { + vi.unstubAllEnvs() + rmSync(home, { recursive: true, force: true }) + }) + + it("keeps the coordinator's row while its inline worker starts and finishes a turn", async () => { + writeSessionFiles() const results: unknown[] = [] for (const payload of capturedHooks) { @@ -101,4 +114,60 @@ describe('Jcode swarm workers sharing the coordinator pane', () => { expect(row?.payload.state).toBe('working') expect(row?.providerSession?.id).toBe(ROOT) }) + it("shows an inline worker's permission request on the coordinator's row until it settles", async () => { + writeSessionFiles() + for (const payload of capturedHooks.slice(0, 5)) { + await run(payload) + } + // request_permission's schema (jcode tool/ambient.rs) in the captured pre_tool/post_tool shape. + const permission = { + cwd: CWD, + session_id: WORKER, + tool_call_id: 'toolu_01PermissionRequestWorker', + tool_input: + '{"action":"push","description":"Push the worker branch","rationale":"The fix is ready","wait":true}', + tool_name: 'request_permission' + } + + const waiting = await run({ ...permission, event: 'pre_tool' }) + expect(waiting?.payload).toMatchObject({ + state: 'waiting', + toolName: 'request_permission', + interactivePrompt: + '{"action":"push","description":"Push the worker branch","rationale":"The fix is ready","wait":true}' + }) + expect(waiting?.providerSession?.id).toBe(ROOT) + + const answered = await run({ ...permission, event: 'post_tool', status: 'ok' }) + expect(answered?.payload.state).toBe('working') + expect(answered?.payload.interactivePrompt).toBeUndefined() + expect(answered?.providerSession?.id).toBe(ROOT) + expect(await run(capturedHooks[5])).toBeNull() + + // Answered after the coordinator's turn ended: the row rests again without a second "finished". + await run({ cwd: CWD, event: 'turn_end', session_id: ROOT, status: 'ok' }) + expect((await run({ ...permission, event: 'pre_tool' }))?.payload.state).toBe('waiting') + const rested = await run({ ...permission, event: 'post_tool', status: 'ok' }) + expect(rested?.payload).toMatchObject({ state: 'done', sessionBoundary: true }) + }) + + it('shows the open question when another helper settles first', async () => { + writeSessionFiles() + for (const payload of capturedHooks.slice(0, 5)) { + await run(payload) + } + const ask = (sessionId: string, action: string) => ({ + cwd: CWD, + session_id: sessionId, + tool_input: `{"action":"${action}","description":"d","rationale":"r","wait":true}`, + tool_name: 'request_permission' + }) + await run({ ...ask(WORKER, 'push'), event: 'pre_tool' }) + await run({ ...ask(SECOND_WORKER, 'delete'), event: 'pre_tool' }) + + const stillOpen = await run({ ...ask(SECOND_WORKER, 'delete'), event: 'post_tool' }) + expect(stillOpen?.payload).toMatchObject({ state: 'waiting', toolInput: 'push' }) + const settled = await run({ ...ask(WORKER, 'push'), event: 'post_tool' }) + expect(settled?.payload.state).toBe('working') + }) }) diff --git a/src/shared/agent-hook-listener/normalization/normalize-hook-payload.ts b/src/shared/agent-hook-listener/normalization/normalize-hook-payload.ts index 33af4d35513..bd64f855b9a 100644 --- a/src/shared/agent-hook-listener/normalization/normalize-hook-payload.ts +++ b/src/shared/agent-hook-listener/normalization/normalize-hook-payload.ts @@ -29,7 +29,7 @@ import { readString } from '../tool-input-preview' import { readClaudeBatchSettledRequests } from '../claude-settled-permission-requests' import { withClaudeToolRequestId } from '../claude-tool-request-identity' import { hasSeparateHookSessionAdmission, readPaneSessionContext } from '../pane-provider-session' -import { isJcodeHelperSessionHook } from '../providers/jcode-events' +import { routeJcodeHelperHook } from '../providers/jcode-helper-permission-wait' /** Canonical transport-agnostic normalization entry shared by main and relay listeners. */ export function normalizeHookPayload( @@ -68,8 +68,9 @@ export function normalizeHookPayload( const sessions = readPaneSessionContext(state, source, envelope, eventName) const { providerSession, statusAdmissionSession } = sessions // Before prompt and tool caches: a helper's turn must not reset the root turn's caches either. - if (isJcodeHelperSessionHook(source, readString(hookPayloadRecord, 'session_id'))) { - return null + const helper = routeJcodeHelperHook(state, source, envelope, options.bindingStatusByPaneKey) + if (helper !== undefined) { + return helper } if (source === 'opencode' && record.opencodeTui === 1 && !providerSession) { return null diff --git a/src/shared/agent-hook-listener/providers/jcode-events.ts b/src/shared/agent-hook-listener/providers/jcode-events.ts index 66ee694ccd1..3a111fa2691 100644 --- a/src/shared/agent-hook-listener/providers/jcode-events.ts +++ b/src/shared/agent-hook-listener/providers/jcode-events.ts @@ -8,8 +8,6 @@ import { resolvePrompt, resolveToolState } from '../prompt-fields' import { extractToolFields, isNewTurnEvent } from '../provider-event-routing' import { readString } from '../tool-input-preview' import { isJcodeUserInputTool } from './jcode-tool-fields' -import { isCachedJcodeHelperSession } from '../../jcode-helper-sessions' -import type { AgentHookSource } from '../transport/agent-hook-relay' // Lifecycle mapping follows docs/reference/jcode-hook-events.md; idle session_start takes the early path. const JCODE_EVENT_STATES: Record = { @@ -69,12 +67,3 @@ export function normalizeJcodeEvent( : snapshot.lastAssistantMessageIsToolOutput }) } - -/** Jcode fires every swarm session's hooks with the requesting pane's key; a helper's must not - * drive the pane's row. The verdict is read ahead of normalization by the hook owner preflight. */ -export function isJcodeHelperSessionHook( - source: AgentHookSource, - sessionId: string | undefined -): boolean { - return source === 'jcode' && isCachedJcodeHelperSession(sessionId) -} diff --git a/src/shared/agent-hook-listener/providers/jcode-helper-permission-wait.ts b/src/shared/agent-hook-listener/providers/jcode-helper-permission-wait.ts new file mode 100644 index 00000000000..3dbe62cb420 --- /dev/null +++ b/src/shared/agent-hook-listener/providers/jcode-helper-permission-wait.ts @@ -0,0 +1,96 @@ +import { isCachedJcodeHelperSession } from '../../jcode-helper-sessions' +import type { ParsedHookEnvelope } from '../hook-envelope' +import type { AgentHookEventPayload } from '../listener-event' +import type { HookListenerState } from '../listener-state' +import { readString } from '../tool-input-preview' +import type { AgentHookSource } from '../transport/agent-hook-relay' +import { extractJcodeToolFields, isJcodeUserInputTool } from './jcode-tool-fields' + +type HelperRequest = { toolInput?: string; interactivePrompt?: string } + +export type JcodeHelperPermissionWait = { + /** Open request_permission questions by helper session, oldest first. */ + requests: Map + /** The pane's status before the first open request, restored once every request settles. */ + before: AgentHookEventPayload['payload'] + /** The question the row shows; any other row means the main agent has moved on. */ + shown: string | undefined +} + +/** Jcode fires every swarm session's hooks with the requesting pane's key, so a helper's hooks must + * not drive the pane's row (the verdict is read ahead by the hook owner preflight). A helper's + * request_permission still blocks on the user, so it shows the row as waiting until it settles. + * Returns undefined for hooks that are not a helper's. */ +export function routeJcodeHelperHook( + state: HookListenerState, + source: AgentHookSource, + { paneKey, eventName, hookPayloadRecord: hookPayload, launchToken }: ParsedHookEnvelope, + committedRows: ReadonlyMap | undefined +): AgentHookEventPayload | null | undefined { + const sessionId = source === 'jcode' ? readString(hookPayload, 'session_id') : undefined + if (!sessionId || !isCachedJcodeHelperSession(sessionId)) { + return undefined + } + // A relay's provider view lags its committed rows; restate the committed one. + const row = (committedRows ?? state.lastStatusByPaneKey).get(paneKey) + // A helper left over from an earlier launch speaks for no current row. + if ( + row?.payload.agentType !== 'jcode' || + (launchToken && row.launchToken && launchToken !== row.launchToken) + ) { + return null + } + const waits = state.jcodeHelperPermissionWaitByPaneKey + const saved = waits.get(paneKey) + const wait = + saved && + row.payload.state === 'waiting' && + row.payload.toolName === 'request_permission' && + row.payload.interactivePrompt === saved.shown + ? saved + : undefined + if (saved && !wait) { + waits.delete(paneKey) + } + const toolName = readString(hookPayload, 'tool_name') + if (eventName === 'pre_tool' && isJcodeUserInputTool(toolName)) { + const { toolInput, interactivePrompt } = extractJcodeToolFields(eventName, hookPayload) + const requests = new Map(wait?.requests) + requests.delete(sessionId) + requests.set(sessionId, { toolInput, interactivePrompt }) + waits.set(paneKey, { requests, before: wait?.before ?? row.payload, shown: interactivePrompt }) + const payload = { + ...row.payload, + state: 'waiting' as const, + toolName, + toolInput, + interactivePrompt + } + return restate(row, payload, 'pre_tool') + } + const settles = + (eventName === 'post_tool' && isJcodeUserInputTool(toolName)) || + eventName === 'turn_end' || + eventName === 'session_end' + if (!wait || !settles || !wait.requests.delete(sessionId)) { + return null + } + const next = [...wait.requests.values()].at(-1) + if (next) { + wait.shown = next.interactivePrompt + return restate(row, { ...row.payload, ...next }, 'pre_tool') + } + waits.delete(paneKey) + const { before } = wait + // A rested row settles as a boundary so the answer does not read as a second finished turn. + return restate(row, before.state === 'done' ? { ...before, sessionBoundary: true } : before) +} + +/** The pane's row with new status; without an event name it neither replays nor notifies. */ +function restate( + row: AgentHookEventPayload, + payload: AgentHookEventPayload['payload'], + hookEventName?: string +): AgentHookEventPayload { + return { ...row, isReplay: undefined, hasExplicitPrompt: undefined, hookEventName, payload } +} From 21f6ec652737c9979d021a482465ca336b572013 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:28:16 -0800 Subject: [PATCH 04/40] Fix Codex account status for Bedrock providers (#40905) * Fix Codex account status for Bedrock and other built-in providers Derive system-default authentication from the configured provider and honor the declared credential mode before reading ChatGPT identity. Co-authored-by: Christopher Ryu * Reuse provider classification until canonical config changes * Bound provider config work and refresh after file removal * Use portable module counters for provider config regression checks * Complete the host target in the account warning fixture * Include the account warning module in Node test typechecking --------- Co-authored-by: Christopher Ryu --- config/tsconfig.node.json | 1 + ...dex-account-identity-api-key-guard.test.ts | 49 +++++ .../codex-accounts/codex-account-identity.ts | 60 ++++-- .../codex-accounts/codex-config-mirror.ts | 33 +++- .../service-system-default-identity.test.ts | 178 +++++++++++++++++- src/main/codex-accounts/service.ts | 2 +- .../launch/codex-model-provider-config.ts | 4 +- 7 files changed, 311 insertions(+), 16 deletions(-) diff --git a/config/tsconfig.node.json b/config/tsconfig.node.json index e871e791659..c616a385638 100644 --- a/config/tsconfig.node.json +++ b/config/tsconfig.node.json @@ -30,6 +30,7 @@ "../src/renderer/src/components/native-chat/session/structured/delivery/structured-agent-session-pending-sends.ts", "../src/renderer/src/components/native-chat/queue/structured-agent-session-queue-request.ts", "../src/renderer/src/components/native-chat/native-chat-composer-primary-action.ts", + "../src/renderer/src/components/settings/accounts/codex/codex-account-auth-warning.ts", "../src/renderer/src/components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-panes.ts", "../src/preload/**/*", "../src/shared/**/*", diff --git a/src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts b/src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts index 5626fd94cca..a3a81aefc79 100644 --- a/src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts +++ b/src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts @@ -34,4 +34,53 @@ describe('managed-home Codex identity', () => { workspaceAccountId: null }) }) + + it.each([ + { + auth_mode: 'bedrockApiKey', + bedrock_api_key: { api_key: 'bedrock-fixture-key', region: 'us-east-2' } + }, + { + auth_mode: 'bedrockAccessKeys', + bedrock_access_keys: { + access_key_id: 'AKIAFIXTUREONLY', + secret_access_key: 'fixture-secret', + region: 'us-east-2' + } + } + ])('does not attribute $auth_mode to stale ChatGPT tokens', async (credential) => { + const home = homeWithAuthJson({ + ...credential, + tokens: { + account_id: 'stale-account', + id_token: idTokenWithClaims({ email: 'stale@example.com' }) + } + }) + + expect(await identity.readFromHome(home, 'account-1')).toEqual({ + email: null, + providerAccountId: null, + workspaceLabel: null, + workspaceAccountId: null + }) + + writeFileSync( + join(home, 'auth.json'), + JSON.stringify({ + ...credential, + auth_mode: 'chatgpt', + OPENAI_API_KEY: 'sk-exchanged-key', + tokens: { + account_id: 'current-account', + id_token: idTokenWithClaims({ email: 'current@example.com' }) + } + }) + ) + expect(await identity.readFromHome(home, 'account-1')).toEqual({ + email: 'current@example.com', + providerAccountId: 'current-account', + workspaceLabel: null, + workspaceAccountId: 'current-account' + }) + }) }) diff --git a/src/main/codex-accounts/codex-account-identity.ts b/src/main/codex-accounts/codex-account-identity.ts index 7768a7521b7..ccf7bab9a29 100644 --- a/src/main/codex-accounts/codex-account-identity.ts +++ b/src/main/codex-accounts/codex-account-identity.ts @@ -8,13 +8,40 @@ import { ManagedCodexHomeTemporarilyUnavailableError } from './host-codex-manage export type ResolvedCodexIdentity = CodexAuthIdentity -/** API-key logins carry no OAuth identity even when a stale `tokens` blob is still present. */ -function declaresApiKeyCredential(parsed: unknown): boolean { +const PROVIDERS_WITHOUT_OPENAI_AUTH = new Set([ + 'amazon-bedrock', + 'amazon-bedrock-runtime', + 'gcp', + 'ollama', + 'lmstudio' +]) +const API_KEY_AUTH_MODES = new Set(['apikey', 'bedrockApiKey', 'bedrockAccessKeys']) + +function resolveStoredAuthMode(parsed: unknown): string | null { if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - return false + return null } - const apiKey = (parsed as Record).OPENAI_API_KEY - return typeof apiKey === 'string' && apiKey.trim() !== '' + const auth = parsed as Record + if (auth.auth_mode != null) { + return typeof auth.auth_mode === 'string' ? auth.auth_mode : null + } + if (auth.personal_access_token != null) { + return 'personalAccessToken' + } + if (auth.bedrock_api_key != null) { + return 'bedrockApiKey' + } + if (auth.bedrock_access_keys != null) { + return 'bedrockAccessKeys' + } + if (auth.OPENAI_API_KEY != null) { + return 'apikey' + } + return 'chatgpt' +} + +function hasChatGptTokenIdentity(mode: string | null): boolean { + return mode === 'chatgpt' || mode === 'chatgptAuthTokens' } export class CodexAccountIdentity { @@ -54,7 +81,7 @@ export class CodexAccountIdentity { // Raw SyntaxError messages may expose credential bytes. throw new Error('Codex auth.json is corrupt or not valid JSON') } - if (declaresApiKeyCredential(parsed)) { + if (!hasChatGptTokenIdentity(resolveStoredAuthMode(parsed))) { return { email: null, providerAccountId: null, @@ -75,7 +102,8 @@ export class CodexAccountIdentity { } // Resolve the system default live from ~/.codex rather than stored managed-account identity. - resolveSystemDefault(): CodexSystemDefaultIdentity { + resolveSystemDefault(provider: string | null): CodexSystemDefaultIdentity { + const usesProviderAuth = provider !== null && PROVIDERS_WITHOUT_OPENAI_AUTH.has(provider) let contents: string try { contents = readFileSync(join(homedir(), '.codex', 'auth.json'), 'utf-8') @@ -83,13 +111,20 @@ export class CodexAccountIdentity { const code = (error as NodeJS.ErrnoException | null)?.code if (code === 'ENOENT' || code === 'ENOTDIR') { // Environment API keys can authenticate without an auth.json file. - return this.systemDefaultIdentity(false, this.hasEnvApiKey() ? 'api-key' : 'none') + return this.systemDefaultIdentity( + false, + usesProviderAuth || this.hasEnvApiKey() ? 'api-key' : 'none' + ) } console.warn( '[codex-accounts] Failed to read system-default Codex identity', code ?? 'unknown-error' ) - return this.systemDefaultIdentity(true, 'none') + return this.systemDefaultIdentity(true, usesProviderAuth ? 'api-key' : 'none') + } + + if (usesProviderAuth) { + return this.systemDefaultIdentity(true, 'api-key') } let parsed: unknown @@ -104,11 +139,12 @@ export class CodexAccountIdentity { console.warn('[codex-accounts] System-default Codex auth has an unexpected format') return this.systemDefaultIdentity(true, 'none') } - if (declaresApiKeyCredential(parsed)) { - return this.systemDefaultIdentity(true, 'api-key') + const mode = resolveStoredAuthMode(parsed) + if (!mode || API_KEY_AUTH_MODES.has(mode)) { + return this.systemDefaultIdentity(true, mode ? 'api-key' : 'none') } - const identity = readCodexAuthIdentity(contents) + const identity = hasChatGptTokenIdentity(mode) ? readCodexAuthIdentity(contents) : null return { hasAuth: true, authKind: 'oauth', diff --git a/src/main/codex-accounts/codex-config-mirror.ts b/src/main/codex-accounts/codex-config-mirror.ts index 46bd1ea0cde..1c19d71fdb9 100644 --- a/src/main/codex-accounts/codex-config-mirror.ts +++ b/src/main/codex-accounts/codex-config-mirror.ts @@ -1,6 +1,8 @@ import { existsSync, readFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' +import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' +import { createIntegrationStateFileCache } from '../credentials/integration-state-file-cache' import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' import { ensureCodexDaemonSocketGuard, @@ -20,6 +22,31 @@ export type CanonicalCodexConfig = { } export class CodexConfigMirror { + private readonly hostModelProvider = createIntegrationStateFileCache({ + filePath: () => join(homedir(), '.codex', 'config.toml'), + readFromDisk: () => { + try { + return readCodexTopLevelModelProvider( + this.readHostConfigContents(join(homedir(), '.codex', 'config.toml')) + ) + } catch (error) { + if (!isDefinitiveAbsence(error)) { + throw error + } + return null + } + } + }) + + readHostModelProvider(): string | null { + try { + return this.hostModelProvider.get() + } catch { + console.warn('[codex-accounts] Failed to read canonical provider config') + return null + } + } + constructor( private readonly store: Pick, private readonly assertManagedHomePath: ( @@ -146,6 +173,10 @@ export class CodexConfigMirror { ) } + private readHostConfigContents(configPath: string): string { + return readFileSync(configPath, 'utf-8') + } + private readHostConfig(): CanonicalCodexConfig | null { const sourceHomePath = join(homedir(), '.codex') const primaryConfigPath = join(sourceHomePath, 'config.toml') @@ -153,7 +184,7 @@ export class CodexConfigMirror { return null } try { - return { contents: readFileSync(primaryConfigPath, 'utf-8'), sourceHomePath } + return { contents: this.readHostConfigContents(primaryConfigPath), sourceHomePath } } catch (error) { console.warn('[codex-accounts] Failed to read canonical config:', error) return null diff --git a/src/main/codex-accounts/service-system-default-identity.test.ts b/src/main/codex-accounts/service-system-default-identity.test.ts index 2b61f5bbe4e..0a58973e9e5 100644 --- a/src/main/codex-accounts/service-system-default-identity.test.ts +++ b/src/main/codex-accounts/service-system-default-identity.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { writeFileSync } from 'node:fs' +import { rmSync, writeFileSync } from 'node:fs' +import type * as FileSystem from 'node:fs' +import { getCodexAccountAuthWarning } from '../../renderer/src/components/settings/accounts/codex/codex-account-auth-warning' import { join } from 'node:path' import { createCodexAuthJson, @@ -12,6 +14,35 @@ import { testState } from './service-test-harness' +const configWork = vi.hoisted(() => ({ readPaths: new Array(), parses: 0 })) + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readFileSync: (...args: Parameters) => { + configWork.readPaths.push(args[0]) + return actual.readFileSync(...args) + } + } +}) + +vi.mock( + import('../codex/structured/launch/codex-model-provider-config'), + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readCodexTopLevelModelProvider: ( + ...args: Parameters + ) => { + configWork.parses += 1 + return actual.readCodexTopLevelModelProvider(...args) + } + } + } +) + vi.mock('electron', () => ({ app: { getPath: () => testState.userDataDir @@ -76,6 +107,151 @@ describe('CodexAccountService config sync', () => { }) }) + it.each(['amazon-bedrock-runtime', 'ollama'])( + 'recognizes %s without an auth.json file', + async (provider) => { + writeFileSync( + join(systemCodexHomeDir(), 'config.toml'), + `model_provider = "${provider}"\n`, + 'utf-8' + ) + const service = await newService() + + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ + hasAuth: false, + authKind: 'api-key', + email: null, + providerAccountId: null, + workspaceLabel: null + }) + expect( + getCodexAccountAuthWarning({ + limits: null, + target: { runtime: 'host', wslDistro: null }, + runtime: { runtime: 'host' }, + activeAccountId: null, + accountId: null, + authKind: withoutEnvApiKey(() => service.listAccounts()).systemDefault?.authKind + }) + ).toBeNull() + } + ) + + it('does not attribute Bedrock Mantle to a saved ChatGPT login', async () => { + writeFileSync( + join(systemCodexHomeDir(), 'config.toml'), + 'model_provider = "amazon-bedrock"\n', + 'utf-8' + ) + writeFileSync(systemAuthPath(), createCodexAuthJson('old@home.dev', 'old', 'refresh')) + const service = await newService() + + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ + hasAuth: true, + authKind: 'api-key', + email: null, + providerAccountId: null, + workspaceLabel: null + }) + + writeFileSync(join(systemCodexHomeDir(), 'config.toml'), 'model_provider = "openai"\n') + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ + hasAuth: true, + authKind: 'oauth', + email: 'old@home.dev', + providerAccountId: 'old', + workspaceLabel: null + }) + }) + + it.each(['bedrockApiKey', undefined])( + 'recognizes a saved Bedrock API key with mode %s instead of reporting OAuth', + async (mode) => { + writeFileSync( + systemAuthPath(), + JSON.stringify({ + ...JSON.parse(createCodexAuthJson('old@home.dev', 'old', 'refresh')), + auth_mode: mode, + bedrock_api_key: { api_key: 'bedrock-fixture-key', region: 'us-east-2' } + }) + ) + const service = await newService() + + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ + hasAuth: true, + authKind: 'api-key', + email: null, + providerAccountId: null, + workspaceLabel: null + }) + } + ) + + it('keeps backend auth status without attributing stale tokens to a personal access token', async () => { + writeFileSync( + systemAuthPath(), + JSON.stringify({ + ...JSON.parse(createCodexAuthJson('old@home.dev', 'old', 'refresh')), + personal_access_token: 'fixture-personal-access-token' + }) + ) + const service = await newService() + + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ + hasAuth: true, + authKind: 'oauth', + email: null, + providerAccountId: null, + workspaceLabel: null + }) + }) + + it.each([750, 7_500])( + 'reuses unchanged provider input across snapshots with %i saved projects', + async (projectCount) => { + const configPath = join(systemCodexHomeDir(), 'config.toml') + const projects = Array.from( + { length: projectCount }, + (_, index) => `[projects."/work/project-${index}"]\ntrust_level = "trusted"\n` + ).join('') + writeFileSync(configPath, `model_provider = "amazon-bedrock"\n${projects}`) + writeFileSync( + systemAuthPath(), + createCodexAuthJson('real@home.dev', 'acct-real', 'refresh') + ) + const service = await newService() + configWork.readPaths = [] + configWork.parses = 0 + const configReads = () => configWork.readPaths.filter((path) => path === configPath).length + + for (let update = 0; update < 20; update += 1) { + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault?.authKind).toBe( + 'api-key' + ) + } + // Usage updates do not invalidate the one current provider classification. + expect(configReads()).toBe(1) + expect(configWork.parses).toBe(1) + + rmSync(configPath) + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault?.authKind).toBe('oauth') + expect(configReads()).toBe(2) + service.listAccounts() + expect(configReads()).toBe(2) + + writeFileSync(configPath, `model_provider = "openai"\n${projects}`) + expect(withoutEnvApiKey(() => service.listAccounts()).systemDefault).toEqual({ + hasAuth: true, + authKind: 'oauth', + email: 'real@home.dev', + providerAccountId: 'acct-real', + workspaceLabel: null + }) + expect(configReads()).toBe(3) + expect(configWork.parses).toBe(2) + } + ) + it('degrades safely when auth.json contains valid JSON with the wrong shape', async () => { writeFileSync(systemAuthPath(), 'null', 'utf-8') const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/main/codex-accounts/service.ts b/src/main/codex-accounts/service.ts index feab44c10a3..dc7dd4eaa44 100644 --- a/src/main/codex-accounts/service.ts +++ b/src/main/codex-accounts/service.ts @@ -261,7 +261,7 @@ export class CodexAccountService { } private resolveSystemDefaultIdentity(): CodexSystemDefaultIdentity { - return this.identity.resolveSystemDefault() + return this.identity.resolveSystemDefault(this.configMirror.readHostModelProvider()) } private readIdentityFromHome( diff --git a/src/main/codex/structured/launch/codex-model-provider-config.ts b/src/main/codex/structured/launch/codex-model-provider-config.ts index 87ac4a267d7..a5db3bc29e8 100644 --- a/src/main/codex/structured/launch/codex-model-provider-config.ts +++ b/src/main/codex/structured/launch/codex-model-provider-config.ts @@ -11,7 +11,9 @@ import { export function readCodexTopLevelModelProvider(config: string): string | null { let state = createTomlLineScanState() let lineOffset = 0 - for (const line of config.split('\n')) { + while (lineOffset <= config.length) { + const lineEnd = config.indexOf('\n', lineOffset) + const line = config.slice(lineOffset, lineEnd === -1 ? config.length : lineEnd) if (isTomlStructuralLine(state)) { if (getTomlTableHeader(line)) { return null From aa6b4197b81cae9e2f3f4a081a05e7834618927b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:29:04 -0800 Subject: [PATCH 05/40] fix(chat): keep generated images visible with the final answer (#40935) * fix(chat): keep generated images with settled answers * fix(chat): deduplicate images against rendered Markdown * Keep generated answer previews aligned with rendered Markdown * Keep generated-image regressions in the existing rendered transcript suite * Keep generated image renderer fixtures within their project boundary --- .../src/components/mobile-markdown-blocks.tsx | 113 +++------- .../mobile-markdown-image-paragraph.test.tsx | 64 ++++++ .../mobile-markdown-image-paragraph.tsx | 84 ++++++++ .../mobile-markdown-image-placement.ts | 53 +++++ .../transcript/MobileNativeChatProse.tsx | 31 +-- ...mobile-native-chat-markdown-image-block.ts | 32 +++ ...bile-native-chat-markdown-image-sources.ts | 35 ++++ ...ile-native-chat-generated-image-answers.ts | 37 ++++ ...obile-native-chat-transcript-rows.test.tsx | 126 +++++++++++ .../use-mobile-native-chat-turn-disclosure.ts | 37 ++-- .../journal-views/codex-history-projection.ts | 3 +- .../rollouts/codex-rollout-item-projection.ts | 2 + .../codex-generated-image-answer.test.ts | 89 ++++++++ .../slots/native-chat-transcript-input.ts | 3 + .../native-chat-transcript-slots.test.ts | 127 ++++++++++- .../slots/native-chat-transcript-slots.ts | 36 +++- .../slots/use-native-chat-transcript-slots.ts | 13 +- .../native-chat-markdown-image-sources.ts | 64 ++++++ .../native-chat-visual-markdown-extension.tsx | 4 +- .../native-chat-visual-markdown-syntax.ts | 6 +- .../rows/NativeChatAgentMessageCard.test.tsx | 128 ++++++++++- .../components/sidebar/CommentMarkdown.tsx | 82 ++------ .../comment-markdown-element-renderers.tsx | 14 +- .../comment-markdown-remark-plugins.ts | 14 ++ .../sidebar/comment-markdown-sanitize.ts | 65 ++++++ .../native-chat-generated-image.ts | 28 ++- ...ative-chat-generated-image-answers.test.ts | 198 ++++++++++++++++++ .../native-chat-generated-image-answers.ts | 171 +++++++++++++++ .../transcript/native-chat-turn-fold.ts | 31 +-- 29 files changed, 1450 insertions(+), 240 deletions(-) create mode 100644 mobile/src/components/mobile-markdown-image-paragraph.test.tsx create mode 100644 mobile/src/components/mobile-markdown-image-paragraph.tsx create mode 100644 mobile/src/components/mobile-markdown-image-placement.ts create mode 100644 mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-block.ts create mode 100644 mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-sources.ts create mode 100644 mobile/src/session/native-chat/transcript/use-mobile-native-chat-generated-image-answers.ts create mode 100644 src/main/codex/structured/items/codex-generated-image-answer.test.ts create mode 100644 src/renderer/src/components/native-chat/markdown/native-chat-markdown-image-sources.ts create mode 100644 src/renderer/src/components/sidebar/comment-markdown-remark-plugins.ts create mode 100644 src/renderer/src/components/sidebar/comment-markdown-sanitize.ts create mode 100644 src/shared/native-chat/transcript/native-chat-generated-image-answers.test.ts create mode 100644 src/shared/native-chat/transcript/native-chat-generated-image-answers.ts diff --git a/mobile/src/components/mobile-markdown-blocks.tsx b/mobile/src/components/mobile-markdown-blocks.tsx index fb0deb4d64d..330d9fa8e9b 100644 --- a/mobile/src/components/mobile-markdown-blocks.tsx +++ b/mobile/src/components/mobile-markdown-blocks.tsx @@ -1,4 +1,10 @@ -import type { Code, List, Nodes, PhrasingContent, RootContent, Table } from 'mdast' +import { renderImageParagraph } from './mobile-markdown-image-paragraph' +import { + mobileMarkdownBlockIsLiteral, + mobileMarkdownNestedBlocks, + mobileMarkdownParagraphImages +} from './mobile-markdown-image-placement' +import type { Code, List, Nodes, RootContent, Table } from 'mdast' import { Fragment, type ReactNode } from 'react' import { Square, SquareCheck } from 'lucide-react-native' import { @@ -34,9 +40,6 @@ import { colors, pressedStyle } from '../theme/mobile-theme' /** Prose base size — passed to MermaidDiagram fallback mono text. */ const MERMAID_BASE = 13 -/** Containers nested deeper than this draw as plain text, so a pathological nesting cannot - * exhaust native layout. */ -const MAX_NESTING = 8 /** A field added here is compared in mobile-markdown-drawn-blocks' `sameContext` too. */ export type MarkdownBlockContext = MarkdownInlineContext & { @@ -77,6 +80,7 @@ function renderCode(node: Code, key: number, ctx: MarkdownBlockContext): ReactNo } function renderList(node: List, key: number, ctx: MarkdownBlockContext, depth: number): ReactNode { + const nested = mobileMarkdownNestedBlocks(node, depth) const itemText: ParagraphText = { style: ctx.listText, selectable: true } return ( @@ -105,7 +109,7 @@ function renderList(node: List, key: number, ctx: MarkdownBlockContext, depth: n )} - {renderBlocks(item.children, ctx, itemText, depth + 1)} + {renderBlocks(nested[itemIndex]!.nodes, ctx, itemText, nested[itemIndex]!.depth)} ))} @@ -161,79 +165,6 @@ function renderTable(node: Table, key: number, ctx: MarkdownBlockContext): React ) } -function isBlankInline(node: PhrasingContent): boolean { - return node.type === 'break' || (node.type === 'text' && node.value.trim() === '') -} - -/** Images draw as blocks between the paragraph's text runs; an image `renderImage` declines stays a link. */ -function renderImageParagraph( - children: PhrasingContent[], - key: number, - ctx: MarkdownBlockContext, - text: ParagraphText -): ReactNode { - const { renderImage } = ctx - if (!renderImage || !children.some((child) => child.type === 'image')) { - return null - } - const parts: ReactNode[] = [] - let drewImage = false - let run: PhrasingContent[] = [] - const flushRun = (): void => { - if (!run.every(isBlankInline)) { - parts.push( - - {renderInline(trimRunEdges(run), ctx)} - - ) - } - run = [] - } - for (const child of children) { - const image = - child.type === 'image' ? renderImage(child.url, child.alt ?? '', child.data?.width) : null - if (image === null || image === undefined) { - run.push(child) - continue - } - flushRun() - parts.push({image}) - drewImage = true - } - if (!drewImage) { - return null - } - flushRun() - // One wrapper whatever the part count, so a growing paragraph never remounts its images. - return ( - - {parts} - - ) -} - -// The line breaks beside an image would otherwise leave blank lines in the text around it. -function trimRunEdges(run: PhrasingContent[]): PhrasingContent[] { - let start = 0 - let end = run.length - while (start < end && run[start]?.type === 'break') { - start += 1 - } - while (end > start && run[end - 1]?.type === 'break') { - end -= 1 - } - const trimmed = run.slice(start, end) - const first = trimmed[0] - if (first?.type === 'text') { - trimmed[0] = { ...first, value: first.value.trimStart() } - } - const last = trimmed.at(-1) - if (last?.type === 'text') { - trimmed[trimmed.length - 1] = { ...last, value: last.value.trimEnd() } - } - return trimmed -} - function renderBlock( node: RootContent, key: number, @@ -241,13 +172,14 @@ function renderBlock( text: ParagraphText, depth: number ): ReactNode { - if (depth > MAX_NESTING && 'children' in node) { + if (mobileMarkdownBlockIsLiteral(node, depth)) { return ( {plainText(node)} ) } + const nested = mobileMarkdownNestedBlocks(node, depth)[0] switch (node.type) { case 'paragraph': { const [only] = node.children @@ -263,7 +195,13 @@ function renderBlock( ) : null } - const withImages = renderImageParagraph(node.children, key, ctx, text) + const withImages = renderImageParagraph( + node.children, + mobileMarkdownParagraphImages(node, depth), + key, + ctx, + text + ) if (withImages) { return withImages } @@ -316,12 +254,12 @@ function renderBlock( // A GitHub alert's body is ordinary text, not a muted quote. return node.data?.callout ? ( - {renderBlocks(node.children, ctx, { style: text.style, selectable: true }, depth + 1)} + {renderBlocks(nested!.nodes, ctx, { style: text.style, selectable: true }, nested!.depth)} ) : ( {renderBlocks( - node.children, + nested!.nodes, ctx, { style: [ @@ -331,7 +269,7 @@ function renderBlock( ], selectable: true }, - depth + 1 + nested!.depth )} ) @@ -366,7 +304,7 @@ function renderBlock( : translate('pullRequest.markdownBlocks.details', 'Details') } > - {renderBlocks(node.children, ctx, text, depth + 1)} + {renderBlocks(nested!.nodes, ctx, text, nested!.depth)} ) case 'footnoteDefinition': @@ -374,7 +312,12 @@ function renderBlock( {`${node.label ?? node.identifier}.`} - {renderBlocks(node.children, ctx, { style: ctx.listText, selectable: true }, depth + 1)} + {renderBlocks( + nested!.nodes, + ctx, + { style: ctx.listText, selectable: true }, + nested!.depth + )} ) diff --git a/mobile/src/components/mobile-markdown-image-paragraph.test.tsx b/mobile/src/components/mobile-markdown-image-paragraph.test.tsx new file mode 100644 index 00000000000..633a4faa39e --- /dev/null +++ b/mobile/src/components/mobile-markdown-image-paragraph.test.tsx @@ -0,0 +1,64 @@ +import { createElement } from 'react' +import { describe, expect, it, vi } from 'vitest' +import { renderImageParagraph } from './mobile-markdown-image-paragraph' +import { mobileMarkdownParagraphImages } from './mobile-markdown-image-placement' +import { parseMobileMarkdownTree } from './mobile-markdown-tree' +import { MARKDOWN_TONES } from './mobile-markdown-styles' +import type { MarkdownBlockContext } from './mobile-markdown-blocks' + +vi.mock('react-native', () => ({ + Linking: { openURL: () => Promise.resolve() }, + Platform: { OS: 'ios' }, + StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, + Text: 'Text', + View: 'View' +})) + +describe('phone Markdown image paragraphs', () => { + it.each([100, 1000])('draws %i images with linear eligibility reads', (count) => { + const root = parseMobileMarkdownTree( + Array(count).fill('![](/tmp/p.png)').join(' '), + false, + true + ) + const paragraph = root.children[0]! + if (paragraph.type !== 'paragraph') { + throw new Error('expected an image paragraph') + } + let reads = 0 + const images = mobileMarkdownParagraphImages(paragraph, 0) + images.forEach((image, index) => { + Object.defineProperty(images, index, { + get() { + reads += 1 + return image + } + }) + }) + const drawn: string[] = [] + const ctx: MarkdownBlockContext = { + onOpenLink: () => {}, + tone: MARKDOWN_TONES.default, + textScale: 1, + chatMath: true, + growing: false, + listText: {}, + listMarker: {}, + directives: [], + mermaidOccurrences: new Map(), + renderImage: (href) => { + drawn.push(href) + return createElement('Image', { href }) + } + } + expect( + renderImageParagraph(paragraph.children, images, 0, ctx, { + style: {}, + selectable: true + }) + ).not.toBeNull() + expect(drawn).toEqual(Array(count).fill('/tmp/p.png')) + // Each eligible image needs one read to index and one to draw, independent of paragraph width. + expect(reads).toBeLessThanOrEqual(2 * count) + }) +}) diff --git a/mobile/src/components/mobile-markdown-image-paragraph.tsx b/mobile/src/components/mobile-markdown-image-paragraph.tsx new file mode 100644 index 00000000000..1eac5a24658 --- /dev/null +++ b/mobile/src/components/mobile-markdown-image-paragraph.tsx @@ -0,0 +1,84 @@ +import type { Image, PhrasingContent } from 'mdast' +import { Fragment, type ReactNode } from 'react' +import { View } from 'react-native' +import { MarkdownText } from './mobile-markdown-text' +import { renderInline } from './mobile-markdown-inline' +import { styles } from './mobile-markdown-styles' +import type { MarkdownBlockContext, ParagraphText } from './mobile-markdown-blocks' + +function isBlankInline(node: PhrasingContent): boolean { + return node.type === 'break' || (node.type === 'text' && node.value.trim() === '') +} + +/** Images draw as blocks between the paragraph's text runs; an image `renderImage` declines stays a link. */ +export function renderImageParagraph( + children: PhrasingContent[], + images: readonly Image[], + key: number, + ctx: MarkdownBlockContext, + text: ParagraphText +): ReactNode { + const { renderImage } = ctx + if (!renderImage || images.length === 0) { + return null + } + const eligibleImages = new Set(images) + const parts: ReactNode[] = [] + let drewImage = false + let run: PhrasingContent[] = [] + const flushRun = (): void => { + if (!run.every(isBlankInline)) { + parts.push( + + {renderInline(trimRunEdges(run), ctx)} + + ) + } + run = [] + } + for (const child of children) { + const image = + child.type === 'image' && eligibleImages.has(child) + ? renderImage(child.url, child.alt ?? '', child.data?.width) + : null + if (image === null || image === undefined) { + run.push(child) + continue + } + flushRun() + parts.push({image}) + drewImage = true + } + if (!drewImage) { + return null + } + flushRun() + // One wrapper whatever the part count, so a growing paragraph never remounts its images. + return ( + + {parts} + + ) +} + +// The line breaks beside an image would otherwise leave blank lines in the text around it. +function trimRunEdges(run: PhrasingContent[]): PhrasingContent[] { + let start = 0 + let end = run.length + while (start < end && run[start]?.type === 'break') { + start += 1 + } + while (end > start && run[end - 1]?.type === 'break') { + end -= 1 + } + const trimmed = run.slice(start, end) + const first = trimmed[0] + if (first?.type === 'text') { + trimmed[0] = { ...first, value: first.value.trimStart() } + } + const last = trimmed.at(-1) + if (last?.type === 'text') { + trimmed[trimmed.length - 1] = { ...last, value: last.value.trimEnd() } + } + return trimmed +} diff --git a/mobile/src/components/mobile-markdown-image-placement.ts b/mobile/src/components/mobile-markdown-image-placement.ts new file mode 100644 index 00000000000..8852fa699d4 --- /dev/null +++ b/mobile/src/components/mobile-markdown-image-placement.ts @@ -0,0 +1,53 @@ +import type { Image, Root, RootContent } from 'mdast' + +/** The same nesting boundary applies to native layout and image discovery. */ +export function mobileMarkdownBlockIsLiteral(node: RootContent, depth: number): boolean { + return depth > 8 && 'children' in node +} + +export function mobileMarkdownParagraphImages(node: RootContent, depth: number): Image[] { + return node.type === 'paragraph' && !mobileMarkdownBlockIsLiteral(node, depth) + ? node.children.filter((child): child is Image => child.type === 'image') + : [] +} + +/** Only block containers recurse into image-bearing paragraphs; inline content stays links. */ +export function mobileMarkdownNestedBlocks( + node: RootContent, + depth: number +): { nodes: readonly RootContent[]; depth: number }[] { + if (mobileMarkdownBlockIsLiteral(node, depth)) { + return [] + } + switch (node.type) { + case 'blockquote': + case 'details': + case 'footnoteDefinition': + return [{ nodes: node.children, depth: depth + 1 }] + case 'list': + return node.children.map((item) => ({ nodes: item.children, depth: depth + 1 })) + default: + return [] + } +} + +export function mobileMarkdownImageSources( + root: Root, + accepts: (href: string) => boolean +): string[] { + const sources: string[] = [] + function collect(nodes: readonly RootContent[], depth: number): void { + for (const node of nodes) { + for (const image of mobileMarkdownParagraphImages(node, depth)) { + if (accepts(image.url)) { + sources.push(image.url) + } + } + for (const nested of mobileMarkdownNestedBlocks(node, depth)) { + collect(nested.nodes, nested.depth) + } + } + } + collect(root.children, 0) + return sources +} diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx index f1df5cb06c7..02dd506a8e8 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx @@ -1,3 +1,4 @@ +import { mobileNativeChatMarkdownImageBlock } from './mobile-native-chat-markdown-image-block' import { useCallback, useContext, useEffect, useState } from 'react' import { Image, Pressable, Text, View } from 'react-native' import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection' @@ -28,34 +29,6 @@ import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { nativeChatHostStatusCopy } from './native-chat-notice-copy' import { pressedStyle } from '../../../theme/mobile-theme' -import { routeNativeChatHref } from '../../../../../src/shared/native-chat/native-chat-href-routing' -import { isRuntimePathAbsolute } from '../../../../../src/shared/cross-platform-path' -import { isRasterImagePath } from '../../../../../src/shared/file-preview/file-preview-kind' -import { isKnownRasterImageMimeType } from '../../../../../src/shared/file-preview/raster-image-preview-limits' -import { isSvgFilePath } from '../../../../../src/shared/file-preview/svg-document' - -/** Raster https, data and absolute-path images draw on the phone (paths through the chat's host); anything else stays a link. - * The shell's CSP refuses plain http, and React Native's Image cannot draw SVG. */ -function markdownImageBlock(href: string, alt: string): NativeChatImageRefBlock | null { - const label = alt.trim() ? { alt } : {} - const source = href.trim() - if (/^data:/i.test(source)) { - return isKnownRasterImageMimeType(source.slice(5).split(/[;,]/, 1)[0]) - ? { type: 'image-ref', url: source, ...label } - : null - } - const route = routeNativeChatHref(source) - if (route.kind === 'web') { - return /^https:/i.test(route.url) && !isSvgFilePath(route.url.split(/[?#]/, 1)[0] ?? '') - ? { type: 'image-ref', url: route.url, ...label } - : null - } - return route.kind === 'file' && - isRuntimePathAbsolute(route.pathText) && - isRasterImagePath(route.pathText) - ? { type: 'image-ref', path: route.pathText, ...label } - : null -} export function Prose({ rowKey, @@ -86,7 +59,7 @@ export function Prose({ const t = useMobileTranslation() const renderImage = useCallback( (href: string, alt: string): React.ReactNode => { - const image = markdownImageBlock(href, alt) + const image = mobileNativeChatMarkdownImageBlock(href, alt) return image ? ( ) : null diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-block.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-block.ts new file mode 100644 index 00000000000..666775ff5b1 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-block.ts @@ -0,0 +1,32 @@ +import type { NativeChatImageRefBlock } from '../../../../../src/shared/native-chat/native-chat-types' +import { routeNativeChatHref } from '../../../../../src/shared/native-chat/native-chat-href-routing' +import { isRuntimePathAbsolute } from '../../../../../src/shared/cross-platform-path' +import { isRasterImagePath } from '../../../../../src/shared/file-preview/file-preview-kind' +import { isKnownRasterImageMimeType } from '../../../../../src/shared/file-preview/raster-image-preview-limits' +import { isSvgFilePath } from '../../../../../src/shared/file-preview/svg-document' + +/** Raster https, data and absolute-path images draw on the phone (paths through the chat's host); anything else stays a link. + * The shell's CSP refuses plain http, and React Native's Image cannot draw SVG. */ +export function mobileNativeChatMarkdownImageBlock( + href: string, + alt: string +): NativeChatImageRefBlock | null { + const label = alt.trim() ? { alt } : {} + const source = href.trim() + if (/^data:/i.test(source)) { + return isKnownRasterImageMimeType(source.slice(5).split(/[;,]/, 1)[0]) + ? { type: 'image-ref', url: source, ...label } + : null + } + const route = routeNativeChatHref(source) + if (route.kind === 'web') { + return /^https:/i.test(route.url) && !isSvgFilePath(route.url.split(/[?#]/, 1)[0] ?? '') + ? { type: 'image-ref', url: route.url, ...label } + : null + } + return route.kind === 'file' && + isRuntimePathAbsolute(route.pathText) && + isRasterImagePath(route.pathText) + ? { type: 'image-ref', path: route.pathText, ...label } + : null +} diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-sources.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-sources.ts new file mode 100644 index 00000000000..de9a935e916 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-markdown-image-sources.ts @@ -0,0 +1,35 @@ +import { + isTextBlock, + type NativeChatMessage +} from '../../../../../src/shared/native-chat/native-chat-types' +import { deriveNativeChatRowContent } from '../../../../../src/shared/native-chat/transcript/native-chat-row-content' +import { parseMobileMarkdownTree } from '../../../components/mobile-markdown-tree' +import { protectMobileMarkdownVisualLines } from '../../../components/mobile-markdown-visual-lines' +import { mobileMarkdownImageSources } from '../../../components/mobile-markdown-image-placement' +import { mobileNativeChatMarkdownImageBlock } from './mobile-native-chat-markdown-image-block' + +function sourceReader(visuals: boolean) { + const sources = new WeakMap() + return function imageSources(message: NativeChatMessage): readonly string[] { + const cached = sources.get(message.blocks) + if (cached) { + return cached + } + const images = deriveNativeChatRowContent(message.blocks).prose.flatMap((block) => { + if (!isTextBlock(block)) { + return [] + } + const content = block.text.trim() + const text = visuals ? protectMobileMarkdownVisualLines(content).text : content + return mobileMarkdownImageSources( + parseMobileMarkdownTree(text, false, true), + (href) => mobileNativeChatMarkdownImageBlock(href, '') !== null + ) + }) + sources.set(message.blocks, images) + return images + } +} + +export const mobileNativeChatMarkdownImageSources = sourceReader(false) +export const mobileNativeChatVisualMarkdownImageSources = sourceReader(true) diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-generated-image-answers.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-generated-image-answers.ts new file mode 100644 index 00000000000..65b660f1419 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-generated-image-answers.ts @@ -0,0 +1,37 @@ +import { useContext, useMemo } from 'react' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import type { NativeChatTurnStatus } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-status' +import { nativeChatGeneratedImageAnswers } from '../../../../../src/shared/native-chat/transcript/native-chat-generated-image-answers' +import { MobileNativeChatVisualContext } from '../visual/mobile-native-chat-visual-context' +import { + mobileNativeChatMarkdownImageSources, + mobileNativeChatVisualMarkdownImageSources +} from './mobile-native-chat-markdown-image-sources' + +export function useMobileNativeChatGeneratedImageAnswers( + enabled: boolean, + messages: readonly NativeChatMessage[], + turnKeys: readonly (string | undefined)[], + completedByTurn: Readonly> +): readonly NativeChatMessage[] { + const visuals = useContext(MobileNativeChatVisualContext) + const sources = visuals + ? mobileNativeChatVisualMarkdownImageSources + : mobileNativeChatMarkdownImageSources + return useMemo( + () => + enabled + ? nativeChatGeneratedImageAnswers( + messages, + turnKeys, + new Set( + Object.entries(completedByTurn).flatMap(([key, status]) => + status.workedSeconds != null ? [key] : [] + ) + ), + sources + ) + : messages, + [enabled, messages, turnKeys, completedByTurn, sources] + ) +} diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transcript-rows.test.tsx b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transcript-rows.test.tsx index 4912557f3fa..af6f1bf00d8 100644 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transcript-rows.test.tsx +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transcript-rows.test.tsx @@ -1,3 +1,4 @@ +import { MobileNativeChatVisualContext } from '../visual/mobile-native-chat-visual-context' import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it } from 'vitest' @@ -32,6 +33,131 @@ describe('how the structured lane draws its rows, as desktop does', () => { renderer = null }) + it('renders generated output in the shipping answer list through collapse and expansion', () => { + const generated: NativeChatMessage = { + ...answer('image'), + blocks: [ + { type: 'text' as const, text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref' as const, path: '/tmp/elephant.png' } + ] + } + const messages = [userMessage('u1'), toolRow('work'), answer('final'), generated] + act(() => { + renderer = create( + createElement(Harness, { + messages, + enabled: true, + isWorking: false, + settledTurns: new Map([['u1', { startedAt: 0, workedSeconds: 3 }]]) + }) + ) + }) + const read = () => renderer!.root.findByType(Result).props.disclosure + const final = read().listMessages.find((row: NativeChatMessage) => row.id === 'final')! + expect(final.blocks).toEqual([ + { type: 'text', text: 'Done.' }, + { type: 'image-ref' as const, path: '/tmp/elephant.png' } + ]) + expect(read().resolveRow(2, final).foldedAway).not.toBe(true) + expect(read().resolveRow(1, messages[1]).foldedAway).toBe(true) + act(() => read().onToggleTurn('u1')) + expect( + read().listMessages.flatMap((row: NativeChatMessage) => + row.blocks.filter((block) => block.type === 'image-ref') + ) + ).toEqual([{ type: 'image-ref' as const, path: '/tmp/elephant.png' }]) + expect(read().listMessages.find((row: NativeChatMessage) => row.id === 'final')).toBe(final) + }) + + it('switches the shipping answer projection with visual availability on unchanged rows', () => { + const messages = [ + userMessage('u1'), + { + ...answer('image'), + blocks: [ + { type: 'text' as const, text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref' as const, path: '/tmp/p.png' } + ] + }, + { + ...answer('final'), + blocks: [ + { type: 'text' as const, text: '::orca-visual{file="plot.html" title="![](/tmp/p.png)"}' } + ] + } + ] + const settledTurns = new Map([['u1', { startedAt: 0, workedSeconds: 3 }]]) + const renderVisual = () => null + const update = (visuals: boolean) => { + const tree = createElement( + MobileNativeChatVisualContext.Provider, + { value: visuals ? renderVisual : null }, + createElement(Harness, { messages, enabled: true, isWorking: false, settledTurns }) + ) + act(() => { + if (renderer) { + renderer.update(tree) + } else { + renderer = create(tree) + } + }) + } + const images = () => + renderer!.root + .findByType(Result) + .props.disclosure.listMessages.flatMap((row: NativeChatMessage) => + row.blocks.filter((block) => block.type === 'image-ref') + ) + update(false) + expect(images()).toEqual([]) + update(true) + expect(images()).toEqual([{ type: 'image-ref' as const, path: '/tmp/p.png' }]) + act(() => renderer!.root.findByType(Result).props.disclosure.onToggleTurn('u1')) + expect(images()).toEqual([{ type: 'image-ref' as const, path: '/tmp/p.png' }]) + update(false) + expect(images()).toEqual([]) + }) + + it.each([ + [['# ![](/tmp/p.png)'], true], + [['![](/tmp/p.png)'], false], + [[' ![](/tmp/p.png)'], false], + [['![][p]', '[p]: /tmp/p.png'], true] + ] as const)( + 'keeps output unless independently rendered prose actually embeds it: %j', + (texts, retained) => { + const messages = [ + userMessage('u1'), + { + ...answer('image'), + blocks: [ + { type: 'text' as const, text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref' as const, path: '/tmp/p.png' } + ] + }, + { ...answer('final'), blocks: texts.map((text) => ({ type: 'text' as const, text })) } + ] + act(() => { + renderer = create( + createElement(Harness, { + messages, + enabled: true, + isWorking: false, + settledTurns: new Map([['u1', { startedAt: 0, workedSeconds: 3 }]]) + }) + ) + }) + const final = renderer!.root + .findByType(Result) + .props.disclosure.listMessages.find((row: NativeChatMessage) => row.id === 'final')! + expect( + final.blocks.filter( + (block: NativeChatMessage['blocks'][number]) => block.type === 'image-ref' + ) + ).toEqual(retained ? [{ type: 'image-ref' as const, path: '/tmp/p.png' }] : []) + } + ) + it('folds a settled turn to its answer until the reader opens it, and only offers that where it hides something', () => { const messages = [ userMessage('u1'), diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts index 097d5428f36..cc5f732f880 100644 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts @@ -1,3 +1,4 @@ +import { useMobileNativeChatGeneratedImageAnswers } from './use-mobile-native-chat-generated-image-answers' import { useMobileNativeChatTurnDiffs } from './use-mobile-native-chat-turn-diffs' import type { MobileNativeChatTurnRow } from './use-mobile-native-chat-row-props' import { useCallback, useMemo, useState } from 'react' @@ -99,7 +100,13 @@ export function useMobileNativeChatTurnDisclosure({ liveLine: MobileNativeChatLiveLine | null onToggleReasoning: (key: string) => void } { - const { rows, turnKeys, liveTurnKey, unresolvedRowIds, partialTurnKey } = useMemo(() => { + const { + rows: sourceRows, + turnKeys, + liveTurnKey, + unresolvedRowIds, + partialTurnKey + } = useMemo(() => { if (!enabled) { return { rows: messages, @@ -118,6 +125,23 @@ export function useMobileNativeChatTurnDisclosure({ unresolvedRowIds: membership.unresolvedRowIds } }, [enabled, messages, turnJournal]) + const turnStatuses = useMobileNativeChatTurnStatus({ + turnKeys, + liveTurnKey, + enabled, + isWorking, + workingStartedAt, + settledTurns, + thinking, + scopeKey + }) + const { active, activeTurnKey, completedByTurn } = turnStatuses + const rows = useMobileNativeChatGeneratedImageAnswers( + enabled, + sourceRows, + turnKeys, + completedByTurn + ) const summaries = useMobileNativeChatTurnDiffs(rows, enabled, turnKeys, partialTurnKey) const waiting = useMemo(() => { const ids = enabled @@ -138,23 +162,12 @@ export function useMobileNativeChatTurnDisclosure({ indexById: new Map(rows.map((message, index) => [message.id, index])) } }, [enabled, rows, stopping, turnJournal]) - const turnStatuses = useMobileNativeChatTurnStatus({ - turnKeys, - liveTurnKey, - enabled, - isWorking, - workingStartedAt, - settledTurns, - thinking, - scopeKey - }) const [expandedTurnIds, toggleExpandedTurn] = useScopedOpenKeys(scopeKey) const [expandedReasoning, toggleReasoning] = useScopedOpenKeys(scopeKey) const [openSubagentGroups, toggleSubagentGroup] = useScopedOpenKeys(scopeKey) const [openUserMessages, toggleUserMessage] = useScopedOpenKeys(scopeKey) const bars = useMemo(() => nativeChatTurnBarRows(rows, turnKeys), [rows, turnKeys]) - const { active, activeTurnKey, completedByTurn } = turnStatuses const inLiveWorkingTurn = useCallback( (index: number) => isNativeChatRowInLiveWorkingTurn( diff --git a/src/main/codex/history/journal-views/codex-history-projection.ts b/src/main/codex/history/journal-views/codex-history-projection.ts index e9cb9313daa..9d2e6e4c010 100644 --- a/src/main/codex/history/journal-views/codex-history-projection.ts +++ b/src/main/codex/history/journal-views/codex-history-projection.ts @@ -10,6 +10,7 @@ import type { import { readRecord } from '../../app-server/codex-item-field-readers' import { codexItemRunState } from '../../structured/items/codex-item-run-state' import type { CodexThreadItem } from '../../structured/items/codex-thread-item-identity' +import { generatedImageBlocks } from '../../../../shared/native-chat/native-chat-generated-image' export function preserveSavedHistoryPayload( item: CodexThreadItem, @@ -55,7 +56,7 @@ export function preserveSavedHistoryPayload( item.result == null && item.failure == null ) { - translated = old + translated = { ...old, blocks: generatedImageBlocks(old.blocks) } } if ( old?.kind === 'tool-call' && diff --git a/src/main/codex/history/rollouts/codex-rollout-item-projection.ts b/src/main/codex/history/rollouts/codex-rollout-item-projection.ts index b2d4678e13f..a6f4faffb63 100644 --- a/src/main/codex/history/rollouts/codex-rollout-item-projection.ts +++ b/src/main/codex/history/rollouts/codex-rollout-item-projection.ts @@ -173,6 +173,8 @@ export function codexRolloutItem(value: unknown): CodexThreadItem | null { } else if (type === 'reasoning') { item.summary = raw.summary_text ?? raw.summary item.content = raw.raw_content ?? raw.content + } else if (type === 'imageGeneration') { + item.savedPath = raw.savedPath ?? raw.saved_path } return item } diff --git a/src/main/codex/structured/items/codex-generated-image-answer.test.ts b/src/main/codex/structured/items/codex-generated-image-answer.test.ts new file mode 100644 index 00000000000..298043d6c02 --- /dev/null +++ b/src/main/codex/structured/items/codex-generated-image-answer.test.ts @@ -0,0 +1,89 @@ +import { expect, it } from 'vitest' +import { codexRolloutItem } from '../../history/rollouts/codex-rollout-item-projection' +import { codexImageItemBody } from './codex-image-item-translation' +import { chat, SESSION, THREAD, turn } from '../threads/codex-thread-catch-up-contract-test-fixture' +import { codexNonMessageIdentity } from './codex-thread-item-identity' +import { codexTurnLifecycleIdentity } from '../journal/codex-structured-journal-translation-turns' +import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import { projectStructuredItemsToNativeChat } from '../../../../shared/agent-session/view/structured-agent-session-projection' +import { nativeChatGeneratedImageAnswers } from '../../../../shared/native-chat/transcript/native-chat-generated-image-answers' + +it('retains the saved image from the provider persisted generation record', () => { + const item = codexRolloutItem({ + type: 'ImageGeneration', + id: 'image-1', + status: 'completed', + saved_path: 'C:\\Users\\person\\.codex\\generated_images\\elephant.png', + result: 'A'.repeat(12000) + })! + const body = codexImageItemBody(item) + expect(body.blocks.find((block) => block.type === 'image-ref')).toEqual({ + type: 'image-ref', + path: 'C:\\Users\\person\\.codex\\generated_images\\elephant.png' + }) +}) + +it.each(['complete', 'sparse'])( + 'enriches %s authoritative saved generation once and preserves the result through replay', + async (shape) => { + const c = await chat({ now: 1000 }) + const identity = codexNonMessageIdentity(THREAD, 'turn-1', 'image-1') + const key = agentJournalItemKey(identity) + const turnIdentity = codexTurnLifecycleIdentity(SESSION, 'turn-1') + await c.journal.appendItem( + turnIdentity, + { kind: 'turn', turnId: 'turn-1', state: 'completed', outcome: 'success' }, + { fence: 1, turnScope: { kind: 'thread' } } + ) + await c.journal.appendItem( + identity, + { + kind: 'message', + role: 'assistant', + blocks: [ + { type: 'text', text: 'Generated image' }, + { type: 'image-ref', path: '/tmp/elephant.png' } + ] + }, + { fence: 1, turnScope: { kind: 'turn', turnItemId: agentJournalItemKey(turnIdentity) } } + ) + const supplied = { + ...turn(1), + items: [ + { + type: 'imageGeneration', + id: 'image-1', + ...(shape === 'complete' ? { status: 'completed', savedPath: '/tmp/elephant.png' } : {}) + }, + { type: 'agentMessage', id: 'answer', text: 'Here is your elephant.' } + ] + } + await c.open([], { returnedTurns: [supplied], paginate: false }) + const saved = c.journal.item(key)! + expect(saved.body).toEqual({ + kind: 'message', + role: 'assistant', + blocks: [ + { type: 'text', text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref', path: '/tmp/elephant.png' } + ] + }) + const messages = projectStructuredItemsToNativeChat(c.journal.snapshot().items) + const projected = nativeChatGeneratedImageAnswers( + messages, + messages.map(() => 'turn-1'), + new Set(['turn-1']), + () => [] + ) + expect( + projected.find((row) => + row.blocks.some((block) => block.type === 'text' && block.text === 'Here is your elephant.') + )?.blocks + ).toEqual([ + { type: 'text', text: 'Here is your elephant.' }, + { type: 'image-ref', path: '/tmp/elephant.png' } + ]) + await c.open([], { returnedTurns: [supplied], paginate: false }) + expect(c.journal.item(key)).toEqual(saved) + } +) diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts index 47e6b69266b..5caae49a239 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts @@ -10,7 +10,10 @@ import type { NativeChatSubagentSections } from '../../subagents/native-chat-subagent-sections' +import type { NativeChatMarkdownImageSources } from '../../../../../../shared/native-chat/transcript/native-chat-generated-image-answers' + export type NativeChatTranscriptSlotsInput = { + imageSources?: NativeChatMarkdownImageSources messages: readonly NativeChatMessage[] unresolvedRowIds?: ReadonlySet typography?: NativeChatRowTypography diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts index 860d226a374..cf809b4e2a4 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts @@ -1,4 +1,6 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +import * as imageSources from '../../markdown/native-chat-markdown-image-sources' +import { nativeChatAgentRowWords } from '../../messages/rows/native-chat-message-row-words' import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' @@ -59,6 +61,129 @@ function toolRun(id: string): NativeChatMessage { } describe('transcript slots', () => { + it('shows completed generated output with final prose after settlement and only once when expanded', () => { + const generated: NativeChatMessage = { + ...text('image', ''), + blocks: [ + { type: 'text', text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref', path: '/tmp/elephant.png' } + ] + } + const rows = [ + text('u', 'Generate.', 'user'), + toolRun('work'), + text('answer', 'Your elephant.'), + generated + ] + const turnStatuses = { + active: null, + completedByTurn: { u: { startedAt: 1, thinking: false, workedSeconds: 4 } } + } + for (const expandedTurnKeys of [new Set(), new Set(['u'])]) { + const slots = build(rows, { turnStatuses, expandedTurnKeys }) + const answer = slots.find((slot) => slot.message.id === 'answer')! + expect(answer.drawsMessage).toBe(true) + expect(answer.endsResponse).toBe(true) + const source = slots.find((slot) => slot.message.id === 'image') + if (expandedTurnKeys.has('u')) { + expect(nativeChatAgentRowWords(source!.message)).toBe('Generated image') + expect(source!.endsResponse).toBe(false) + } + expect(answer.message.blocks).toEqual([ + { type: 'text', text: 'Your elephant.' }, + { type: 'image-ref', path: '/tmp/elephant.png' } + ]) + expect( + slots + .filter((slot) => slot.drawsMessage) + .flatMap((slot) => slot.message.blocks.filter((block) => block.type === 'image-ref')) + ).toEqual([{ type: 'image-ref', path: '/tmp/elephant.png' }]) + } + const embedded = build( + [rows[0]!, generated, text('answer', '![]()')], + { turnStatuses } + ) + expect(embedded.find((slot) => slot.message.id === 'answer')?.message.blocks).toEqual([ + { type: 'text', text: '![]()' } + ]) + }) + + it.each([ + ['![](/tmp/p.png)', false], + ['$$\n![](/tmp/p.png)\n$$', true], + ['```md\n![](/tmp/p.png)\n```', true], + ['[picture](/tmp/p.png)', true], + ['Picture', false], + ['', true], + ['``', true] + ])('deduplicates only rendered image embeds in %s', (markdown, retained) => { + const generated: NativeChatMessage = { + ...text('image', ''), + blocks: [ + { type: 'text', text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref', path: '/tmp/p.png' } + ] + } + const slots = build([text('u', 'Generate.', 'user'), generated, text('answer', markdown)], { + turnStatuses: { + active: null, + completedByTurn: { u: { startedAt: 1, thinking: false, workedSeconds: 4 } } + } + }) + expect( + slots + .find((slot) => slot.message.id === 'answer') + ?.message.blocks.filter((block) => block.type === 'image-ref') + ).toEqual(retained ? [{ type: 'image-ref', path: '/tmp/p.png' }] : []) + }) + + it.each([1000, 10000])( + 'keeps completed image responses stable on the production streaming trigger at %i rows', + (count) => { + const generated: NativeChatMessage = { + ...text('image', ''), + blocks: [ + { type: 'text', text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref', path: '/tmp/p.png' } + ] + } + const rows = [ + text('u', 'Generate.', 'user'), + generated, + ...Array.from({ length: count - 3 }, (_, index) => text(`work-${index}`, 'Working.')), + text('answer', 'Finished.'), + text('live', 'Next.', 'user'), + text('stream', 'Streaming.') + ] + const overrides = { + turnStatuses: { + active: null, + completedByTurn: { u: { startedAt: 1, thinking: false, workedSeconds: 4 } } + } + } + const reads = vi.spyOn(imageSources, 'nativeChatMarkdownImageSources') + try { + const first = build(rows, overrides) + expect(reads).toHaveBeenCalledTimes(1) + reads.mockClear() + const next = build([...rows.slice(0, -1), text('stream', 'Streaming more.')], overrides) + // Only live text changed: settled answers need zero source discovery and preserve row identity. + expect(reads).not.toHaveBeenCalled() + expect( + next + .filter((slot) => slot.turnKey === 'u') + .every( + (slot) => + slot.message === + first.find((before) => before.message.id === slot.message.id)?.message + ) + ).toBe(true) + } finally { + reads.mockRestore() + } + } + ) + it('draws the completed plan outside collapsed work', () => { const plan: NativeChatMessage = { ...text('plan', '# Proposed change', 'system'), diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts index 7072134dc54..dbbba160294 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts @@ -9,6 +9,8 @@ import { nativeChatTurnFoldRow } from '../../../../../../shared/native-chat/transcript/native-chat-turn-fold' import { nativeChatRowRendersContent } from '../../../../../../shared/native-chat/transcript/native-chat-row-content' +import { nativeChatGeneratedImageAnswers } from '../../../../../../shared/native-chat/transcript/native-chat-generated-image-answers' +import { nativeChatMarkdownImageSources } from '../../markdown/native-chat-markdown-image-sources' import { estimateNativeChatRowHeight, nativeChatRowContentMetrics @@ -27,7 +29,11 @@ import { type NativeChatSubagentEntriesSlot, type NativeChatSubagentSectionSlot } from '../../subagents/native-chat-subagent-section-slots' -import { nativeChatRowSpeaksOrActs } from '../../../../../../shared/native-chat/native-chat-trailing-run' +import { isGeneratedImageOperation } from '../../../../../../shared/native-chat/native-chat-generated-image' +import { + nativeChatRowRendersProse, + nativeChatRowSpeaksOrActs +} from '../../../../../../shared/native-chat/native-chat-trailing-run' import { nativeChatTranscriptWorkRuns } from '../../tools/runs/native-chat-transcript-work-runs' import { nativeChatAgentRowHasImages, @@ -109,7 +115,8 @@ export function buildNativeChatTranscript( forkPoint: NativeChatSideChatForkPoint | null } { const { - messages, + messages: sourceMessages, + imageSources = nativeChatMarkdownImageSources, unresolvedRowIds, typography, turnKeys, @@ -127,18 +134,24 @@ export function buildNativeChatTranscript( tailRowBelow = false, forkOffer } = input + const settledTurnKeys = new Set( + Object.entries(turnStatuses.completedByTurn) + .filter(([, status]) => status.workedSeconds != null) + .map(([turnKey]) => turnKey) + ) + const messages = nativeChatGeneratedImageAnswers( + sourceMessages, + turnKeys, + settledTurnKeys, + imageSources + ) // Share row rendering facts with fold selection so answer detection agrees with visible prose. const foldRows = messages.map((message, index) => nativeChatTurnFoldRow(message, turnKeys[index], receipts.has(message.id)) ) // Liveness follows the turn frontier, not a call’s stale running flag. - const trailingRunIndex = foldRows.findLastIndex((row, index) => - nativeChatRowSpeaksOrActs(messages[index]!, row.rendersProse, receipts) - ) - const settledTurnKeys = new Set( - Object.entries(turnStatuses.completedByTurn) - .filter(([, status]) => status.workedSeconds != null) - .map(([turnKey]) => turnKey) + const trailingRunIndex = messages.findLastIndex((message) => + nativeChatRowSpeaksOrActs(message, nativeChatRowRendersProse(message), receipts) ) const { foldedRows, foldableTurnKeys } = nativeChatTurnFold({ rows: foldRows, @@ -252,7 +265,10 @@ export function buildNativeChatTranscript( if (!slot.drawsMessage || slot.message.role !== 'assistant') { continue } - if (nativeChatAgentRowWords(slot.message, t).length > 0) { + if ( + !slot.message.blocks.some(isGeneratedImageOperation) && + nativeChatAgentRowWords(slot.message, t).length > 0 + ) { lastWordsByTurn.set(slot.turnKey, slot) } else if (nativeChatAgentRowHasImages(slot.message, t)) { lastImageByTurn.set(slot.turnKey, slot) diff --git a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts index 4f4d3b63536..c738d723e7e 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts @@ -1,4 +1,9 @@ -import { useMemo } from 'react' +import { NativeChatVisualOwnerContext } from '../../media/visuals/native-chat-visual-owner' +import { + nativeChatMarkdownImageSources, + nativeChatVisualMarkdownImageSources +} from '../../markdown/native-chat-markdown-image-sources' +import { useContext, useMemo } from 'react' import { nativeChatLiveLine, type NativeChatLiveLine @@ -28,6 +33,10 @@ export function useNativeChatTranscriptSlots({ forkPoint: NativeChatSideChatForkPoint | null liveLine: NativeChatLiveLine | null } { + const visualOwner = useContext(NativeChatVisualOwnerContext) + const imageSources = visualOwner + ? nativeChatVisualMarkdownImageSources + : nativeChatMarkdownImageSources const { messages, unresolvedRowIds, @@ -82,6 +91,7 @@ export function useNativeChatTranscriptSlots({ const { slots, forkPoint } = useMemo( () => buildNativeChatTranscript({ + imageSources, messages, unresolvedRowIds, typography, @@ -102,6 +112,7 @@ export function useNativeChatTranscriptSlots({ }), [ expandedTurnKeys, + imageSources, forkOffer, isWorking, lifecycleWorking, diff --git a/src/renderer/src/components/native-chat/markdown/native-chat-markdown-image-sources.ts b/src/renderer/src/components/native-chat/markdown/native-chat-markdown-image-sources.ts new file mode 100644 index 00000000000..58a741d7c45 --- /dev/null +++ b/src/renderer/src/components/native-chat/markdown/native-chat-markdown-image-sources.ts @@ -0,0 +1,64 @@ +import { nativeChatVisualRemarkPlugins } from '../media/visuals/native-chat-visual-markdown-syntax' +import { unified } from 'unified' +import remarkParse from 'remark-parse' +import remarkRehype from 'remark-rehype' +import rehypeRaw from 'rehype-raw' +import rehypeSanitize from 'rehype-sanitize' +import type { Root, RootContent } from 'hast' +import { + commentMarkdownSanitizeSchema, + commentMarkdownAllowedTagNames, + commentMarkdownUrlTransform +} from '../../sidebar/comment-markdown-sanitize' +import { remarkUnknownHtmlAsText } from '../../sidebar/comment-markdown-unknown-html-as-text' +import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' +import { deriveNativeChatRowContent } from '../../../../../shared/native-chat/transcript/native-chat-row-content' +import { commentMarkdownRemarkPlugins } from '../../sidebar/comment-markdown-remark-plugins' +import { remarkChatMath } from '../../sidebar/chat-markdown-math' +import { remarkNativeChatFileDestinations } from './native-chat-markdown-file-destinations' + +function sourceReader(visuals: boolean) { + const parser = unified() + .use(remarkParse) + .use(remarkUnknownHtmlAsText(commentMarkdownAllowedTagNames)) + .use(commentMarkdownRemarkPlugins) + .use(remarkChatMath) + .use(visuals ? nativeChatVisualRemarkPlugins('image-source-discovery') : []) + .use(remarkNativeChatFileDestinations) + .use(remarkRehype, { allowDangerousHtml: true }) + .use(rehypeRaw) + .use(rehypeSanitize, commentMarkdownSanitizeSchema) + const sources = new WeakMap() + + return function imageSources(message: NativeChatMessage): readonly string[] { + const cached = sources.get(message.blocks) + if (cached) { + return cached + } + const root = parser.runSync(parser.parse(deriveNativeChatRowContent(message.blocks).markdown)) + const images: string[] = [] + function collect(node: Root | RootContent): void { + if ( + node.type === 'element' && + node.tagName === 'img' && + typeof node.properties.src === 'string' + ) { + const source = commentMarkdownUrlTransform(node.properties.src, 'src', node) + if (source) { + images.push(source) + } + } + if ('children' in node) { + for (const child of node.children) { + collect(child) + } + } + } + collect(root) + sources.set(message.blocks, images) + return images + } +} + +export const nativeChatMarkdownImageSources = sourceReader(false) +export const nativeChatVisualMarkdownImageSources = sourceReader(true) diff --git a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-extension.tsx b/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-extension.tsx index 450717f6f40..cbff57c5cc7 100644 --- a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-extension.tsx +++ b/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-extension.tsx @@ -11,7 +11,7 @@ import type { NativeChatVisualOwner } from './native-chat-visual-owner' import { useNativeChatVisualOwner } from './native-chat-visual-owner' import { NATIVE_CHAT_VISUAL_PLACEHOLDER_PROPERTIES, - remarkNativeChatVisuals + nativeChatVisualRemarkPlugins } from './native-chat-visual-markdown-syntax' type DivProps = ComponentPropsWithoutRef<'div'> & ExtraProps @@ -55,7 +55,7 @@ function createVisualExtension( ) } return { - remarkPlugins: [[remarkNativeChatVisuals, nonce]], + remarkPlugins: nativeChatVisualRemarkPlugins(nonce), extraFlowSyntaxMarkers: [NATIVE_CHAT_VISUAL_DIRECTIVE_MARKER], sanitizeAttributes: { div: [...NATIVE_CHAT_VISUAL_PLACEHOLDER_PROPERTIES] }, components: { div: VisualPlaceholder } diff --git a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.ts b/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.ts index dbf4e6fa593..01a57fbdec8 100644 --- a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.ts +++ b/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.ts @@ -10,7 +10,7 @@ import type { State, TokenizeContext } from 'micromark-util-types' -import type { Processor } from 'unified' +import type { Processor, PluggableList } from 'unified' import { NATIVE_CHAT_VISUAL_DIRECTIVE_MAX_LINE_LENGTH, NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE, @@ -150,3 +150,7 @@ export function remarkNativeChatVisuals(this: Processor, nonce: string): (tree: data.fromMarkdownExtensions = [...(data.fromMarkdownExtensions ?? []), visualFromMarkdown] return (tree) => placeVisuals(tree, true, nonce, { count: 0 }) } + +export function nativeChatVisualRemarkPlugins(nonce: string): PluggableList { + return [[remarkNativeChatVisuals, nonce]] +} diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.test.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.test.tsx index 63e2fa2af28..d91380803ff 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.test.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.test.tsx @@ -1,7 +1,7 @@ import type * as RuntimeRpcCallModule from '@/runtime/rpc/calls/runtime-rpc-call' // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, screen } from '@testing-library/react' +import { act, cleanup, fireEvent, renderHook, screen } from '@testing-library/react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { render } from '../actions/native-chat-tooltip-test-harness' import { useAppStore } from '@/store' @@ -23,6 +23,13 @@ import { buildNativeChatTranscriptSlots } from '../../conversation/slots/native- import { nativeChatSlotCopyText } from '../actions/native-chat-message-copy-text' import { NativeChatAgentMessageCard } from './NativeChatAgentMessageCard' import { MessageRow } from './NativeChatMessageRow' +import type { PropsWithChildren } from 'react' +import { + NativeChatVisualOwnerContext, + type NativeChatVisualOwner +} from '../../media/visuals/native-chat-visual-owner' +import { useNativeChatTranscriptSlots } from '../../conversation/slots/use-native-chat-transcript-slots' +import { nativeChatGeneratedImageAnswers } from '../../../../../../shared/native-chat/transcript/native-chat-generated-image-answers' import { projectStructuredAgentStartItem } from '../../../../../../shared/structured-agent-start-projection' import { projectStructuredQuestionMessages } from '../../../../../../shared/structured-agent-question-projection' import { desktopStructuredTranscript } from '../../conversation/projection/structured-agent-session-message-projection' @@ -426,3 +433,122 @@ it.each(['task', 'mail', 'generic'] as const)( mounted.unmount() } ) + +it('rederives generated attachments when the shipping transcript gains or loses visual ownership', () => { + const messages: NativeChatMessage[] = [ + { + id: 'image', + role: 'assistant', + timestamp: 1, + source: 'transcript', + blocks: [ + { type: 'text', text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref', path: '/tmp/p.png' } + ] + }, + { + id: 'answer', + role: 'assistant', + timestamp: 1, + source: 'transcript', + blocks: [{ type: 'text', text: '::orca-visual{file="plot.html" title="![](/tmp/p.png)"}' }] + } + ] + const input = { + messages, + turnKeys: ['u', 'u'], + liveTurnKey: undefined, + receipts: new Map(), + turnDiffs: new Map(), + expandedTurnKeys: new Set(), + turnStatuses: { + active: null, + completedByTurn: { u: { startedAt: 0, workedSeconds: 3, thinking: false } } + }, + isWorking: false, + lifecycleWorking: false, + line: { tailRow: null, thinking: false } + } + let owner: NativeChatVisualOwner | null = null + function Wrapper({ children }: PropsWithChildren) { + return ( + + {children} + + ) + } + const { result, rerender } = renderHook(() => useNativeChatTranscriptSlots(input), { + wrapper: Wrapper + }) + const attachments = () => + result.current.slots.flatMap((slot) => + slot.kind === 'message' && slot.drawsMessage + ? slot.message.blocks.filter((block) => block.type === 'image-ref') + : [] + ) + expect(attachments()).toEqual([]) + owner = { target: { kind: 'local' }, worktreeId: 'workspace', sessionId: 'session' } + rerender() + expect(attachments()).toEqual([{ type: 'image-ref', path: '/tmp/p.png' }]) + owner = null + rerender() + expect(attachments()).toEqual([]) +}) + +it('renders expanded generated work as a labelled step while the final answer owns its image and controls', () => { + const source: NativeChatMessage = { + id: 'generated', + role: 'assistant', + timestamp: 1, + source: 'transcript', + blocks: [ + { type: 'text', text: 'Generated image', presentation: 'generated-image' }, + { type: 'image-ref', path: '/tmp/p.png' } + ] + } + const answer: NativeChatMessage = { + id: 'answer', + role: 'assistant', + timestamp: 1, + source: 'transcript', + blocks: [{ type: 'text', text: 'Your picture.' }] + } + const rows = nativeChatGeneratedImageAnswers( + [source, answer], + ['u', 'u'], + new Set(['u']), + () => [] + ) + const { container, rerender } = render( + <> + {rows.map((message, index) => ( + + ))} + + ) + expect(screen.getByText('Generated image')).toBeVisible() + expect(container.querySelector('[data-native-chat-message-id="generated"]')).toBeNull() + expect(container.querySelector('[data-native-chat-message-id="answer"]')).not.toBeNull() + expect(screen.getAllByRole('button', { name: 'Copy message' })).toHaveLength(1) + expect(rows[0]!.blocks.some((block) => block.type === 'image-ref')).toBe(false) + expect(rows[1]!.blocks).toEqual([ + { type: 'text', text: 'Your picture.' }, + { type: 'image-ref', path: '/tmp/p.png' } + ]) + rerender( + + ) + expect(screen.getByText('Generated image')).toBeVisible() +}) diff --git a/src/renderer/src/components/sidebar/CommentMarkdown.tsx b/src/renderer/src/components/sidebar/CommentMarkdown.tsx index d8c5ee3a363..3be70d85897 100644 --- a/src/renderer/src/components/sidebar/CommentMarkdown.tsx +++ b/src/renderer/src/components/sidebar/CommentMarkdown.tsx @@ -4,23 +4,21 @@ import { CommentMarkdownMermaidContext, CommentMarkdownMermaidSourceContext } from './comment-markdown-mermaid-policy' +import type { Components, Options as MarkdownOptions } from 'react-markdown' import { - defaultUrlTransform, - type Components, - type Options as MarkdownOptions -} from 'react-markdown' -import remarkGfm from 'remark-gfm' -import remarkBreaks from 'remark-breaks' + commentMarkdownSanitizeSchema, + commentMarkdownAllowedTagNames, + commentMarkdownUrlTransform +} from './comment-markdown-sanitize' +import { commentMarkdownRemarkPlugins as remarkPlugins } from './comment-markdown-remark-plugins' import { remarkChatMath } from './chat-markdown-math' import { copyChatMathSelection } from './chat-markdown-math-selection' -import remarkCjkFriendly from 'remark-cjk-friendly/parseOnly' import rehypeRaw from 'rehype-raw' -import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from 'rehype-sanitize' +import rehypeSanitize, { type Options as SanitizeSchema } from 'rehype-sanitize' import remend from 'remend' import { cn } from '@/lib/class-names' import { selectCommentMarkdownComponents, - isTrustedCompactImageSrc, type CommentMarkdownLinkClickHandler, type DocumentCodeBlockRenderer } from './comment-markdown-element-renderers' @@ -36,9 +34,6 @@ import { useMarkdownBlocks, markdownBlockContent } from './comment-markdown-block-pipeline' -import { GITHUB_CALLOUT_SANITIZE_ATTRIBUTE } from '../../../../shared/github/github-callouts' -import { remarkGitHubCallouts } from '@/lib/markdown/remark-github-callouts' -import { remarkAutolinkLiteralProseBoundary } from '@/lib/markdown/remark-autolink-literal-prose-boundary' import { linkGitHubReferences, type GitHubRepoReference @@ -50,13 +45,6 @@ type MarkdownPlugins = NonNullable type RemarkPlugins = NonNullable type UrlTransform = NonNullable -const commentMarkdownUrlTransform: UrlTransform = (value, key, node) => { - if (key === 'src' && node?.tagName === 'img' && isTrustedCompactImageSrc(value)) { - return value - } - return defaultUrlTransform(value) -} - const commentMarkdownFileUriUrlTransform: UrlTransform = (value, key, node) => { if (key === 'href' && node?.tagName === 'a' && value.trim().toLowerCase().startsWith('file:')) { return value @@ -64,15 +52,6 @@ const commentMarkdownFileUriUrlTransform: UrlTransform = (value, key, node) => { return commentMarkdownUrlTransform(value, key, node) } -// remark-breaks preserves newlines expected by existing plain-text comments; CommonMark otherwise collapses them. -const remarkPlugins = [ - remarkGfm, - remarkCjkFriendly, - remarkAutolinkLiteralProseBoundary, - remarkGitHubCallouts, - remarkBreaks -] - function remarkNativeChatFileLinks( exists: FileLinkExists ): () => (tree: Parameters[0]) => void { @@ -85,48 +64,13 @@ export function remarkGitHubReferences( return () => (tree) => linkGitHubReferences(tree, defaultRepo) } -const commentMarkdownSanitizeSchema: SanitizeSchema = { - ...defaultSchema, - tagNames: [...(defaultSchema.tagNames ?? []), 'details', 'summary', 'sub', 'sup', 'ins', 'kbd'], - attributes: { - ...defaultSchema.attributes, - a: [...(defaultSchema.attributes?.a ?? []), 'href', 'title'], - blockquote: [ - ...(defaultSchema.attributes?.blockquote ?? []), - GITHUB_CALLOUT_SANITIZE_ATTRIBUTE - ], - details: [...(defaultSchema.attributes?.details ?? []), 'open'], - img: [...(defaultSchema.attributes?.img ?? []), 'src', 'alt', 'title', 'width', 'height'], - input: [...(defaultSchema.attributes?.input ?? []), 'type', 'checked', 'disabled'], - code: [ - ...(defaultSchema.attributes?.code ?? []), - ['className', 'language-math', 'math-inline', 'math-display'] - ], - span: [ - ...(defaultSchema.attributes?.span ?? []), - ['className', 'language-math', 'math-inline', 'math-display', 'whitespace-pre-wrap'] - ], - div: [ - ...(defaultSchema.attributes?.div ?? []), - ['className', 'language-math', 'math-inline', 'math-display', 'whitespace-pre-wrap'] - ], - td: [...(defaultSchema.attributes?.td ?? []), 'align'], - th: [...(defaultSchema.attributes?.th ?? []), 'align'] - }, - protocols: { - ...defaultSchema.protocols, - // Allow file links through sanitize for native chat; other surfaces still strip them in URL transformation. - href: [...(defaultSchema.protocols?.href ?? []), 'file'], - src: [...(defaultSchema.protocols?.src ?? []), 'data', 'blob', 'orca-jira-image'] - } -} - -const allowedTagNames: ReadonlySet = new Set( - (commentMarkdownSanitizeSchema.tagNames ?? []).map((name) => name.toLowerCase()) -) // Escape HTML before remark-breaks so newlines inside it still break. -const unknownHtmlAsTextRemarkPlugins = [remarkUnknownHtmlAsText(allowedTagNames), ...remarkPlugins] -const unknownHtmlRendersAsText = (html: string): boolean => htmlRendersAsText(html, allowedTagNames) +const unknownHtmlAsTextRemarkPlugins = [ + remarkUnknownHtmlAsText(commentMarkdownAllowedTagNames), + ...remarkPlugins +] +const unknownHtmlRendersAsText = (html: string): boolean => + htmlRendersAsText(html, commentMarkdownAllowedTagNames) // GitHub comments use raw HTML; parse it then sanitize before rendering. const rehypePlugins: MarkdownPlugins = [rehypeRaw, [rehypeSanitize, commentMarkdownSanitizeSchema]] diff --git a/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx b/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx index 902338fc406..510002e5b21 100644 --- a/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx +++ b/src/renderer/src/components/sidebar/comment-markdown-element-renderers.tsx @@ -1,6 +1,6 @@ import { GitHubBodyImageUrlsContext } from './comment-markdown-github-image-urls' import React from 'react' -import { jiraImageReference } from '../../../../shared/jira/jira-attachment-image' +import { isTrustedCompactImageSrc } from './comment-markdown-sanitize' import type { Components } from 'react-markdown' import { NATIVE_CHAT_FILE_HREF_PREFIX } from '../../../../shared/native-chat/native-chat-href-routing' import { @@ -30,18 +30,6 @@ export type DocumentCodeBlockRenderer = (props: { sourceLine?: number }) => React.JSX.Element -export function isTrustedCompactImageSrc(src: string | undefined): src is string { - if (!src) { - return false - } - const normalized = src.trim().toLowerCase() - return ( - jiraImageReference(src) !== null || - normalized.startsWith('blob:') || - /^data:image\/(?:png|jpe?g|gif|webp);base64,/.test(normalized) - ) -} - function handleMarkdownAnchorClick( event: React.MouseEvent, href: string | undefined, diff --git a/src/renderer/src/components/sidebar/comment-markdown-remark-plugins.ts b/src/renderer/src/components/sidebar/comment-markdown-remark-plugins.ts new file mode 100644 index 00000000000..b56cff81b27 --- /dev/null +++ b/src/renderer/src/components/sidebar/comment-markdown-remark-plugins.ts @@ -0,0 +1,14 @@ +import remarkGfm from 'remark-gfm' +import remarkBreaks from 'remark-breaks' +import remarkCjkFriendly from 'remark-cjk-friendly/parseOnly' +import { remarkGitHubCallouts } from '@/lib/markdown/remark-github-callouts' +import { remarkAutolinkLiteralProseBoundary } from '@/lib/markdown/remark-autolink-literal-prose-boundary' + +// Keep image-source discovery on the same grammar as the rendered prose. +export const commentMarkdownRemarkPlugins = [ + remarkGfm, + remarkCjkFriendly, + remarkAutolinkLiteralProseBoundary, + remarkGitHubCallouts, + remarkBreaks +] diff --git a/src/renderer/src/components/sidebar/comment-markdown-sanitize.ts b/src/renderer/src/components/sidebar/comment-markdown-sanitize.ts new file mode 100644 index 00000000000..3907493a98d --- /dev/null +++ b/src/renderer/src/components/sidebar/comment-markdown-sanitize.ts @@ -0,0 +1,65 @@ +import { defaultSchema, type Options as SanitizeSchema } from 'rehype-sanitize' +import { defaultUrlTransform, type Options as MarkdownOptions } from 'react-markdown' +import { GITHUB_CALLOUT_SANITIZE_ATTRIBUTE } from '../../../../shared/github/github-callouts' +import { jiraImageReference } from '../../../../shared/jira/jira-attachment-image' + +export function isTrustedCompactImageSrc(src: string | undefined): src is string { + if (!src) { + return false + } + const normalized = src.trim().toLowerCase() + return ( + jiraImageReference(src) !== null || + normalized.startsWith('blob:') || + /^data:image\/(?:png|jpe?g|gif|webp);base64,/.test(normalized) + ) +} + +type UrlTransform = NonNullable + +export const commentMarkdownUrlTransform: UrlTransform = (value, key, node) => { + if (key === 'src' && node?.tagName === 'img' && isTrustedCompactImageSrc(value)) { + return value + } + return defaultUrlTransform(value) +} + +export const commentMarkdownSanitizeSchema: SanitizeSchema = { + ...defaultSchema, + tagNames: [...(defaultSchema.tagNames ?? []), 'details', 'summary', 'sub', 'sup', 'ins', 'kbd'], + attributes: { + ...defaultSchema.attributes, + a: [...(defaultSchema.attributes?.a ?? []), 'href', 'title'], + blockquote: [ + ...(defaultSchema.attributes?.blockquote ?? []), + GITHUB_CALLOUT_SANITIZE_ATTRIBUTE + ], + details: [...(defaultSchema.attributes?.details ?? []), 'open'], + img: [...(defaultSchema.attributes?.img ?? []), 'src', 'alt', 'title', 'width', 'height'], + input: [...(defaultSchema.attributes?.input ?? []), 'type', 'checked', 'disabled'], + code: [ + ...(defaultSchema.attributes?.code ?? []), + ['className', 'language-math', 'math-inline', 'math-display'] + ], + span: [ + ...(defaultSchema.attributes?.span ?? []), + ['className', 'language-math', 'math-inline', 'math-display', 'whitespace-pre-wrap'] + ], + div: [ + ...(defaultSchema.attributes?.div ?? []), + ['className', 'language-math', 'math-inline', 'math-display', 'whitespace-pre-wrap'] + ], + td: [...(defaultSchema.attributes?.td ?? []), 'align'], + th: [...(defaultSchema.attributes?.th ?? []), 'align'] + }, + protocols: { + ...defaultSchema.protocols, + // Allow file links through sanitize for native chat; other surfaces still strip them in URL transformation. + href: [...(defaultSchema.protocols?.href ?? []), 'file'], + src: [...(defaultSchema.protocols?.src ?? []), 'data', 'blob', 'orca-jira-image'] + } +} + +export const commentMarkdownAllowedTagNames: ReadonlySet = new Set( + (commentMarkdownSanitizeSchema.tagNames ?? []).map((name) => name.toLowerCase()) +) diff --git a/src/shared/native-chat/native-chat-generated-image.ts b/src/shared/native-chat/native-chat-generated-image.ts index 8ebabd5d0af..d70514b91bf 100644 --- a/src/shared/native-chat/native-chat-generated-image.ts +++ b/src/shared/native-chat/native-chat-generated-image.ts @@ -1,2 +1,28 @@ -/** An image the agent made for the user; the turn fold keeps it visible beside the answer. */ +import type { NativeChatBlock } from './native-chat-types' + export const NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION = 'generated-image' + +/** Record provenance while the producer still knows this is output, rather than an image it read. */ +export function generatedImageBlocks(blocks: NativeChatBlock[]): NativeChatBlock[] { + if (!blocks.some((block) => block.type === 'image-ref')) { + return blocks + } + let marked = false + const result = blocks.map((block) => { + if (block.type !== 'text') { + return block + } + marked = true + return { ...block, presentation: NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION } + }) + return marked + ? result + : [ + { type: 'text', text: '', presentation: NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION }, + ...blocks + ] +} + +export function isGeneratedImageOperation(block: NativeChatBlock): boolean { + return block.type === 'text' && block.presentation === NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION +} diff --git a/src/shared/native-chat/transcript/native-chat-generated-image-answers.test.ts b/src/shared/native-chat/transcript/native-chat-generated-image-answers.test.ts new file mode 100644 index 00000000000..cf9348c8051 --- /dev/null +++ b/src/shared/native-chat/transcript/native-chat-generated-image-answers.test.ts @@ -0,0 +1,198 @@ +import { expect, it } from 'vitest' +import { generatedImageBlocks } from '../native-chat-generated-image' +import type { NativeChatMessage } from '../native-chat-types' +import { nativeChatGeneratedImageAnswers } from './native-chat-generated-image-answers' +import { nativeChatTurnFold, nativeChatTurnFoldRow } from './native-chat-turn-fold' + +const noEmbeds = () => [] +function text( + id: string, + value: string, + role: NativeChatMessage['role'] = 'assistant' +): NativeChatMessage { + return { id, role, blocks: [{ type: 'text', text: value }], timestamp: 1, source: 'transcript' } +} +function generated(id: string, path = '/tmp/elephant.png'): NativeChatMessage { + return { + ...text(id, 'Generated image'), + blocks: generatedImageBlocks([ + { type: 'text', text: 'Generated image' }, + { type: 'image-ref', path } + ]) + } +} +function project(messages: NativeChatMessage[], turnKeys = messages.map(() => 'u')) { + const rows = nativeChatGeneratedImageAnswers(messages, turnKeys, new Set(turnKeys), noEmbeds) + const fold = nativeChatTurnFold({ + rows: rows.map((message, i) => nativeChatTurnFoldRow(message, turnKeys[i], false)), + settledTurnKeys: new Set(turnKeys), + expandedTurnKeys: new Set() + }) + return rows.filter((_, i) => !fold.foldedRows.has(i)) +} + +it.each(['before', 'after'])( + 'keeps generated output with final prose when it arrives %s the prose', + (order) => { + const image = generated('image') + const answer = text('answer', 'Here is your elephant.') + const rows = project([ + text('u', 'Generate an elephant.', 'user'), + text('work', 'Working.'), + ...(order === 'before' ? [image, answer] : [answer, image]) + ]) + expect(rows.map((row) => [row.id, row.blocks])).toEqual([ + ['u', [{ type: 'text', text: 'Generate an elephant.' }]], + [ + 'answer', + [ + { type: 'text', text: 'Here is your elephant.' }, + { type: 'image-ref', path: '/tmp/elephant.png' } + ] + ] + ]) + } +) + +it('retains image-only output beside a failure and preserves the error notice', () => { + const failure = { + ...text('error', 'Codex could not finish. Try again.', 'system'), + blocks: [{ type: 'text' as const, text: 'Codex could not finish. Try again.', tone: 'error' }] + } + const rows = project([text('u', 'Generate.', 'user'), generated('image'), failure]) + expect(rows.map((row) => row.id)).toEqual(['u', 'image', 'error']) + expect(rows[1]!.blocks.filter((block) => block.type === 'image-ref')).toEqual([ + { type: 'image-ref', path: '/tmp/elephant.png' } + ]) + expect(rows[2]).toBe(failure) +}) + +it('keeps send-back outputs in their own answer segments and turn/producer scopes', () => { + const hook = { + ...text('hook', 'Continue.', 'system'), + blocks: [{ type: 'text' as const, text: 'Continue.', presentation: 'hook-sent-back' }] + } + const child = { ...generated('child', '/tmp/child.png'), agentId: 'child' } + const rows = project( + [ + text('u', 'Generate.', 'user'), + generated('first', '/tmp/first.png'), + text('a1', 'First.'), + hook, + child, + generated('second', '/tmp/second.png'), + text('a2', 'Second.'), + text('u2', 'Another turn.', 'user'), + text('a3', 'Other turn.') + ], + ['u', 'u', 'u', 'u', 'u', 'u', 'u', 'u2', 'u2'] + ) + expect(rows.find((row) => row.id === 'a1')?.blocks).toEqual([ + { type: 'text', text: 'First.' }, + { type: 'image-ref', path: '/tmp/first.png' } + ]) + expect(rows.find((row) => row.id === 'a2')?.blocks).toEqual([ + { type: 'text', text: 'Second.' }, + { type: 'image-ref', path: '/tmp/second.png' } + ]) + expect(rows.find((row) => row.id === 'a3')?.blocks).toEqual([ + { type: 'text', text: 'Other turn.' } + ]) + expect( + rows.find((row) => row.id === 'child')?.blocks.filter((block) => block.type === 'image-ref') + ).toEqual([{ type: 'image-ref', path: '/tmp/child.png' }]) +}) + +it('deduplicates Windows and UNC destinations already rendered by Markdown, preserving raw output paths', () => { + const messages = [ + generated('a', 'C:\\Users\\person\\elephant.png'), + generated('b', '\\\\server\\share\\elephant.png'), + generated('c', '/tmp/second.png'), + generated('d', '/tmp/second.png'), + text('answer', 'Pictures.') + ] + const rows = nativeChatGeneratedImageAnswers( + messages, + ['u', 'u', 'u', 'u', 'u'], + new Set(['u']), + () => ['file:///c:/Users/person/elephant.png', 'file://server/share/elephant.png'] + ) + expect(rows[4]!.blocks).toEqual([ + { type: 'text', text: 'Pictures.' }, + { type: 'image-ref', path: '/tmp/second.png' } + ]) + expect( + rows.slice(0, 4).flatMap((row) => row.blocks.filter((block) => block.type === 'image-ref')) + ).toEqual([]) +}) + +it('leaves viewed images as work and preserves untouched messages across another turn update', () => { + const viewed = { + ...text('view', 'Viewed image'), + blocks: [ + { type: 'text' as const, text: 'Viewed image' }, + { type: 'image-ref' as const, path: '/tmp/input.png' } + ] + } + const answer = text('answer', 'Finished.') + expect(project([text('u', 'Inspect.', 'user'), viewed, answer]).map((row) => row.id)).toEqual([ + 'u', + 'answer' + ]) + const messages = [generated('image'), answer, text('other', 'Streaming.')] + const keys = ['u', 'u', 'other'] + const first = nativeChatGeneratedImageAnswers(messages, keys, new Set(['u']), noEmbeds) + const next = nativeChatGeneratedImageAnswers( + [messages[0]!, answer, text('other', 'Streaming more.')], + keys, + new Set(['u']), + noEmbeds + ) + expect(next[0]).toBe(first[0]) + expect(next[1]).toBe(first[1]) + expect(nativeChatGeneratedImageAnswers(messages, keys, new Set(), noEmbeds)).toBe(messages) +}) + +it.each([1000, 10000])( + 'bounds unrelated streaming work at %i loaded rows without reparsing completed answers', + (count) => { + let blockReads = 0 + let parses = 0 + const sources = () => { + parses += 1 + return [] + } + const messages = [ + generated('image'), + ...Array.from({ length: count - 2 }, (_, index) => text(`work-${index}`, 'Working.')), + text('answer', 'Finished.') + ].map((message) => { + const blocks = message.blocks + return Object.defineProperty(message, 'blocks', { + get() { + blockReads += 1 + return blocks + } + }) + }) + const keys = [...messages.map(() => 'u'), 'live'] + const first = nativeChatGeneratedImageAnswers( + [...messages, text('live', 'Streaming.')], + keys, + new Set(['u']), + sources + ) + blockReads = 0 + parses = 0 + const next = nativeChatGeneratedImageAnswers( + [...messages, text('live', 'Streaming more.')], + keys, + new Set(['u']), + sources + ) + // Producing the loaded transcript requires one classification per row; the one generated ref has bounded extra visits. + expect(blockReads).toBeLessThanOrEqual(count + 8) + expect(parses).toBe(0) + expect(next.slice(0, count).every((message, index) => message === first[index])).toBe(true) + } +) diff --git a/src/shared/native-chat/transcript/native-chat-generated-image-answers.ts b/src/shared/native-chat/transcript/native-chat-generated-image-answers.ts new file mode 100644 index 00000000000..8b6f886d6ee --- /dev/null +++ b/src/shared/native-chat/transcript/native-chat-generated-image-answers.ts @@ -0,0 +1,171 @@ +import { normalizeRuntimePathForComparison } from '../../cross-platform-path' +import { routeNativeChatHref } from '../native-chat-href-routing' +import { + isGeneratedImageOperation, + NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION +} from '../native-chat-generated-image' +import type { NativeChatBlock, NativeChatMessage } from '../native-chat-types' +import { nativeChatTurnFoldRow } from './native-chat-turn-fold' + +type Image = Extract +export type NativeChatMarkdownImageSources = (message: NativeChatMessage) => readonly string[] +type Segment = { images: number[]; answer: number | undefined } + +const stripped = new WeakMap() +const projected = new WeakMap< + NativeChatMessage, + { + images: readonly Image[] + sources: NativeChatMarkdownImageSources + synthetic: boolean + message: NativeChatMessage + } +>() + +function imageKey(image: Image): string { + return image.path !== undefined + ? `path:${normalizeRuntimePathForComparison(image.path)}` + : `url:${image.url ?? ''}` +} + +function markdownImageKey(source: string): string { + const route = routeNativeChatHref(source) + return route.kind === 'file' + ? `path:${normalizeRuntimePathForComparison(route.pathText)}` + : `url:${source}` +} + +function withoutGeneratedPreview(message: NativeChatMessage): NativeChatMessage { + let result = stripped.get(message) + if (!result) { + result = { ...message, blocks: message.blocks.filter((block) => block.type !== 'image-ref') } + stripped.set(message, result) + } + return result +} + +function answerWithImages( + answer: NativeChatMessage, + images: readonly Image[], + sources: NativeChatMarkdownImageSources, + synthetic: boolean +): NativeChatMessage { + const cached = projected.get(answer) + if ( + cached && + cached.synthetic === synthetic && + cached.sources === sources && + cached.images.length === images.length && + cached.images.every((image, i) => image === images[i]) + ) { + return cached.message + } + const blocks = synthetic + ? answer.blocks.filter( + (block) => block.type !== 'image-ref' && !isGeneratedImageOperation(block) + ) + : answer.blocks + const shown = new Set([ + ...blocks.filter((block): block is Image => block.type === 'image-ref').map(imageKey), + ...sources(answer).map(markdownImageKey) + ]) + const missing = images.filter((image) => { + const key = imageKey(image) + if (shown.has(key)) { + return false + } + shown.add(key) + return true + }) + const message = + !synthetic && missing.length === 0 + ? answer + : { + ...answer, + blocks: [ + ...blocks, + ...(synthetic + ? [ + { + type: 'text' as const, + text: '', + presentation: NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION + } + ] + : []), + ...missing + ] + } + projected.set(answer, { images, sources, synthetic, message }) + return message +} + +/** Project completed output into its answer without rewriting the journal or moving viewed inputs. */ +export function nativeChatGeneratedImageAnswers( + messages: readonly NativeChatMessage[], + turnKeys: readonly (string | undefined)[], + settledTurnKeys: ReadonlySet, + sources: NativeChatMarkdownImageSources +): readonly NativeChatMessage[] { + let result: NativeChatMessage[] | undefined + const turns = new Map>() + const finish = (segment: Segment) => { + const lastImage = segment.images.at(-1) + if (lastImage === undefined) { + return + } + const answer = segment.answer === undefined ? undefined : messages[segment.answer] + const synthetic = answer?.role !== 'assistant' + const target = synthetic ? lastImage : segment.answer! + const images = segment.images.flatMap((index) => + messages[index]!.blocks.filter((block): block is Image => block.type === 'image-ref') + ) + result ??= [...messages] + for (const index of segment.images) { + result[index] = withoutGeneratedPreview(messages[index]!) + } + result[target] = answerWithImages(messages[target]!, images, sources, synthetic) + } + for (const [index, message] of messages.entries()) { + const turnKey = turnKeys[index] + if (turnKey === undefined || !settledTurnKeys.has(turnKey)) { + continue + } + let producers = turns.get(turnKey) + if (!producers) { + producers = new Map() + turns.set(turnKey, producers) + } + let segment = producers.get(message.agentId) + if (!segment) { + segment = { images: [], answer: undefined } + producers.set(message.agentId, segment) + } + const facts = nativeChatTurnFoldRow(message, turnKey, false) + if (facts.sendsBack) { + finish(segment) + segment = { images: [], answer: undefined } + producers.set(message.agentId, segment) + } + if ( + message.role === 'assistant' && + message.blocks.some(isGeneratedImageOperation) && + message.blocks.some((block) => block.type === 'image-ref') + ) { + segment.images.push(index) + } else if ( + facts.rendersProse && + !facts.outlivesTurn && + !facts.explainsTurn && + (message.role === 'assistant' || (message.role === 'system' && facts.reportsFailure)) + ) { + segment.answer = index + } + } + for (const producers of turns.values()) { + for (const segment of producers.values()) { + finish(segment) + } + } + return result ?? messages +} diff --git a/src/shared/native-chat/transcript/native-chat-turn-fold.ts b/src/shared/native-chat/transcript/native-chat-turn-fold.ts index 3c82fc21b5c..c2c30071d70 100644 --- a/src/shared/native-chat/transcript/native-chat-turn-fold.ts +++ b/src/shared/native-chat/transcript/native-chat-turn-fold.ts @@ -6,9 +6,9 @@ import { AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION } from '../../agent-session/j import { AGENT_SESSION_ORCA_STOP_PRESENTATION } from '../../agent-session/lifecycle/agent-session-orca-stop' import { AGENT_SESSION_TURN_NOTICE_PRESENTATION } from '../../agent-session/journal/agent-session-turn-notice' import { nativeChatRowRendersContent } from './native-chat-row-content' -import { NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION } from '../native-chat-generated-image' import { isStoppedBeforeStartBlock } from '../native-chat-stopped-before-start' import { nativeChatRowRendersProse } from '../native-chat-trailing-run' +import { isGeneratedImageOperation } from '../native-chat-generated-image' import { isBackgroundTaskBlock, isSubagentGroupBlock, @@ -29,7 +29,7 @@ export type NativeChatTurnFoldRow = { outlivesTurn: boolean /** System failures compete as final answers so failed turns end on visible errors. */ reportsFailure: boolean - /** Plans, turn notices and generated images remain visible independently of the agent's answer. */ + /** Plans and turn notices remain visible independently of the agent's answer. */ explainsTurn: boolean /** A Stop hook sent the agent back after it answered, so the prose before this row is an answer too. */ sendsBack: boolean @@ -59,7 +59,8 @@ function deriveTurnFoldRow( return { turnKey, role: message.role, - rendersProse: nativeChatRowRendersProse(message), + rendersProse: + nativeChatRowRendersProse(message) && !message.blocks.some(isGeneratedImageOperation), draws: hasReceipt || message.agentStart === true || nativeChatRowRendersContent(message.blocks), // Use raw roster blocks: empty rosters render no block, making their plain-text twin the sole spawn record. outlivesTurn: @@ -77,17 +78,19 @@ function deriveTurnFoldRow( (block.tone === 'error' || block.failure?.kind === 'usageLimitReached') && block.presentation !== AGENT_SESSION_ORCA_STOP_PRESENTATION ), - explainsTurn: message.blocks.some( - (block) => - block.type === 'text' && - (block.presentation === 'plan-document' || - block.presentation === 'compaction' || - block.presentation === AGENT_SESSION_COMPACTION_SKIPPED_PRESENTATION || - block.presentation === AGENT_SESSION_ORCA_STOP_PRESENTATION || - block.presentation === AGENT_SESSION_TURN_NOTICE_PRESENTATION || - block.presentation === AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION || - block.presentation === NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION) - ), + explainsTurn: + message.blocks.some( + (block) => + block.type === 'text' && + (block.presentation === 'plan-document' || + block.presentation === 'compaction' || + block.presentation === AGENT_SESSION_COMPACTION_SKIPPED_PRESENTATION || + block.presentation === AGENT_SESSION_ORCA_STOP_PRESENTATION || + block.presentation === AGENT_SESSION_TURN_NOTICE_PRESENTATION || + block.presentation === AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION) + ) || + (message.blocks.some(isGeneratedImageOperation) && + message.blocks.some((block) => block.type === 'image-ref')), sendsBack: message.blocks.some( (block) => block.type === 'text' && block.presentation === AGENT_SESSION_HOOK_SENT_BACK_PRESENTATION From ed31974c2d03c72fd12bf00014919bcf450447b9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:30:07 -0800 Subject: [PATCH 06/40] fix: warn before closing a window with a busy native chat (#40953) * fix: warn before closing a window with a busy chat Co-authored-by: Renato Pires * test: cover missing chat status and child-only observations * fix: synchronize the shared close-warning translation keys --------- Co-authored-by: Renato Pires --- .../locale-ko-key-overrides.json | 3 - .../components/TerminalWorkspaceDialogs.tsx | 4 +- .../window-close-running-work.test.ts | 132 +++++++++++++++++- .../terminal/window-close-running-work.ts | 53 +++++-- src/renderer/src/i18n/locales/de.json | 1 - src/renderer/src/i18n/locales/en.json | 2 +- src/renderer/src/i18n/locales/es.json | 1 - src/renderer/src/i18n/locales/fr.json | 1 - src/renderer/src/i18n/locales/ja.json | 1 - src/renderer/src/i18n/locales/ko.json | 1 - src/renderer/src/i18n/locales/pt.json | 1 - src/renderer/src/i18n/locales/ru.json | 1 - src/renderer/src/i18n/locales/tr.json | 1 - src/renderer/src/i18n/locales/zh-Hant.json | 1 - src/renderer/src/i18n/locales/zh.json | 1 - .../languages/protected-copy-keys.json | 2 +- 16 files changed, 178 insertions(+), 28 deletions(-) diff --git a/config/scripts/locale-catalog/locale-ko-key-overrides.json b/config/scripts/locale-catalog/locale-ko-key-overrides.json index 8e46d02ef70..58203344f03 100644 --- a/config/scripts/locale-catalog/locale-ko-key-overrides.json +++ b/config/scripts/locale-catalog/locale-ko-key-overrides.json @@ -446,9 +446,6 @@ "auto.components.Terminal.5b2c1a9e44": { "ko": "agent CLI를 찾지 못했습니다. 하나를 설치하거나 설정에서 기본 agent를 선택하세요." }, - "auto.components.Terminal.7958465754": { - "ko": "실행 중인 프로세스가 있는 terminals이 있습니다. 그래도 창을 닫으시겠습니까?" - }, "auto.components.Terminal.e57db40c11": { "ko": "{{value0}} 실행 명령을 만들 수 없습니다." }, diff --git a/src/renderer/src/components/TerminalWorkspaceDialogs.tsx b/src/renderer/src/components/TerminalWorkspaceDialogs.tsx index f0b4c6166a2..f97709a1b6a 100644 --- a/src/renderer/src/components/TerminalWorkspaceDialogs.tsx +++ b/src/renderer/src/components/TerminalWorkspaceDialogs.tsx @@ -91,8 +91,8 @@ export function TerminalWorkspaceDialogs({ 'A remote host could not be reached, so Orca cannot tell whether work is still running there. Close the window anyway?' ) : t( - 'auto.components.Terminal.7958465754', - 'There are terminals with running processes. Close the window anyway?' + 'auto.components.Terminal.93c2e9d845', + 'There is running work in chats or terminals. Close the window anyway?' )} diff --git a/src/renderer/src/components/terminal/window-close-running-work.test.ts b/src/renderer/src/components/terminal/window-close-running-work.test.ts index a12b70ee650..bda5bf66542 100644 --- a/src/renderer/src/components/terminal/window-close-running-work.test.ts +++ b/src/renderer/src/components/terminal/window-close-running-work.test.ts @@ -1,8 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const { getStateMock, inspectRuntimeTerminalProcessMock } = vi.hoisted(() => ({ +const { getStateMock, inspectRuntimeTerminalProcessMock, getStatusFeedMock } = vi.hoisted(() => ({ getStateMock: vi.fn(), - inspectRuntimeTerminalProcessMock: vi.fn() + inspectRuntimeTerminalProcessMock: vi.fn(), + getStatusFeedMock: vi.fn() })) vi.mock('@/store', () => ({ @@ -13,6 +14,10 @@ vi.mock('@/runtime/hosted-terminals/inspection/runtime-terminal-process-inspecti inspectRuntimeTerminalProcess: inspectRuntimeTerminalProcessMock })) +vi.mock('@/runtime/native-chat/status/structured-agent-session-status-feed', () => ({ + getStructuredAgentSessionStatusFeed: getStatusFeedMock +})) + import { assessWindowCloseRunningWork } from './window-close-running-work' const LOCAL_PTY = 'pty-local' @@ -38,10 +43,33 @@ function setState(ptyIds: string[]): void { settings: { activeRuntimeEnvironmentId: null }, tabsByWorktree: { 'worktree-1': [{ id: 'tab-1' }] }, ptyIdsByTabId: { 'tab-1': ptyIds }, - terminalLayoutsByTabId: {} + terminalLayoutsByTabId: {}, + unifiedTabsByWorktree: {} }) } +function chat(executionHostId: string | undefined = 'local') { + return { + contentType: 'agent-session', + entityId: 'chat-1', + worktreeId: 'worktree-1', + executionHostId + } +} + +function representChat(executionHostId?: string): void { + getStateMock().unifiedTabsByWorktree = { + 'worktree-1': [chat(executionHostId)] + } +} + +function feed(status: string | null | undefined, observation = 'live', extra = {}) { + return { + getSnapshot: () => new Map(status === undefined ? [] : [['chat-1', { status, ...extra }]]), + getSessionObservation: () => observation + } +} + function answerWith(byPtyId: Record): void { inspectRuntimeTerminalProcessMock.mockImplementation((ptyId: string) => ptyId in byPtyId ? Promise.resolve(byPtyId[ptyId]) : new Promise(() => {}) @@ -50,6 +78,7 @@ function answerWith(byPtyId: Record): void { beforeEach(() => { vi.clearAllMocks() + getStatusFeedMock.mockReturnValue(feed(null, 'unverifiable')) }) afterEach(() => { @@ -57,6 +86,103 @@ afterEach(() => { }) describe('assessWindowCloseRunningWork', () => { + it.each(['working', 'attention'])( + 'warns for a live %s chat without a PTY or ownership metadata', + async (status) => { + setState([]) + representChat() + getStatusFeedMock.mockReturnValue(feed(status)) + + await expect(assessWindowCloseRunningWork({ isQuitting: false })).resolves.toEqual({ + kind: 'running' + }) + expect(inspectRuntimeTerminalProcessMock).not.toHaveBeenCalled() + } + ) + + it.each([ + ['working', 'unverifiable', {}], + ['idle', 'live', { hostExecutionOwned: true, children: [{ kind: 'agent', state: 'working' }] }], + ['idle', 'live', { children: [{ kind: 'agent', state: 'unverifiable' }] }], + [null, 'live', {}], + [undefined, 'live', {}] + ])('does not warn for status %s observed as %s', async (status, observation, extra) => { + setState([]) + representChat() + getStatusFeedMock.mockReturnValue(feed(status, observation, extra)) + + await expect(assessWindowCloseRunningWork({ isQuitting: false })).resolves.toEqual({ + kind: 'none' + }) + }) + + it('keeps equal chat IDs separate across hosts and resolves legacy tabs through their workspace owner', async () => { + setState([]) + const state = getStateMock() + state.repos = [{ id: 'repo-1', executionHostId: 'runtime:env-1' }] + state.worktreesByRepo = { + 'repo-1': [{ id: 'worktree-1', repoId: 'repo-1', hostId: 'runtime:env-1' }] + } + state.unifiedTabsByWorktree = { + 'worktree-1': [chat('local'), { ...chat(), executionHostId: undefined }] + } + getStatusFeedMock.mockImplementation((target) => + feed(target.kind === 'environment' && target.environmentId === 'env-1' ? 'working' : 'idle') + ) + + await expect(assessWindowCloseRunningWork({ isQuitting: false })).resolves.toEqual({ + kind: 'running' + }) + }) + + it('does not use a local observation for an unserved SSH chat', async () => { + setState([]) + representChat('ssh:openclaw') + getStatusFeedMock.mockReturnValue(feed('working')) + + await expect(assessWindowCloseRunningWork({ isQuitting: false })).resolves.toEqual({ + kind: 'none' + }) + expect(getStatusFeedMock).not.toHaveBeenCalled() + }) + + it('uses current chat membership, owner and status after terminal probes settle', async () => { + setState([LOCAL_PTY]) + representChat() + getStatusFeedMock.mockReturnValue(feed('working')) + let finishProbe!: (value: unknown) => void + inspectRuntimeTerminalProcessMock.mockReturnValue( + new Promise((resolve) => { + finishProbe = resolve + }) + ) + const assessment = assessWindowCloseRunningWork({ isQuitting: false }) + setState([]) + representChat('runtime:env-2') + getStatusFeedMock.mockImplementation((target) => + feed(target.kind === 'local' ? 'working' : 'idle') + ) + finishProbe({ foregroundProcess: null, hasChildProcesses: false }) + + await expect(assessment).resolves.toEqual({ kind: 'none' }) + expect(getStatusFeedMock).toHaveBeenCalledWith({ kind: 'environment', environmentId: 'env-2' }) + }) + + it('prefers a live chat over unverifiable remote terminal work, but never reads chats on quit', async () => { + setState([SSH_PTY]) + representChat() + answerWith({ [SSH_PTY]: UNVERIFIABLE }) + getStatusFeedMock.mockReturnValue(feed('working')) + + await expect(assessWindowCloseRunningWork({ isQuitting: false })).resolves.toEqual({ + kind: 'running' + }) + getStatusFeedMock.mockClear() + await expect(assessWindowCloseRunningWork({ isQuitting: true })).resolves.toEqual({ + kind: 'unverifiable' + }) + expect(getStatusFeedMock).not.toHaveBeenCalled() + }) // #29916: a paired runtime owns its terminals and keeps them after this client quits. it('does not warn on quit, or probe, for a live process on a paired runtime host', async () => { setState([RUNTIME_PTY, OWNERLESS_RUNTIME_PTY]) diff --git a/src/renderer/src/components/terminal/window-close-running-work.ts b/src/renderer/src/components/terminal/window-close-running-work.ts index c37bde92130..87132d1fbe2 100644 --- a/src/renderer/src/components/terminal/window-close-running-work.ts +++ b/src/renderer/src/components/terminal/window-close-running-work.ts @@ -1,4 +1,9 @@ import { useAppStore } from '@/store' +import { + structuredAgentSessionTargetForHost, + structuredAgentSessionTargetForTab +} from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' +import { getStructuredAgentSessionStatusFeed } from '@/runtime/native-chat/status/structured-agent-session-status-feed' import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' import { collectTabPtyIds } from './running-terminal-close-guard' import { probePtyRunningWork } from './pty-running-work-probe' @@ -12,6 +17,39 @@ export type WindowCloseRunningWork = /** A remote execution host could not be observed, so its work may still be live. */ | { kind: 'unverifiable' } +function hasRunningChat(): boolean { + const state = useAppStore.getState() + const legacyTargets = new Map>() + for (const tabs of Object.values(state.unifiedTabsByWorktree)) { + for (const tab of tabs ?? []) { + if (tab.contentType !== 'agent-session') { + continue + } + let target + if (tab.executionHostId != null) { + target = structuredAgentSessionTargetForHost(tab.executionHostId) + } else { + if (!legacyTargets.has(tab.worktreeId)) { + legacyTargets.set(tab.worktreeId, structuredAgentSessionTargetForTab(state, tab)) + } + target = legacyTargets.get(tab.worktreeId) + } + if (!target) { + continue + } + const feed = getStructuredAgentSessionStatusFeed(target) + const status = feed.getSnapshot().get(tab.entityId)?.status + if ( + feed.getSessionObservation(tab.entityId) === 'live' && + (status === 'working' || status === 'attention') + ) { + return true + } + } + } + return false +} + /** Quit consents to local process termination (#524); warn for SSH relay work that may die after detach grace, including unverifiable hosts. Paired runtimes retain terminals independently (#29916), and local probe failures have no transport ambiguity. */ export async function assessWindowCloseRunningWork(params: { isQuitting: boolean @@ -25,14 +63,13 @@ export async function assessWindowCloseRunningWork(params: { const candidatePtyIds = params.isQuitting ? [...ptyIds].filter((ptyId) => parseAppSshPtyId(ptyId) !== null) : [...ptyIds] - if (candidatePtyIds.length === 0) { - return { kind: 'none' } - } - - const probes = await probePtyRunningWork(candidatePtyIds, { - timeoutMs: WINDOW_CLOSE_PROBE_TIMEOUT_MS - }) - if (probes.some((probe) => probe.verdict === 'live')) { + const probes = candidatePtyIds.length + ? await probePtyRunningWork(candidatePtyIds, { timeoutMs: WINDOW_CLOSE_PROBE_TIMEOUT_MS }) + : [] + if ( + probes.some((probe) => probe.verdict === 'live') || + (!params.isQuitting && hasRunningChat()) + ) { return { kind: 'running' } } if (probes.some((probe) => probe.remote && probe.verdict === 'unverifiable')) { diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 3285025db8a..21b07a8c755 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -3229,7 +3229,6 @@ "Terminal": { "73768427cf": "Schließen", "f82e9f02df": "Abbrechen", - "7958465754": "In einigen Terminals laufen noch Prozesse. Fenster trotzdem schließen?", "b7c1f0a934": "Ein Remote-Host konnte nicht erreicht werden. Daher kann Orca nicht feststellen, ob dort noch Aufgaben ausgeführt werden. Fenster trotzdem schließen?", "2fa9c69ff3": "Fenster schließen?", "cd51e28d8b": "Speichern", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 51c214d5740..960e042c55d 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -3737,7 +3737,7 @@ "Terminal": { "73768427cf": "Close", "f82e9f02df": "Cancel", - "7958465754": "There are terminals with running processes. Close the window anyway?", + "93c2e9d845": "There is running work in chats or terminals. Close the window anyway?", "b7c1f0a934": "A remote host could not be reached, so Orca cannot tell whether work is still running there. Close the window anyway?", "2fa9c69ff3": "Close Window?", "cd51e28d8b": "Save", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 10641f98332..3d6d54aef13 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -2715,7 +2715,6 @@ "Terminal": { "73768427cf": "Cerrar", "f82e9f02df": "Cancelar", - "7958465754": "Hay terminales con procesos en ejecución. ¿Cerrar la ventana de todos modos?", "2fa9c69ff3": "¿Cerrar ventana?", "cd51e28d8b": "Guardar", "0037b21794": "No guardar", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 659a4cec52e..9759252f9a1 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -2985,7 +2985,6 @@ "Terminal": { "73768427cf": "Fermer", "f82e9f02df": "Annuler", - "7958465754": "Des terminaux exécutent des processus. Fermer quand même la fenêtre ?", "2fa9c69ff3": "Fermer la fenêtre ?", "cd51e28d8b": "Enregistrer", "0037b21794": "Ne pas enregistrer", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 8d306274538..c0cb1bc9bf8 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -2667,7 +2667,6 @@ "Terminal": { "73768427cf": "閉じる", "f82e9f02df": "キャンセル", - "7958465754": "プロセスが実行中のターミナルがあります。このままウィンドウを閉じますか?", "2fa9c69ff3": "ウィンドウを閉じますか?", "cd51e28d8b": "保存", "0037b21794": "保存しないでください", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index ab428ee6831..0d9db7946dd 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -2667,7 +2667,6 @@ "Terminal": { "73768427cf": "닫기", "f82e9f02df": "취소", - "7958465754": "실행 중인 프로세스가 있는 terminals이 있습니다. 그래도 창을 닫으시겠습니까?", "2fa9c69ff3": "창을 닫으시겠습니까?", "cd51e28d8b": "저장", "0037b21794": "저장하지 않음", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index de4225c9523..41f783fe0e2 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -19479,7 +19479,6 @@ "Terminal": { "73768427cf": "Fechar", "f82e9f02df": "Cancelar", - "7958465754": "Há terminais com processos em execução. Fechar a janela mesmo assim?", "b7c1f0a934": "Não foi possível alcançar um host remoto, então o Orca não pode saber se ainda há trabalho em execução lá. Fechar a janela mesmo assim?", "2fa9c69ff3": "Fechar Janela?", "cd51e28d8b": "Salvar", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 9c7888fb728..a76addca2aa 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -3310,7 +3310,6 @@ "Terminal": { "73768427cf": "Закрыть", "f82e9f02df": "Отмена", - "7958465754": "В терминалах есть работающие процессы. Всё равно закрыть окно?", "b7c1f0a934": "Нет связи с удалённым компьютером, поэтому Orca не может определить, продолжается ли там работа. Всё равно закрыть окно?", "2fa9c69ff3": "Закрыть окно?", "cd51e28d8b": "Сохранить", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index edcec95b384..755038f7023 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -3198,7 +3198,6 @@ "Terminal": { "73768427cf": "Kapat", "f82e9f02df": "İptal", - "7958465754": "Çalışan işlemleri olan terminaller var. Pencere yine de kapatılsın mı?", "b7c1f0a934": "Bir uzak sunucuya ulaşılamadığı için Orca orada işin hala çalışıp çalışmadığını belirleyemiyor. Pencere yine de kapatılsın mı?", "2fa9c69ff3": "Pencere Kapatılsın mı?", "cd51e28d8b": "Kaydet", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 572851fbf54..9c70d8136e3 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -3159,7 +3159,6 @@ "Terminal": { "73768427cf": "關閉", "f82e9f02df": "取消", - "7958465754": "部分終端機中仍有執行中的行程。仍要關閉視窗嗎?", "b7c1f0a934": "無法連線至遠端主機,因此 Orca 無法判斷該主機上的工作是否仍在執行。仍要關閉視窗嗎?", "2fa9c69ff3": "關閉視窗?", "cd51e28d8b": "儲存", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 3473cd31c27..d9c1da5ab8c 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -2858,7 +2858,6 @@ "Terminal": { "73768427cf": "关闭", "f82e9f02df": "取消", - "7958465754": "本地终端中还有正在运行的进程,是否仍要关闭窗口?", "2fa9c69ff3": "关闭窗口?", "cd51e28d8b": "保存", "0037b21794": "不保存", diff --git a/src/shared/plugins/languages/protected-copy-keys.json b/src/shared/plugins/languages/protected-copy-keys.json index e80e17c9b73..65521cb3d7b 100644 --- a/src/shared/plugins/languages/protected-copy-keys.json +++ b/src/shared/plugins/languages/protected-copy-keys.json @@ -33,7 +33,7 @@ "auto.components.Terminal.46e08bc5c8", "auto.components.Terminal.61ed600d29", "auto.components.Terminal.73768427cf", - "auto.components.Terminal.7958465754", + "auto.components.Terminal.93c2e9d845", "auto.components.Terminal.b7c1f0a934", "auto.components.Terminal.cd51e28d8b", "auto.components.Terminal.f82e9f02df", From 13f6f2a65cea7ce67af379d50b38ba688754a2b6 Mon Sep 17 00:00:00 2001 From: registered2nd <39094401+registered2nd@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:31:56 +0800 Subject: [PATCH 07/40] fix(terminal): re-arm split escape sequences omitted from reveal snapshots (#34272) --- .../hidden-output-restore-snapshot.ts | 6 +- ...connection-gap-escape-continuation.test.ts | 184 ++++++++++++++++++ .../reattach/apply-reattach-payload.ts | 12 +- .../delivery/terminal-stream-position.test.ts | 31 +++ .../delivery/terminal-stream-position.ts | 56 +++++- 5 files changed, 281 insertions(+), 8 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-gap-escape-continuation.test.ts diff --git a/src/renderer/src/components/terminal-pane/pty-connection/output-restore/hidden-output-restore-snapshot.ts b/src/renderer/src/components/terminal-pane/pty-connection/output-restore/hidden-output-restore-snapshot.ts index afd339cc7e6..d72e4acb570 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/output-restore/hidden-output-restore-snapshot.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/output-restore/hidden-output-restore-snapshot.ts @@ -185,7 +185,11 @@ export function bindHiddenOutputRestoreSnapshot(session: ConnectPanePtySession): session.recordRendererOrderedSeq(snapshot) if (typeof snapshot.seq === 'number' && restorePtyId) { // The replay, pending escape tail included, leaves xterm exactly at the snapshot's position. - session.streamPosition.anchor(restorePtyId, snapshot.seq) + session.streamPosition.anchor( + restorePtyId, + snapshot.seq, + snapshot.pendingEscapeTailAnsi ?? '' + ) } recordTerminalOutput(session.pane.terminal) await waitForTerminalReplayWritesParsed(session.pane.terminal) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-gap-escape-continuation.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-gap-escape-continuation.test.ts new file mode 100644 index 00000000000..73ebf69e8b0 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-gap-escape-continuation.test.ts @@ -0,0 +1,184 @@ +import type * as React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { Terminal } from '@xterm/headless' +import { flushAsyncTicks, writeHeadlessTerminal } from '../test-fixtures/pty-connection-test-async' +import { + createMockTransport, + createPane, + createManager, + type ConnectCallbacks, + type MockTransport +} from '../test-fixtures/pty-connection-test-pane-fixtures' +import { buildPaneConnectionDeps } from '../test-fixtures/pty-connection-test-deps' +import type { PtyDataMeta } from '../../pty-transport/delivery/pty-dispatcher' +import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures' +import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' +import { + installTerminalTestGlobals, + restoreTerminalTestGlobals +} from '../test-fixtures/pty-connection-test-environment' +import { connectMockPanePty } from '../test-fixtures/pty-connection-test-connect-mock-pane' + +// #33766: a snapshot seq can cut a queued chunk mid-escape; xterm must not print the escape's tail as text. + +const { scheduleRuntimeGraphSync, shouldSeedCacheTimerOnInitialTitle } = vi.hoisted(() => ({ + scheduleRuntimeGraphSync: vi.fn(), + shouldSeedCacheTimerOnInitialTitle: vi.fn(() => false) +})) + +let mockStoreState: StoreState +let transportFactoryQueue: MockTransport[] = [] + +vi.mock('@/runtime/sync-runtime-graph/graph-sync-scheduler', () => ({ scheduleRuntimeGraphSync })) + +vi.mock('@/store/index', () => ({ + useAppStore: { + getState: () => mockStoreState, + subscribe: () => () => {} + } +})) + +vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { + const { buildAgentStatusModuleMock } = + await import('../test-fixtures/pty-connection-test-environment') + return buildAgentStatusModuleMock(await importOriginal>()) +}) + +vi.mock('../../titles/cache-timer-seeding', () => ({ shouldSeedCacheTimerOnInitialTitle })) + +vi.mock('@/lib/agent-session/accounts/codex/codex-stale-pane-sweep', () => ({ + notifyCodexPaneBoundForStaleSweep: vi.fn() +})) + +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + useCallback: unknown>(fn: T): T => fn + } +}) + +vi.mock('../../pty-transport/ipc/pty-transport', () => ({ + createIpcPtyTransport: vi.fn(() => { + const nextTransport = transportFactoryQueue.shift() + if (!nextTransport) { + throw new Error('No mock transport queued') + } + return nextTransport + }) +})) + +vi.mock('../../pty-transport/delivery/pty-dispatcher', async (importOriginal) => ({ + ...(await importOriginal>()), + getEagerPtyBufferHandle: vi.fn(() => undefined) +})) + +const PTY_ID = 'pty-id' +// Overflow the 2MB client queue so reveal repaints from main's snapshot. +const HIDDEN_FLOOD = 'x'.repeat(2 * 1024 * 1024 + 1) +// Claude Code's DEC 2026 frame start, split after ESC [ by the gap. +const RESUMED = '?2026h> prompt' +const TAIL = '2026h' + +async function connectLocalPane(visible: boolean) { + const transport = createMockTransport(PTY_ID) + const captured: { current: ((data: string, meta?: PtyDataMeta) => void) | null } = { + current: null + } + transport.connect.mockImplementation(async ({ callbacks }: { callbacks?: ConnectCallbacks }) => { + captured.current = callbacks?.onData ?? null + return PTY_ID + }) + transportFactoryQueue.push(transport) + const pane = createPane(1) + const deps = buildPaneConnectionDeps(() => mockStoreState, { + isVisibleRef: { current: visible } + }) + const disposable = await connectMockPanePty(pane, createManager(1), deps) + await flushAsyncTicks(6) + expect(captured.current).not.toBeNull() + return { + disposable, + deliver: (data: string, meta: PtyDataMeta) => captured.current?.(data, meta), + setVisible: (next: boolean) => { + deps.isVisibleRef.current = next + }, + written: () => pane.terminal.write.mock.calls.map(([data]) => String(data)) + } +} + +// What xterm drew from these writes, and whether it parsed the frame's ESC[?2026h whole. +async function paneOf( + chunks: string[] +): Promise<{ prompt: boolean; tail: boolean; synchronized: boolean }> { + const term = new Terminal({ cols: 120, rows: 8, allowProposedApi: true }) + try { + for (const chunk of chunks) { + await writeHeadlessTerminal(term, chunk) + } + const lines: string[] = [] + for (let index = 0; index < term.buffer.active.length; index++) { + lines.push(term.buffer.active.getLine(index)?.translateToString(true) ?? '') + } + const screen = lines.join('\n') + return { + prompt: screen.includes('> prompt'), + tail: screen.includes(TAIL), + synchronized: term.modes.synchronizedOutputMode + } + } finally { + term.dispose() + } +} + +describe('snapshot cut inside an escape (#33766)', () => { + beforeEach(async () => { + vi.resetModules() + vi.clearAllMocks() + transportFactoryQueue = [] + mockStoreState = createInitialStoreState(() => mockStoreState) + await installTerminalTestGlobals() + }) + + afterEach(async () => { + await restoreTerminalTestGlobals() + }) + + async function revealAfterCut(pendingEscapeTailAnsi: string | undefined) { + const frame = `\x1b[${RESUMED}` + // The snapshot's seq lands after the frame's ESC [. + vi.mocked(window.api.pty.getMainBufferSnapshot).mockResolvedValue({ + data: 'history\r\n', + cols: 120, + rows: 40, + seq: HIDDEN_FLOOD.length + 2, + ...(pendingEscapeTailAnsi ? { pendingEscapeTailAnsi } : {}) + }) + const drive = await connectLocalPane(false) + vi.useFakeTimers() + drive.deliver(HIDDEN_FLOOD, { seq: HIDDEN_FLOOD.length, rawLength: HIDDEN_FLOOD.length }) + drive.setVisible(true) + drive.deliver(frame, { seq: HIDDEN_FLOOD.length + frame.length, rawLength: frame.length }) + await vi.advanceTimersByTimeAsync(60_000) + await flushAsyncTicks(20) + drive.disposable.dispose() + vi.useRealTimers() + return paneOf(drive.written()) + } + + it('completes the escape from the cut chunk when the snapshot re-arms none', async () => { + expect(await revealAfterCut(undefined)).toEqual({ + prompt: true, + tail: false, + synchronized: true + }) + }) + + it('keeps the tail that finishes the escape the snapshot re-armed', async () => { + expect(await revealAfterCut('\x1b[')).toEqual({ + prompt: true, + tail: false, + synchronized: true + }) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/reattach/apply-reattach-payload.ts b/src/renderer/src/components/terminal-pane/pty-connection/reattach/apply-reattach-payload.ts index ac9c5853d25..53b5b760eab 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/reattach/apply-reattach-payload.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/reattach/apply-reattach-payload.ts @@ -116,7 +116,11 @@ export function createReattachPayloadHandlers( ) session.recordRendererOrderedSeq({ seq: ctx.connectResult.snapshotSeq }) if (typeof ctx.connectResult.snapshotSeq === 'number') { - session.streamPosition.anchor(ctx.ptyId, ctx.connectResult.snapshotSeq) + session.streamPosition.anchor( + ctx.ptyId, + ctx.connectResult.snapshotSeq, + ctx.connectResult.pendingEscapeTailAnsi ?? '' + ) } session.sendFocusedReattachFocusInAfterReplay(ctx.ptyId, ctx.attemptGeneration) if (ctx.connectResult.coldRestore) { @@ -186,7 +190,11 @@ export function createReattachPayloadHandlers( ) session.recordRendererOrderedSeq(modelSnapshot) if (typeof modelSnapshot.seq === 'number') { - session.streamPosition.anchor(ctx.ptyId, modelSnapshot.seq) + session.streamPosition.anchor( + ctx.ptyId, + modelSnapshot.seq, + modelSnapshot.pendingEscapeTailAnsi ?? '' + ) } session.sendFocusedReattachFocusInAfterReplay(ctx.ptyId, ctx.attemptGeneration) if (ctx.connectResult?.coldRestore) { diff --git a/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.test.ts index 92d5d13cb69..2831b3a5489 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.test.ts @@ -52,6 +52,25 @@ describe('TerminalStreamPosition', () => { ) }) + it('re-arms an escape the replay omitted for a chunk cut at its seq (#33766)', () => { + const position = new TerminalStreamPosition() + position.anchor(PTY, 100, '') + const cut = { startsAtGround: false, boundaryUnknown: true, cutEscapeTail: '\x1b[' } + expect(position.admit(PTY, '>4;2m', at(100, '>4;2m', cut))).toBe('\x1b[>4;2m') + // Only the delivery at the replay's own seq re-arms. + expect(position.admit(PTY, '>4;2m', at(105, '>4;2m', cut))).toBe('>4;2m') + }) + + it('leaves a cut as it is when the replay re-armed a tail or did not say', () => { + const cut = { startsAtGround: false, boundaryUnknown: true, cutEscapeTail: '\x1b[' } + const rearmed = new TerminalStreamPosition() + rearmed.anchor(PTY, 100, '\x1b[') + expect(rearmed.admit(PTY, '>4;2m', at(100, '>4;2m', cut))).toBe('>4;2m') + const unsaid = new TerminalStreamPosition() + unsaid.anchor(PTY, 100) + expect(unsaid.admit(PTY, '>4;2m', at(100, '>4;2m', cut))).toBe('>4;2m') + }) + it('treats bytes after its own reset as a gap, even at the same position', () => { const position = new TerminalStreamPosition() position.anchor(PTY, 100) @@ -167,6 +186,18 @@ describe('streamDeliveryOf', () => { }) }) + it('reports the escape a cut leaves open where its state is known', () => { + const cutTail = (delivered: { data: string; seq: number; midEscape?: true | 'unknown' }) => + streamDeliveryOf('>4;2m', delivered, { seqCountsChars: true }).cutEscapeTail + expect(cutTail({ data: 'ab\x1b[>4;2m', seq: 9 })).toBe('\x1b[') + expect(cutTail({ data: 'ab\x1b[1m>4;2m', seq: 11 })).toBeUndefined() + // A chunk that starts inside an escape is known from the first ESC it cuts off. + expect(cutTail({ data: '2B\x1b[>4;2m', seq: 9, midEscape: true })).toBe('\x1b[') + expect(cutTail({ data: '2B>4;2m', seq: 7, midEscape: 'unknown' })).toBeUndefined() + // Cut-off bytes holding a C1 control are not scanned. + expect(cutTail({ data: '\u009bab\x1b[>4;2m', seq: 10 })).toBeUndefined() + }) + it('never fabricates a position for a suffix of a transformed chunk', () => { expect( streamDeliveryOf('REST', { data: 'nREST', seq: 130, rawLength: 30 }, { seqCountsChars: true }) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.ts b/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.ts index 723568865b2..8bb936fa26b 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-stream-position.ts @@ -1,3 +1,7 @@ +import { + MAX_PARTIAL_ESCAPE_TAIL_LENGTH, + extractPartialEscapeTail +} from '../../../../../../shared/terminal/protocol/escape/terminal-partial-escape-tail' import type { PtyDataMeta } from './pty-dispatcher' const CAN = '\x18' @@ -17,6 +21,11 @@ export type StreamDelivery = { startsAtGround: boolean /** Bytes before this delivery were lost, so main cannot tell whether an escape is open. */ boundaryUnknown: boolean + /** + * For a suffix the renderer cut from a chunk: the incomplete escape the cut-off bytes end in; + * absent when they end at ground or their state is unknown. + */ + cutEscapeTail?: string } /** @@ -35,14 +44,20 @@ export class TerminalStreamPosition { // xterm's parser is known to be at ground: it parsed nothing yet, or Orca's own CAN-led write last. private grounded = true private skippedUnknown = 0 + // The escape tail re-armed by the replay that set `seq` ('' for none); null after stream bytes. + private replayedEscapeTail: string | null = null - /** A replay (snapshot plus its pending escape tail) left xterm exactly at `seq`. */ - anchor(ptyId: string, seq: number): void { + /** + * A replay (snapshot plus its pending escape tail) left xterm exactly at `seq`. A replay passes + * the tail it re-armed, '' for none, so a cut at `seq` can re-arm one its snapshot omitted. + */ + anchor(ptyId: string, seq: number, replayedEscapeTail?: string): void { this.ptyId = ptyId this.seq = seq this.exact = true this.grounded = false this.skippedUnknown = 0 + this.replayedEscapeTail = replayedEscapeTail ?? null } /** The stream's seq domain ended (exit, PTY replacement, a restarted counter); xterm keeps its parser state. */ @@ -89,9 +104,15 @@ export class TerminalStreamPosition { this.anchor(ptyId, endSeq) return wasGrounded ? data : `${CAN}${data}` } else if (this.seq !== null && this.exact && startSeq <= this.seq) { - // An exact continuation, or an overlap with bytes xterm already parsed. + // An exact continuation, or an overlap with bytes xterm already parsed. A snapshot can omit + // the escape open at its seq (#33766); a chunk cut there still holds that escape's start, so + // re-arm it from those bytes as the snapshot's pending tail would have. + const rearm = + startSeq === this.seq && this.replayedEscapeTail === '' + ? (delivery.cutEscapeTail ?? '') + : '' this.anchor(ptyId, endSeq) - return data + return `${rearm}${data}` } const releaseUnknown = delivery.boundaryUnknown && this.skippedUnknown >= MAX_SKIPPED_UNKNOWN_DELIVERIES @@ -143,14 +164,39 @@ export function streamDeliveryOf( // A suffix of a transformed chunk has no exact raw position; never fabricate one. return { startSeq: undefined, endSeq: undefined, startsAtGround: false, boundaryUnknown: true } } + const cutEscapeTail = whole ? '' : escapeTailBeforeCut(data, delivered) return { startSeq: endSeq - (whole ? rawLength : data.length), endSeq, startsAtGround: whole && !delivered.midEscape, - boundaryUnknown: !whole || delivered.midEscape === 'unknown' + boundaryUnknown: !whole || delivered.midEscape === 'unknown', + ...(cutEscapeTail ? { cutEscapeTail } : {}) } } +/** + * The incomplete escape the bytes cut off before `data` end in, '' when none is known. The scan + * starts where the state is known: the chunk's start when main proved it is at ground, otherwise + * the cut-off bytes' first ESC, past which the state no longer depends on what preceded it. + * Cut-off bytes holding an 8-bit C1 control are not scanned; main's boundary tracking does not + * follow C1 either. + */ +function escapeTailBeforeCut( + data: string, + delivered: { data: string; midEscape?: true | 'unknown' } +): string { + if (!delivered.data.endsWith(data)) { + return '' + } + const cutOff = delivered.data.slice(0, delivered.data.length - data.length) + const from = delivered.midEscape ? cutOff.indexOf('\x1b') : 0 + if (from === -1 || /[\u0080-\u009f]/.test(cutOff)) { + return '' + } + const tail = extractPartialEscapeTail(cutOff.slice(from)) + return tail.length > MAX_PARTIAL_ESCAPE_TAIL_LENGTH ? '' : tail +} + /** * Metadata for the kept tail of a chunk whose head was dropped: the tail keeps its true raw range * when chars map 1:1 onto the stream, otherwise it loses its position. Either way it starts after From b13956330e15e79230997c15eb21fefaea3becd5 Mon Sep 17 00:00:00 2001 From: mousepotato03 Date: Thu, 12 Nov 2026 06:32:03 +0900 Subject: [PATCH 08/40] fix(tab-group): keep a window-drag handle when tabs fill the strip (#33988) --- .../components/tab-group/TabGroupPanel.tsx | 5 +- .../e2e/tab-strip-window-drag-handle.spec.ts | 65 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 tests/e2e/tab-strip-window-drag-handle.spec.ts diff --git a/src/renderer/src/components/tab-group/TabGroupPanel.tsx b/src/renderer/src/components/tab-group/TabGroupPanel.tsx index a7c44107a5e..8cd380515eb 100644 --- a/src/renderer/src/components/tab-group/TabGroupPanel.tsx +++ b/src/renderer/src/components/tab-group/TabGroupPanel.tsx @@ -75,6 +75,7 @@ export default function TabGroupPanel({ const t = useTranslate() const rightSidebarOpen = useAppStore((state) => state.rightSidebarOpen) const sidebarOpen = useAppStore((state) => state.sidebarOpen) + const reserveRightTitlebarSpace = reserveClosedExplorerToggleSpace && !rightSidebarOpen const model = useTabGroupWorkspaceModel({ groupId, worktreeId }) const { activeTab, @@ -303,6 +304,8 @@ export default function TabGroupPanel({ /> ) : null}
{tabBar}
+ {/* Why: overflowing tabs eat all strip whitespace; keep a window-drag handle while the right sidebar header is closed. */} + {reserveRightTitlebarSpace ?
: null}
{/* Why: Electron drag hit-test respects no-drag only on DOM descendants, not z-index siblings, so this no-drag spacer keeps the floating right-sidebar toggle + window controls clickable. */} - {reserveClosedExplorerToggleSpace && !rightSidebarOpen ? ( + {reserveRightTitlebarSpace ? (
{ + await orcaPage.setViewportSize({ width: 1280, height: 800 }) + await waitForSessionReady(orcaPage) + const worktreeId = await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + + await orcaPage.evaluate((id) => { + const state = window.__store?.getState() + state?.setSidebarOpen(false) + state?.setRightSidebarOpen(false) + for (let i = 0; i < 14; i++) { + state?.createTab(id, undefined, undefined, { activate: false }) + } + }, worktreeId) + await expect + .poll(() => + orcaPage.evaluate(() => { + const strip = document.querySelector('.terminal-tab-strip') + return strip ? strip.scrollWidth > strip.clientWidth : false + }) + ) + .toBe(true) + + // Terminal focus intentionally turns the strip no-drag until the next click (#6301). + await orcaPage.evaluate(() => { + const active = document.activeElement + if (active instanceof HTMLElement) { + active.blur() + } + }) + await expect(orcaPage.locator('html')).not.toHaveAttribute('data-regular-terminal-input-focused') + + const widestDragRun = await orcaPage.evaluate(() => { + const strip = document.querySelector('[data-tab-group-strip-id]') + if (!strip) { + return 0 + } + const rect = strip.getBoundingClientRect() + const y = rect.top + rect.height / 2 + // Electron applies the nearest ancestor's app region; count only regions the strip owns, + // not the collapsed sidebar header floating over its left edge. + const isDraggable = (x: number): boolean => { + for (let el = document.elementFromPoint(x, y); el; el = el.parentElement) { + const region = getComputedStyle(el).getPropertyValue('-webkit-app-region').trim() + if (region === 'drag' || region === 'no-drag') { + return region === 'drag' && strip.contains(el) + } + } + return false + } + let widest = 0 + let run = 0 + for (let x = Math.ceil(rect.left); x < rect.right; x++) { + run = isDraggable(x) ? run + 1 : 0 + widest = Math.max(widest, run) + } + return widest + }) + expect(widestDragRun).toBeGreaterThanOrEqual(40) +}) From dd263743c322623477e962b119b2cde34e628277 Mon Sep 17 00:00:00 2001 From: Aashish Mahato <145881415+aashish254@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:18:23 +0545 Subject: [PATCH 09/40] fix(startup): seed HOME and distro bins into a packaged launch's env (#23285) --- .../configure-process-packaged-home.test.ts | 75 +++++++++++++++++++ src/main/startup/configure-process.ts | 22 +++++- src/shared/system-cli-install-dirs.ts | 2 +- 3 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 src/main/startup/configure-process-packaged-home.test.ts diff --git a/src/main/startup/configure-process-packaged-home.test.ts b/src/main/startup/configure-process-packaged-home.test.ts new file mode 100644 index 00000000000..46bc60e5dd4 --- /dev/null +++ b/src/main/startup/configure-process-packaged-home.test.ts @@ -0,0 +1,75 @@ +import type * as nodeOs from 'node:os' +import { isAbsolute, join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) + +vi.mock('node:os', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, homedir: homedirMock } +}) + +vi.mock('electron', () => ({ app: { isPackaged: true } })) + +describe('patchPackagedProcessPath without an inherited HOME or PATH (#23214)', () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + const originalHome = process.env.HOME + const originalPath = process.env.PATH + + afterEach(() => { + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + for (const [key, value] of [ + ['HOME', originalHome], + ['PATH', originalPath] + ] as const) { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } + } + homedirMock.mockReset() + }) + + function launchBareLinux(): void { + Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) + delete process.env.HOME + delete process.env.PATH + } + + it('seeds HOME and the distro bins, keeping user bins behind them', async () => { + const { patchPackagedProcessPath } = await import('./configure-process') + launchBareLinux() + homedirMock.mockReturnValue('/home/tester') + + patchPackagedProcessPath() + + expect(process.env.HOME).toBe('/home/tester') + const segments = (process.env.PATH ?? '').split(':') + expect(segments).toContain('/bin') + expect(segments.every((segment) => isAbsolute(segment))).toBe(true) + // #18234: a ~/.local/bin wrapper must not outrank the system gh. + expect(segments.indexOf('/usr/bin')).toBeGreaterThan(-1) + expect(segments.indexOf(join('/home/tester', '.local/bin'))).toBeGreaterThan( + segments.indexOf('/usr/bin') + ) + }) + + it('still seeds the system bins when the account directory cannot be resolved', async () => { + const { patchPackagedProcessPath } = await import('./configure-process') + launchBareLinux() + homedirMock.mockImplementation(() => { + throw new Error('uv_os_homedir returned ENOENT') + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + patchPackagedProcessPath() + + expect(process.env.HOME).toBeUndefined() + const segments = (process.env.PATH ?? '').split(':') + expect(segments).toContain('/usr/bin') + expect(segments.every((segment) => isAbsolute(segment))).toBe(true) + }) +}) diff --git a/src/main/startup/configure-process.ts b/src/main/startup/configure-process.ts index 4185041b493..060967d63f2 100644 --- a/src/main/startup/configure-process.ts +++ b/src/main/startup/configure-process.ts @@ -121,12 +121,26 @@ export function resetDevParentShutdownRequestForTests(): void { devParentShutdownRequested = false } +function resolvePackagedHome(): string { + try { + return homedir() + } catch (error) { + // Unmapped uids with no HOME make homedir() throw; keep seeding system dirs. + console.warn('[startup] Could not resolve the home directory:', error) + return '' + } +} + export function patchPackagedProcessPath(): void { if (!app.isPackaged) { return } - const home = process.env.HOME ?? '' + const home = resolvePackagedHome() + // #23214: desktop-launched AppImages can lack HOME, so spawned CLIs like gh miss their config. + if (process.platform !== 'win32' && !process.env.HOME && home) { + process.env.HOME = home + } // #18234: append generic user bins; prepending ~/.local/bin made a gh/mise wrapper recursively shadow system gh. Shell hydration owns user ordering. const isGenericUserBinDir = (path: string): boolean => process.platform !== 'win32' && @@ -144,7 +158,8 @@ export function patchPackagedProcessPath(): void { appendPaths.push('/snap/bin', '/home/linuxbrew/.linuxbrew/bin') } - appendPaths.push('/nix/var/nix/profiles/default/bin') + // A launch with no inherited PATH otherwise cannot reach package-manager CLIs (#23214). + appendPaths.push('/nix/var/nix/profiles/default/bin', '/usr/bin', '/bin') if (home) { appendPaths.push( @@ -165,7 +180,8 @@ export function patchPackagedProcessPath(): void { } // env-node shebangs require runtime shims; exclude generic user bins so arbitrary wrappers cannot shadow system tools. - for (const path of getVersionManagerBinPaths()) { + // An empty home would seed cwd-relative entries like `.volta/bin`. + for (const path of home ? getVersionManagerBinPaths({ homePath: home }) : []) { if (isWindowsFnmDefaultAliasDir(path)) { appendPaths.push(path) } else if (!isGenericUserBinDir(path)) { diff --git a/src/shared/system-cli-install-dirs.ts b/src/shared/system-cli-install-dirs.ts index c12f4234cad..a41fc30a7d3 100644 --- a/src/shared/system-cli-install-dirs.ts +++ b/src/shared/system-cli-install-dirs.ts @@ -3,7 +3,7 @@ import { join } from 'node:path' /** Lookup-only fallback: prepending system dirs to inherited PATH would reorder the user’s binaries (#18234). * Keep system-block order aligned with patchPackagedProcessPath/POSIX_VERSION_MANAGER_BIN_DIRS; cross-block precedence differs * for ~/.local/bin, which precedes this fallback but follows seeded system dirs. Do not hoist system paths above version managers. - * Omit sbin/~/bin and off-darwin /opt/homebrew; Linuxbrew has its own prefix. Include installer-owned .opencode/.vite-plus (#829) and .grok (#17590) bins. + * Omit sbin/~/bin, /usr/bin, /bin, and off-darwin /opt/homebrew; Linuxbrew has its own prefix. Include installer-owned .opencode/.vite-plus (#829) and .grok (#17590) bins. * Exception: a newly discovered CLI with sibling node may prepend that dir only to its child PATH for runtime pairing (#10932). */ export function getSystemCliInstallDirectories( platform: NodeJS.Platform, From 4f6d182dde7c973dfac321f7f2b760c85f50bfda Mon Sep 17 00:00:00 2001 From: Dat <38579777+stevedat@users.noreply.github.com> Date: Thu, 12 Nov 2026 04:33:30 +0700 Subject: [PATCH 10/40] feat(watcher): ignore mobile/monorepo build folders while keeping Pods live-watched (#28494) --- src/main/git/huge-folder-ignore.ts | 13 ++++++++++++- .../watchers/filesystem-watcher-ignore.ts | 5 ++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/main/git/huge-folder-ignore.ts b/src/main/git/huge-folder-ignore.ts index 15cdb5f03f0..bf003e3d1a7 100644 --- a/src/main/git/huge-folder-ignore.ts +++ b/src/main/git/huge-folder-ignore.ts @@ -5,7 +5,18 @@ import { checkIgnoredPaths } from './source-control/check-ignored-paths' import type { GitRuntimeOptions } from './git-runtime-options' // Offer common dependency/build folders when unignored content saturates status. -const KNOWN_HUGE_FOLDER_NAMES = ['node_modules', '.next', 'dist', 'build', 'target', 'vendor'] +const KNOWN_HUGE_FOLDER_NAMES = [ + 'node_modules', + '.next', + 'dist', + 'build', + 'target', + 'vendor', + '.dart_tool', + '.gradle', + '.turbo', + 'Pods' +] export async function findKnownHugeFolderPathsToIgnore( worktreePath: string, diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-ignore.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-ignore.ts index 1ea8daa7fad..3f125f71142 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-ignore.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-ignore.ts @@ -8,7 +8,10 @@ export const WATCHER_IGNORE_DIRS: string[] = [ '.cache', 'target', '.venv', - '__pycache__' + '__pycache__', + '.dart_tool', + '.gradle', + '.turbo' ] // FSEvents rejects all exclusions above eight paths; regex filtering covers the remaining names at every depth. From 3edfe5e8761acc77c261f09003d31efd0e60df6a Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:33:55 +0000 Subject: [PATCH 11/40] fix(native-chat): keep a launching Codex task's session out of chat and text-generation agents (#41243) --- .../app-server/codex-app-server-session.ts | 3 ++- .../opencode/text-tasks/opencode-text-task.ts | 3 ++- .../managed-provider-process.test.ts | 16 ++++++++++++ .../managed-provider-process.ts | 18 +++++++++---- ...ed-agent-shell-environment-catalog.test.ts | 23 ++++++++++++++++ .../structured-agent-shell-environment.ts | 19 ++++++++------ .../launch/structured-agent-launch-support.ts | 7 +---- .../commit-message-agent-environment.ts | 11 ++++---- .../source-control-agent-launch.test.ts | 26 +++++++++++++++++++ .../source-control-agent-launch.ts | 3 ++- .../startup/parent-agent-session-env.ts | 9 +++++++ src/shared/command-environment.ts | 7 ++++- 12 files changed, 117 insertions(+), 28 deletions(-) diff --git a/src/main/codex/app-server/codex-app-server-session.ts b/src/main/codex/app-server/codex-app-server-session.ts index c41bcfae3f5..29668ce02cb 100644 --- a/src/main/codex/app-server/codex-app-server-session.ts +++ b/src/main/codex/app-server/codex-app-server-session.ts @@ -1,6 +1,7 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { spawnManagedProviderProcess } from '../../provider-process/managed-provider-process' import { resolveProviderChildEnv } from '../../provider-process/provider-process-launch' +import { processEnvWithoutAgentSession } from '../../../shared/agent-launch/startup/parent-agent-session-env' import { stderrIndicatesMissingAppServer } from './codex-app-server-capability-signal' import { withCliRuntimeOnPath } from '../../../shared/node-cli-command-resolution' import { @@ -91,7 +92,7 @@ export async function runCodexAppServerSession( ): Promise { invocation.signal?.throwIfAborted() // Strip CODEX_HOME after the overlay so default-home grants target the real ~/.codex. - const childEnv = resolveProviderChildEnv(invocation, process.env) + const childEnv = resolveProviderChildEnv(invocation, processEnvWithoutAgentSession()) const pairedEnv = invocation.cliPath ? withCliRuntimeOnPath(invocation.cliPath, childEnv) : childEnv diff --git a/src/main/opencode/text-tasks/opencode-text-task.ts b/src/main/opencode/text-tasks/opencode-text-task.ts index 1df8e7ebcfe..e56f2c6ae78 100644 --- a/src/main/opencode/text-tasks/opencode-text-task.ts +++ b/src/main/opencode/text-tasks/opencode-text-task.ts @@ -11,6 +11,7 @@ import { localGenerationLaneKey, setLocalGenerationCancelToken } from '../../text-generation/source-control-generation-lanes' +import { processEnvWithoutAgentSession } from '../../../shared/agent-launch/startup/parent-agent-session-env' import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from '../../text-generation/source-control-generation-limits' import type { InternalTextGenerationResult, @@ -76,7 +77,7 @@ export async function runOpenCodeTextTask(input: { ...common, env: mergeCommandEnvironment(input.target.env, input.plan.env, process.platform) ?? - process.env, + processEnvWithoutAgentSession(), spawn: input.spawnAgent, stop: killSourceControlAgentProcess, shouldExecute: input.shouldExecute diff --git a/src/main/provider-process/managed-provider-process.test.ts b/src/main/provider-process/managed-provider-process.test.ts index 9486c957a49..e0a5adcd123 100644 --- a/src/main/provider-process/managed-provider-process.test.ts +++ b/src/main/provider-process/managed-provider-process.test.ts @@ -112,6 +112,22 @@ describe('managed provider process', () => { } ) + it('keeps the agent session that launched Orca out of a provider child', () => { + vi.stubEnv('CODEX_THREAD_ID', 'parent-thread') + vi.stubEnv('CODEX_WINDOWS_REGISTERED_CORE', '1') + vi.stubEnv('CODEX_HOME', '/home/user/.codex') + try { + const fixture = fakeChild() + launch(fixture) + const env = fixture.spawn.mock.calls[0][0].env + expect(env?.CODEX_THREAD_ID).toBeUndefined() + expect(env?.CODEX_WINDOWS_REGISTERED_CORE).toBeUndefined() + expect(env?.CODEX_HOME).toBe('/home/user/.codex') + } finally { + vi.unstubAllEnvs() + } + }) + it('does not turn a transport close with an existing pid into Claude exit proof', () => { const fixture = fakeChild() const managed = launch(fixture) diff --git a/src/main/provider-process/managed-provider-process.ts b/src/main/provider-process/managed-provider-process.ts index 27ea3fadc04..77ba20b62df 100644 --- a/src/main/provider-process/managed-provider-process.ts +++ b/src/main/provider-process/managed-provider-process.ts @@ -3,6 +3,7 @@ import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import { spawnProcess } from '@orca/process-host' import { RetryableProcessExitProof } from '@orca/process-host/retryable-process-exit-proof' import type { ProviderProcessLaunch } from './provider-process-launch' +import { processEnvWithoutAgentSession } from '../../shared/agent-launch/startup/parent-agent-session-env' import { PROVIDER_BRIEF_SIGTERM_GRACE_MS, PROVIDER_SUPERVISOR_MAX_STOP_MS, @@ -93,11 +94,18 @@ export function spawnManagedProviderProcess( ): ManagedProviderProcess { const platform = options.platform ?? process.platform const closePolicy = options.policy ?? rootOnlyProviderClosePolicy - const spec = createProviderSpawnSpec(launch, options.inheritedEnv ?? process.env, platform, { - // Owner death must request the same close as an explicit provider close. - closeRequest: closePolicy(true).signalSupervisorOnClose ? 'stdin-end-and-sigterm' : 'stdin-end', - ...(options.lifetime ? { lifetime: options.lifetime } : {}) - }) + const spec = createProviderSpawnSpec( + launch, + options.inheritedEnv ?? processEnvWithoutAgentSession(platform), + platform, + { + // Owner death must request the same close as an explicit provider close. + closeRequest: closePolicy(true).signalSupervisorOnClose + ? 'stdin-end-and-sigterm' + : 'stdin-end', + ...(options.lifetime ? { lifetime: options.lifetime } : {}) + } + ) const policy = closePolicy(spec.supervised) if (spec.supervised && !(policy.gracefulExitMs >= PROVIDER_SUPERVISOR_MAX_STOP_MS)) { throw new RangeError( diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts index 87bd9cad5e9..bc51568ddc0 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts @@ -146,3 +146,26 @@ it('retires a producer on effective Refresh before new publication and fences la expect(agentModelCatalogStore.failureDetail(h.fingerprint)).toBe('current failure') expect(h.save).toHaveBeenCalledTimes(writes) }) + +it.each([true, false])( + 'keeps the agent session that launched Orca out of a chat agent environment (inherit shell: %s)', + async (inheritAll) => { + const parentSession = { CODEX_THREAD_ID: 'parent-thread', CODEX_WINDOWS_REGISTERED_CORE: '1' } + const resolvers = createStructuredAgentEnvironmentResolvers({ + prewarm: false, + processEnvironment: { PATH: '/a', CODEX_HOME: '/home/user/.codex', ...parentSession }, + resolveEnvironment: async () => ({ + PATH: '/a', + CODEX_HOME: '/home/user/.codex', + ...parentSession + }), + resolveShellEnvironmentPolicy: () => ({ inheritAll, names: [] }), + resolveAgentLaunchEnv: () => ({ CODEX_CI: 'set-by-user' }) + }) + const env = await resolvers.resolveAgentEnvironment('codex') + expect(env.CODEX_THREAD_ID).toBeUndefined() + expect(env.CODEX_WINDOWS_REGISTERED_CORE).toBeUndefined() + expect(env.CODEX_HOME).toBe('/home/user/.codex') + expect(env.CODEX_CI).toBe('set-by-user') + } +) diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts index e050391680d..366bbd3809d 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts @@ -12,6 +12,7 @@ import { } from '../../../pty/environment/windows-path-segment-merge' import type { GlobalSettings } from '../../../../shared/global-settings-types' import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' +import { stripInheritedAgentSessionEnv } from '../../../../shared/agent-launch/startup/parent-agent-session-env' import { nativeChatShellEnvironmentPolicy, type NativeChatShellEnvironmentPolicy @@ -57,15 +58,17 @@ export function structuredAgentBaseEnvironment(input: { processEnv?: NodeJS.ProcessEnv platform?: NodeJS.Platform }): Record { - if (input.policy.inheritAll) { - return definedEnv(input.shellEnv) - } const platform = input.platform ?? process.platform - return overlayEnvironmentVariables( - definedEnv(input.processEnv ?? process.env), - pickShellVariables(input.shellEnv, input.policy.names, platform), - platform - ) + const base = input.policy.inheritAll + ? definedEnv(input.shellEnv) + : overlayEnvironmentVariables( + definedEnv(input.processEnv ?? process.env), + pickShellVariables(input.shellEnv, input.policy.names, platform), + platform + ) + // The user's per-agent overlay, applied later, owns any deliberate session values. + stripInheritedAgentSessionEnv(base, { platform }) + return base } // Share one capture across launch bursts while discovering newly installed CLIs without restart. diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts index 1276a29f33b..d6c402cb949 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts @@ -33,7 +33,6 @@ import type { AgentSessionAccountHome } from '../../../../shared/agent-session/l import { nativeChatShellEnvironmentPolicy } from '../../../../shared/native-chat/native-chat-shell-environment' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' import { structuredChatUnavailableOnPlatform } from '../../../../shared/agent-session/structured-chat-platform-support' -import { stripInheritedAgentSessionEnv } from '../../../../shared/agent-launch/startup/parent-agent-session-env' export type LaunchEnvironmentSettings = Pick< GlobalSettings, @@ -103,12 +102,8 @@ export async function resolveHostStructuredAgentLaunchEnvironment( agent: string, settings: LaunchEnvironmentSettings ): Promise> { - const inherited = { ...(await resolveHostAgentBaseEnvironment(settings)) } - if (agent === 'claude') { - stripInheritedAgentSessionEnv(inherited) - } return overlayEnvironmentVariables( - inherited, + await resolveHostAgentBaseEnvironment(settings), isTuiAgent(agent) ? resolveTuiAgentLaunchEnv(agent, settings) : undefined, process.platform ) diff --git a/src/main/text-generation/commit-message-agent-environment.ts b/src/main/text-generation/commit-message-agent-environment.ts index 88fa1e3ad12..27ab2272757 100644 --- a/src/main/text-generation/commit-message-agent-environment.ts +++ b/src/main/text-generation/commit-message-agent-environment.ts @@ -2,7 +2,10 @@ import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-au import { applyClaudeEnvPatch } from '../claude-accounts/environment' import { readShellStartupEnvVar } from '../pty/shell-startup/shell-startup-env' import { parseWslUncPath } from '../../shared/wsl-paths' -import { stripInheritedAgentSessionEnv } from '../../shared/agent-launch/startup/parent-agent-session-env' +import { + processEnvWithoutAgentSession, + stripInheritedAgentSessionEnv +} from '../../shared/agent-launch/startup/parent-agent-session-env' export type CommitMessageAgentEnvironmentResolvers = { prepareForCodexLaunch?: ( @@ -22,7 +25,7 @@ export type CommitMessageAgentRuntimeTarget = { function cloneProcessEnv(): Record { const env: Record = {} - for (const [key, value] of Object.entries(process.env)) { + for (const [key, value] of Object.entries(processEnvWithoutAgentSession())) { if (value !== undefined) { env[key] = value } @@ -119,9 +122,7 @@ export async function prepareLocalCommitMessageAgentEnv( return { ok: true } } const base = hostBase ?? cloneProcessEnv() - if (agentId === 'claude') { - stripInheritedAgentSessionEnv(base) - } + stripInheritedAgentSessionEnv(base) if (!resolvers) { return { ok: true, env: base } } diff --git a/src/main/text-generation/source-control-agent-launch.test.ts b/src/main/text-generation/source-control-agent-launch.test.ts index e2c85810c3f..b11df24d2ac 100644 --- a/src/main/text-generation/source-control-agent-launch.test.ts +++ b/src/main/text-generation/source-control-agent-launch.test.ts @@ -64,4 +64,30 @@ process.stdin.on('end', () => setTimeout(() => console.log(prompt.includes('READ lifetime: 'one-shot' }) }) + + it('drops the agent session that launched Orca but keeps assignments in the command', async () => { + const agent = join(folder, 'session-agent.cjs') + writeFileSync( + agent, + `process.stdin.resume() +process.stdin.on('end', () => console.log('Thread ' + (process.env.CODEX_THREAD_ID ?? 'unset') + ', effort ' + process.env.CLAUDE_EFFORT)) +` + ) + vi.stubEnv('CODEX_THREAD_ID', 'parent-thread') + try { + await expect( + generateCommitMessageFromContext( + { branch: 'main', stagedSummary: 'M README.md', stagedPatch: '+test' }, + { + agentId: 'custom', + model: '', + customAgentCommand: `CLAUDE_EFFORT=low "${process.execPath}" "${agent}"` + }, + { kind: 'local', cwd: folder } + ) + ).resolves.toMatchObject({ success: true, message: 'Thread unset, effort low' }) + } finally { + vi.unstubAllEnvs() + } + }) }) diff --git a/src/main/text-generation/source-control-agent-launch.ts b/src/main/text-generation/source-control-agent-launch.ts index 66b97a0ea6a..52c3aa07b0c 100644 --- a/src/main/text-generation/source-control-agent-launch.ts +++ b/src/main/text-generation/source-control-agent-launch.ts @@ -6,6 +6,7 @@ import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quotin import { resolveCliCommand } from '../codex-cli/command' import { wslAwareSpawn } from '../git/runner' import { AGENT_PANE_HOOK_ENV_KEYS } from '../ipc/pty/host-env/spawn-env-keys' +import { processEnvWithoutAgentSession } from '../../shared/agent-launch/startup/parent-agent-session-env' import { spawnSupervisedAgent } from './source-control-supervised-agent-spawn' import type { SourceControlAgentSpawnInput, @@ -51,7 +52,7 @@ export const spawnSourceControlAgent: SpawnSourceControlAgent = (input) => { ? wslDistroForCommand(input.cwd, input.wslDistro) : input.wslDistro // Background agents cannot report hooks against the terminal that launched Orca. - const spawnEnv = { ...(input.env ?? process.env) } + const spawnEnv = { ...(input.env ?? processEnvWithoutAgentSession()) } for (const key of Object.keys(spawnEnv)) { if (BACKGROUND_HOOK_ENV_KEYS.has(process.platform === 'win32' ? key.toUpperCase() : key)) { delete spawnEnv[key] diff --git a/src/shared/agent-launch/startup/parent-agent-session-env.ts b/src/shared/agent-launch/startup/parent-agent-session-env.ts index 5fbe8013be1..444e426dbf4 100644 --- a/src/shared/agent-launch/startup/parent-agent-session-env.ts +++ b/src/shared/agent-launch/startup/parent-agent-session-env.ts @@ -67,3 +67,12 @@ export function stripInheritedAgentSessionEnv( } } } + +/** Orca's own environment as an independent child's base, without the agent session that launched Orca. */ +export function processEnvWithoutAgentSession( + platform: NodeJS.Platform = process.platform +): NodeJS.ProcessEnv { + const env = { ...process.env } + stripInheritedAgentSessionEnv(env, { platform }) + return env +} diff --git a/src/shared/command-environment.ts b/src/shared/command-environment.ts index 971e0fc61b9..60d15dcf87e 100644 --- a/src/shared/command-environment.ts +++ b/src/shared/command-environment.ts @@ -1,3 +1,5 @@ +import { processEnvWithoutAgentSession } from './agent-launch/startup/parent-agent-session-env' + /** Leading assignments are data, never shell expressions. */ export function extractLeadingEnvAssignments(tokens: string[]): { env?: Record @@ -30,7 +32,10 @@ export function mergeCommandEnvironment( if (!overrides) { return base } - const entries = [...Object.entries(base ?? process.env), ...Object.entries(overrides)] + const entries = [ + ...Object.entries(base ?? processEnvWithoutAgentSession()), + ...Object.entries(overrides) + ] // Windows keys share one spelling so guards cannot retain differently cased aliases. return Object.fromEntries( platform === 'win32' ? entries.map(([key, value]) => [key.toUpperCase(), value]) : entries From 53cdcde820756878b703b53d3e94366ddd6cdd1f Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:36:42 -0800 Subject: [PATCH 12/40] fix(source-control): stop cutting the AI commit subject at 72 characters (#41254) --- .../generation/commit-message-generation.test.ts | 15 +++++++++++++++ .../ai/generation/commit-message-generation.ts | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 src/shared/source-control/ai/generation/commit-message-generation.test.ts diff --git a/src/shared/source-control/ai/generation/commit-message-generation.test.ts b/src/shared/source-control/ai/generation/commit-message-generation.test.ts new file mode 100644 index 00000000000..ae6a1ddf0b6 --- /dev/null +++ b/src/shared/source-control/ai/generation/commit-message-generation.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest' +import { splitGeneratedCommitMessage } from './commit-message-generation' + +describe('splitGeneratedCommitMessage', () => { + it('keeps a subject longer than 72 characters intact instead of chopping mid-word', () => { + const subject = + 'feat(find, contribute): offer type-specific add actions on empty local results (#62)' + + expect(splitGeneratedCommitMessage(`${subject}\n\n- Why`)).toEqual({ + subject, + body: '- Why', + message: `${subject}\n\n- Why` + }) + }) +}) diff --git a/src/shared/source-control/ai/generation/commit-message-generation.ts b/src/shared/source-control/ai/generation/commit-message-generation.ts index 16f945fe2b6..837b8aa8b34 100644 --- a/src/shared/source-control/ai/generation/commit-message-generation.ts +++ b/src/shared/source-control/ai/generation/commit-message-generation.ts @@ -68,7 +68,7 @@ export function splitGeneratedCommitMessage(message: string): GeneratedCommitMes const normalized = cleanGeneratedCommitMessage(message) const firstNewline = normalized.indexOf('\n') const subjectLine = firstNewline === -1 ? normalized : normalized.slice(0, firstNewline) - const subject = subjectLine.trim().replace(/[.]+$/g, '').slice(0, 72).trimEnd() + const subject = subjectLine.trim().replace(/[.]+$/g, '').trimEnd() const body = firstNewline === -1 ? '' : normalized.slice(firstNewline + 1).trim() const safeSubject = subject.length > 0 ? subject : 'Update project files' return { From 04bbfd7a3099fd88ae1b20d094afd527f35bb505 Mon Sep 17 00:00:00 2001 From: Nawapat Buakoet Date: Thu, 12 Nov 2026 04:39:38 +0700 Subject: [PATCH 13/40] fix(workspace): name the GitHub link when it cannot be resolved (#24465) --- .../github-submit-resolution.ts | 8 ++- .../github-submit-unresolved-message.test.ts | 55 +++++++++++++++++++ .../github-submit-unresolved-message.ts | 23 ++++++++ src/renderer/src/i18n/locales/en.json | 2 + 4 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 src/renderer/src/hooks/composer-state/github-submit-unresolved-message.test.ts create mode 100644 src/renderer/src/hooks/composer-state/github-submit-unresolved-message.ts diff --git a/src/renderer/src/hooks/composer-state/github-submit-resolution.ts b/src/renderer/src/hooks/composer-state/github-submit-resolution.ts index c0d2f861f80..1848dec8179 100644 --- a/src/renderer/src/hooks/composer-state/github-submit-resolution.ts +++ b/src/renderer/src/hooks/composer-state/github-submit-resolution.ts @@ -51,6 +51,7 @@ import { import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import type { PendingSmartGitHubSubmitResolution } from './source-selection-decisions' import { getGitHubLinkedWorkItemIdentity } from './source-selection-decisions' +import { getUnresolvedSmartGitHubSubmitMessage } from './github-submit-unresolved-message' export function useGitHubSubmitResolution(input: GitHubSubmitResolutionInput) { const { @@ -190,7 +191,12 @@ export function useGitHubSubmitResolution(input: GitHubSubmitResolutionInput) { }) : null if (!item) { - throw new Error('Could not resolve the GitHub item before creating the workspace.') + throw new Error( + getUnresolvedSmartGitHubSubmitMessage( + intent, + !isProjectGroupTarget && Boolean(selectedRepo) && selectedRepoIsGit + ) + ) } const itemIdentity = resolveGitHubWorkItemIdentity(item) diff --git a/src/renderer/src/hooks/composer-state/github-submit-unresolved-message.test.ts b/src/renderer/src/hooks/composer-state/github-submit-unresolved-message.test.ts new file mode 100644 index 00000000000..efd1e84fc80 --- /dev/null +++ b/src/renderer/src/hooks/composer-state/github-submit-unresolved-message.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { + getSmartGitHubSubmitIntent, + type SmartGitHubSubmitIntent +} from '@/lib/work-items/github/smart-github-submit' +import { getUnresolvedSmartGitHubSubmitMessage } from './github-submit-unresolved-message' + +const GENERIC = 'Could not resolve the GitHub item before creating the workspace.' + +function intentFor(input: string): SmartGitHubSubmitIntent { + const intent = getSmartGitHubSubmitIntent(input) + if (!intent) { + throw new Error(`expected a GitHub intent for ${input}`) + } + return intent +} + +describe('getUnresolvedSmartGitHubSubmitMessage', () => { + it('names a pasted github.com issue without the default host', () => { + expect( + getUnresolvedSmartGitHubSubmitMessage( + intentFor('https://github.com/org/app-client-a/issues/144'), + true + ) + ).toBe( + 'Could not load org/app-client-a#144. Check that it exists, that you can access it, and that it belongs to the origin or upstream repository of the selected project.' + ) + }) + + it('keeps the GitHub Enterprise host so the repository is unambiguous', () => { + expect( + getUnresolvedSmartGitHubSubmitMessage( + { + kind: 'link', + host: 'ghe.example.com', + owner: 'org', + repo: 'app', + number: 3, + type: 'issue' + }, + true + ) + ).toContain('Could not load ghe.example.com/org/app#3.') + }) + + it('keeps the generic message for #number lookups', () => { + expect(getUnresolvedSmartGitHubSubmitMessage(intentFor('#7'), true)).toBe(GENERIC) + }) + + it('keeps the generic message when no single git project was looked up', () => { + expect( + getUnresolvedSmartGitHubSubmitMessage(intentFor('https://github.com/org/app/issues/1'), false) + ).toBe(GENERIC) + }) +}) diff --git a/src/renderer/src/hooks/composer-state/github-submit-unresolved-message.ts b/src/renderer/src/hooks/composer-state/github-submit-unresolved-message.ts new file mode 100644 index 00000000000..2f7375bafd6 --- /dev/null +++ b/src/renderer/src/hooks/composer-state/github-submit-unresolved-message.ts @@ -0,0 +1,23 @@ +import { translate } from '@/i18n/i18n' +import type { SmartGitHubSubmitIntent } from '@/lib/work-items/github/smart-github-submit' +import { isDefaultGitHubHost } from '../../../../shared/github/repository-identity-key' + +export function getUnresolvedSmartGitHubSubmitMessage( + intent: SmartGitHubSubmitIntent, + lookedUpInSingleGitProject: boolean +): string { + // Why: link lookups only query origin/upstream, so name the repo the user can act on. + if (intent.kind === 'link' && lookedUpInSingleGitProject) { + const slug = `${intent.owner}/${intent.repo}` + const repository = isDefaultGitHubHost(intent.host) ? slug : `${intent.host}/${slug}` + return translate( + 'auto.hooks.useComposerState.githubLinkUnresolvedForProject', + 'Could not load {{repository}}#{{number}}. Check that it exists, that you can access it, and that it belongs to the origin or upstream repository of the selected project.', + { repository, number: intent.number } + ) + } + return translate( + 'auto.hooks.useComposerState.githubItemUnresolved', + 'Could not resolve the GitHub item before creating the workspace.' + ) +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 960e042c55d..191904f8f9e 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2485,6 +2485,8 @@ "folderWorkspaceCreateFailedTitle": "Folder workspace creation failed", "folderWorkspaceCreateFailedMessage": "The folder workspace could not be created. Check the error details above, then try again.", "setupAgentStartupPolicySaveFailed": "Failed to save setup startup behavior.", + "githubLinkUnresolvedForProject": "Could not load {{repository}}#{{number}}. Check that it exists, that you can access it, and that it belongs to the origin or upstream repository of the selected project.", + "githubItemUnresolved": "Could not resolve the GitHub item before creating the workspace.", "5f3d2c8a1b": "Failed to resolve MR base.", "dropPartiallyAttached_one": "{{failureCount}} of {{count}} item could not be attached.", "dropPartiallyAttached_other": "{{failureCount}} of {{count}} items could not be attached.", From 6f6bb326e2baf30fbe59c4e3fb55fafea97216c2 Mon Sep 17 00:00:00 2001 From: gum798 <33922655+gum798@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:39:45 +0900 Subject: [PATCH 14/40] fix(editor): keep review note cards after an edit removes their lines (#18333) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 서정화 --- ...h-markdown-review-note-positioning.test.ts | 59 +++++++++++++++++++ .../rich-markdown-review-note-positioning.ts | 5 +- 2 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.test.ts diff --git a/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.test.ts b/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.test.ts new file mode 100644 index 00000000000..fdf53ad8f9e --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.test.ts @@ -0,0 +1,59 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Editor } from '@tiptap/core' +import type { DiffComment } from '../../../../../../shared/diff-comment-types' +import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' +import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' +import { measureRichMarkdownReviewNotePositions } from './rich-markdown-review-note-positioning' + +const editors: Editor[] = [] + +afterEach(() => { + for (const editor of editors.splice(0)) { + editor.destroy() + } + vi.restoreAllMocks() +}) + +function makeComment(id: string, lineNumber: number): DiffComment { + return { + id, + worktreeId: 'workspace', + filePath: 'notes.md', + source: 'markdown', + lineNumber, + body: 'Review', + createdAt: 1, + side: 'modified' + } +} + +describe('measureRichMarkdownReviewNotePositions', () => { + it('keeps notes on separator lines or past the end anchored to the block above', () => { + const editor = new Editor({ + element: document.createElement('div'), + extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), + content: 'First\n\nSecond\n\nThird', + contentType: 'markdown' + }) + editors.push(editor) + const blockStarts: number[] = [] + editor.state.doc.forEach((_node, offset) => blockStarts.push(offset + 1)) + vi.spyOn(editor.view, 'coordsAtPos').mockImplementation((pos) => ({ + top: pos, + bottom: pos + 1, + left: 0, + right: 1 + })) + + const topOf = (lineNumber: number) => + measureRichMarkdownReviewNotePositions({ + editor, + container: document.createElement('div'), + markdownComments: [makeComment('note', lineNumber)], + markdownSourceLineOffset: 0 + })[0]?.top + + expect([topOf(3), topOf(4), topOf(9)]).toEqual([blockStarts[1], blockStarts[1], blockStarts[2]]) + }) +}) diff --git a/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.ts b/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.ts index 5692b91e2c9..b385a0d0065 100644 --- a/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.ts +++ b/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-note-positioning.ts @@ -25,9 +25,8 @@ export function measureRichMarkdownReviewNotePositions({ const nextPositions = markdownComments .map((comment): RichMarkdownReviewNotePosition | null => { const bodyLineNumber = Math.max(1, comment.lineNumber - markdownSourceLineOffset) - const block = blocks.find( - (candidate) => candidate.startLine <= bodyLineNumber && bodyLineNumber <= candidate.endLine - ) + // Why: separator lines and lines past a shrunken doc's end match no block; use the one above. + const block = blocks.findLast((candidate) => candidate.startLine <= bodyLineNumber) if (!block) { return null } From 5b1b6fe0569d31073d454c0d01045e441035c23c Mon Sep 17 00:00:00 2001 From: Wooseong Kim <2222333+innocarpe@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:39:52 +0900 Subject: [PATCH 15/40] fix(renderer): preserve spaced and escaped Windows path pastes in rich markdown (#24809) --- .../rich-markdown-terminal-path-paste.test.ts | 35 ++++++++++++ .../rich-markdown-terminal-path-paste.ts | 55 ++++++++----------- 2 files changed, 59 insertions(+), 31 deletions(-) create mode 100644 src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts diff --git a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts new file mode 100644 index 00000000000..d0cf373a07a --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.test.ts @@ -0,0 +1,35 @@ +// @vitest-environment happy-dom +import { describe, expect, it } from 'vitest' +import { shouldPasteTerminalWindowsPathAsPlainText } from './rich-markdown-terminal-path-paste' + +describe('shouldPasteTerminalWindowsPathAsPlainText', () => { + it.each([ + 'Read C:\\Users\\My Project\\README.md before editing.', + 'Review \\\\build-server\\Team Docs\\README.md with the release notes.', + 'Open \\\\server\\README.md before editing.', + 'Open C:\\Users\\My Project\\README.md.', + '"path": "C:\\\\Users\\\\My Project\\\\README.md"' + ])('detects the linked basename in %s', (plainText) => { + expect( + shouldPasteTerminalWindowsPathAsPlainText({ + plainText, + htmlText: 'README.md' + }) + ).toBe(true) + }) + + it.each([ + 'Open C:\\Users\\README.md.backup before editing.', + 'Open C:\\Users\\README.md,backup before editing.', + 'Open C:\\Users\\NOTES.txt and review README.md before editing.', + 'Open C:\\docs\\notes.txt and /README.md before editing.', + 'Install to C:/Tools then read docs/README.md before editing.' + ])('does not match a different basename in %s', (plainText) => { + expect( + shouldPasteTerminalWindowsPathAsPlainText({ + plainText, + htmlText: 'README.md' + }) + ).toBe(false) + }) +}) diff --git a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.ts b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.ts index 52d18033889..b8435319572 100644 --- a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.ts +++ b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-terminal-path-paste.ts @@ -1,43 +1,34 @@ import type { Editor } from '@tiptap/react' +import { escapeRegex } from '../../../../../../shared/string-utils' -type ClipboardAnchor = { - href: string -} - -const WINDOWS_ABSOLUTE_PATH_PATTERN = - /(?:[A-Za-z]:[\\/][^\s<>"|?*\r\n]+|\\\\[^\s\\/:*?"<>|\r\n]+\\[^\s\\/:*?"<>|\r\n]+(?:\\[^\s<>"|?*\r\n]+)*)/g +const WINDOWS_PATH_ROOT = /(?:[A-Za-z]:[\\/]+|\\\\[^\s\\/:*?"<>|]+\\+)/ +// Separator runs cover escaped paths; spaced folders must be backslash-delimited so "C:\App and docs/README.md" stays rich. +const WINDOWS_PATH_FOLDERS = + /(?:[^\s<>:"|?*\\/]+[\\/]+|(?<=\\)[^\s<>:"|?*\\/]*[^\S\r\n][^<>:"|?*\\/\r\n]*\\+)*/.source +const WINDOWS_BASENAME_END = /\.?(?=$|[\s<>:"|?*])/.source function readClipboardText(event: ClipboardEvent, type: string): string { return event.clipboardData?.getData(type) ?? '' } -function getWindowsPathBasename(filePath: string): string { - const normalized = filePath.replaceAll('/', '\\') - const separatorIndex = normalized.lastIndexOf('\\') - return separatorIndex !== -1 ? normalized.slice(separatorIndex + 1) : normalized -} - -function extractClipboardAnchors(html: string): ClipboardAnchor[] { +function extractClipboardAnchorHrefs(html: string): string[] { if (!html || typeof DOMParser === 'undefined') { return [] } const document = new DOMParser().parseFromString(html, 'text/html') - return Array.from(document.querySelectorAll('a[href]'), (anchor) => ({ - href: anchor.getAttribute('href') ?? '' - })) + return Array.from( + document.querySelectorAll('a[href]'), + (anchor) => anchor.getAttribute('href') ?? '' + ) } -function hrefPointsAtPathBasename(href: string, basename: string): boolean { - if (!href || !basename) { - return false - } - +function getHttpHostname(href: string): string | null { try { const url = new URL(href) - return url.protocol.startsWith('http') && url.hostname.toLowerCase() === basename.toLowerCase() + return url.protocol.startsWith('http') ? url.hostname : null } catch { - return false + return null } } @@ -48,20 +39,22 @@ export function shouldPasteTerminalWindowsPathAsPlainText({ plainText: string htmlText: string }): boolean { - const paths = Array.from(plainText.matchAll(WINDOWS_ABSOLUTE_PATH_PATTERN), (match) => match[0]) - if (paths.length === 0) { + if (!WINDOWS_PATH_ROOT.test(plainText)) { return false } - const anchors = extractClipboardAnchors(htmlText) - if (anchors.length === 0) { + const hostnames = new Set( + extractClipboardAnchorHrefs(htmlText).flatMap((href) => getHttpHostname(href) ?? []) + ) + if (hostnames.size === 0) { return false } - return paths.some((filePath) => { - const basename = getWindowsPathBasename(filePath) - return anchors.some((anchor) => hrefPointsAtPathBasename(anchor.href, basename)) - }) + const basenames = Array.from(hostnames, escapeRegex).join('|') + return new RegExp( + `${WINDOWS_PATH_ROOT.source}${WINDOWS_PATH_FOLDERS}(?:${basenames})${WINDOWS_BASENAME_END}`, + 'i' + ).test(plainText) } export function handleRichMarkdownTerminalPathPaste( From 33c73525476a23ae899981930f51cba09f6c0607 Mon Sep 17 00:00:00 2001 From: itigoppo Date: Thu, 12 Nov 2026 06:39:59 +0900 Subject: [PATCH 16/40] fix(github): resolve dotted SSH host aliases for account binding while preserving GHE hosts (#31766) Co-authored-by: itigoppo <1428989+itigoppo@users.noreply.github.com> --- .../account-binding-required-host.test.ts | 66 +++++++++++++++++++ .../github/account-binding-required-host.ts | 14 ++-- 2 files changed, 76 insertions(+), 4 deletions(-) create mode 100644 src/main/github/account-binding-required-host.test.ts diff --git a/src/main/github/account-binding-required-host.test.ts b/src/main/github/account-binding-required-host.test.ts new file mode 100644 index 00000000000..bf4fb4140a7 --- /dev/null +++ b/src/main/github/account-binding-required-host.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from 'vitest' +import { resolveGhAccountRequiredHost } from './account-binding-required-host' + +function repoFor(remoteUrl: string, canonicalHost?: string) { + const host = + canonicalHost ?? + remoteUrl + .replace(/^git@/, '') + .replace(/^ssh:\/\/(?:[^@]+@)?/, '') + .split(/[:/]/)[0] + ?.toLowerCase() ?? + 'github.com' + return { + path: '/repos/sample-app', + connectionId: null, + gitRemoteIdentity: { + canonicalKey: `${host}/example/sample-app`, + remoteUrl + } + } +} + +describe('resolveGhAccountRequiredHost', () => { + it('keeps a dotted enterprise host literal unless ssh config points it at github.com', async () => { + for (const resolveAlias of [ + async () => ({ hostname: '10.0.0.5' }), + async () => ({ hostname: null }), + async () => { + throw new Error('ssh -G failed') + } + ]) { + await expect( + resolveGhAccountRequiredHost( + repoFor('git@ghe.example.com:example/sample-app.git'), + {}, + resolveAlias + ) + ).resolves.toBe('ghe.example.com') + } + }) + + it('filters a dotted alias that resolves to github.com to github.com', async () => { + const resolveAlias = vi.fn(async () => ({ hostname: 'github.com' })) + await expect( + resolveGhAccountRequiredHost( + repoFor('git@work.github.com:example/sample-app.git'), + {}, + resolveAlias + ) + ).resolves.toBe('github.com') + expect(resolveAlias).toHaveBeenCalledWith('work.github.com', { + repoPath: '/repos/sample-app', + connectionId: null + }) + }) + + it('expands an SCP alias whose path has a leading slash', async () => { + await expect( + resolveGhAccountRequiredHost( + repoFor('git@github-work:/example/sample-app.git', 'github-work'), + {}, + async () => ({ hostname: 'github.com' }) + ) + ).resolves.toBe('github.com') + }) +}) diff --git a/src/main/github/account-binding-required-host.ts b/src/main/github/account-binding-required-host.ts index ddc1d35dc51..a027dc750a7 100644 --- a/src/main/github/account-binding-required-host.ts +++ b/src/main/github/account-binding-required-host.ts @@ -25,12 +25,12 @@ export async function resolveGhAccountRequiredHost( resolveAlias: SshAliasHostnameResolver = resolveSshConfigHostname ): Promise { const host = githubHostFromIdentityKey(repo.gitRemoteIdentity?.canonicalKey) - // Why: only SSH transport reads ~/.ssh/config; a dotless HTTPS host is literal. + // Why: only SSH transport reads ~/.ssh/config; an HTTPS host is literal. const remoteUrl = repo.gitRemoteIdentity?.remoteUrl ?? '' - if (!host || !isUnresolvedSshHostAlias(host) || !remoteUrlUsesSshTransport(remoteUrl)) { + if (!host || host === 'github.com' || !remoteUrlUsesSshTransport(remoteUrl)) { return host } - // Expand SSH aliases in the runtime that runs gh; aliases themselves are not gh login hosts. + // Expand SSH aliases in the runtime that runs gh; aliases are not gh login hosts. const context: SshConfigResolutionContext = { repoPath: repo.path, connectionId: repo.connectionId ?? null, @@ -39,7 +39,13 @@ export async function resolveGhAccountRequiredHost( // Why raw: the canonical key is lowercased, but OpenSSH matches Host patterns case-sensitively. const alias = rawSshTransportHost(remoteUrl) ?? host const resolved = await resolveAlias(alias, context).catch(() => null) - const hostname = resolved?.hostname?.trim().toLowerCase() + const expanded = resolved?.hostname?.trim().toLowerCase() + // Why: a dotted host is its own gh login host (a GHE HostName may be an IP) unless it aliases github.com. + const hostname = + isUnresolvedSshHostAlias(host) || + (expanded && foldComparableGitHubHost(expanded) === 'github.com') + ? expanded + : host if (!hostname || isUnresolvedSshHostAlias(hostname)) { return undefined } From a028c2e3c5189f5da98e808c95b96432b7f1f670 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:40:08 -0800 Subject: [PATCH 17/40] fix(terminal): keep word motion only for the US Option layer on B/F/D (#41255) --- .../terminal-option-shortcut-policy.test.ts | 44 +++++++++++++++++++ .../terminal-option-shortcut-policy.ts | 31 +++++++------ 2 files changed, 62 insertions(+), 13 deletions(-) create mode 100644 src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.test.ts diff --git a/src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.test.ts b/src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.test.ts new file mode 100644 index 00000000000..d5ea930cac1 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { resolveTerminalOptionShortcutAction } from './terminal-option-shortcut-policy' + +describe('resolveTerminalOptionShortcutAction', () => { + it('types non-US Option characters on B/F/D instead of readline word motion (#32100)', () => { + for (const [key, code] of [ + ['[', 'KeyF'], + ['{', 'KeyB'], + ['“', 'KeyD'] + ] as const) { + expect( + resolveTerminalOptionShortcutAction( + { key, code, metaKey: false, ctrlKey: false, altKey: true, shiftKey: false }, + { + isMac: true, + macOptionAsAlt: 'false', + optionKeyLocations: 1, + getKittyKeyboardFlags: () => 0 + } + ) + ).toBeNull() + } + }) + + it('preserves readline word motion for US Option glyphs on B/F/D', () => { + for (const [key, code, expected] of [ + ['∫', 'KeyB', '\x1bb'], + ['ƒ', 'KeyF', '\x1bf'], + ['∂', 'KeyD', '\x1bd'] + ] as const) { + expect( + resolveTerminalOptionShortcutAction( + { key, code, metaKey: false, ctrlKey: false, altKey: true, shiftKey: false }, + { + isMac: true, + macOptionAsAlt: 'false', + optionKeyLocations: 1, + getKittyKeyboardFlags: () => 0 + } + ) + ).toEqual({ type: 'sendInput', data: expected }) + } + }) +}) diff --git a/src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.ts b/src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.ts index 1de5ee7e7f2..1cc57e97f4d 100644 --- a/src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.ts +++ b/src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy.ts @@ -66,6 +66,13 @@ function isLayoutComposedCharacter( ) } +// US/ABC Option layer keeps readline word motion when Option is not Meta (#696). +const READLINE_OPTION_WORD_KEYS = new Map([ + ['KeyB', { optionCharacter: '∫', data: '\x1bb' }], + ['KeyF', { optionCharacter: 'ƒ', data: '\x1bf' }], + ['KeyD', { optionCharacter: '∂', data: '\x1bd' }] +]) + function isImeOwnedKey(event: TerminalOptionShortcutEvent): boolean { return ( event.isComposing === true || @@ -152,10 +159,10 @@ export function resolveTerminalOptionShortcutAction( } if (!event.shiftKey) { + const character = + (event.code ? context.layoutCharacterForCode?.(event.code, false) : undefined) ?? + pc101CharacterForCode(event.code) if (shouldActAsMeta) { - const character = - (event.code ? context.layoutCharacterForCode?.(event.code, false) : undefined) ?? - pc101CharacterForCode(event.code) if (character) { return { type: 'sendInput', @@ -166,16 +173,14 @@ export function resolveTerminalOptionShortcutAction( } } } - if (!shouldActAsMeta) { - if (event.code === 'KeyB') { - return { type: 'sendInput', data: '\x1bb' } - } - if (event.code === 'KeyF') { - return { type: 'sendInput', data: '\x1bf' } - } - if (event.code === 'KeyD') { - return { type: 'sendInput', data: '\x1bd' } - } + const wordKey = event.code ? READLINE_OPTION_WORD_KEYS.get(event.code) : undefined + // Non-US Option characters (Croatian-PC `[` `{` `“`) are text. + if ( + !shouldActAsMeta && + wordKey && + (event.key === wordKey.optionCharacter || !isLayoutComposedCharacter(event.key, character)) + ) { + return { type: 'sendInput', data: wordKey.data } } } if ( From 7a47001b2bc54405daaeda274cbc57ff296795a6 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:40:17 -0800 Subject: [PATCH 18/40] fix(terminal): detect Codex drafts above a footer that names reasoning effort (#41256) --- .../input/terminal-composer-draft.test.ts | 22 +++++++++++++++++++ .../terminal/input/terminal-composer-draft.ts | 3 ++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/shared/terminal/input/terminal-composer-draft.test.ts b/src/shared/terminal/input/terminal-composer-draft.test.ts index f2806fb4387..c1070364202 100644 --- a/src/shared/terminal/input/terminal-composer-draft.test.ts +++ b/src/shared/terminal/input/terminal-composer-draft.test.ts @@ -170,6 +170,28 @@ describe('detectTerminalComposerDraft', () => { ).toBeNull() }) + it.each(['gpt-5.4 high · ~/repo', 'gpt-5.4 high Fast · ~/repo'])( + 'recognizes a Codex composer whose undimmed footer reads %s', + (footer) => { + expect( + detectTerminalComposerDraft({ + rows: ['› review the change'], + typedRows: ['› review the change'], + promptGlyphBoldRows: [true], + rowsBelow: ['', ` ${footer}`], + typedRowsBelow: ['', ` ${footer}`], + rowsBelowWrapped: [false, false], + rowsBelowCustomForeground: [false, false], + beforeCursor: '› review the change', + afterCursor: '', + rawAfterCursor: '', + cursorHidden: false, + cursorViewportRow: 4 + }) + ).toMatchObject({ text: 'review the change', promptGlyph: '›' }) + } + ) + it('rejects a hidden-cursor dialog even when its selected row uses a composer glyph', () => { expect( detectTerminalComposerDraft({ diff --git a/src/shared/terminal/input/terminal-composer-draft.ts b/src/shared/terminal/input/terminal-composer-draft.ts index 0ac60854c3e..49715368b5c 100644 --- a/src/shared/terminal/input/terminal-composer-draft.ts +++ b/src/shared/terminal/input/terminal-composer-draft.ts @@ -30,7 +30,8 @@ type TerminalComposerMatch = TerminalComposerDraft & { placeholder: boolean } const COMPOSER_PROMPT_PREFIX = /^\s*[\u276F\u203A\u00BB]\s?/ const COMPOSER_FRAME_LINE = /^[\u2500\u2501-]{8,}\s*$/ const COMPOSER_TOP_FRAME_PREFIX = /^[\u2500\u2501-]{8,}/ -const CODEX_FOOTER_LINE = /^\s*(?:gpt-\S+|o\d\S*)\s+[\u00B7\u2022]\s+\S.*$/i +// Codex can follow the model with reasoning effort and service tier (`gpt-5.4 high Fast`). +const CODEX_FOOTER_LINE = /^\s*(?:gpt-\S+|o\d\S*)(?:\s+[\w-]+){0,2}\s+[\u00B7\u2022]\s+\S.*$/i function composerContinuationRows( context: TerminalCursorContext, From 65d30b156a938bcf9bda9dd90974ccf085be26a2 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:45:40 -0800 Subject: [PATCH 19/40] fix(computer-use): only SW_RESTORE minimized windows on Windows (#41253) --- .../computer-use-windows/runtime-pointer.test.ps1 | 14 ++++++++++++++ native/computer-use-windows/runtime.ps1 | 8 +++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/native/computer-use-windows/runtime-pointer.test.ps1 b/native/computer-use-windows/runtime-pointer.test.ps1 index 34d5fa81176..347fe912922 100644 --- a/native/computer-use-windows/runtime-pointer.test.ps1 +++ b/native/computer-use-windows/runtime-pointer.test.ps1 @@ -13,6 +13,7 @@ using System.Collections.Generic; public static class OrcaDesktopWin32 { public static readonly List Calls = new List(); public static bool AllowActivation; + public static bool Minimized; public static IntPtr Foreground; public static IntPtr Pending; public static int FocusReads; @@ -21,11 +22,15 @@ public static class OrcaDesktopWin32 { public static void Reset(bool allow) { Calls.Clear(); AllowActivation = allow; + Minimized = false; Foreground = new IntPtr(202); Pending = IntPtr.Zero; FocusReads = 0; WindowX = 100; } + public static bool IsIconic(IntPtr hwnd) { + return Minimized; + } public static bool ShowWindow(IntPtr hwnd, int command) { Calls.Add("restore"); return true; @@ -114,4 +119,13 @@ foreach ($case in @( $result = Invoke-OrcaOperation ([pscustomobject]@{ tool = "click"; app = "Fixture"; element = [pscustomobject]@{ index = 1 } }) Assert-TestEqual $result.action.path "accessibility" "pattern click path" Assert-TestEqual ([OrcaDesktopWin32]::Calls.Count) 0 "pattern click bypasses activation and global input" +[OrcaDesktopWin32]::Reset($true) +Restore-OrcaWindow (Find-OrcaProcess) +Assert-TestEqual (@([OrcaDesktopWin32]::Calls) -join ",") "activate" "non-minimized window skips SW_RESTORE" + +[OrcaDesktopWin32]::Reset($true) +[OrcaDesktopWin32]::Minimized = $true +Restore-OrcaWindow (Find-OrcaProcess) +Assert-TestEqual (@([OrcaDesktopWin32]::Calls) -join ",") "restore,activate" "minimized window runs SW_RESTORE" + Write-Output "windows-pointer-tests-ok" diff --git a/native/computer-use-windows/runtime.ps1 b/native/computer-use-windows/runtime.ps1 index b7c254a8232..4d71604bafc 100644 --- a/native/computer-use-windows/runtime.ps1 +++ b/native/computer-use-windows/runtime.ps1 @@ -94,6 +94,9 @@ public static class OrcaDesktopWin32 { [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow); + [DllImport("user32.dll")] + public static extern bool IsIconic(IntPtr hwnd); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd); @@ -342,7 +345,10 @@ function Assert-OrcaWindowTarget($Process, $WindowId, $WindowIndex) { function Restore-OrcaWindow($Process) { if ($Process.MainWindowHandle -eq 0) { return } - [void][OrcaDesktopWin32]::ShowWindow([IntPtr]$Process.MainWindowHandle, 9) + # Why: SW_RESTORE also un-maximizes, which moves the frame the agent targeted. + if ([OrcaDesktopWin32]::IsIconic([IntPtr]$Process.MainWindowHandle)) { + [void][OrcaDesktopWin32]::ShowWindow([IntPtr]$Process.MainWindowHandle, 9) + } [void][OrcaDesktopWin32]::SetForegroundWindow([IntPtr]$Process.MainWindowHandle) } From 1708f1caeea901d32886572e993a9f77bd6d1f90 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:47:58 -0800 Subject: [PATCH 20/40] refactor(claude-accounts): organize sign-in and profile owners (#41222) --- .github/workflows/performance-contracts.yml | 1 - config/build-plugins/cli-main-entry-names.ts | 2 +- .../build-plugins/main-build-entry-points.ts | 2 +- config/flaky-test-pattern-baseline.txt | 6 - config/knip.json | 6 +- config/main-sync-fs-baseline.txt | 32 +- .../scripts/ci/sharding/ci-shard-timings.json | 43 +- .../server-bundle/orcad-entry-build.mjs | 3 +- .../wsl-guest/build-wsl-guest.mjs | 2 +- .../source-routing/pr-package-test-paths.mjs | 2 +- config/vitest.performance.config.ts | 1 - src/cli/handlers/account.test.ts | 47 +- .../server/server-ingest-normalization.ts | 2 +- src/main/ai-vault/ai-vault-scan-roots.ts | 2 +- src/main/ai-vault/session-scanner-roots.ts | 2 +- .../claude-account-service.test.ts | 109 +--- .../claude-launch-routing.test.ts | 180 ------ .../host-sign-in-real-cli.test.ts | 87 --- .../{ => profiles}/claude-profile-homes.ts | 0 .../claude-profile-paths.test.ts | 26 +- .../{ => profiles}/claude-profile-paths.ts | 8 +- .../{ => profiles}/claude-profile-report.ts | 0 .../claude-account-usage-preparation.ts | 2 +- .../routing}/claude-observed-config-dirs.ts | 8 +- .../claude-profile-installed-router.ts | 6 +- .../routing}/claude-profile-launch-errors.ts | 6 +- .../claude-profile-launch-preparation.ts | 6 +- .../routing}/claude-profile-routed-home.ts | 2 +- .../routing}/claude-profile-router.test.ts | 95 +--- .../routing}/claude-profile-router.ts | 36 +- .../claude-profile-selection-homes.ts | 2 +- .../claude-profile-history-windows.test.ts | 6 +- .../setup}/claude-profile-history.test.ts | 0 .../setup}/claude-profile-history.ts | 8 +- .../setup}/claude-profile-prompt-history.ts | 8 +- .../claude-profile-provisioning.test.ts | 4 +- .../setup}/claude-profile-provisioning.ts | 10 +- .../setup}/claude-profile-settings.ts | 6 +- .../claude-profile-setup-worker-entry.ts | 2 +- .../claude-profile-setup-worker.test.ts | 26 +- .../setup}/claude-profile-setup-worker.ts | 6 +- .../setup}/claude-profile-setup.test.ts | 44 +- .../setup}/claude-profile-setup.ts | 6 +- .../setup}/claude-profile-sharing.ts | 6 +- .../setup}/claude-profile-state.ts | 0 .../wsl}/claude-profile-wsl-entry.ts | 0 .../wsl}/claude-profile-wsl-paths.ts | 2 +- .../wsl}/claude-profile-wsl-provision.ts | 2 +- .../wsl}/claude-profile-wsl-router.test.ts | 88 +-- .../wsl}/claude-profile-wsl-router.ts | 35 +- .../runtime-auth-service.test.ts | 89 --- .../claude-accounts/runtime-auth-service.ts | 12 +- .../claude-structured-auth-policy.test.ts | 4 +- .../claude-structured-auth-policy.ts | 8 +- .../{ => runtime-auth}/environment.ts | 4 +- .../keychain-config-directory-aliases.test.ts | 0 .../{ => runtime-auth}/keychain.ts | 2 +- .../runtime-auth/runtime-auth-types.ts | 2 +- .../{ => runtime-auth}/runtime-paths.ts | 0 .../claude-account-selection.ts | 12 +- .../{ => selection}/runtime-selection.test.ts | 2 +- .../{ => selection}/runtime-selection.ts | 4 +- src/main/claude-accounts/service.ts | 12 +- .../claude-account-folder.test.ts | 4 +- .../{ => sign-in}/claude-account-folder.ts | 8 +- .../claude-account-registration.ts | 6 +- ...laude-command-process-windows-only.test.ts | 2 +- .../{ => sign-in}/claude-command-process.ts | 19 +- .../{ => sign-in}/claude-duplicate-account.ts | 4 +- .../claude-login-process-termination.ts | 6 +- .../claude-login-session.test.ts | 24 - .../{ => sign-in}/claude-login-session.ts | 2 +- .../claude-pasted-code-login.test.ts | 2 +- .../{ => sign-in}/claude-pasted-code-login.ts | 4 +- .../claude-sign-in-browser.test.ts | 0 .../{ => sign-in}/claude-sign-in-browser.ts | 2 +- .../windows-command-invocation.test.ts | 0 .../windows-command-invocation.ts | 0 .../scanner-incremental-append.test.ts | 143 ----- .../scanner-incremental-ownership.test.ts | 514 ------------------ .../scanner-incremental-reader.test.ts | 512 ----------------- .../claude-usage/scanner-long-context.test.ts | 2 +- .../transcript-file-discovery-errors.test.ts | 2 +- .../claude-usage/transcript-file-discovery.ts | 2 +- .../claude/agent-view/agent-view-service.ts | 2 +- .../claude-child-process-environment.ts | 5 +- src/main/claude/claude-cli-conversations.ts | 2 +- .../claude/claude-conversation-copy.test.ts | 84 +-- src/main/claude/claude-conversation-copy.ts | 2 +- src/main/claude/claude-launch-account.ts | 4 +- .../claude/claude-naming-invocation.test.ts | 4 +- src/main/claude/claude-naming-invocation.ts | 4 +- src/main/claude/claude-profile-hooks.test.ts | 74 +-- ...aude-real-cli-availability-test-support.ts | 2 +- src/main/claude/claude-rewind-fork.ts | 2 +- src/main/claude/hook-service.ts | 2 +- .../claude-conversation-title-owner.test.ts | 67 --- .../claude-conversation-title-owner.ts | 2 +- .../launch/claude-structured-child-env.ts | 2 +- ...-structured-launch-account-routing.test.ts | 105 ---- .../launch/claude-structured-launch-home.ts | 2 +- .../claude-structured-launch-resolution.ts | 4 +- .../theme-sync/claude-code-theme-sync.ts | 4 +- src/main/ipc/account-sign-in-link-opener.ts | 2 +- src/main/ipc/claude-accounts.ts | 2 +- src/main/ipc/pty/host-env/types.ts | 4 +- .../ipc/pty/ipc/claude-diff-panel-notice.ts | 2 +- src/main/ipc/pty/ipc/claude-old-terminal.ts | 2 +- src/main/ipc/pty/ipc/spawn-preflight.ts | 2 +- src/main/ipc/pty/ipc/spawn-state.ts | 2 +- src/main/ipc/pty/runtime/spawn-preflight.ts | 2 +- src/main/ipc/pty/runtime/spawn-state.ts | 2 +- ...ion-claude-account-routing.test-support.ts | 6 +- ...ession-failed-create-owner-verdict.test.ts | 94 ---- src/main/native-chat/session-file-resolver.ts | 2 +- .../orcad-wsl-host-claude-profile-refresh.ts | 8 +- .../accounts/provider-account-services.ts | 2 +- .../claude/claude-managed-account-usage.ts | 2 +- .../claude/claude-oauth-credentials.ts | 6 +- .../claude/claude-rate-limit-target.ts | 2 +- .../rate-limits/service/rate-limit-service.ts | 2 +- .../service/service-account-refresh.ts | 2 +- .../service/service-fetch-policy.ts | 6 +- .../service/service-fetch-targets.ts | 2 +- .../service/service-full-cycle-preparation.ts | 2 +- src/main/rate-limits/service/service-state.ts | 2 +- src/main/rate-limits/service/service-types.ts | 2 +- .../environment/runtime-account-controller.ts | 2 +- .../structured-agent-account-home.ts | 4 +- .../runtime-structured-agent-host.ts | 2 +- .../structured-agent-runtime-metadata.ts | 2 +- ...ructured-agent-session-runtime-contract.ts | 2 +- .../structured-session-recovery-options.ts | 2 +- .../structured-chat-naming-agent-launch.ts | 2 +- ...ured-session-account-home-location.test.ts | 78 --- .../launch/terminal-split-source-authority.ts | 2 +- .../bundled-skill-local-host.ts | 2 +- .../startup/wsl-orcad-account-env-wiring.ts | 4 +- .../commit-message-agent-environment.ts | 4 +- .../window/attach-main-window-services.ts | 4 +- .../worktree-retirement-discovery.ts | 2 +- 141 files changed, 312 insertions(+), 2727 deletions(-) delete mode 100644 src/main/claude-accounts/claude-launch-routing.test.ts delete mode 100644 src/main/claude-accounts/host-sign-in-real-cli.test.ts rename src/main/claude-accounts/{ => profiles}/claude-profile-homes.ts (100%) rename src/main/claude-accounts/{ => profiles}/claude-profile-paths.test.ts (84%) rename src/main/claude-accounts/{ => profiles}/claude-profile-paths.ts (96%) rename src/main/claude-accounts/{ => profiles}/claude-profile-report.ts (100%) rename src/main/claude-accounts/{ => profiles/routing}/claude-account-usage-preparation.ts (89%) rename src/main/claude-accounts/{ => profiles/routing}/claude-observed-config-dirs.ts (88%) rename src/main/claude-accounts/{ => profiles/routing}/claude-profile-installed-router.ts (89%) rename src/main/claude-accounts/{ => profiles/routing}/claude-profile-launch-errors.ts (63%) rename src/main/claude-accounts/{ => profiles/routing}/claude-profile-launch-preparation.ts (85%) rename src/main/claude-accounts/{ => profiles/routing}/claude-profile-routed-home.ts (96%) rename src/main/claude-accounts/{ => profiles/routing}/claude-profile-router.test.ts (77%) rename src/main/claude-accounts/{ => profiles/routing}/claude-profile-router.ts (89%) rename src/main/claude-accounts/{ => profiles/routing}/claude-profile-selection-homes.ts (90%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-history-windows.test.ts (97%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-history.test.ts (100%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-history.ts (95%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-prompt-history.ts (96%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-provisioning.test.ts (97%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-provisioning.ts (96%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-settings.ts (93%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-setup-worker-entry.ts (93%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-setup-worker.test.ts (65%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-setup-worker.ts (89%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-setup.test.ts (72%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-setup.ts (93%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-sharing.ts (89%) rename src/main/claude-accounts/{ => profiles/setup}/claude-profile-state.ts (100%) rename src/main/claude-accounts/{ => profiles/wsl}/claude-profile-wsl-entry.ts (100%) rename src/main/claude-accounts/{ => profiles/wsl}/claude-profile-wsl-paths.ts (97%) rename src/main/claude-accounts/{ => profiles/wsl}/claude-profile-wsl-provision.ts (95%) rename src/main/claude-accounts/{ => profiles/wsl}/claude-profile-wsl-router.test.ts (68%) rename src/main/claude-accounts/{ => profiles/wsl}/claude-profile-wsl-router.ts (90%) delete mode 100644 src/main/claude-accounts/runtime-auth-service.test.ts rename src/main/claude-accounts/{ => runtime-auth}/claude-structured-auth-policy.test.ts (92%) rename src/main/claude-accounts/{ => runtime-auth}/claude-structured-auth-policy.ts (73%) rename src/main/claude-accounts/{ => runtime-auth}/environment.ts (95%) rename src/main/claude-accounts/{ => runtime-auth}/keychain-config-directory-aliases.test.ts (100%) rename src/main/claude-accounts/{ => runtime-auth}/keychain.ts (97%) rename src/main/claude-accounts/{ => runtime-auth}/runtime-paths.ts (100%) rename src/main/claude-accounts/{ => selection}/claude-account-selection.ts (95%) rename src/main/claude-accounts/{ => selection}/runtime-selection.test.ts (96%) rename src/main/claude-accounts/{ => selection}/runtime-selection.ts (97%) rename src/main/claude-accounts/{ => sign-in}/claude-account-folder.test.ts (96%) rename src/main/claude-accounts/{ => sign-in}/claude-account-folder.ts (96%) rename src/main/claude-accounts/{ => sign-in}/claude-account-registration.ts (97%) rename src/main/claude-accounts/{ => sign-in}/claude-command-process-windows-only.test.ts (97%) rename src/main/claude-accounts/{ => sign-in}/claude-command-process.ts (93%) rename src/main/claude-accounts/{ => sign-in}/claude-duplicate-account.ts (90%) rename src/main/claude-accounts/{ => sign-in}/claude-login-process-termination.ts (88%) rename src/main/claude-accounts/{ => sign-in}/claude-login-session.test.ts (76%) rename src/main/claude-accounts/{ => sign-in}/claude-login-session.ts (97%) rename src/main/claude-accounts/{ => sign-in}/claude-pasted-code-login.test.ts (98%) rename src/main/claude-accounts/{ => sign-in}/claude-pasted-code-login.ts (95%) rename src/main/claude-accounts/{ => sign-in}/claude-sign-in-browser.test.ts (100%) rename src/main/claude-accounts/{ => sign-in}/claude-sign-in-browser.ts (98%) rename src/main/claude-accounts/{ => sign-in}/windows-command-invocation.test.ts (100%) rename src/main/claude-accounts/{ => sign-in}/windows-command-invocation.ts (100%) delete mode 100644 src/main/claude-usage/scanner-incremental-append.test.ts delete mode 100644 src/main/claude-usage/scanner-incremental-ownership.test.ts delete mode 100644 src/main/claude-usage/scanner-incremental-reader.test.ts delete mode 100644 src/main/claude/structured/launch/claude-structured-launch-account-routing.test.ts delete mode 100644 src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-failed-create-owner-verdict.test.ts delete mode 100644 src/main/runtime/session-tabs/structured-session-account-home-location.test.ts diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index e39f3001d60..850f0671463 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -25,7 +25,6 @@ on: - 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts' - 'src/main/codex-usage/scanner-incremental-append.test.ts' - 'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts' - - 'src/main/claude-usage/scanner-incremental-append.test.ts' permissions: contents: read diff --git a/config/build-plugins/cli-main-entry-names.ts b/config/build-plugins/cli-main-entry-names.ts index bb80c31d534..a5489423531 100644 --- a/config/build-plugins/cli-main-entry-names.ts +++ b/config/build-plugins/cli-main-entry-names.ts @@ -3,7 +3,7 @@ export const CLI_MAIN_ENTRY_NAMES = [ 'agent-hooks/installation/managed-agent-hook-controls', 'gitlab/projects/project-ref-parser', 'orca-profiles/profile-index-store', - 'claude-accounts/keychain', + 'claude-accounts/runtime-auth/keychain', // The CLI checks a relocated runtime socket dir before it sends the auth token. 'daemon/endpoint/publication/daemon-socket-endpoint-path', 'skills/bundled-skill-install/bundled-skill-local-host', diff --git a/config/build-plugins/main-build-entry-points.ts b/config/build-plugins/main-build-entry-points.ts index ccd430d2f88..1535e239862 100644 --- a/config/build-plugins/main-build-entry-points.ts +++ b/config/build-plugins/main-build-entry-points.ts @@ -47,7 +47,7 @@ export const MAIN_BUILD_ENTRY_POINTS: Record = { ), // Why: a first account setup can merge a large history tree with sync fs calls. 'claude-profile-setup-worker-entry': resolve( - 'src/main/claude-accounts/claude-profile-setup-worker-entry.ts' + 'src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts' ), 'profile-state-backup-worker-entry': resolve( 'src/main/persistence/profile-state/backup/profile-state-backup-worker-entry.ts' diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 42efc2b86cd..8f37a728c8e 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -151,11 +151,6 @@ 1 test-no-real-time-wait:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts 1 test-no-real-time-wait:src/main/browser/network/tunnels/execution-route-socket-duplex.test.ts 1 test-no-real-time-wait:src/main/browser/network/tunnels/remote-browser-socks-server.test.ts -1 test-no-real-time-wait:src/main/claude-accounts/claude-login-session.test.ts -1 test-no-real-time-wait:src/main/claude-accounts/claude-profile-router.test.ts -1 test-no-real-time-wait:src/main/claude-accounts/claude-profile-wsl-router.test.ts -1 test-no-real-time-wait:src/main/claude-accounts/runtime-auth-service.test.ts -1 test-no-real-time-wait:src/main/claude-usage/scanner-incremental-reader.test.ts 1 test-no-real-time-wait:src/main/claude/claude-agent-sdk-exit-proof.test.ts 1 test-no-real-time-wait:src/main/claude/claude-agent-sdk-user-message-queue.test.ts 1 test-no-real-time-wait:src/main/claude/claude-stop-ack-race.test.ts @@ -646,7 +641,6 @@ 1 test-timeout-needs-reason:src/main/browser/guest-lifecycle/find/browser-find-frame-traversal.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts -3 test-timeout-needs-reason:src/main/claude-usage/scanner-incremental-reader.test.ts 1 test-timeout-needs-reason:src/main/claude/claude-agent-sdk-exit-proof.test.ts 1 test-timeout-needs-reason:src/main/claude/claude-background-run-isolation-real-cli.test.ts 2 test-timeout-needs-reason:src/main/claude/claude-status-line-windows.test.ts diff --git a/config/knip.json b/config/knip.json index 34746da37b6..d0703c61f99 100644 --- a/config/knip.json +++ b/config/knip.json @@ -16,7 +16,7 @@ "src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts", "src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts", "src/main/agent-hooks/installation/managed-agent-hook-controls.ts", - "src/main/claude-accounts/keychain.ts", + "src/main/claude-accounts/runtime-auth/keychain.ts", "src/renderer/src/main.tsx", "src/renderer/src/popout.tsx", "src/renderer/src/web/main.tsx", @@ -43,12 +43,12 @@ "src/main/native-chat/wsl-transcript-fs-process-entry.ts", "src/main/usage/scan-worker/usage-scan-worker-entry.ts", "src/main/workspaces/space-analysis/workspace-space-scan-worker-entry.ts", - "src/main/claude-accounts/claude-profile-setup-worker-entry.ts", + "src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts", "src/main/persistence/profile-state/backup/profile-state-backup-worker-entry.ts", "src/main/persistence/profile-state/writer/profile-state-writer-worker-entry.ts", "src/main/orcad/orcad-local-serve-selection-entry.ts", "src/main/orcad/launcher.ts", - "src/main/claude-accounts/claude-profile-wsl-entry.ts", + "src/main/claude-accounts/profiles/wsl/claude-profile-wsl-entry.ts", "src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process-entry.ts", "src/wsl-guest/wsl-browser-network-relay.ts", "src/renderer/src/space.tsx", diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 9c56a270dab..ff6de5dd7d7 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -72,22 +72,22 @@ 4 src/main/browser/routing/partitions/browser-route-partition-pending-deletes.ts 4 src/main/browser/sessions/profiles/browser-session-meta-store.ts 2 src/main/browser/site-settings/browser-profile-site-store.ts -7 src/main/claude-accounts/claude-account-folder.ts -1 src/main/claude-accounts/claude-observed-config-dirs.ts -14 src/main/claude-accounts/claude-profile-history.ts -2 src/main/claude-accounts/claude-profile-homes.ts -1 src/main/claude-accounts/claude-profile-launch-preparation.ts -7 src/main/claude-accounts/claude-profile-paths.ts -26 src/main/claude-accounts/claude-profile-prompt-history.ts -5 src/main/claude-accounts/claude-profile-provisioning.ts -5 src/main/claude-accounts/claude-profile-router.ts -1 src/main/claude-accounts/claude-profile-settings.ts -1 src/main/claude-accounts/claude-profile-setup-worker.ts -1 src/main/claude-accounts/claude-profile-setup.ts -12 src/main/claude-accounts/claude-profile-sharing.ts -1 src/main/claude-accounts/claude-profile-wsl-router.ts -2 src/main/claude-accounts/keychain.ts -1 src/main/claude-accounts/runtime-paths.ts +7 src/main/claude-accounts/sign-in/claude-account-folder.ts +1 src/main/claude-accounts/profiles/routing/claude-observed-config-dirs.ts +14 src/main/claude-accounts/profiles/setup/claude-profile-history.ts +2 src/main/claude-accounts/profiles/claude-profile-homes.ts +1 src/main/claude-accounts/profiles/routing/claude-profile-launch-preparation.ts +7 src/main/claude-accounts/profiles/claude-profile-paths.ts +26 src/main/claude-accounts/profiles/setup/claude-profile-prompt-history.ts +5 src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts +5 src/main/claude-accounts/profiles/routing/claude-profile-router.ts +1 src/main/claude-accounts/profiles/setup/claude-profile-settings.ts +1 src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.ts +1 src/main/claude-accounts/profiles/setup/claude-profile-setup.ts +12 src/main/claude-accounts/profiles/setup/claude-profile-sharing.ts +1 src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts +2 src/main/claude-accounts/runtime-auth/keychain.ts +1 src/main/claude-accounts/runtime-auth/runtime-paths.ts 3 src/main/claude/agent-view/agent-view-install.ts 1 src/main/claude/claude-diff-panel-auto-open.ts 14 src/main/claude/claude-folder-trust-file.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index d0bec709c14..532f628dabf 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -1035,33 +1035,27 @@ "src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts": 678, "src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.test.ts": 146, "src/main/browser/routing/local-host-partitions/wsl-host-browser-route-partition.test.ts": 753, - "src/main/claude-accounts/claude-account-folder.test.ts": 153, + "src/main/claude-accounts/sign-in/claude-account-folder.test.ts": 153, "src/main/claude-accounts/claude-account-service.test.ts": 1207, - "src/main/claude-accounts/claude-command-process-windows-only.test.ts": 90, - "src/main/claude-accounts/claude-launch-routing.test.ts": 516, - "src/main/claude-accounts/claude-login-session.test.ts": 1048, - "src/main/claude-accounts/claude-pasted-code-login.test.ts": 238, - "src/main/claude-accounts/claude-profile-history-windows.test.ts": 121, - "src/main/claude-accounts/claude-profile-history.test.ts": 173, - "src/main/claude-accounts/claude-profile-paths.test.ts": 82, - "src/main/claude-accounts/claude-profile-provisioning.test.ts": 854, - "src/main/claude-accounts/claude-profile-router.test.ts": 1091, - "src/main/claude-accounts/claude-profile-setup-worker.test.ts": 410, - "src/main/claude-accounts/claude-profile-setup.test.ts": 405, - "src/main/claude-accounts/claude-profile-wsl-router.test.ts": 919, - "src/main/claude-accounts/claude-sign-in-browser.test.ts": 314, - "src/main/claude-accounts/claude-structured-auth-policy.test.ts": 52, - "src/main/claude-accounts/host-sign-in-real-cli.test.ts": 222, - "src/main/claude-accounts/keychain-config-directory-aliases.test.ts": 51, - "src/main/claude-accounts/runtime-auth-service.test.ts": 305, - "src/main/claude-accounts/runtime-selection.test.ts": 41, - "src/main/claude-accounts/windows-command-invocation.test.ts": 48, + "src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts": 90, + "src/main/claude-accounts/sign-in/claude-login-session.test.ts": 1048, + "src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts": 238, + "src/main/claude-accounts/profiles/setup/claude-profile-history-windows.test.ts": 121, + "src/main/claude-accounts/profiles/setup/claude-profile-history.test.ts": 173, + "src/main/claude-accounts/profiles/claude-profile-paths.test.ts": 82, + "src/main/claude-accounts/profiles/setup/claude-profile-provisioning.test.ts": 854, + "src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts": 1091, + "src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.test.ts": 410, + "src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts": 405, + "src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts": 919, + "src/main/claude-accounts/sign-in/claude-sign-in-browser.test.ts": 314, + "src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts": 52, + "src/main/claude-accounts/runtime-auth/keychain-config-directory-aliases.test.ts": 51, + "src/main/claude-accounts/selection/runtime-selection.test.ts": 41, + "src/main/claude-accounts/sign-in/windows-command-invocation.test.ts": 48, "src/main/claude-usage/claude-model-pricing.test.ts": 74, "src/main/claude-usage/claude-usage-report-aggregation.test.ts": 57, "src/main/claude-usage/persisted-source-authority.test.ts": 491, - "src/main/claude-usage/scanner-incremental-append.test.ts": 235, - "src/main/claude-usage/scanner-incremental-ownership.test.ts": 545, - "src/main/claude-usage/scanner-incremental-reader.test.ts": 819, "src/main/claude-usage/scanner-long-context.test.ts": 186, "src/main/claude-usage/scanner-scan.test.ts": 295, "src/main/claude-usage/scanner.test.ts": 80, @@ -1164,7 +1158,6 @@ "src/main/claude/structured/journal/claude-structured-prompt-ownership.test.ts": 944, "src/main/claude/structured/launch/claude-structured-applied-options.test.ts": 956, "src/main/claude/structured/launch/claude-structured-child-env.test.ts": 126, - "src/main/claude/structured/launch/claude-structured-launch-account-routing.test.ts": 1800, "src/main/claude/structured/launch/claude-structured-launch-resolution.test.ts": 672, "src/main/claude/structured/launch/claude-structured-launch-visuals.test.ts": 565, "src/main/claude/structured/launch/claude-structured-message-options.test.ts": 1586, @@ -2401,7 +2394,6 @@ "src/main/native-chat/agent-session-wire/operations/testing/structured-agent-session-ended-prompt-cancel.test.ts": 1466, "src/main/native-chat/agent-session-wire/termination/testing/structured-agent-session-eviction.test.ts": 478, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-exit-delivery.test.ts": 2327, - "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-failed-create-owner-verdict.test.ts": 2022, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-fork-rewind.test.ts": 1797, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-held-child-lease-renewal.test.ts": 957, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-input-order-rewind.test.ts": 1509, @@ -3641,7 +3633,6 @@ "src/main/runtime/session-tabs/session-tabs-main-rows-parity.test.ts": 4606, "src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts": 4153, "src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts": 4444, - "src/main/runtime/session-tabs/structured-session-account-home-location.test.ts": 935, "src/main/runtime/orchestration/terminal-authority/settled-worker-process-replacement.test.ts": 5013, "src/main/runtime/sidebar-inputs/cached-scan.test.ts": 106, "src/main/runtime/sidebar-inputs/desktop-sidebar-facts.test.ts": 378, diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs index 27c736a8faa..116f01e391b 100644 --- a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs +++ b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs @@ -27,7 +27,8 @@ export const ORCAD_CHILD_ENTRY_POINTS = { sessionScanner: 'src/main/ai-vault/scan-service/session-scanner-service-entry.ts', workerThreadChildProcess: 'src/main/worker-thread-child-process/worker-thread-child-process-entry.ts', - claudeProfileSetup: 'src/main/claude-accounts/claude-profile-setup-worker-entry.ts', + claudeProfileSetup: + 'src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts', claudeConversationFork: 'src/main/claude/claude-conversation-fork-worker-entry.ts', sttWorker: 'src/main/speech/stt-worker.ts', computerSidecar: 'src/main/computer/computer-sidecar.ts' diff --git a/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs b/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs index 678052caba0..0790109a5eb 100644 --- a/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs +++ b/config/scripts/remote-host-build/wsl-guest/build-wsl-guest.mjs @@ -55,7 +55,7 @@ stampVersion('wsl-browser-network-relay.js', '.browser-network-version') console.log(`Built WSL browser network relay → ${outDir}/wsl-browser-network-relay.js`) await bundle( - 'src/main/claude-accounts/claude-profile-wsl-entry.ts', + 'src/main/claude-accounts/profiles/wsl/claude-profile-wsl-entry.ts', WSL_CLAUDE_PROFILE_HELPER_FILENAME ) await bundle( diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 3917f9a496b..f22d5c6747d 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -193,7 +193,7 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts', 'src/main/wsl/execution/wsl-guest-environment.test.ts', 'src/main/wsl/execution/wsl-executable-path.win32.test.ts', - 'src/main/claude-accounts/claude-profile-history-windows.test.ts', + 'src/main/claude-accounts/profiles/setup/claude-profile-history-windows.test.ts', 'src/shared/source-scan/source-tree-scan.test.ts', 'src/main/cli/wsl/wsl-cli-powershell-boundary.test.ts', 'src/main/cursor/hook-service.test.ts', diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 8035a86a0b8..07688401e26 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -15,7 +15,6 @@ 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/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts' ] for (const contract of contracts) { diff --git a/src/cli/handlers/account.test.ts b/src/cli/handlers/account.test.ts index 7242a09940a..99d39d92022 100644 --- a/src/cli/handlers/account.test.ts +++ b/src/cli/handlers/account.test.ts @@ -46,7 +46,7 @@ vi.mock('@orca/process-host', async (importOriginal) => ({ spawnProcess: (spec: ProcessSpec) => spec.args?.includes('--help') ? probeMock(spec) : spawnMock(spec.program, spec.args, spec) })) -vi.mock('../../main/claude-accounts/keychain', () => ({ +vi.mock('../../main/claude-accounts/runtime-auth/keychain', () => ({ deleteActiveClaudeKeychainCredentialsStrict: deleteKeychainMock, readActiveClaudeKeychainCredentialsStrict: readKeychainMock, writeActiveClaudeKeychainCredentials: writeKeychainMock @@ -223,41 +223,6 @@ describe('account CLI handlers', () => { exitSpy.mockRestore() }) - it('keeps the original add error when cleanup also fails', async () => { - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - rmSyncMock.mockImplementationOnce(() => { - throw new Error('EBUSY: resource busy or locked') - }) - callMock.mockImplementation((method: string) => - method === 'status.get' - ? Promise.resolve({ - id: 'test', - ok: true, - result: { - capabilities: [ACCOUNT_IMPORT_RUNTIME_CAPABILITY, CLAUDE_SIGN_IN_RUNTIME_CAPABILITY] - }, - _meta: { runtimeId: 'test-runtime' } - }) - : method === 'accounts.list' - ? Promise.resolve({ - id: 'test', - ok: true, - result: { claude: accountState('c@e.com'), codex: accountState('x@e.com') }, - _meta: { runtimeId: 'test-runtime' } - }) - : Promise.reject(new Error('registration rejected by runtime')) - ) - - await expect(ACCOUNT_HANDLERS['account add'](context('codex'))).rejects.toThrow( - 'registration rejected by runtime' - ) - expect(warnSpy).toHaveBeenCalledWith( - expect.stringContaining('Failed to clean up the temporary login directory'), - expect.any(Error) - ) - warnSpy.mockRestore() - }) - it('fails a successful add when the temporary credentials cannot be removed', async () => { rmSyncMock.mockImplementationOnce(() => { throw new Error('EBUSY: resource busy or locked') @@ -358,15 +323,5 @@ describe('account CLI handlers', () => { ).rejects.toThrow('claude-org-a, claude-org-b') expect(mutatingCalls()).toEqual([]) }) - - it('refuses the Claude system default from WSL rather than resetting the Windows host', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - process.env.ORCA_CLI_WSL_DISTRO = 'Ubuntu' - - await expect( - ACCOUNT_HANDLERS['account select'](selectionContext('claude', 'system')) - ).rejects.toThrow('Select the Claude system default for a WSL distro in Orca Settings') - expect(callMock).not.toHaveBeenCalled() - }) }) }) diff --git a/src/main/agent-hooks/server/server-ingest-normalization.ts b/src/main/agent-hooks/server/server-ingest-normalization.ts index 0304873f18e..d9cd3dcd580 100644 --- a/src/main/agent-hooks/server/server-ingest-normalization.ts +++ b/src/main/agent-hooks/server/server-ingest-normalization.ts @@ -20,7 +20,7 @@ import { } from '../../../shared/agent-hook-listener/opencode-session-registry' import type { EnrichedAgentHookEventPayload, NormalizedLocalHook } from './server-types' import { AgentHookServerTmuxStatus } from './server-tmux-status' -import { getClaudeObservedConfigDirs } from '../../claude-accounts/claude-profile-installed-router' +import { getClaudeObservedConfigDirs } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' export abstract class AgentHookServerIngestNormalization extends AgentHookServerTmuxStatus { protected readonly attributionDiagnostics = new AgentHookAttributionDiagnostics() diff --git a/src/main/ai-vault/ai-vault-scan-roots.ts b/src/main/ai-vault/ai-vault-scan-roots.ts index d73ea78fa97..df30c789acd 100644 --- a/src/main/ai-vault/ai-vault-scan-roots.ts +++ b/src/main/ai-vault/ai-vault-scan-roots.ts @@ -1,7 +1,7 @@ import { join } from 'node:path' import { isWslUncPath } from '../../shared/wsl-paths' import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import { claudeProfileHistoryDirs } from '../claude-accounts/claude-profile-installed-router' +import { claudeProfileHistoryDirs } from '../claude-accounts/profiles/routing/claude-profile-installed-router' import { getCachedWslDistros, hasCachedWslDistros } from '../wsl/discovery/distro-catalog' import { listLastKnownRunningWslHomeDirs, diff --git a/src/main/ai-vault/session-scanner-roots.ts b/src/main/ai-vault/session-scanner-roots.ts index d82c83a0759..133cdee917b 100644 --- a/src/main/ai-vault/session-scanner-roots.ts +++ b/src/main/ai-vault/session-scanner-roots.ts @@ -1,4 +1,4 @@ -import { claudeProfileHistoryDirs } from '../claude-accounts/claude-profile-installed-router' +import { claudeProfileHistoryDirs } from '../claude-accounts/profiles/routing/claude-profile-installed-router' import { homedir } from 'node:os' import { join } from 'node:path' import { resolveAbsoluteDirOverride } from '../../shared/absolute-dir-override' diff --git a/src/main/claude-accounts/claude-account-service.test.ts b/src/main/claude-accounts/claude-account-service.test.ts index 01a0b743d16..944c48015d8 100644 --- a/src/main/claude-accounts/claude-account-service.test.ts +++ b/src/main/claude-accounts/claude-account-service.test.ts @@ -5,11 +5,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultSettings } from '../../shared/constants' import type { GlobalSettings } from '../../shared/global-settings-types' import type { ClaudeManagedAccount } from '../../shared/managed-account-types' -import { CLAUDE_SIGN_IN_NOT_FINISHED_MESSAGE } from './claude-account-registration' -import { CLAUDE_ACCOUNT_FOLDER_IN_USE_MESSAGE } from './claude-account-selection' -import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process' -import { describeClaudeProfile } from './claude-profile-paths' -import type { ClaudeAccountSelectionTarget } from './runtime-selection' + +import type { ClaudeCommandConfig, ClaudeCommandOptions } from './sign-in/claude-command-process' + +import type { ClaudeAccountSelectionTarget } from './selection/runtime-selection' import { ClaudeAccountService } from './service' const roots: string[] = [] @@ -102,77 +101,6 @@ function handOverClaudeSignInLink(windowsPath: string, link: string): void { } describe('ClaudeAccountService', () => { - it('saves an account only once its folder holds a login', async () => { - const f = fixture() - const begun = await f.service.beginSignIn({ runtime: 'host' }) - expect(begun).toMatchObject({ - runtime: 'host', - configDir: join(f.root, begun.accountId, 'home') - }) - await expect(f.service.finishSignIn(begun)).rejects.toThrow(CLAUDE_SIGN_IN_NOT_FINISHED_MESSAGE) - expect(f.settings().claudeManagedAccounts).toHaveLength(2) - - f.signIn(begun.accountId, 'new@example.test') - await f.service.finishSignIn(begun) - expect(f.settings().claudeManagedAccounts.at(-1)).toMatchObject({ - id: begun.accountId, - email: 'new@example.test', - managedAuthPath: begun.configDir - }) - }) - - it.each([ - { email: 'new@example.test', organizationUuid: 'new-org', duplicate: false }, - { email: 'imported@example.test', organizationUuid: 'saved-org', duplicate: true }, - { email: 'current@example.test', organizationUuid: 'current-org', duplicate: true } - ])( - 'finishes sign-in for $email despite an invalid imported account ID', - async ({ email, organizationUuid, duplicate }) => { - const imported = account('invalid.id', { - email: 'imported@example.test', - organizationUuid: 'saved-org', - organizationName: 'Saved organization' - }) - const f = fixture([imported, account('a')]) - vi.spyOn(f.runtimeAuth.router, 'accountHome').mockImplementation((id) => { - describeClaudeProfile(f.root, id, { executionHostId: 'local', runtime: 'host' }) - return f.home(id) - }) - f.signIn('a', 'current@example.test', 'current-org') - const rows = f.service.listAccounts().accounts - expect(rows).toEqual([ - expect.objectContaining({ - id: imported.id, - email: imported.email, - organizationUuid: imported.organizationUuid, - organizationName: imported.organizationName, - needsSignIn: true - }), - expect.objectContaining({ - id: 'a', - email: 'current@example.test', - organizationUuid: 'current-org' - }) - ]) - - const begun = await f.service.beginSignIn({ runtime: 'host' }) - f.signIn(begun.accountId, email, organizationUuid) - if (duplicate) { - await expect(f.service.finishSignIn(begun)).rejects.toThrow('already added') - expect(existsSync(f.home(begun.accountId))).toBe(false) - expect(f.settings().claudeManagedAccounts).toEqual([imported, account('a')]) - } else { - await expect(f.service.finishSignIn(begun)).resolves.toMatchObject({ - accounts: expect.arrayContaining([ - expect.objectContaining({ id: begun.accountId, email, organizationUuid }) - ]) - }) - expect(f.settings().claudeManagedAccounts).toHaveLength(3) - expect(existsSync(f.home(begun.accountId))).toBe(true) - } - } - ) - it.each([ { savedEmail: 'old@example.test', currentEmail: 'current@example.test' }, { savedEmail: 'same@example.test', currentEmail: 'same@example.test' } @@ -224,25 +152,6 @@ describe('ClaudeAccountService', () => { } ) - it.skipIf(process.platform === 'win32')( - 'ends a copy-link sign-in when Claude hands BROWSER something other than a sign-in link', - async () => { - const f = fixture() - f.runLogin.mockImplementationOnce( - (_args, _config, _timeoutMs, options) => - new Promise((_resolve, reject) => { - writeFileSync(`${options!.browser}.link`, 'https://example.test/not-a-sign-in') - options?.signal?.addEventListener('abort', () => - reject(new Error('Claude sign-in was cancelled.')) - ) - }) - ) - const adding = f.service.addAccount({ runtime: 'host' }, true) - await expect(f.service.waitForSignInLink()).resolves.toBeNull() - await expect(adding).rejects.toThrow('Claude sign-in failed. Please try again.') - } - ) - it('leaves no row or folder when the hidden login is cancelled', async () => { const f = fixture() f.runLogin.mockImplementationOnce( @@ -281,14 +190,4 @@ describe('ClaudeAccountService', () => { expect(f.runtimeAuth.removeAccountFolder).not.toHaveBeenCalled() expect(f.settings().claudeManagedAccounts.map((entry) => entry.id)).toEqual(['a', 'b']) }) - - it('keeps the row when its folder cannot be deleted, so the user can retry', async () => { - const f = fixture() - f.runtimeAuth.removeAccountFolder.mockRejectedValueOnce( - Object.assign(new Error('resource busy'), { code: 'EBUSY' }) - ) - await expect(f.service.removeAccount('a')).rejects.toThrow(CLAUDE_ACCOUNT_FOLDER_IN_USE_MESSAGE) - expect(f.settings().claudeManagedAccounts.map((entry) => entry.id)).toEqual(['a', 'b']) - expect(f.settings().activeClaudeManagedAccountIdsByRuntime?.host).toBeNull() - }) }) diff --git a/src/main/claude-accounts/claude-launch-routing.test.ts b/src/main/claude-accounts/claude-launch-routing.test.ts deleted file mode 100644 index 48bf3bf29c7..00000000000 --- a/src/main/claude-accounts/claude-launch-routing.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ClaudeManagedAccount } from '../../shared/managed-account-types' -import { resolveClaudeStructuredInvocation } from '../claude/structured/launch/claude-structured-launch-resolution' -import { resolveClaudeStructuredLaunchHome } from '../claude/structured/launch/claude-structured-launch-home' -import { resolveStructuredClaudeAccountHomePath } from '../runtime/agent-session/environment/structured-agent-account-home' -import { - installClaudeProfileRouter, - withClaudeProfileTerminalEnv -} from './claude-profile-installed-router' -import { ClaudeProfileRouter, type ClaudeProfileRouterSettings } from './claude-profile-router' -import { prepareLocalCommitMessageAgentEnv } from '../text-generation/commit-message-agent-environment' -import { claudeStructuredAuthPolicyForSettings } from './claude-structured-auth-policy' -import { applyClaudeEnvPatch } from './environment' -import { withoutInheritedClaudeConfigDir } from '../claude/claude-config-dir-pin' - -const roots: string[] = [] -afterEach(() => { - installClaudeProfileRouter(undefined) - roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) -}) - -function signIn(stateDir: string, email: string): void { - mkdirSync(stateDir, { recursive: true }) - writeFileSync( - join(stateDir, '.claude.json'), - JSON.stringify({ oauthAccount: { emailAddress: email } }) - ) -} - -function coveredAccount() { - const root = mkdtempSync(join(tmpdir(), 'claude-launch-routing-')) - roots.push(root) - const userHome = join(root, 'personal') - const dataRoot = join(root, 'data') - const account: ClaudeManagedAccount = { - id: 'a', - email: 'a@example.test', - authMethod: 'subscription-oauth', - managedAuthPath: '/unused-legacy', - createdAt: 0, - updatedAt: 0, - lastAuthenticatedAt: 0 - } - const settings: ClaudeProfileRouterSettings = { - claudeManagedAccounts: [account], - activeClaudeManagedAccountId: 'a', - activeClaudeManagedAccountIdsByRuntime: undefined, - agentStatusHooksEnabled: false, - disabledTuiAgents: [] - } - const router = new ClaudeProfileRouter({ - getSettings: () => settings, - dataRoot, - userHome, - env: {}, - runSetup: async () => ({ outcome: 'prepared', warnings: [], surfaces: {} }) - }) - const accountHome = router.accountHome('a') - mkdirSync(accountHome, { recursive: true }) - writeFileSync(join(accountHome, '..', 'profile.json'), '{}') - signIn(userHome, 'a@example.test') - installClaudeProfileRouter(router) - return { router, settings, accountHome, systemHome: join(userHome, '.claude') } -} - -async function launchHomes(f: ReturnType) { - const chatEnv: Record = {} - return { - terminal: (await f.router.prepareLaunch()).configDir, - terminalEnv: withClaudeProfileTerminalEnv>({}, { runtime: 'host' }) - .CLAUDE_CONFIG_DIR, - chat: await resolveClaudeStructuredLaunchHome(f.router, chatEnv, '/recorded'), - chatEnv: chatEnv.CLAUDE_CONFIG_DIR, - chatRecord: await resolveStructuredClaudeAccountHomePath({ - launchEnv: {}, - wslDistro: null, - getClaudeConfigDirectory: () => f.router.systemDefaultHome() - }), - chatAuth: claudeStructuredAuthPolicyForSettings(f.settings), - usage: f.router.preparation().configDir, - inactiveUsage: f.router.accountUsagePreparation('a').configDir - } -} - -describe('one router decision for every Claude launch', () => { - it('sends every entry point to System default, then to the account once it signs in', async () => { - const f = coveredAccount() - expect(await launchHomes(f)).toEqual({ - terminal: f.systemHome, - terminalEnv: undefined, - chat: f.systemHome, - chatEnv: undefined, - chatRecord: f.systemHome, - chatAuth: { account: 'system' }, - usage: f.systemHome, - inactiveUsage: f.systemHome - }) - const prepare = vi.spyOn(f.router, 'prepareLaunch') - const inherited = withoutInheritedClaudeConfigDir({ CLAUDE_CONFIG_DIR: '/inherited' }) - expect(await f.router.accountSelectionHomes(inherited)).toEqual([f.systemHome, f.systemHome]) - const overlay = { ...inherited, CLAUDE_CONFIG_DIR: join(f.systemHome, 'explicit') } - expect(await f.router.accountSelectionHomes(overlay)).toEqual([ - overlay.CLAUDE_CONFIG_DIR, - overlay.CLAUDE_CONFIG_DIR - ]) - expect(prepare).not.toHaveBeenCalled() - expect(await resolveClaudeStructuredLaunchHome(f.router, { ...overlay }, '/recorded')).toBe( - overlay.CLAUDE_CONFIG_DIR - ) - signIn(f.accountHome, 'a@example.test') - expect(await f.router.accountSelectionHomes(overlay)).toEqual([ - overlay.CLAUDE_CONFIG_DIR, - f.accountHome - ]) - expect(await resolveClaudeStructuredLaunchHome(f.router, { ...overlay }, '/recorded')).toBe( - f.accountHome - ) - prepare.mockRestore() - expect(await launchHomes(f)).toEqual({ - terminal: f.accountHome, - terminalEnv: f.accountHome, - chat: f.accountHome, - chatEnv: f.accountHome, - chatRecord: f.accountHome, - chatAuth: { account: 'managed' }, - usage: f.accountHome, - inactiveUsage: f.accountHome - }) - }) - - it.each(['signed-in account', 'System default fallback'])( - "keeps a shell proxy's key with its address on every launch: %s", - async (scenario) => { - const f = coveredAccount() - if (scenario === 'signed-in account') { - signIn(f.accountHome, 'a@example.test') - } - const home = scenario === 'signed-in account' ? f.accountHome : undefined - const shell = { - ANTHROPIC_BASE_URL: 'https://proxy.example.test', - ANTHROPIC_API_KEY: 'proxy-key', - ANTHROPIC_AUTH_TOKEN: 'proxy-token' - } - const terminal = applyClaudeEnvPatch( - { PATH: '/usr/bin', ...shell }, - (await f.router.prepareLaunch()).envPatch - ) - expect(terminal).toMatchObject(shell) - expect(terminal.CLAUDE_CONFIG_DIR).toBe(home) - const chat = await resolveClaudeStructuredInvocation({ - resolveCommand: () => ({ command: 'claude', prefixArgs: [] }), - resolveInheritedEnv: async () => ({ PATH: '/usr/bin', ...shell }), - resolveAuthPolicy: () => claudeStructuredAuthPolicyForSettings(f.settings) - }) - expect(chat.env).toMatchObject(shell) - const saved = Object.fromEntries(Object.keys(shell).map((key) => [key, process.env[key]])) - Object.assign(process.env, shell) - try { - const commit = await prepareLocalCommitMessageAgentEnv('claude', { - prepareForClaudeLaunch: () => f.router.prepareLaunch() - }) - expect(commit).toMatchObject({ ok: true, env: shell }) - if (home) { - expect(commit.ok && commit.env?.CLAUDE_CONFIG_DIR).toBe(home) - } - } finally { - for (const [key, value] of Object.entries(saved)) { - if (value === undefined) { - delete process.env[key] - } else { - process.env[key] = value - } - } - } - } - ) -}) diff --git a/src/main/claude-accounts/host-sign-in-real-cli.test.ts b/src/main/claude-accounts/host-sign-in-real-cli.test.ts deleted file mode 100644 index 2790ba6bca3..00000000000 --- a/src/main/claude-accounts/host-sign-in-real-cli.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -// Real `claude` / `codex` logins as a remote client's sign-in drives them. Opt in with -// ORCA_REAL_CLAUDE_CLI_TEST=1 or ORCA_REAL_CODEX_CLI_TEST=1. Each runs in a throwaway folder and -// never signs in: Claude is sent a bogus code, and the Codex login is cancelled at its prompt. -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { spawnProcess } from '@orca/process-host' -import { describe, expect, it } from 'vitest' -import { runClaudeCommandProcess } from './claude-command-process' -import { - CLAUDE_PASTED_CODE_REJECTED_MESSAGE, - runClaudePastedCodeLogin -} from './claude-pasted-code-login' -import { runCodexLoginSession } from '../codex-accounts/codex-login-session' -import type { HostAccountSignInPrompt } from '../../shared/host-account-sign-in-types' - -const claudeEnabled = process.env.ORCA_REAL_CLAUDE_CLI_TEST === '1' -const codexEnabled = process.env.ORCA_REAL_CODEX_CLI_TEST === '1' -const posixHost = process.platform !== 'win32' - -describe('host sign-in against the real CLIs', () => { - it.skipIf(!claudeEnabled || !posixHost)( - 'Claude prints its pasted-code link with piped stdin and refuses a bogus code', - async () => { - const folder = mkdtempSync(join(tmpdir(), 'orca-host-sign-in-claude-')) - const prompts: HostAccountSignInPrompt[] = [] - try { - const error = await runClaudePastedCodeLogin( - { windowsPath: folder, linuxPath: null, wslDistro: null }, - runClaudeCommandProcess, - { - signal: new AbortController().signal, - onPrompt: (prompt) => prompts.push(prompt), - nextCode: async () => 'bogus-code#bogus-state' - }, - () => {} - ).then( - () => null, - (rejection: unknown) => rejection - ) - expect(prompts).toHaveLength(1) - expect(new URL(prompts[0].url).searchParams.get('code')).toBe('true') - expect(error).toBeInstanceOf(Error) - expect(error instanceof Error ? error.message : '').toBe( - CLAUDE_PASTED_CODE_REJECTED_MESSAGE - ) - } finally { - rmSync(folder, { recursive: true, force: true }) - } - }, - 60_000 - ) - - it.skipIf(!codexEnabled || !posixHost)( - 'Codex device auth prints its page and code, and cancel stops it', - async () => { - const home = mkdtempSync(join(tmpdir(), 'orca-host-sign-in-codex-')) - const handle: { cancel: (() => boolean) | null } = { cancel: null } - const prompted = Promise.withResolvers<{ url: string; userCode: string }>() - try { - const login = runCodexLoginSession(home, { - wslCommand: 'wsl.exe', - spawn: ({ command, args, env }) => - spawnProcess({ program: command, args, env, stdio: ['ignore', 'pipe', 'pipe'] }), - killProcessTree: (child) => void child.kill(), - setCancel: (next) => { - handle.cancel = next - }, - onAuthUrl: () => {}, - deviceAuth: { onPrompt: prompted.resolve } - }) - const settledLogin = login.then( - () => null, - (rejection: unknown) => rejection - ) - const prompt = await prompted.promise - expect(prompt.url).toBe('https://auth.openai.com/codex/device') - expect(prompt.userCode).toMatch(/^[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+$/) - expect(handle.cancel?.()).toBe(true) - expect(await settledLogin).toBeInstanceOf(Error) - } finally { - rmSync(home, { recursive: true, force: true }) - } - }, - 60_000 - ) -}) diff --git a/src/main/claude-accounts/claude-profile-homes.ts b/src/main/claude-accounts/profiles/claude-profile-homes.ts similarity index 100% rename from src/main/claude-accounts/claude-profile-homes.ts rename to src/main/claude-accounts/profiles/claude-profile-homes.ts diff --git a/src/main/claude-accounts/claude-profile-paths.test.ts b/src/main/claude-accounts/profiles/claude-profile-paths.test.ts similarity index 84% rename from src/main/claude-accounts/claude-profile-paths.test.ts rename to src/main/claude-accounts/profiles/claude-profile-paths.test.ts index 269ba3fe991..f2a01aa6a4e 100644 --- a/src/main/claude-accounts/claude-profile-paths.test.ts +++ b/src/main/claude-accounts/profiles/claude-profile-paths.test.ts @@ -121,31 +121,7 @@ describe('Claude profile namespace', () => { expect(existsSync(profile.home)).toBe(false) expect(readFileSync(marker, 'utf8')).toBe(original) }) - it.each(['file', 'link'] as const)( - 'preserves a %s occupying home and its completion marker', - (kind) => { - const dir = root() - const userHome = root() - const profile = describeClaudeProfile(dir, 'a', local) - prepareClaudeProfileDirectory(dir, profile, userHome)() - const marker = join(dir, 'claude-profiles/a/profile.json') - const original = readFileSync(marker, 'utf8') - rmSync(profile.home, { recursive: true }) - const outside = root() - writeFileSync(join(outside, 'keep'), 'personal data') - if (kind === 'file') { - writeFileSync(profile.home, 'personal data') - } else { - symlinkSync(outside, profile.home, 'junction') - } - expect(() => prepareClaudeProfileDirectory(dir, profile, userHome)).toThrow() - expect(readFileSync(marker, 'utf8')).toBe(original) - expect( - readFileSync(kind === 'file' ? profile.home : join(profile.home, 'keep'), 'utf8') - ).toBe('personal data') - expect(readFileSync(join(outside, 'keep'), 'utf8')).toBe('personal data') - } - ) + it('rejects a linked account parent before creating a profile outside the namespace', () => { const dir = root() mkdirSync(join(dir, 'claude-profiles')) diff --git a/src/main/claude-accounts/claude-profile-paths.ts b/src/main/claude-accounts/profiles/claude-profile-paths.ts similarity index 96% rename from src/main/claude-accounts/claude-profile-paths.ts rename to src/main/claude-accounts/profiles/claude-profile-paths.ts index e72bd64a1ce..d0b922b52fc 100644 --- a/src/main/claude-accounts/claude-profile-paths.ts +++ b/src/main/claude-accounts/profiles/claude-profile-paths.ts @@ -4,10 +4,10 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'nod import { CLAUDE_INJECTED_CONFIG_DIR_ENV, CLAUDE_USER_CONFIG_DIR_ENV -} from '../../shared/claude-profile-routing' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import type { ExecutionHostId } from '../../shared/execution-host' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' +} from '../../../shared/claude-profile-routing' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import type { ExecutionHostId } from '../../../shared/execution-host' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' import { ClaudeProfileSurfaceError } from './claude-profile-report' /** Caller-relative `executionHostId` routes calls but must not be persisted. */ diff --git a/src/main/claude-accounts/claude-profile-report.ts b/src/main/claude-accounts/profiles/claude-profile-report.ts similarity index 100% rename from src/main/claude-accounts/claude-profile-report.ts rename to src/main/claude-accounts/profiles/claude-profile-report.ts diff --git a/src/main/claude-accounts/claude-account-usage-preparation.ts b/src/main/claude-accounts/profiles/routing/claude-account-usage-preparation.ts similarity index 89% rename from src/main/claude-accounts/claude-account-usage-preparation.ts rename to src/main/claude-accounts/profiles/routing/claude-account-usage-preparation.ts index 140dedd03d0..a0da0271e78 100644 --- a/src/main/claude-accounts/claude-account-usage-preparation.ts +++ b/src/main/claude-accounts/profiles/routing/claude-account-usage-preparation.ts @@ -1,5 +1,5 @@ import type { ClaudeProfileRouter } from './claude-profile-router' -import type { ClaudeRuntimeAuthPreparation } from './runtime-auth/runtime-auth-types' +import type { ClaudeRuntimeAuthPreparation } from '../../runtime-auth/runtime-auth-types' /** Usage reads use the same login route as account launches. */ export function claudeAccountUsagePreparation( diff --git a/src/main/claude-accounts/claude-observed-config-dirs.ts b/src/main/claude-accounts/profiles/routing/claude-observed-config-dirs.ts similarity index 88% rename from src/main/claude-accounts/claude-observed-config-dirs.ts rename to src/main/claude-accounts/profiles/routing/claude-observed-config-dirs.ts index 948bb459924..c78d5b3ee50 100644 --- a/src/main/claude-accounts/claude-observed-config-dirs.ts +++ b/src/main/claude-accounts/profiles/routing/claude-observed-config-dirs.ts @@ -1,9 +1,9 @@ import { readFileSync } from 'node:fs' import { basename, dirname, isAbsolute, resolve } from 'node:path' -import { resolveAbsoluteDirOverride } from '../../shared/absolute-dir-override' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { isDirectory } from './claude-profile-homes' +import { resolveAbsoluteDirOverride } from '../../../../shared/absolute-dir-override' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import { isDirectory } from '../claude-profile-homes' const MAX_OBSERVED_CONFIG_DIRS = 32 diff --git a/src/main/claude-accounts/claude-profile-installed-router.ts b/src/main/claude-accounts/profiles/routing/claude-profile-installed-router.ts similarity index 89% rename from src/main/claude-accounts/claude-profile-installed-router.ts rename to src/main/claude-accounts/profiles/routing/claude-profile-installed-router.ts index 4ac6ad2969e..27dd4db9c94 100644 --- a/src/main/claude-accounts/claude-profile-installed-router.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-installed-router.ts @@ -1,9 +1,9 @@ import { join } from 'node:path' -import { isDirectory } from './claude-profile-homes' +import { isDirectory } from '../claude-profile-homes' // Keep the router setup graph out of scan workers. import type { ClaudeProfileRouter } from './claude-profile-router' -import type { ClaudeWslProfileRouter } from './claude-profile-wsl-router' -import type { ClaudeAccountSelectionTarget } from './runtime-selection' +import type { ClaudeWslProfileRouter } from '../wsl/claude-profile-wsl-router' +import type { ClaudeAccountSelectionTarget } from '../../selection/runtime-selection' import type { ClaudeObservedConfigDirs } from './claude-observed-config-dirs' let installed: ClaudeProfileRouter | undefined diff --git a/src/main/claude-accounts/claude-profile-launch-errors.ts b/src/main/claude-accounts/profiles/routing/claude-profile-launch-errors.ts similarity index 63% rename from src/main/claude-accounts/claude-profile-launch-errors.ts rename to src/main/claude-accounts/profiles/routing/claude-profile-launch-errors.ts index 365b29c992b..a1aa4626e64 100644 --- a/src/main/claude-accounts/claude-profile-launch-errors.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-launch-errors.ts @@ -1,9 +1,9 @@ import { CLAUDE_PROFILE_MISSING_MESSAGE, CLAUDE_PROFILE_SETUP_FAILED_MESSAGE -} from '../../shared/claude-profile-routing' -import '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { AgentSessionPreSpawnError } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' +} from '../../../../shared/claude-profile-routing' +import '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { AgentSessionPreSpawnError } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' export function claudeProfileMissing(): AgentSessionPreSpawnError { return new AgentSessionPreSpawnError(new Error(CLAUDE_PROFILE_MISSING_MESSAGE), { diff --git a/src/main/claude-accounts/claude-profile-launch-preparation.ts b/src/main/claude-accounts/profiles/routing/claude-profile-launch-preparation.ts similarity index 85% rename from src/main/claude-accounts/claude-profile-launch-preparation.ts rename to src/main/claude-accounts/profiles/routing/claude-profile-launch-preparation.ts index 9c319a1fd6a..d459af18a64 100644 --- a/src/main/claude-accounts/claude-profile-launch-preparation.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-launch-preparation.ts @@ -1,8 +1,8 @@ import { existsSync } from 'node:fs' -import { claudeProfileMarkerPath, type ClaudeProfileDescriptor } from './claude-profile-paths' -import type { ClaudeProfileSetupReport } from './claude-profile-setup' +import { claudeProfileMarkerPath, type ClaudeProfileDescriptor } from '../claude-profile-paths' +import type { ClaudeProfileSetupReport } from '../setup/claude-profile-setup' import { claudeProfileSetupFailed } from './claude-profile-launch-errors' -import { isDirectory } from './claude-profile-homes' +import { isDirectory } from '../claude-profile-homes' /** First construction requires setup; a prepared profile keeps its existing bounded refresh behavior. */ export async function prepareClaudeProfileForLaunch( diff --git a/src/main/claude-accounts/claude-profile-routed-home.ts b/src/main/claude-accounts/profiles/routing/claude-profile-routed-home.ts similarity index 96% rename from src/main/claude-accounts/claude-profile-routed-home.ts rename to src/main/claude-accounts/profiles/routing/claude-profile-routed-home.ts index 6855109f731..48566ce0409 100644 --- a/src/main/claude-accounts/claude-profile-routed-home.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-routed-home.ts @@ -4,7 +4,7 @@ import { claudeStateFileAsync, isSameClaudeLogin, readClaudeFolderLoginAsync -} from './claude-account-folder' +} from '../../sign-in/claude-account-folder' import { claudeProfileMissing } from './claude-profile-launch-errors' /** `routedHome` without blocking main: chat reads run once per options read and send. */ diff --git a/src/main/claude-accounts/claude-profile-router.test.ts b/src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts similarity index 77% rename from src/main/claude-accounts/claude-profile-router.test.ts rename to src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts index b5349098f59..b2351a46e6d 100644 --- a/src/main/claude-accounts/claude-profile-router.test.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-router.test.ts @@ -13,16 +13,16 @@ import { import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ClaudeManagedAccount } from '../../shared/managed-account-types' -import type { ClaudeProfileSetupReport } from './claude-profile-setup' +import type { ClaudeManagedAccount } from '../../../../shared/managed-account-types' +import type { ClaudeProfileSetupReport } from '../setup/claude-profile-setup' import { claudeProfileMarkerPath, describeClaudeProfile, prepareClaudeProfileDirectory, type ClaudeProfileDescriptor -} from './claude-profile-paths' -import { CLAUDE_PROFILE_SETUP_FAILED_MESSAGE } from '../../shared/claude-profile-routing' -import { getPosixClaudeShellFunction } from '../../shared/claude-shell-function' +} from '../claude-profile-paths' + +import { getPosixClaudeShellFunction } from '../../../../shared/claude-shell-function' import { ClaudeProfileRouter, type ClaudeProfileRouterSettings } from './claude-profile-router' import { claudeProfileHistoryDirs, @@ -35,17 +35,17 @@ import { claudeRoutedHomeAsync } from './claude-profile-routed-home' vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() })) const command = vi.hoisted(() => ({ path: '/unused-claude' })) -vi.mock('../codex-cli/command', () => ({ resolveClaudeCommand: () => command.path })) +vi.mock('../../../codex-cli/command', () => ({ resolveClaudeCommand: () => command.path })) const shell = vi.hoisted(() => ({ hang: false })) -vi.mock('../startup/login-shell-environment', () => ({ +vi.mock('../../../startup/login-shell-environment', () => ({ resolveLoginShellEnvironment: () => shell.hang ? new Promise(() => {}) : Promise.resolve({ CLAUDE_CONFIG_DIR: resolve('/shell/own') }) })) // Account removal must never reach the real Keychain. -vi.mock('../macos-keychain/generic-password', () => ({ +vi.mock('../../../macos-keychain/generic-password', () => ({ execSecurityCommand: async () => { throw new Error('The specified item could not be found in the keychain.') } @@ -233,71 +233,6 @@ describe('ClaudeProfileRouter', () => { expect(existsSync(f.router.pointerPath)).toBe(false) }) - it('refreshes a set-up folder before each launch, which never fails or hangs on it', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const f = fixture() - mkdirSync(f.home('a'), { recursive: true }) - const first = f.router.prepareLaunch() - await vi.waitFor(() => expect(f.setup.calls).toBe(1)) - f.setup.settle() - await expect(first).resolves.toMatchObject({ configDir: f.home('a') }) - - let launched = false - const second = f.router.prepareLaunch().then((prepared) => { - launched = true - return prepared - }) - await vi.waitFor(() => expect(f.setup.calls).toBe(2)) - expect(launched).toBe(false) - f.setup.settle() - await expect(second).resolves.toMatchObject({ configDir: f.home('a') }) - - f.setup.outcome = 'refused' - const hungRefreshLaunch = f.router.prepareLaunch() - await advanceRefreshDeadline(hungRefreshLaunch, 500) - await expect(hungRefreshLaunch).resolves.toMatchObject({ configDir: f.home('a') }) - expect(f.setup.calls).toBe(3) - f.setup.settle() - await vi.advanceTimersByTimeAsync(10) - const fourth = f.router.prepareLaunch() - await vi.waitFor(() => expect(f.setup.calls).toBe(4)) - f.setup.settle() - await expect(fourth).resolves.toMatchObject({ configDir: f.home('a') }) - }) - - it('makes a launch redo a first setup that was cut off after its ownership gate', async () => { - const f = fixture() - const profile = describeClaudeProfile(f.dataRoot, 'a', { - executionHostId: 'local', - runtime: 'host' - }) - prepareClaudeProfileDirectory(f.dataRoot, profile, f.userHome)() - rmSync(profile.home, { recursive: true }) - const cutOff = new ClaudeProfileRouter({ - getSettings: () => f.settings, - dataRoot: f.dataRoot, - userHome: f.userHome, - env: {}, - runSetup: async (args) => { - prepareClaudeProfileDirectory(args.dataRoot, args.profile, args.userHome) - throw new Error('Claude account setup timed out') - } - }) - await expect(cutOff.prepareLaunch()).rejects.toThrow(CLAUDE_PROFILE_SETUP_FAILED_MESSAGE) - expect(existsSync(profile.home)).toBe(true) - expect(existsSync(claudeProfileMarkerPath(profile))).toBe(false) - - const launch = f.router.prepareLaunch() - await vi.waitFor(() => expect(f.setup.calls).toBe(1)) - f.setup.settle() - await expect(launch).resolves.toMatchObject({ configDir: f.home('a') }) - expect(JSON.parse(readFileSync(claudeProfileMarkerPath(profile), 'utf8'))).toEqual({ - version: 1, - accountId: 'a', - runtime: 'host' - }) - }) - it("launches a set-up, signed-in account without waiting for the login shell's env", async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) shell.hang = true @@ -397,20 +332,6 @@ describe('ClaudeProfileRouter', () => { } ) - it('removes a folder only after its running setup, so the setup cannot bring it back', async () => { - const f = fixture() - mkdirSync(f.home('a'), { recursive: true }) - f.router.publish() - await vi.waitFor(() => expect(f.setup.calls).toBe(1)) - const removal = f.router.removeAccount('a') - await new Promise((resolve) => setTimeout(resolve, 10)) - mkdirSync(f.home('a'), { recursive: true }) - writeFileSync(join(f.home('a'), 'settings.json'), '{}') - f.setup.settle() - await removal - expect(existsSync(join(f.dataRoot, 'claude-profiles', 'a'))).toBe(false) - }) - // Creating real symlinks requires additional Windows privileges. it('lists history under a wrapper CLAUDE_CONFIG_DIR seen in a hook, after restart too', () => { diff --git a/src/main/claude-accounts/claude-profile-router.ts b/src/main/claude-accounts/profiles/routing/claude-profile-router.ts similarity index 89% rename from src/main/claude-accounts/claude-profile-router.ts rename to src/main/claude-accounts/profiles/routing/claude-profile-router.ts index 99087d9bd35..c101c1aa7c1 100644 --- a/src/main/claude-accounts/claude-profile-router.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-router.ts @@ -1,49 +1,49 @@ import { claudeAccountUsagePreparation } from './claude-account-usage-preparation' import { claudeProfileSelectionHomes } from './claude-profile-selection-homes' import { prepareClaudeProfileForLaunch } from './claude-profile-launch-preparation' -import { getClaudeAgentViewService } from '../claude/agent-view/agent-view-service' +import { getClaudeAgentViewService } from '../../../claude/agent-view/agent-view-service' import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' import { homedir } from 'node:os' import { dirname, join } from 'node:path' -import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { isAgentStatusHooksEnabledForAgent } from '../../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import { CLAUDE_INJECTED_CONFIG_DIR_ENV, CLAUDE_PROFILE_POINTER_ENV, CLAUDE_PROFILE_SETUP_FAILED_MESSAGE, CLAUDE_USER_CONFIG_DIR_ENV -} from '../../shared/claude-profile-routing' +} from '../../../../shared/claude-profile-routing' import { claudeProfileMissing } from './claude-profile-launch-errors' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { ClaudeManagedAccount } from '../../shared/managed-account-types' -import { probeRecentClaudeCliVersion } from '../claude/claude-hook-event-versions' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { resolveClaudeCommand } from '../codex-cli/command' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { ClaudeManagedAccount } from '../../../../shared/managed-account-types' +import { probeRecentClaudeCliVersion } from '../../../claude/claude-hook-event-versions' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import { resolveClaudeCommand } from '../../../codex-cli/command' import { describeClaudeProfile, type ClaudeProfileDescriptor, readUserClaudeConfigDir, readUserClaudeConfigDirAsSet, resolveClaudeDefaultHome -} from './claude-profile-paths' -import type { ClaudeProfileSetupReport } from './claude-profile-setup' -import { runClaudeProfileSetupInWorker } from './claude-profile-setup-worker' -import type { ClaudeEnvPatch } from './environment' -import type { ClaudeRuntimeAuthPreparation } from './runtime-auth/runtime-auth-types' +} from '../claude-profile-paths' +import type { ClaudeProfileSetupReport } from '../setup/claude-profile-setup' +import { runClaudeProfileSetupInWorker } from '../setup/claude-profile-setup-worker' +import type { ClaudeEnvPatch } from '../../runtime-auth/environment' +import type { ClaudeRuntimeAuthPreparation } from '../../runtime-auth/runtime-auth-types' import { findClaudeAccount, getSelectedClaudeAccountIdForTarget, type ClaudeAccountSelectionTarget -} from './runtime-selection' -import { wslClaudeProfilePointer } from './claude-profile-wsl-paths' -import { isDirectory, listClaudeProfileHomes } from './claude-profile-homes' +} from '../../selection/runtime-selection' +import { wslClaudeProfilePointer } from '../wsl/claude-profile-wsl-paths' +import { isDirectory, listClaudeProfileHomes } from '../claude-profile-homes' import { claudeStateFile, readClaudeFolderLogin, removeClaudeAccountFolder, isSameClaudeLogin, type ClaudeFolderLogin -} from './claude-account-folder' -import { resolveLoginShellEnvironment } from '../startup/login-shell-environment' +} from '../../sign-in/claude-account-folder' +import { resolveLoginShellEnvironment } from '../../../startup/login-shell-environment' export type ClaudeProfileRouterSettings = Pick< GlobalSettings, diff --git a/src/main/claude-accounts/claude-profile-selection-homes.ts b/src/main/claude-accounts/profiles/routing/claude-profile-selection-homes.ts similarity index 90% rename from src/main/claude-accounts/claude-profile-selection-homes.ts rename to src/main/claude-accounts/profiles/routing/claude-profile-selection-homes.ts index a51eb587895..076a9ed5253 100644 --- a/src/main/claude-accounts/claude-profile-selection-homes.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-selection-homes.ts @@ -1,5 +1,5 @@ import type { ClaudeProfileRouter, ClaudeProfileRouterSettings } from './claude-profile-router' -import { claudeLaunchDestinationHome } from '../claude/claude-launch-destination-home' +import { claudeLaunchDestinationHome } from '../../../claude/claude-launch-destination-home' /** Every native switcher destination, even an account whose setup has not created its home. */ export async function claudeProfileSelectionHomes( diff --git a/src/main/claude-accounts/claude-profile-history-windows.test.ts b/src/main/claude-accounts/profiles/setup/claude-profile-history-windows.test.ts similarity index 97% rename from src/main/claude-accounts/claude-profile-history-windows.test.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-history-windows.test.ts index 775da14de1f..d81168e8c1f 100644 --- a/src/main/claude-accounts/claude-profile-history-windows.test.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-history-windows.test.ts @@ -2,7 +2,7 @@ import * as fs from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as FsUtils from '../filesystem/atomic-file-publication' +import type * as FsUtils from '../../../filesystem/atomic-file-publication' vi.mock('electron', () => ({ app: { getPath: () => '/unused-test-path' } })) vi.mock('node:fs', async (original) => { const actual = await original() @@ -13,11 +13,11 @@ vi.mock('node:fs', async (original) => { symlinkSync: vi.fn(actual.symlinkSync) } }) -vi.mock('../filesystem/atomic-file-publication', async (original) => { +vi.mock('../../../filesystem/atomic-file-publication', async (original) => { const actual = await original() return { ...actual, writeFileAtomically: vi.fn(actual.writeFileAtomically) } }) -import { writeFileAtomically } from '../filesystem/atomic-file-publication' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' import { shareClaudeProfileHistory } from './claude-profile-history' // Junctions and hardlinks need no Windows privilege; POSIX uses symlinks for junctions. diff --git a/src/main/claude-accounts/claude-profile-history.test.ts b/src/main/claude-accounts/profiles/setup/claude-profile-history.test.ts similarity index 100% rename from src/main/claude-accounts/claude-profile-history.test.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-history.test.ts diff --git a/src/main/claude-accounts/claude-profile-history.ts b/src/main/claude-accounts/profiles/setup/claude-profile-history.ts similarity index 95% rename from src/main/claude-accounts/claude-profile-history.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-history.ts index de607d2aa6e..209975827ff 100644 --- a/src/main/claude-accounts/claude-profile-history.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-history.ts @@ -8,9 +8,9 @@ import { unlinkSync } from 'node:fs' import { join } from 'node:path' -import '../filesystem/atomic-file-publication' -import { renameFileWithWindowsRetry } from '../../shared/windows-retry-file-operations' -import { resolveClaudeDefaultHome } from './claude-profile-paths' +import '../../../filesystem/atomic-file-publication' +import { renameFileWithWindowsRetry } from '../../../../shared/windows-retry-file-operations' +import { resolveClaudeDefaultHome } from '../claude-profile-paths' import { ClaudeProfileSurfaceError, createClaudeProfileReport, @@ -18,7 +18,7 @@ import { warnClaudeProfile, type ClaudeProfileReport, type ClaudeProfileSurfaceOutcome -} from './claude-profile-report' +} from '../claude-profile-report' import { CLAUDE_PROFILE_MERGE_SUFFIX, crossFilesystem, diff --git a/src/main/claude-accounts/claude-profile-prompt-history.ts b/src/main/claude-accounts/profiles/setup/claude-profile-prompt-history.ts similarity index 96% rename from src/main/claude-accounts/claude-profile-prompt-history.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-prompt-history.ts index 35c50e31f73..601d232ffdd 100644 --- a/src/main/claude-accounts/claude-profile-prompt-history.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-prompt-history.ts @@ -16,15 +16,15 @@ import { type Stats } from 'node:fs' import { join } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { renameFileWithWindowsRetry } from '../../shared/windows-retry-file-operations' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import { renameFileWithWindowsRetry } from '../../../../shared/windows-retry-file-operations' import { ClaudeProfileSurfaceError, warnClaudeProfile, type ClaudeProfileReport, type ClaudeProfileSurfaceOutcome -} from './claude-profile-report' +} from '../claude-profile-report' export const CLAUDE_PROFILE_MERGE_SUFFIX = '.orca-profile-merge' const HISTORY = 'history.jsonl' diff --git a/src/main/claude-accounts/claude-profile-provisioning.test.ts b/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.test.ts similarity index 97% rename from src/main/claude-accounts/claude-profile-provisioning.test.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-provisioning.test.ts index e5c20a7673a..51dfe9536a8 100644 --- a/src/main/claude-accounts/claude-profile-provisioning.test.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.test.ts @@ -2,13 +2,13 @@ import * as fs from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as FsUtils from '../filesystem/atomic-file-publication' +import type * as FsUtils from '../../../filesystem/atomic-file-publication' vi.mock('electron', () => ({ app: { getPath: () => '/unused-test-path' } })) vi.mock('node:fs', async (original) => { const actual = await original() return { ...actual, symlinkSync: vi.fn(actual.symlinkSync) } }) -vi.mock('../filesystem/atomic-file-publication', async (original) => { +vi.mock('../../../filesystem/atomic-file-publication', async (original) => { const actual = await original() return { ...actual, writeFileAtomically: vi.fn(actual.writeFileAtomically) } }) diff --git a/src/main/claude-accounts/claude-profile-provisioning.ts b/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts similarity index 96% rename from src/main/claude-accounts/claude-profile-provisioning.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts index 42bcdd1a8e5..3d27f2ac77b 100644 --- a/src/main/claude-accounts/claude-profile-provisioning.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-provisioning.ts @@ -1,14 +1,14 @@ import { randomUUID } from 'node:crypto' import { existsSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' import { resolveClaudeGlobalConfigFile, updateClaudeGlobalConfig -} from '../claude/claude-folder-trust-file' -import { publishFileWithoutOverwrite } from '../filesystem/atomic-file-publication' +} from '../../../claude/claude-folder-trust-file' +import { publishFileWithoutOverwrite } from '../../../filesystem/atomic-file-publication' import { CLAUDE_PROFILE_HISTORY_DIRS, mergeClaudeProfileDirectory } from './claude-profile-history' -import { readClaudeProfileObject, resolveClaudeDefaultHome } from './claude-profile-paths' +import { readClaudeProfileObject, resolveClaudeDefaultHome } from '../claude-profile-paths' import { lstatIfPresent } from './claude-profile-prompt-history' import { ClaudeProfileSurfaceError, @@ -17,7 +17,7 @@ import { warnClaudeProfile, type ClaudeProfileReport, type ClaudeProfileSurfaceOutcome -} from './claude-profile-report' +} from '../claude-profile-report' import { syncClaudeProfileSettings } from './claude-profile-settings' import { mergeClaudeProfileState, selectSharedClaudeProfileState } from './claude-profile-state' import { copyClaudeProfileFile, linkClaudeProfileDirectory } from './claude-profile-sharing' diff --git a/src/main/claude-accounts/claude-profile-settings.ts b/src/main/claude-accounts/profiles/setup/claude-profile-settings.ts similarity index 93% rename from src/main/claude-accounts/claude-profile-settings.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-settings.ts index 32c146d8670..34b493684c7 100644 --- a/src/main/claude-accounts/claude-profile-settings.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-settings.ts @@ -1,12 +1,12 @@ import { createHash } from 'node:crypto' import { statSync } from 'node:fs' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { readClaudeProfileObject } from './claude-profile-paths' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import { readClaudeProfileObject } from '../claude-profile-paths' import { lstatIfPresent } from './claude-profile-prompt-history' import { ClaudeProfileSurfaceError, type ClaudeProfileSurfaceOutcome -} from './claude-profile-report' +} from '../claude-profile-report' // Digests, not values, so proxy keys in settings are not stored a second time. function digestSettings(value: Record): Record { diff --git a/src/main/claude-accounts/claude-profile-setup-worker-entry.ts b/src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts similarity index 93% rename from src/main/claude-accounts/claude-profile-setup-worker-entry.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts index 3ac5a3c9275..722f4355ab8 100644 --- a/src/main/claude-accounts/claude-profile-setup-worker-entry.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts @@ -1,5 +1,5 @@ import { parentPort, workerData } from 'node:worker_threads' -import { ClaudeHookService } from '../claude/hook-service' +import { ClaudeHookService } from '../../../claude/hook-service' import { provisionClaudeAccountProfile } from './claude-profile-setup' import type { ClaudeProfileSetupJob } from './claude-profile-setup-worker' diff --git a/src/main/claude-accounts/claude-profile-setup-worker.test.ts b/src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.test.ts similarity index 65% rename from src/main/claude-accounts/claude-profile-setup-worker.test.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.test.ts index d584f8ddec6..5b9cfc035e6 100644 --- a/src/main/claude-accounts/claude-profile-setup-worker.test.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.test.ts @@ -1,10 +1,10 @@ -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { build } from 'esbuild' import { afterEach, expect, it } from 'vitest' -import { JSONC_PARSER_ESM_ALIAS } from '../../../config/build-plugins/jsonc-parser-esm' -import { describeClaudeProfile } from './claude-profile-paths' +import { JSONC_PARSER_ESM_ALIAS } from '../../../../../config/build-plugins/jsonc-parser-esm' +import { describeClaudeProfile } from '../claude-profile-paths' import { runClaudeProfileSetupInWorker } from './claude-profile-setup-worker' const roots: string[] = [] @@ -23,7 +23,9 @@ it('runs account setup in the built worker entry, off the calling thread', async mkdirSync(profile.home, { recursive: true }) const entry = join(root, 'claude-profile-setup-worker-entry.js') await build({ - entryPoints: [resolve('src/main/claude-accounts/claude-profile-setup-worker-entry.ts')], + entryPoints: [ + resolve('src/main/claude-accounts/profiles/setup/claude-profile-setup-worker-entry.ts') + ], outfile: entry, bundle: true, alias: JSONC_PARSER_ESM_ALIAS, @@ -61,19 +63,3 @@ it('runs account setup in the built worker entry, off the calling thread', async ) ).rejects.toThrow() }) - -it('rejects and stops a setup worker that never finishes', async () => { - const root = mkdtempSync(join(tmpdir(), 'claude-setup-worker-')) - roots.push(root) - const hung = join(root, 'hung.js') - writeFileSync(hung, 'setInterval(() => {}, 1000)\n') - const job = { - dataRoot: root, - profile: describeClaudeProfile(root, 'a', { executionHostId: 'local', runtime: 'host' }), - userHome: root, - userConfigDir: undefined, - hooks: false, - claudeVersion: undefined - } - await expect(runClaudeProfileSetupInWorker(job, hung, 50)).rejects.toThrow('timed out') -}) diff --git a/src/main/claude-accounts/claude-profile-setup-worker.ts b/src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.ts similarity index 89% rename from src/main/claude-accounts/claude-profile-setup-worker.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.ts index 13b33da63ea..8afe91125b5 100644 --- a/src/main/claude-accounts/claude-profile-setup-worker.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-setup-worker.ts @@ -1,11 +1,11 @@ import { existsSync } from 'node:fs' import { dirname, join } from 'node:path' -import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' +import { spawnWorkerThread } from '../../../worker-threads/worker-thread-spawn' import { currentWorkerEntryLayout, resolveWorkerThreadEntryPath -} from '../worker-threads/worker-thread-entry-path' -import type { ClaudeProfileDescriptor } from './claude-profile-paths' +} from '../../../worker-threads/worker-thread-entry-path' +import type { ClaudeProfileDescriptor } from '../claude-profile-paths' import type { ClaudeProfileSetupReport } from './claude-profile-setup' export type ClaudeProfileSetupJob = { diff --git a/src/main/claude-accounts/claude-profile-setup.test.ts b/src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts similarity index 72% rename from src/main/claude-accounts/claude-profile-setup.test.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts index a1308315d42..e4bea6e70d7 100644 --- a/src/main/claude-accounts/claude-profile-setup.test.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-setup.test.ts @@ -18,9 +18,9 @@ vi.mock('node:os', async (original) => ({ homedir: () => state.home })) vi.mock('electron', () => ({ app: { getPath: () => state.home } })) -import { parseClaudeCliVersionOutput } from '../claude/claude-hook-event-versions' -import { ClaudeHookService } from '../claude/hook-service' -import { describeClaudeProfile, prepareClaudeProfileDirectory } from './claude-profile-paths' + +import { ClaudeHookService } from '../../../claude/hook-service' +import { describeClaudeProfile, prepareClaudeProfileDirectory } from '../claude-profile-paths' import { provisionClaudeAccountProfile } from './claude-profile-setup' const roots: string[] = [] @@ -56,44 +56,6 @@ function fixture() { const itLinks = it.skipIf(process.platform === 'win32') describe('Claude account profile setup', () => { - itLinks('prepares, shares history, provisions and installs hooks in one call', async () => { - const f = fixture() - mkdirSync(join(f.defaultHome, 'skills')) - writeFileSync(join(f.defaultHome, 'settings.json'), '{"model":"opus"}') - f.service.install({ claudeVersion: '2.1.261' }) - const report = await f.setup() - const home = join(f.dataRoot, 'claude-profiles/a/home') - expect(report).toMatchObject({ outcome: 'prepared', warnings: [] }) - expect(report.surfaces).toMatchObject({ - projects: 'linked', - 'history.jsonl': 'linked', - skills: 'linked', - 'settings.json': 'synced', - '.claude.json': 'absent', - hooks: 'merged' - }) - expect(existsSync(join(f.dataRoot, 'claude-profiles/a/profile.json'))).toBe(true) - const settings = JSON.parse(readFileSync(join(home, 'settings.json'), 'utf8')) - const defaults = JSON.parse(readFileSync(join(f.defaultHome, 'settings.json'), 'utf8')) - expect(settings).toEqual({ - model: 'opus', - hooks: defaults.hooks, - statusLine: defaults.statusLine - }) - expect(realpathSync(join(home, 'projects'))).toBe(realpathSync(join(f.defaultHome, 'projects'))) - expect(existsSync(join(home, '.credentials.json'))).toBe(false) - const unknown = parseClaudeCliVersionOutput('11.17.0') ?? undefined - const refreshed = await provisionClaudeAccountProfile({ - dataRoot: f.dataRoot, - profile: describeClaudeProfile(f.dataRoot, 'a', local), - userHome: state.home, - installHooks: (target) => f.service.install({ ...target, claudeVersion: unknown }), - platform: 'linux' - }) - expect(refreshed.warnings).toEqual([]) - expect(JSON.parse(readFileSync(join(home, 'settings.json'), 'utf8'))).toEqual(settings) - expect((await f.setup()).warnings).toEqual([]) - }) itLinks('shares plugins Claude wrote into the folder before its first setup', async () => { const f = fixture() mkdirSync(join(f.defaultHome, 'plugins')) diff --git a/src/main/claude-accounts/claude-profile-setup.ts b/src/main/claude-accounts/profiles/setup/claude-profile-setup.ts similarity index 93% rename from src/main/claude-accounts/claude-profile-setup.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-setup.ts index f967c45e621..255c51c4e17 100644 --- a/src/main/claude-accounts/claude-profile-setup.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-setup.ts @@ -1,11 +1,11 @@ import { existsSync } from 'node:fs' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { shareClaudeProfileHistory } from './claude-profile-history' import { claudeProfileMarkerPath, prepareClaudeProfileDirectory, type ClaudeProfileDescriptor -} from './claude-profile-paths' +} from '../claude-profile-paths' import { provisionClaudeProfile } from './claude-profile-provisioning' import { ClaudeProfileSurfaceError, @@ -13,7 +13,7 @@ import { runClaudeProfileSurface, warnClaudeProfile, type ClaudeProfileReport -} from './claude-profile-report' +} from '../claude-profile-report' /** `refused` means ownership validation failed before any writes. */ export type ClaudeProfileSetupReport = ClaudeProfileReport & { outcome: 'refused' | 'prepared' } diff --git a/src/main/claude-accounts/claude-profile-sharing.ts b/src/main/claude-accounts/profiles/setup/claude-profile-sharing.ts similarity index 89% rename from src/main/claude-accounts/claude-profile-sharing.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-sharing.ts index fa92c65f6a2..8a942b2e9cf 100644 --- a/src/main/claude-accounts/claude-profile-sharing.ts +++ b/src/main/claude-accounts/profiles/setup/claude-profile-sharing.ts @@ -10,9 +10,9 @@ import { unlinkSync } from 'node:fs' import { dirname } from 'node:path' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import type { ClaudeProfileSurfaceOutcome } from './claude-profile-report' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' +import { writeFileAtomically } from '../../../filesystem/atomic-file-publication' +import type { ClaudeProfileSurfaceOutcome } from '../claude-profile-report' export function linkClaudeProfileDirectory( source: string, diff --git a/src/main/claude-accounts/claude-profile-state.ts b/src/main/claude-accounts/profiles/setup/claude-profile-state.ts similarity index 100% rename from src/main/claude-accounts/claude-profile-state.ts rename to src/main/claude-accounts/profiles/setup/claude-profile-state.ts diff --git a/src/main/claude-accounts/claude-profile-wsl-entry.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-entry.ts similarity index 100% rename from src/main/claude-accounts/claude-profile-wsl-entry.ts rename to src/main/claude-accounts/profiles/wsl/claude-profile-wsl-entry.ts diff --git a/src/main/claude-accounts/claude-profile-wsl-paths.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-paths.ts similarity index 97% rename from src/main/claude-accounts/claude-profile-wsl-paths.ts rename to src/main/claude-accounts/profiles/wsl/claude-profile-wsl-paths.ts index 9b1ac2b7cc7..40b965ab35a 100644 --- a/src/main/claude-accounts/claude-profile-wsl-paths.ts +++ b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-paths.ts @@ -1,5 +1,5 @@ import { basename, posix } from 'node:path' -import { describeClaudeProfile, type ClaudeProfileDescriptor } from './claude-profile-paths' +import { describeClaudeProfile, type ClaudeProfileDescriptor } from '../claude-profile-paths' export function wslClaudeProfile( guestHome: string, diff --git a/src/main/claude-accounts/claude-profile-wsl-provision.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-provision.ts similarity index 95% rename from src/main/claude-accounts/claude-profile-wsl-provision.ts rename to src/main/claude-accounts/profiles/wsl/claude-profile-wsl-provision.ts index a174816d0f0..429d26a7282 100644 --- a/src/main/claude-accounts/claude-profile-wsl-provision.ts +++ b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-provision.ts @@ -1,7 +1,7 @@ import { provisionClaudeAccountProfile, type ClaudeProfileSetupReport -} from './claude-profile-setup' +} from '../setup/claude-profile-setup' import { wslClaudeProfile } from './claude-profile-wsl-paths' /** diff --git a/src/main/claude-accounts/claude-profile-wsl-router.test.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts similarity index 68% rename from src/main/claude-accounts/claude-profile-wsl-router.test.ts rename to src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts index cb622b5601c..863eaa8ff15 100644 --- a/src/main/claude-accounts/claude-profile-wsl-router.test.ts +++ b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts @@ -1,4 +1,4 @@ -import type { BlockedWslDistro } from '../wsl/filesystem/wsl-unc-access-gate' +import type { BlockedWslDistro } from '../../../wsl/filesystem/wsl-unc-access-gate' import { spawnSync } from 'node:child_process' import { existsSync, @@ -7,16 +7,15 @@ import { mkdtempSync, readFileSync, rmSync, - symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { build } from 'esbuild' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ClaudeManagedAccount } from '../../shared/managed-account-types' -import type { WslSpec } from '../wsl/execution/wsl-runner' -import type * as WslPaths from '../../shared/wsl-paths' +import type { ClaudeManagedAccount } from '../../../../shared/managed-account-types' +import type { WslSpec } from '../../../wsl/execution/wsl-runner' +import type * as WslPaths from '../../../../shared/wsl-paths' const guest = vi.hoisted( (): { home: string; failure: { code: number; stdout: string } | null } => ({ @@ -25,11 +24,11 @@ const guest = vi.hoisted( }) ) // Emulate the guest with local POSIX paths and /bin/sh. -vi.mock('../../shared/wsl-paths', async (original) => ({ +vi.mock('../../../../shared/wsl-paths', async (original) => ({ ...(await original()), toWindowsWslPath: (linuxPath: string) => linuxPath })) -vi.mock('../wsl/discovery/distro-catalog', () => ({ +vi.mock('../../../wsl/discovery/distro-catalog', () => ({ getWslHomeAsync: async (distro: string) => `\\\\wsl.localhost\\${distro}${guest.home}`, listRunningWslDistrosAsync: async () => ['Ubuntu'] })) @@ -38,8 +37,10 @@ const gate = vi.hoisted(() => ({ async (_path: string, _distro?: string | null): Promise => null ) })) -vi.mock('../wsl/filesystem/wsl-unc-access-gate', () => ({ blockedWslDistroForPath: gate.blocked })) -vi.mock('../wsl/execution/wsl-runner', () => ({ +vi.mock('../../../wsl/filesystem/wsl-unc-access-gate', () => ({ + blockedWslDistroForPath: gate.blocked +})) +vi.mock('../../../wsl/execution/wsl-runner', () => ({ runWslProcess: async (spec: WslSpec) => { if (guest.failure) { return { ...guest.failure, stderr: '', timedOut: false } @@ -50,11 +51,10 @@ vi.mock('../wsl/execution/wsl-runner', () => ({ return { code: result.status, stdout: result.stdout, stderr: result.stderr, timedOut: false } } })) -import { CLAUDE_PROFILE_SETUP_FAILED_MESSAGE } from '../../shared/claude-profile-routing' -import type { ClaudeProfileRouterSettings } from './claude-profile-router' -import { prepareClaudeProfileDirectory } from './claude-profile-paths' + +import type { ClaudeProfileRouterSettings } from '../routing/claude-profile-router' + import { ClaudeWslProfileRouter } from './claude-profile-wsl-router' -import { wslClaudeProfile } from './claude-profile-wsl-paths' // Guest emulation runs POSIX scripts and the Linux Node bundle. const posixHost = process.platform !== 'win32' @@ -123,66 +123,6 @@ describe.skipIf(!posixHost)('ClaudeWslProfileRouter', () => { expect(existsSync(f.pointer)).toBe(false) }) - it('makes a launch redo a first setup that was cut off after its ownership gate', async () => { - const f = fixture() - mkdirSync(f.profileHome, { recursive: true }) - const cutOff = new ClaudeWslProfileRouter({ - getSettings: () => f.settings, - dataRoot: join(guest.home, '..', 'orca-dev'), - runSetup: async (distro, home, accountId) => { - const { dataRoot, profile } = wslClaudeProfile(home, distro, accountId) - prepareClaudeProfileDirectory(dataRoot, profile, home) - throw new Error('timed out') - } - }) - await expect(cutOff.prepareLaunch('Ubuntu')).rejects.toThrow( - CLAUDE_PROFILE_SETUP_FAILED_MESSAGE - ) - expect(existsSync(join(f.profileHome, '..', 'profile.json'))).toBe(false) - - await f.router.prepareLaunch('Ubuntu') - expect(f.setup.calls).toBe(1) - }) - - it('sets up a new account folder for sign-in and deletes it without following its links', async () => { - const f = fixture() - const sharedHistory = join(guest.home, '.claude', 'projects') - mkdirSync(sharedHistory) - writeFileSync(join(sharedHistory, 'chat.jsonl'), '{}') - // The setup stub always writes account a's folder, even when preparing b. - mkdirSync(f.profileHome, { recursive: true }) - const home = await f.router.prepareAccount('Ubuntu', 'b') - expect(home).toBe(join(guest.home, '.local/share/orca/claude-profiles/b/home')) - expect(f.setup.calls).toBe(1) - mkdirSync(home, { recursive: true }) - symlinkSync(sharedHistory, join(home, 'projects')) - - await f.router.removeAccount('Ubuntu', 'b') - expect(existsSync(join(home, '..'))).toBe(false) - expect(existsSync(join(sharedHistory, 'chat.jsonl'))).toBe(true) - - f.setup.fail = true - await expect(f.router.prepareAccount('Ubuntu', 'c')).rejects.toThrow( - CLAUDE_PROFILE_SETUP_FAILED_MESSAGE - ) - }) - - it('removes a guest folder only after its running setup, so the setup cannot bring it back', async () => { - const f = fixture() - mkdirSync(f.profileHome, { recursive: true }) - let release = () => {} - f.setup.gate = new Promise((resolve) => (release = resolve)).then(() => { - mkdirSync(f.profileHome, { recursive: true }) - }) - await f.router.publish('Ubuntu') - await vi.waitFor(() => expect(f.setup.calls).toBe(1)) - const removal = f.router.removeAccount('Ubuntu', 'a') - await new Promise((resolve) => setTimeout(resolve, 50)) - release() - await removal - expect(existsSync(join(f.profileHome, '..'))).toBe(false) - }) - it('a launch waiting on setup leaves a selection made meanwhile in the pointer', async () => { const f = fixture() mkdirSync(f.profileHome, { recursive: true }) @@ -254,7 +194,7 @@ it.skipIf(!posixHost)( mkdirSync(profileHome, { recursive: true }) const helper = join(root, 'claude-profile-wsl.cjs') await build({ - entryPoints: [resolve('src/main/claude-accounts/claude-profile-wsl-entry.ts')], + entryPoints: [resolve('src/main/claude-accounts/profiles/wsl/claude-profile-wsl-entry.ts')], outfile: helper, bundle: true, platform: 'node', diff --git a/src/main/claude-accounts/claude-profile-wsl-router.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts similarity index 90% rename from src/main/claude-accounts/claude-profile-wsl-router.ts rename to src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts index 7def9cf8475..4964813369c 100644 --- a/src/main/claude-accounts/claude-profile-wsl-router.ts +++ b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts @@ -1,35 +1,38 @@ import { existsSync } from 'node:fs' import { lstat, readFile } from 'node:fs/promises' import { join, posix } from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' +import { getAppEnvironment } from '../../../../shared/app-environment' import { CLAUDE_INJECTED_CONFIG_DIR_ENV, CLAUDE_PROFILE_POINTER_ENV, CLAUDE_PROFILE_SETUP_FAILED_MESSAGE -} from '../../shared/claude-profile-routing' -import { WSL_CLAUDE_PROFILE_HELPER_FILENAME } from '../../shared/remote-bundle-artifacts' -import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' -import { getWslHomeAsync, listRunningWslDistrosAsync } from '../wsl/discovery/distro-catalog' -import { ensureWslPinnedRuntime } from '../wsl/execution/wsl-pinned-runtime' -import { relayBundleCandidates } from '../wsl/execution/relay-bundle-paths' -import { runWslProcess, type WslSpec } from '../wsl/execution/wsl-runner' -import { describeWslProcessFailure } from '../wsl/execution/wsl-process-failure' -import { blockedWslDistroForPath } from '../wsl/filesystem/wsl-unc-access-gate' -import { claudeProfileMarkerPath, type ClaudeProfileDescriptor } from './claude-profile-paths' -import type { ClaudeProfileRouterSettings } from './claude-profile-router' -import { claudeProfileMissing, claudeProfileSetupFailed } from './claude-profile-launch-errors' +} from '../../../../shared/claude-profile-routing' +import { WSL_CLAUDE_PROFILE_HELPER_FILENAME } from '../../../../shared/remote-bundle-artifacts' +import { parseWslUncPath, toWindowsWslPath } from '../../../../shared/wsl-paths' +import { getWslHomeAsync, listRunningWslDistrosAsync } from '../../../wsl/discovery/distro-catalog' +import { ensureWslPinnedRuntime } from '../../../wsl/execution/wsl-pinned-runtime' +import { relayBundleCandidates } from '../../../wsl/execution/relay-bundle-paths' +import { runWslProcess, type WslSpec } from '../../../wsl/execution/wsl-runner' +import { describeWslProcessFailure } from '../../../wsl/execution/wsl-process-failure' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import { claudeProfileMarkerPath, type ClaudeProfileDescriptor } from '../claude-profile-paths' +import type { ClaudeProfileRouterSettings } from '../routing/claude-profile-router' +import { + claudeProfileMissing, + claudeProfileSetupFailed +} from '../routing/claude-profile-launch-errors' import { isSameClaudeLogin, readClaudeFolderLoginAsync, type ClaudeFolderLogin -} from './claude-account-folder' +} from '../../sign-in/claude-account-folder' import { wslClaudeProfile, wslClaudeProfilePointer } from './claude-profile-wsl-paths' -import type { ClaudeRuntimeAuthPreparation } from './runtime-auth/runtime-auth-types' +import type { ClaudeRuntimeAuthPreparation } from '../../runtime-auth/runtime-auth-types' import { findClaudeAccount, getClaudeWslSelectionKey, getSelectedClaudeAccountIdForTarget -} from './runtime-selection' +} from '../../selection/runtime-selection' type WslSetup = (distro: string, guestHome: string, accountId: string) => Promise diff --git a/src/main/claude-accounts/runtime-auth-service.test.ts b/src/main/claude-accounts/runtime-auth-service.test.ts deleted file mode 100644 index 38141690390..00000000000 --- a/src/main/claude-accounts/runtime-auth-service.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../shared/constants' -import type { GlobalSettings } from '../../shared/global-settings-types' - -const fakes = vi.hoisted(() => ({ - host: { - prepareLaunch: async () => ({ runtime: 'host' }), - publish: () => {}, - systemDefaultHome: () => '/host/.claude' - }, - wsl: { - prepareLaunch: async (distro: string) => ({ runtime: 'wsl', wslDistro: distro }), - preparation: async (distro: string) => ({ runtime: 'wsl', wslDistro: distro }), - publish: async (_distro: string): Promise => {}, - runningDistros: async (): Promise => [] - } -})) -vi.mock('../../shared/app-environment', () => ({ - getAppEnvironment: () => ({ getPath: () => '/data/orca' }) -})) -vi.mock('../wsl/discovery/distro-catalog', () => ({ - getDefaultWslDistro: () => 'Ubuntu', - getWslHome: (distro: string) => `/wsl/${distro}/home` -})) -vi.mock('./claude-profile-router', () => ({ - ClaudeProfileRouter: function ClaudeProfileRouter() { - return fakes.host - } -})) -vi.mock('./claude-profile-wsl-router', () => ({ - ClaudeWslProfileRouter: function ClaudeWslProfileRouter() { - return fakes.wsl - } -})) -vi.mock('./claude-profile-installed-router', () => ({ - installClaudeObservedConfigDirs: () => {}, - installClaudeProfileRouter: () => {}, - installClaudeWslProfileRouter: () => {} -})) - -import { ClaudeRuntimeAuthService } from './runtime-auth-service' - -const platform = Object.getOwnPropertyDescriptor(process, 'platform')! -function service( - platformName: NodeJS.Platform, - overrides: Partial = {}, - isDistroRunning: (distro: string) => Promise = async () => true -) { - Object.defineProperty(process, 'platform', { configurable: true, value: platformName }) - const settings = { ...getDefaultSettings('/home/user'), ...overrides } - return new ClaudeRuntimeAuthService({ getSettings: () => settings }, isDistroRunning) -} - -beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) -}) -afterEach(() => { - Object.defineProperty(process, 'platform', platform) - vi.restoreAllMocks() -}) - -describe('ClaudeRuntimeAuthService', () => { - it('never fails a select over a failed guest publish, and publishes one pass at a time', async () => { - const auth = service('win32') - vi.spyOn(fakes.wsl, 'publish').mockRejectedValue(new Error('distro is gone')) - await expect( - auth.syncForCurrentSelection({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - ).resolves.toBeUndefined() - - const order: string[] = [] - let release = () => {} - const gate = new Promise((resolve) => (release = resolve)) - vi.spyOn(fakes.host, 'publish').mockImplementation(() => order.push('host')) - vi.spyOn(fakes.wsl, 'runningDistros') - .mockImplementationOnce(async () => { - await gate - order.push('first guests') - return [] - }) - .mockResolvedValue([]) - const first = auth.publishAll() - const second = auth.publishAll() - await new Promise((resolve) => setTimeout(resolve, 10)) - expect(order).toEqual(['host']) - release() - await Promise.all([first, second]) - expect(order).toEqual(['host', 'first guests', 'host']) - }) -}) diff --git a/src/main/claude-accounts/runtime-auth-service.ts b/src/main/claude-accounts/runtime-auth-service.ts index f9e665c5db2..42889693404 100644 --- a/src/main/claude-accounts/runtime-auth-service.ts +++ b/src/main/claude-accounts/runtime-auth-service.ts @@ -5,19 +5,17 @@ import { resolveLocalAccountRuntimeTarget } from '../../shared/local-account-run import type { Store } from '../persistence/loading-store/store' import { isWslDistroRunning } from '../wsl/discovery/wsl-background-distro-gate' import { getDefaultWslDistro, getWslHome } from '../wsl/discovery/distro-catalog' -import { ClaudeProfileRouter } from './claude-profile-router' -import { ClaudeWslProfileRouter } from './claude-profile-wsl-router' +import { ClaudeProfileRouter } from './profiles/routing/claude-profile-router' +import { ClaudeWslProfileRouter } from './profiles/wsl/claude-profile-wsl-router' import { installClaudeObservedConfigDirs, installClaudeProfileRouter, installClaudeWslProfileRouter -} from './claude-profile-installed-router' -import { ClaudeObservedConfigDirs } from './claude-observed-config-dirs' -import type { ClaudeAccountSelectionTarget } from './runtime-selection' +} from './profiles/routing/claude-profile-installed-router' +import { ClaudeObservedConfigDirs } from './profiles/routing/claude-observed-config-dirs' +import type { ClaudeAccountSelectionTarget } from './selection/runtime-selection' import type { ClaudeRuntimeAuthPreparation } from './runtime-auth/runtime-auth-types' -export type { ClaudeRuntimeAuthPreparation } from './runtime-auth/runtime-auth-types' - /** `readPath` exposes a guest configDir to the host through UNC on WSL. */ export type ClaudeAccountFolder = { configDir: string; readPath: string } diff --git a/src/main/claude-accounts/claude-structured-auth-policy.test.ts b/src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts similarity index 92% rename from src/main/claude-accounts/claude-structured-auth-policy.test.ts rename to src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts index 55036620abf..b5bf34dc7cc 100644 --- a/src/main/claude-accounts/claude-structured-auth-policy.test.ts +++ b/src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { ClaudeManagedAccount } from '../../shared/managed-account-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { ClaudeManagedAccount } from '../../../shared/managed-account-types' import { isHostManagedClaudeAccount } from './environment' import { claudeStructuredAuthPolicyForSettings } from './claude-structured-auth-policy' diff --git a/src/main/claude-accounts/claude-structured-auth-policy.ts b/src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.ts similarity index 73% rename from src/main/claude-accounts/claude-structured-auth-policy.ts rename to src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.ts index c825d138732..47c52b29ca4 100644 --- a/src/main/claude-accounts/claude-structured-auth-policy.ts +++ b/src/main/claude-accounts/runtime-auth/claude-structured-auth-policy.ts @@ -1,8 +1,8 @@ -import type { AgentSessionAccountKind } from '../../shared/agent-session/agent-session-availability' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { getClaudeProfileRouter } from './claude-profile-installed-router' +import type { AgentSessionAccountKind } from '../../../shared/agent-session/agent-session-availability' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { getClaudeProfileRouter } from '../profiles/routing/claude-profile-installed-router' import { isHostManagedClaudeAccount } from './environment' -import { getSelectedClaudeAccountIdForTarget } from './runtime-selection' +import { getSelectedClaudeAccountIdForTarget } from '../selection/runtime-selection' /** Label sign-in failures without changing inherited Anthropic authentication. */ export type ClaudeStructuredAuthPolicy = { diff --git a/src/main/claude-accounts/environment.ts b/src/main/claude-accounts/runtime-auth/environment.ts similarity index 95% rename from src/main/claude-accounts/environment.ts rename to src/main/claude-accounts/runtime-auth/environment.ts index dbba876dc50..583cf6a99d6 100644 --- a/src/main/claude-accounts/environment.ts +++ b/src/main/claude-accounts/runtime-auth/environment.ts @@ -1,9 +1,9 @@ -import type { ClaudeManagedAccount } from '../../shared/managed-account-types' +import type { ClaudeManagedAccount } from '../../../shared/managed-account-types' import { CLAUDE_INJECTED_CONFIG_DIR_ENV, CLAUDE_PROFILE_POINTER_ENV, CLAUDE_USER_CONFIG_DIR_ENV -} from '../../shared/claude-profile-routing' +} from '../../../shared/claude-profile-routing' export const CLAUDE_AUTH_ENV_VARS = [ 'ANTHROPIC_API_KEY', diff --git a/src/main/claude-accounts/keychain-config-directory-aliases.test.ts b/src/main/claude-accounts/runtime-auth/keychain-config-directory-aliases.test.ts similarity index 100% rename from src/main/claude-accounts/keychain-config-directory-aliases.test.ts rename to src/main/claude-accounts/runtime-auth/keychain-config-directory-aliases.test.ts diff --git a/src/main/claude-accounts/keychain.ts b/src/main/claude-accounts/runtime-auth/keychain.ts similarity index 97% rename from src/main/claude-accounts/keychain.ts rename to src/main/claude-accounts/runtime-auth/keychain.ts index bc250727864..5bb6f34b6aa 100644 --- a/src/main/claude-accounts/keychain.ts +++ b/src/main/claude-accounts/runtime-auth/keychain.ts @@ -2,7 +2,7 @@ import { createHash } from 'node:crypto' import { lstatSync, realpathSync } from 'node:fs' import { userInfo } from 'node:os' import { basename, dirname, join } from 'node:path' -import { readKeychainPassword } from '../macos-keychain/generic-password' +import { readKeychainPassword } from '../../macos-keychain/generic-password' const ACTIVE_CLAUDE_SERVICE = 'Claude Code-credentials' export async function readActiveClaudeKeychainCredentialsStrict( diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts index 42082d211a9..df7fe11cc37 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts @@ -1,4 +1,4 @@ -import type { ClaudeEnvPatch } from '../environment' +import type { ClaudeEnvPatch } from './environment' export type ClaudeRuntimeAuthPreparation = { configDir: string diff --git a/src/main/claude-accounts/runtime-paths.ts b/src/main/claude-accounts/runtime-auth/runtime-paths.ts similarity index 100% rename from src/main/claude-accounts/runtime-paths.ts rename to src/main/claude-accounts/runtime-auth/runtime-paths.ts diff --git a/src/main/claude-accounts/claude-account-selection.ts b/src/main/claude-accounts/selection/claude-account-selection.ts similarity index 95% rename from src/main/claude-accounts/claude-account-selection.ts rename to src/main/claude-accounts/selection/claude-account-selection.ts index 08fed8cba9b..f1867ab0005 100644 --- a/src/main/claude-accounts/claude-account-selection.ts +++ b/src/main/claude-accounts/selection/claude-account-selection.ts @@ -2,12 +2,12 @@ import type { ClaudeManagedAccount, ClaudeManagedAccountSummary, ClaudeRateLimitAccountsState -} from '../../shared/managed-account-types' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { RateLimitService } from '../rate-limits/service/rate-limit-service' -import { claudeStateFile, readClaudeFolderLogin } from './claude-account-folder' -import { savedWslClaudeAccountHome } from './claude-profile-wsl-paths' -import type { ClaudeRuntimeAuthService } from './runtime-auth-service' +} from '../../../shared/managed-account-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' +import { claudeStateFile, readClaudeFolderLogin } from '../sign-in/claude-account-folder' +import { savedWslClaudeAccountHome } from '../profiles/wsl/claude-profile-wsl-paths' +import type { ClaudeRuntimeAuthService } from '../runtime-auth-service' import { getClaudeSelectionTargetForAccount, getClaudeWslSelectionKey, diff --git a/src/main/claude-accounts/runtime-selection.test.ts b/src/main/claude-accounts/selection/runtime-selection.test.ts similarity index 96% rename from src/main/claude-accounts/runtime-selection.test.ts rename to src/main/claude-accounts/selection/runtime-selection.test.ts index 2b92536ae54..99389381382 100644 --- a/src/main/claude-accounts/runtime-selection.test.ts +++ b/src/main/claude-accounts/selection/runtime-selection.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' import { getSelectedClaudeAccountIdForTarget } from './runtime-selection' diff --git a/src/main/claude-accounts/runtime-selection.ts b/src/main/claude-accounts/selection/runtime-selection.ts similarity index 97% rename from src/main/claude-accounts/runtime-selection.ts rename to src/main/claude-accounts/selection/runtime-selection.ts index 06f00c025c6..2b88f835245 100644 --- a/src/main/claude-accounts/runtime-selection.ts +++ b/src/main/claude-accounts/selection/runtime-selection.ts @@ -1,8 +1,8 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' import type { ClaudeManagedAccount, ClaudeManagedAccountRuntimeSelection -} from '../../shared/managed-account-types' +} from '../../../shared/managed-account-types' export type ClaudeAccountSelectionTarget = { runtime?: 'host' | 'wsl' diff --git a/src/main/claude-accounts/service.ts b/src/main/claude-accounts/service.ts index b1921b9c119..c75bc1ab865 100644 --- a/src/main/claude-accounts/service.ts +++ b/src/main/claude-accounts/service.ts @@ -3,19 +3,19 @@ import type { ClaudeRateLimitAccountsState, ClaudeSignInRequest } from '../../shared/managed-account-types' -import { ClaudeAccountRegistration } from './claude-account-registration' +import { ClaudeAccountRegistration } from './sign-in/claude-account-registration' import { ClaudeAccountSelection, type ClaudeAccountRuntime, type ClaudeAccountStore, type ClaudeAccountUsage -} from './claude-account-selection' -import { runClaudeCommandProcess } from './claude-command-process' -import { runClaudeLoginSession } from './claude-login-session' -import { runClaudePastedCodeLogin } from './claude-pasted-code-login' +} from './selection/claude-account-selection' +import { runClaudeCommandProcess } from './sign-in/claude-command-process' +import { runClaudeLoginSession } from './sign-in/claude-login-session' +import { runClaudePastedCodeLogin } from './sign-in/claude-pasted-code-login' import type { HostAccountSignInChannel } from '../../shared/host-account-sign-in-types' import type { ClaudeRuntimeAuthService } from './runtime-auth-service' -import type { ClaudeAccountSelectionTarget } from './runtime-selection' +import type { ClaudeAccountSelectionTarget } from './selection/runtime-selection' export class ClaudeAccountService { private mutationQueue: Promise = Promise.resolve() diff --git a/src/main/claude-accounts/claude-account-folder.test.ts b/src/main/claude-accounts/sign-in/claude-account-folder.test.ts similarity index 96% rename from src/main/claude-accounts/claude-account-folder.test.ts rename to src/main/claude-accounts/sign-in/claude-account-folder.test.ts index b14649168c4..7ac8354ca18 100644 --- a/src/main/claude-accounts/claude-account-folder.test.ts +++ b/src/main/claude-accounts/sign-in/claude-account-folder.test.ts @@ -9,7 +9,7 @@ vi.mock('node:os', async (original) => ({ ...(await original()), homedir: () => keychain.userHome })) -vi.mock('../macos-keychain/generic-password', () => ({ +vi.mock('../../macos-keychain/generic-password', () => ({ execSecurityCommand: async (args: string[]) => { const service = args[2] const count = keychain.items.get(service) ?? 0 @@ -23,7 +23,7 @@ vi.mock('../macos-keychain/generic-password', () => ({ import { removeClaudeAccountFolder } from './claude-account-folder' -import { claudeKeychainService } from './keychain' +import { claudeKeychainService } from '../runtime-auth/keychain' const roots: string[] = [] afterEach(() => { diff --git a/src/main/claude-accounts/claude-account-folder.ts b/src/main/claude-accounts/sign-in/claude-account-folder.ts similarity index 96% rename from src/main/claude-accounts/claude-account-folder.ts rename to src/main/claude-accounts/sign-in/claude-account-folder.ts index b227ad312be..562a14c70ba 100644 --- a/src/main/claude-accounts/claude-account-folder.ts +++ b/src/main/claude-accounts/sign-in/claude-account-folder.ts @@ -11,10 +11,10 @@ import { readFile, stat } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, join } from 'node:path' import { z } from 'zod' -import { resolveClaudeGlobalConfigFile } from '../claude/claude-folder-trust-file' -import { execSecurityCommand } from '../macos-keychain/generic-password' -import { describeClaudeProfile, readClaudeProfileObject } from './claude-profile-paths' -import { claudeConfigDirSpellings, claudeKeychainService } from './keychain' +import { resolveClaudeGlobalConfigFile } from '../../claude/claude-folder-trust-file' +import { execSecurityCommand } from '../../macos-keychain/generic-password' +import { describeClaudeProfile, readClaudeProfileObject } from '../profiles/claude-profile-paths' +import { claudeConfigDirSpellings, claudeKeychainService } from '../runtime-auth/keychain' export type ClaudeFolderLogin = { email: string diff --git a/src/main/claude-accounts/claude-account-registration.ts b/src/main/claude-accounts/sign-in/claude-account-registration.ts similarity index 97% rename from src/main/claude-accounts/claude-account-registration.ts rename to src/main/claude-accounts/sign-in/claude-account-registration.ts index 29f0782e6eb..c8ae04602f0 100644 --- a/src/main/claude-accounts/claude-account-registration.ts +++ b/src/main/claude-accounts/sign-in/claude-account-registration.ts @@ -3,21 +3,21 @@ import type { ClaudeAccountSignIn, ClaudeRateLimitAccountsState, ClaudeSignInRequest -} from '../../shared/managed-account-types' +} from '../../../shared/managed-account-types' import { claudeStateFile, readClaudeFolderLogin } from './claude-account-folder' import type { ClaudeAccountRuntime, ClaudeAccountSelection, ClaudeAccountStore, ClaudeAccountUsage -} from './claude-account-selection' +} from '../selection/claude-account-selection' import type { ClaudeCommandConfig } from './claude-command-process' import { findDuplicateClaudeAccount } from './claude-duplicate-account' import { getClaudeSelectionTargetForAccount, normalizeClaudeAccountSelectionTarget, type ClaudeAccountSelectionTarget -} from './runtime-selection' +} from '../selection/runtime-selection' export const CLAUDE_SIGN_IN_NOT_FINISHED_MESSAGE = 'Claude has not finished signing in to this account yet. Finish the sign-in in the terminal, then try again.' diff --git a/src/main/claude-accounts/claude-command-process-windows-only.test.ts b/src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts similarity index 97% rename from src/main/claude-accounts/claude-command-process-windows-only.test.ts rename to src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts index 947bea6925c..a41f4460f23 100644 --- a/src/main/claude-accounts/claude-command-process-windows-only.test.ts +++ b/src/main/claude-accounts/sign-in/claude-command-process-windows-only.test.ts @@ -29,7 +29,7 @@ vi.mock('@orca/process-host', () => ({ return child } })) -vi.mock('../codex-cli/command', () => ({ +vi.mock('../../codex-cli/command', () => ({ resolveClaudeCommand: () => state.resolved.shift() ?? '/home/me/.local/bin/claude' })) diff --git a/src/main/claude-accounts/claude-command-process.ts b/src/main/claude-accounts/sign-in/claude-command-process.ts similarity index 93% rename from src/main/claude-accounts/claude-command-process.ts rename to src/main/claude-accounts/sign-in/claude-command-process.ts index 75242562b95..33a55e73814 100644 --- a/src/main/claude-accounts/claude-command-process.ts +++ b/src/main/claude-accounts/sign-in/claude-command-process.ts @@ -1,21 +1,24 @@ import { spawnProcess } from '@orca/process-host' -import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' +import { withCliRuntimeOnPath } from '../../../shared/node-cli-command-resolution' import { buildWindowsHostInteractiveLoginSpawn, type WindowsHostInteractiveLoginSpawn -} from '../../shared/windows-interactive-login-spawn' -import { buildWslExecArgs, buildWslLoginShellCommand } from '../../shared/wsl-login-shell-command' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { resolveClaudeCommand } from '../codex-cli/command' +} from '../../../shared/windows-interactive-login-spawn' +import { + buildWslExecArgs, + buildWslLoginShellCommand +} from '../../../shared/wsl-login-shell-command' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { resolveClaudeCommand } from '../../codex-cli/command' import { isSpawnEnoent, isWindowsOnlyAgentCommand, windowsOnlyCliMessage -} from '../codex-cli/windows-only-agent-cli' -import { resolveWslExecutablePath } from '../wsl/execution/wsl-executable-path' +} from '../../codex-cli/windows-only-agent-cli' +import { resolveWslExecutablePath } from '../../wsl/execution/wsl-executable-path' import { buildWindowsCommandInvocation } from './windows-command-invocation' import { terminateClaudeProcess } from './claude-login-process-termination' -import { stripInheritedAgentSessionEnv } from '../../shared/agent-launch/startup/parent-agent-session-env' +import { stripInheritedAgentSessionEnv } from '../../../shared/agent-launch/startup/parent-agent-session-env' const MAX_COMMAND_OUTPUT_CHARS = 4_000 const CLAUDE_AUTH_DENIED_PATTERN = diff --git a/src/main/claude-accounts/claude-duplicate-account.ts b/src/main/claude-accounts/sign-in/claude-duplicate-account.ts similarity index 90% rename from src/main/claude-accounts/claude-duplicate-account.ts rename to src/main/claude-accounts/sign-in/claude-duplicate-account.ts index 191c13b2e93..0aad4a7fb30 100644 --- a/src/main/claude-accounts/claude-duplicate-account.ts +++ b/src/main/claude-accounts/sign-in/claude-duplicate-account.ts @@ -1,5 +1,5 @@ -import type { ClaudeManagedAccountSummary } from '../../shared/managed-account-types' -import { getClaudeWslSelectionKey } from './runtime-selection' +import type { ClaudeManagedAccountSummary } from '../../../shared/managed-account-types' +import { getClaudeWslSelectionKey } from '../selection/runtime-selection' export type ClaudeAccountIdentityCandidate = { email: string | null diff --git a/src/main/claude-accounts/claude-login-process-termination.ts b/src/main/claude-accounts/sign-in/claude-login-process-termination.ts similarity index 88% rename from src/main/claude-accounts/claude-login-process-termination.ts rename to src/main/claude-accounts/sign-in/claude-login-process-termination.ts index f9c8f00fc2f..70e359b4902 100644 --- a/src/main/claude-accounts/claude-login-process-termination.ts +++ b/src/main/claude-accounts/sign-in/claude-login-process-termination.ts @@ -1,8 +1,8 @@ import { spawnProcess } from '@orca/process-host' import type { ChildProcess } from 'node:child_process' -import type { WindowsHostInteractiveLoginSpawn } from '../../shared/windows-interactive-login-spawn' -import { recordSelfInitiatedTreeKill } from '../crash-reporting/process-exits/self-initiated-tree-kill-log' -import { admitSelfInitiatedTreeKill } from '../pty/process-retirement/own-chromium-tree-kill-guard' +import type { WindowsHostInteractiveLoginSpawn } from '../../../shared/windows-interactive-login-spawn' +import { recordSelfInitiatedTreeKill } from '../../crash-reporting/process-exits/self-initiated-tree-kill-log' +import { admitSelfInitiatedTreeKill } from '../../pty/process-retirement/own-chromium-tree-kill-guard' const WINDOWS_TASKKILL_TIMEOUT_MS = 5_000 diff --git a/src/main/claude-accounts/claude-login-session.test.ts b/src/main/claude-accounts/sign-in/claude-login-session.test.ts similarity index 76% rename from src/main/claude-accounts/claude-login-session.test.ts rename to src/main/claude-accounts/sign-in/claude-login-session.test.ts index dd81f503449..e3e84176e38 100644 --- a/src/main/claude-accounts/claude-login-session.test.ts +++ b/src/main/claude-accounts/sign-in/claude-login-session.test.ts @@ -67,28 +67,4 @@ describe('runClaudeLoginSession', () => { expect(onLink).toHaveBeenCalledExactlyOnceWith(LINK) expect(openWslSignInLink).not.toHaveBeenCalled() }) - - it('never opens a link for a WSL login the user already cancelled', async () => { - const config = folder('wsl') - const openWslSignInLink = vi.fn() - let cancel: (() => boolean) | null = null - const runCommand = vi.fn(async (_args, _config, _ms, options) => { - handOverClaudeSignInLink(config.windowsPath, LINK) - expect(cancel?.()).toBe(true) - expect(options?.signal?.aborted).toBe(true) - // Allow a watcher poll to verify cancellation suppresses delivery. - await new Promise((resolve) => setTimeout(resolve, 300)) - throw new Error('Claude sign-in was cancelled.') - }) - await expect( - runClaudeLoginSession(config, { - runCommand, - setCancel: (next) => { - cancel ??= next - }, - openWslSignInLink - }) - ).rejects.toThrow('cancelled') - expect(openWslSignInLink).not.toHaveBeenCalled() - }) }) diff --git a/src/main/claude-accounts/claude-login-session.ts b/src/main/claude-accounts/sign-in/claude-login-session.ts similarity index 97% rename from src/main/claude-accounts/claude-login-session.ts rename to src/main/claude-accounts/sign-in/claude-login-session.ts index a0093f88b47..381e35d57a4 100644 --- a/src/main/claude-accounts/claude-login-session.ts +++ b/src/main/claude-accounts/sign-in/claude-login-session.ts @@ -1,4 +1,4 @@ -import { CLAUDE_SIGN_IN_FAILED_MESSAGE } from '../../shared/claude-sign-in-link' +import { CLAUDE_SIGN_IN_FAILED_MESSAGE } from '../../../shared/claude-sign-in-link' import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process' import { prepareClaudeSignInBrowser, type ClaudeSignInBrowser } from './claude-sign-in-browser' diff --git a/src/main/claude-accounts/claude-pasted-code-login.test.ts b/src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts similarity index 98% rename from src/main/claude-accounts/claude-pasted-code-login.test.ts rename to src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts index 5380c5f7027..b09dc864f2e 100644 --- a/src/main/claude-accounts/claude-pasted-code-login.test.ts +++ b/src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, readdirSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { HostAccountSignInChannel } from '../../shared/host-account-sign-in-types' +import type { HostAccountSignInChannel } from '../../../shared/host-account-sign-in-types' import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process' import { parseClaudePastedCodeSignInLink, diff --git a/src/main/claude-accounts/claude-pasted-code-login.ts b/src/main/claude-accounts/sign-in/claude-pasted-code-login.ts similarity index 95% rename from src/main/claude-accounts/claude-pasted-code-login.ts rename to src/main/claude-accounts/sign-in/claude-pasted-code-login.ts index 08e84cde607..cbcb1b37db6 100644 --- a/src/main/claude-accounts/claude-pasted-code-login.ts +++ b/src/main/claude-accounts/sign-in/claude-pasted-code-login.ts @@ -1,5 +1,5 @@ -import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences' -import type { HostAccountSignInChannel } from '../../shared/host-account-sign-in-types' +import { stripAnsiEscapeSequences } from '../../../shared/ansi-escape-sequences' +import type { HostAccountSignInChannel } from '../../../shared/host-account-sign-in-types' import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process' import { isClaudeLocalSignInLink, prepareClaudeSignInBrowser } from './claude-sign-in-browser' diff --git a/src/main/claude-accounts/claude-sign-in-browser.test.ts b/src/main/claude-accounts/sign-in/claude-sign-in-browser.test.ts similarity index 100% rename from src/main/claude-accounts/claude-sign-in-browser.test.ts rename to src/main/claude-accounts/sign-in/claude-sign-in-browser.test.ts diff --git a/src/main/claude-accounts/claude-sign-in-browser.ts b/src/main/claude-accounts/sign-in/claude-sign-in-browser.ts similarity index 98% rename from src/main/claude-accounts/claude-sign-in-browser.ts rename to src/main/claude-accounts/sign-in/claude-sign-in-browser.ts index ff4da747af6..d290c4ce05d 100644 --- a/src/main/claude-accounts/claude-sign-in-browser.ts +++ b/src/main/claude-accounts/sign-in/claude-sign-in-browser.ts @@ -4,7 +4,7 @@ import { setTimeout as delay } from 'node:timers/promises' import { CLAUDE_SIGN_IN_FAILED_MESSAGE, canCopyClaudeSignInLink -} from '../../shared/claude-sign-in-link' +} from '../../../shared/claude-sign-in-link' import type { ClaudeCommandConfig } from './claude-command-process' const HELPER_NAME = '.orca-sign-in-browser' diff --git a/src/main/claude-accounts/windows-command-invocation.test.ts b/src/main/claude-accounts/sign-in/windows-command-invocation.test.ts similarity index 100% rename from src/main/claude-accounts/windows-command-invocation.test.ts rename to src/main/claude-accounts/sign-in/windows-command-invocation.test.ts diff --git a/src/main/claude-accounts/windows-command-invocation.ts b/src/main/claude-accounts/sign-in/windows-command-invocation.ts similarity index 100% rename from src/main/claude-accounts/windows-command-invocation.ts rename to src/main/claude-accounts/sign-in/windows-command-invocation.ts diff --git a/src/main/claude-usage/scanner-incremental-append.test.ts b/src/main/claude-usage/scanner-incremental-append.test.ts deleted file mode 100644 index e8c862c0e47..00000000000 --- a/src/main/claude-usage/scanner-incremental-append.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { appendFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import type * as NodeFs from 'node:fs' -import type * as NodeFsPromises from 'node:fs/promises' -import type * as NodeOs from 'node:os' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { homedirMock, streamReads } = vi.hoisted(() => { - const streamReads: { path: string; start: number; bytes: number }[] = [] - return { homedirMock: vi.fn<() => string>(), streamReads } -}) - -vi.mock('node:os', async () => ({ - ...(await vi.importActual('node:os')), - homedir: homedirMock -})) - -vi.mock('../claude-accounts/claude-profile-installed-router', () => ({ - claudeProfileHistoryDirs: () => [] -})) - -vi.mock('node:fs', async () => { - const actual = await vi.importActual('node:fs') - return { - ...actual, - createReadStream: ( - path: Parameters[0], - options?: Parameters[1] - ) => { - const range = typeof options === 'object' && options !== null ? options : {} - const read = { path: String(path), start: range.start ?? 0, bytes: 0 } - streamReads.push(read) - const stream = actual.createReadStream(path, options) - stream.on('data', (chunk: string | Buffer) => { - read.bytes += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length - }) - return stream - } - } -}) - -vi.mock('node:fs/promises', async () => { - const actual = await vi.importActual('node:fs/promises') - return { - ...actual, - open: async (...args: Parameters) => { - const handle = await actual.open(...args) - const createStream = handle.createReadStream.bind(handle) - const readWindow = handle.read.bind(handle) - let streaming = false - vi.spyOn(handle, 'createReadStream').mockImplementation((options) => { - const read = { path: String(args[0]), start: options?.start ?? 0, bytes: 0 } - streamReads.push(read) - const stream = createStream(options) - streaming = true - stream.once('end', () => (streaming = false)) - stream.once('close', () => (streaming = false)) - stream.on('data', (chunk: string | Buffer) => { - read.bytes += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length - }) - return stream - }) - vi.spyOn(handle, 'read').mockImplementation(async (...readArgs) => { - const streamRead = streaming - const result = await readWindow(...readArgs) - if (streamRead) { - return result - } - const position = readArgs.at(-1) - streamReads.push({ - path: String(args[0]), - start: typeof position === 'number' ? position : 0, - bytes: result.bytesRead - }) - return result - }) - return handle - } - } -}) - -let root: string -let transcriptPath: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-usage-append-')) - homedirMock.mockReturnValue(root) - const projectDir = join(root, '.claude', 'projects', 'project-a') - await mkdir(projectDir, { recursive: true }) - transcriptPath = join(projectDir, 'active-session.jsonl') - streamReads.length = 0 - vi.resetModules() -}) - -afterEach(async () => { - await rm(root, { recursive: true, force: true }) -}) - -function usageRecord(index: number, inputTokens = 100, cacheReadTokens = 0): string { - return `${JSON.stringify({ - type: 'assistant', - sessionId: 'active-session', - timestamp: `2026-10-09T12:${String(index % 60).padStart(2, '0')}:00.000Z`, - requestId: `request-${index}`, - cwd: join(root, 'repo'), - message: { - id: `message-${index}`, - model: 'claude-sonnet-4-6', - usage: { - input_tokens: inputTokens, - output_tokens: 10, - cache_read_input_tokens: cacheReadTokens, - cache_creation_input_tokens: 20, - cache_creation: { ephemeral_1h_input_tokens: 5 } - } - } - })}\n` -} - -function prefixRecords(): string { - const toolResult = `${JSON.stringify({ type: 'user', content: '界'.repeat(350_000) })}\n` - return toolResult + Array.from({ length: 80 }, (_, index) => usageRecord(index)).join('') -} - -describe('Claude usage append scans', () => { - it('updates a previously counted assistant row with its later token maxima', async () => { - await writeFile(transcriptPath, prefixRecords()) - const { scanClaudeUsageFiles } = await import('./scanner') - const first = await scanClaudeUsageFiles([], [], undefined, []) - await appendFile(transcriptPath, usageRecord(3, 250, 40) + usageRecord(80)) - - const second = await scanClaudeUsageFiles([], first.processedFiles, undefined, []) - const cold = await scanClaudeUsageFiles([], [], undefined, []) - - expect(second.sessions).toEqual(cold.sessions) - expect(second.dailyAggregates).toEqual(cold.dailyAggregates) - expect(second.sessions[0]?.turnCount).toBe(81) - expect(second.sessions[0]?.totalInputTokens).toBe(8_250) - expect(second.sessions[0]?.totalCacheReadTokens).toBe(40) - expect(second.dailyAggregates[0]?.zeroCacheReadTurnCount).toBe(80) - }) -}) diff --git a/src/main/claude-usage/scanner-incremental-ownership.test.ts b/src/main/claude-usage/scanner-incremental-ownership.test.ts deleted file mode 100644 index 3396201d62b..00000000000 --- a/src/main/claude-usage/scanner-incremental-ownership.test.ts +++ /dev/null @@ -1,514 +0,0 @@ -import { appendFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import type * as NodeFs from 'node:fs' -import type * as NodeFsPromises from 'node:fs/promises' -import type * as NodeOs from 'node:os' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ClaudeUsagePersistedFile } from './types' -import type { ClaudeUsageWorktreeRef } from './worktree-attribution' - -const { homedirMock, streamReads } = vi.hoisted(() => { - const streamReads: { path: string; start: number; checkpointWindow: boolean; bytes: number }[] = - [] - return { homedirMock: vi.fn<() => string>(), streamReads } -}) - -vi.mock('node:os', async () => ({ - ...(await vi.importActual('node:os')), - homedir: homedirMock -})) - -vi.mock('../claude-accounts/claude-profile-installed-router', () => ({ - claudeProfileHistoryDirs: () => [] -})) - -vi.mock('node:fs', async () => { - const actual = await vi.importActual('node:fs') - return { - ...actual, - createReadStream: ( - path: Parameters[0], - options?: Parameters[1] - ) => { - const range = typeof options === 'object' && options !== null ? options : {} - return observeReadStream( - String(path), - range.start ?? 0, - range.end, - actual.createReadStream(path, options) - ) - } - } -}) - -vi.mock('node:fs/promises', async () => { - const actual = await vi.importActual('node:fs/promises') - return { - ...actual, - open: async ( - path: Parameters[0], - flags: Parameters[1], - mode?: Parameters[2] - ) => { - const handle = await actual.open(path, flags, mode) - const createReadStream = handle.createReadStream.bind(handle) - handle.createReadStream = (options) => - observeReadStream( - String(path), - options?.start ?? 0, - options?.end, - createReadStream(options) - ) - return handle - } - } -}) - -function observeReadStream( - path: string, - start: number, - end: number | undefined, - stream: NodeFs.ReadStream -): NodeFs.ReadStream { - const read = { - path, - start, - checkpointWindow: end !== undefined && end - start + 1 === 4096, - bytes: 0 - } - streamReads.push(read) - stream.on('data', (chunk: string | Buffer) => { - read.bytes += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length - }) - return stream -} - -type AssistantRowOptions = { - identified?: boolean - sessionId?: string - timestamp?: string - model?: string - cwd?: string - gitBranch?: string - inputTokens?: number - outputTokens?: number - cacheReadTokens?: number - cacheWriteTokens?: number - cacheWrite1hTokens?: number -} - -let root: string -let projectDir: string -let worktrees: ClaudeUsageWorktreeRef[] - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-append-ownership-')) - homedirMock.mockReturnValue(root) - projectDir = join(root, '.claude', 'projects', 'project-a') - worktrees = ['a', 'b'].map((id) => ({ - repoId: `repo-${id}`, - worktreeId: `worktree-${id}`, - path: join(root, `workspace-${id}`), - displayName: `Workspace ${id.toUpperCase()}` - })) - await Promise.all([ - mkdir(projectDir, { recursive: true }), - ...worktrees.map((worktree) => mkdir(worktree.path)) - ]) - streamReads.length = 0 - vi.resetModules() -}) - -afterEach(async () => { - await rm(root, { recursive: true, force: true }) -}) - -function assistantRow(key: string, options: AssistantRowOptions = {}): string { - return `${JSON.stringify({ - type: 'assistant', - sessionId: options.sessionId ?? 'owner-session', - timestamp: options.timestamp ?? '2026-10-09T12:00:00.000Z', - cwd: options.cwd ?? worktrees[0]?.path, - gitBranch: options.gitBranch ?? 'original-branch', - requestId: options.identified === false ? undefined : `request-${key}`, - message: { - id: options.identified === false ? undefined : `message-${key}`, - model: options.model ?? 'claude-sonnet-4-6', - usage: { - input_tokens: options.inputTokens ?? 10, - output_tokens: options.outputTokens ?? 0, - cache_read_input_tokens: options.cacheReadTokens ?? 0, - cache_creation_input_tokens: options.cacheWriteTokens ?? 0, - cache_creation: { ephemeral_1h_input_tokens: options.cacheWrite1hTokens ?? 0 } - } - } - })}\n` -} - -function largePrefix(label = 'original'): string { - // Tool-result padding clears the resume floor without introducing extra billable turns. - return `${JSON.stringify({ type: 'user', label, content: '界'.repeat(12_000) })}\n` -} - -function processedFile(files: ClaudeUsagePersistedFile[], path: string): ClaudeUsagePersistedFile { - const file = files.find((candidate) => candidate.path === path) - if (!file) { - throw new Error(`Expected a scanned file at ${path}`) - } - return file -} - -function parseReadOffsets(path: string): number[] { - return streamReads - .filter((read) => read.path === path && !read.checkpointWindow && read.bytes > 0) - .map((read) => read.start) -} - -async function scanner() { - const { scanClaudeUsageFiles } = await import('./scanner') - return (previous: ClaudeUsagePersistedFile[] = []) => - scanClaudeUsageFiles(worktrees, previous, undefined, []) -} - -describe('Claude usage append ownership', () => { - it.each([ - { kind: 'object', keys: { copiedKey: 'message-streamed:request-streamed' } }, - { kind: 'string', keys: 'message-streamed:request-streamed' } - ])( - 'reparses persisted ownership keys stored as a $kind without reserving invalid claims', - async ({ keys }) => { - const ownerPath = join(projectDir, 'aaaa-damaged-owner.jsonl') - const forkPath = join(projectDir, 'zzzz-late-fork.jsonl') - await writeFile(ownerPath, largePrefix() + assistantRow('streamed', { inputTokens: 100 })) - const scan = await scanner() - const first = await scan() - const cached: ClaudeUsagePersistedFile[] = JSON.parse(JSON.stringify(first.processedFiles)) - Reflect.set(processedFile(cached, ownerPath), 'ownedDedupeKeys', keys) - await appendFile(ownerPath, assistantRow('streamed', { inputTokens: 150 })) - await writeFile( - forkPath, - largePrefix() + - assistantRow('streamed', { sessionId: 'fork-session', inputTokens: 100 }) + - assistantRow('fork-new', { sessionId: 'fork-session', inputTokens: 50 }) - ) - streamReads.length = 0 - - const second = await scan(cached) - expect(parseReadOffsets(ownerPath)).toEqual([0]) - const cold = await scan() - expect(second.sessions).toEqual(cold.sessions) - expect(second.dailyAggregates).toEqual(cold.dailyAggregates) - expect(processedFile(second.processedFiles, ownerPath).ownedDedupeKeys).toEqual([ - 'message-streamed:request-streamed' - ]) - expect(processedFile(second.processedFiles, forkPath).ownedDedupeKeys).toEqual([ - 'message-fork-new:request-fork-new' - ]) - expect(second.sessions.reduce((total, session) => total + session.totalInputTokens, 0)).toBe( - 200 - ) - } - ) - - it('retains a resumed owner when a fork of its earlier history appears', async () => { - const ownerPath = join(projectDir, 'aaaa-owner.jsonl') - const forkPath = join(projectDir, 'zzzz-late-fork.jsonl') - await writeFile(ownerPath, largePrefix() + assistantRow('shared')) - const scan = await scanner() - const first = await scan() - const ownerOffset = processedFile(first.processedFiles, ownerPath).size - - await appendFile(ownerPath, assistantRow('owner-new', { inputTokens: 20 })) - await writeFile( - forkPath, - largePrefix() + - assistantRow('shared', { sessionId: 'fork-session' }) + - assistantRow('fork-new', { sessionId: 'fork-session', inputTokens: 30 }) - ) - streamReads.length = 0 - const second = await scan(first.processedFiles) - expect(parseReadOffsets(ownerPath)).toEqual([ownerOffset]) - expect(processedFile(second.processedFiles, ownerPath).ownedDedupeKeys).toEqual([ - 'message-shared:request-shared', - 'message-owner-new:request-owner-new' - ]) - expect(processedFile(second.processedFiles, forkPath).ownedDedupeKeys).toEqual([ - 'message-fork-new:request-fork-new' - ]) - expect(processedFile(second.processedFiles, forkPath).hasDeferredClaims).toBe(true) - - const cold = await scan() - expect(second.sessions).toEqual(cold.sessions) - expect(second.dailyAggregates).toEqual(cold.dailyAggregates) - expect(second.sessions.map((session) => [session.sessionId, session.turnCount])).toEqual([ - ['owner-session', 2], - ['fork-session', 1] - ]) - }) - - it('reclaims copied turns after a deferred fork resumes and its owner is deleted', async () => { - const ownerPath = join(projectDir, 'aaaa-owner.jsonl') - const forkPath = join(projectDir, 'zzzz-deferred-fork.jsonl') - await writeFile(ownerPath, largePrefix() + assistantRow('shared')) - await writeFile( - forkPath, - largePrefix() + - assistantRow('shared', { sessionId: 'fork-session' }) + - assistantRow('fork-new', { sessionId: 'fork-session', inputTokens: 20 }) - ) - const scan = await scanner() - const first = await scan() - const forkOffset = processedFile(first.processedFiles, forkPath).size - - await appendFile( - forkPath, - assistantRow('fork-later', { sessionId: 'fork-session', inputTokens: 30 }) - ) - streamReads.length = 0 - const second = await scan(first.processedFiles) - expect(parseReadOffsets(forkPath)).toEqual([forkOffset]) - expect(processedFile(second.processedFiles, forkPath).hasDeferredClaims).toBe(true) - - await rm(ownerPath) - const third = await scan(second.processedFiles) - const cold = await scan() - expect(third.sessions).toEqual(cold.sessions) - expect(third.dailyAggregates).toEqual(cold.dailyAggregates) - expect(third.sessions[0]?.turnCount).toBe(3) - expect(third.sessions[0]?.totalInputTokens).toBe(60) - expect(processedFile(third.processedFiles, forkPath).ownedDedupeKeys).toHaveLength(3) - }) - - it.each(['rewritten', 'truncated'])( - 'reclaims an unchanged fork after its owner is %s', - async (mode) => { - const ownerPath = join(projectDir, 'aaaa-owner.jsonl') - const forkPath = join(projectDir, 'zzzz-deferred-fork.jsonl') - await writeFile(ownerPath, largePrefix() + assistantRow('shared')) - await writeFile( - forkPath, - largePrefix() + - assistantRow('shared', { sessionId: 'fork-session' }) + - assistantRow('fork-new', { sessionId: 'fork-session', inputTokens: 20 }) - ) - const scan = await scanner() - const first = await scan() - const unrelated = assistantRow('replacement', { - sessionId: 'replacement-session', - inputTokens: 11 - }) - await writeFile( - ownerPath, - mode === 'rewritten' ? largePrefix('replacement') + unrelated : unrelated - ) - - const second = await scan(first.processedFiles) - const cold = await scan() - expect(second.sessions).toEqual(cold.sessions) - expect(second.dailyAggregates).toEqual(cold.dailyAggregates) - expect(processedFile(second.processedFiles, forkPath).ownedDedupeKeys).toEqual([ - 'message-shared:request-shared', - 'message-fork-new:request-fork-new' - ]) - expect(second.sessions.reduce((total, session) => total + session.totalInputTokens, 0)).toBe( - 41 - ) - } - ) - - it('keeps first-row metadata while applying independent token maxima across appends', async () => { - const transcriptPath = join(projectDir, 'first-metadata.jsonl') - await writeFile( - transcriptPath, - largePrefix() + assistantRow('streamed', { outputTokens: 2, cacheWriteTokens: 5 }) - ) - const scan = await scanner() - const first = await scan() - const firstOffset = processedFile(first.processedFiles, transcriptPath).size - const changedMetadata = { - sessionId: 'different-session', - timestamp: '2026-10-10T12:00:00.000Z', - model: 'claude-opus-4-6', - cwd: worktrees[1]?.path, - gitBranch: 'different-branch' - } - await appendFile( - transcriptPath, - assistantRow('streamed', { - ...changedMetadata, - inputTokens: 20, - outputTokens: 7, - cacheReadTokens: 100, - cacheWriteTokens: 8, - cacheWrite1hTokens: 3 - }) - ) - streamReads.length = 0 - const second = await scan(first.processedFiles) - expect(parseReadOffsets(transcriptPath)).toEqual([firstOffset]) - - await appendFile( - transcriptPath, - assistantRow('streamed', { - ...changedMetadata, - inputTokens: 15, - outputTokens: 12, - cacheReadTokens: 50, - cacheWriteTokens: 6, - cacheWrite1hTokens: 5 - }) - ) - streamReads.length = 0 - const third = await scan(second.processedFiles) - expect(parseReadOffsets(transcriptPath)).toEqual([ - processedFile(second.processedFiles, transcriptPath).size - ]) - const cold = await scan() - expect(third.sessions).toEqual(cold.sessions) - expect(third.dailyAggregates).toEqual(cold.dailyAggregates) - expect(third.sessions).toHaveLength(1) - expect(third.sessions[0]).toMatchObject({ - sessionId: 'owner-session', - firstTimestamp: '2026-10-09T12:00:00.000Z', - lastTimestamp: '2026-10-09T12:00:00.000Z', - model: 'claude-sonnet-4-6', - lastCwd: worktrees[0]?.path, - lastGitBranch: 'original-branch', - primaryWorktreeId: 'worktree-a', - turnCount: 1, - totalInputTokens: 20, - totalOutputTokens: 12, - totalCacheReadTokens: 100, - totalCacheWriteTokens: 8, - totalCacheWrite1hTokens: 5 - }) - expect(third.dailyAggregates[0]?.zeroCacheReadTurnCount).toBe(0) - }) - - it('keeps two keys aligned with distinct metadata after persisted appends arrive in reversed key order', async () => { - const transcriptPath = join(projectDir, 'persisted-key-alignment.jsonl') - const firstMetadata = { - sessionId: 'session-a', - timestamp: '2026-10-09T12:00:00.000Z', - cwd: worktrees[0]?.path, - model: 'claude-sonnet-4-6', - gitBranch: 'branch-a' - } - const secondMetadata = { - sessionId: 'session-b', - timestamp: '2026-10-08T13:00:00.000Z', - cwd: worktrees[1]?.path, - model: 'claude-opus-4-6', - gitBranch: 'branch-b' - } - await writeFile( - transcriptPath, - largePrefix() + - assistantRow('key-a', { - ...firstMetadata, - inputTokens: 100, - outputTokens: 10, - cacheReadTokens: 5, - cacheWriteTokens: 20, - cacheWrite1hTokens: 3 - }) + - assistantRow('key-b', { - ...secondMetadata, - inputTokens: 20, - outputTokens: 80, - cacheWriteTokens: 7, - cacheWrite1hTokens: 2 - }) - ) - const scan = await scanner() - const first = await scan() - const firstCache: ClaudeUsagePersistedFile[] = JSON.parse(JSON.stringify(first.processedFiles)) - await appendFile( - transcriptPath, - assistantRow('key-b', { - ...firstMetadata, - timestamp: '2026-10-10T12:00:00.000Z', - inputTokens: 50, - outputTokens: 70, - cacheReadTokens: 11, - cacheWriteTokens: 9, - cacheWrite1hTokens: 1 - }) + - assistantRow('key-a', { - ...secondMetadata, - timestamp: '2026-10-11T12:00:00.000Z', - inputTokens: 80, - outputTokens: 30, - cacheReadTokens: 1, - cacheWriteTokens: 25, - cacheWrite1hTokens: 5 - }) - ) - streamReads.length = 0 - const second = await scan(firstCache) - expect(parseReadOffsets(transcriptPath)).toEqual([ - processedFile(firstCache, transcriptPath).size - ]) - const secondCold = await scan() - expect(second.sessions).toEqual(secondCold.sessions) - expect(second.dailyAggregates).toEqual(secondCold.dailyAggregates) - const secondCache: ClaudeUsagePersistedFile[] = JSON.parse( - JSON.stringify(second.processedFiles) - ) - await appendFile( - transcriptPath, - assistantRow('key-b', { - ...firstMetadata, - inputTokens: 40, - outputTokens: 90, - cacheReadTokens: 9, - cacheWriteTokens: 8, - cacheWrite1hTokens: 4 - }) + - assistantRow('key-a', { - ...secondMetadata, - inputTokens: 130, - outputTokens: 20, - cacheWriteTokens: 24, - cacheWrite1hTokens: 4 - }) - ) - streamReads.length = 0 - const third = await scan(secondCache) - expect(parseReadOffsets(transcriptPath)).toEqual([ - processedFile(secondCache, transcriptPath).size - ]) - const cold = await scan() - expect(third.sessions).toEqual(cold.sessions) - expect(third.dailyAggregates).toEqual(cold.dailyAggregates) - expect(third.sessions.find((session) => session.sessionId === 'session-a')).toMatchObject({ - firstTimestamp: firstMetadata.timestamp, - lastTimestamp: firstMetadata.timestamp, - model: firstMetadata.model, - lastCwd: firstMetadata.cwd, - lastGitBranch: firstMetadata.gitBranch, - primaryWorktreeId: 'worktree-a', - turnCount: 1, - totalInputTokens: 130, - totalOutputTokens: 30, - totalCacheReadTokens: 5, - totalCacheWriteTokens: 25, - totalCacheWrite1hTokens: 5 - }) - expect(third.sessions.find((session) => session.sessionId === 'session-b')).toMatchObject({ - firstTimestamp: secondMetadata.timestamp, - lastTimestamp: secondMetadata.timestamp, - model: secondMetadata.model, - lastCwd: secondMetadata.cwd, - lastGitBranch: secondMetadata.gitBranch, - primaryWorktreeId: 'worktree-b', - turnCount: 1, - totalInputTokens: 50, - totalOutputTokens: 90, - totalCacheReadTokens: 11, - totalCacheWriteTokens: 9, - totalCacheWrite1hTokens: 4 - }) - }) -}) diff --git a/src/main/claude-usage/scanner-incremental-reader.test.ts b/src/main/claude-usage/scanner-incremental-reader.test.ts deleted file mode 100644 index 47eab695f6a..00000000000 --- a/src/main/claude-usage/scanner-incremental-reader.test.ts +++ /dev/null @@ -1,512 +0,0 @@ -import { appendFile, mkdir, mkdtemp, rename, rm, stat, utimes, writeFile } from 'node:fs/promises' -import type * as NodeFsPromises from 'node:fs/promises' -import type * as NodeOs from 'node:os' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { scanClaudeUsageFiles } from './scanner' -import type { ClaudeUsagePersistedFile } from './types' - -type ReaderObservations = { - chunkBytes: number | undefined - afterStat: (() => Promise) | undefined - readFailure: 'eof' | Error | undefined - readFailureAtCall: number | undefined - streamEndOverride: number | undefined - handles: { path: string; closes: number; closed: boolean }[] - streams: { path: string; start: number; end: number | undefined; bytes: number }[] - windows: { path: string; start: number; bytes: number }[] -} - -const { homedirMock, reads } = vi.hoisted(() => { - const reads: ReaderObservations = { - chunkBytes: undefined, - afterStat: undefined, - readFailure: undefined, - readFailureAtCall: undefined, - streamEndOverride: undefined, - handles: [], - streams: [], - windows: [] - } - return { homedirMock: vi.fn<() => string>(), reads } -}) - -vi.mock('node:os', async () => ({ - ...(await vi.importActual('node:os')), - homedir: homedirMock -})) - -vi.mock('../claude-accounts/claude-profile-installed-router', () => ({ - claudeProfileHistoryDirs: () => [] -})) - -vi.mock('node:fs/promises', async () => { - const actual = await vi.importActual('node:fs/promises') - return { - ...actual, - open: async (...args: Parameters) => { - const handle = await actual.open(...args) - const observedHandle = { path: String(args[0]), closes: 0, closed: false } - reads.handles.push(observedHandle) - const statHandle = handle.stat.bind(handle) - const closeHandle = handle.close.bind(handle) - const createStream = handle.createReadStream.bind(handle) - const readWindow = handle.read.bind(handle) - let streaming = false - vi.spyOn(handle, 'stat').mockImplementation(async (options) => { - const snapshot = await statHandle(options) - const mutate = reads.afterStat - reads.afterStat = undefined - await mutate?.() - return snapshot - }) - vi.spyOn(handle, 'close').mockImplementation(async () => { - await closeHandle() - if (!observedHandle.closed && handle.fd === -1) { - observedHandle.closes++ - } - observedHandle.closed = handle.fd === -1 - }) - vi.spyOn(handle, 'createReadStream').mockImplementation((options) => { - const read = { - path: String(args[0]), - start: options?.start ?? 0, - end: options?.end, - bytes: 0 - } - reads.streams.push(read) - const end = reads.streamEndOverride ?? options?.end - reads.streamEndOverride = undefined - const stream = createStream({ ...options, end, highWaterMark: reads.chunkBytes }) - streaming = true - stream.once('end', () => (streaming = false)) - stream.once('close', () => (streaming = false)) - stream.on('data', (chunk) => { - read.bytes += chunk.length - }) - return stream - }) - vi.spyOn(handle, 'read').mockImplementation(async (...readArgs) => { - if (streaming) { - return readWindow(...readArgs) - } - const scheduled = - reads.readFailureAtCall === undefined || - reads.readFailureAtCall === reads.windows.length + 1 - const failure = scheduled ? reads.readFailure : undefined - if (scheduled) { - reads.readFailure = undefined - reads.readFailureAtCall = undefined - } - if (failure && failure !== 'eof') { - throw failure - } - const result = await readWindow(...readArgs) - const read = failure === 'eof' ? { ...result, bytesRead: 0 } : result - const position = readArgs.at(-1) - reads.windows.push({ - path: String(args[0]), - start: typeof position === 'number' ? position : 0, - bytes: read.bytesRead - }) - return read - }) - return handle - } - } -}) - -type ScanResult = Awaited> - -let root: string -let transcriptPath: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-usage-reader-')) - homedirMock.mockReturnValue(root) - const projectDir = join(root, '.claude', 'projects', 'project-a') - await mkdir(projectDir, { recursive: true }) - transcriptPath = join(projectDir, 'reader-session.jsonl') - reads.chunkBytes = undefined - reads.afterStat = undefined - reads.readFailure = undefined - reads.readFailureAtCall = undefined - reads.streamEndOverride = undefined - reads.handles.length = 0 - reads.streams.length = 0 - reads.windows.length = 0 - vi.resetModules() -}) - -afterEach(async () => { - await rm(root, { recursive: true, force: true }) -}) - -function assistantRow(key: string | null, inputTokens: number, ending = '\n'): string { - return `${JSON.stringify({ - type: 'assistant', - sessionId: 'reader-会🙂', - timestamp: '2026-10-09T12:00:00.000Z', - cwd: join(root, 'workspace-会🙂'), - requestId: key === null ? undefined : `request-${key}`, - message: { - id: key === null ? undefined : `message-${key}-会🙂`, - model: 'claude-sonnet-4-6', - usage: { input_tokens: inputTokens, output_tokens: 5 } - } - })}${ending}` -} - -function padding(ending = '\n'): string { - return `${JSON.stringify({ type: 'user', content: '界🙂'.repeat(2500) })}${ending}` -} - -async function scan(previous: ClaudeUsagePersistedFile[] = []): Promise { - const { scanClaudeUsageFiles } = await import('./scanner') - return scanClaudeUsageFiles([], previous, undefined, []) -} - -function onlyFile(result: ScanResult): ClaudeUsagePersistedFile { - expect(result.processedFiles).toHaveLength(1) - const file = result.processedFiles[0] - if (!file) { - throw new Error('Expected one scanned transcript.') - } - return file -} - -function expectParseRange(start: number, size: number): void { - if (size <= 3 * 4096) { - expect(reads.streams).toHaveLength(0) - expect(reads.windows.slice(-2)).toEqual([ - { path: transcriptPath, start, bytes: size - start }, - { path: transcriptPath, start: 0, bytes: size } - ]) - return - } - expect(reads.streams.filter((read) => read.path === transcriptPath)).toEqual([ - { path: transcriptPath, start, end: size - 1, bytes: size - start } - ]) -} - -async function expectColdParity(result: ScanResult): Promise { - const cold = await scan() - expect(result.sessions).toEqual(cold.sessions) - expect(result.dailyAggregates).toEqual(cold.dailyAggregates) - expect(onlyFile(result).lineCount).toBe(onlyFile(cold).lineCount) -} - -describe('Claude usage incremental reader', () => { - it('publishes the pinned snapshot and discovers a concurrent append on the next scan', async () => { - const prefix = padding() + assistantRow('old', 10) - const appended = assistantRow('new', 20) - await writeFile(transcriptPath, prefix) - reads.afterStat = () => appendFile(transcriptPath, appended) - - const first = await scan() - - expectParseRange(0, Buffer.byteLength(prefix)) - expect(onlyFile(first).size).toBe(Buffer.byteLength(prefix)) - expect(onlyFile(first).parseResumeState?.parsedBytes).toBe(Buffer.byteLength(prefix)) - expect((await stat(transcriptPath)).size).toBe(Buffer.byteLength(prefix + appended)) - expect(first.sessions[0]?.totalInputTokens).toBe(10) - reads.streams.length = 0 - - const second = await scan(first.processedFiles) - - expectParseRange(Buffer.byteLength(prefix), Buffer.byteLength(prefix + appended)) - expect(onlyFile(second).size).toBe(Buffer.byteLength(prefix + appended)) - expect(second.sessions[0]?.totalInputTokens).toBe(30) - expect(second.sessions[0]?.turnCount).toBe(2) - await expectColdParity(second) - }) - - it('reopens after truncation between stat and sampling and closes every opened handle', async () => { - await writeFile(transcriptPath, padding() + assistantRow('old', 10)) - const replacement = assistantRow('replacement', 90) - reads.afterStat = () => writeFile(transcriptPath, replacement) - - const result = await scan() - - expectParseRange(0, Buffer.byteLength(replacement)) - expect(reads.windows.some((read) => read.path === transcriptPath && read.bytes === 0)).toBe( - true - ) - expect(reads.handles).toEqual([ - { path: transcriptPath, closes: 1, closed: true }, - { path: transcriptPath, closes: 1, closed: true } - ]) - expect(onlyFile(result).size).toBe(Buffer.byteLength(replacement)) - expect(result.sessions[0]?.totalInputTokens).toBe(90) - await expectColdParity(result) - }, 5000) - - it('rejects a zero-byte post-parse verification read from an unchanged file without retrying', async () => { - const content = padding() + assistantRow('old', 10) + assistantRow('new', 20) - const contentBytes = Buffer.byteLength(content) - await writeFile(transcriptPath, content) - const original = await stat(transcriptPath) - reads.readFailure = 'eof' - reads.readFailureAtCall = 3 - - await expect(scan()).rejects.toThrow(/snapshot read.*unchanged file boundary/) - - expectParseRange(0, contentBytes) - expect(reads.windows).toEqual([ - { path: transcriptPath, start: 0, bytes: 4096 }, - { path: transcriptPath, start: contentBytes - 4096, bytes: 4096 }, - { path: transcriptPath, start: 0, bytes: 0 } - ]) - expect(reads.handles).toEqual([{ path: transcriptPath, closes: 1, closed: true }]) - expect(await stat(transcriptPath)).toMatchObject({ - dev: original.dev, - ino: original.ino, - size: original.size, - mtimeMs: original.mtimeMs, - ctimeMs: original.ctimeMs - }) - reads.streams.length = 0 - reads.handles.length = 0 - - const cold = await scan() - - expectParseRange(0, contentBytes) - expect(reads.handles).toEqual([{ path: transcriptPath, closes: 1, closed: true }]) - expect(onlyFile(cold).size).toBe(contentBytes) - expect(onlyFile(cold).ownedDedupeKeys).toEqual([ - 'message-old-会🙂:request-old', - 'message-new-会🙂:request-new' - ]) - expect(onlyFile(cold).parseResumeState?.ownedTokenMaxima).toHaveLength(2) - expect(cold.sessions[0]?.totalInputTokens).toBe(30) - expect(cold.sessions[0]?.turnCount).toBe(2) - }, 5000) - - it('rejects an unchanged large file stream that ends early instead of caching partial totals', async () => { - const head = padding() - const rows = Array.from({ length: 40 }, (_, index) => assistantRow(`row-${index}`, 10)) - const content = head + rows.join('') - const partialContent = head + rows.slice(0, 5).join('') - const contentBytes = Buffer.byteLength(content) - const partialBytes = Buffer.byteLength(partialContent) - await writeFile(transcriptPath, content) - const original = await stat(transcriptPath) - reads.streamEndOverride = partialBytes - 1 - - await expect(scan()).rejects.toThrow(/snapshot stream.*unchanged file boundary/) - - expect(reads.handles).toEqual([{ path: transcriptPath, closes: 1, closed: true }]) - expect(reads.streams).toEqual([ - { path: transcriptPath, start: 0, end: contentBytes - 1, bytes: partialBytes } - ]) - expect(reads.windows).toContainEqual({ - path: transcriptPath, - start: contentBytes - 4096, - bytes: 4096 - }) - expect(await stat(transcriptPath)).toMatchObject({ - dev: original.dev, - ino: original.ino, - size: original.size, - mtimeMs: original.mtimeMs, - ctimeMs: original.ctimeMs - }) - reads.streams.length = 0 - reads.handles.length = 0 - - const cold = await scan() - - expectParseRange(0, contentBytes) - expect(reads.handles).toEqual([{ path: transcriptPath, closes: 1, closed: true }]) - expect(onlyFile(cold).size).toBe(contentBytes) - expect(onlyFile(cold).parseResumeState?.parsedBytes).toBe(contentBytes) - expect(onlyFile(cold).ownedDedupeKeys).toEqual( - rows.map((_, index) => `message-row-${index}-会🙂:request-row-${index}`) - ) - expect(onlyFile(cold).parseResumeState?.ownedTokenMaxima).toHaveLength(40) - expect(onlyFile(cold).hasDeferredClaims).toBe(false) - expect(cold.sessions[0]?.totalInputTokens).toBe(400) - expect(cold.sessions[0]?.totalOutputTokens).toBe(200) - expect(cold.sessions[0]?.turnCount).toBe(40) - }, 5000) - - it('resumes at exact UTF8 byte offsets after CRLF and blank lines', async () => { - reads.chunkBytes = 7 - const prefix = `${padding('\r\n')}${assistantRow('old', 10, '\r\n')}\r\n` - await writeFile(transcriptPath, prefix) - const first = await scan() - const prefixBytes = Buffer.byteLength(prefix) - expect(prefixBytes).toBeGreaterThan(prefix.length) - expect(onlyFile(first).parseResumeState?.parsedBytes).toBe(prefixBytes) - expect(onlyFile(first).parseResumeState?.lineCount).toBe(3) - const appended = `${assistantRow('new', 20, '\r\n')}{"type":"user","text":"終🙂"}\r\n` - await appendFile(transcriptPath, appended) - reads.streams.length = 0 - reads.windows.length = 0 - - const second = await scan(first.processedFiles) - - expectParseRange(prefixBytes, prefixBytes + Buffer.byteLength(appended)) - expect(reads.windows.some((read) => read.start === 0 && read.bytes === 4096)).toBe(true) - expect(onlyFile(second).parseResumeState?.parsedBytes).toBe( - prefixBytes + Buffer.byteLength(appended) - ) - expect(onlyFile(second).lineCount).toBe(5) - expect(second.sessions[0]?.sessionId).toBe('reader-会🙂') - expect(second.sessions[0]?.totalInputTokens).toBe(30) - expect(second.sessions[0]?.turnCount).toBe(2) - await expectColdParity(second) - }) - - it('replays an incomplete UTF8 tail from the last complete line when it becomes valid', async () => { - const prefix = padding('\r\n') + assistantRow('old', 10, '\r\n') - const next = Buffer.from(assistantRow('completed', 20, '\r\n')) - const split = next.indexOf(Buffer.from('🙂')) + 2 - await writeFile(transcriptPath, Buffer.concat([Buffer.from(prefix), next.subarray(0, split)])) - const first = await scan() - expect(onlyFile(first).parseResumeState?.parsedBytes).toBe(Buffer.byteLength(prefix)) - expect(onlyFile(first).parseResumeState?.lineCount).toBe(2) - expect(onlyFile(first).lineCount).toBe(3) - expect(first.sessions[0]?.totalInputTokens).toBe(10) - await appendFile(transcriptPath, next.subarray(split)) - reads.streams.length = 0 - - const second = await scan(first.processedFiles) - - expectParseRange(Buffer.byteLength(prefix), Buffer.byteLength(prefix) + next.length) - expect(onlyFile(second).lineCount).toBe(3) - expect(second.sessions[0]?.totalInputTokens).toBe(30) - expect(second.sessions[0]?.turnCount).toBe(2) - await expectColdParity(second) - }) - - it.each([ - { label: 'unkeyed turn', key: null, firstTotal: 35, nextTotal: 55, turns: 3 }, - { label: 'duplicate token maxima', key: 'old', firstTotal: 25, nextTotal: 45, turns: 2 } - ])('counts a valid unterminated $label once when later terminated', async (testCase) => { - const prefix = padding() + assistantRow('old', 10) - const tail = assistantRow(testCase.key, 25, '') - await writeFile(transcriptPath, prefix + tail) - const first = await scan() - expect(onlyFile(first).parseResumeState).toBeNull() - expect(first.sessions[0]?.totalInputTokens).toBe(testCase.firstTotal) - const appended = `\n${assistantRow('new', 20)}` - await appendFile(transcriptPath, appended) - reads.streams.length = 0 - - const second = await scan(first.processedFiles) - - expectParseRange(0, Buffer.byteLength(prefix + tail + appended)) - expect(second.sessions[0]?.totalInputTokens).toBe(testCase.nextTotal) - expect(second.sessions[0]?.turnCount).toBe(testCase.turns) - await expectColdParity(second) - const unchanged = await scan(second.processedFiles) - expect(unchanged.sessions).toEqual(second.sessions) - expect(unchanged.dailyAggregates).toEqual(second.dailyAggregates) - }) - - it('restores a JSON-persisted checkpoint after restart and resumes growth with unchanged mtime', async () => { - const prefix = padding() + assistantRow('old', 10) - const timestamp = new Date('2026-10-09T12:00:00.000Z') - await writeFile(transcriptPath, prefix) - await utimes(transcriptPath, timestamp, timestamp) - const first = await scan() - const persisted: ClaudeUsagePersistedFile[] = JSON.parse(JSON.stringify(first.processedFiles)) - const appended = assistantRow('old', 25) + assistantRow('new', 20) - await appendFile(transcriptPath, appended) - await utimes(transcriptPath, timestamp, timestamp) - expect((await stat(transcriptPath)).mtimeMs).toBe(onlyFile(first).mtimeMs) - vi.resetModules() - reads.streams.length = 0 - - const second = await scan(persisted) - - expectParseRange(Buffer.byteLength(prefix), Buffer.byteLength(prefix + appended)) - expect(second.sessions[0]?.totalInputTokens).toBe(45) - expect(second.sessions[0]?.turnCount).toBe(2) - await expectColdParity(second) - }) - - it.each([ - { mutation: 'rotation', layout: 'small' }, - { mutation: 'in-place rewrite', layout: 'small' }, - { mutation: 'rotation', layout: 'large' }, - { mutation: 'in-place rewrite', layout: 'large middle' } - ])( - 'invalidates a $layout file after same-size $mutation with restored mtime', - async ({ mutation, layout }) => { - const timestamp = new Date('2026-10-09T12:00:00.000Z') - const prefix = layout === 'small' ? '' : padding() - const suffix = layout === 'large middle' ? padding() : '' - const original = prefix + assistantRow('old', 10) + suffix - const replacement = prefix + assistantRow('new', 90) + suffix - expect(Buffer.byteLength(replacement)).toBe(Buffer.byteLength(original)) - await writeFile(transcriptPath, original) - await utimes(transcriptPath, timestamp, timestamp) - const first = await scan() - const cached = onlyFile(first) - if (layout === 'small') { - expect(cached.parseResumeState).toBeNull() - } else { - expect(cached.parseResumeState).toBeTruthy() - } - await new Promise((resolve) => setTimeout(resolve, 20)) - if (mutation === 'rotation') { - await rename(transcriptPath, `${transcriptPath}.rotated`) - } - await writeFile(transcriptPath, replacement) - await utimes(transcriptPath, timestamp, timestamp) - const rewritten = await stat(transcriptPath) - expect(rewritten.size).toBe(cached.size) - expect(rewritten.mtimeMs).toBe(cached.mtimeMs) - expect(rewritten.ctimeMs).not.toBe(cached.ctimeMs) - reads.streams.length = 0 - - const second = await scan(first.processedFiles) - - expectParseRange(0, Buffer.byteLength(replacement)) - expect(second.sessions[0]?.totalInputTokens).toBe(90) - const current = onlyFile(second) - if (mutation === 'rotation' && cached.physicalFileId !== null) { - expect(current.physicalFileId).not.toBe(cached.physicalFileId) - } else { - expect(current.physicalFileId).toBe(cached.physicalFileId) - } - await expectColdParity(second) - } - ) - - it.each([ - { mutation: 'head rewrite', total: 140 }, - { mutation: 'boundary rewrite', total: 100 }, - { mutation: 'rotation', total: 50 }, - { mutation: 'truncation', total: 50 } - ])('discards stale totals after $mutation', async ({ mutation, total }) => { - const prefix = assistantRow('old', 10) + padding() + assistantRow('second', 30) - await writeFile(transcriptPath, prefix) - const first = await scan() - expect(onlyFile(first).parseResumeState).toBeTruthy() - let replacement: string - if (mutation === 'rotation') { - await rename(transcriptPath, `${transcriptPath}.rotated`) - replacement = assistantRow('replacement', 50) - } else if (mutation === 'truncation') { - replacement = assistantRow('replacement', 50) - } else { - replacement = - prefix.replace( - mutation === 'head rewrite' ? '"input_tokens":10' : '"input_tokens":30', - mutation === 'head rewrite' ? '"input_tokens":90' : '"input_tokens":70' - ) + assistantRow('new', 20) - } - await writeFile(transcriptPath, replacement) - reads.streams.length = 0 - - const second = await scan(first.processedFiles) - - expectParseRange(0, Buffer.byteLength(replacement)) - expect(second.sessions[0]?.totalInputTokens).toBe(total) - await expectColdParity(second) - }) -}) diff --git a/src/main/claude-usage/scanner-long-context.test.ts b/src/main/claude-usage/scanner-long-context.test.ts index e3eb8168a7d..f082f5c959f 100644 --- a/src/main/claude-usage/scanner-long-context.test.ts +++ b/src/main/claude-usage/scanner-long-context.test.ts @@ -13,7 +13,7 @@ vi.mock('node:os', async () => ({ homedir: homedirMock })) -vi.mock('../claude-accounts/claude-profile-installed-router', () => ({ +vi.mock('../claude-accounts/profiles/routing/claude-profile-installed-router', () => ({ claudeProfileHistoryDirs: () => [] })) diff --git a/src/main/claude-usage/transcript-file-discovery-errors.test.ts b/src/main/claude-usage/transcript-file-discovery-errors.test.ts index 5811df59e49..7d3b02e1aa1 100644 --- a/src/main/claude-usage/transcript-file-discovery-errors.test.ts +++ b/src/main/claude-usage/transcript-file-discovery-errors.test.ts @@ -13,7 +13,7 @@ vi.mock('node:os', async () => { return { ...actual, homedir: () => state.home } }) -vi.mock('../claude-accounts/claude-profile-installed-router', () => ({ +vi.mock('../claude-accounts/profiles/routing/claude-profile-installed-router', () => ({ claudeProfileHistoryDirs: () => [] })) diff --git a/src/main/claude-usage/transcript-file-discovery.ts b/src/main/claude-usage/transcript-file-discovery.ts index c534b058bcc..a39ec5535ae 100644 --- a/src/main/claude-usage/transcript-file-discovery.ts +++ b/src/main/claude-usage/transcript-file-discovery.ts @@ -1,4 +1,4 @@ -import { claudeProfileHistoryDirs } from '../claude-accounts/claude-profile-installed-router' +import { claudeProfileHistoryDirs } from '../claude-accounts/profiles/routing/claude-profile-installed-router' import { homedir } from 'node:os' import { join } from 'node:path' import { readdir } from 'node:fs/promises' diff --git a/src/main/claude/agent-view/agent-view-service.ts b/src/main/claude/agent-view/agent-view-service.ts index c11f8dd3c16..3cb6e66cd35 100644 --- a/src/main/claude/agent-view/agent-view-service.ts +++ b/src/main/claude/agent-view/agent-view-service.ts @@ -6,7 +6,7 @@ import { isAgentStatusHooksEnabledForAgent } from '../../../shared/agent-hook-li import { getAgentLaunchExecutableName } from '../../../shared/agent-launch/startup/agent-command-line-intent' import { withTimeout } from '../../../shared/promise-timeout-fallback' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import { listClaudeProfileHomesAsync } from '../../claude-accounts/claude-profile-homes' +import { listClaudeProfileHomesAsync } from '../../claude-accounts/profiles/claude-profile-homes' import { resolveLoginShellEnvironment } from '../../startup/login-shell-environment' import { reconcileClaudeAgentViewConfig } from './agent-view-config' import { ensureClaudeAgentViewPluginAsync } from './agent-view-plugin' diff --git a/src/main/claude/claude-child-process-environment.ts b/src/main/claude/claude-child-process-environment.ts index ced33e68edc..1df9100bef9 100644 --- a/src/main/claude/claude-child-process-environment.ts +++ b/src/main/claude/claude-child-process-environment.ts @@ -1,4 +1,7 @@ -import { CLAUDE_AUTH_ENV_VARS, applyClaudeEnvPatch } from '../claude-accounts/environment' +import { + CLAUDE_AUTH_ENV_VARS, + applyClaudeEnvPatch +} from '../claude-accounts/runtime-auth/environment' import { stripInheritedAgentSessionEnv } from '../../shared/agent-launch/startup/parent-agent-session-env' import { LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV, diff --git a/src/main/claude/claude-cli-conversations.ts b/src/main/claude/claude-cli-conversations.ts index ad6d0125e76..6a83df22ef2 100644 --- a/src/main/claude/claude-cli-conversations.ts +++ b/src/main/claude/claude-cli-conversations.ts @@ -1,6 +1,6 @@ import { homedir } from 'node:os' import { join } from 'node:path' -import { getClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-installed-router' import { resolveSessionFilePath } from '../native-chat/session-file-resolver' import { directoryTranscriptImport, diff --git a/src/main/claude/claude-conversation-copy.test.ts b/src/main/claude/claude-conversation-copy.test.ts index 017af012c27..084c12488c4 100644 --- a/src/main/claude/claude-conversation-copy.test.ts +++ b/src/main/claude/claude-conversation-copy.test.ts @@ -1,13 +1,12 @@ import './claude-conversation-worker.test-fixture' -import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { copyClaudeConversation } from './claude-conversation-copy' -import { materializeClaudeRewindTranscript } from './claude-rewind-transcript' const accounts = vi.hoisted((): { homes: string[] } => ({ homes: [] })) -vi.mock('../claude-accounts/claude-profile-installed-router', () => ({ +vi.mock('../claude-accounts/profiles/routing/claude-profile-installed-router', () => ({ getClaudeProfileRouter: () => ({ accountHomes: () => accounts.homes, systemDefaultHome: () => accounts.homes[0] @@ -67,39 +66,6 @@ function copy(uuid: string, settled: boolean, before?: string, opener?: string, }) } -it('reads the source account and writes the independent copy to the selected home, including the terminal tool result', async () => { - const prefix = rows.slice(0, 28) - const original = `${prefix.map((row) => JSON.stringify(row)).join('\n')}\n` - await writeFile(sourcePath, original) - const assistant = prefix.findLast((row) => row.type === 'assistant')! - const result = await copy(assistant.uuid, true) - expect(result.filePath).toBe( - join(selectedHome, 'projects', 'workspace', `${result.sessionId}.jsonl`) - ) - const copied = (await readFile(result.filePath!, 'utf8')) - .trim() - .split('\n') - .map((line) => JSON.parse(line)) - const messages = copied.filter((row) => row.type === 'assistant' || row.type === 'user') - expect(messages.at(-1)).toMatchObject({ - type: 'user', - forkedFrom: { messageUuid: 'a33ccffb-9cd3-54dc-bd5c-bad5de38fdd7' } - }) - expect(result.coverage).toEqual({ - unit: 'claude-entry', - ids: copied - .filter( - (row) => - ['user', 'assistant', 'attachment'].includes(row.type) || - (row.type === 'system' && typeof row.parentUuid === 'string') - ) - .map((row) => row.uuid) - }) - expect(result.resumeCursor).toBe(messages.at(-1)?.uuid) - expect(await readFile(sourcePath, 'utf8')).toBe(original) - expect(await readdir(join(oldHome, 'projects', 'workspace'))).toEqual([`${SOURCE}.jsonl`]) -}) - it('uses the settled native root when the streamed final frame was lost after a recorded tool result', async () => { await writeFile( sourcePath, @@ -143,49 +109,3 @@ it('retains an accepted queued steer at the interrupted main-branch endpoint', a forkedFrom: { messageUuid: '00000000-0000-4000-8000-000000000099' } }) }) - -it.each(['fork', 'rewind'] as const)( - 'forks inherited responses from real SDK %s output ending in custom-title', - async (origin) => { - const prefix = rows.slice(0, 52) - await writeFile(sourcePath, `${prefix.map((row) => JSON.stringify(row)).join('\n')}\n`) - const last = prefix.findLast((row) => row.type === 'assistant')! - const first = - origin === 'fork' - ? await copy(last.uuid, true) - : await materializeClaudeRewindTranscript( - sourcePath, - { - sessionId: 'rewind-child', - sourceSessionId: SOURCE, - throughEntryId: rows[50].uuid, - replacesSessionId: SOURCE - }, - join(selectedHome, 'projects', 'workspace') - ) - const copied = parseRows( - await readFile( - join(selectedHome, 'projects', 'workspace', `${first.sessionId}.jsonl`), - 'utf8' - ) - ) - expect(copied.at(-1)).toMatchObject({ type: 'custom-title' }) - expect(copied.at(-1)?.parentUuid).toBeUndefined() - const reply = copied.findLast((row) => row.type === 'assistant')! - const second = await copy(reply.uuid, true, undefined, undefined, first.sessionId) - const secondRows = parseRows(await readFile(second.filePath!, 'utf8')) - expect(secondRows.findLast((row) => row.type === 'assistant')).toMatchObject({ - forkedFrom: { sessionId: first.sessionId, messageUuid: reply.uuid } - }) - const nextPrompt = copied.find((row) => row.forkedFrom?.messageUuid === rows[34].uuid)! - const earlierReply = copied.find((row) => row.type === 'assistant')! - const bounded = await copy(earlierReply.uuid, true, nextPrompt.uuid, undefined, first.sessionId) - const boundedRows = parseRows(await readFile(bounded.filePath!, 'utf8')) - expect(boundedRows.some((row) => row.forkedFrom?.messageUuid === nextPrompt.uuid)).toBe(false) - expect(boundedRows.findLast((row) => row.type === 'user')).toMatchObject({ - forkedFrom: { - messageUuid: copied.find((row) => row.forkedFrom?.messageUuid === rows[26].uuid)!.uuid - } - }) - } -) diff --git a/src/main/claude/claude-conversation-copy.ts b/src/main/claude/claude-conversation-copy.ts index c550e2254a4..c659f4aad3e 100644 --- a/src/main/claude/claude-conversation-copy.ts +++ b/src/main/claude/claude-conversation-copy.ts @@ -1,6 +1,6 @@ import { basename, dirname, join } from 'node:path' import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { getClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-installed-router' import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { resolveSessionFilePath } from '../native-chat/session-file-resolver' diff --git a/src/main/claude/claude-launch-account.ts b/src/main/claude/claude-launch-account.ts index 0a991865718..02969a655d7 100644 --- a/src/main/claude/claude-launch-account.ts +++ b/src/main/claude/claude-launch-account.ts @@ -1,6 +1,6 @@ import type { ClaudeAccountRecipe } from '../../shared/agent-session/lifecycle/agent-session-acquired-account' -import type { ClaudeProfileRouter } from '../claude-accounts/claude-profile-router' -import { applyClaudeEnvPatch } from '../claude-accounts/environment' +import type { ClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-router' +import { applyClaudeEnvPatch } from '../claude-accounts/runtime-auth/environment' import { resolveStructuredClaudeAccountHomePath } from '../runtime/agent-session/environment/structured-agent-account-home' /** The account a launch runs under is the current selection; the receipt records what it used. */ diff --git a/src/main/claude/claude-naming-invocation.test.ts b/src/main/claude/claude-naming-invocation.test.ts index ed1e8f66cb2..3e5fd87360d 100644 --- a/src/main/claude/claude-naming-invocation.test.ts +++ b/src/main/claude/claude-naming-invocation.test.ts @@ -2,8 +2,8 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it, vi } from 'vitest' -import { ClaudeProfileRouter } from '../claude-accounts/claude-profile-router' -import * as installedRouter from '../claude-accounts/claude-profile-installed-router' +import { ClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-router' +import * as installedRouter from '../claude-accounts/profiles/routing/claude-profile-installed-router' import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' import type { StructuredAgentLaunchSources } from '../runtime/agent-session/launch/structured-agent-launch-composition' import { claudeNamingInvocation } from './claude-naming-invocation' diff --git a/src/main/claude/claude-naming-invocation.ts b/src/main/claude/claude-naming-invocation.ts index 365f37176ae..dc077bf6e34 100644 --- a/src/main/claude/claude-naming-invocation.ts +++ b/src/main/claude/claude-naming-invocation.ts @@ -1,7 +1,7 @@ import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { getClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' -import { applyClaudeEnvPatch } from '../claude-accounts/environment' +import { getClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-installed-router' +import { applyClaudeEnvPatch } from '../claude-accounts/runtime-auth/environment' import { agentSessionPinnedLaunchDirectory } from '../runtime/agent-session/records/agent-session-record-launch-directory' import type { StructuredAgentLaunchSources } from '../runtime/agent-session/launch/structured-agent-launch-composition' import { resolveStructuredAgentCommand } from '../native-chat/structured-agent-command-resolution' diff --git a/src/main/claude/claude-profile-hooks.test.ts b/src/main/claude/claude-profile-hooks.test.ts index a9161057581..d7e885f5c30 100644 --- a/src/main/claude/claude-profile-hooks.test.ts +++ b/src/main/claude/claude-profile-hooks.test.ts @@ -18,7 +18,7 @@ vi.mock('node:os', async (original) => ({ })) vi.mock('electron', () => ({ app: { getPath: () => state.home } })) import { ClaudeHookService } from './hook-service' -import { provisionClaudeProfile } from '../claude-accounts/claude-profile-provisioning' +import { provisionClaudeProfile } from '../claude-accounts/profiles/setup/claude-profile-provisioning' const caseInsensitive = (() => { const dir = mkdtempSync(join(tmpdir(), 'claude-case-probe-')) @@ -57,82 +57,10 @@ function fixture() { return { defaultDir, profile, settings, edit, service, installProfile, provision } } -function stopHooks(f: ReturnType) { - const hook = (command: string) => ({ matcher: '', hooks: [{ type: 'command', command }] }) - const stopOf = (value: Record): unknown[] => { - const hooks: unknown = value.hooks - return hooks && typeof hooks === 'object' && 'Stop' in hooks && Array.isArray(hooks.Stop) - ? hooks.Stop - : [] - } - const isOrca = (entry: unknown) => JSON.stringify(entry).includes('agent-hooks') - const setStop = (dir: string, commands: string[]) => - f.edit(dir, (value) => { - const hooks = typeof value.hooks === 'object' ? value.hooks : {} - value.hooks = { ...hooks, Stop: [...commands.map(hook), ...stopOf(value).filter(isOrca)] } - }) - const stop = (dir: string) => stopOf(f.settings(dir)) - const orcaCount = (dir: string) => stop(dir).filter(isOrca).length - return { hook, setStop, stop, orcaCount } -} -const sync = async (f: ReturnType) => { - const report = await f.provision() - expect(f.installProfile().state).toBe('installed') - return report -} - // Symlink creation needs Windows privileges. const itLinks = it.skipIf(process.platform === 'win32') describe('Claude hooks at an explicit profile', () => { - it('installs managed hooks at a profile without editing default settings or adding a statusline', () => { - const f = fixture() - writeFileSync(join(f.defaultDir, 'settings.json'), '{"model":"default"}') - writeFileSync(join(f.profile, 'settings.json'), '{"model":"profile"}') - expect(f.service.install(CURRENT).state).toBe('installed') - const before = readFileSync(join(f.defaultDir, 'settings.json'), 'utf8') - const result = f.installProfile() - expect(result.configPath).toBe(join(f.profile, 'settings.json')) - expect(result.state).toBe('installed') - expect(readFileSync(join(f.defaultDir, 'settings.json'), 'utf8')).toBe(before) - expect(f.settings(f.profile)).toEqual({ model: 'profile', hooks: JSON.parse(before).hooks }) - }) - it("shares the user's hooks, Orca's hooks and statusline as plain keys that installs leave in sync", async () => { - const f = fixture() - const { hook, setStop, stop, orcaCount } = stopHooks(f) - f.service.install(CURRENT) - setStop(f.defaultDir, ['notify-me']) - await sync(f) - expect(f.settings(f.profile).hooks).toEqual(f.settings(f.defaultDir).hooks) - expect(f.settings(f.profile).statusLine).toEqual(f.settings(f.defaultDir).statusLine) - expect((await sync(f)).surfaces['settings.json']).toBe('unchanged') - setStop(f.defaultDir, ['notify-v2']) - await sync(f) - expect(stop(f.profile)[0]).toEqual(hook('notify-v2')) - expect(orcaCount(f.profile)).toBe(1) - setStop(f.profile, ['profile-only']) - setStop(f.defaultDir, ['notify-v3']) - await sync(f) - expect(stop(f.profile)[0]).toEqual(hook('notify-v3')) - expect(orcaCount(f.profile)).toBe(1) - }) - it('carries a default-home statusline opt-out and an old-Claude retire to the profile', async () => { - const f = fixture() - f.service.install(CURRENT) - await sync(f) - expect(f.settings(f.profile).statusLine).toBeDefined() - f.edit(f.defaultDir, (value) => delete value.statusLine) - await sync(f) - expect(f.settings(f.profile).statusLine).toBeUndefined() - const old = fixture() - old.service.install(CURRENT) - await sync(old) - old.service.install({ claudeVersion: '1.0.0' }) - await old.provision() - old.service.install({ claudeVersion: '1.0.0', configDir: old.profile }) - expect(old.settings(old.defaultDir).statusLine).toBeUndefined() - expect(old.settings(old.profile).statusLine).toBeUndefined() - }) itLinks('refuses a profile destination that is or links into the default home', () => { const f = fixture() f.service.install(CURRENT) diff --git a/src/main/claude/claude-real-cli-availability-test-support.ts b/src/main/claude/claude-real-cli-availability-test-support.ts index 19d6ab766b5..22150adc1cd 100644 --- a/src/main/claude/claude-real-cli-availability-test-support.ts +++ b/src/main/claude/claude-real-cli-availability-test-support.ts @@ -3,7 +3,7 @@ import { join } from 'node:path' import { runProcessSync } from '@orca/process-host' import type { ProcessResult } from '@orca/process-host/process-spec' import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' -import { CLAUDE_AUTH_ENV_VARS } from '../claude-accounts/environment' +import { CLAUDE_AUTH_ENV_VARS } from '../claude-accounts/runtime-auth/environment' import { resolveClaudeCommand } from '../codex-cli/command' import { resolveRealClaudeCliGate } from './claude-real-cli-test-gate' diff --git a/src/main/claude/claude-rewind-fork.ts b/src/main/claude/claude-rewind-fork.ts index 706ff4a8a04..1c1f22a174b 100644 --- a/src/main/claude/claude-rewind-fork.ts +++ b/src/main/claude/claude-rewind-fork.ts @@ -6,7 +6,7 @@ import { type AgentSessionProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' import type { AgentSessionRewindFork } from '../../shared/agent-session/lifecycle/agent-session-rewind' -import { getClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../claude-accounts/profiles/routing/claude-profile-installed-router' import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { resolveSessionFilePath } from '../native-chat/session-file-resolver' import { splitTranscriptStreamLines } from '../native-chat/transcript-stream-lines' diff --git a/src/main/claude/hook-service.ts b/src/main/claude/hook-service.ts index 968aa05d0e8..433eb1b1ad6 100644 --- a/src/main/claude/hook-service.ts +++ b/src/main/claude/hook-service.ts @@ -3,7 +3,7 @@ import { getAppEnvironment } from '../../shared/app-environment' import { listClaudeProfileHomes, listClaudeProfileHomesAsync -} from '../claude-accounts/claude-profile-homes' +} from '../claude-accounts/profiles/claude-profile-homes' import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' import type { SFTPWrapper } from 'ssh2' import type { diff --git a/src/main/claude/structured/claude-conversation-title-owner.test.ts b/src/main/claude/structured/claude-conversation-title-owner.test.ts index 5b7c3d8e9d1..b6e29f72b51 100644 --- a/src/main/claude/structured/claude-conversation-title-owner.test.ts +++ b/src/main/claude/structured/claude-conversation-title-owner.test.ts @@ -1,76 +1,9 @@ -import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router' -import * as installedRouter from '../../claude-accounts/claude-profile-installed-router' import { afterEach, expect, it, vi } from 'vitest' import { acquired, fakeClaude, PROVIDER_SESSION_ID } from './claude-structured-session-test-support' import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' afterEach(() => vi.restoreAllMocks()) -it('reads only cached support and rejects a retired acquisition or changed account/context', async () => { - const cliFlag = vi.fn(async () => 'supported' as const) - const cli = fakeClaude() - const router = new ClaudeProfileRouter({ - getSettings: () => ({ - claudeManagedAccounts: [], - activeClaudeManagedAccountId: null, - agentStatusHooksEnabled: false, - disabledTuiAgents: [] - }), - dataRoot: '/isolated', - userHome: '/users/test', - env: {} - }) - const preparation = vi.spyOn(router, 'preparation') - vi.spyOn(installedRouter, 'getClaudeProfileRouter').mockReturnValue(router) - const adapter = await acquired(cli, { - cliFlag, - account: 'system', - claudeConfigDir: '/accounts/claude', - accountRecipe: { route: 'system', home: '/accounts/claude', configDir: '/accounts/claude' } - }) - try { - const record = agentSessionRecordFixture() - record.sessionId = 'session-1' - record.accountHome = { variable: 'CLAUDE_CONFIG_DIR', path: '/accounts/claude' } - record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID - const generate = vi.fn(async () => 'Broken chat title') - cli.connections[0]!.generateSessionTitle = generate - const owner = adapter.captureConversationTitleOwner(record)! - expect(owner.isCurrent(record)).toBe(true) - expect(await owner.generate('Repair login', () => owner.isCurrent(record))).toBe( - 'Broken chat title' - ) - expect(cliFlag).toHaveBeenLastCalledWith( - { option: 'generate_session_title', firstVersion: '2.1.310' }, - 250, - false - ) - expect( - owner.isCurrent({ ...record, accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/other' } }) - ).toBe(false) - expect( - owner.isCurrent({ - ...record, - providerContextBoundary: { operationId: 'clear-1', afterFence: 7, clearedAt: 1 } - }) - ).toBe(false) - const system = router.preparation() - preparation.mockReturnValue({ - ...system, - provenance: 'profile:other', - configDir: '/accounts/other' - }) - expect(owner.isCurrent(record)).toBe(false) - preparation.mockReturnValue(system) - expect(owner.isCurrent(record)).toBe(true) - await adapter.closeAll() - expect(owner.isCurrent(record)).toBe(false) - } finally { - await adapter.closeAll() - cli.dispose() - } -}) - it('retains retirement knowledge when the optional title method is missing', async () => { const cli = fakeClaude() const adapter = await acquired(cli) diff --git a/src/main/claude/structured/claude-conversation-title-owner.ts b/src/main/claude/structured/claude-conversation-title-owner.ts index 640b72c668c..b7e4c11091a 100644 --- a/src/main/claude/structured/claude-conversation-title-owner.ts +++ b/src/main/claude/structured/claude-conversation-title-owner.ts @@ -1,5 +1,5 @@ import { resolve } from 'node:path' -import { getClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' import { agentSessionAccountHomesEqual } from '../../../shared/agent-session/lifecycle/agent-session-account-home' import { claudeNamingContextId } from '../claude-conversation-naming' import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS } from '../claude-cli-flag-support' diff --git a/src/main/claude/structured/launch/claude-structured-child-env.ts b/src/main/claude/structured/launch/claude-structured-child-env.ts index f26f26593fa..46f29548a52 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.ts @@ -10,7 +10,7 @@ import { // `--version` probe that runs the same binary. import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolution' -import { applyClaudeEnvPatch } from '../../../claude-accounts/environment' +import { applyClaudeEnvPatch } from '../../../claude-accounts/runtime-auth/environment' import { resolveClaudeCommand } from '../../../codex-cli/command' import { withoutInheritedClaudeConfigDir } from '../../claude-config-dir-pin' import { stripInheritedAgentSessionEnv } from '../../../../shared/agent-launch/startup/parent-agent-session-env' diff --git a/src/main/claude/structured/launch/claude-structured-launch-account-routing.test.ts b/src/main/claude/structured/launch/claude-structured-launch-account-routing.test.ts deleted file mode 100644 index 27105568573..00000000000 --- a/src/main/claude/structured/launch/claude-structured-launch-account-routing.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { createClaudeStructuredLaunchResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { agentSessionRecordFixture } from '../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import type { AgentSessionRewindRecord } from '../../../../shared/agent-session/lifecycle/agent-session-rewind' -import { ClaudeProfileRouter } from '../../../claude-accounts/claude-profile-router' -import { installClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' - -const roots: string[] = [] -afterEach(() => { - installClaudeProfileRouter(undefined) - roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) -}) - -function routedResumeFixture(rewind?: AgentSessionRewindRecord, transcriptFiles = false) { - const root = mkdtempSync(join(tmpdir(), 'claude-launch-routing-')) - roots.push(root) - const home = join(root, 'claude-profiles', 'a', 'home') - mkdirSync(home, { recursive: true }) - writeFileSync(join(root, 'claude-profiles', 'a', 'profile.json'), '{}') - installClaudeProfileRouter( - new ClaudeProfileRouter({ - getSettings: () => ({ - claudeManagedAccounts: [], - activeClaudeManagedAccountId: 'a', - activeClaudeManagedAccountIdsByRuntime: undefined, - agentStatusHooksEnabled: false, - disabledTuiAgents: [] - }), - dataRoot: root, - userHome: join(root, 'personal'), - env: {} - }) - ) - const handle = claudeProviderHandle('ran-under-b', 'leaf-1') - const record = { - ...agentSessionRecordFixture(), - providerHandleChain: [ - { linkId: 'link-1', origin: 'created' as const, mintedAtFence: 1, observedAt: 1, handle } - ], - ...(rewind ? { rewind } : {}) - } - const transcriptHomes = new Set() - const resolve = createClaudeStructuredLaunchResolver({ - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - resolveLaunchArgs: () => [], - resolveWorkspacePath: async (id) => `/repos/${id}`, - resolveCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }), - resolveInheritedEnv: async () => ({ PATH: '/usr/bin' }), - resolveAuthPolicy: () => ({ account: 'system' }), - hasTranscript: transcriptFiles - ? undefined - : async ({ claudeConfigDir }) => transcriptHomes.has(claudeConfigDir) - }) - const identity = { - sessionId: record.sessionId, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude' as const, - providerHandle: handle - } - return { root, home, record, transcriptHomes, launch: () => resolve({ identity }) } -} - -it('refuses a rewind fork from its saved custom home and recovers when its source reaches the selected account', async () => { - const { root, home, record, launch } = routedResumeFixture( - { - operationId: 'rewind-1', - callerKey: 'desktop', - itemId: 'item-1', - expectedEpoch: 'epoch-1', - phase: 'completed', - providerFork: { - sessionId: 'forked', - sourceSessionId: 'ran-under-b', - throughEntryId: 'entry-1', - replacesSessionId: 'ran-under-b' - } - }, - true - ) - const customHome = join(root, 'custom-claude-home') - record.accountHome = { variable: 'CLAUDE_CONFIG_DIR', path: customHome } - const sourceProject = join(customHome, 'projects', '-repos-workspace-1') - mkdirSync(sourceProject, { recursive: true }) - writeFileSync(join(sourceProject, 'ran-under-b.jsonl'), '{}\n') - - await expect(launch()).rejects.toMatchObject({ - name: 'AgentSessionPreSpawnError', - reason: 'historyInOtherAccount' - }) - - const selectedProject = join(home, 'projects', '-repos-workspace-1') - mkdirSync(selectedProject, { recursive: true }) - writeFileSync(join(selectedProject, 'ran-under-b.jsonl'), '{}\n') - expect((await launch()).options).toMatchObject({ - sessionId: 'forked', - resume: 'ran-under-b', - resumeSessionAt: 'entry-1', - forkSession: true - }) -}) diff --git a/src/main/claude/structured/launch/claude-structured-launch-home.ts b/src/main/claude/structured/launch/claude-structured-launch-home.ts index 98e05d12e67..88df61b9e6f 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-home.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-home.ts @@ -1,5 +1,5 @@ import { join } from 'node:path' -import type { ClaudeProfileRouter } from '../../../claude-accounts/claude-profile-router' +import type { ClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-router' import { AgentSessionPreSpawnError } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' import { resolveSessionFilePath } from '../../../native-chat/session-file-resolver' import { prepareClaudeLaunchAccount } from '../../claude-launch-account' diff --git a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts index e462e89a305..e58f06c59e1 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts @@ -2,7 +2,7 @@ import type { ClaudeAccountRecipe } from '../../../../shared/agent-session/lifec import { prepareClaudeLaunchAccount } from '../../claude-launch-account' import { assertStructuredAgentResolutionCurrent } from '../../../native-chat/structured-agent-command-resolution' import { activeProviderContext } from '../../../../shared/agent-session/agent-session-provider-context' -import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' import type { Options as ClaudeAgentSdkOptions, @@ -17,7 +17,7 @@ import { agentSessionProviderHandleRoot, claudeProviderHandleLeafUuid } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import type { ClaudeStructuredAuthPolicy } from '../../../claude-accounts/claude-structured-auth-policy' +import type { ClaudeStructuredAuthPolicy } from '../../../claude-accounts/runtime-auth/claude-structured-auth-policy' import { claudeChildEnv, claudeProbeEnv, diff --git a/src/main/claude/theme-sync/claude-code-theme-sync.ts b/src/main/claude/theme-sync/claude-code-theme-sync.ts index 4bd63ebf552..1f9a224ef8f 100644 --- a/src/main/claude/theme-sync/claude-code-theme-sync.ts +++ b/src/main/claude/theme-sync/claude-code-theme-sync.ts @@ -5,11 +5,11 @@ import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absen import { readHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-read' import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' import { defaultClaudeConfigDir } from '../claude-config-dir-pin' -import { listClaudeProfileHomesAsync } from '../../claude-accounts/claude-profile-homes' +import { listClaudeProfileHomesAsync } from '../../claude-accounts/profiles/claude-profile-homes' import { getClaudeObservedConfigDirs, getClaudeProfileRouter -} from '../../claude-accounts/claude-profile-installed-router' +} from '../../claude-accounts/profiles/routing/claude-profile-installed-router' import { resolveClaudeCommand } from '../../codex-cli/command' import { claudeLoadsCustomThemes, probeRecentClaudeCliVersion } from '../claude-hook-event-versions' import type { ClaudeCodeTheme } from './claude-code-theme' diff --git a/src/main/ipc/account-sign-in-link-opener.ts b/src/main/ipc/account-sign-in-link-opener.ts index f38835d7418..2048023a288 100644 --- a/src/main/ipc/account-sign-in-link-opener.ts +++ b/src/main/ipc/account-sign-in-link-opener.ts @@ -1,5 +1,5 @@ import { shell } from 'electron' -import { isClaudeLocalSignInLink } from '../claude-accounts/claude-sign-in-browser' +import { isClaudeLocalSignInLink } from '../claude-accounts/sign-in/claude-sign-in-browser' import { isCodexLoginAuthUrl } from '../codex-accounts/codex-login-auth-url' export type AccountSignInProvider = 'claude' | 'codex' diff --git a/src/main/ipc/claude-accounts.ts b/src/main/ipc/claude-accounts.ts index 07fb93911fc..61074321ce7 100644 --- a/src/main/ipc/claude-accounts.ts +++ b/src/main/ipc/claude-accounts.ts @@ -1,6 +1,6 @@ import { ipcMain } from 'electron' import type { ClaudeAccountService } from '../claude-accounts/service' -import type { ClaudeAccountSelectionTarget } from '../claude-accounts/runtime-selection' +import type { ClaudeAccountSelectionTarget } from '../claude-accounts/selection/runtime-selection' import { openAccountSignInLink } from './account-sign-in-link-opener' export function registerClaudeAccountHandlers(claudeAccounts: ClaudeAccountService): void { diff --git a/src/main/ipc/pty/host-env/types.ts b/src/main/ipc/pty/host-env/types.ts index bef62088cd7..b2325de5a67 100644 --- a/src/main/ipc/pty/host-env/types.ts +++ b/src/main/ipc/pty/host-env/types.ts @@ -1,8 +1,8 @@ import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { AgentProviderSessionMetadata } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import type { NetworkProxySettings } from '../../../../shared/network-proxy' -import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth-service' -import type { ClaudeAccountSelectionTarget } from '../../../claude-accounts/runtime-selection' +import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' +import type { ClaudeAccountSelectionTarget } from '../../../claude-accounts/selection/runtime-selection' import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' import type { CodexPaneHomeRoute } from '../../../codex/configuration/homes/codex-pane-account-registry-types' import type { CodexSessionResumePreparation } from '../../../codex/history/resume/codex-session-resume-home' diff --git a/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts b/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts index 0263e4ab3fe..0a7d931857d 100644 --- a/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts +++ b/src/main/ipc/pty/ipc/claude-diff-panel-notice.ts @@ -4,7 +4,7 @@ import { getPtyIpc } from '../pty-host-bindings' import { parseAppSshPtyId } from '../../../providers/ssh-pty-id' import { claudeDiffPanelMayAutoOpen } from '../../../claude/claude-diff-panel-auto-open' import { probeRecentClaudeCliVersion } from '../../../claude/claude-hook-event-versions' -import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { resolveClaudeCommand } from '../../../codex-cli/command' import { ptyOwnership } from '../provider/ownership-state' import { tryGetProviderForPty } from '../provider/registry' diff --git a/src/main/ipc/pty/ipc/claude-old-terminal.ts b/src/main/ipc/pty/ipc/claude-old-terminal.ts index a90a81a76ec..761029d443d 100644 --- a/src/main/ipc/pty/ipc/claude-old-terminal.ts +++ b/src/main/ipc/pty/ipc/claude-old-terminal.ts @@ -1,7 +1,7 @@ import { getClaudeProfileRouter, getClaudeWslProfileRouter -} from '../../../claude-accounts/claude-profile-installed-router' +} from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { getPtyIpc } from '../pty-host-bindings' import { CLAUDE_ACCOUNT_FUNCTION_DAEMON_PROTOCOL_VERSION, diff --git a/src/main/ipc/pty/ipc/spawn-preflight.ts b/src/main/ipc/pty/ipc/spawn-preflight.ts index 24198414c9f..3f82ea0a723 100644 --- a/src/main/ipc/pty/ipc/spawn-preflight.ts +++ b/src/main/ipc/pty/ipc/spawn-preflight.ts @@ -1,4 +1,4 @@ -import { withClaudeProfileTerminalEnv } from '../../../claude-accounts/claude-profile-installed-router' +import { withClaudeProfileTerminalEnv } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { mintPtySessionId } from '../../../daemon/sessions/pty-session-id' import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' import { diff --git a/src/main/ipc/pty/ipc/spawn-state.ts b/src/main/ipc/pty/ipc/spawn-state.ts index e50a7694108..aca96356115 100644 --- a/src/main/ipc/pty/ipc/spawn-state.ts +++ b/src/main/ipc/pty/ipc/spawn-state.ts @@ -11,7 +11,7 @@ import type { CodexPaneHomeRoute } from '../../../codex/configuration/homes/code import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import type { ResumeSpawnAdmission } from '../host-env/saved-resume-admission' -import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth-service' +import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' import { type PtySpawnTiming, createPtySpawnTiming } from '../pty-spawn-timing' import { noCodexResumeLaunch, type CodexResumeLaunch } from '../host-env/codex-resume' import type { StablePaneOwner } from '../pane/stable-owner' diff --git a/src/main/ipc/pty/runtime/spawn-preflight.ts b/src/main/ipc/pty/runtime/spawn-preflight.ts index 867140f29ec..750ceb88d58 100644 --- a/src/main/ipc/pty/runtime/spawn-preflight.ts +++ b/src/main/ipc/pty/runtime/spawn-preflight.ts @@ -1,4 +1,4 @@ -import { withClaudeProfileTerminalEnv } from '../../../claude-accounts/claude-profile-installed-router' +import { withClaudeProfileTerminalEnv } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import type { PtySpawnResult } from '../../../providers/pty-provider-contract' import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provider' import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id' diff --git a/src/main/ipc/pty/runtime/spawn-state.ts b/src/main/ipc/pty/runtime/spawn-state.ts index 7c87dc4e349..6ba02a090ec 100644 --- a/src/main/ipc/pty/runtime/spawn-state.ts +++ b/src/main/ipc/pty/runtime/spawn-state.ts @@ -12,7 +12,7 @@ import type { } from '../../../providers/pty-provider-contract' import type { CodexPaneHomeRoute } from '../../../codex/configuration/homes/codex-pane-account-registry-types' import type { CodexAccountSelectionTarget } from '../../../codex-accounts/runtime-selection' -import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth-service' +import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' import type { StablePaneOwner } from '../pane/stable-owner' import type { PaneSpawnReservation } from '../pane/spawn-reservation' import type { AdoptStablePaneResult } from '../ipc/spawn-types' diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-support.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-support.ts index 123dda9d356..03fc698b5ef 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-support.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-support.ts @@ -5,9 +5,9 @@ import type { AgentSessionJournalIdentity } from '../../../../../shared/agent-se import { ClaudeProfileRouter, type ClaudeProfileRouterSettings -} from '../../../../claude-accounts/claude-profile-router' -import { installClaudeProfileRouter } from '../../../../claude-accounts/claude-profile-installed-router' -import { claudeProfileMarkerPath } from '../../../../claude-accounts/claude-profile-paths' +} from '../../../../claude-accounts/profiles/routing/claude-profile-router' +import { installClaudeProfileRouter } from '../../../../claude-accounts/profiles/routing/claude-profile-installed-router' +import { claudeProfileMarkerPath } from '../../../../claude-accounts/profiles/claude-profile-paths' import { CLAUDE_STRUCTURED_AGENT } from '../../../../claude/structured/claude-structured-agent-definition' import { claudeInitializationAuthError } from '../../../../claude/structured/claude-structured-init-proof' import type { AgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store' diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-failed-create-owner-verdict.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-failed-create-owner-verdict.test.ts deleted file mode 100644 index 89959c32331..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-failed-create-owner-verdict.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -// Durable exit proof distinguishes safe new-operation retry from a possibly existing session. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import type { AgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store-test-harness' -import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter' -import { StructuredAgentSessionHost } from '../structured-agent-session-host' -import { - HOST_TEST_NOW as NOW, - HOST_TEST_THREAD as THREAD, - hostTestAttachParams, - resetHostTestOperationIds -} from './structured-agent-session-host-test-data' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createStructuredAgentSessionLogger } from '../structured-agent-session-logger' -import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { NO_STRUCTURED_AGENTS } from '../../providers/testing/structured-agent-session-adapter-router-test-support' -import { claudeProfileSetupFailed } from '../../../../claude-accounts/claude-profile-launch-errors' - -const CALLER = { callerKey: 'client-1' } - -let root: string -let store: AgentSessionRecordStore -let host: StructuredAgentSessionHost -let acquire: Mock - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-failed-create-verdict-')) - resetHostTestOperationIds() - acquire = vi.fn(async ({ fence, spawnToken }) => ({ - acquisitionGeneration: globalThis.crypto.randomUUID(), - process: { hostId: 'local', pid: 4242, processStartTimeMs: 1_700_000_000_000, spawnToken }, - link: { - linkId: `link-${fence}`, - handle: codexProviderHandle(THREAD), - origin: 'created', - mintedAtFence: fence, - observedAt: NOW - } - })) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - logger: createStructuredAgentSessionLogger(), - store, - adapter: { - open: async () => ({ - reportedOptions: { model: '' } - }), - acquire, - releaseAcquisition: vi.fn(async () => true), - dispatch: vi.fn(async () => ({ state: 'admitted' as const })), - cancelTurn: vi.fn(async () => ({ cancelled: true })), - answerPrompt: vi.fn(async () => undefined), - setOption: vi.fn(async () => undefined) - }, - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - now: () => NOW - }) -}) - -afterEach(async () => { - await host.flushAllStreamedEvents() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -describe('failed create owner verdict', () => { - it('returns a typed preparation failure on its first response and replay, then permits recovery', async () => { - acquire.mockRejectedValueOnce(claudeProfileSetupFailed()) - const params = hostTestAttachParams(null) - const first = await host.attach(CALLER, params) - expect(first).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_operation_invalid', - details: { reason: 'claudeAccountSetupFailed', ownerVerdict: 'exited' }, - ownerVerdict: 'exited' - } - }) - await expect(host.attach(CALLER, params)).resolves.toEqual(first) - await expect(host.attach(CALLER, hostTestAttachParams(null))).resolves.toMatchObject({ - ok: true - }) - }) -}) diff --git a/src/main/native-chat/session-file-resolver.ts b/src/main/native-chat/session-file-resolver.ts index 6af57f9d6b3..5c45188e22c 100644 --- a/src/main/native-chat/session-file-resolver.ts +++ b/src/main/native-chat/session-file-resolver.ts @@ -1,4 +1,4 @@ -import { claudeProfileHistoryDirs } from '../claude-accounts/claude-profile-installed-router' +import { claudeProfileHistoryDirs } from '../claude-accounts/profiles/routing/claude-profile-installed-router' import { homedir } from 'node:os' import { extname, join } from 'node:path' import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types' diff --git a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts b/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts index a7d857a348a..008e92264da 100644 --- a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts +++ b/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts @@ -7,10 +7,10 @@ import { existsSync } from 'node:fs' import { homedir } from 'node:os' import { posix } from 'node:path' import type { HostAccountLaunchEnv } from '../../shared/agent-launch/startup/host-account-launch-env' -import { claudeProfileMarkerPath } from '../claude-accounts/claude-profile-paths' -import type { ClaudeProfileSetupReport } from '../claude-accounts/claude-profile-setup' -import { wslClaudeProfile } from '../claude-accounts/claude-profile-wsl-paths' -import { provisionWslClaudeAccountProfile } from '../claude-accounts/claude-profile-wsl-provision' +import { claudeProfileMarkerPath } from '../claude-accounts/profiles/claude-profile-paths' +import type { ClaudeProfileSetupReport } from '../claude-accounts/profiles/setup/claude-profile-setup' +import { wslClaudeProfile } from '../claude-accounts/profiles/wsl/claude-profile-wsl-paths' +import { provisionWslClaudeAccountProfile } from '../claude-accounts/profiles/wsl/claude-profile-wsl-provision' /** The desktop router's cap: a slow refresh delays a launch this long, then runs alongside it. */ const REFRESH_WAIT_MS = 5_000 diff --git a/src/main/providers/accounts/provider-account-services.ts b/src/main/providers/accounts/provider-account-services.ts index 02418e4013b..99b32924dfa 100644 --- a/src/main/providers/accounts/provider-account-services.ts +++ b/src/main/providers/accounts/provider-account-services.ts @@ -22,7 +22,7 @@ import { } from '../../antigravity/native-account-host' import { createAccountRuntimeTargetSettingsSync } from '../../rate-limits/service/account-runtime-target-sync' import { normalizeCodexRuntimeSelection } from '../../codex-accounts/runtime-selection' -import { normalizeClaudeRuntimeSelection } from '../../claude-accounts/runtime-selection' +import { normalizeClaudeRuntimeSelection } from '../../claude-accounts/selection/runtime-selection' import type { ClaudeStatusLineRateLimits } from '../../../shared/claude-statusline-rate-limits' export type ProviderAccountServices = { diff --git a/src/main/rate-limits/providers/claude/claude-managed-account-usage.ts b/src/main/rate-limits/providers/claude/claude-managed-account-usage.ts index 0730f9408a5..5b3c26add47 100644 --- a/src/main/rate-limits/providers/claude/claude-managed-account-usage.ts +++ b/src/main/rate-limits/providers/claude/claude-managed-account-usage.ts @@ -2,7 +2,7 @@ import type { ProviderRateLimits } from '../../../../shared/rate-limit-types' import { getClaudeProfileRouter, getClaudeWslProfileRouter -} from '../../../claude-accounts/claude-profile-installed-router' +} from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { toWindowsWslPath } from '../../../../shared/wsl-paths' import type { ClaudeManagedAccountUsageOptions } from './claude-usage-fetch-options' import { fetchActiveClaudeRateLimits } from './claude-active-usage-fetch' diff --git a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts index e62db9444d5..5c6b11b11b3 100644 --- a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts +++ b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts @@ -3,10 +3,10 @@ import { homedir } from 'node:os' import path from 'node:path' import { z } from 'zod' import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' -import { readActiveClaudeKeychainCredentialsStrict } from '../../../claude-accounts/keychain' +import { readActiveClaudeKeychainCredentialsStrict } from '../../../claude-accounts/runtime-auth/keychain' import type { ClaudeRuntimeAuthPreparation } from '../../../claude-accounts/runtime-auth/runtime-auth-types' -import { readUserClaudeConfigDir } from '../../../claude-accounts/claude-profile-paths' -import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' +import { readUserClaudeConfigDir } from '../../../claude-accounts/profiles/claude-profile-paths' +import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' export type ClaudeOAuthCredentialSource = | 'scoped-keychain' diff --git a/src/main/rate-limits/providers/claude/claude-rate-limit-target.ts b/src/main/rate-limits/providers/claude/claude-rate-limit-target.ts index d9bce7e7107..dc4d5355e2e 100644 --- a/src/main/rate-limits/providers/claude/claude-rate-limit-target.ts +++ b/src/main/rate-limits/providers/claude/claude-rate-limit-target.ts @@ -3,7 +3,7 @@ import { getClaudeWslSelectionKey, normalizeClaudeRuntimeSelection, type ClaudeAccountSelectionTarget -} from '../../../claude-accounts/runtime-selection' +} from '../../../claude-accounts/selection/runtime-selection' import { getInitialAccountRateLimitTarget } from '../../initial-account-rate-limit-target' export function getInitialClaudeRateLimitTarget( diff --git a/src/main/rate-limits/service/rate-limit-service.ts b/src/main/rate-limits/service/rate-limit-service.ts index 7a73fc9dc57..9dcc556cc53 100644 --- a/src/main/rate-limits/service/rate-limit-service.ts +++ b/src/main/rate-limits/service/rate-limit-service.ts @@ -27,7 +27,7 @@ import type { import { type ClaudeAccountSelectionTarget, normalizeClaudeAccountSelectionTarget -} from '../../claude-accounts/runtime-selection' +} from '../../claude-accounts/selection/runtime-selection' import type { InactiveClaudeAccount } from '../providers/claude/claude-managed-account-usage' import type { RateLimitState } from '../../../shared/rate-limit-types' import type { NetworkProxySettings } from '../../../shared/network-proxy' diff --git a/src/main/rate-limits/service/service-account-refresh.ts b/src/main/rate-limits/service/service-account-refresh.ts index deef27ef19f..2f49faaeaea 100644 --- a/src/main/rate-limits/service/service-account-refresh.ts +++ b/src/main/rate-limits/service/service-account-refresh.ts @@ -8,7 +8,7 @@ import { import { normalizeClaudeAccountSelectionTarget, type ClaudeAccountSelectionTarget -} from '../../claude-accounts/runtime-selection' +} from '../../claude-accounts/selection/runtime-selection' import type { RateLimitRuntimeTarget, RateLimitState, diff --git a/src/main/rate-limits/service/service-fetch-policy.ts b/src/main/rate-limits/service/service-fetch-policy.ts index 9abc38cf22a..8af5c4b22b0 100644 --- a/src/main/rate-limits/service/service-fetch-policy.ts +++ b/src/main/rate-limits/service/service-fetch-policy.ts @@ -8,15 +8,15 @@ import { } from './service-types' import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types' import type { ClaudeStatusLineRateLimits } from '../../../shared/claude-statusline-rate-limits' -import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/runtime-selection' +import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/selection/runtime-selection' import type { ProviderRateLimits, RateLimitWindow } from '../../../shared/rate-limit-types' import { isSameClaudeUsageWindow, isStaleClaudeUsageWindow, mapClaudeUsageWindow } from '../providers/claude/claude-usage-window' -import { readUserClaudeConfigDir } from '../../claude-accounts/claude-profile-paths' -import { getClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' +import { readUserClaudeConfigDir } from '../../claude-accounts/profiles/claude-profile-paths' +import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router' export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchTargets { protected getMiniMaxCredentialError(message: string): ProviderRateLimits { diff --git a/src/main/rate-limits/service/service-fetch-targets.ts b/src/main/rate-limits/service/service-fetch-targets.ts index 9c3bb5811eb..98e7469acba 100644 --- a/src/main/rate-limits/service/service-fetch-targets.ts +++ b/src/main/rate-limits/service/service-fetch-targets.ts @@ -13,7 +13,7 @@ import type { CodexAccountSelectionTarget, NormalizedCodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' -import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/runtime-selection' +import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/selection/runtime-selection' import type { ProviderRateLimits, RateLimitState, diff --git a/src/main/rate-limits/service/service-full-cycle-preparation.ts b/src/main/rate-limits/service/service-full-cycle-preparation.ts index 77c1c48f867..1c616da325b 100644 --- a/src/main/rate-limits/service/service-full-cycle-preparation.ts +++ b/src/main/rate-limits/service/service-full-cycle-preparation.ts @@ -16,7 +16,7 @@ import { RateLimitServiceAntigravityAccounts } from './service-antigravity-accou import type { SettledProviderResult } from './service-sibling-provider-result' import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types' import type { InternalRateLimitState } from './service-types' -import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/runtime-selection' +import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/selection/runtime-selection' import type { NormalizedCodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' import type { ProviderRateLimits } from '../../../shared/rate-limit-types' diff --git a/src/main/rate-limits/service/service-state.ts b/src/main/rate-limits/service/service-state.ts index 0b227054390..2c19eaab23c 100644 --- a/src/main/rate-limits/service/service-state.ts +++ b/src/main/rate-limits/service/service-state.ts @@ -23,7 +23,7 @@ import { DEFAULT_POLL_MS } from './service-types' import type { NormalizedCodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' -import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/runtime-selection' +import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accounts/selection/runtime-selection' import type { InactiveClaudeAccount } from '../providers/claude/claude-managed-account-usage' import type { NetworkProxySettings } from '../../../shared/network-proxy' import { readGrokAuthSession } from '../providers/grok/grok-auth' diff --git a/src/main/rate-limits/service/service-types.ts b/src/main/rate-limits/service/service-types.ts index 6058ff47dd4..7b02dda32e9 100644 --- a/src/main/rate-limits/service/service-types.ts +++ b/src/main/rate-limits/service/service-types.ts @@ -1,7 +1,7 @@ import type { ProviderRateLimits } from '../../../shared/rate-limit-types' import type { ZcodePlanSite } from '../../../shared/zcode-plan-sites' import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types' -import type { ClaudeAccountSelectionTarget } from '../../claude-accounts/runtime-selection' +import type { ClaudeAccountSelectionTarget } from '../../claude-accounts/selection/runtime-selection' import type { KimiHomeResolution } from '../../kimi/kimi-runtime-home' import type { CodexAccountSelectionTarget } from '../../../shared/codex-selection-lane' import type { CodexRateLimitHomeResolution } from '../../codex-accounts/runtime-home-service-types' diff --git a/src/main/runtime/agent-session/environment/runtime-account-controller.ts b/src/main/runtime/agent-session/environment/runtime-account-controller.ts index 125680af224..a7a8ed17960 100644 --- a/src/main/runtime/agent-session/environment/runtime-account-controller.ts +++ b/src/main/runtime/agent-session/environment/runtime-account-controller.ts @@ -28,7 +28,7 @@ import { getClaudeSelectionTargetForAccount, getSelectedClaudeAccountIdForTarget, type ClaudeAccountSelectionTarget -} from '../../../claude-accounts/runtime-selection' +} from '../../../claude-accounts/selection/runtime-selection' import { hostAccountsManagedByDesktopMessage, type HostAccountLaunchEnv diff --git a/src/main/runtime/agent-session/environment/structured-agent-account-home.ts b/src/main/runtime/agent-session/environment/structured-agent-account-home.ts index d74eaabd789..bd6058eb775 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-account-home.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-account-home.ts @@ -1,8 +1,8 @@ import type { AgentSessionAccountKind } from '../../../../shared/agent-session/agent-session-availability' import type { GlobalSettings } from '../../../../shared/global-settings-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' -import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' -import { claudeRoutedHomeAsync } from '../../../claude-accounts/claude-profile-routed-home' +import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' +import { claudeRoutedHomeAsync } from '../../../claude-accounts/profiles/routing/claude-profile-routed-home' import { normalizeCodexRuntimeSelection } from '../../../codex-accounts/runtime-selection' import { resolveOrcaManagedCodexHomePath, diff --git a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts index 4bc70ab1968..c74956f87f3 100644 --- a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts +++ b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts @@ -2,7 +2,7 @@ import { ensureStructuredAgentModelCatalogOwner } from '../model-catalog/structu import type { StructuredAgentModelCatalogDeps } from './structured-agent-runtime-registration-types' import { resolveStructuredCodexAccountKind } from '../environment/structured-agent-account-home' import { nativeChatShellEnvironmentPolicy } from '../../../../shared/native-chat/native-chat-shell-environment' -import { claudeStructuredAuthPolicyForSettings } from '../../../claude-accounts/claude-structured-auth-policy' +import { claudeStructuredAuthPolicyForSettings } from '../../../claude-accounts/runtime-auth/claude-structured-auth-policy' import { resolveStructuredAgentCommand } from '../../../native-chat/structured-agent-command-resolution' import { structuredAgentConfiguredArgs } from '../../../native-chat/structured-agent-configured-args' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' diff --git a/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts b/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts index 5ff06a3a982..a9c1b2a4d2d 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-runtime-metadata.ts @@ -15,7 +15,7 @@ import { isNativeLocalLocation as supportsCodexStructuredLocation } from '../../ import { supportsClaudeStructuredLocation } from '../../../claude/structured/launch/claude-structured-location-support' import { supportsAcpStructuredLocation } from '../../../acp/session/acp-structured-location-support' import { PI_RPC_RUNTIME_METADATA } from '../../../pi/rpc-runtime-metadata' -import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { resolveStructuredClaudeAccountHomePath, resolveStructuredCodexAccountHomePath diff --git a/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts index 91fea923bff..34c77a1cf36 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts @@ -9,7 +9,7 @@ import type { StructuredAgentCommandSettings } from '../../../native-chat/structured-agent-command-resolution' import type { NativeChatShellEnvironmentPolicy } from '../../../../shared/native-chat/native-chat-shell-environment' -import type { ClaudeStructuredAuthPolicy } from '../../../claude-accounts/claude-structured-auth-policy' +import type { ClaudeStructuredAuthPolicy } from '../../../claude-accounts/runtime-auth/claude-structured-auth-policy' import type { RuntimeAgentAccountHomeResolver } from '../model-catalog/structured-agent-model-catalog-wiring' import type { ClaudeCliFlagSupport } from '../../../claude/claude-cli-flag-support' import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' diff --git a/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts b/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts index 7678151bba0..a43701d9a9b 100644 --- a/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-session-recovery-options.ts @@ -2,7 +2,7 @@ import { realpath, stat } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { agentSessionProviderHandleChainHead } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { agentSessionPinnedLaunchDirectory } from '../records/agent-session-record-launch-directory' import { structuredAgentRuntimeMetadata } from '../installation/structured-agent-runtime-metadata' import type { StructuredAgentTranscriptImport } from '../../../native-chat/structured-agent-cli-conversations' diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts index 24f0049e695..c59b8c1b969 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts @@ -3,7 +3,7 @@ import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-s import { resolveTuiAgentLaunchEnv } from '../../../../shared/agent-launch/choices/tui-agent-launch-defaults' import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' import { acpLaunchSpecFor } from '../../../acp/launch/acp-launch-registry' -import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' +import { getClaudeProfileRouter } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { claudeConfigDirEnvPatch, withoutInheritedClaudeConfigDir diff --git a/src/main/runtime/session-tabs/structured-session-account-home-location.test.ts b/src/main/runtime/session-tabs/structured-session-account-home-location.test.ts deleted file mode 100644 index 12e54b68cf9..00000000000 --- a/src/main/runtime/session-tabs/structured-session-account-home-location.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router' -import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { OrcaRuntimeWithStructuredSessionAccountHome } from './structured-session-account-home' -import { installClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' - -vi.mock('./structured-session-cli-writer-host', () => ({ - OrcaRuntimeWithStructuredSessionCliWriterHost: class {} -})) -vi.mock('../../orca-profiles/profile-storage-paths', async () => { - const { tmpdir } = await import('node:os') - return { getProfileUserDataPath: () => tmpdir() } -}) -const roots: string[] = [] -abstract class AccountHomeRuntime extends OrcaRuntimeWithStructuredSessionAccountHome { - resolveCreateHome(record: ReturnType) { - return this.structuredAgentAccountHomeResolver( - record.provider, - '', - 'launch' - )?.({ - launchEnv: {}, - location: record.location - }) - } -} -afterEach(() => { - installClaudeProfileRouter(undefined) - roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) -}) - -it('with a router names the selected account before its folder exists, through the real runtime resolver', async () => { - const root = mkdtempSync(join(tmpdir(), 'orca-account-identity-')) - roots.push(root) - const settings = { - claudeManagedAccounts: [], - activeClaudeManagedAccountId: 'a', - activeClaudeManagedAccountIdsByRuntime: undefined, - agentStatusHooksEnabled: false, - disabledTuiAgents: [] - } - const runSetup = vi.fn(async () => { - throw new Error('setup refused') - }) - const router = new ClaudeProfileRouter({ - getSettings: () => settings, - dataRoot: root, - userHome: join(root, 'personal'), - env: {}, - runSetup - }) - installClaudeProfileRouter(router) - const runtime: AccountHomeRuntime = Object.assign(Object.create(AccountHomeRuntime.prototype), { - accounts: { getClaudeConfigDirectory: () => router.systemDefaultHome() }, - requireStore: () => ({ getSettings: () => settings }), - structuredAgentLaunchEnv: () => ({}) - }) - const record = agentSessionRecordFixture() - const selected = { variable: 'CLAUDE_CONFIG_DIR', path: router.accountHome('a') } - await expect( - runtime.resolveStructuredAgentLaunchAccountHome(record, 'identity') - ).resolves.toEqual(selected) - await expect(runtime.resolveCreateHome(record)).resolves.toEqual(selected) - await expect(runtime.resolveStructuredAgentLaunchAccountHome(record)).rejects.toMatchObject({ - name: 'AgentSessionPreSpawnError', - reason: 'claudeAccountFolderMissing' - }) - // Neither read starts the account's setup; only a launch does. - expect(existsSync(selected.path)).toBe(false) - mkdirSync(selected.path, { recursive: true }) - await expect(runtime.resolveStructuredAgentLaunchAccountHome(record)).resolves.toEqual(selected) - await expect( - runtime.resolveStructuredAgentLaunchAccountHome(record, 'identity') - ).resolves.toEqual(selected) -}) diff --git a/src/main/runtime/terminal/launch/terminal-split-source-authority.ts b/src/main/runtime/terminal/launch/terminal-split-source-authority.ts index 91d8a8316c0..6b3901a9c89 100644 --- a/src/main/runtime/terminal/launch/terminal-split-source-authority.ts +++ b/src/main/runtime/terminal/launch/terminal-split-source-authority.ts @@ -11,7 +11,7 @@ import { ensureClaudeAgentTeamsShimDir, resolveClaudeAgentTeamsShimBin } from './claude-agent-teams-shim-env' -import { applyClaudeEnvPatch } from '../../../claude-accounts/environment' +import { applyClaudeEnvPatch } from '../../../claude-accounts/runtime-auth/environment' import { worktreeIdsEqual } from '../../../../shared/worktree/id' import { splitPanePendingError } from './terminal-split-retry' import { diff --git a/src/main/skills/bundled-skill-install/bundled-skill-local-host.ts b/src/main/skills/bundled-skill-install/bundled-skill-local-host.ts index 2a453c67a24..880f37b5699 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-local-host.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-local-host.ts @@ -7,7 +7,7 @@ import { detectInstalledAgentsWithShellPathHydration } from '../../preflight/ins import { readUserClaudeConfigDir, resolveClaudeDefaultHome -} from '../../claude-accounts/claude-profile-paths' +} from '../../claude-accounts/profiles/claude-profile-paths' import { resolveEnvironmentSkillProviderRoots, withClaudeSkillProviderRoot diff --git a/src/main/startup/wsl-orcad-account-env-wiring.ts b/src/main/startup/wsl-orcad-account-env-wiring.ts index dc722baaa19..f6f73304bfc 100644 --- a/src/main/startup/wsl-orcad-account-env-wiring.ts +++ b/src/main/startup/wsl-orcad-account-env-wiring.ts @@ -1,6 +1,6 @@ import { BrowserWindow } from 'electron' -import { withClaudeProfileTerminalEnv } from '../claude-accounts/claude-profile-installed-router' -import { getSelectedClaudeAccountIdForTarget } from '../claude-accounts/runtime-selection' +import { withClaudeProfileTerminalEnv } from '../claude-accounts/profiles/routing/claude-profile-installed-router' +import { getSelectedClaudeAccountIdForTarget } from '../claude-accounts/selection/runtime-selection' import { getSelectedCodexAccountIdForTarget } from '../codex-accounts/runtime-selection' import type { Store } from '../persistence/loading-store/store' import { installWslOrcadAccountEnvDependencies } from '../wsl/orcad/wsl-orcad-account-env' diff --git a/src/main/text-generation/commit-message-agent-environment.ts b/src/main/text-generation/commit-message-agent-environment.ts index 27ab2272757..7ce44a57547 100644 --- a/src/main/text-generation/commit-message-agent-environment.ts +++ b/src/main/text-generation/commit-message-agent-environment.ts @@ -1,5 +1,5 @@ -import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth-service' -import { applyClaudeEnvPatch } from '../claude-accounts/environment' +import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth/runtime-auth-types' +import { applyClaudeEnvPatch } from '../claude-accounts/runtime-auth/environment' import { readShellStartupEnvVar } from '../pty/shell-startup/shell-startup-env' import { parseWslUncPath } from '../../shared/wsl-paths' import { diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index 360e4cd7233..a4918046469 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -35,9 +35,9 @@ import { scheduleHistoryGc } from '../pty/history/terminal-history-gc' import { openCodeHookService, openCode2HookService } from '../opencode/status-hooks/hook-service' import { listLiveDaemonPtyIds } from '../daemon/providers/lifecycle/daemon-provider-state' import { hydrateLocalPtyRegistryAtBoot } from '../memory/hydrate-local-pty-registry' -import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth-service' +import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth/runtime-auth-types' import { getKnownWorktreeIdsForHistoryGc } from './history-gc-worktree-ids' -import type { ClaudeAccountSelectionTarget } from '../claude-accounts/runtime-selection' +import type { ClaudeAccountSelectionTarget } from '../claude-accounts/selection/runtime-selection' import { scheduleWorktreeBaseDirectoryWatcherSync, setWorktreeBaseDirectoryWatcherSyncContext diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts index 62fd4512ae1..5acb7526aec 100644 --- a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts +++ b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts @@ -1,4 +1,4 @@ -import { claudeProfileHistoryDirs } from '../../../claude-accounts/claude-profile-installed-router' +import { claudeProfileHistoryDirs } from '../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { homedir } from 'node:os' import { join } from 'node:path' import { isWslUncPath, parseWslUncPath } from '../../../../shared/wsl-paths' From 9bf3826210065e4bf9a648d4cc4945e39db891d0 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:50:52 -0500 Subject: [PATCH 21/40] perf(orchestration): an unreadable item holds back only its own conversation, and remote-owned queries use their indexes (#41121) * perf(orchestration): an unreadable item holds back only its own conversation, and remote-owned queries use their indexes * fix(orchestration): a held conversation stays skipped for its batch, and pulls past the hold-back cap wait locally --- .../remote-owned/remote-dispatch-records.ts | 39 +++++--- .../remote-owned-query-plans.test.ts | 68 ++++++++++++++ .../remote-owned/remote-owned-schema-sql.ts | 3 + .../peer-mail/held-peer-conversations.test.ts | 17 ++++ .../peer-mail/held-peer-conversations.ts | 59 ++++++++++++ .../federation/peer-mail/peer-mail-relay.ts | 29 ++++-- .../remote-owned/remote-owed-actions.test.ts | 92 +++++++++++++------ .../remote-owned/remote-owned-reads.test.ts | 14 ++- .../remote-owned/remote-owned-reads.ts | 11 ++- .../federation/peer-coordinator.test.ts | 14 +++ .../federation/peer-mail-methods.ts | 13 ++- .../orchestration-peer-mail-params.ts | 4 +- 12 files changed, 301 insertions(+), 62 deletions(-) create mode 100644 src/main/runtime/orchestration/db/remote-owned/remote-owned-query-plans.test.ts create mode 100644 src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.test.ts create mode 100644 src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.ts diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-dispatch-records.ts b/src/main/runtime/orchestration/db/remote-owned/remote-dispatch-records.ts index a696a2c0f22..fa8a54f73f7 100644 --- a/src/main/runtime/orchestration/db/remote-owned/remote-dispatch-records.ts +++ b/src/main/runtime/orchestration/db/remote-owned/remote-dispatch-records.ts @@ -66,28 +66,37 @@ export function getRemoteDispatch( | undefined } -/** Newest first, in one Run or every Run, with the state of the link each came home under. */ +type RemoteDispatchListRow = RemoteDispatchRow & { + link_state: RemoteRunLinkRow['state'] | null + server_name: string | null +} + +/** Newest first, in one Run or every Run, with the state of the link each came home under. Two + * statements, not `? IS NULL OR`, so a named Run reads through its index. */ export function listRemoteDispatches( db: OrchestrationDb, scope: { runId?: string; limit: number } -): (RemoteDispatchRow & { link_state: RemoteRunLinkRow['state'] | null })[] { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the record's columns plus the joined link state. - return db.db - .prepare( - `SELECT record.*, link.state AS link_state FROM remote_dispatches record - LEFT JOIN remote_run_links link ON link.conversation_id = record.conversation_id - WHERE (? IS NULL OR record.run_id = ?) ORDER BY record.rowid DESC LIMIT ?` - ) - .all(scope.runId ?? null, scope.runId ?? null, scope.limit) as (RemoteDispatchRow & { - link_state: RemoteRunLinkRow['state'] | null - })[] +): RemoteDispatchListRow[] { + const select = `SELECT record.*, link.state AS link_state, link.server_name AS server_name + FROM remote_dispatches record + LEFT JOIN remote_run_links link ON link.conversation_id = record.conversation_id` + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the record's columns plus the joined link's state and name. + return ( + scope.runId === undefined + ? db.db.prepare(`${select} ORDER BY record.rowid DESC LIMIT ?`).all(scope.limit) + : db.db + .prepare(`${select} WHERE record.run_id = ? ORDER BY record.rowid DESC LIMIT ?`) + .all(scope.runId, scope.limit) + ) as RemoteDispatchListRow[] } export function countRemoteDispatches(db: OrchestrationDb, runId: string | undefined): number { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: COUNT(*) returns one number. - const row = db.db - .prepare('SELECT COUNT(*) AS count FROM remote_dispatches WHERE (? IS NULL OR run_id = ?)') - .get(runId ?? null, runId ?? null) as { count: number } + const row = ( + runId === undefined + ? db.db.prepare('SELECT COUNT(*) AS count FROM remote_dispatches').get() + : db.db.prepare('SELECT COUNT(*) AS count FROM remote_dispatches WHERE run_id = ?').get(runId) + ) as { count: number } return row.count } diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-owned-query-plans.test.ts b/src/main/runtime/orchestration/db/remote-owned/remote-owned-query-plans.test.ts new file mode 100644 index 00000000000..f33bdec0662 --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-owned-query-plans.test.ts @@ -0,0 +1,68 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { OrchestrationDb } from '../orchestration-db' +import { countRemoteDispatches, listRemoteDispatches } from './remote-dispatch-records' +import { closeRemoteRunLink, openRemoteRunLink } from './remote-run-links' + +/** The query plan of every statement `act` prepares that reads or writes one of `tables`. */ +function plansOf(db: OrchestrationDb, tables: string[], act: () => void): string[] { + const prepare = vi.spyOn(db.db, 'prepare') + act() + const statements = prepare.mock.calls + .map(([sql]) => sql) + .filter((sql) => tables.some((table) => sql.includes(table))) + prepare.mockRestore() + expect(statements.length).toBeGreaterThan(0) + return statements.flatMap((sql) => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: EXPLAIN QUERY PLAN rows carry a detail column. + (db.db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all() as { detail: string }[]).map( + ({ detail }) => detail + ) + ) +} + +describe('remote-owned queries read through their indexes', () => { + let db: OrchestrationDb + + beforeEach(() => { + db = new OrchestrationDb(':memory:') + }) + + afterEach(() => { + db.close() + }) + + it("closing a link visits only that link's placements and records", () => { + const run = db.createRun({ + objective: 'Ship', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const link = openRemoteRunLink(db, run.id, { + environmentId: 'env_b', + name: 'devB', + peerFingerprint: 'host_b', + homePeerFingerprint: 'cred_a', + pairingRevision: 1 + }) + + const plans = plansOf(db, ['remote_placements', 'remote_dispatches'], () => + closeRemoteRunLink(db, link.conversation_id, 'The pairing with devB was re-made.') + ) + expect(plans.filter((detail) => detail.startsWith('SCAN'))).toEqual([]) + expect(plans).toEqual( + expect.arrayContaining([ + expect.stringContaining('idx_remote_placements_conversation'), + expect.stringContaining('idx_remote_dispatches_conversation') + ]) + ) + }) + + it("worker-list for one Run reads that Run's records by its index", () => { + const plans = plansOf(db, ['remote_dispatches'], () => { + countRemoteDispatches(db, 'run_1') + listRemoteDispatches(db, { runId: 'run_1', limit: 50 }) + }) + expect(plans.filter((detail) => detail.startsWith('SCAN'))).toEqual([]) + expect(plans.filter((detail) => detail.includes('idx_remote_dispatches_run'))).toHaveLength(2) + }) +}) diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-owned-schema-sql.ts b/src/main/runtime/orchestration/db/remote-owned/remote-owned-schema-sql.ts index 4910528812e..f21a2969e5c 100644 --- a/src/main/runtime/orchestration/db/remote-owned/remote-owned-schema-sql.ts +++ b/src/main/runtime/orchestration/db/remote-owned/remote-owned-schema-sql.ts @@ -41,6 +41,8 @@ CREATE TABLE IF NOT EXISTS remote_placements ( dispatch_id TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); +-- Closing a link visits only its own rows here and in remote_dispatches. +CREATE INDEX IF NOT EXISTS idx_remote_placements_conversation ON remote_placements(conversation_id); -- What the server last said about one of its Dispatches here, and any stop this Orca owes it. CREATE TABLE IF NOT EXISTS remote_dispatches ( @@ -71,6 +73,7 @@ CREATE TABLE IF NOT EXISTS remote_dispatches ( ); CREATE INDEX IF NOT EXISTS idx_remote_dispatches_run ON remote_dispatches(run_id); CREATE INDEX IF NOT EXISTS idx_remote_dispatches_task ON remote_dispatches(task_id); +CREATE INDEX IF NOT EXISTS idx_remote_dispatches_conversation ON remote_dispatches(conversation_id); CREATE INDEX IF NOT EXISTS idx_remote_dispatches_stop_owed ON remote_dispatches(environment_id) WHERE stop_owed = 1; diff --git a/src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.test.ts b/src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.test.ts new file mode 100644 index 00000000000..bd6872a10e7 --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { HeldPeerConversations } from './held-peer-conversations' + +describe('conversations held back from a pull', () => { + it('names the latest-due 50 past the cap, so the soonest due come back and are retried first', () => { + const held = new HeldPeerConversations() + for (let index = 0; index <= 50; index += 1) { + held.failed(`conv_${index}`, 1_000 + index) + } + + const { holdBack, waitMs } = held.forPull(1_100, 20_000) + expect(holdBack).toHaveLength(50) + expect(holdBack).not.toContain('conv_0') + expect(holdBack).toContain('conv_50') + expect(waitMs).toBe(1_900) + }) +}) diff --git a/src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.ts b/src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.ts new file mode 100644 index 00000000000..713e47ec023 --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/held-peer-conversations.ts @@ -0,0 +1,59 @@ +import { federationRelayRetryDelayMs } from '../relay/federation-relay-scheduler' + +// The server's cap on one pull's held-back list. +const MAX_HELD_BACK = 50 + +/** Conversations on one server whose next item this Orca could not read. Each waits out its own + * backoff, held back from the server's pulls meanwhile, so the rest of its mail keeps its cadence. */ +export class HeldPeerConversations { + private readonly held = new Map() + + /** What the next pull holds back, and how long it may wait before a held one is due again. Past + * the cap, the soonest due go unnamed: the server returns them, and they are retried first. */ + forPull(now: number, maxWaitMs: number): { holdBack: string[]; waitMs: number } { + const waiting = [...this.held].filter(([, hold]) => hold.retryAt > now) + waiting.sort(([, a], [, b]) => b.retryAt - a.retryAt) + return { + holdBack: waiting.slice(0, MAX_HELD_BACK).map(([conversationId]) => conversationId), + waitMs: this.msUntilDue( + waiting.map(([conversationId]) => conversationId), + now, + maxWaitMs + ) + } + } + + /** Until the first of these is due again, at most `maxMs`. */ + msUntilDue(conversationIds: Iterable, now: number, maxMs: number): number { + let ms = maxMs + for (const conversationId of conversationIds) { + const retryAt = this.held.get(conversationId)?.retryAt + if (retryAt !== undefined) { + ms = Math.min(ms, Math.max(0, retryAt - now)) + } + } + return ms + } + + untilFirstDue(conversationIds: Iterable, now: number, maxMs: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, this.msUntilDue(conversationIds, now, maxMs)).unref?.() + }) + } + + isWaiting(conversationId: string, now: number): boolean { + return (this.held.get(conversationId)?.retryAt ?? 0) > now + } + + failed(conversationId: string, now: number): void { + const failures = (this.held.get(conversationId)?.failures ?? 0) + 1 + this.held.set(conversationId, { + failures, + retryAt: now + federationRelayRetryDelayMs(failures) + }) + } + + read(conversationId: string): void { + this.held.delete(conversationId) + } +} diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts index b6409bab3bd..dbd37b0e756 100644 --- a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts @@ -5,6 +5,7 @@ import { resolveBareOrchestrationRecipient } from '../../../rpc/methods/orchestr import type { OrchestrationDb } from '../../db/orchestration-db' import type { MessageRow } from '../../db/orchestration-records' import { federationRelayRetryDelayMs } from '../relay/federation-relay-scheduler' +import { HeldPeerConversations } from './held-peer-conversations' import type { OrchestrationEnvironmentTransport } from '../environment-transport' import { peerMailLocalRecipient } from './peer-mail-delivery' import { presentImportedPeerItem } from '../../mailbox/formatting/imported-peer-item-presentation' @@ -50,6 +51,7 @@ type Loop = { db: OrchestrationDb stopped: boolean resending: boolean + held: HeldPeerConversations } /** One pull loop per paired server this Orca opened conversations with or coordinates Runs on. The @@ -78,7 +80,7 @@ export class PeerMailRelay { if (current && !current.stopped && current.db === db) { continue } - const loop: Loop = { db, stopped: false, resending: false } + const loop: Loop = { db, stopped: false, resending: false, held: new HeldPeerConversations() } this.loops.set(environmentId, loop) void this.run(environmentId, loop) } @@ -164,11 +166,12 @@ export class PeerMailRelay { (handle, type) => this.runtime.notifyMessageArrived(handle, type) ) this.resendOwed(environmentId, loop) + const { holdBack, waitMs } = loop.held.forPull(Date.now(), PULL_WAIT_MS) const response = await this.runtime .callOrchestrationWorkerServer( environmentId, 'orchestration.peerMailPull', - { waitMs: PULL_WAIT_MS }, + { waitMs, ...(holdBack.length > 0 ? { holdBack } : {}) }, PULL_TIMEOUT_MS ) .catch((error: unknown) => { @@ -191,11 +194,21 @@ export class PeerMailRelay { } const through = new Map() const stuck = new Map() + // One clock for the batch, and a held conversation stays skipped to its end: none of its later + // items is imported, so the ack never passes the item it is waiting to retry. + const now = Date.now() + const heldBack = new Set() + let onlyHeldBack = true for (const item of items) { // An item that cannot be read holds back its own conversation only; the others keep moving. - if (stuck.has(item.conversationId)) { + if (stuck.has(item.conversationId) || heldBack.has(item.conversationId)) { continue } + if (loop.held.isWaiting(item.conversationId, now)) { + heldBack.add(item.conversationId) + continue + } + onlyHeldBack = false try { const stored = this.importItem(loop.db, environmentId, item) // Wake before the ack: a replay after a failed ack finds the row stored and stays quiet. @@ -204,9 +217,11 @@ export class PeerMailRelay { } } catch (error) { stuck.set(item.conversationId, error) + loop.held.failed(item.conversationId, now) noteRemoteRunLinkError(loop.db, item.conversationId, error) continue } + loop.held.read(item.conversationId) through.set( item.conversationId, Math.max(through.get(item.conversationId) ?? 0, item.sequence) @@ -228,11 +243,13 @@ export class PeerMailRelay { const [failure] = stuck.values() if (failure !== undefined) { console.warn( - `[orchestration] Stopped reading ${stuck.size} conversation(s) from ${environmentId}:`, + `[orchestration] Holding back ${stuck.size} conversation(s) from ${environmentId}:`, failure instanceof Error ? failure.message : failure ) - // Backs the loop off, so a server that keeps returning the same unreadable item is not re-pulled hot. - throw failure + } + if (onlyHeldBack) { + // Only conversations still waiting came back (an older server, or past the cap): no hot re-pull. + await loop.held.untilFirstDue(heldBack, now, PULL_WAIT_MS) } } diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.test.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.test.ts index f606244cc4f..40faa91260a 100644 --- a/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.test.ts +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.test.ts @@ -30,9 +30,10 @@ import type { } from '../environment-transport' import { resendOwedRemoteActions, sendOwedRemoteStop } from './remote-owed-actions' +const retry = vi.hoisted(() => ({ delayMs: 5 })) vi.mock('../relay/federation-relay-scheduler', async (original) => ({ ...(await original()), - federationRelayRetryDelayMs: () => 5 + federationRelayRetryDelayMs: () => retry.delayMs })) const COORDINATOR_PANE = 'tab_coord:11111111-1111-4111-8111-111111111111' @@ -62,7 +63,8 @@ describe('what the coordinating Orca owes a paired server', () => { const createTransport = ( sent: Sent[], answers: Record, - pulls: unknown[][] + pulls: unknown[][], + pullParams: unknown[] ): OrchestrationEnvironmentTransport => ({ resolve: () => server, hasEnvironment: () => true, @@ -77,6 +79,7 @@ describe('what the coordinating Orca owes a paired server', () => { return ok({ capabilities: [ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY] }) } if (method === 'orchestration.peerMailPull') { + pullParams.push(params) await new Promise((resolve) => setImmediate(resolve)) return ok({ items: pulls.shift() ?? [] }) } @@ -95,14 +98,17 @@ describe('what the coordinating Orca owes a paired server', () => { } }) let pulls: unknown[][] + let pullParams: unknown[] beforeEach(() => { sent = [] answers = {} pulls = [] + pullParams = [] + retry.delayMs = 5 db = new OrchestrationDb(':memory:') runtime = new OrcaRuntimeService(null, undefined, { - orchestrationEnvironmentTransport: createTransport(sent, answers, pulls) + orchestrationEnvironmentTransport: createTransport(sent, answers, pulls, pullParams) }) vi.spyOn(runtime, 'readMachineName').mockReturnValue('Mac A') runtime.setOrchestrationDb(db) @@ -328,33 +334,33 @@ describe('what the coordinating Orca owes a paired server', () => { }) describe('S8 pull loop', () => { - it('acknowledges what it imported before an unreadable item, and never that item', async () => { - startedOnB() - const state = (seq: number, payload?: string) => ({ - conversationId: link.conversation_id, - sequence: seq, - messageId: `state_${seq}`, - kind: 'worker_state', - payload: - payload ?? - JSON.stringify({ - v: 1, - id: `state_${seq}`, - homeRunId: run.id, - peerRunId: 'run_on_b', - dispatch: { - id: 'ctx_b1', - taskId: 'task_t', - status: 'dispatched', - workerState: 'ready', - lastFailure: null, - agent: null - }, - task: { status: 'dispatched', result: null }, - correctedUnobservedPrompt: false, - removed: null - }) - }) + const state = (seq: number, payload?: string) => ({ + conversationId: link.conversation_id, + sequence: seq, + messageId: `state_${seq}`, + kind: 'worker_state', + payload: + payload ?? + JSON.stringify({ + v: 1, + id: `state_${seq}`, + homeRunId: run.id, + peerRunId: 'run_on_b', + dispatch: { + id: 'ctx_b1', + taskId: 'task_t', + status: 'dispatched', + workerState: 'ready', + lastFailure: null, + agent: null + }, + task: { status: 'dispatched', result: null }, + correctedUnobservedPrompt: false, + removed: null + }) + }) + + function otherConversation() { const otherRun = db.createRun({ objective: 'Other', coordinatorHandle: null, @@ -366,6 +372,12 @@ describe('what the coordinating Orca owes a paired server', () => { conversationId: other.conversation_id, payload: state(7).payload.replace(run.id, otherRun.id) } + return { other, otherItem } + } + + it('acknowledges what it imported before an unreadable item, and never that item', async () => { + startedOnB() + const { other, otherItem } = otherConversation() pulls.push([state(1), { ...state(2), kind: 'worker_future' }, state(3), otherItem]) answers['orchestration.peerMailAck'] = [{ result: { acknowledged: 1 } }] runtime.ensureOrchestrationFederationRelay() @@ -387,5 +399,25 @@ describe('what the coordinating Orca owes a paired server', () => { last_error: expect.stringContaining('kind worker_future') }) }) + + it("keeps reading the server's other conversations while an unreadable one waits out its own backoff", async () => { + retry.delayMs = 10_000 + startedOnB() + const { other, otherItem } = otherConversation() + pulls.push([{ ...state(1), kind: 'worker_future' }], [otherItem]) + answers['orchestration.peerMailAck'] = [{ result: { acknowledged: 1 } }] + runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => + expect(sent.some((s) => s.method === 'orchestration.peerMailAck')).toBe(true) + ) + runtime.stopOrchestrationFederationRelay() + expect(sent.find((s) => s.method === 'orchestration.peerMailAck')?.params).toEqual({ + acknowledgments: [{ conversationId: other.conversation_id, throughSequence: 7 }] + }) + expect(pullParams[1]).toMatchObject({ + holdBack: [link.conversation_id], + waitMs: expect.toSatisfy((ms: number) => ms > 0 && ms <= 10_000) + }) + }) }) }) diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.test.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.test.ts index 2fee903fd98..6d1a20ef6d4 100644 --- a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.test.ts +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.test.ts @@ -14,7 +14,7 @@ import { recordRemoteDispatchState } from '../../db/remote-owned/remote-dispatch-records' import { recordRemoteStart, reserveRemotePlacement } from '../../db/remote-owned/remote-placements' -import { openRemoteRunLink } from '../../db/remote-owned/remote-run-links' +import { closeRemoteRunLink, openRemoteRunLink } from '../../db/remote-owned/remote-run-links' import { ORCHESTRATION_WORKER_LIST_METHOD } from '../../../rpc/methods/orchestration/worker/worker-list-method' const SERVER: OrchestrationWorkerServer = { @@ -94,6 +94,18 @@ describe('reads of workers a paired server runs, from this Orca’s records', () } as never)) as ListedWorkers } + it('lists a worker on a server removed since under the name the server had', async () => { + const record = remoteWorker('task_1', 'ctx_w1', 'env_gone') + closeRemoteRunLink( + db, + record.conversation_id, + "devB was removed from this Orca's paired servers." + ) + + const listed = await listWorkers({ run: run.id, paginate: true }) + expect(listed.workers[0]?.server).toMatchObject({ name: 'devB' }) + }) + it('lists remote workers on the first page beside local ones, named by their server, and nowhere else', async () => { remoteWorker('task_1', 'ctx_w1') remoteWorker('task_2', 'ctx_w2') diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.ts index 9737a034207..a596f7a9f9c 100644 --- a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.ts +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.ts @@ -131,7 +131,7 @@ export type RemoteWorkerListRow = ReturnType function remoteWorkerListRow( record: ReturnType[number], - name: (environmentId: string) => string + name: (environmentId: string, recorded: string | null) => string ) { return { dispatchId: record.dispatch_id, @@ -142,7 +142,7 @@ function remoteWorkerListRow( agentTerminalHandle: null, terminalState: null, resource: null, - server: remoteWorkerServer(record, record.link_state, name) + server: remoteWorkerServer(record, record.link_state, (id) => name(id, record.server_name)) } } @@ -177,9 +177,10 @@ export function withRemoteWorkerRows( return { ...page, page: { ...page.page, total: page.page.total + total } } } const names = new Map() - const name = (id: string): string => { - const known = names.get(id) ?? remoteServerName(runtime, id) - names.set(id, known) + const name = (id: string, recorded: string | null): string => { + const key = `${id}\n${recorded ?? ''}` + const known = names.get(key) ?? remoteServerName(runtime, id, recorded) + names.set(key, known) return known } const rows = listRemoteDispatches(db, { runId: params.run, limit: Math.max(0, maxRows) }).map( diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts index 287a4305dd9..e941bfaa012 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts @@ -144,6 +144,20 @@ describe('a paired Orca coordinating its Run on this server', () => { ]) }) + it('leaves out the conversations a pull holds back, and returns the others', async () => { + const held = conversationId + const other = generateId('peerconv') + await peerCall('orchestration.runCurrent', {}) + await peerCall('orchestration.runCurrent', {}, { conversation: other }) + for (const conversation of [held, other]) { + const runId = db.getPeerRunForConversation(conversation)!.run_id + db.insertMessage({ from: 'term_w', to: `run:${runId}`, subject: 'mail', runId }) + } + + const items = await pull('pull', { holdBack: [held] }) + expect(items.items.map((item) => item.conversationId)).toEqual([other]) + }) + it('rotates the page when more conversations are pending than it holds, so none starves', async () => { const conversations = Array.from({ length: 51 }, () => generateId('peerconv')) for (const conversation of conversations) { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts index 7c7b5df0a94..892294934d0 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts @@ -40,10 +40,14 @@ const pullRotations = new WeakMap>() /** Every conversation with pending items gets an equal share of the page, so an item the paired Orca * cannot import yet, which stays at its conversation's head, never starves another conversation. */ -function pendingReplies(db: OrchestrationDb, peerFingerprint: string): FederationRelayItemRow[] { +function pendingReplies( + db: OrchestrationDb, + peerFingerprint: string, + holdBack: ReadonlySet +): FederationRelayItemRow[] { const pending = db .listPeerConversationIds(peerFingerprint) - .filter((id) => db.listPendingFederationRelay(id, 'to_home', 1).length > 0) + .filter((id) => !holdBack.has(id) && db.listPendingFederationRelay(id, 'to_home', 1).length > 0) const share = Math.max(1, Math.floor(PULL_PAGE_SIZE / pending.length)) const pullRotation = pullRotations.get(db.db) ?? new Map() pullRotations.set(db.db, pullRotation) @@ -159,13 +163,14 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ handler: async (params, ctx) => { const peerFingerprint = requireRuntimePairing(ctx) const db = ctx.runtime.getOrchestrationDb() - let items = pendingReplies(db, peerFingerprint) + const holdBack = new Set(params.holdBack) + let items = pendingReplies(db, peerFingerprint, holdBack) const waitMs = Math.min(Math.max(params.waitMs ?? 0, 0), MAX_PULL_WAIT_MS) const deadline = Date.now() + waitMs // A wake is any queued change on this Orca, so one that queued nothing for this peer waits on. while (items.length === 0 && Date.now() < deadline && !ctx.signal?.aborted) { await waitForPeerMail(db.db, deadline - Date.now(), ctx.signal) - items = pendingReplies(ctx.runtime.getOrchestrationDb(), peerFingerprint) + items = pendingReplies(ctx.runtime.getOrchestrationDb(), peerFingerprint, holdBack) } return { items: items.map((item) => ({ diff --git a/src/shared/rpc-contract/orchestration-peer-mail-params.ts b/src/shared/rpc-contract/orchestration-peer-mail-params.ts index a0fca4764df..09fadb16720 100644 --- a/src/shared/rpc-contract/orchestration-peer-mail-params.ts +++ b/src/shared/rpc-contract/orchestration-peer-mail-params.ts @@ -16,7 +16,9 @@ export const PeerMailDeliverParams = z.object({ /** The opening Orca pulls replies queued for its conversations; waits up to waitMs for one. */ export const PeerMailPullParams = z.object({ - waitMs: OptionalFiniteNumber + waitMs: OptionalFiniteNumber, + /** Conversations it could not read and is waiting to retry: their items neither return nor end the wait. */ + holdBack: z.array(z.string()).max(50).optional() }) export const PeerMailAckParams = z.object({ From 3cd9f9981c615caa2fc95ddd6ab183c9592d5424 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:53:24 -0800 Subject: [PATCH 22/40] fix(skills): ignore Claude desktop synced skills in feature install checks (#41257) --- .../installed-agent-skill-verdict.ts | 16 ++++- .../discovery/useInstalledAgentSkills.test.ts | 61 +++++++++++++++++++ .../discovery/useInstalledAgentSkills.ts | 3 +- 3 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.test.ts diff --git a/src/renderer/src/hooks/skills/discovery/installed-agent-skill-verdict.ts b/src/renderer/src/hooks/skills/discovery/installed-agent-skill-verdict.ts index 67d895ad3f8..5ea956d24ff 100644 --- a/src/renderer/src/hooks/skills/discovery/installed-agent-skill-verdict.ts +++ b/src/renderer/src/hooks/skills/discovery/installed-agent-skill-verdict.ts @@ -1,4 +1,9 @@ -import type { SkillDiscoverySource, SkillSourceKind } from '../../../../../shared/skills' +import { relativePathInsideRoot } from '../../../../../shared/cross-platform-path' +import type { + DiscoveredSkill, + SkillDiscoverySource, + SkillSourceKind +} from '../../../../../shared/skills' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' @@ -54,3 +59,12 @@ export function getInstalledAgentSkillVerdict( : null) } } + +// Why: Claude desktop owns `~/.claude/skills/synced//` copies; they are not Orca feature installs. +export function isClaudeDesktopSyncedSkill(skill: DiscoveredSkill): boolean { + if (skill.sourceKind !== 'home' || !skill.providers.includes('claude')) { + return false + } + const segments = relativePathInsideRoot(skill.rootPath, skill.directoryPath)?.split('/') ?? [] + return segments.length >= 3 && segments[0] === 'synced' +} diff --git a/src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.test.ts b/src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.test.ts new file mode 100644 index 00000000000..b0052f0c40a --- /dev/null +++ b/src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import type { DiscoveredSkill } from '../../../../../shared/skills' +import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, hasInstalledAgentSkill } from './useInstalledAgentSkills' + +function makeSkill( + overrides: Partial & Pick +): DiscoveredSkill { + return { + id: overrides.name, + description: '', + sourceKind: 'home', + sourceLabel: 'Claude', + installed: true, + updatedAt: null, + providers: ['claude'], + rootPath: '/Users/test/.claude/skills', + directoryPath: `/Users/test/.claude/skills/${overrides.name}`, + skillFilePath: `/Users/test/.claude/skills/${overrides.name}/SKILL.md`, + ...overrides + } +} + +describe('hasInstalledAgentSkill synced-folder exclusion', () => { + it('does not count Claude desktop synced skills as installs', () => { + const synced = [ + makeSkill({ + name: 'computer-use', + providers: ['claude'], + rootPath: '/Users/test/.claude/skills', + directoryPath: '/Users/test/.claude/skills/synced/org_bucket/computer-use' + }), + makeSkill({ + name: 'computer-use', + providers: ['claude'], + rootPath: 'C:\\Users\\test\\.claude\\skills', + directoryPath: 'C:\\Users\\test\\.claude\\skills\\synced\\org_bucket\\computer-use' + }) + ] + expect( + hasInstalledAgentSkill(synced, 'computer-use', { + sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS + }) + ).toBe(false) + }) + + it('still counts synced folder installs outside Claude home', () => { + const options = { sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS } + for (const directoryPath of [ + '/Users/test/.hermes/skills/synced/computer-use', + '/Users/test/.hermes/skills/synced/team/computer-use' + ]) { + const installed = makeSkill({ + name: 'computer-use', + providers: ['codex'], + rootPath: '/Users/test/.hermes/skills', + directoryPath + }) + expect(hasInstalledAgentSkill([installed], 'computer-use', options)).toBe(true) + } + }) +}) diff --git a/src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts b/src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts index 243ccf7ffea..88ab44a59ae 100644 --- a/src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts +++ b/src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts @@ -18,6 +18,7 @@ import { } from './installed-agent-skill-discovery' import { getInstalledAgentSkillVerdict, + isClaudeDesktopSyncedSkill, type InstalledAgentSkillScan } from './installed-agent-skill-verdict' import { @@ -92,7 +93,7 @@ export function hasInstalledAgentSkillNamed( if (options.agent && !agentReadsSkill(options.agent, skill, options.sources ?? [])) { return false } - if (!skill.installed) { + if (!skill.installed || isClaudeDesktopSyncedSkill(skill)) { return false } if (options.sourceKinds && !options.sourceKinds.includes(skill.sourceKind)) { From d411a584fa1efda73a810ca93b266207ae624a15 Mon Sep 17 00:00:00 2001 From: Noah Date: Thu, 12 Nov 2026 06:55:01 +0900 Subject: [PATCH 23/40] fix(clipboard): paste macOS URLs copied without standard text (#36929) --- src/main/window/clipboard-ipc-handlers.ts | 3 +- .../window/clipboard-plain-text-read.test.ts | 71 +++++++++++++++++++ src/main/window/clipboard-plain-text-read.ts | 45 ++++++++++++ 3 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 src/main/window/clipboard-plain-text-read.test.ts create mode 100644 src/main/window/clipboard-plain-text-read.ts diff --git a/src/main/window/clipboard-ipc-handlers.ts b/src/main/window/clipboard-ipc-handlers.ts index 305568c8828..4ab7419c76c 100644 --- a/src/main/window/clipboard-ipc-handlers.ts +++ b/src/main/window/clipboard-ipc-handlers.ts @@ -41,6 +41,7 @@ import { uploadPasteToAgentSessionAttachments } from '../ipc/agent-session-attac import { readWindowsClipboardImageFileAsPng } from './clipboard-windows-image-file' import { readClipboardImageSource } from './clipboard-image-source' import { readClipboardCopiedFilePaths } from './clipboard-copied-file-paths' +import { readClipboardPlainText } from './clipboard-plain-text-read' import { buildClipboardImageThumbnail } from './clipboard-image-thumbnail' import { readClipboardNativeImage } from './clipboard-native-image' import { encodeClipboardNativeImagePng } from './clipboard-image-png-encode' @@ -125,7 +126,7 @@ export function registerClipboardHandlers( ipcMain.handle('clipboard:readText', async (event, options?: ReadClipboardTextOptions) => { assertTrustedClipboardTextSender(event) - return assertClipboardTextWithinLimitWithYield(clipboard.readText(), options) + return assertClipboardTextWithinLimitWithYield(readClipboardPlainText(clipboard), options) }) // Rich-text copies keep their links only in the HTML flavor; skip shipping HTML that has none. ipcMain.handle('clipboard:readLinkHtml', (event): string => { diff --git a/src/main/window/clipboard-plain-text-read.test.ts b/src/main/window/clipboard-plain-text-read.test.ts new file mode 100644 index 00000000000..430b960d48b --- /dev/null +++ b/src/main/window/clipboard-plain-text-read.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it, vi } from 'vitest' +import { readClipboardPlainText } from './clipboard-plain-text-read' + +const URL_TEXT = 'https://example.com/한글' + +function clipboardWith({ + text = '', + formats = [], + buffers = {} +}: { + text?: string + formats?: string[] + buffers?: Record +}) { + return { + readText: vi.fn(() => text), + availableFormats: vi.fn(() => formats), + readBuffer: vi.fn((format: string) => buffers[format] ?? Buffer.alloc(0)), + has: vi.fn(() => false) + } +} + +describe('readClipboardPlainText', () => { + it('prefers standard text without inspecting other pasteboard types', () => { + const clipboard = clipboardWith({ + text: 'standard', + buffers: { 'public.plain-text': Buffer.from('other') } + }) + expect(readClipboardPlainText(clipboard, 'darwin')).toBe('standard') + expect(clipboard.readBuffer).not.toHaveBeenCalled() + }) + + it.each([ + ['public.plain-text', { 'public.plain-text': Buffer.from(URL_TEXT) }], + ['public.url', { 'public.url': Buffer.from(URL_TEXT) }] + ])('reads a Universal Clipboard URL from %s on macOS', (_type, buffers) => { + expect(readClipboardPlainText(clipboardWith({ buffers }), 'darwin')).toBe(URL_TEXT) + }) + + it('skips an undecodable plain-text type and uses the URL', () => { + const buffers = { + 'public.plain-text': Buffer.from(URL_TEXT, 'utf16le'), + 'public.url': Buffer.from(URL_TEXT) + } + expect(readClipboardPlainText(clipboardWith({ buffers }), 'darwin')).toBe(URL_TEXT) + }) + + it('keeps a copied image out of the text path when it carries a source URL', () => { + const clipboard = clipboardWith({ + formats: ['image/png'], + buffers: { 'public.url': Buffer.from(URL_TEXT) } + }) + expect(readClipboardPlainText(clipboard, 'darwin')).toBe('') + }) + + it('keeps a copied file out of the text path', () => { + const clipboard = clipboardWith({ + buffers: { + 'public.file-url': Buffer.from('file:///tmp/a.txt'), + 'public.url': Buffer.from('file:///tmp/a.txt') + } + }) + expect(readClipboardPlainText(clipboard, 'darwin')).toBe('') + }) + + it.each(['linux', 'win32'] as const)('does not read macOS pasteboard types on %s', (platform) => { + const clipboard = clipboardWith({ buffers: { 'public.url': Buffer.from(URL_TEXT) } }) + expect(readClipboardPlainText(clipboard, platform)).toBe('') + expect(clipboard.readBuffer).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/window/clipboard-plain-text-read.ts b/src/main/window/clipboard-plain-text-read.ts new file mode 100644 index 00000000000..70d3a0a5493 --- /dev/null +++ b/src/main/window/clipboard-plain-text-read.ts @@ -0,0 +1,45 @@ +import { readClipboardCopiedFilePaths } from './clipboard-copied-file-paths' +import { readClipboardImageSource } from './clipboard-image-source' + +type ClipboardTextReader = { + readText: () => string + availableFormats: () => string[] + readBuffer: (format: string) => Buffer + has: (format: string) => boolean +} + +// Universal Clipboard URLs can omit public.utf8-plain-text, the only type readText() sees on macOS. +const MAC_TEXT_FALLBACK_TYPES = ['public.plain-text', 'public.url'] as const + +function decodeUtf8Text(buffer: Buffer): string { + try { + const text = new TextDecoder('utf-8', { fatal: true }).decode(buffer) + return text.includes('\0') ? '' : text + } catch { + return '' + } +} + +export function readClipboardPlainText( + clipboard: ClipboardTextReader, + platform: NodeJS.Platform = process.platform +): string { + const text = clipboard.readText() + if (text || platform !== 'darwin') { + return text + } + // A copied image or file can carry a source URL; paste must keep treating it as an image or file. + if ( + readClipboardImageSource(clipboard, platform) || + readClipboardCopiedFilePaths(clipboard, platform).length > 0 + ) { + return '' + } + for (const type of MAC_TEXT_FALLBACK_TYPES) { + const fallback = decodeUtf8Text(clipboard.readBuffer(type)) + if (fallback) { + return fallback + } + } + return '' +} From 33a3cd3b1f2039adf36a65c97271e608b5b7619a Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:03:10 -0800 Subject: [PATCH 24/40] refactor(cloud): organize push service by concrete owners (#41261) * refactor(push): organize provider, delivery, and host authentication owners * style(push): brace moved fixture guards and cleanup --- .../push/src/apns-session-replacement.test.ts | 45 ------- cloud/apps/push/src/config.ts | 2 +- .../src/{ => database}/durable-push-schema.ts | 0 .../push-background-database.ts | 2 +- .../push/src/{ => database}/push-database.ts | 10 +- .../push/src/{ => database}/push-schema.ts | 0 .../{ => delivery}/durable-push-claim.test.ts | 81 ++----------- .../durable-push-retention.test.ts | 21 ---- .../durable-push-store.test-fixture.ts | 5 +- .../{ => delivery}/durable-push-store.test.ts | 4 +- .../src/{ => delivery}/durable-push-store.ts | 10 +- .../durable-push-worker.test.ts | 95 +-------------- .../src/{ => delivery}/durable-push-worker.ts | 0 .../{ => delivery}/push-delivery-message.ts | 2 +- .../{ => delivery}/push-delivery-payload.ts | 2 +- .../src/{ => delivery}/push-dispatcher.ts | 10 +- .../{ => delivery}/push-queued-dismissal.ts | 4 +- .../{ => delivery}/push-worker-concurrency.ts | 0 .../device-registration-delete-race.test.ts | 92 --------------- .../device-registry-store.test.ts | 27 +---- .../{ => devices}/device-registry-store.ts | 17 +-- .../durable-push-claim-mixed-revision.test.ts | 103 ---------------- .../src/{ => host-auth}/canonical-base64.ts | 0 .../host-challenge-answering.test-fixture.ts | 30 +++-- .../host-challenge-store.test.ts | 17 +-- .../{ => host-auth}/host-challenge-store.ts | 8 +- .../src/{ => host-auth}/host-fingerprint.ts | 2 +- .../host-proof-concurrency.test.ts | 2 +- .../host-session-store.test.ts | 19 +-- .../src/{ => host-auth}/host-session-store.ts | 4 +- .../push-session-concurrency.test.ts | 25 +--- .../{ => http}/client-ip-rate-limit.test.ts | 14 +-- .../src/{ => http}/client-ip-rate-limit.ts | 2 +- .../src/{ => http}/push-auth-admission.ts | 0 .../push-authenticated-ip-limit.test.ts | 4 +- .../push/src/{ => http}/push-readiness.ts | 2 +- .../push/src/{ => http}/push-request-drain.ts | 0 .../{ => http}/push-send-idempotency.test.ts | 30 +---- .../src/{ => http}/push-server-auth.test.ts | 8 +- .../push-server-harness.test-fixture.ts | 14 ++- .../src/{ => http}/push-server-limits.test.ts | 56 +-------- .../src/{ => http}/push-server-send.test.ts | 6 +- .../push/src/http/push-server-wake.test.ts | 46 ++++++++ cloud/apps/push/src/index.ts | 2 +- .../apns}/apns-authentication-token.ts | 2 +- .../{ => providers/apns}/apns-client.test.ts | 37 +----- .../src/{ => providers/apns}/apns-client.ts | 8 +- .../apns}/apns-http2-transport.ts | 1 - .../apns}/apns-stream-response.test.ts | 10 -- .../apns}/apns-stream-response.ts | 2 +- .../apns}/apns-topic-recovery.test.ts | 4 +- .../{ => providers/fcm}/fcm-access-token.ts | 0 .../{ => providers/fcm}/fcm-client.test.ts | 38 +----- .../src/{ => providers/fcm}/fcm-client.ts | 8 +- .../{ => providers}/provider-retry-delay.ts | 0 .../{ => providers}/push-provider-outcome.ts | 0 cloud/apps/push/src/push-background.ts | 9 +- .../push-database-postgres-startup.test.ts | 101 ---------------- .../push/src/push-delivery-lifecycle.test.ts | 15 +-- .../push/src/push-dismissal-provider.test.ts | 31 ----- .../push/src/push-notification-sound.test.ts | 33 ------ .../push/src/push-schema-boot-lock.test.ts | 56 --------- cloud/apps/push/src/push-server-wake.test.ts | 111 ------------------ cloud/apps/push/src/push-server.ts | 54 +++++---- cloud/apps/push/src/push-validation.test.ts | 90 -------------- .../push/src/sqlite-transaction-queue.test.ts | 101 ---------------- cloud/packages/cloud-database/package.json | 12 +- cloud/packages/push-contract/package.json | 32 ++++- 68 files changed, 267 insertions(+), 1311 deletions(-) delete mode 100644 cloud/apps/push/src/apns-session-replacement.test.ts rename cloud/apps/push/src/{ => database}/durable-push-schema.ts (100%) rename cloud/apps/push/src/{ => database}/push-background-database.ts (92%) rename cloud/apps/push/src/{ => database}/push-database.ts (66%) rename cloud/apps/push/src/{ => database}/push-schema.ts (100%) rename cloud/apps/push/src/{ => delivery}/durable-push-claim.test.ts (67%) rename cloud/apps/push/src/{ => delivery}/durable-push-retention.test.ts (68%) rename cloud/apps/push/src/{ => delivery}/durable-push-store.test-fixture.ts (96%) rename cloud/apps/push/src/{ => delivery}/durable-push-store.test.ts (99%) rename cloud/apps/push/src/{ => delivery}/durable-push-store.ts (97%) rename cloud/apps/push/src/{ => delivery}/durable-push-worker.test.ts (66%) rename cloud/apps/push/src/{ => delivery}/durable-push-worker.ts (100%) rename cloud/apps/push/src/{ => delivery}/push-delivery-message.ts (96%) rename cloud/apps/push/src/{ => delivery}/push-delivery-payload.ts (95%) rename cloud/apps/push/src/{ => delivery}/push-dispatcher.ts (81%) rename cloud/apps/push/src/{ => delivery}/push-queued-dismissal.ts (96%) rename cloud/apps/push/src/{ => delivery}/push-worker-concurrency.ts (100%) delete mode 100644 cloud/apps/push/src/device-registration-delete-race.test.ts rename cloud/apps/push/src/{ => devices}/device-registry-store.test.ts (79%) rename cloud/apps/push/src/{ => devices}/device-registry-store.ts (95%) delete mode 100644 cloud/apps/push/src/durable-push-claim-mixed-revision.test.ts rename cloud/apps/push/src/{ => host-auth}/canonical-base64.ts (100%) rename cloud/apps/push/src/{ => host-auth}/host-challenge-answering.test-fixture.ts (90%) rename cloud/apps/push/src/{ => host-auth}/host-challenge-store.test.ts (89%) rename cloud/apps/push/src/{ => host-auth}/host-challenge-store.ts (95%) rename cloud/apps/push/src/{ => host-auth}/host-fingerprint.ts (96%) rename cloud/apps/push/src/{ => host-auth}/host-proof-concurrency.test.ts (95%) rename cloud/apps/push/src/{ => host-auth}/host-session-store.test.ts (72%) rename cloud/apps/push/src/{ => host-auth}/host-session-store.ts (93%) rename cloud/apps/push/src/{ => host-auth}/push-session-concurrency.test.ts (60%) rename cloud/apps/push/src/{ => http}/client-ip-rate-limit.test.ts (97%) rename cloud/apps/push/src/{ => http}/client-ip-rate-limit.ts (97%) rename cloud/apps/push/src/{ => http}/push-auth-admission.ts (100%) rename cloud/apps/push/src/{ => http}/push-authenticated-ip-limit.test.ts (91%) rename cloud/apps/push/src/{ => http}/push-readiness.ts (90%) rename cloud/apps/push/src/{ => http}/push-request-drain.ts (100%) rename cloud/apps/push/src/{ => http}/push-send-idempotency.test.ts (56%) rename cloud/apps/push/src/{ => http}/push-server-auth.test.ts (93%) rename cloud/apps/push/src/{ => http}/push-server-harness.test-fixture.ts (89%) rename cloud/apps/push/src/{ => http}/push-server-limits.test.ts (78%) rename cloud/apps/push/src/{ => http}/push-server-send.test.ts (97%) create mode 100644 cloud/apps/push/src/http/push-server-wake.test.ts rename cloud/apps/push/src/{ => providers/apns}/apns-authentication-token.ts (96%) rename cloud/apps/push/src/{ => providers/apns}/apns-client.test.ts (64%) rename cloud/apps/push/src/{ => providers/apns}/apns-client.ts (91%) rename cloud/apps/push/src/{ => providers/apns}/apns-http2-transport.ts (98%) rename cloud/apps/push/src/{ => providers/apns}/apns-stream-response.test.ts (99%) rename cloud/apps/push/src/{ => providers/apns}/apns-stream-response.ts (96%) rename cloud/apps/push/src/{ => providers/apns}/apns-topic-recovery.test.ts (90%) rename cloud/apps/push/src/{ => providers/fcm}/fcm-access-token.ts (100%) rename cloud/apps/push/src/{ => providers/fcm}/fcm-client.test.ts (74%) rename cloud/apps/push/src/{ => providers/fcm}/fcm-client.ts (93%) rename cloud/apps/push/src/{ => providers}/provider-retry-delay.ts (100%) rename cloud/apps/push/src/{ => providers}/push-provider-outcome.ts (100%) delete mode 100644 cloud/apps/push/src/push-database-postgres-startup.test.ts delete mode 100644 cloud/apps/push/src/push-dismissal-provider.test.ts delete mode 100644 cloud/apps/push/src/push-notification-sound.test.ts delete mode 100644 cloud/apps/push/src/push-schema-boot-lock.test.ts delete mode 100644 cloud/apps/push/src/push-server-wake.test.ts delete mode 100644 cloud/apps/push/src/push-validation.test.ts delete mode 100644 cloud/apps/push/src/sqlite-transaction-queue.test.ts diff --git a/cloud/apps/push/src/apns-session-replacement.test.ts b/cloud/apps/push/src/apns-session-replacement.test.ts deleted file mode 100644 index 2678732ca94..00000000000 --- a/cloud/apps/push/src/apns-session-replacement.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { EventEmitter } from 'node:events' -import { expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ - connect: vi.fn(), - read: vi.fn(async () => ({ status: 200, body: '' })) -})) -vi.mock('node:http2', async (original) => ({ - ...(await original()), - connect: mocks.connect -})) -vi.mock('./apns-stream-response.js', () => ({ readApnsStreamResponse: mocks.read })) -import { createApnsHttp2Transport } from './apns-http2-transport.js' - -it('keeps the replacement cached when the draining session closes later', async () => { - const sessions: Array< - EventEmitter & { - closed: boolean - destroyed: boolean - request: ReturnType - close: ReturnType - } - > = [] - mocks.connect.mockImplementation(() => { - const session = Object.assign(new EventEmitter(), { - closed: false, - destroyed: false, - request: vi.fn(() => ({})), - close: vi.fn() - }) - sessions.push(session) - return session - }) - const transport = createApnsHttp2Transport() - const request = { host: 'api.push.apple.com', path: '/synthetic', headers: {}, body: '{}' } - await transport(request) - sessions[0]!.closed = true - await transport(request) - sessions[0]!.emit('close') - sessions[0]!.emit('error', new Error('old-session')) - await transport(request) - expect(sessions).toHaveLength(2) - expect(sessions[1]!.request).toHaveBeenCalledTimes(2) - transport.close() - expect(sessions[1]!.close).toHaveBeenCalledOnce() -}) diff --git a/cloud/apps/push/src/config.ts b/cloud/apps/push/src/config.ts index 2ed0d2111f1..3a885edc22c 100644 --- a/cloud/apps/push/src/config.ts +++ b/cloud/apps/push/src/config.ts @@ -1,4 +1,4 @@ -import { PUSH_DEFAULTS } from '@orca-cloud/push-contract' +import { PUSH_DEFAULTS } from '@orca-cloud/push-contract/push-limits' import { z } from 'zod' export const PUSH_DATABASE_POOL_MAX = 10 diff --git a/cloud/apps/push/src/durable-push-schema.ts b/cloud/apps/push/src/database/durable-push-schema.ts similarity index 100% rename from cloud/apps/push/src/durable-push-schema.ts rename to cloud/apps/push/src/database/durable-push-schema.ts diff --git a/cloud/apps/push/src/push-background-database.ts b/cloud/apps/push/src/database/push-background-database.ts similarity index 92% rename from cloud/apps/push/src/push-background-database.ts rename to cloud/apps/push/src/database/push-background-database.ts index 8a6b759badf..d3d26b9bf31 100644 --- a/cloud/apps/push/src/push-background-database.ts +++ b/cloud/apps/push/src/database/push-background-database.ts @@ -1,4 +1,4 @@ -import type { PushDatabase } from './push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' // Caps worker and prune traffic at poolMax - 1 connections so request-path lookups always find one. export function reserveRequestConnection(database: PushDatabase, poolMax: number): PushDatabase { diff --git a/cloud/apps/push/src/push-database.ts b/cloud/apps/push/src/database/push-database.ts similarity index 66% rename from cloud/apps/push/src/push-database.ts rename to cloud/apps/push/src/database/push-database.ts index 0684d1a3f66..fa6e375f9df 100644 --- a/cloud/apps/push/src/push-database.ts +++ b/cloud/apps/push/src/database/push-database.ts @@ -3,15 +3,17 @@ import { openInMemoryCloudDatabase, type CloudDatabase, type OpenCloudDatabaseInput -} from '@orca-cloud/cloud-database' +} from '@orca-cloud/cloud-database/cloud-database' import { pushSchemaStatements } from './push-schema.js' -export type { CloudDatabase as PushDatabase, SqlRow } from '@orca-cloud/cloud-database' - export async function openPushDatabase( input: Omit ): Promise { - return await openCloudDatabase({ ...input, service: 'push', schemaStatements: pushSchemaStatements() }) + return await openCloudDatabase({ + ...input, + service: 'push', + schemaStatements: pushSchemaStatements() + }) } export async function openInMemoryPushDatabase(): Promise { diff --git a/cloud/apps/push/src/push-schema.ts b/cloud/apps/push/src/database/push-schema.ts similarity index 100% rename from cloud/apps/push/src/push-schema.ts rename to cloud/apps/push/src/database/push-schema.ts diff --git a/cloud/apps/push/src/durable-push-claim.test.ts b/cloud/apps/push/src/delivery/durable-push-claim.test.ts similarity index 67% rename from cloud/apps/push/src/durable-push-claim.test.ts rename to cloud/apps/push/src/delivery/durable-push-claim.test.ts index 2d5e91d4000..93f65135504 100644 --- a/cloud/apps/push/src/durable-push-claim.test.ts +++ b/cloud/apps/push/src/delivery/durable-push-claim.test.ts @@ -1,73 +1,19 @@ import { afterEach, expect, it } from 'vitest' -import type { PushDatabase } from './push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' import { DELIVERY_LEASE_MS, DurablePushStore } from './durable-push-store.js' -import { reserveRequestConnection } from './push-background-database.js' -import { cleanupDurablePushFixtures, DEVICE_HEAD_SQL, durablePushTestDatabaseUrl, fixture, notification, pauseAfter, within } from './durable-push-store.test-fixture.js' +import { + cleanupDurablePushFixtures, + DEVICE_HEAD_SQL, + durablePushTestDatabaseUrl, + fixture, + notification, + pauseAfter, + within +} from './durable-push-store.test-fixture.js' afterEach(cleanupDurablePushFixtures) -it.skipIf(!durablePushTestDatabaseUrl)( - 'leaves completion, renewal, requests and another store independent of queued claims', - async () => { - const { db, store, clock, advance } = await fixture({ poolMax: 6 }) - await store.accept('host', 'finished', notification(1)) - const finished = await store.claim() - await store.accept('host', 'renewed', notification(2)) - const renewed = await store.claim() - if (!finished || !renewed) throw new Error('setup_claim_missing') - await store.accept('host', 'phone-a', notification(3)) - advance(1) - await store.accept('host', 'phone-b', notification(4)) - advance(1) - await store.accept('host', 'phone-c', notification(5)) - advance(1) - await store.accept('host', 'phone-d', notification(6)) - const background = reserveRequestConnection(db, 6) - const held = [pauseAfter(background), pauseAfter(background), pauseAfter(background)] as const - let admitted = 0 - const observed: PushDatabase = { - ...background, - transaction: (run) => (held[admitted++]?.wrapped ?? background).transaction(run) - } - const limited = new DurablePushStore(db, clock, observed) - const first = limited.claim() - await held[0].atCandidate - const second = limited.claim() - await held[1].atCandidate - const third = limited.claim() - await held[2].atCandidate - const waiting = Array.from({ length: 3 }, () => limited.claim()) - try { - advance(10) - const [, , rows, other] = await within( - Promise.all([ - limited.finish(finished), - limited.renew(renewed), - db.query('SELECT COUNT(*) AS total FROM push_devices'), - store.claim() - ]), - 2_000 - ) - expect(Number(rows[0]?.total)).toBe(0) - expect(other?.registrationId).toBe('phone-d') - const [lease] = await db.query( - 'SELECT lease_until FROM push_delivery_batches WHERE batch_id = ?', - [renewed.id] - ) - expect(Number(lease?.lease_until)).toBe(clock() + DELIVERY_LEASE_MS) - expect(await store.pendingCount('finished')).toBe(0) - } finally { - for (const pause of held) pause.release() - await Promise.allSettled([first, second, third, ...waiting]) - } - expect((await first)?.registrationId).toBe('phone-a') - expect((await second)?.registrationId).toBe('phone-b') - expect((await third)?.registrationId).toBe('phone-c') - expect(await Promise.all(waiting)).toEqual([null, null, null]) - } -) - it.skipIf(!durablePushTestDatabaseUrl)( 'rolls back a failed claim and admits a fourth waiter while the other claims stay held', async () => { @@ -117,8 +63,6 @@ it.skipIf(!durablePushTestDatabaseUrl)( } ) - - it('leases exactly one delivery per device across concurrent claimers', async () => { const { db, store, clock, advance } = await fixture() for (let seq = 1; seq <= 5; seq++) { @@ -197,11 +141,6 @@ it.skipIf(!durablePushTestDatabaseUrl)( // Only the TTL term keeps the candidate scan off an unpruned backlog; expires_at is not indexed first. - - - - - it('frees a device held by a crashed worker once its lease lapses', async () => { const { db, store, clock, advance } = await fixture() await store.accept('host', 'phone', notification(1)) diff --git a/cloud/apps/push/src/durable-push-retention.test.ts b/cloud/apps/push/src/delivery/durable-push-retention.test.ts similarity index 68% rename from cloud/apps/push/src/durable-push-retention.test.ts rename to cloud/apps/push/src/delivery/durable-push-retention.test.ts index 72dcc225b79..4304bcce3f4 100644 --- a/cloud/apps/push/src/durable-push-retention.test.ts +++ b/cloud/apps/push/src/delivery/durable-push-retention.test.ts @@ -5,7 +5,6 @@ import { fixture, within } from './durable-push-store.test-fixture.js' -import { PRUNE_BATCH_ROWS } from './durable-push-store.js' afterEach(cleanupDurablePushFixtures) @@ -27,26 +26,6 @@ const retentionTables = [ } ] as const -it.each(retentionTables)( - 'prunes expired $table rows across batches and preserves the cutoff', - async ({ table, columns, values }) => { - const { db, store, clock } = await fixture() - const cutoff = clock() - 24 * 60 * 60_000 - const expired = PRUNE_BATCH_ROWS + 3 - await db.query( - `INSERT INTO ${table} (${columns}) - WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < ?), - rows AS (SELECT n, CASE WHEN n <= ? THEN ? ELSE ? + n - ? - 1 END AS created_at FROM seq) - SELECT ${values} FROM rows`, - [expired + 2, expired, cutoff - 1, cutoff, expired] - ) - expect(await store.prune()).toEqual({ deleted: expired, saturated: false }) - const preserved = await db.query(`SELECT created_at FROM ${table} ORDER BY created_at`) - expect(preserved.map((row) => Number(row.created_at))).toEqual([cutoff, cutoff + 1]) - expect(await store.prune()).toEqual({ deleted: 0, saturated: false }) - } -) - it.skipIf(!durablePushTestDatabaseUrl).each(retentionTables)( 'skips a locked oldest $table row until its transaction releases it', async ({ table, columns, values }) => { diff --git a/cloud/apps/push/src/durable-push-store.test-fixture.ts b/cloud/apps/push/src/delivery/durable-push-store.test-fixture.ts similarity index 96% rename from cloud/apps/push/src/durable-push-store.test-fixture.ts rename to cloud/apps/push/src/delivery/durable-push-store.test-fixture.ts index 67ef6999db1..c9aa565db9b 100644 --- a/cloud/apps/push/src/durable-push-store.test-fixture.ts +++ b/cloud/apps/push/src/delivery/durable-push-store.test-fixture.ts @@ -1,7 +1,8 @@ import { randomUUID } from 'node:crypto' import pg from 'pg' -import type { PushNotification } from '@orca-cloud/push-contract' -import { openInMemoryPushDatabase, openPushDatabase, type PushDatabase } from './push-database.js' +import type { PushNotification } from '@orca-cloud/push-contract/send-messages' +import { openInMemoryPushDatabase, openPushDatabase } from '../database/push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' import { DurablePushStore } from './durable-push-store.js' export const durablePushTestDatabaseUrl = diff --git a/cloud/apps/push/src/durable-push-store.test.ts b/cloud/apps/push/src/delivery/durable-push-store.test.ts similarity index 99% rename from cloud/apps/push/src/durable-push-store.test.ts rename to cloud/apps/push/src/delivery/durable-push-store.test.ts index d8387793d45..9be0e32ec8f 100644 --- a/cloud/apps/push/src/durable-push-store.test.ts +++ b/cloud/apps/push/src/delivery/durable-push-store.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it } from 'vitest' -import { openPushDatabase } from './push-database.js' +import { openPushDatabase } from '../database/push-database.js' import { DurablePushStore, DELIVERY_LEASE_MS } from './durable-push-store.js' import { cleanupDurablePushFixtures, @@ -89,8 +89,6 @@ describe('durable push acceptance', () => { await store.finish(fresh!) }) - - it('rolls quota and payload back together if persistence fails', async () => { const { db, store } = await fixture() await db.query('ALTER TABLE push_delivery_batches RENAME TO push_delivery_batches_unavailable') diff --git a/cloud/apps/push/src/durable-push-store.ts b/cloud/apps/push/src/delivery/durable-push-store.ts similarity index 97% rename from cloud/apps/push/src/durable-push-store.ts rename to cloud/apps/push/src/delivery/durable-push-store.ts index 1bcdda0bdc7..9d9151e584a 100644 --- a/cloud/apps/push/src/durable-push-store.ts +++ b/cloud/apps/push/src/delivery/durable-push-store.ts @@ -1,10 +1,14 @@ import { isDismissedAlert, reconcileQueuedDismissal } from './push-queued-dismissal.js' import { parsePushDeliveryPayload } from './push-delivery-payload.js' import { createHash, randomUUID } from 'node:crypto' -import { PUSH_LIMITS, type PushNotification } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' +import type { PushNotification } from '@orca-cloud/push-contract/send-messages' import { WORKER_DRAINS } from './push-worker-concurrency.js' -import type { PushDatabase, SqlRow } from './push-database.js' -import { limitPushDatabaseConcurrency } from './push-background-database.js' +import type { + CloudDatabase as PushDatabase, + SqlRow +} from '@orca-cloud/cloud-database/cloud-database' +import { limitPushDatabaseConcurrency } from '../database/push-background-database.js' const RETENTION_MS = 24 * 60 * 60_000 // accept() caps expires_at at due_at + TTL, so older due_at is expired: scans skip an unpruned backlog. diff --git a/cloud/apps/push/src/durable-push-worker.test.ts b/cloud/apps/push/src/delivery/durable-push-worker.test.ts similarity index 66% rename from cloud/apps/push/src/durable-push-worker.test.ts rename to cloud/apps/push/src/delivery/durable-push-worker.test.ts index 5eb84f35110..78303de18e6 100644 --- a/cloud/apps/push/src/durable-push-worker.test.ts +++ b/cloud/apps/push/src/delivery/durable-push-worker.test.ts @@ -1,13 +1,12 @@ - import { afterEach, expect, it, vi } from 'vitest' -import type { PushNotification } from '@orca-cloud/push-contract' +import type { PushNotification } from '@orca-cloud/push-contract/send-messages' import { DurablePushStore } from './durable-push-store.js' import { DurablePushWorker } from './durable-push-worker.js' import { PushDispatcher } from './push-dispatcher.js' -import { PushDeviceRegistryStore } from './device-registry-store.js' -import { openInMemoryPushDatabase } from './push-database.js' +import { PushDeviceRegistryStore } from '../devices/device-registry-store.js' +import { openInMemoryPushDatabase } from '../database/push-database.js' import type { PushDelivery } from './push-delivery-message.js' -import type { PushProviderOutcome } from './push-provider-outcome.js' +import type { PushProviderOutcome } from '../providers/push-provider-outcome.js' import { pauseAfter, within } from './durable-push-store.test-fixture.js' @@ -69,52 +68,6 @@ async function fixture() { } } -it('preserves provider retry delay when waking a restarted worker', async () => { - const h = await fixture() - vi.useFakeTimers() - h.send.mockResolvedValueOnce({ - status: 'error', - reason: 'busy', - retryable: true, - retryAfterMs: 10000 - }) - await h.accept(note(1)) - await h.worker.runDue() - expect(h.send).toHaveBeenCalledOnce() - await h.worker.stop() - const restarted = new DurablePushWorker(h.store, h.dispatcher, { now: h.now, onRetry: h.onRetry }) - restarted.start() - h.advance(9999) - restarted.wake() - await restarted.runDue() - expect(h.send).toHaveBeenCalledOnce() - h.advance(1) - restarted.wake() - await restarted.runDue() - expect(h.send).toHaveBeenCalledTimes(2) - expect(h.send.mock.calls.map(([delivery]) => delivery.expiresAt)).toEqual([1_300_000, 1_300_000]) - expect(h.onRetry).toHaveBeenCalledOnce() - expect(await h.store.pendingCount(h.registrationId)).toBe(0) - await restarted.stop() -}) - -it('expires instead of shortening a provider delay beyond the delivery lifetime', async () => { - const h = await fixture() - h.send.mockResolvedValue({ - status: 'error', - reason: 'busy', - retryable: true, - retryAfterMs: 600000 - }) - await h.accept(note(1)) - await h.worker.runDue() - h.advance(600000) - await h.worker.runDue() - expect(h.send).toHaveBeenCalledOnce() - expect(await h.store.pendingCount(h.registrationId)).toBe(0) - expect(h.onRetry).not.toHaveBeenCalled() -}) - it('rechecks the device before a persisted retry and does not send after unregistration', async () => { const h = await fixture() h.send.mockResolvedValue({ status: 'error', reason: 'timeout', retryable: true }) @@ -127,46 +80,6 @@ it('rechecks the device before a persisted retry and does not send after unregis expect(await h.store.pendingCount(h.registrationId)).toBe(0) }) -it('joins active work on shutdown and leaves unclaimed work for the next instance', async () => { - const h = await fixture() - vi.useFakeTimers() - let finish!: (outcome: PushProviderOutcome) => void - let started!: () => void - const entered = new Promise((resolve) => { - started = resolve - }) - h.send.mockImplementationOnce(() => { - started() - return new Promise((resolve) => { - finish = resolve - }) - }) - await h.accept(note(1)) - h.worker.start() - h.worker.wake() - const pending = h.worker.runDue() - await entered - await h.accept(note(2)) - h.worker.wake() - let stopped = false - const stopping = h.worker.stop().then(() => { - stopped = true - }) - await Promise.resolve() - expect(stopped).toBe(false) - finish({ status: 'sent' }) - await Promise.all([pending, stopping]) - expect(stopped).toBe(true) - expect(h.send).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - const resumed = new DurablePushWorker(h.store, h.dispatcher, { now: h.now }) - resumed.start() - await vi.advanceTimersByTimeAsync(1000) - await resumed.runDue() - expect(h.send).toHaveBeenCalledTimes(2) - await resumed.stop() -}) - it('stops queued claim admissions without leasing the remaining device', async () => { const h = await fixture() const other = await h.devices.upsert({ diff --git a/cloud/apps/push/src/durable-push-worker.ts b/cloud/apps/push/src/delivery/durable-push-worker.ts similarity index 100% rename from cloud/apps/push/src/durable-push-worker.ts rename to cloud/apps/push/src/delivery/durable-push-worker.ts diff --git a/cloud/apps/push/src/push-delivery-message.ts b/cloud/apps/push/src/delivery/push-delivery-message.ts similarity index 96% rename from cloud/apps/push/src/push-delivery-message.ts rename to cloud/apps/push/src/delivery/push-delivery-message.ts index 1d37f621573..200d4c78908 100644 --- a/cloud/apps/push/src/push-delivery-message.ts +++ b/cloud/apps/push/src/delivery/push-delivery-message.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { type PushNotification } from '@orca-cloud/push-contract' +import type { PushNotification } from '@orca-cloud/push-contract/send-messages' export type PushOrcaData = { kind?: 'alert' | 'dismiss' diff --git a/cloud/apps/push/src/push-delivery-payload.ts b/cloud/apps/push/src/delivery/push-delivery-payload.ts similarity index 95% rename from cloud/apps/push/src/push-delivery-payload.ts rename to cloud/apps/push/src/delivery/push-delivery-payload.ts index 825286125b7..3ce1541facf 100644 --- a/cloud/apps/push/src/push-delivery-payload.ts +++ b/cloud/apps/push/src/delivery/push-delivery-payload.ts @@ -1,4 +1,4 @@ -import type { PushNotification } from '@orca-cloud/push-contract' +import type { PushNotification } from '@orca-cloud/push-contract/send-messages' export function parsePushDeliveryPayload(payload: string): PushNotification { const value: unknown = JSON.parse(payload) diff --git a/cloud/apps/push/src/push-dispatcher.ts b/cloud/apps/push/src/delivery/push-dispatcher.ts similarity index 81% rename from cloud/apps/push/src/push-dispatcher.ts rename to cloud/apps/push/src/delivery/push-dispatcher.ts index ca9006bc435..68ae5ae5b1d 100644 --- a/cloud/apps/push/src/push-dispatcher.ts +++ b/cloud/apps/push/src/delivery/push-dispatcher.ts @@ -1,9 +1,9 @@ -import type { ApnsClient } from './apns-client.js' -import type { PushDeviceRegistryStore } from './device-registry-store.js' -import type { FcmClient } from './fcm-client.js' -import { fingerprintLogPrefix } from './host-fingerprint.js' +import type { ApnsClient } from '../providers/apns/apns-client.js' +import type { PushDeviceRegistryStore } from '../devices/device-registry-store.js' +import type { FcmClient } from '../providers/fcm/fcm-client.js' +import { fingerprintLogPrefix } from '../host-auth/host-fingerprint.js' import type { PushDelivery } from './push-delivery-message.js' -import type { PushProviderOutcome } from './push-provider-outcome.js' +import type { PushProviderOutcome } from '../providers/push-provider-outcome.js' export type PushDispatcherOptions = { devices: PushDeviceRegistryStore diff --git a/cloud/apps/push/src/push-queued-dismissal.ts b/cloud/apps/push/src/delivery/push-queued-dismissal.ts similarity index 96% rename from cloud/apps/push/src/push-queued-dismissal.ts rename to cloud/apps/push/src/delivery/push-queued-dismissal.ts index e1b48bcac53..6056974b0e4 100644 --- a/cloud/apps/push/src/push-queued-dismissal.ts +++ b/cloud/apps/push/src/delivery/push-queued-dismissal.ts @@ -1,5 +1,5 @@ -import type { PushNotification } from '@orca-cloud/push-contract' -import type { PushDatabase } from './push-database.js' +import type { PushNotification } from '@orca-cloud/push-contract/send-messages' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' import { parsePushDeliveryPayload } from './push-delivery-payload.js' export async function reconcileQueuedDismissal( diff --git a/cloud/apps/push/src/push-worker-concurrency.ts b/cloud/apps/push/src/delivery/push-worker-concurrency.ts similarity index 100% rename from cloud/apps/push/src/push-worker-concurrency.ts rename to cloud/apps/push/src/delivery/push-worker-concurrency.ts diff --git a/cloud/apps/push/src/device-registration-delete-race.test.ts b/cloud/apps/push/src/device-registration-delete-race.test.ts deleted file mode 100644 index 2e2bdbdc7fa..00000000000 --- a/cloud/apps/push/src/device-registration-delete-race.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { openPushDatabase, type PushDatabase } from './push-database.js' -import { PushDeviceRegistryStore } from './device-registry-store.js' - -const databaseUrl = process.env.ORCA_PUSH_TEST_DATABASE_URL -it.skipIf(!databaseUrl)( - 'serializes deletion with a registration that has already read its row', - async () => { - if (!process.env.CI && new URL(databaseUrl!).port !== '55440') - throw new Error('isolated_postgres_port_required') - const database = await openPushDatabase({ - databaseUrl, - dataDir: '', - poolMax: 4, - applicationName: 'push-delete-race' - }) - let release!: () => void - const paused = new Promise((resolve) => { - release = resolve - }) - let read = false - let pause = false - const wrapped: PushDatabase = { - dialect: database.dialect, - query: database.query.bind(database), - close: database.close.bind(database), - lockQuotaScope: database.lockQuotaScope.bind(database), - tryLockScope: database.tryLockScope.bind(database), - tryLockSharedScope: database.tryLockSharedScope.bind(database), - transaction: (run) => - database.transaction((tx) => - run({ - dialect: tx.dialect, - close: tx.close.bind(tx), - transaction: tx.transaction.bind(tx), - lockQuotaScope: tx.lockQuotaScope.bind(tx), - tryLockScope: tx.tryLockScope.bind(tx), - tryLockSharedScope: tx.tryLockSharedScope.bind(tx), - query: async (sql, params) => { - const rows = await tx.query(sql, params) - if (pause && sql.startsWith('SELECT registration_id FROM push_devices')) { - read = true - await paused - } - return rows - } - }) - ) - } - const devices = new PushDeviceRegistryStore(wrapped) - const input = { - hostFingerprint: 'delete-race-host', - deviceId: 'phone', - platform: 'android' as const, - token: 'synthetic' - } - let registration: Promise | undefined - let deletion: Promise | undefined - try { - await database.query('DELETE FROM push_devices WHERE host_fingerprint = ?', [ - input.hostFingerprint - ]) - const first = await devices.upsert(input) - if (!first.ok) throw new Error('registration refused') - pause = true - registration = devices.upsert(input) - await vi.waitFor(() => expect(read).toBe(true)) - let deleted = false - deletion = devices.deleteOwned(input.hostFingerprint, first.registrationId).then((value) => { - deleted = true - return value - }) - await vi.waitFor(async () => { - const rows = await database.query( - "SELECT 1 FROM pg_stat_activity WHERE application_name = 'push-delete-race' AND wait_event_type = 'Lock'" - ) - expect(deleted || rows.length > 0).toBe(true) - }) - expect(deleted).toBe(false) - release() - expect(await registration).toEqual(first) - expect(await deletion).toBe(true) - } finally { - release() - await Promise.allSettled([registration, deletion]) - await database.query('DELETE FROM push_devices WHERE host_fingerprint = ?', [ - input.hostFingerprint - ]) - await database.close() - } - } -) diff --git a/cloud/apps/push/src/device-registry-store.test.ts b/cloud/apps/push/src/devices/device-registry-store.test.ts similarity index 79% rename from cloud/apps/push/src/device-registry-store.test.ts rename to cloud/apps/push/src/devices/device-registry-store.test.ts index 97f3e47acc5..7639ed974b9 100644 --- a/cloud/apps/push/src/device-registry-store.test.ts +++ b/cloud/apps/push/src/devices/device-registry-store.test.ts @@ -1,7 +1,8 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { PushDeviceRegistryStore, type PushDeviceUpsert } from './device-registry-store.js' -import { openInMemoryPushDatabase, type PushDatabase } from './push-database.js' +import { openInMemoryPushDatabase } from '../database/push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' const OWNER = 'abcdefghijklmnop' const OTHER = 'ponmlkjihgfedcba' @@ -117,28 +118,6 @@ describe('push device registry store', () => { expect(await devices.findOwned(OWNER, [])).toEqual(new Map()) }) - it('refuses a new device once the host reaches its registration cap', async () => { - for (let index = 0; index < PUSH_LIMITS.maxDevicesPerHost; index++) { - await upsertOk(androidDevice(`device-${index}`)) - } - expect(await devices.upsert(androidDevice('one-too-many'))).toEqual({ - ok: false, - reason: 'too_many_devices' - }) - expect(await devices.list(OWNER)).toHaveLength(PUSH_LIMITS.maxDevicesPerHost) - }) - - it('still lets a capped host re-register a device it already owns', async () => { - for (let index = 0; index < PUSH_LIMITS.maxDevicesPerHost; index++) { - await upsertOk(androidDevice(`device-${index}`)) - } - const rotated = await devices.upsert({ ...androidDevice('device-0'), token: 'rotated-token' }) - expect(rotated.ok).toBe(true) - expect(await devices.list(OWNER)).toHaveLength(PUSH_LIMITS.maxDevicesPerHost) - }) - - - it('counts the cap per host, not across the whole table', async () => { for (let index = 0; index < PUSH_LIMITS.maxDevicesPerHost; index++) { await upsertOk(androidDevice(`device-${index}`)) diff --git a/cloud/apps/push/src/device-registry-store.ts b/cloud/apps/push/src/devices/device-registry-store.ts similarity index 95% rename from cloud/apps/push/src/device-registry-store.ts rename to cloud/apps/push/src/devices/device-registry-store.ts index a4061189e35..1db88954d62 100644 --- a/cloud/apps/push/src/device-registry-store.ts +++ b/cloud/apps/push/src/devices/device-registry-store.ts @@ -1,11 +1,14 @@ import { randomUUID } from 'node:crypto' -import { - PUSH_LIMITS, - type ApnsEnvironment, - type PushDeviceSummary, - type PushPlatform -} from '@orca-cloud/push-contract' -import type { PushDatabase, SqlRow } from './push-database.js' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' +import type { + ApnsEnvironment, + PushDeviceSummary, + PushPlatform +} from '@orca-cloud/push-contract/device-registration-messages' +import type { + CloudDatabase as PushDatabase, + SqlRow +} from '@orca-cloud/cloud-database/cloud-database' const DEVICE_CAP_LOCK_PREFIX = 'orca-push-device-cap:' diff --git a/cloud/apps/push/src/durable-push-claim-mixed-revision.test.ts b/cloud/apps/push/src/durable-push-claim-mixed-revision.test.ts deleted file mode 100644 index 869160c3591..00000000000 --- a/cloud/apps/push/src/durable-push-claim-mixed-revision.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import type { PushDatabase } from './push-database.js' -import { DELIVERY_LEASE_MS, DurablePushStore } from './durable-push-store.js' -import { - cleanupDurablePushFixtures, - durablePushTestDatabaseUrl, - fixture, - notification, - pauseAfter, - within -} from './durable-push-store.test-fixture.js' - -afterEach(cleanupDurablePushFixtures) - -const LEASE_SQL = 'UPDATE push_delivery_batches SET lease_token' - -// The previous revision's claim statements, in order, with a hook between its candidate scan and re-read. -function previousRevisionClaim( - db: PushDatabase, - clock: () => number, - afterCandidate: () => Promise -): Promise { - return db.transaction(async (tx) => { - await tx.lockQuotaScope('push-worker-claim') - const now = clock() - const [candidate] = await tx.query( - `SELECT * FROM push_delivery_batches WHERE state = 'pending' AND lease_until <= ? AND expires_at > ? AND due_at <= ? AND NOT EXISTS (SELECT 1 FROM push_delivery_batches busy WHERE busy.registration_id = push_delivery_batches.registration_id AND busy.lease_until > ?) - ORDER BY due_at, created_at, batch_id LIMIT 1`, - [now, now, now, now] - ) - await afterCandidate() - if (!candidate) return null - await tx.lockQuotaScope(`push-events:${String(candidate.host_fingerprint)}`) - const [row] = await tx.query('SELECT * FROM push_delivery_batches WHERE batch_id = ?', [ - candidate.batch_id - ]) - if (!row || row.state !== 'pending' || Number(row.expires_at) <= now) return null - await tx.query( - 'UPDATE push_delivery_batches SET lease_token = ?, lease_until = ?, attempts = attempts + 1 WHERE batch_id = ?', - ['previous', now + DELIVERY_LEASE_MS, row.batch_id] - ) - return 'previous' - }) -} - -it.skipIf(!durablePushTestDatabaseUrl)( - 'keeps a previous-revision claim from re-leasing a delivery this revision leased', - async () => { - const { db, store, clock } = await fixture({ ownDatabase: true }) - await store.accept('host', 'phone', notification(1)) - const paused = pauseAfter(db, LEASE_SQL) - const current = new DurablePushStore(paused.wrapped, clock).claim() - await paused.atCandidate - let committed!: () => void - const currentCommitted = new Promise((resolve) => (committed = resolve)) - const previous = previousRevisionClaim(db, clock, () => currentCommitted) - try { - await vi.waitFor(async () => { - const waiting = await db.query( - "SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock' AND wait_event = 'advisory'" - ) - expect(waiting).toHaveLength(1) - }) - } finally { - paused.release() - try { - await current - } finally { - committed() - await previous - } - } - const leased = await current - expect(await previous).toBeNull() - const [row] = await db.query('SELECT lease_token FROM push_delivery_batches') - expect(leased?.lease).toBeTruthy() - expect(row?.lease_token).toBe(leased?.lease) - } -) - -it.skipIf(!durablePushTestDatabaseUrl)( - 'yields to a previous-revision claim that already holds the claim lock', - async () => { - const { db, store, clock } = await fixture({ ownDatabase: true }) - await store.accept('host', 'phone', notification(1)) - let scanned!: () => void - const atCandidate = new Promise((resolve) => (scanned = resolve)) - let release!: () => void - const released = new Promise((resolve) => (release = resolve)) - const previous = previousRevisionClaim(db, clock, async () => { - scanned() - await released - }) - await atCandidate - try { - expect(await within(store.claim(), 2_000)).toBeNull() - } finally { - release() - } - expect(await previous).toBe('previous') - expect(await store.claim()).toBeNull() - } -) diff --git a/cloud/apps/push/src/canonical-base64.ts b/cloud/apps/push/src/host-auth/canonical-base64.ts similarity index 100% rename from cloud/apps/push/src/canonical-base64.ts rename to cloud/apps/push/src/host-auth/canonical-base64.ts diff --git a/cloud/apps/push/src/host-challenge-answering.test-fixture.ts b/cloud/apps/push/src/host-auth/host-challenge-answering.test-fixture.ts similarity index 90% rename from cloud/apps/push/src/host-challenge-answering.test-fixture.ts rename to cloud/apps/push/src/host-auth/host-challenge-answering.test-fixture.ts index ac5320cd1ab..b9d5eba99d5 100644 --- a/cloud/apps/push/src/host-challenge-answering.test-fixture.ts +++ b/cloud/apps/push/src/host-auth/host-challenge-answering.test-fixture.ts @@ -2,9 +2,9 @@ import { createHmac, timingSafeEqual } from 'node:crypto' import { PUSH_HOST_CHALLENGE_PLAINTEXT_DOMAIN, PUSH_HOST_PROOF_TRANSCRIPT_DOMAIN, - PUSH_HOST_PROOF_TRANSCRIPT_FIELD_COUNT, - PUSH_LIMITS -} from '@orca-cloud/push-contract' + PUSH_HOST_PROOF_TRANSCRIPT_FIELD_COUNT +} from '@orca-cloud/push-contract/push-host-proof-transcript' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import nacl from 'tweetnacl' import { decodeCanonicalBase64 } from './canonical-base64.js' import { deriveHostFingerprint } from './host-fingerprint.js' @@ -63,7 +63,10 @@ function parseTranscript(transcript: Uint8Array): Map | null function readUint64(value: Uint8Array | undefined): number | null { if (!value || value.byteLength !== 8) return null - const parsed = new DataView(value.buffer, value.byteOffset, value.byteLength).getBigUint64(0, false) + const parsed = new DataView(value.buffer, value.byteOffset, value.byteLength).getBigUint64( + 0, + false + ) return parsed <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(parsed) : null } @@ -98,14 +101,17 @@ function validateTranscript( ], ['not-expired', now - PUSH_LIMITS.clockSkewToleranceMs <= challenge.expiresAt], ['issuedAt-before-expiry', issuedAt === null || issuedAt <= challenge.expiresAt], - [ - 'window', - issuedAt === null || challenge.expiresAt - issuedAt <= PUSH_LIMITS.challengeTtlMs - ], + ['window', issuedAt === null || challenge.expiresAt - issuedAt <= PUSH_LIMITS.challengeTtlMs], ['expiry-consistent', expiresAt === challenge.expiresAt], - ['protocol', equal(fields.get('protocol'), textEncoder.encode(PUSH_HOST_PROOF_TRANSCRIPT_DOMAIN))], + [ + 'protocol', + equal(fields.get('protocol'), textEncoder.encode(PUSH_HOST_PROOF_TRANSCRIPT_DOMAIN)) + ], ['version', equal(fields.get('version'), new Uint8Array([1]))], - ['gatewayOrigin', equal(fields.get('gatewayOrigin'), textEncoder.encode(context.gatewayOrigin))], + [ + 'gatewayOrigin', + equal(fields.get('gatewayOrigin'), textEncoder.encode(context.gatewayOrigin)) + ], ['gatewayEphemeralPublicKey', equal(fields.get('gatewayEphemeralPublicKey'), gatewayKey)], ['challengeNonce', equal(fields.get('challengeNonce'), nonce)], ['challengeId', equal(fields.get('challengeId'), textEncoder.encode(challenge.challengeId))], @@ -125,7 +131,9 @@ export function answerPushHostChallenge( const gatewayKey = decodeCanonicalBase64(challenge.gatewayEphemeralPublicKeyB64, 32) const nonce = decodeCanonicalBase64(challenge.nonceB64, 24) const ciphertext = Buffer.from(challenge.ciphertextB64, 'base64') - if (!gatewayKey || !nonce || ciphertext.toString('base64') !== challenge.ciphertextB64) return null + if (!gatewayKey || !nonce || ciphertext.toString('base64') !== challenge.ciphertextB64) { + return null + } const plaintext = nacl.box.open(ciphertext, nonce, gatewayKey, context.keypair.secretKey) if (!plaintext) { context.onInvalid?.('challenge-box-open') diff --git a/cloud/apps/push/src/host-challenge-store.test.ts b/cloud/apps/push/src/host-auth/host-challenge-store.test.ts similarity index 89% rename from cloud/apps/push/src/host-challenge-store.test.ts rename to cloud/apps/push/src/host-auth/host-challenge-store.test.ts index f73a4f53ea8..a5b4e5574ea 100644 --- a/cloud/apps/push/src/host-challenge-store.test.ts +++ b/cloud/apps/push/src/host-auth/host-challenge-store.test.ts @@ -1,4 +1,4 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { answerPushHostChallenge, @@ -7,7 +7,8 @@ import { } from './host-challenge-answering.test-fixture.js' import { PushHostChallengeStore } from './host-challenge-store.js' -import { openInMemoryPushDatabase, type PushDatabase } from './push-database.js' +import { openInMemoryPushDatabase } from '../database/push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' const GATEWAY_ORIGIN = 'https://push.onorca.dev' @@ -26,12 +27,6 @@ describe('push host challenge store', () => { await database.close() }) - - - - - - it('rejects a challenge the moment its own ttl elapses', async () => { const host = createPushHostKeypair(4) const challenge = await store.issue(hostPublicKeyB64(host)) @@ -47,10 +42,6 @@ describe('push host challenge store', () => { }) }) - - - - it('refuses a wrong host: the box will not open and a foreign proof will not match', async () => { const owner = createPushHostKeypair(6) const intruder = createPushHostKeypair(7) @@ -74,6 +65,4 @@ describe('push host challenge store', () => { reason: 'proof_mismatch' }) }) - - }) diff --git a/cloud/apps/push/src/host-challenge-store.ts b/cloud/apps/push/src/host-auth/host-challenge-store.ts similarity index 95% rename from cloud/apps/push/src/host-challenge-store.ts rename to cloud/apps/push/src/host-auth/host-challenge-store.ts index fd12af85983..5cfb68d2f12 100644 --- a/cloud/apps/push/src/host-challenge-store.ts +++ b/cloud/apps/push/src/host-auth/host-challenge-store.ts @@ -2,13 +2,13 @@ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from import { buildPushHostChallengePlaintext, buildPushHostProofMacInput, - buildPushHostProofTranscript, - PUSH_LIMITS -} from '@orca-cloud/push-contract' + buildPushHostProofTranscript +} from '@orca-cloud/push-contract/push-host-proof-transcript' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import nacl from 'tweetnacl' import { decodeCanonicalBase64 } from './canonical-base64.js' import { deriveHostFingerprint } from './host-fingerprint.js' -import type { PushDatabase } from './push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' export type IssuedPushChallenge = { challengeId: string diff --git a/cloud/apps/push/src/host-fingerprint.ts b/cloud/apps/push/src/host-auth/host-fingerprint.ts similarity index 96% rename from cloud/apps/push/src/host-fingerprint.ts rename to cloud/apps/push/src/host-auth/host-fingerprint.ts index 955b1ac8ecb..b0cee6ca15b 100644 --- a/cloud/apps/push/src/host-fingerprint.ts +++ b/cloud/apps/push/src/host-auth/host-fingerprint.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { PUSH_HOST_FINGERPRINT_LENGTH } from '@orca-cloud/push-contract' +import { PUSH_HOST_FINGERPRINT_LENGTH } from '@orca-cloud/push-contract/push-limits' // Identical derivation to deriveRelayHostId on the desktop, so a host and a // phone reach the same fingerprint from the same X25519 public key. diff --git a/cloud/apps/push/src/host-proof-concurrency.test.ts b/cloud/apps/push/src/host-auth/host-proof-concurrency.test.ts similarity index 95% rename from cloud/apps/push/src/host-proof-concurrency.test.ts rename to cloud/apps/push/src/host-auth/host-proof-concurrency.test.ts index 031ca61c7fd..8e64ab10165 100644 --- a/cloud/apps/push/src/host-proof-concurrency.test.ts +++ b/cloud/apps/push/src/host-auth/host-proof-concurrency.test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { openInMemoryPushDatabase, openPushDatabase } from './push-database.js' +import { openInMemoryPushDatabase, openPushDatabase } from '../database/push-database.js' import { PushHostChallengeStore } from './host-challenge-store.js' import { answerPushHostChallenge, diff --git a/cloud/apps/push/src/host-session-store.test.ts b/cloud/apps/push/src/host-auth/host-session-store.test.ts similarity index 72% rename from cloud/apps/push/src/host-session-store.test.ts rename to cloud/apps/push/src/host-auth/host-session-store.test.ts index ad90407164d..4389d310f4a 100644 --- a/cloud/apps/push/src/host-session-store.test.ts +++ b/cloud/apps/push/src/host-auth/host-session-store.test.ts @@ -1,7 +1,8 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { PushHostSessionStore } from './host-session-store.js' -import { openInMemoryPushDatabase, type PushDatabase } from './push-database.js' +import { openInMemoryPushDatabase } from '../database/push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' const HOST = 'abcdefghijklmnop' @@ -20,18 +21,6 @@ describe('push host session store', () => { await database.close() }) - it('mints a 24 hour session and stores only its hash', async () => { - const session = await sessions.create(HOST) - expect(session.expiresAt).toBe(clock + PUSH_LIMITS.sessionTtlMs) - expect(Buffer.from(session.sessionToken, 'base64url').byteLength).toBe(32) - const [row] = await database.query('SELECT token_hash FROM push_sessions') - expect(String(row?.token_hash)).not.toBe(session.sessionToken) - await expect(sessions.resolve(session.sessionToken)).resolves.toMatchObject({ - ok: true, - hostFingerprint: HOST - }) - }) - it('reports expiry separately from an unknown token', async () => { const session = await sessions.create(HOST) clock += PUSH_LIMITS.sessionTtlMs + 1 @@ -45,8 +34,6 @@ describe('push host session store', () => { }) }) - - it('keeps one live session per host and prunes it once expired', async () => { const first = await sessions.create(HOST) const second = await sessions.create(HOST) diff --git a/cloud/apps/push/src/host-session-store.ts b/cloud/apps/push/src/host-auth/host-session-store.ts similarity index 93% rename from cloud/apps/push/src/host-session-store.ts rename to cloud/apps/push/src/host-auth/host-session-store.ts index 5ee1f2aa6a0..6841bb4c633 100644 --- a/cloud/apps/push/src/host-session-store.ts +++ b/cloud/apps/push/src/host-auth/host-session-store.ts @@ -1,6 +1,6 @@ import { createHash, randomBytes } from 'node:crypto' -import { PUSH_LIMITS } from '@orca-cloud/push-contract' -import type { PushDatabase } from './push-database.js' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' export type IssuedPushSession = { sessionToken: string diff --git a/cloud/apps/push/src/push-session-concurrency.test.ts b/cloud/apps/push/src/host-auth/push-session-concurrency.test.ts similarity index 60% rename from cloud/apps/push/src/push-session-concurrency.test.ts rename to cloud/apps/push/src/host-auth/push-session-concurrency.test.ts index 4c6944255f8..221a5c91ab4 100644 --- a/cloud/apps/push/src/push-session-concurrency.test.ts +++ b/cloud/apps/push/src/host-auth/push-session-concurrency.test.ts @@ -1,7 +1,8 @@ import { randomUUID } from 'node:crypto' import { tmpdir } from 'node:os' import { afterEach, describe, expect, it } from 'vitest' -import { openInMemoryPushDatabase, openPushDatabase, type PushDatabase } from './push-database.js' +import { openInMemoryPushDatabase, openPushDatabase } from '../database/push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' import { PushHostSessionStore } from './host-session-store.js' const databases: PushDatabase[] = [] afterEach(async () => { @@ -31,16 +32,6 @@ it('serializes sessions on SQLite', async () => { await concurrentSessions(await openInMemoryPushDatabase()) }) -it('enforces one session per host directly in the schema', async () => { - const db = await openInMemoryPushDatabase() - databases.push(db) - await db.query('INSERT INTO push_sessions VALUES (?, ?, ?, ?)', ['first', 'host', 100, 1]) - await expect( - db.query('INSERT INTO push_sessions VALUES (?, ?, ?, ?)', ['second', 'host', 100, 2]) - ).rejects.toThrow() - expect(await db.query('SELECT token_hash FROM push_sessions')).toEqual([{ token_hash: 'first' }]) -}) - describe.skipIf(!process.env.ORCA_PUSH_TEST_DATABASE_URL)('PostgreSQL push sessions', () => { it('leaves exactly one live token after concurrent creates', async () => { await concurrentSessions( @@ -50,16 +41,4 @@ describe.skipIf(!process.env.ORCA_PUSH_TEST_DATABASE_URL)('PostgreSQL push sessi }) ) }) - it('allows concurrent schema startup', async () => { - const opened = await Promise.all( - Array.from({ length: 4 }, () => - openPushDatabase({ - databaseUrl: process.env.ORCA_PUSH_TEST_DATABASE_URL!, - dataDir: tmpdir() - }) - ) - ) - databases.push(...opened) - for (const db of opened) expect(await db.query('SELECT 1 AS ok')).toEqual([{ ok: 1 }]) - }) }) diff --git a/cloud/apps/push/src/client-ip-rate-limit.test.ts b/cloud/apps/push/src/http/client-ip-rate-limit.test.ts similarity index 97% rename from cloud/apps/push/src/client-ip-rate-limit.test.ts rename to cloud/apps/push/src/http/client-ip-rate-limit.test.ts index 11baec26394..041b1577f08 100644 --- a/cloud/apps/push/src/client-ip-rate-limit.test.ts +++ b/cloud/apps/push/src/http/client-ip-rate-limit.test.ts @@ -1,4 +1,4 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { Hono } from 'hono' import { describe, expect, it } from 'vitest' import { ClientIpRateLimiter, clientIpRateLimit } from './client-ip-rate-limit.js' @@ -14,18 +14,6 @@ function limiterApp(limiter: ClientIpRateLimiter, trustedProxyHops = 0): Hono { } describe('client ip rate limiter', () => { - - - - - - - - - - - - it('buckets on the last forwarded hop, the only one the platform appended', async () => { const app = limiterApp(new ClientIpRateLimiter({ now: () => 1_000 })) for (let index = 0; index < CAPACITY; index++) { diff --git a/cloud/apps/push/src/client-ip-rate-limit.ts b/cloud/apps/push/src/http/client-ip-rate-limit.ts similarity index 97% rename from cloud/apps/push/src/client-ip-rate-limit.ts rename to cloud/apps/push/src/http/client-ip-rate-limit.ts index 6ac3e4d3c15..d13794b7095 100644 --- a/cloud/apps/push/src/client-ip-rate-limit.ts +++ b/cloud/apps/push/src/http/client-ip-rate-limit.ts @@ -1,4 +1,4 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import type { Context, MiddlewareHandler } from 'hono' const REFILL_WINDOW_MS = 60_000 diff --git a/cloud/apps/push/src/push-auth-admission.ts b/cloud/apps/push/src/http/push-auth-admission.ts similarity index 100% rename from cloud/apps/push/src/push-auth-admission.ts rename to cloud/apps/push/src/http/push-auth-admission.ts diff --git a/cloud/apps/push/src/push-authenticated-ip-limit.test.ts b/cloud/apps/push/src/http/push-authenticated-ip-limit.test.ts similarity index 91% rename from cloud/apps/push/src/push-authenticated-ip-limit.test.ts rename to cloud/apps/push/src/http/push-authenticated-ip-limit.test.ts index a626b80060a..01b68073dad 100644 --- a/cloud/apps/push/src/push-authenticated-ip-limit.test.ts +++ b/cloud/apps/push/src/http/push-authenticated-ip-limit.test.ts @@ -1,6 +1,6 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { expect, it } from 'vitest' -import { createPushHostKeypair } from './host-challenge-answering.test-fixture.js' +import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' import { createPushServerHarness, FCM_TOKEN } from './push-server-harness.test-fixture.js' it('bounds valid hosts together across routes without letting key rotation reset the IP budget', async () => { diff --git a/cloud/apps/push/src/push-readiness.ts b/cloud/apps/push/src/http/push-readiness.ts similarity index 90% rename from cloud/apps/push/src/push-readiness.ts rename to cloud/apps/push/src/http/push-readiness.ts index c071a0750e4..c1751ef72f6 100644 --- a/cloud/apps/push/src/push-readiness.ts +++ b/cloud/apps/push/src/http/push-readiness.ts @@ -1,4 +1,4 @@ -import type { PushDatabase } from './push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' export type PushReadinessOptions = { cacheMs?: number diff --git a/cloud/apps/push/src/push-request-drain.ts b/cloud/apps/push/src/http/push-request-drain.ts similarity index 100% rename from cloud/apps/push/src/push-request-drain.ts rename to cloud/apps/push/src/http/push-request-drain.ts diff --git a/cloud/apps/push/src/push-send-idempotency.test.ts b/cloud/apps/push/src/http/push-send-idempotency.test.ts similarity index 56% rename from cloud/apps/push/src/push-send-idempotency.test.ts rename to cloud/apps/push/src/http/push-send-idempotency.test.ts index 1a687a35449..b061eef3040 100644 --- a/cloud/apps/push/src/push-send-idempotency.test.ts +++ b/cloud/apps/push/src/http/push-send-idempotency.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, it } from 'vitest' import { createPushServerHarness, notification } from './push-server-harness.test-fixture.js' -import { createPushHostKeypair } from './host-challenge-answering.test-fixture.js' +import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' const harnesses: Awaited>[] = [] afterEach(async () => { await Promise.all(harnesses.splice(0).map((h) => h.close())) @@ -34,31 +34,3 @@ it('returns queued for concurrent retries without double quota or delivery', asy await h.flushDeliveries() expect(h.fcmRequests).toHaveLength(2) }) - -it.each([false, true])( - 'accepts default alert kind equivalently through the API (explicit first: %s)', - async (explicitFirst) => { - const h = await createPushServerHarness() - harnesses.push(h) - const token = await h.signIn(createPushHostKeypair(3)) - const registrationId = await h.registerAndroid(token) - const implicit = notification() - const explicit = { kind: 'alert', ...implicit } - for (const event of explicitFirst ? [explicit, implicit] : [implicit, explicit]) { - const response = await h.post( - '/v1/send', - { v: 1, registrationIds: [registrationId], notification: event }, - token - ) - expect(await response.json()).toEqual({ results: [{ registrationId, status: 'queued' }] }) - } - await h.flushDeliveries() - expect(h.fcmRequests).toHaveLength(1) - const changed = await h.post( - '/v1/send', - { v: 1, registrationIds: [registrationId], notification: { ...explicit, body: 'changed' } }, - token - ) - expect(await changed.json()).toEqual({ results: [{ registrationId, status: 'error' }] }) - } -) diff --git a/cloud/apps/push/src/push-server-auth.test.ts b/cloud/apps/push/src/http/push-server-auth.test.ts similarity index 93% rename from cloud/apps/push/src/push-server-auth.test.ts rename to cloud/apps/push/src/http/push-server-auth.test.ts index 50ad8add4f9..ad1989955f7 100644 --- a/cloud/apps/push/src/push-server-auth.test.ts +++ b/cloud/apps/push/src/http/push-server-auth.test.ts @@ -1,8 +1,8 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createPushHostKeypair } from './host-challenge-answering.test-fixture.js' -import type { PushDatabase } from './push-database.js' -import { createPushServer } from './push-server.js' +import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' +import { createPushServer } from '../push-server.js' import { createPushServerHarness, testPushConfig } from './push-server-harness.test-fixture.js' describe('push gateway authentication and device routes', () => { diff --git a/cloud/apps/push/src/push-server-harness.test-fixture.ts b/cloud/apps/push/src/http/push-server-harness.test-fixture.ts similarity index 89% rename from cloud/apps/push/src/push-server-harness.test-fixture.ts rename to cloud/apps/push/src/http/push-server-harness.test-fixture.ts index f1567dd9ab7..2d7c403c19a 100644 --- a/cloud/apps/push/src/push-server-harness.test-fixture.ts +++ b/cloud/apps/push/src/http/push-server-harness.test-fixture.ts @@ -1,15 +1,17 @@ import { generateKeyPairSync } from 'node:crypto' import { expect } from 'vitest' -import type { ApnsRequest, ApnsResponse } from './apns-http2-transport.js' -import type { PushConfig } from './config.js' -import type { FcmRequest, FcmResponse } from './fcm-client.js' +import type { ApnsRequest } from '../providers/apns/apns-http2-transport.js' +import type { ApnsResponse } from '../providers/apns/apns-stream-response.js' +import type { PushConfig } from '../config.js' +import type { FcmRequest, FcmResponse } from '../providers/fcm/fcm-client.js' import { answerPushHostChallenge, hostPublicKeyB64, type PushHostKeypair -} from './host-challenge-answering.test-fixture.js' -import { openInMemoryPushDatabase, type PushDatabase } from './push-database.js' -import { createPushServer } from './push-server.js' +} from '../host-auth/host-challenge-answering.test-fixture.js' +import { openInMemoryPushDatabase } from '../database/push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' +import { createPushServer } from '../push-server.js' export const GATEWAY_ORIGIN = 'https://push.onorca.dev' export const APNS_TOKEN = 'a'.repeat(64) diff --git a/cloud/apps/push/src/push-server-limits.test.ts b/cloud/apps/push/src/http/push-server-limits.test.ts similarity index 78% rename from cloud/apps/push/src/push-server-limits.test.ts rename to cloud/apps/push/src/http/push-server-limits.test.ts index a46384d0d3c..465684353d4 100644 --- a/cloud/apps/push/src/push-server-limits.test.ts +++ b/cloud/apps/push/src/http/push-server-limits.test.ts @@ -1,11 +1,10 @@ -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createPushHostKeypair, hostPublicKeyB64 } from './host-challenge-answering.test-fixture.js' import { - createPushServerHarness, - FCM_TOKEN, - notification -} from './push-server-harness.test-fixture.js' + createPushHostKeypair, + hostPublicKeyB64 +} from '../host-auth/host-challenge-answering.test-fixture.js' +import { createPushServerHarness, notification } from './push-server-harness.test-fixture.js' const CLIENT_IP = '203.0.113.7' const OTHER_CLIENT_IP = '198.51.100.9' @@ -177,51 +176,6 @@ describe('push gateway request limits', () => { expect(challenge.status).toBe(200) }) - it('stops repeated forged bearers after the invalid-auth budget is exhausted', async () => { - const headers = { 'x-forwarded-for': CLIENT_IP } - const [before] = await harness.database.query('SELECT COUNT(*) AS sessions FROM push_sessions') - for (let index = 0; index < PUSH_LIMITS.unauthenticatedRequestsPerMinutePerIp; index++) { - const refused = await harness.authorized('/v1/send', { method: 'POST', headers }, 'forged') - expect(refused.status).toBe(401) - } - const limited = await harness.authorized('/v1/send', { method: 'POST', headers }, 'forged') - expect(limited.status).toBe(429) - expect(await limited.json()).toEqual({ error: 'rate_limited' }) - expect(harness.server.unauthenticatedIps.trackedIpCount()).toBe(0) - const [after] = await harness.database.query('SELECT COUNT(*) AS sessions FROM push_sessions') - expect(Number(after?.sessions)).toBe(Number(before?.sessions)) - }) - - it('answers 409 once a host has registered its device allowance', async () => { - const sessionToken = await harness.signIn(createPushHostKeypair(66)) - for (let index = 0; index < PUSH_LIMITS.maxDevicesPerHost; index++) { - const accepted = await harness.post( - '/v1/devices', - { - v: 1, - deviceId: `device-${index}`, - platform: 'android', - token: FCM_TOKEN - }, - sessionToken - ) - expect(accepted.status).toBe(200) - } - - const refused = await harness.post( - '/v1/devices', - { v: 1, deviceId: 'one-too-many', platform: 'android', token: FCM_TOKEN }, - sessionToken - ) - expect(refused.status).toBe(409) - expect(await refused.json()).toEqual({ error: 'too_many_devices' }) - - const listed = await harness.authorized('/v1/devices', {}, sessionToken) - expect(((await listed.json()) as { devices: unknown[] }).devices).toHaveLength( - PUSH_LIMITS.maxDevicesPerHost - ) - }) - // Why: a database error carries the failing row in its message. The response // and the log must both stop at the error's name. it('answers an unexpected route failure with a bare 500 and logs only the name', async () => { diff --git a/cloud/apps/push/src/push-server-send.test.ts b/cloud/apps/push/src/http/push-server-send.test.ts similarity index 97% rename from cloud/apps/push/src/push-server-send.test.ts rename to cloud/apps/push/src/http/push-server-send.test.ts index 9536bed841e..48982f5f697 100644 --- a/cloud/apps/push/src/push-server-send.test.ts +++ b/cloud/apps/push/src/http/push-server-send.test.ts @@ -1,7 +1,7 @@ -import { PushNotificationSchema } from '@orca-cloud/push-contract' -import { PUSH_LIMITS } from '@orca-cloud/push-contract' +import { PushNotificationSchema } from '@orca-cloud/push-contract/send-messages' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createPushHostKeypair } from './host-challenge-answering.test-fixture.js' +import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' import { APNS_TOKEN, createPushServerHarness, diff --git a/cloud/apps/push/src/http/push-server-wake.test.ts b/cloud/apps/push/src/http/push-server-wake.test.ts new file mode 100644 index 00000000000..c8f42b23990 --- /dev/null +++ b/cloud/apps/push/src/http/push-server-wake.test.ts @@ -0,0 +1,46 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { startPushBackground } from '../push-background.js' +import { createPushHostKeypair } from '../host-auth/host-challenge-answering.test-fixture.js' +import { createPushServerHarness, notification } from './push-server-harness.test-fixture.js' + +const cleanups: (() => Promise)[] = [] +afterEach(async () => { + for (const cleanup of cleanups.splice(0)) { + await cleanup() + } + vi.useRealTimers() + vi.restoreAllMocks() +}) + +async function fixture() { + const h = await createPushServerHarness() + const token = await h.signIn(createPushHostKeypair(31)) + const registrationId = await h.registerAndroid(token) + let stop = async () => {} + cleanups.push(async () => { + await stop() + await h.close() + }) + vi.useFakeTimers() + return { + ...h, + registrationId, + start: () => { + stop = startPushBackground({ mode: 'active' }, h.server) + }, + send: (event = notification(), ids = [registrationId]) => + h.post('/v1/send', { v: 1, registrationIds: ids, notification: event }, token), + invalid: () => h.post('/v1/send', { v: 1 }, token) + } +} + +it('keeps concurrent accepted retries idempotent while automatic delivery runs', async () => { + const h = await fixture() + h.start() + await Promise.all(Array.from({ length: 10 }, () => h.send())) + await vi.waitFor(() => expect(h.fcmRequests).toHaveLength(1)) + await h.send() + await h.server.worker.runDue() + expect(h.fcmRequests).toHaveLength(1) + expect(await h.server.deliveryStore.pendingCount(h.registrationId)).toBe(0) +}) diff --git a/cloud/apps/push/src/index.ts b/cloud/apps/push/src/index.ts index d44148874c7..e9abf51c78a 100644 --- a/cloud/apps/push/src/index.ts +++ b/cloud/apps/push/src/index.ts @@ -1,6 +1,6 @@ import { startPushBackground } from './push-background.js' import { loadPushConfig } from './config.js' -import { openPushDatabase } from './push-database.js' +import { openPushDatabase } from './database/push-database.js' import { createPushServer } from './push-server.js' const config = loadPushConfig() diff --git a/cloud/apps/push/src/apns-authentication-token.ts b/cloud/apps/push/src/providers/apns/apns-authentication-token.ts similarity index 96% rename from cloud/apps/push/src/apns-authentication-token.ts rename to cloud/apps/push/src/providers/apns/apns-authentication-token.ts index 34def16e86e..751c7279f17 100644 --- a/cloud/apps/push/src/apns-authentication-token.ts +++ b/cloud/apps/push/src/providers/apns/apns-authentication-token.ts @@ -1,5 +1,5 @@ import { createPrivateKey, type KeyObject, sign } from 'node:crypto' -import type { ApnsCredentials } from './config.js' +import type { ApnsCredentials } from '../../config.js' // Apple rejects a provider token older than an hour and throttles reissue // under about 20 minutes, so 50 minutes is the safe rotation point. diff --git a/cloud/apps/push/src/apns-client.test.ts b/cloud/apps/push/src/providers/apns/apns-client.test.ts similarity index 64% rename from cloud/apps/push/src/apns-client.test.ts rename to cloud/apps/push/src/providers/apns/apns-client.test.ts index 6e17085506d..7c76aeda694 100644 --- a/cloud/apps/push/src/apns-client.test.ts +++ b/cloud/apps/push/src/providers/apns/apns-client.test.ts @@ -2,9 +2,10 @@ import { generateKeyPairSync } from 'node:crypto' import { expect, it } from 'vitest' import { ApnsClient } from './apns-client.js' -import type { ApnsRequest, ApnsResponse } from './apns-http2-transport.js' -import type { ApnsCredentials } from './config.js' -import { buildPushDelivery } from './push-delivery-message.js' +import type { ApnsRequest } from './apns-http2-transport.js' +import type { ApnsResponse } from './apns-stream-response.js' +import type { ApnsCredentials } from '../../config.js' +import { buildPushDelivery } from '../../delivery/push-delivery-message.js' const HOST = 'abcdefghijklmnop' @@ -46,10 +47,6 @@ function fakeTransport(response: ApnsResponse) { } } - - - - it('does not collapse background dismissals with visible alerts', async () => { const fake = fakeTransport({ status: 200, body: '' }) const apns = new ApnsClient({ @@ -72,29 +69,3 @@ it('does not collapse background dismissals with visible alerts', async () => { }) expect(JSON.parse(fake.requests[0]!.body).aps).toEqual({ 'content-available': 1 }) }) - -it('keeps the absolute deadline across retries and refuses expired delivery', async () => { - let now = 1_700_000_000_000 - const fake = fakeTransport({ status: 503, body: '{}' }) - const client = new ApnsClient({ - topic: 'test', - credentials: credentials(), - now: () => now, - transport: fake.transport - }) - const pending = delivery(now) - const device = { token: 'test', apnsEnvironment: 'sandbox' as const } - await client.send(pending, device) - now += 60_000 - await client.send(pending, device) - expect(fake.requests.map((request) => request.headers['apns-expiration'])).toEqual([ - String(pending.expiresAt / 1000), - String(pending.expiresAt / 1000) - ]) - now = pending.expiresAt - await expect(client.send(pending, device)).resolves.toEqual({ - status: 'error', - reason: 'expired' - }) - expect(fake.requests).toHaveLength(2) -}) diff --git a/cloud/apps/push/src/apns-client.ts b/cloud/apps/push/src/providers/apns/apns-client.ts similarity index 91% rename from cloud/apps/push/src/apns-client.ts rename to cloud/apps/push/src/providers/apns/apns-client.ts index 827efdfea79..e49f593b83b 100644 --- a/cloud/apps/push/src/apns-client.ts +++ b/cloud/apps/push/src/providers/apns/apns-client.ts @@ -1,9 +1,9 @@ -import type { ApnsEnvironment } from '@orca-cloud/push-contract' +import type { ApnsEnvironment } from '@orca-cloud/push-contract/device-registration-messages' import { ApnsAuthenticationToken } from './apns-authentication-token.js' import type { ApnsTransport } from './apns-http2-transport.js' -import type { ApnsCredentials } from './config.js' -import type { PushDelivery } from './push-delivery-message.js' -import type { PushProviderOutcome } from './push-provider-outcome.js' +import type { ApnsCredentials } from '../../config.js' +import type { PushDelivery } from '../../delivery/push-delivery-message.js' +import type { PushProviderOutcome } from '../push-provider-outcome.js' const APNS_HOSTS: Record = { production: 'api.push.apple.com', diff --git a/cloud/apps/push/src/apns-http2-transport.ts b/cloud/apps/push/src/providers/apns/apns-http2-transport.ts similarity index 98% rename from cloud/apps/push/src/apns-http2-transport.ts rename to cloud/apps/push/src/providers/apns/apns-http2-transport.ts index d6cbc9b0b13..bf37ece50b7 100644 --- a/cloud/apps/push/src/apns-http2-transport.ts +++ b/cloud/apps/push/src/providers/apns/apns-http2-transport.ts @@ -8,7 +8,6 @@ export type ApnsRequest = { body: string } -export type { ApnsResponse } export type ApnsTransport = (request: ApnsRequest) => Promise // Cache APNs HTTP/2 sessions per host until socket loss; long-lived connections avoid reconnect overhead. diff --git a/cloud/apps/push/src/apns-stream-response.test.ts b/cloud/apps/push/src/providers/apns/apns-stream-response.test.ts similarity index 99% rename from cloud/apps/push/src/apns-stream-response.test.ts rename to cloud/apps/push/src/providers/apns/apns-stream-response.test.ts index 0cf8b3554be..e8fb3ad6f6c 100644 --- a/cloud/apps/push/src/apns-stream-response.test.ts +++ b/cloud/apps/push/src/providers/apns/apns-stream-response.test.ts @@ -28,8 +28,6 @@ function fakeApnsStream(): FakeStream { } describe('apns stream response', () => { - - it('rejects when the peer resets the stream without an end or an error', async () => { const stream = fakeApnsStream() const pending = readApnsStreamResponse(stream, 'body') @@ -38,12 +36,4 @@ describe('apns stream response', () => { stream.emit('close') await expect(pending).rejects.toThrow('apns_stream_closed') }) - - - - - - - - }) diff --git a/cloud/apps/push/src/apns-stream-response.ts b/cloud/apps/push/src/providers/apns/apns-stream-response.ts similarity index 96% rename from cloud/apps/push/src/apns-stream-response.ts rename to cloud/apps/push/src/providers/apns/apns-stream-response.ts index 8ea0c1b1a21..18f27c425c8 100644 --- a/cloud/apps/push/src/apns-stream-response.ts +++ b/cloud/apps/push/src/providers/apns/apns-stream-response.ts @@ -1,5 +1,5 @@ import type { EventEmitter } from 'node:events' -import { providerRetryAfter } from './provider-retry-delay.js' +import { providerRetryAfter } from '../provider-retry-delay.js' import { constants } from 'node:http2' export type ApnsResponse = { status: number; body: string; retryAfterMs?: number } diff --git a/cloud/apps/push/src/apns-topic-recovery.test.ts b/cloud/apps/push/src/providers/apns/apns-topic-recovery.test.ts similarity index 90% rename from cloud/apps/push/src/apns-topic-recovery.test.ts rename to cloud/apps/push/src/providers/apns/apns-topic-recovery.test.ts index 583d4536b5a..2697564792c 100644 --- a/cloud/apps/push/src/apns-topic-recovery.test.ts +++ b/cloud/apps/push/src/providers/apns/apns-topic-recovery.test.ts @@ -1,10 +1,10 @@ import { expect, it } from 'vitest' -import { createPushHostKeypair } from './host-challenge-answering.test-fixture.js' +import { createPushHostKeypair } from '../../host-auth/host-challenge-answering.test-fixture.js' import { APNS_TOKEN, createPushServerHarness, notification -} from './push-server-harness.test-fixture.js' +} from '../../http/push-server-harness.test-fixture.js' it('delivers again after a topic error without re-registering the phone', async () => { const h = await createPushServerHarness() diff --git a/cloud/apps/push/src/fcm-access-token.ts b/cloud/apps/push/src/providers/fcm/fcm-access-token.ts similarity index 100% rename from cloud/apps/push/src/fcm-access-token.ts rename to cloud/apps/push/src/providers/fcm/fcm-access-token.ts diff --git a/cloud/apps/push/src/fcm-client.test.ts b/cloud/apps/push/src/providers/fcm/fcm-client.test.ts similarity index 74% rename from cloud/apps/push/src/fcm-client.test.ts rename to cloud/apps/push/src/providers/fcm/fcm-client.test.ts index 107ef8c648d..8aeeba07af6 100644 --- a/cloud/apps/push/src/fcm-client.test.ts +++ b/cloud/apps/push/src/providers/fcm/fcm-client.test.ts @@ -1,7 +1,6 @@ - import { describe, expect, it } from 'vitest' import { FcmClient, type FcmRequest, type FcmResponse } from './fcm-client.js' -import { buildPushDelivery } from './push-delivery-message.js' +import { buildPushDelivery } from '../../delivery/push-delivery-message.js' const NOW = 1_700_000_000_000 const HOST = 'abcdefghijklmnop' @@ -51,9 +50,6 @@ function client(response: FcmResponse) { } describe('fcm client', () => { - - - it('marks an invalid-argument that names the token dead, and others an error', async () => { const named = client({ status: 400, @@ -78,8 +74,6 @@ describe('fcm client', () => { retryAfterMs: 10000 }) }) - - }) it('does not send when credential refresh crosses the absolute expiry', async () => { @@ -100,33 +94,3 @@ it('does not send when credential refresh crosses the absolute expiry', async () }) expect(fake.requests).toHaveLength(0) }) - -it('decreases retry TTL and refuses expired delivery before refreshing credentials', async () => { - let now = NOW - let refreshes = 0 - const fake = fakeTransport({ status: 503, body: '{}' }) - const fcm = new FcmClient({ - projectId: 'test', - now: () => now, - accessToken: async () => { - refreshes++ - return 'test-token' - }, - transport: fake.transport - }) - const pending = delivery() - await fcm.send(pending, { token: TOKEN }) - now += 60_000 - await fcm.send(pending, { token: TOKEN }) - expect(fake.requests.map((request) => JSON.parse(request.body).message.android.ttl)).toEqual([ - '300s', - '240s' - ]) - now = pending.expiresAt - await expect(fcm.send(pending, { token: TOKEN })).resolves.toEqual({ - status: 'error', - reason: 'expired' - }) - expect(fake.requests).toHaveLength(2) - expect(refreshes).toBe(2) -}) diff --git a/cloud/apps/push/src/fcm-client.ts b/cloud/apps/push/src/providers/fcm/fcm-client.ts similarity index 93% rename from cloud/apps/push/src/fcm-client.ts rename to cloud/apps/push/src/providers/fcm/fcm-client.ts index 0b58aae80f5..66ef292bd18 100644 --- a/cloud/apps/push/src/fcm-client.ts +++ b/cloud/apps/push/src/providers/fcm/fcm-client.ts @@ -1,7 +1,7 @@ -import { providerRetryAfter } from './provider-retry-delay.js' -import { PUSH_DEFAULTS } from '@orca-cloud/push-contract' -import { orcaDataStrings, type PushDelivery } from './push-delivery-message.js' -import type { PushProviderOutcome } from './push-provider-outcome.js' +import { providerRetryAfter } from '../provider-retry-delay.js' +import { PUSH_DEFAULTS } from '@orca-cloud/push-contract/push-limits' +import { orcaDataStrings, type PushDelivery } from '../../delivery/push-delivery-message.js' +import type { PushProviderOutcome } from '../push-provider-outcome.js' export const FCM_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging' diff --git a/cloud/apps/push/src/provider-retry-delay.ts b/cloud/apps/push/src/providers/provider-retry-delay.ts similarity index 100% rename from cloud/apps/push/src/provider-retry-delay.ts rename to cloud/apps/push/src/providers/provider-retry-delay.ts diff --git a/cloud/apps/push/src/push-provider-outcome.ts b/cloud/apps/push/src/providers/push-provider-outcome.ts similarity index 100% rename from cloud/apps/push/src/push-provider-outcome.ts rename to cloud/apps/push/src/providers/push-provider-outcome.ts diff --git a/cloud/apps/push/src/push-background.ts b/cloud/apps/push/src/push-background.ts index 25b98d0d467..fec2f121117 100644 --- a/cloud/apps/push/src/push-background.ts +++ b/cloud/apps/push/src/push-background.ts @@ -1,5 +1,5 @@ import type { PushConfig } from './config.js' -import type { PushPruneSweep } from './durable-push-store.js' +import type { PushPruneSweep } from './delivery/durable-push-store.js' import type { createPushServer } from './push-server.js' const CHALLENGE_PRUNE_INTERVAL_MS = 60_000 @@ -45,9 +45,10 @@ function prune(label: string, run: () => Promise, intervalMs: nu } // One DELETE under a statement timeout: there is no batch budget for it to exhaust. -const unbatchedSweep = - (run: () => Promise) => - async (): Promise => ({ deleted: await run(), saturated: false }) +const unbatchedSweep = (run: () => Promise) => async (): Promise => ({ + deleted: await run(), + saturated: false +}) export function startPushBackground( config: Pick, diff --git a/cloud/apps/push/src/push-database-postgres-startup.test.ts b/cloud/apps/push/src/push-database-postgres-startup.test.ts deleted file mode 100644 index 08be1dad766..00000000000 --- a/cloud/apps/push/src/push-database-postgres-startup.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { randomUUID } from 'node:crypto' - -const fakes = vi.hoisted(() => ({ - configs: [] as Array>, - lifecycle: [] as string[], - query: vi.fn(async (_sql: string) => ({ rows: [], rowCount: 0 })), - release: vi.fn() -})) - -vi.mock('pg', () => ({ - default: { - Pool: class { - on = vi.fn() - connect = vi.fn(async () => ({ query: fakes.query, release: fakes.release })) - private readonly label: string - - constructor(config: Record) { - fakes.configs.push(config) - this.label = `max=${String(config.max)} statement_timeout=${String(config.statement_timeout)}` - fakes.lifecycle.push(`open ${this.label}`) - } - - async end(): Promise { - fakes.lifecycle.push(`end ${this.label}`) - } - } - } -})) - -import { openPushDatabase } from './push-database.js' -import { pushSchemaStatements } from './push-schema.js' - -describe('PostgreSQL push gateway startup', () => { - beforeEach(() => { - fakes.configs.length = 0 - fakes.lifecycle.length = 0 - fakes.query.mockClear() - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - const socketPassword = `${randomUUID()}@/` - const socketUrl = `postgresql://push:${encodeURIComponent(socketPassword)}@/orca_push?host=/cloudsql/test:region:instance` - - it('passes the Terraform socket URL unchanged to both active pools', async () => { - const database = await openPushDatabase({ databaseUrl: socketUrl, dataDir: '/unused' }) - expect(fakes.configs.map((config) => config.connectionString)).toEqual([socketUrl, socketUrl]) - await database.close() - }) - - it('parses socket credentials and query options before enforcing validation read-only', async () => { - const options = '-c search_path=validation -c default_transaction_read_only=off' - const database = await openPushDatabase({ - databaseUrl: `${socketUrl}&port=5433&sslmode=disable&options=${encodeURIComponent(options)}`, - dataDir: '/unused', - readOnly: true - }) - expect(fakes.configs).toHaveLength(1) - expect(fakes.configs[0]).toMatchObject({ - host: '/cloudsql/test:region:instance', - user: 'push', - password: socketPassword, - database: 'orca_push', - port: 5433, - ssl: false, - options: `${options} -c default_transaction_read_only=on` - }) - expect(fakes.configs[0]).not.toHaveProperty('connectionString') - expect(fakes.query).not.toHaveBeenCalled() - await database.close() - }) - - // Growing-table CREATE INDEX can exceed request deadlines; inheriting them makes startup fail forever at the same DDL. - it('applies the schema on an untimed pool that is gone before the serving pool opens', async () => { - const database = await openPushDatabase({ - databaseUrl: 'postgresql://push@localhost:55440/orca_push', - dataDir: '/unused', - poolMax: 2, - applicationName: 'orca-push' - }) - expect(fakes.lifecycle).toEqual([ - 'open max=1 statement_timeout=0', - 'end max=1 statement_timeout=0', - 'open max=2 statement_timeout=5000' - ]) - expect(fakes.configs[0]).toMatchObject({ - application_name: 'orca-push/schema', - lock_timeout: 1_000, - idle_in_transaction_session_timeout: 5_000 - }) - expect( - fakes.query.mock.calls.map(([sql]) => sql).slice(0, pushSchemaStatements().length) - ).toEqual(pushSchemaStatements()) - await database.close() - }) - - -}) diff --git a/cloud/apps/push/src/push-delivery-lifecycle.test.ts b/cloud/apps/push/src/push-delivery-lifecycle.test.ts index c94108e459c..ef845cc0811 100644 --- a/cloud/apps/push/src/push-delivery-lifecycle.test.ts +++ b/cloud/apps/push/src/push-delivery-lifecycle.test.ts @@ -1,12 +1,13 @@ import { afterEach, expect, it, vi } from 'vitest' import { Hono } from 'hono' -import { PushRequestDrain } from './push-request-drain.js' -import { PushDispatcher } from './push-dispatcher.js' -import { PushDeviceRegistryStore } from './device-registry-store.js' -import { openInMemoryPushDatabase, type PushDatabase } from './push-database.js' -import { buildPushDelivery } from './push-delivery-message.js' -import { PushNotificationSchema } from '@orca-cloud/push-contract' -import { notification } from './push-server-harness.test-fixture.js' +import { PushRequestDrain } from './http/push-request-drain.js' +import { PushDispatcher } from './delivery/push-dispatcher.js' +import { PushDeviceRegistryStore } from './devices/device-registry-store.js' +import { openInMemoryPushDatabase } from './database/push-database.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' +import { buildPushDelivery } from './delivery/push-delivery-message.js' +import { PushNotificationSchema } from '@orca-cloud/push-contract/send-messages' +import { notification } from './http/push-server-harness.test-fixture.js' const databases: PushDatabase[] = [] afterEach(async () => { diff --git a/cloud/apps/push/src/push-dismissal-provider.test.ts b/cloud/apps/push/src/push-dismissal-provider.test.ts deleted file mode 100644 index 65572e8401c..00000000000 --- a/cloud/apps/push/src/push-dismissal-provider.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { expect, it } from 'vitest' -import { apnsBody } from './apns-client.js' -import { fcmMessageBody } from './fcm-client.js' -import { buildPushDelivery } from './push-delivery-message.js' - -it('dismissal provider payloads cannot display a new alert or play a sound', () => { - const delivery = buildPushDelivery({ - expiresAt: Date.now() + 300_000, - registrationId: 'reg', - hostFingerprint: 'host', - notification: { - kind: 'dismiss', - notificationId: 'note', - notificationSeq: 2, - notificationEpoch: 'epoch', - source: 'agent-task-complete', - agentState: null, - title: 'Orca', - body: '' - } - }) - expect(JSON.parse(apnsBody(delivery)).aps).toEqual({ 'content-available': 1 }) - const android = JSON.parse(fcmMessageBody({ delivery, token: 'test', channelId: 'test' })).message - expect(android).not.toHaveProperty('notification') - expect(android.android).not.toHaveProperty('notification') - expect(android.android).not.toHaveProperty('collapse_key') - expect(android.data).not.toHaveProperty('title') - expect(android.data).not.toHaveProperty('message') - expect(android.data).not.toHaveProperty('sound') - expect(android.data.kind).toBe('dismiss') -}) diff --git a/cloud/apps/push/src/push-notification-sound.test.ts b/cloud/apps/push/src/push-notification-sound.test.ts deleted file mode 100644 index ede4dcd3291..00000000000 --- a/cloud/apps/push/src/push-notification-sound.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { expect, it } from 'vitest' -import { apnsBody } from './apns-client.js' -import { fcmMessageBody } from './fcm-client.js' -import { buildPushDelivery } from './push-delivery-message.js' -import { PushNotificationSchema } from '@orca-cloud/push-contract' - -it('carries a silent preference through validation to APNs and Android payloads', () => { - const notification = PushNotificationSchema.parse({ - notificationSeq: 1, - notificationEpoch: 'epoch', - source: 'terminal-bell', - agentState: null, - title: 'Bell', - body: '', - sound: false - }) - const delivery = buildPushDelivery({ - expiresAt: Date.now() + 300_000, - registrationId: 'reg', - hostFingerprint: 'host', - notification - }) - expect(JSON.parse(apnsBody(delivery)).aps).not.toHaveProperty('sound') - expect( - JSON.parse(fcmMessageBody({ delivery, token: 'test-token', channelId: 'orca-desktop' })).message - .data.channelId - ).toBe('orca-desktop-silent') - expect( - JSON.parse(fcmMessageBody({ delivery, token: 'test-token', channelId: 'orca-desktop' })).message - .data.sound - ).toBe('') - expect(JSON.parse(apnsBody({ ...delivery, sound: undefined })).aps.sound).toBe('default') -}) diff --git a/cloud/apps/push/src/push-schema-boot-lock.test.ts b/cloud/apps/push/src/push-schema-boot-lock.test.ts deleted file mode 100644 index 1c08fab56d1..00000000000 --- a/cloud/apps/push/src/push-schema-boot-lock.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { randomUUID } from 'node:crypto' -import pg from 'pg' -import { afterEach, expect, it, vi } from 'vitest' -import { openPushDatabase } from './push-database.js' -import { durablePushTestDatabaseUrl } from './durable-push-store.test-fixture.js' - -const QUEUE_INDEXES = ['push_batches_pending_device'] -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - vi.restoreAllMocks() - for (const cleanup of cleanups.splice(0).reverse()) await cleanup() -}) - -// Push applies its schema with retryLockTimeout, so a lock timeout is retried, never deferred: -// the new revision either boots with every index or does not boot at all. -it.skipIf(!durablePushTestDatabaseUrl)( - 'creates the queue index after waiting out a writer that holds the table', - async () => { - const admin = new pg.Client({ connectionString: durablePushTestDatabaseUrl }) - await admin.connect() - const schema = `boot_${randomUUID().replaceAll('-', '')}` - cleanups.push(async () => { - await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) - await admin.end() - }) - await admin.query(`CREATE SCHEMA ${schema}`) - const url = new URL(durablePushTestDatabaseUrl!) - url.searchParams.set('options', `-c search_path=${schema}`) - await (await openPushDatabase({ databaseUrl: url.toString(), dataDir: '' })).close() - await admin.query( - `DROP INDEX ${QUEUE_INDEXES.map((name) => `${schema}.${name}`).join(', ')}` - ) - - const writer = new pg.Client({ connectionString: url.toString() }) - await writer.connect() - cleanups.push(() => writer.end()) - await writer.query('BEGIN') - await writer.query('LOCK TABLE push_delivery_batches IN ROW EXCLUSIVE MODE') - const warnings: string[] = [] - vi.spyOn(console, 'warn').mockImplementation((line: string) => warnings.push(line)) - vi.spyOn(console, 'log').mockImplementation(() => undefined) - const held = setTimeout(() => void writer.query('COMMIT'), 2_500) - cleanups.push(async () => clearTimeout(held)) - - const booted = await openPushDatabase({ databaseUrl: url.toString(), dataDir: '' }) - await booted.close() - const { rows } = await admin.query( - 'SELECT indexname FROM pg_indexes WHERE schemaname = $1 AND indexname = ANY($2) ORDER BY 1', - [schema, QUEUE_INDEXES] - ) - expect(rows.map((row) => row.indexname)).toEqual(QUEUE_INDEXES) - const events = warnings.map((line) => JSON.parse(line).event) - expect(events).toContain('orca_push_postgres_schema_retry') - expect(events).not.toContain('orca_push_postgres_schema_object_deferred') - } -) diff --git a/cloud/apps/push/src/push-server-wake.test.ts b/cloud/apps/push/src/push-server-wake.test.ts deleted file mode 100644 index 8a5442df9c5..00000000000 --- a/cloud/apps/push/src/push-server-wake.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { startPushBackground } from './push-background.js' -import { createPushHostKeypair } from './host-challenge-answering.test-fixture.js' -import { createPushServerHarness, notification } from './push-server-harness.test-fixture.js' - -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - for (const cleanup of cleanups.splice(0)) await cleanup() - vi.useRealTimers() - vi.restoreAllMocks() -}) - -async function fixture() { - const h = await createPushServerHarness() - const token = await h.signIn(createPushHostKeypair(31)) - const registrationId = await h.registerAndroid(token) - let stop = async () => {} - cleanups.push(async () => { - await stop() - await h.close() - }) - vi.useFakeTimers() - return { - ...h, - registrationId, - start: () => { - stop = startPushBackground({ mode: 'active' }, h.server) - }, - send: (event = notification(), ids = [registrationId]) => - h.post('/v1/send', { v: 1, registrationIds: ids, notification: event }, token), - invalid: () => h.post('/v1/send', { v: 1 }, token) - } -} - -it('delivers a committed send before the next poll without waiting in the HTTP handler', async () => { - const h = await fixture() - h.start() - const startedAt = Date.now() - const claim = h.server.deliveryStore.claim.bind(h.server.deliveryStore) - const release = Promise.withResolvers() - vi.spyOn(h.server.deliveryStore, 'claim').mockImplementation(async () => { - await release.promise - return claim() - }) - try { - const response = await h.send() - expect(await response.json()).toEqual({ - results: [{ registrationId: h.registrationId, status: 'queued' }] - }) - expect(h.fcmRequests).toHaveLength(0) - release.resolve() - await vi.waitFor(() => expect(h.fcmRequests).toHaveLength(1)) - expect(Date.now() - startedAt).toBeLessThan(1000) - expect(JSON.parse(h.fcmRequests[0]!.body).message.data.notificationSeq).toBe('1') - } finally { - release.resolve() - } -}) - -it('keeps concurrent accepted retries idempotent while automatic delivery runs', async () => { - const h = await fixture() - h.start() - await Promise.all(Array.from({ length: 10 }, () => h.send())) - await vi.waitFor(() => expect(h.fcmRequests).toHaveLength(1)) - await h.send() - await h.server.worker.runDue() - expect(h.fcmRequests).toHaveLength(1) - expect(await h.server.deliveryStore.pendingCount(h.registrationId)).toBe(0) -}) - -it('does not wake for invalid, unowned or dead registrations', async () => { - const h = await fixture() - h.start() - const wake = vi.spyOn(h.server.worker, 'wake') - expect((await h.invalid()).status).toBe(400) - expect(await (await h.send(notification(), ['unknown'])).json()).toEqual({ - results: [{ registrationId: 'unknown', status: 'error' }] - }) - const device = await h.server.devices.findById(h.registrationId) - if (!device) throw new Error('registration missing') - await h.server.devices.markDead(device) - expect(await (await h.send()).json()).toEqual({ - results: [{ registrationId: h.registrationId, status: 'dead' }] - }) - expect(wake).not.toHaveBeenCalled() - expect(h.fcmRequests).toHaveLength(0) -}) - -it.each(['queued', 'sent'] as const)( - 'preserves dismissal of an already %s alert', - async (phase) => { - const h = await fixture() - if (phase === 'sent') h.start() - await h.send() - if (phase === 'sent') await vi.waitFor(() => expect(h.fcmRequests).toHaveLength(1)) - await h.send(notification({ kind: 'dismiss', notificationSeq: 2, sound: false })) - if (phase === 'queued') { - h.start() - await vi.advanceTimersByTimeAsync(1000) - } - await vi.waitFor(() => expect(h.fcmRequests).toHaveLength(phase === 'sent' ? 2 : 1)) - const last = h.fcmRequests.at(-1) - if (!last) throw new Error('dismissal missing') - const message = JSON.parse(last.body).message - expect(message.data.kind).toBe('dismiss') - expect(message.data.notificationId).toBe('note-1') - expect(message.data.notificationSeq).toBe('2') - expect(message.data.title).toBeUndefined() - expect(message.data.sound).toBeUndefined() - } -) diff --git a/cloud/apps/push/src/push-server.ts b/cloud/apps/push/src/push-server.ts index a174a3994f1..5889f811df9 100644 --- a/cloud/apps/push/src/push-server.ts +++ b/cloud/apps/push/src/push-server.ts @@ -1,32 +1,42 @@ -import { PushAuthAdmission } from './push-auth-admission.js' +import { PushAuthAdmission } from './http/push-auth-admission.js' import { createAdaptorServer } from '@hono/node-server' +import { PUSH_LIMITS } from '@orca-cloud/push-contract/push-limits' +import { PushDeviceRegistrationRequestSchema } from '@orca-cloud/push-contract/device-registration-messages' import { - PUSH_LIMITS, - PushDeviceRegistrationRequestSchema, PushHostChallengeRequestSchema, - PushHostSessionRequestSchema, - PushSendRequestSchema, - type PushSendResult -} from '@orca-cloud/push-contract' + PushHostSessionRequestSchema +} from '@orca-cloud/push-contract/host-auth-messages' +import { PushSendRequestSchema, type PushSendResult } from '@orca-cloud/push-contract/send-messages' import { Hono, type MiddlewareHandler } from 'hono' import { bodyLimit } from 'hono/body-limit' -import { ApnsClient } from './apns-client.js' -import { createApnsHttp2Transport, type ApnsTransport } from './apns-http2-transport.js' -import { clientIpRateLimit, ClientIpRateLimiter, readClientIp } from './client-ip-rate-limit.js' -import { DurablePushStore } from './durable-push-store.js' -import { DurablePushWorker } from './durable-push-worker.js' +import { ApnsClient } from './providers/apns/apns-client.js' +import { + createApnsHttp2Transport, + type ApnsTransport +} from './providers/apns/apns-http2-transport.js' +import { + clientIpRateLimit, + ClientIpRateLimiter, + readClientIp +} from './http/client-ip-rate-limit.js' +import { DurablePushStore } from './delivery/durable-push-store.js' +import { DurablePushWorker } from './delivery/durable-push-worker.js' import type { PushConfig } from './config.js' -import { PushDeviceRegistryStore } from './device-registry-store.js' -import { createFcmAccessTokenProvider } from './fcm-access-token.js' -import { createFcmFetchTransport, FcmClient, type FcmTransport } from './fcm-client.js' -import { PushHostChallengeStore } from './host-challenge-store.js' -import { PushHostSessionStore } from './host-session-store.js' -import type { PushDatabase } from './push-database.js' -import { PushDispatcher } from './push-dispatcher.js' +import { PushDeviceRegistryStore } from './devices/device-registry-store.js' +import { createFcmAccessTokenProvider } from './providers/fcm/fcm-access-token.js' +import { + createFcmFetchTransport, + FcmClient, + type FcmTransport +} from './providers/fcm/fcm-client.js' +import { PushHostChallengeStore } from './host-auth/host-challenge-store.js' +import { PushHostSessionStore } from './host-auth/host-session-store.js' +import type { CloudDatabase as PushDatabase } from '@orca-cloud/cloud-database/cloud-database' +import { PushDispatcher } from './delivery/push-dispatcher.js' import { PushObservability } from './push-observability.js' -import { reserveRequestConnection } from './push-background-database.js' -import { createPushReadiness } from './push-readiness.js' -import { PushRequestDrain } from './push-request-drain.js' +import { reserveRequestConnection } from './database/push-background-database.js' +import { createPushReadiness } from './http/push-readiness.js' +import { PushRequestDrain } from './http/push-request-drain.js' export type PushServerOptions = { now?: () => number diff --git a/cloud/apps/push/src/push-validation.test.ts b/cloud/apps/push/src/push-validation.test.ts deleted file mode 100644 index afb6906e423..00000000000 --- a/cloud/apps/push/src/push-validation.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { loadPushConfig } from './config.js' -import { openPushDatabase } from './push-database.js' -import { createPushServer } from './push-server.js' -import { startPushBackground } from './push-background.js' - -it('fails closed on an invalid validation mode', () => { - for (const mode of ['typo', '', ' ']) { - expect(() => - loadPushConfig({ - ORCA_PUSH_FCM_PROJECT_ID: 'onorca-cloud', - ORCA_PUSH_PUBLIC_URL: 'https://push.onorca.dev', - ORCA_PUSH_MODE: mode - }) - ).toThrow() - } -}) - -const databaseUrl = process.env.ORCA_PUSH_TEST_DATABASE_URL -it.skipIf(!databaseUrl)( - 'validation cannot write PostgreSQL and starts no consumers or pruners', - async () => { - if (!process.env.CI && new URL(databaseUrl!).port !== '55440') - throw new Error('isolated_postgres_port_required') - const active = await openPushDatabase({ databaseUrl, dataDir: '' }) - const schema = `validation_${Date.now()}` - await active.query(`CREATE SCHEMA ${schema}`) - const isolatedUrl = new URL(databaseUrl!) - isolatedUrl.searchParams.set( - 'options', - `-c search_path=${schema} -c default_transaction_read_only=off` - ) - isolatedUrl.searchParams.set('host', isolatedUrl.hostname) - isolatedUrl.searchParams.set('port', isolatedUrl.port) - const hostlessUrl = `postgresql://${isolatedUrl.username}:${isolatedUrl.password}@${isolatedUrl.pathname}?${isolatedUrl.searchParams}` - const database = await openPushDatabase({ - databaseUrl: hostlessUrl, - dataDir: '', - readOnly: true - }) - const config = loadPushConfig({ - ORCA_PUSH_FCM_PROJECT_ID: 'onorca-cloud', - ORCA_PUSH_PUBLIC_URL: 'https://push.onorca.dev', - ORCA_PUSH_MODE: 'validation' - }) - const runtime = createPushServer(config, database) - let stop: (() => Promise) | undefined - try { - const [setting] = await database.query( - "SELECT current_setting('default_transaction_read_only') AS default_transaction_read_only" - ) - expect(setting!.default_transaction_read_only).toBe('on') - await expect( - database.query(`CREATE TABLE ${schema}.forbidden (id integer)`) - ).rejects.toMatchObject({ code: '25006' }) - // An empty schema stays empty: validation must not run startup DDL. - expect( - await active.query('SELECT tablename FROM pg_tables WHERE schemaname = ?', [schema]) - ).toEqual([]) - const calls = vi.spyOn(database, 'query') - const claim = vi.spyOn(runtime.deliveryStore, 'claim') - const send = vi.spyOn(runtime.worker, 'start') - vi.useFakeTimers() - stop = startPushBackground(config, runtime) - await vi.advanceTimersByTimeAsync(31 * 60_000) - expect(calls).not.toHaveBeenCalled() - expect(claim).not.toHaveBeenCalled() - expect(send).not.toHaveBeenCalled() - vi.useRealTimers() - expect(await (await runtime.app.request('/health')).json()).toMatchObject({ - mode: 'validation' - }) - expect((await runtime.app.request('/ready')).status).toBe(200) - expect((await runtime.app.request('/v1/host/challenge', { method: 'POST' })).status).toBe(503) - expect((await runtime.app.request('/v1/send', { method: 'POST' })).status).toBe(503) - expect(calls.mock.calls.map(([sql]) => sql)).toEqual(['SELECT 1 AS ready']) - await expect( - database.query('DELETE FROM public.push_challenges WHERE false') - ).rejects.toMatchObject({ code: '25006' }) - } finally { - vi.useRealTimers() - await stop?.() - runtime.closeTransports() - await database.close() - await active.query(`DROP SCHEMA ${schema} CASCADE`) - await active.close() - vi.restoreAllMocks() - } - } -) diff --git a/cloud/apps/push/src/sqlite-transaction-queue.test.ts b/cloud/apps/push/src/sqlite-transaction-queue.test.ts deleted file mode 100644 index 1ee5e8b3d52..00000000000 --- a/cloud/apps/push/src/sqlite-transaction-queue.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { DatabaseSync } from 'node:sqlite' -import { setImmediate } from 'node:timers/promises' -import { expect, it, vi } from 'vitest' -import { openPushDatabase } from './push-database.js' - -it('releases queued work and close after a SQLite transaction cannot acquire its lock', async () => { - const dataDir = mkdtempSync(join(tmpdir(), 'orca-push-sqlite-queue-')) - let connection: DatabaseSync | undefined - const prepare = DatabaseSync.prototype.prepare - // Keep the native handle reachable for cleanup even if a queue regression strands close(). - const capture = vi - .spyOn(DatabaseSync.prototype, 'prepare') - .mockImplementation(function (this: DatabaseSync, sql) { - connection = this - return prepare.call(this, sql) - }) - const database = await openPushDatabase({ dataDir }) - capture.mockRestore() - const blocker = new DatabaseSync(join(dataDir, 'orca-push.sqlite')) - try { - await database.query('CREATE TABLE queue_progress (value INTEGER)') - await database.query('INSERT INTO queue_progress VALUES (0)') - blocker.exec('BEGIN IMMEDIATE') - const operation = vi.fn(async () => undefined) - await expect(database.transaction(operation)).rejects.toThrow('database is locked') - let lockFailures = 0 - const blocked = Array.from({ length: 5 }, () => - database.transaction(operation).catch(() => { - lockFailures += 1 - }) - ) - await setImmediate() - expect(lockFailures).toBe(5) - await Promise.all(blocked) - expect(operation).not.toHaveBeenCalled() - blocker.exec('ROLLBACK') - let completed = 0 - const pending = Array.from({ length: 100 }, () => - database.transaction(async (transaction) => { - await transaction.query('UPDATE queue_progress SET value = value + 1') - completed += 1 - }) - ) - for (const request of pending) void request.catch(() => undefined) - await setImmediate() - expect(completed).toBe(100) - await Promise.all(pending) - expect(await database.query('SELECT value FROM queue_progress')).toEqual([{ value: 100 }]) - let closed = false - const closing = database.close().then(() => { - closed = true - }) - await setImmediate() - expect(closed).toBe(true) - await closing - } finally { - capture.mockRestore() - blocker.close() - if (connection?.isOpen) connection.close() - rmSync(dataDir, { recursive: true, force: true }) - } -}) - -it('does not roll back a transaction when BEGIN failed before taking ownership', async () => { - const dataDir = mkdtempSync(join(tmpdir(), 'orca-push-sqlite-owner-')) - let connection: DatabaseSync | undefined - const prepare = DatabaseSync.prototype.prepare - const capture = vi - .spyOn(DatabaseSync.prototype, 'prepare') - .mockImplementation(function (this: DatabaseSync, sql) { - connection = this - return prepare.call(this, sql) - }) - const database = await openPushDatabase({ dataDir }) - capture.mockRestore() - try { - await database.query('CREATE TABLE queue_owner (value INTEGER)') - await database.query('BEGIN IMMEDIATE') - await database.query('INSERT INTO queue_owner VALUES (7)') - await expect(database.transaction(async () => undefined)).rejects.toThrow( - 'cannot start a transaction within a transaction' - ) - expect(connection?.isTransaction).toBe(true) - let rows: unknown - void database.query('SELECT value FROM queue_owner').then((result) => { - rows = result - }) - await setImmediate() - expect(rows).toEqual([{ value: 7 }]) - await database.query('ROLLBACK') - expect(await database.query('SELECT value FROM queue_owner')).toEqual([]) - await database.close() - } finally { - capture.mockRestore() - if (connection?.isOpen) connection.close() - rmSync(dataDir, { recursive: true, force: true }) - } -}) diff --git a/cloud/packages/cloud-database/package.json b/cloud/packages/cloud-database/package.json index 206fd4f6f70..d51b8fb517b 100644 --- a/cloud/packages/cloud-database/package.json +++ b/cloud/packages/cloud-database/package.json @@ -1,10 +1,20 @@ { "name": "@orca-cloud/cloud-database", - "private": true, "version": "0.0.0", + "private": true, "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./cloud-database": { + "types": "./dist/cloud-database.d.ts", + "default": "./dist/cloud-database.js" + } + }, "scripts": { "build": "tsc -p tsconfig.build.json", "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"", diff --git a/cloud/packages/push-contract/package.json b/cloud/packages/push-contract/package.json index 558f8e970f3..29484abca8d 100644 --- a/cloud/packages/push-contract/package.json +++ b/cloud/packages/push-contract/package.json @@ -1,10 +1,40 @@ { "name": "@orca-cloud/push-contract", - "private": true, "version": "0.0.0", + "private": true, "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./device-registration-messages": { + "types": "./dist/device-registration-messages.d.ts", + "default": "./dist/device-registration-messages.js" + }, + "./host-auth-messages": { + "types": "./dist/host-auth-messages.d.ts", + "default": "./dist/host-auth-messages.js" + }, + "./push-host-proof-transcript": { + "types": "./dist/push-host-proof-transcript.d.ts", + "default": "./dist/push-host-proof-transcript.js" + }, + "./push-limits": { + "types": "./dist/push-limits.d.ts", + "default": "./dist/push-limits.js" + }, + "./send-messages": { + "types": "./dist/send-messages.d.ts", + "default": "./dist/send-messages.js" + }, + "./wire-scalars": { + "types": "./dist/wire-scalars.d.ts", + "default": "./dist/wire-scalars.js" + } + }, "scripts": { "build": "pnpm clean && tsc -p tsconfig.build.json", "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"", From b1106ba883d95ee14413da0e73af86ff575efeaa Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Wed, 11 Nov 2026 14:14:48 -0800 Subject: [PATCH 25/40] test: remove low-value suites, recorder snapshots, and repeated inputs (#41244) * test: remove weak recorder scenarios and arithmetic suites * test: remove low-value boundary suites and recorder cases * test: remove mock suites and trim repetitive boundary inputs * test: remove shallow provider and browser checks --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 6 - ...enerated-artifact-line-ending-pin.test.mjs | 18 +- .../native-chat-readability-local-repo.json | 83 -- .../native-chat-readability-refused.json | 77 -- .../native-chat-readability-remote-repo.json | 81 -- ...reate-terminal-agent-launched-as-chat.json | 209 ---- ...ession-create-terminal-agent-launched.json | 206 ---- ...n-create-terminal-diff-notes-launched.json | 230 ----- ...ate-terminal-diff-notes-not-delivered.json | 228 ----- ...minal-launches-an-agent-quick-command.json | 201 ---- ...ssion-create-terminal-replaces-active.json | 197 ---- ...-create-terminal-runs-a-quick-command.json | 201 ---- ...on-create-terminal-without-active-tab.json | 203 ---- .../session-diff-notes-load-refused.json | 80 -- .../goldens/session-diff-notes-loaded.json | 122 --- .../goldens/session-file-tab-read.json | 87 -- .../goldens/session-markdown-disk-read.json | 131 --- .../goldens/session-markdown-disk-served.json | 93 -- .../goldens/session-markdown-tab-read.json | 93 -- .../goldens/session-markdown-tab-refused.json | 83 -- .../goldens/session-tab-closed.json | 94 -- .../goldens/session-tab-rename.json | 97 -- .../goldens/session-tab-renamed.json | 97 -- mobile/rpc-foundation/pilot-scenarios.json | 963 ------------------ .../browser/browser-touch-geometry.test.ts | 88 +- .../workspace-option-values.test.ts | 22 - mobile/src/mock-server-account-state.test.ts | 63 -- .../mock-server-session-tabs-fixture.test.ts | 92 -- ...ck-server-terminal-fixture-routing.test.ts | 65 -- .../adapters/session-notes-mount-adapters.ts | 64 -- .../session-screen-read-mount-adapters.ts | 41 +- .../session-screen-tab-mount-adapters.ts | 27 +- .../session-terminal-create-mount-adapters.ts | 47 +- .../mutants/operation-mutations.ts | 20 - .../last-visited-worktree-repo.test.ts | 12 - .../worktree/workspace-filter-repos.test.ts | 27 - .../workspace-list-pinned-lineage.test.ts | 49 +- .../worktree/workspace-view-settings.test.ts | 14 - .../computer-use-linux/runtime_render_test.py | 171 ++-- native/wayland-clipboard/protocol_test.py | 22 +- .../status-hooks/hook-service.test.ts | 21 - .../opencode-text-task-session.test.ts | 30 +- src/main/pi/rpc/launch/rpc-launch.test.ts | 47 - src/main/pi/rpc/prompts/rpc-prompt.test.ts | 35 - ...edBrowserPagePane.failure-remount.test.tsx | 43 - .../host-guest/browser-page-metadata.test.ts | 78 +- .../editor/image-viewer-zoom.test.ts | 20 - .../feature-tip-modal-state.test.ts | 34 - .../github-project/GhAuthErrorHelp.test.ts | 30 - .../commit/component-gates.test.ts | 8 - .../sync/git-history-graph-svg.test.tsx | 14 - .../shortcuts/ShortcutFilterRail.test.ts | 31 - 52 files changed, 93 insertions(+), 5002 deletions(-) delete mode 100644 mobile/rpc-foundation/goldens/native-chat-readability-local-repo.json delete mode 100644 mobile/rpc-foundation/goldens/native-chat-readability-refused.json delete mode 100644 mobile/rpc-foundation/goldens/native-chat-readability-remote-repo.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-agent-launched-as-chat.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-agent-launched.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-launched.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-not-delivered.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-launches-an-agent-quick-command.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-replaces-active.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-runs-a-quick-command.json delete mode 100644 mobile/rpc-foundation/goldens/session-create-terminal-without-active-tab.json delete mode 100644 mobile/rpc-foundation/goldens/session-diff-notes-load-refused.json delete mode 100644 mobile/rpc-foundation/goldens/session-diff-notes-loaded.json delete mode 100644 mobile/rpc-foundation/goldens/session-file-tab-read.json delete mode 100644 mobile/rpc-foundation/goldens/session-markdown-disk-read.json delete mode 100644 mobile/rpc-foundation/goldens/session-markdown-disk-served.json delete mode 100644 mobile/rpc-foundation/goldens/session-markdown-tab-read.json delete mode 100644 mobile/rpc-foundation/goldens/session-markdown-tab-refused.json delete mode 100644 mobile/rpc-foundation/goldens/session-tab-closed.json delete mode 100644 mobile/rpc-foundation/goldens/session-tab-rename.json delete mode 100644 mobile/rpc-foundation/goldens/session-tab-renamed.json delete mode 100644 mobile/src/host-screen/workspace-option-values.test.ts delete mode 100644 mobile/src/mock-server-account-state.test.ts delete mode 100644 mobile/src/mock-server-session-tabs-fixture.test.ts delete mode 100644 mobile/src/mock-server-terminal-fixture-routing.test.ts delete mode 100644 src/main/pi/rpc/launch/rpc-launch.test.ts delete mode 100644 src/main/pi/rpc/prompts/rpc-prompt.test.ts delete mode 100644 src/renderer/src/components/editor/image-viewer-zoom.test.ts delete mode 100644 src/renderer/src/components/feature-tips/feature-tip-modal-state.test.ts delete mode 100644 src/renderer/src/components/github-project/GhAuthErrorHelp.test.ts delete mode 100644 src/renderer/src/components/right-sidebar/source-control/commit/component-gates.test.ts delete mode 100644 src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 532f628dabf..477db43ea47 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -2719,9 +2719,7 @@ "src/main/pi/managed-extensions/agent-status/agent-status-extension-session-change.test.ts": 613, "src/main/pi/managed-extensions/agent-status/agent-status-input-redaction.test.ts": 573, "src/main/pi/managed-extensions/agent-status/omp-model-command-source.test.ts": 640, - "src/main/pi/rpc/launch/rpc-launch.test.ts": 305, "src/main/pi/rpc/prompts/rpc-prompt-delivery.test.ts": 204, - "src/main/pi/rpc/prompts/rpc-prompt.test.ts": 228, "src/main/pi/rpc/rpc-session-rename.test.ts": 1172, "src/main/pi/rpc/rpc-session-startup.test.ts": 4955, "src/main/pi/rpc/rpc-turn-races.test.ts": 2191, @@ -4571,7 +4569,6 @@ "src/renderer/src/components/editor/image-png-export.chromium.test.ts": 212, "src/renderer/src/components/editor/image-png-export.test.ts": 50, "src/renderer/src/components/editor/image-viewer-zoom-ownership.test.tsx": 2268, - "src/renderer/src/components/editor/image-viewer-zoom.test.ts": 47, "src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-outputs.test.ts": 307, "src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-session-start-lifetime.test.ts": 140, "src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-session.test.ts": 180, @@ -4710,7 +4707,6 @@ "src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx": 1968, "src/renderer/src/components/emulator-pane/use-mobile-emulator-tab-intro-actions.test.tsx": 1828, "src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.test.tsx": 1093, - "src/renderer/src/components/feature-tips/feature-tip-modal-state.test.ts": 244, "src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx": 2028, "src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts": 466, "src/renderer/src/components/floating-terminal/floating-workspace-tab-reorder.test.ts": 2520, @@ -4720,7 +4716,6 @@ "src/renderer/src/components/github-item-dialog/load-item-details/use-github-item-dialog-details.test.tsx": 2850, "src/renderer/src/components/github-item-dialog/load-item-details/use-github-task-refresh.test.tsx": 1070, "src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.task-record.test.tsx": 1391, - "src/renderer/src/components/github-project/GhAuthErrorHelp.test.ts": 479, "src/renderer/src/components/github-project/ProjectBoard.test.tsx": 988, "src/renderer/src/components/github-project/github-project-picker-filter.test.ts": 53, "src/renderer/src/components/github-project/group-sort.test.ts": 75, @@ -5086,7 +5081,6 @@ "src/renderer/src/components/settings/runtime-environments/pairing/RuntimePairingGeneratorForm.test.tsx": 461, "src/renderer/src/components/settings/appearance/fonts/FontAutocomplete.test.tsx": 1202, "src/renderer/src/components/settings/form-controls/SettingsFormControls.segmented-control.test.tsx": 730, - "src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts": 273, "src/renderer/src/components/settings/shortcuts/ShortcutsPane.provenance.test.tsx": 2302, "src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.test.tsx": 744, "src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.test.tsx": 438, diff --git a/config/scripts/workspace-package-build/generated-artifact-line-ending-pin.test.mjs b/config/scripts/workspace-package-build/generated-artifact-line-ending-pin.test.mjs index 600d7c1f10a..05379ea2053 100644 --- a/config/scripts/workspace-package-build/generated-artifact-line-ending-pin.test.mjs +++ b/config/scripts/workspace-package-build/generated-artifact-line-ending-pin.test.mjs @@ -12,25 +12,11 @@ it('keeps byte-compared artifacts and source LF in an autocrlf checkout', () => const crlf = 'first\r\nsecond\r\n' const paths = new Map([ ['resources/skills/current-manifest.json', lf], - ['src/main/__snapshots__/example.test.ts.snap', lf], - ['src/renderer/src/example.tsx', lf], ['src/main/example.ts', lf], - ['config/scripts/example.mjs', lf], ['config/scripts/nested/deeper/example.mjs', lf], - ['skill-guides/example.md', lf], - ['skill-stubs/example.md', lf], - ['skill-stubs/_shared/example.md', lf], - ['skills/example/SKILL.md', lf], - ['src/cli/bundled-skill-guides.ts', lf], - ...['cmd', 'bat', 'ps1', 'nsh'].map((extension) => [`config/example.${extension}`, crlf]), + ['config/example.cmd', crlf], ['resources/skills-extra/example.json', crlf], - ['vendor/resources/skills/example.json', crlf], - ['scripts/example.mjs', crlf], - ['config/scripts-extra/example.mjs', crlf], - ['vendor/config/scripts/example.mjs', crlf], - ['config/scripts/example.mjsx', crlf], - ['src/main/runtime/__fixtures__/example.txt', crlf], - ['src/main/daemon/__fixtures__/pty-transcripts/example.txt', crlf] + ['src/main/runtime/__fixtures__/example.txt', crlf] ]) const git = (args) => execFileSync('git', args, { cwd: root, stdio: 'pipe' }) diff --git a/mobile/rpc-foundation/goldens/native-chat-readability-local-repo.json b/mobile/rpc-foundation/goldens/native-chat-readability-local-repo.json deleted file mode 100644 index 1e9dabb4988..00000000000 --- a/mobile/rpc-foundation/goldens/native-chat-readability-local-repo.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.native-chat-readability", - "family": "session.native-chat-readability", - "namedDeltas": [], - "values": { - "19b2979d7fc2": { - "name": "repo.list#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"repo.list\"}" - }, - "70e0675ab2a9": { - "name": "repo.list#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "repo.list" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "repos": [ - { - "connectionId": { - "$rpc": "null" - }, - "id": "repo-1" - } - ] - } - } - } - }, - "dcf89ce6b4ca": { - "readable": true, - "worktreeId": "repo-1::/w" - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "native-chat-readability-local-repo", - "checkpoints": [ - { - "id": "readable", - "observation": { - "sender": ["70e0675ab2a9"], - "payloads": ["19b2979d7fc2"], - "settlements": { - "mount": "eb79a9b3682a" - }, - "state": "dcf89ce6b4ca", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/native-chat-readability-refused.json b/mobile/rpc-foundation/goldens/native-chat-readability-refused.json deleted file mode 100644 index 406e4dd32ad..00000000000 --- a/mobile/rpc-foundation/goldens/native-chat-readability-refused.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.native-chat-readability", - "family": "session.native-chat-readability", - "namedDeltas": [], - "values": { - "0b8777edb86c": { - "readable": false, - "worktreeId": "repo-1::/w" - }, - "19b2979d7fc2": { - "name": "repo.list#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"repo.list\"}" - }, - "6a68d9e91bc8": { - "name": "repo.list#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "repo.list" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "internal", - "message": "Scan failed" - }, - "id": "frame-1", - "ok": false - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "native-chat-readability-refused", - "checkpoints": [ - { - "id": "unreadable", - "observation": { - "sender": ["6a68d9e91bc8"], - "payloads": ["19b2979d7fc2"], - "settlements": { - "mount": "eb79a9b3682a" - }, - "state": "0b8777edb86c", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/native-chat-readability-remote-repo.json b/mobile/rpc-foundation/goldens/native-chat-readability-remote-repo.json deleted file mode 100644 index 0bc701f4c35..00000000000 --- a/mobile/rpc-foundation/goldens/native-chat-readability-remote-repo.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.native-chat-readability", - "family": "session.native-chat-readability", - "namedDeltas": [], - "values": { - "0b8777edb86c": { - "readable": false, - "worktreeId": "repo-1::/w" - }, - "19b2979d7fc2": { - "name": "repo.list#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"repo.list\"}" - }, - "7023dde78391": { - "name": "repo.list#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "repo.list" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "repos": [ - { - "connectionId": "ssh-1", - "id": "repo-1" - } - ] - } - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "native-chat-readability-remote-repo", - "checkpoints": [ - { - "id": "unreadable", - "observation": { - "sender": ["7023dde78391"], - "payloads": ["19b2979d7fc2"], - "settlements": { - "mount": "eb79a9b3682a" - }, - "state": "0b8777edb86c", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-agent-launched-as-chat.json b/mobile/rpc-foundation/goldens/session-create-terminal-agent-launched-as-chat.json deleted file mode 100644 index 84d74e902ad..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-agent-launched-as-chat.json +++ /dev/null @@ -1,209 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "0dec6eece95b": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "claude", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "claude_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "$rpc": "undefined" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "outcome": { - "handle": "h-1", - "kind": "structured", - "sessionId": "claude_s1" - }, - "receipt": { - "detail": "Started a terminal agent.", - "mode": "structured", - "preferred": "structured", - "reason": "user_default" - }, - "worktreeId": "wt-1" - } - } - } - }, - "4e536fd51d5d": { - "name": "agent.launchReplay#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"agent.launchReplay\",\"params\":{\"agent\":\"claude\",\"operationId\":\"1767225600000-00000000000040008000000000000004\",\"target\":{\"kind\":\"existing\",\"worktree\":\"id:wt-1\"},\"paneKey\":\"00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002\",\"sessionId\":\"claude_00000000_0000_4000_8000_000000000003\"}}" - }, - "58c784334dd1": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": false, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": 5, - "surface": { - "handle": { - "$rpc": "null" - }, - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "claude_s1" - } - }, - "sessionTabs": [], - "terminals": [] - }, - "6248a3dd0710": { - "name": "fetch-session-tabs", - "ordinal": 3, - "value": {} - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "c7778ace6ed5": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "claude", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "claude_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "$rpc": "undefined" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "f6051f871c2d": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": { - "$rpc": "null" - }, - "surface": { - "handle": { - "$rpc": "null" - }, - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "claude_00000000_0000_4000_8000_000000000003" - } - }, - "sessionTabs": [], - "terminals": [] - } - }, - "recording": { - "scenario": "session-create-terminal-agent-launched-as-chat", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["c7778ace6ed5"], - "payloads": ["4e536fd51d5d"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "f6051f871c2d", - "effects": [] - } - }, - { - "id": "launched", - "observation": { - "sender": ["0dec6eece95b"], - "payloads": ["4e536fd51d5d"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "58c784334dd1", - "effects": ["6248a3dd0710"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["0dec6eece95b"], - "payloads": ["4e536fd51d5d"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "58c784334dd1", - "effects": ["6248a3dd0710"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-agent-launched.json b/mobile/rpc-foundation/goldens/session-create-terminal-agent-launched.json deleted file mode 100644 index 75413785de2..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-agent-launched.json +++ /dev/null @@ -1,206 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "4e536fd51d5d": { - "name": "agent.launchReplay#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"agent.launchReplay\",\"params\":{\"agent\":\"claude\",\"operationId\":\"1767225600000-00000000000040008000000000000004\",\"target\":{\"kind\":\"existing\",\"worktree\":\"id:wt-1\"},\"paneKey\":\"00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002\",\"sessionId\":\"claude_00000000_0000_4000_8000_000000000003\"}}" - }, - "5bc4a173d7eb": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": false, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": 5, - "surface": { - "handle": "terminal-1", - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "claude_00000000_0000_4000_8000_000000000003" - } - }, - "sessionTabs": [], - "terminals": [] - }, - "6248a3dd0710": { - "name": "fetch-session-tabs", - "ordinal": 3, - "value": {} - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "b686ad3ebac0": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "claude", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "claude_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "$rpc": "undefined" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "outcome": { - "handle": "terminal-1", - "kind": "terminal" - }, - "receipt": { - "detail": "Started a terminal agent.", - "mode": "terminal", - "preferred": "terminal", - "reason": "user_default" - }, - "worktreeId": "wt-1" - } - } - } - }, - "c7778ace6ed5": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "claude", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "claude_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "$rpc": "undefined" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "f6051f871c2d": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": { - "$rpc": "null" - }, - "surface": { - "handle": { - "$rpc": "null" - }, - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "claude_00000000_0000_4000_8000_000000000003" - } - }, - "sessionTabs": [], - "terminals": [] - } - }, - "recording": { - "scenario": "session-create-terminal-agent-launched", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["c7778ace6ed5"], - "payloads": ["4e536fd51d5d"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "f6051f871c2d", - "effects": [] - } - }, - { - "id": "launched", - "observation": { - "sender": ["b686ad3ebac0"], - "payloads": ["4e536fd51d5d"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "5bc4a173d7eb", - "effects": ["6248a3dd0710"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["b686ad3ebac0"], - "payloads": ["4e536fd51d5d"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "5bc4a173d7eb", - "effects": ["6248a3dd0710"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-launched.json b/mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-launched.json deleted file mode 100644 index 1eaf40e5c51..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-launched.json +++ /dev/null @@ -1,230 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "0e3a24adf091": { - "name": "toast", - "ordinal": 4, - "value": { - "durationMs": { - "$rpc": "null" - }, - "message": "Notes sent" - } - }, - "553cfc6cdea5": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": { - "$rpc": "null" - }, - "surface": { - "handle": { - "$rpc": "null" - }, - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003" - } - }, - "sessionTabs": [], - "terminals": [] - }, - "6248a3dd0710": { - "name": "fetch-session-tabs", - "ordinal": 3, - "value": {} - }, - "73449f52ee06": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": false, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": 5, - "surface": { - "handle": "terminal-1", - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003" - } - }, - "sessionTabs": [], - "terminals": [] - }, - "79b24f8555fe": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "codex", - "launchSource": "diff_notes_send", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "prompt": { - "delivery": "submit", - "text": "review these notes" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "timeoutMs": 90000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "outcome": { - "handle": "terminal-1", - "kind": "terminal" - }, - "prompt": { - "delivery": "submit", - "outcome": "handed-to-terminal" - }, - "receipt": { - "detail": "Started a terminal agent.", - "mode": "terminal", - "preferred": "terminal", - "reason": "user_default" - }, - "worktreeId": "wt-1" - } - } - } - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "ad660413fab0": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "codex", - "launchSource": "diff_notes_send", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "prompt": { - "delivery": "submit", - "text": "review these notes" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "timeoutMs": 90000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "e41ec8af1dfd": { - "name": "agent.launchReplay#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"agent.launchReplay\",\"params\":{\"agent\":\"codex\",\"operationId\":\"1767225600000-00000000000040008000000000000004\",\"target\":{\"kind\":\"existing\",\"worktree\":\"id:wt-1\"},\"prompt\":{\"text\":\"review these notes\",\"delivery\":\"submit\"},\"launchSource\":\"diff_notes_send\",\"paneKey\":\"00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002\",\"sessionId\":\"codex_00000000_0000_4000_8000_000000000003\"}}" - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-create-terminal-diff-notes-launched", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["ad660413fab0"], - "payloads": ["e41ec8af1dfd"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "553cfc6cdea5", - "effects": [] - } - }, - { - "id": "notes-sent", - "observation": { - "sender": ["79b24f8555fe"], - "payloads": ["e41ec8af1dfd"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "73449f52ee06", - "effects": ["6248a3dd0710", "0e3a24adf091"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["79b24f8555fe"], - "payloads": ["e41ec8af1dfd"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "73449f52ee06", - "effects": ["6248a3dd0710", "0e3a24adf091"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-not-delivered.json b/mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-not-delivered.json deleted file mode 100644 index c658d151a50..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-diff-notes-not-delivered.json +++ /dev/null @@ -1,228 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "553cfc6cdea5": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": { - "$rpc": "null" - }, - "surface": { - "handle": { - "$rpc": "null" - }, - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003" - } - }, - "sessionTabs": [], - "terminals": [] - }, - "6248a3dd0710": { - "name": "fetch-session-tabs", - "ordinal": 3, - "value": {} - }, - "73449f52ee06": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": false, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "kind": "launched", - "lock": "mobile-create:mjuohs00-8ig2hens", - "snapshotsLeft": 5, - "surface": { - "handle": "terminal-1", - "pane": { - "leafId": "00000000-0000-4000-8000-000000000002", - "tabId": "00000000-0000-4000-8000-000000000001" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003" - } - }, - "sessionTabs": [], - "terminals": [] - }, - "776182f604c7": { - "name": "toast", - "ordinal": 4, - "value": { - "durationMs": 2400, - "message": "The agent started, but the notes weren't sent." - } - }, - "8f06d46b0825": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "codex", - "launchSource": "diff_notes_send", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "prompt": { - "delivery": "submit", - "text": "review these notes" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "timeoutMs": 90000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "outcome": { - "handle": "terminal-1", - "kind": "terminal" - }, - "prompt": { - "delivery": "submit", - "outcome": "not-delivered" - }, - "receipt": { - "detail": "Started a terminal agent.", - "mode": "terminal", - "preferred": "terminal", - "reason": "user_default" - }, - "worktreeId": "wt-1" - } - } - } - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "ad660413fab0": { - "name": "agent.launchReplay#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "agent.launchReplay" - }, - { - "name": "params", - "value": { - "agent": "codex", - "launchSource": "diff_notes_send", - "operationId": "1767225600000-00000000000040008000000000000004", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "prompt": { - "delivery": "submit", - "text": "review these notes" - }, - "sessionId": "codex_00000000_0000_4000_8000_000000000003", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - } - } - }, - { - "name": "options", - "value": { - "timeoutMs": 90000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "e41ec8af1dfd": { - "name": "agent.launchReplay#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"agent.launchReplay\",\"params\":{\"agent\":\"codex\",\"operationId\":\"1767225600000-00000000000040008000000000000004\",\"target\":{\"kind\":\"existing\",\"worktree\":\"id:wt-1\"},\"prompt\":{\"text\":\"review these notes\",\"delivery\":\"submit\"},\"launchSource\":\"diff_notes_send\",\"paneKey\":\"00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002\",\"sessionId\":\"codex_00000000_0000_4000_8000_000000000003\"}}" - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-create-terminal-diff-notes-not-delivered", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["ad660413fab0"], - "payloads": ["e41ec8af1dfd"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "553cfc6cdea5", - "effects": [] - } - }, - { - "id": "notes-kept", - "observation": { - "sender": ["8f06d46b0825"], - "payloads": ["e41ec8af1dfd"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "73449f52ee06", - "effects": ["6248a3dd0710", "776182f604c7"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["8f06d46b0825"], - "payloads": ["e41ec8af1dfd"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "73449f52ee06", - "effects": ["6248a3dd0710", "776182f604c7"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-launches-an-agent-quick-command.json b/mobile/rpc-foundation/goldens/session-create-terminal-launches-an-agent-quick-command.json deleted file mode 100644 index 096a2f8c2f7..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-launches-an-agent-quick-command.json +++ /dev/null @@ -1,201 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "27c32960f51e": { - "name": "session.tabs.createTerminal#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"session.tabs.createTerminal\",\"params\":{\"worktree\":\"id:wt-1\",\"afterTabId\":\"tab-0\",\"clientMutationId\":\"mobile-create:mjuohs00-8ig2hens\",\"agentPrompt\":\"summarize the diff\",\"agent\":\"claude\",\"activate\":false,\"select\":true,\"navigation\":\"caller\"}}" - }, - "3166a9d93c25": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": "tab-0", - "agent": "claude", - "agentPrompt": "summarize the diff", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "navigation": "caller", - "select": true, - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "3225d4a6ece6": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": "tab-0", - "agent": "claude", - "agentPrompt": "summarize the diff", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "navigation": "caller", - "select": true, - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "tab": { - "id": "tab-1", - "isActive": true, - "terminal": "terminal-1", - "title": "zsh", - "type": "terminal" - } - } - } - } - }, - "4d318de3b635": { - "name": "unsubscribe-terminal", - "ordinal": 3, - "value": { - "handle": "terminal-0" - } - }, - "4e377b1c4bf7": { - "activeHandle": "terminal-1", - "activeSessionTabId": "tab-1", - "createError": "", - "creating": false, - "initializedHandles": [], - "pendingSelection": { - "handle": "terminal-1", - "kind": "terminal", - "tabId": "tab-1" - }, - "sessionTabs": ["tab-1"], - "terminals": ["terminal-1"] - }, - "6275ace50da2": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "$rpc": "null" - }, - "sessionTabs": [], - "terminals": [] - }, - "7a53e88025f0": { - "name": "fetch-session-tabs", - "ordinal": 6, - "value": {} - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "c9f8d8917777": { - "name": "subscribe-terminal", - "ordinal": 4, - "value": { - "handle": "terminal-1" - } - }, - "e458e239d53c": { - "name": "schedule-delayed-action", - "ordinal": 5, - "value": { - "delayMs": 500 - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-create-terminal-launches-an-agent-quick-command", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["3166a9d93c25"], - "payloads": ["27c32960f51e"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "6275ace50da2", - "effects": [] - } - }, - { - "id": "created", - "observation": { - "sender": ["3225d4a6ece6"], - "payloads": ["27c32960f51e"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["3225d4a6ece6"], - "payloads": ["27c32960f51e"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c", "7a53e88025f0"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-replaces-active.json b/mobile/rpc-foundation/goldens/session-create-terminal-replaces-active.json deleted file mode 100644 index c959113bd59..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-replaces-active.json +++ /dev/null @@ -1,197 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "2977cbddd89f": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": "tab-0", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "navigation": "caller", - "select": true, - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "tab": { - "id": "tab-1", - "isActive": true, - "terminal": "terminal-1", - "title": "zsh", - "type": "terminal" - } - } - } - } - }, - "4d318de3b635": { - "name": "unsubscribe-terminal", - "ordinal": 3, - "value": { - "handle": "terminal-0" - } - }, - "4e377b1c4bf7": { - "activeHandle": "terminal-1", - "activeSessionTabId": "tab-1", - "createError": "", - "creating": false, - "initializedHandles": [], - "pendingSelection": { - "handle": "terminal-1", - "kind": "terminal", - "tabId": "tab-1" - }, - "sessionTabs": ["tab-1"], - "terminals": ["terminal-1"] - }, - "6275ace50da2": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "$rpc": "null" - }, - "sessionTabs": [], - "terminals": [] - }, - "7a53e88025f0": { - "name": "fetch-session-tabs", - "ordinal": 6, - "value": {} - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "b1d637072fc8": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": "tab-0", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "navigation": "caller", - "select": true, - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "c9f8d8917777": { - "name": "subscribe-terminal", - "ordinal": 4, - "value": { - "handle": "terminal-1" - } - }, - "cce8a731064a": { - "name": "session.tabs.createTerminal#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"session.tabs.createTerminal\",\"params\":{\"worktree\":\"id:wt-1\",\"afterTabId\":\"tab-0\",\"clientMutationId\":\"mobile-create:mjuohs00-8ig2hens\",\"activate\":false,\"select\":true,\"navigation\":\"caller\"}}" - }, - "e458e239d53c": { - "name": "schedule-delayed-action", - "ordinal": 5, - "value": { - "delayMs": 500 - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-create-terminal-replaces-active", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["b1d637072fc8"], - "payloads": ["cce8a731064a"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "6275ace50da2", - "effects": [] - } - }, - { - "id": "created", - "observation": { - "sender": ["2977cbddd89f"], - "payloads": ["cce8a731064a"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["2977cbddd89f"], - "payloads": ["cce8a731064a"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c", "7a53e88025f0"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-runs-a-quick-command.json b/mobile/rpc-foundation/goldens/session-create-terminal-runs-a-quick-command.json deleted file mode 100644 index d4560d11b1c..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-runs-a-quick-command.json +++ /dev/null @@ -1,201 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "4d318de3b635": { - "name": "unsubscribe-terminal", - "ordinal": 3, - "value": { - "handle": "terminal-0" - } - }, - "4e377b1c4bf7": { - "activeHandle": "terminal-1", - "activeSessionTabId": "tab-1", - "createError": "", - "creating": false, - "initializedHandles": [], - "pendingSelection": { - "handle": "terminal-1", - "kind": "terminal", - "tabId": "tab-1" - }, - "sessionTabs": ["tab-1"], - "terminals": ["terminal-1"] - }, - "57f5d12210c7": { - "name": "session.tabs.createTerminal#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"session.tabs.createTerminal\",\"params\":{\"worktree\":\"id:wt-1\",\"afterTabId\":\"tab-0\",\"clientMutationId\":\"mobile-create:mjuohs00-8ig2hens\",\"command\":\"pnpm test\",\"startupCommandDelivery\":\"shell-ready\",\"activate\":false,\"select\":true,\"navigation\":\"caller\"}}" - }, - "6275ace50da2": { - "activeHandle": "terminal-0", - "activeSessionTabId": "tab-0", - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "$rpc": "null" - }, - "sessionTabs": [], - "terminals": [] - }, - "7a53e88025f0": { - "name": "fetch-session-tabs", - "ordinal": 6, - "value": {} - }, - "87e43dbf0e1e": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": "tab-0", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "command": "pnpm test", - "navigation": "caller", - "select": true, - "startupCommandDelivery": "shell-ready", - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "tab": { - "id": "tab-1", - "isActive": true, - "terminal": "terminal-1", - "title": "zsh", - "type": "terminal" - } - } - } - } - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "c9f8d8917777": { - "name": "subscribe-terminal", - "ordinal": 4, - "value": { - "handle": "terminal-1" - } - }, - "dbd0992ab33b": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": "tab-0", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "command": "pnpm test", - "navigation": "caller", - "select": true, - "startupCommandDelivery": "shell-ready", - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "e458e239d53c": { - "name": "schedule-delayed-action", - "ordinal": 5, - "value": { - "delayMs": 500 - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-create-terminal-runs-a-quick-command", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["dbd0992ab33b"], - "payloads": ["57f5d12210c7"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "6275ace50da2", - "effects": [] - } - }, - { - "id": "created", - "observation": { - "sender": ["87e43dbf0e1e"], - "payloads": ["57f5d12210c7"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["87e43dbf0e1e"], - "payloads": ["57f5d12210c7"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c", "7a53e88025f0"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-create-terminal-without-active-tab.json b/mobile/rpc-foundation/goldens/session-create-terminal-without-active-tab.json deleted file mode 100644 index ee7b03676cb..00000000000 --- a/mobile/rpc-foundation/goldens/session-create-terminal-without-active-tab.json +++ /dev/null @@ -1,203 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.create-terminal", - "family": "session.create-terminal", - "namedDeltas": [], - "values": { - "246e4444bf16": { - "name": "session.tabs.createTerminal#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"session.tabs.createTerminal\",\"params\":{\"worktree\":\"id:wt-1\",\"clientMutationId\":\"mobile-create:mjuohs00-8ig2hens\",\"activate\":false,\"select\":true,\"navigation\":\"caller\"}}" - }, - "4d318de3b635": { - "name": "unsubscribe-terminal", - "ordinal": 3, - "value": { - "handle": "terminal-0" - } - }, - "4e377b1c4bf7": { - "activeHandle": "terminal-1", - "activeSessionTabId": "tab-1", - "createError": "", - "creating": false, - "initializedHandles": [], - "pendingSelection": { - "handle": "terminal-1", - "kind": "terminal", - "tabId": "tab-1" - }, - "sessionTabs": ["tab-1"], - "terminals": ["terminal-1"] - }, - "5ab2dfc4122d": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": { - "$rpc": "undefined" - }, - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "navigation": "caller", - "select": true, - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "7a53e88025f0": { - "name": "fetch-session-tabs", - "ordinal": 6, - "value": {} - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "c9f8d8917777": { - "name": "subscribe-terminal", - "ordinal": 4, - "value": { - "handle": "terminal-1" - } - }, - "d553e9003a7d": { - "name": "session.tabs.createTerminal#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.createTerminal" - }, - { - "name": "params", - "value": { - "activate": false, - "afterTabId": { - "$rpc": "undefined" - }, - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "navigation": "caller", - "select": true, - "worktree": "id:wt-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "tab": { - "id": "tab-1", - "isActive": true, - "terminal": "terminal-1", - "title": "zsh", - "type": "terminal" - } - } - } - } - }, - "dbfef1b09c9f": { - "activeHandle": "terminal-0", - "activeSessionTabId": { - "$rpc": "null" - }, - "createError": "", - "creating": true, - "initializedHandles": ["terminal-0"], - "pendingSelection": { - "$rpc": "null" - }, - "sessionTabs": [], - "terminals": [] - }, - "e458e239d53c": { - "name": "schedule-delayed-action", - "ordinal": 5, - "value": { - "delayMs": 500 - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-create-terminal-without-active-tab", - "checkpoints": [ - { - "id": "creating", - "observation": { - "sender": ["5ab2dfc4122d"], - "payloads": ["246e4444bf16"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "9270aeb7d9c6" - }, - "state": "dbfef1b09c9f", - "effects": [] - } - }, - { - "id": "created", - "observation": { - "sender": ["d553e9003a7d"], - "payloads": ["246e4444bf16"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c"] - } - }, - { - "id": "tabs-refreshed", - "observation": { - "sender": ["d553e9003a7d"], - "payloads": ["246e4444bf16"], - "settlements": { - "mount": "eb79a9b3682a", - "create": "eb79a9b3682a" - }, - "state": "4e377b1c4bf7", - "effects": ["4d318de3b635", "c9f8d8917777", "e458e239d53c", "7a53e88025f0"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-diff-notes-load-refused.json b/mobile/rpc-foundation/goldens/session-diff-notes-load-refused.json deleted file mode 100644 index a77512d0b4b..00000000000 --- a/mobile/rpc-foundation/goldens/session-diff-notes-load-refused.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.diff-notes", - "family": "session.diff-notes", - "namedDeltas": [], - "values": { - "270b4ca66aa7": { - "name": "worktree.show#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:workspace-1\"}}" - }, - "432aeb4f1709": { - "busy": false, - "diffComments": [], - "pendingDelivery": { - "$rpc": "null" - } - }, - "52ec1b835753": { - "name": "worktree.show#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "worktree.show" - }, - { - "name": "params", - "value": { - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "worktree_not_found", - "message": "No such workspace" - }, - "id": "frame-1", - "ok": false - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-diff-notes-load-refused", - "checkpoints": [ - { - "id": "unchanged", - "observation": { - "sender": ["52ec1b835753"], - "payloads": ["270b4ca66aa7"], - "settlements": { - "mount": "eb79a9b3682a" - }, - "state": "432aeb4f1709", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-diff-notes-loaded.json b/mobile/rpc-foundation/goldens/session-diff-notes-loaded.json deleted file mode 100644 index 6ef5fae55a0..00000000000 --- a/mobile/rpc-foundation/goldens/session-diff-notes-loaded.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.diff-notes", - "family": "session.diff-notes", - "namedDeltas": [], - "values": { - "194b8cd56a74": { - "name": "worktree.show#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "worktree.show" - }, - { - "name": "params", - "value": { - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "worktree": { - "diffComments": [ - { - "body": "needs a test", - "createdAt": 0, - "filePath": "src/app.ts", - "id": "note-1", - "lineNumber": 4, - "worktreeId": "workspace-1" - } - ] - } - } - } - } - }, - "270b4ca66aa7": { - "name": "worktree.show#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:workspace-1\"}}" - }, - "e28b1ad79121": { - "busy": false, - "diffComments": [ - { - "body": "needs a test", - "createdAt": 0, - "diffIdentity": { - "$rpc": "undefined" - }, - "filePath": "src/app.ts", - "id": "note-1", - "lineNumber": 4, - "oldPath": { - "$rpc": "undefined" - }, - "scope": { - "$rpc": "undefined" - }, - "selectedText": { - "$rpc": "undefined" - }, - "sentAt": { - "$rpc": "undefined" - }, - "side": "modified", - "source": "diff", - "startLine": { - "$rpc": "undefined" - }, - "updatedAt": { - "$rpc": "undefined" - }, - "worktreeId": "workspace-1" - } - ], - "pendingDelivery": { - "$rpc": "null" - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-diff-notes-loaded", - "checkpoints": [ - { - "id": "loaded", - "observation": { - "sender": ["194b8cd56a74"], - "payloads": ["270b4ca66aa7"], - "settlements": { - "mount": "eb79a9b3682a" - }, - "state": "e28b1ad79121", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-file-tab-read.json b/mobile/rpc-foundation/goldens/session-file-tab-read.json deleted file mode 100644 index 2581381e00b..00000000000 --- a/mobile/rpc-foundation/goldens/session-file-tab-read.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-documents", - "family": "session.tab-documents", - "namedDeltas": [], - "values": { - "023c5158861a": { - "name": "files.read#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "files.read" - }, - { - "name": "params", - "value": { - "relativePath": "src/app.ts", - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "byteLength": 2, - "content": "a\n", - "truncated": false - } - } - } - }, - "5ea03f95e781": { - "file": { - "tab-file": { - "byteLength": 2, - "content": "a\n", - "kind": "file", - "status": "ready", - "truncated": false - } - }, - "markdown": {} - }, - "c59b180ead68": { - "name": "files.read#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"files.read\",\"params\":{\"worktree\":\"id:workspace-1\",\"relativePath\":\"src/app.ts\"}}" - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-file-tab-read", - "checkpoints": [ - { - "id": "read", - "observation": { - "sender": ["023c5158861a"], - "payloads": ["c59b180ead68"], - "settlements": { - "file": "eb79a9b3682a" - }, - "state": "5ea03f95e781", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-markdown-disk-read.json b/mobile/rpc-foundation/goldens/session-markdown-disk-read.json deleted file mode 100644 index a0a1babc809..00000000000 --- a/mobile/rpc-foundation/goldens/session-markdown-disk-read.json +++ /dev/null @@ -1,131 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-documents", - "family": "session.markdown-disk-fallback", - "namedDeltas": [], - "values": { - "44abbe2af7aa": { - "name": "markdown.readTab#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"markdown.readTab\",\"params\":{\"worktree\":\"id:workspace-1\",\"tabId\":\"tab-md\"}}" - }, - "c6cea5310098": { - "file": {}, - "markdown": { - "tab-md": { - "baseVersion": "", - "content": "# disk", - "editable": false, - "isDirty": false, - "localContent": "# disk", - "readOnlyReason": "Editing needs Orca desktop running.", - "stale": false, - "status": "ready" - } - } - }, - "d4be01606497": { - "name": "files.read#1", - "ordinal": 4, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"files.read\",\"params\":{\"worktree\":\"id:workspace-1\",\"relativePath\":\"docs/readme.md\"}}" - }, - "d59404d25d6c": { - "name": "files.read#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "files.read" - }, - { - "name": "params", - "value": { - "relativePath": "docs/readme.md", - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "byteLength": 6, - "content": "# disk", - "truncated": false - } - } - } - }, - "e258dafc91f1": { - "name": "markdown.readTab#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "markdown.readTab" - }, - { - "name": "params", - "value": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "renderer_unavailable", - "message": "Renderer unavailable" - }, - "id": "frame-1", - "ok": false - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-markdown-disk-read", - "checkpoints": [ - { - "id": "fell-back", - "observation": { - "sender": ["e258dafc91f1", "d59404d25d6c"], - "payloads": ["44abbe2af7aa", "d4be01606497"], - "settlements": { - "markdown": "eb79a9b3682a" - }, - "state": "c6cea5310098", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-markdown-disk-served.json b/mobile/rpc-foundation/goldens/session-markdown-disk-served.json deleted file mode 100644 index 44c9bca57df..00000000000 --- a/mobile/rpc-foundation/goldens/session-markdown-disk-served.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-documents", - "family": "session.markdown-disk-fallback", - "namedDeltas": [], - "values": { - "0d6b0adc036f": { - "name": "markdown.readTab#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "markdown.readTab" - }, - { - "name": "params", - "value": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "content": "# served", - "editable": true, - "isDirty": false, - "version": "v1" - } - } - } - }, - "3e3efaab3a20": { - "file": {}, - "markdown": { - "tab-md": { - "baseVersion": "v1", - "content": "# served", - "editable": true, - "isDirty": false, - "localContent": "# served", - "readOnlyReason": { - "$rpc": "undefined" - }, - "stale": false, - "status": "ready" - } - } - }, - "44abbe2af7aa": { - "name": "markdown.readTab#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"markdown.readTab\",\"params\":{\"worktree\":\"id:workspace-1\",\"tabId\":\"tab-md\"}}" - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-markdown-disk-served", - "checkpoints": [ - { - "id": "served", - "observation": { - "sender": ["0d6b0adc036f"], - "payloads": ["44abbe2af7aa"], - "settlements": { - "markdown": "eb79a9b3682a" - }, - "state": "3e3efaab3a20", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-markdown-tab-read.json b/mobile/rpc-foundation/goldens/session-markdown-tab-read.json deleted file mode 100644 index 474c47b7073..00000000000 --- a/mobile/rpc-foundation/goldens/session-markdown-tab-read.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-documents", - "family": "session.tab-documents", - "namedDeltas": [], - "values": { - "44abbe2af7aa": { - "name": "markdown.readTab#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"markdown.readTab\",\"params\":{\"worktree\":\"id:workspace-1\",\"tabId\":\"tab-md\"}}" - }, - "79f4c7ca7e69": { - "name": "markdown.readTab#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "markdown.readTab" - }, - { - "name": "params", - "value": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "content": "# a", - "editable": true, - "isDirty": false, - "version": "v1" - } - } - } - }, - "d4cf305b17f8": { - "file": {}, - "markdown": { - "tab-md": { - "baseVersion": "v1", - "content": "# a", - "editable": true, - "isDirty": false, - "localContent": "# a", - "readOnlyReason": { - "$rpc": "undefined" - }, - "stale": false, - "status": "ready" - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-markdown-tab-read", - "checkpoints": [ - { - "id": "read", - "observation": { - "sender": ["79f4c7ca7e69"], - "payloads": ["44abbe2af7aa"], - "settlements": { - "markdown": "eb79a9b3682a" - }, - "state": "d4cf305b17f8", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-markdown-tab-refused.json b/mobile/rpc-foundation/goldens/session-markdown-tab-refused.json deleted file mode 100644 index 4e6665a2750..00000000000 --- a/mobile/rpc-foundation/goldens/session-markdown-tab-refused.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-documents", - "family": "session.tab-documents", - "namedDeltas": [], - "values": { - "31e723411add": { - "name": "markdown.readTab#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "markdown.readTab" - }, - { - "name": "params", - "value": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "tab_not_found", - "message": "No such tab" - }, - "id": "frame-1", - "ok": false - } - } - }, - "44abbe2af7aa": { - "name": "markdown.readTab#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"markdown.readTab\",\"params\":{\"worktree\":\"id:workspace-1\",\"tabId\":\"tab-md\"}}" - }, - "877720375363": { - "file": {}, - "markdown": { - "tab-md": { - "message": "Couldn't load markdown", - "status": "error" - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-markdown-tab-refused", - "checkpoints": [ - { - "id": "errored", - "observation": { - "sender": ["31e723411add"], - "payloads": ["44abbe2af7aa"], - "settlements": { - "markdown": "eb79a9b3682a" - }, - "state": "877720375363", - "effects": [] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-tab-closed.json b/mobile/rpc-foundation/goldens/session-tab-closed.json deleted file mode 100644 index ec628250d87..00000000000 --- a/mobile/rpc-foundation/goldens/session-tab-closed.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-close", - "family": "session.tab-close-session", - "namedDeltas": [], - "values": { - "1195cdf08e57": { - "name": "unsubscribe-terminal", - "ordinal": 3, - "value": { - "handle": "terminal-1" - } - }, - "50a46af5cf5c": { - "name": "session.tabs.close#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"session.tabs.close\",\"params\":{\"worktree\":\"id:workspace-1\",\"tabId\":\"tab-1\",\"reason\":\"user\"}}" - }, - "567d11711027": { - "activeHandle": { - "$rpc": "null" - }, - "sessionTabs": [], - "terminals": [ - { - "handle": "terminal-1", - "isActive": true, - "title": "Terminal" - } - ] - }, - "de4cc94c0333": { - "name": "session.tabs.close#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "session.tabs.close" - }, - { - "name": "params", - "value": { - "reason": "user", - "tabId": "tab-1", - "worktree": "id:workspace-1" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "closed": true - } - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-tab-closed", - "checkpoints": [ - { - "id": "closed", - "observation": { - "sender": ["de4cc94c0333"], - "payloads": ["50a46af5cf5c"], - "settlements": { - "close-tab": "eb79a9b3682a" - }, - "state": "567d11711027", - "effects": ["1195cdf08e57"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-tab-rename.json b/mobile/rpc-foundation/goldens/session-tab-rename.json deleted file mode 100644 index c08b316a0ef..00000000000 --- a/mobile/rpc-foundation/goldens/session-tab-rename.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-close", - "family": "session.tab-close", - "namedDeltas": [], - "values": { - "0923ddf47a9b": { - "name": "fetch-terminals", - "ordinal": 3, - "value": {} - }, - "42b6d6d7fdf9": { - "activeHandle": "terminal-1", - "sessionTabs": [ - { - "id": "tab-1", - "isActive": true, - "terminal": "terminal-1", - "title": "Terminal", - "type": "terminal" - } - ], - "terminals": [ - { - "handle": "terminal-1", - "isActive": true, - "title": "build" - } - ] - }, - "7e43ade02444": { - "name": "terminal.rename#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"terminal.rename\",\"params\":{\"terminal\":\"terminal-1\",\"title\":\"build\"}}" - }, - "b6460631c63c": { - "name": "terminal.rename#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "terminal.rename" - }, - { - "name": "params", - "value": { - "terminal": "terminal-1", - "title": "build" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "renamed": true - } - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-tab-rename", - "checkpoints": [ - { - "id": "renamed", - "observation": { - "sender": ["b6460631c63c"], - "payloads": ["7e43ade02444"], - "settlements": { - "rename": "eb79a9b3682a" - }, - "state": "42b6d6d7fdf9", - "effects": ["0923ddf47a9b"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/goldens/session-tab-renamed.json b/mobile/rpc-foundation/goldens/session-tab-renamed.json deleted file mode 100644 index eefbd368b58..00000000000 --- a/mobile/rpc-foundation/goldens/session-tab-renamed.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "goldenFormatVersion": 6, - "operation": "session.tab-close", - "family": "session.tab-rename", - "namedDeltas": [], - "values": { - "0923ddf47a9b": { - "name": "fetch-terminals", - "ordinal": 3, - "value": {} - }, - "42b6d6d7fdf9": { - "activeHandle": "terminal-1", - "sessionTabs": [ - { - "id": "tab-1", - "isActive": true, - "terminal": "terminal-1", - "title": "Terminal", - "type": "terminal" - } - ], - "terminals": [ - { - "handle": "terminal-1", - "isActive": true, - "title": "build" - } - ] - }, - "7e43ade02444": { - "name": "terminal.rename#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"terminal.rename\",\"params\":{\"terminal\":\"terminal-1\",\"title\":\"build\"}}" - }, - "b6460631c63c": { - "name": "terminal.rename#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "terminal.rename" - }, - { - "name": "params", - "value": { - "terminal": "terminal-1", - "title": "build" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "renamed": true - } - } - } - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - } - }, - "recording": { - "scenario": "session-tab-renamed", - "checkpoints": [ - { - "id": "renamed", - "observation": { - "sender": ["b6460631c63c"], - "payloads": ["7e43ade02444"], - "settlements": { - "rename": "eb79a9b3682a" - }, - "state": "42b6d6d7fdf9", - "effects": ["0923ddf47a9b"] - } - } - ] - } -} diff --git a/mobile/rpc-foundation/pilot-scenarios.json b/mobile/rpc-foundation/pilot-scenarios.json index 44e47a4e043..ada2bc09b04 100644 --- a/mobile/rpc-foundation/pilot-scenarios.json +++ b/mobile/rpc-foundation/pilot-scenarios.json @@ -18699,38 +18699,6 @@ } ] }, - { - "id": "session-markdown-tab-read", - "operation": "session.tab-documents", - "family": "session.tab-documents", - "sites": ["mobile/src/files/session-documents/use-mobile-session-document-readers.ts"], - "schedules": [], - "steps": [ - { - "action": "markdown", - "id": "markdown" - }, - { - "complete": "markdown.readTab#1", - "params": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - }, - "reply": { - "ok": true, - "result": { - "content": "# a", - "version": "v1", - "isDirty": false, - "editable": true - } - } - }, - { - "checkpoint": "read" - } - ] - }, { "id": "session-markdown-tab-disk-fallback", "operation": "session.tab-documents", @@ -18776,67 +18744,6 @@ } ] }, - { - "id": "session-markdown-tab-refused", - "operation": "session.tab-documents", - "family": "session.tab-documents", - "sites": ["mobile/src/files/session-documents/use-mobile-session-document-readers.ts"], - "schedules": [], - "steps": [ - { - "action": "markdown", - "id": "markdown" - }, - { - "complete": "markdown.readTab#1", - "params": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - }, - "reply": { - "ok": false, - "error": { - "code": "tab_not_found", - "message": "No such tab" - } - } - }, - { - "checkpoint": "errored" - } - ] - }, - { - "id": "session-file-tab-read", - "operation": "session.tab-documents", - "family": "session.tab-documents", - "sites": ["mobile/src/files/session-documents/use-mobile-session-document-readers.ts"], - "schedules": [], - "steps": [ - { - "action": "file", - "id": "file" - }, - { - "complete": "files.read#1", - "params": { - "relativePath": "src/app.ts", - "worktree": "id:workspace-1" - }, - "reply": { - "ok": true, - "result": { - "content": "a\n", - "truncated": false, - "byteLength": 2 - } - } - }, - { - "checkpoint": "read" - } - ] - }, { "id": "session-terminal-list-merged", "operation": "session.terminal-inventory", @@ -18976,101 +18883,6 @@ } ] }, - { - "id": "native-chat-readability-local-repo", - "operation": "session.native-chat-readability", - "family": "session.native-chat-readability", - "sites": ["mobile/src/session/native-chat/transcript/use-mobile-native-chat-readability.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount" - }, - { - "complete": "repo.list#1", - "params": { - "$undefined": true - }, - "reply": { - "ok": true, - "result": { - "repos": [ - { - "id": "repo-1", - "connectionId": null - } - ] - } - } - }, - { - "checkpoint": "readable" - } - ] - }, - { - "id": "native-chat-readability-remote-repo", - "operation": "session.native-chat-readability", - "family": "session.native-chat-readability", - "sites": ["mobile/src/session/native-chat/transcript/use-mobile-native-chat-readability.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount" - }, - { - "complete": "repo.list#1", - "params": { - "$undefined": true - }, - "reply": { - "ok": true, - "result": { - "repos": [ - { - "id": "repo-1", - "connectionId": "ssh-1" - } - ] - } - } - }, - { - "checkpoint": "unreadable" - } - ] - }, - { - "id": "native-chat-readability-refused", - "operation": "session.native-chat-readability", - "family": "session.native-chat-readability", - "sites": ["mobile/src/session/native-chat/transcript/use-mobile-native-chat-readability.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount" - }, - { - "complete": "repo.list#1", - "params": { - "$undefined": true - }, - "reply": { - "ok": false, - "error": { - "code": "internal", - "message": "Scan failed" - } - } - }, - { - "checkpoint": "unreadable" - } - ] - }, { "id": "native-chat-stop-accepted", "operation": "session.native-chat-stop", @@ -19520,41 +19332,6 @@ } ] }, - { - "id": "session-tab-rename", - "operation": "session.tab-close", - "family": "session.tab-close", - "sites": ["mobile/src/session/tabs/use-mobile-session-close-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "rename", - "id": "rename", - "args": { - "title": "build" - } - }, - { - "complete": "terminal.rename#1", - "params": { - "terminal": "terminal-1", - "title": "build" - }, - "reply": { - "ok": true, - "result": { - "renamed": true - } - } - }, - { - "advance": 300 - }, - { - "checkpoint": "renamed" - } - ] - }, { "id": "session-tab-close-session-tab", "operation": "session.tab-close", @@ -19989,74 +19766,6 @@ } ] }, - { - "id": "session-diff-notes-loaded", - "operation": "session.diff-notes", - "family": "session.diff-notes", - "sites": ["mobile/src/source-control/review/use-mobile-session-diff-comments.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount" - }, - { - "complete": "worktree.show#1", - "params": { - "worktree": "id:workspace-1" - }, - "reply": { - "ok": true, - "result": { - "worktree": { - "diffComments": [ - { - "body": "needs a test", - "createdAt": 0, - "filePath": "src/app.ts", - "id": "note-1", - "lineNumber": 4, - "worktreeId": "workspace-1" - } - ] - } - } - } - }, - { - "checkpoint": "loaded" - } - ] - }, - { - "id": "session-diff-notes-load-refused", - "operation": "session.diff-notes", - "family": "session.diff-notes", - "sites": ["mobile/src/source-control/review/use-mobile-session-diff-comments.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount" - }, - { - "complete": "worktree.show#1", - "params": { - "worktree": "id:workspace-1" - }, - "reply": { - "ok": false, - "error": { - "code": "worktree_not_found", - "message": "No such workspace" - } - } - }, - { - "checkpoint": "unchanged" - } - ] - }, { "id": "session-markdown-saved", "operation": "session.markdown-save", @@ -23058,62 +22767,6 @@ } ] }, - { - "id": "session-create-terminal-replaces-active", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1", - "activeSessionTabId": "tab-0" - } - }, - { - "action": "create", - "id": "create" - }, - { - "checkpoint": "creating" - }, - { - "complete": "session.tabs.createTerminal#1", - "params": { - "worktree": "id:wt-1", - "afterTabId": "tab-0", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "activate": false, - "select": true, - "navigation": "caller" - }, - "reply": { - "ok": true, - "result": { - "tab": { - "type": "terminal", - "id": "tab-1", - "title": "zsh", - "terminal": "terminal-1", - "isActive": true - } - } - } - }, - { - "checkpoint": "created" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, { "id": "session-create-terminal-refused", "operation": "session.create-terminal", @@ -23218,189 +22871,6 @@ } ] }, - { - "id": "session-create-terminal-without-active-tab", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1" - } - }, - { - "action": "create", - "id": "create" - }, - { - "checkpoint": "creating" - }, - { - "complete": "session.tabs.createTerminal#1", - "params": { - "worktree": "id:wt-1", - "afterTabId": { - "$undefined": true - }, - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "activate": false, - "select": true, - "navigation": "caller" - }, - "reply": { - "ok": true, - "result": { - "tab": { - "type": "terminal", - "id": "tab-1", - "title": "zsh", - "terminal": "terminal-1", - "isActive": true - } - } - } - }, - { - "checkpoint": "created" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, - { - "id": "session-create-terminal-runs-a-quick-command", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1", - "activeSessionTabId": "tab-0" - } - }, - { - "action": "create", - "id": "create", - "args": { - "startupCommand": "pnpm test", - "startupCommandDelivery": "shell-ready", - "errorToast": "Couldn't run Tests" - } - }, - { - "checkpoint": "creating" - }, - { - "complete": "session.tabs.createTerminal#1", - "params": { - "worktree": "id:wt-1", - "afterTabId": "tab-0", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "command": "pnpm test", - "startupCommandDelivery": "shell-ready", - "activate": false, - "select": true, - "navigation": "caller" - }, - "reply": { - "ok": true, - "result": { - "tab": { - "type": "terminal", - "id": "tab-1", - "title": "zsh", - "terminal": "terminal-1", - "isActive": true - } - } - } - }, - { - "checkpoint": "created" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, - { - "id": "session-create-terminal-launches-an-agent-quick-command", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1", - "activeSessionTabId": "tab-0" - } - }, - { - "action": "create", - "id": "create", - "args": { - "agent": "claude", - "agentPrompt": "summarize the diff", - "errorToast": "Couldn't run Review" - } - }, - { - "checkpoint": "creating" - }, - { - "complete": "session.tabs.createTerminal#1", - "params": { - "worktree": "id:wt-1", - "afterTabId": "tab-0", - "clientMutationId": "mobile-create:mjuohs00-8ig2hens", - "agentPrompt": "summarize the diff", - "agent": "claude", - "activate": false, - "select": true, - "navigation": "caller" - }, - "reply": { - "ok": true, - "result": { - "tab": { - "type": "terminal", - "id": "tab-1", - "title": "zsh", - "terminal": "terminal-1", - "isActive": true - } - } - } - }, - { - "checkpoint": "created" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, { "id": "session-create-terminal-ignores-a-second-create-in-flight", "operation": "session.create-terminal", @@ -23473,297 +22943,6 @@ } ] }, - { - "id": "session-create-terminal-agent-launched", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1", - "activeSessionTabId": "tab-0", - "deviceToken": "device-token-1", - "agentLaunch": true - } - }, - { - "action": "create", - "id": "create", - "args": { - "agent": "claude" - } - }, - { - "checkpoint": "creating" - }, - { - "complete": "agent.launchReplay#1", - "params": { - "agent": "claude", - "operationId": "1767225600000-00000000000040008000000000000004", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - }, - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "claude_00000000_0000_4000_8000_000000000003" - }, - "reply": { - "ok": true, - "result": { - "outcome": { - "kind": "terminal", - "handle": "terminal-1" - }, - "worktreeId": "wt-1", - "receipt": { - "mode": "terminal", - "preferred": "terminal", - "reason": "user_default", - "detail": "Started a terminal agent." - } - } - } - }, - { - "checkpoint": "launched" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, - { - "id": "session-create-terminal-agent-launched-as-chat", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1", - "activeSessionTabId": "tab-0", - "deviceToken": "device-token-1", - "agentLaunch": true - } - }, - { - "action": "create", - "id": "create", - "args": { - "agent": "claude" - } - }, - { - "checkpoint": "creating" - }, - { - "complete": "agent.launchReplay#1", - "params": { - "agent": "claude", - "operationId": "1767225600000-00000000000040008000000000000004", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - }, - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "claude_00000000_0000_4000_8000_000000000003" - }, - "reply": { - "ok": true, - "result": { - "outcome": { - "kind": "structured", - "sessionId": "claude_s1", - "handle": "h-1" - }, - "worktreeId": "wt-1", - "receipt": { - "mode": "structured", - "preferred": "structured", - "reason": "user_default", - "detail": "Started a terminal agent." - } - } - } - }, - { - "checkpoint": "launched" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, - { - "id": "session-create-terminal-diff-notes-launched", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1", - "activeSessionTabId": "tab-0", - "deviceToken": "device-token-1", - "agentLaunch": true - } - }, - { - "action": "create", - "id": "create", - "args": { - "agent": "codex", - "initialPrompt": "review these notes", - "successToast": "Notes sent" - } - }, - { - "checkpoint": "creating" - }, - { - "complete": "agent.launchReplay#1", - "params": { - "agent": "codex", - "operationId": "1767225600000-00000000000040008000000000000004", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - }, - "prompt": { - "text": "review these notes", - "delivery": "submit" - }, - "launchSource": "diff_notes_send", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "codex_00000000_0000_4000_8000_000000000003" - }, - "reply": { - "ok": true, - "result": { - "outcome": { - "kind": "terminal", - "handle": "terminal-1" - }, - "worktreeId": "wt-1", - "receipt": { - "mode": "terminal", - "preferred": "terminal", - "reason": "user_default", - "detail": "Started a terminal agent." - }, - "prompt": { - "delivery": "submit", - "outcome": "handed-to-terminal" - } - } - } - }, - { - "checkpoint": "notes-sent" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, - { - "id": "session-create-terminal-diff-notes-not-delivered", - "operation": "session.create-terminal", - "family": "session.create-terminal", - "sites": ["mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "mount", - "id": "mount", - "args": { - "worktreeId": "wt-1", - "activeSessionTabId": "tab-0", - "deviceToken": "device-token-1", - "agentLaunch": true - } - }, - { - "action": "create", - "id": "create", - "args": { - "agent": "codex", - "initialPrompt": "review these notes", - "successToast": "Notes sent" - } - }, - { - "checkpoint": "creating" - }, - { - "complete": "agent.launchReplay#1", - "params": { - "agent": "codex", - "operationId": "1767225600000-00000000000040008000000000000004", - "target": { - "kind": "existing", - "worktree": "id:wt-1" - }, - "prompt": { - "text": "review these notes", - "delivery": "submit" - }, - "launchSource": "diff_notes_send", - "paneKey": "00000000-0000-4000-8000-000000000001:00000000-0000-4000-8000-000000000002", - "sessionId": "codex_00000000_0000_4000_8000_000000000003" - }, - "reply": { - "ok": true, - "result": { - "outcome": { - "kind": "terminal", - "handle": "terminal-1" - }, - "worktreeId": "wt-1", - "receipt": { - "mode": "terminal", - "preferred": "terminal", - "reason": "user_default", - "detail": "Started a terminal agent." - }, - "prompt": { - "delivery": "submit", - "outcome": "not-delivered" - } - } - } - }, - { - "checkpoint": "notes-kept" - }, - { - "advance": 500 - }, - { - "checkpoint": "tabs-refreshed" - } - ] - }, { "id": "session-terminal-display-mode-auto-take-floor", "operation": "session.terminal-display-mode", @@ -24463,71 +23642,6 @@ } ] }, - { - "id": "session-tab-renamed", - "operation": "session.tab-close", - "family": "session.tab-rename", - "sites": ["mobile/src/session/tabs/use-mobile-session-close-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "rename", - "id": "rename", - "args": { - "title": "build" - } - }, - { - "complete": "terminal.rename#1", - "params": { - "terminal": "terminal-1", - "title": "build" - }, - "reply": { - "ok": true, - "result": { - "renamed": true - } - } - }, - { - "advance": 300 - }, - { - "checkpoint": "renamed" - } - ] - }, - { - "id": "session-tab-closed", - "operation": "session.tab-close", - "family": "session.tab-close-session", - "sites": ["mobile/src/session/tabs/use-mobile-session-close-actions.ts"], - "schedules": [], - "steps": [ - { - "action": "close-tab", - "id": "close-tab" - }, - { - "complete": "session.tabs.close#1", - "params": { - "reason": "user", - "tabId": "tab-1", - "worktree": "id:workspace-1" - }, - "reply": { - "ok": true, - "result": { - "closed": true - } - } - }, - { - "checkpoint": "closed" - } - ] - }, { "id": "new-tab-local-agents", "operation": "settings.new-tab-agents", @@ -24691,83 +23805,6 @@ } ] }, - { - "id": "session-markdown-disk-read", - "operation": "session.tab-documents", - "family": "session.markdown-disk-fallback", - "sites": ["mobile/src/files/session-documents/use-mobile-session-document-readers.ts"], - "schedules": [], - "steps": [ - { - "action": "markdown", - "id": "markdown" - }, - { - "complete": "markdown.readTab#1", - "params": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - }, - "reply": { - "ok": false, - "error": { - "code": "renderer_unavailable", - "message": "Renderer unavailable" - } - } - }, - { - "complete": "files.read#1", - "params": { - "relativePath": "docs/readme.md", - "worktree": "id:workspace-1" - }, - "reply": { - "ok": true, - "result": { - "content": "# disk", - "truncated": false, - "byteLength": 6 - } - } - }, - { - "checkpoint": "fell-back" - } - ] - }, - { - "id": "session-markdown-disk-served", - "operation": "session.tab-documents", - "family": "session.markdown-disk-fallback", - "sites": ["mobile/src/files/session-documents/use-mobile-session-document-readers.ts"], - "schedules": [], - "steps": [ - { - "action": "markdown", - "id": "markdown" - }, - { - "complete": "markdown.readTab#1", - "params": { - "tabId": "tab-md", - "worktree": "id:workspace-1" - }, - "reply": { - "ok": true, - "result": { - "content": "# served", - "version": "v1", - "isDirty": false, - "editable": true - } - } - }, - { - "checkpoint": "served" - } - ] - }, { "id": "mobile-web-bundle-manifest-read", "operation": "mobileWeb.bundle-manifest", diff --git a/mobile/src/browser/browser-touch-geometry.test.ts b/mobile/src/browser/browser-touch-geometry.test.ts index affed95c4a4..465faf04826 100644 --- a/mobile/src/browser/browser-touch-geometry.test.ts +++ b/mobile/src/browser/browser-touch-geometry.test.ts @@ -1,11 +1,8 @@ import { describe, expect, it } from 'vitest' import { browserWheelDeltaFromScreen, - clampBrowserZoomState, computeBrowserFrameGeometry, - computeBrowserTouchClickRadiusCss, - mapScreenToBrowserPoint, - readLocalTouchPoint + mapScreenToBrowserPoint } from './browser-touch-geometry' const NO_ZOOM = { scale: 1, offsetX: 0, offsetY: 0 } @@ -21,28 +18,6 @@ const NO_VIEWPORT_META = { } describe('browser touch geometry', () => { - it('maps the visual center of a letterboxed desktop frame to the browser center', () => { - const layout = { width: 390, height: 700 } - const metadata = { deviceWidth: 1280, deviceHeight: 720 } - const geometry = computeBrowserFrameGeometry(layout, metadata) - - expect(geometry).toMatchObject({ - renderedWidth: 390, - offsetX: 0, - sourceWidth: 1280, - sourceHeight: 720 - }) - expect( - mapScreenToBrowserPoint( - 195, - geometry!.offsetY + geometry!.renderedHeight / 2, - layout, - metadata, - { scale: 1, offsetX: 0, offsetY: 0 } - ) - ).toEqual({ x: 640, y: 360 }) - }) - it('divides the frame device space by the page scale and adds no scroll offset', () => { const layout = { width: 400, height: 600 } const metadata = { @@ -56,31 +31,6 @@ describe('browser touch geometry', () => { expect(mapScreenToBrowserPoint(100, 200, layout, metadata, NO_ZOOM)).toEqual({ x: 200, y: 400 }) }) - it('reads a missing or unusable page scale as one rather than dividing by it', () => { - const layout = { width: 402, height: 593 } - for (const pageScaleFactor of [undefined, 0, -1, Number.NaN]) { - expect( - mapScreenToBrowserPoint( - 120, - 240, - layout, - { deviceWidth: 402, deviceHeight: 593, pageScaleFactor }, - NO_ZOOM - ) - ).toEqual({ x: 120, y: 240 }) - } - }) - - it('grows the touch radius by the page scale, because a CSS pixel is smaller', () => { - const layout = { width: 400, height: 600 } - const metadata = { deviceWidth: 400, deviceHeight: 600, pageScaleFactor: 0.5 } - - expect(computeBrowserTouchClickRadiusCss(layout, metadata, NO_ZOOM, 14)).toBe(28) - expect( - computeBrowserTouchClickRadiusCss(layout, { ...metadata, pageScaleFactor: 1 }, NO_ZOOM, 14) - ).toBe(14) - }) - it('scrolls the page by the page scale, not by the frame fit alone', () => { const layout = { width: 402, height: 593 } const geometry = computeBrowserFrameGeometry(layout, NO_VIEWPORT_META) @@ -93,40 +43,4 @@ describe('browser touch geometry', () => { // What it sent before: the screen delta itself, 41% of the scroll asked for. expect(delta.dy).not.toBe(-100) }) - - it('leaves a web view scroll and a pinched one where they were', () => { - const layout = { width: 402, height: 593 } - const unscaled = computeBrowserFrameGeometry(layout, { - deviceWidth: 402, - deviceHeight: 593, - pageScaleFactor: 1 - }) - - expect(browserWheelDeltaFromScreen(0, 100, unscaled, 1)).toEqual({ dx: 0, dy: -100 }) - // A pinch to 2x halves what a screen point is worth, on top of whatever the page scale is. - expect(browserWheelDeltaFromScreen(0, 100, unscaled, 2)).toEqual({ dx: 0, dy: -50 }) - expect(browserWheelDeltaFromScreen(-40, 0, null, 1)).toEqual({ dx: 40, dy: 0 }) - }) - - it('rejects page-level touch coordinates instead of mixing coordinate spaces', () => { - expect(readLocalTouchPoint({ pageX: 120, pageY: 240 })).toBeNull() - }) - - it('clamps zoom offsets after the viewport geometry changes', () => { - const nextGeometry = computeBrowserFrameGeometry( - { width: 390, height: 700 }, - { deviceWidth: 1280, deviceHeight: 720 } - )! - - const clamped = clampBrowserZoomState( - { scale: 3.5, offsetX: 300, offsetY: 500 }, - nextGeometry, - 1, - 3.5 - ) - - expect(clamped.scale).toBe(3.5) - expect(clamped.offsetX).toBe(300) - expect(clamped.offsetY).toBeCloseTo(33.90625) - }) }) diff --git a/mobile/src/host-screen/workspace-option-values.test.ts b/mobile/src/host-screen/workspace-option-values.test.ts deleted file mode 100644 index 659b83ce62a..00000000000 --- a/mobile/src/host-screen/workspace-option-values.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { choiceLabel, summarizeChecklist } from './workspace-option-values' - -describe('a checklist option value on the main sheet', () => { - it('reads all, none, the single checked item, or a count', () => { - expect(summarizeChecklist(['a', 'b', 'c'], 3, 'All hosts')).toBe('All hosts') - expect(summarizeChecklist([], 3, 'All')).toBe('None') - expect(summarizeChecklist(['m4 air'], 3, 'All hosts')).toBe('m4 air') - expect(summarizeChecklist(['a', 'b'], 3, 'All')).toBe('2 of 3') - }) -}) - -describe('a pick-one option value', () => { - it("reads the chosen choice's label, and nothing for an unknown id", () => { - const choices = [ - { id: 'name', label: 'Name' }, - { id: 'recent', label: 'Recent' } - ] - expect(choiceLabel(choices, 'recent')).toBe('Recent') - expect(choiceLabel(choices, 'newer-host-value')).toBe('') - }) -}) diff --git a/mobile/src/mock-server-account-state.test.ts b/mobile/src/mock-server-account-state.test.ts deleted file mode 100644 index 12ac948f4bf..00000000000 --- a/mobile/src/mock-server-account-state.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { - consumeMockCodexResetCredit, - createMockAccountsSnapshot, - getMockCodexResetScope, - resetMockAccountState, - selectMockCodexAccount -} from '../scripts/mock-server-account-state' - -const FIRST_OPERATION_ID = '11111111-1111-4111-8111-111111111111' - -describe('mock account reset state', () => { - beforeEach(() => { - resetMockAccountState(1_700_000_000_000) - }) - - it('keeps reset and expiry deadlines fixed between snapshots', () => { - const first = createMockAccountsSnapshot() - expect(first.rateLimits.codex.session?.resetsAt).toBe(1_700_005_400_000) - expect(first.rateLimits.codex.rateLimitResetCredits.nextExpiresAt).toBe(1_700_432_000_000) - const second = createMockAccountsSnapshot() - - expect(second.rateLimits.codex.session?.resetsAt).toBe(first.rateLimits.codex.session?.resetsAt) - expect(second.rateLimits.codex.rateLimitResetCredits.nextExpiresAt).toBe( - first.rateLimits.codex.rateLimitResetCredits.nextExpiresAt - ) - }) - - it('resets only the selected account and updates its visible usage', () => { - const personalScope = getMockCodexResetScope() - expect(personalScope).not.toBeNull() - - expect(consumeMockCodexResetCredit(FIRST_OPERATION_ID, personalScope)).toMatchObject({ - outcome: 'reset', - scope: personalScope - }) - const personalAfter = createMockAccountsSnapshot() - expect(personalAfter.rateLimits.codex.session?.usedPercent).toBe(0) - expect(personalAfter.rateLimits.codex.rateLimitResetCredits.availableCount).toBe(0) - - selectMockCodexAccount('codex-team') - const team = createMockAccountsSnapshot() - expect(team.rateLimits.codex.session?.usedPercent).toBe(100) - expect(team.rateLimits.codex.rateLimitResetCredits.availableCount).toBe(1) - expect(getMockCodexResetScope()?.accountId).toBe('codex-team') - }) - - it('replays the same operation result and authoritatively discards a stale attempt', () => { - const scope = getMockCodexResetScope() - expect(scope).not.toBeNull() - const first = consumeMockCodexResetCredit(FIRST_OPERATION_ID, scope) - expect(first).toEqual({ outcome: 'reset', scope }) - expect(consumeMockCodexResetCredit(FIRST_OPERATION_ID, scope)).toEqual(first) - - expect(() => consumeMockCodexResetCredit('not-a-uuid', scope)).toThrow('Invalid idempotencyKey') - expect(consumeMockCodexResetCredit('22222222-2222-4222-8222-222222222222', scope)).toEqual({ - status: 'rejectedBeforeProvider', - retryDisposition: 'discardAttempt', - reason: 'offerChanged', - scope - }) - }) -}) diff --git a/mobile/src/mock-server-session-tabs-fixture.test.ts b/mobile/src/mock-server-session-tabs-fixture.test.ts deleted file mode 100644 index 832be0fa611..00000000000 --- a/mobile/src/mock-server-session-tabs-fixture.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' -import type { WebSocket } from 'ws' -import type { - handleRequest as handleRpcRequest, - RpcRequest, - RpcResponse -} from '../scripts/mock-server-rpc-handlers' - -let handleRequest: typeof handleRpcRequest - -beforeAll(async () => { - vi.stubEnv('MOCK_NATIVE_CHAT', '0') - vi.stubEnv('MOCK_REPO_COUNT', '2') - vi.stubEnv('MOCK_WORKTREE_COUNT', '2') - vi.stubEnv('MOCK_RPC_DELAY_MS', '0') - for (const method of ['session.tabs.list', 'terminal.list']) { - vi.stubEnv(`MOCK_RPC_DELAY_${method.replaceAll('.', '_').toUpperCase()}_MS`, '0') - } - ;({ handleRequest } = await import('../scripts/mock-server-rpc-handlers')) -}) - -afterAll(() => vi.unstubAllEnvs()) - -function callRpc(method: string, params?: Record): RpcResponse { - let response: RpcResponse | undefined - const request: RpcRequest = { id: 'request-1', method, ...(params ? { params } : {}) } - handleRequest( - request, - (nextResponse) => { - response = nextResponse - }, - {} as WebSocket - ) - expect(response).toBeDefined() - return response! -} - -function listSessionTabs(worktree: string): RpcResponse { - return callRpc('session.tabs.list', { worktree }) -} - -describe('mock server session tabs fixture', () => { - it('returns a contract-complete terminal surface for the requested worktree', () => { - const response = listSessionTabs('id:repo-1::worktree-1') - - expect(response.result).toEqual({ - worktree: 'repo-1::worktree-1', - publicationEpoch: expect.stringMatching(/^mock-server:/), - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'tab-1::f47ac10b-58cc-4372-a567-0e02b2c3d479', - activeTabType: 'terminal', - tabGroups: [ - { - id: 'group-1', - activeTabId: 'tab-1', - tabOrder: ['tab-1'], - recentTabIds: ['tab-1'] - } - ], - tabs: [ - { - type: 'terminal', - id: 'tab-1::f47ac10b-58cc-4372-a567-0e02b2c3d479', - title: 'zsh', - parentTabId: 'tab-1', - leafId: 'f47ac10b-58cc-4372-a567-0e02b2c3d479', - status: 'ready', - terminal: 'term-1', - isActive: true - } - ] - }) - }) - - it('passes a bare worktree selector through unprefixed', () => { - const response = listSessionTabs('repo-1::worktree-1') - - expect((response.result as { worktree: string }).worktree).toBe('repo-1::worktree-1') - }) - - it('falls back to the same worktree terminal.list uses when no selector is sent', () => { - const terminals = callRpc('terminal.list').result as { - terminals: { worktreeId: string }[] - } - const expected = terminals.terminals[0]?.worktreeId - expect(expected).toBeTruthy() - - const tabs = callRpc('session.tabs.list').result as { worktree: string } - expect(tabs.worktree).toBe(expected) - }) -}) diff --git a/mobile/src/mock-server-terminal-fixture-routing.test.ts b/mobile/src/mock-server-terminal-fixture-routing.test.ts deleted file mode 100644 index 292462a2939..00000000000 --- a/mobile/src/mock-server-terminal-fixture-routing.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' -import type { WebSocket } from 'ws' -import type { - handleRequest as handleRpcRequest, - RpcRequest, - RpcResponse -} from '../scripts/mock-server-rpc-handlers' - -let handleRequest: typeof handleRpcRequest - -beforeAll(async () => { - vi.stubEnv('MOCK_NATIVE_CHAT', '0') - vi.stubEnv('MOCK_REPO_COUNT', '2') - vi.stubEnv('MOCK_WORKTREE_COUNT', '2') - vi.stubEnv('MOCK_RPC_DELAY_MS', '0') - for (const method of ['worktree.ps', 'worktree.create', 'worktree.activate', 'terminal.list']) { - vi.stubEnv(`MOCK_RPC_DELAY_${method.replaceAll('.', '_').toUpperCase()}_MS`, '0') - } - ;({ handleRequest } = await import('../scripts/mock-server-rpc-handlers')) -}) - -afterAll(() => vi.unstubAllEnvs()) - -let requestSequence = 0 - -function sendMockRequest(method: string, params?: Record): RpcResponse { - let response: RpcResponse | undefined - const request: RpcRequest = { id: `request-${++requestSequence}`, method, params } - handleRequest( - request, - (nextResponse) => { - response = nextResponse - }, - {} as WebSocket - ) - expect(response).toBeDefined() - return response! -} - -function listedTerminalWorktreeIds(worktree?: string): string[] { - const response = sendMockRequest('terminal.list', worktree ? { worktree } : undefined) - const result = response.result as { terminals: Array<{ worktreeId: string }> } - return [...new Set(result.terminals.map((terminal) => terminal.worktreeId))] -} - -describe('mock server terminal fixture routing', () => { - it('follows worktree creation and activation', () => { - const worktreeResponse = sendMockRequest('worktree.ps') - const initialWorktreeId = ( - worktreeResponse.result as { worktrees: Array<{ worktreeId: string }> } - ).worktrees[0]!.worktreeId - - const createResponse = sendMockRequest('worktree.create', { - repo: 'id:repo-1', - name: 'terminal-fixture-routing' - }) - const createdWorktreeId = (createResponse.result as { worktree: { id: string } }).worktree.id - expect(createdWorktreeId).not.toBe(initialWorktreeId) - expect(listedTerminalWorktreeIds()).toEqual([createdWorktreeId]) - expect(listedTerminalWorktreeIds(`id:${initialWorktreeId}`)).toEqual([initialWorktreeId]) - - sendMockRequest('worktree.activate', { worktree: `id:${initialWorktreeId}` }) - expect(listedTerminalWorktreeIds()).toEqual([initialWorktreeId]) - }) -}) diff --git a/mobile/src/test-support/rpc-recording/adapters/session-notes-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/session-notes-mount-adapters.ts index dff1a0af5c7..86092ceb9b7 100644 --- a/mobile/src/test-support/rpc-recording/adapters/session-notes-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/session-notes-mount-adapters.ts @@ -1,10 +1,7 @@ -import type * as UseMobileSessionDiffCommentsModule from '../../../source-control/review/use-mobile-session-diff-comments' import type * as UseMobileSessionMarkdownActionsModule from '../../../files/session-documents/use-mobile-session-markdown-actions' import type * as UseQuickCommandsModule from '../../../terminal/quick-commands/use-quick-commands' import { hookMount, performHookAction } from '../hook-mount' import { mountFixture } from '../recorder-fixture-shape' -import type { DiffComment } from '../../../../../src/shared/diff-comment-types' -import type { DiffNotesDelivery } from '../../../source-control/review/mobile-review-comment-state' import type { MarkdownDocState } from '../../../files/session-documents/session-document-state' import type { MountAdapter } from '../recording-scenario' import type { operationModuleLoader } from '../operation-module-loader' @@ -17,67 +14,6 @@ export function sessionNotesMountAdapters( modules: ReturnType ): Record { return { - 'session.diff-notes': ({ client, effect }) => { - const useComments = modules.load( - 'mobile/src/source-control/review/use-mobile-session-diff-comments.ts' - ).useMobileSessionDiffComments - let diffComments: DiffComment[] = [] - const diffCommentsRef = { current: diffComments } - let busy = false - let pendingDelivery: DiffNotesDelivery | null = null - let comments: ReturnType - const hook = hookMount(() => { - comments = useComments( - mountFixture[0]>({ - worktreeId: WORKSPACE, - isFloatingWorkspaceRoute: false, - client, - connState: 'connected', - setDiffComments: (update) => { - diffComments = typeof update === 'function' ? update(diffComments) : update - diffCommentsRef.current = diffComments - }, - diffCommentsRef, - diffCommentBusy: busy, - setDiffCommentBusy: (update) => { - busy = typeof update === 'function' ? update(busy) : update - }, - setPendingDiffNotesDelivery: (update) => { - pendingDelivery = typeof update === 'function' ? update(pendingDelivery) : update - }, - showToast: (message: string) => effect('toast', { message }) - }) - ) - }) - return { - action(name, args) { - if (name === 'mount') { - return hook.mount() - } - return performHookAction(() => { - if (name === 'add') { - return comments.addDiffCommentForFile( - 'src/app.ts', - Number(args.line ?? 4), - String(args.body ?? 'needs a test') - ) - } - if (name === 'delete') { - return comments.deleteDiffCommentForFile(String(args.id ?? 'note-1')) - } - if (name === 'copy') { - return comments.copyDiffCommentsToClipboard() - } - if (name === 'reload') { - return comments.loadDiffComments() - } - throw new Error(`Unknown diff notes action: ${name}`) - }) - }, - state: () => ({ diffComments, busy, pendingDelivery }), - dispose: hook.unmount - } - }, 'session.markdown-save': ({ client, effect }) => { const useMarkdown = modules.load( 'mobile/src/files/session-documents/use-mobile-session-markdown-actions.ts' diff --git a/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts index c7a6cb9e2e4..0af37c6409d 100644 --- a/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts @@ -10,7 +10,6 @@ import type { TerminalRecord } from '../../../terminal/session/mobile-terminal-r import { mountFixture } from '../recorder-fixture-shape' import type { MountAdapter } from '../recording-scenario' import type { operationModuleLoader } from '../operation-module-loader' -import type * as MobileNativeChatReadability from '../../../session/native-chat/transcript/use-mobile-native-chat-readability' import type * as MobileNativeChatStopModule from '../../../session/native-chat/composer/use-mobile-native-chat-stop' const WORKSPACE = 'workspace-1' @@ -50,7 +49,7 @@ export function sessionScreenReadMountAdapters( }) hook.mount() return { - action(name, args) { + action(name) { if (name === 'markdown') { return performHookAction(() => readers.readMarkdownTab( @@ -58,19 +57,7 @@ export function sessionScreenReadMountAdapters( type: 'markdown', id: 'tab-md', relativePath: 'docs/readme.md', - isDirty: args.dirty === true - }) - ) - ) - } - if (name === 'file') { - return performHookAction(() => - readers.readFileTab( - mountFixture[0]>({ - type: 'file', - id: 'tab-file', - relativePath: 'src/app.ts', - ...(args.diff === true ? { diffSource: 'staged' as const } : {}) + isDirty: false }) ) ) @@ -137,30 +124,6 @@ export function sessionScreenReadMountAdapters( dispose: hook.unmount } }, - 'session.native-chat-readability': ({ client }) => { - const useReadability = modules.load( - 'mobile/src/session/native-chat/transcript/use-mobile-native-chat-readability.ts' - ).useMobileNativeChatReadability - let readable = false - let worktreeId = `repo-1::/w` - const hook = hookMount(() => { - readable = useReadability(client, worktreeId) - }) - return { - action(name) { - if (name === 'mount') { - return hook.mount() - } - if (name === 'reroute') { - worktreeId = 'repo-2::/w' - return hook.update() - } - throw new Error(`Unknown readability action: ${name}`) - }, - state: () => ({ readable, worktreeId }), - dispose: hook.unmount - } - }, 'session.native-chat-stop': ({ client, effect }) => { const useStop = modules.load( 'mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts' diff --git a/mobile/src/test-support/rpc-recording/adapters/session-screen-tab-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/session-screen-tab-mount-adapters.ts index 2fab713f623..da77ee4ebc5 100644 --- a/mobile/src/test-support/rpc-recording/adapters/session-screen-tab-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/session-screen-tab-mount-adapters.ts @@ -10,7 +10,7 @@ import type { operationModuleLoader } from '../operation-module-loader' const WORKSPACE = 'workspace-1' const HANDLE = 'terminal-1' -// Project the real tab list so refused rename/close writes cannot masquerade as successful local erasure. +// Project the real tab list so refused closes cannot masquerade as successful local erasure. export function sessionScreenTabMountAdapters( modules: ReturnType ): Record { @@ -104,8 +104,6 @@ export function sessionScreenTabMountAdapters( let sessionTabs: MobileSessionTab[] = sessionTabsRef.current let activeHandle: string | null = HANDLE const activeHandleRef: { current: string | null } = { current: HANDLE } - const renameTarget: { handle: string } | null = { handle: HANDLE } - const timers: ReturnType[] = [] let actions: ReturnType const hook = hookMount(() => { actions = useClose( @@ -129,37 +127,23 @@ export function sessionScreenTabMountAdapters( setActiveSessionTabId: () => {}, activeSessionTabIdRef: { current: 'tab-1' }, selectedSessionTabIdRef: { current: 'tab-1' }, - renameTarget, - setRenameTarget: () => {}, terminalRefs: { current: new Map() }, initializedHandlesRef: { current: new Set([HANDLE]) }, activeHandleRef, activeSessionTabTypeRef: { current: 'terminal' }, pendingSelectionRef: { current: null }, pendingBrowserFocusPageIdRef: { current: null }, - scheduleDelayedAction: (callback: () => void, delayMs: number) => { - timers.push(setTimeout(callback, delayMs)) - }, unsubscribeTerminal: (handle: string) => effect('unsubscribe-terminal', { handle }), subscribeToTerminal: (handle: string) => { effect('subscribe-terminal', { handle }) return true - }, - fetchTerminals: () => { - effect('fetch-terminals', {}) - return Promise.resolve(true) } }) ) }) hook.mount() return { - action(name, args) { - if (name === 'rename') { - return performHookAction(() => - actions.handleRenameTerminal(String(args.title ?? 'renamed')) - ) - } + action(name) { if (name === 'close-terminal') { return performHookAction(() => actions.handleCloseTerminal({ handle: HANDLE, title: 'Terminal', isActive: true }) @@ -171,12 +155,7 @@ export function sessionScreenTabMountAdapters( throw new Error(`Unknown tab close action: ${name}`) }, state: () => ({ terminals, sessionTabs, activeHandle }), - dispose: () => { - for (const timer of timers) { - clearTimeout(timer) - } - hook.unmount() - } + dispose: hook.unmount } } } diff --git a/mobile/src/test-support/rpc-recording/adapters/session-terminal-create-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/session-terminal-create-mount-adapters.ts index 5419a39871b..d040a2bbc0d 100644 --- a/mobile/src/test-support/rpc-recording/adapters/session-terminal-create-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/session-terminal-create-mount-adapters.ts @@ -9,33 +9,13 @@ import type { MobileSessionTabType } from '../../../session/tabs/mobile-session-tabs' import type { Terminal } from '../../../terminal/session/mobile-terminal-model' -import type { TuiAgent } from '../../../../../src/shared/agent-launch/catalog/tui-agent' import { SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY } from '../../../../../src/shared/protocol-version' const PREVIOUS_HANDLE = 'terminal-0' -const DECLARABLE_AGENTS = ['claude', 'codex'] as const satisfies readonly TuiAgent[] - -function declaredAgent(value: unknown): TuiAgent | undefined { - if (value === undefined) { - return undefined - } - const agent = DECLARABLE_AGENTS.find((candidate) => candidate === value) - if (!agent) { - throw new Error(`Unknown agent: ${String(value)}`) - } - return agent -} - // Record unsubscribe choice to catch leaked desktop dimensions; no device subscription runs here. // Scenario inputs own wire values and omissions: worktree/tab on mount, launch options on create. // The scheduler pins time/randomness and primes React so mutation ids stay deterministic. -const AGENT_LAUNCH_HOST_CAPABILITIES = [ - 'agent.launch.v2', - 'agent.launch.replay.v1', - 'agent.launch.replay-required.v1' -] - export function sessionTerminalCreateMountAdapters( modules: ReturnType ): Record { @@ -51,7 +31,7 @@ export function sessionTerminalCreateMountAdapters( let activeHandle: string | null = PREVIOUS_HANDLE let worktreeId = '' let activeSessionTabId: string | null = null - let hostCapabilities: string[] = [SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY] + const hostCapabilities = [SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY] let creating = false let createError = '' const terminalsRef = { current: terminals } @@ -132,42 +112,21 @@ export function sessionTerminalCreateMountAdapters( activeSessionTabId = typeof args.activeSessionTabId === 'string' ? args.activeSessionTabId : null activeSessionTabIdRef.current = activeSessionTabId - hostCapabilities = [ - ...(args.supportsSplitGroupPlacement === false - ? [] - : [SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY]), - ...(args.agentLaunch === true ? AGENT_LAUNCH_HOST_CAPABILITIES : []) - ] deviceTokenRef.current = typeof args.deviceToken === 'string' ? args.deviceToken : null return hook.mount() } if (name !== 'create') { throw new Error(`Unknown terminal create action: ${name}`) } - const agent = declaredAgent(args.agent) - if ( - args.startupCommandDelivery !== undefined && - args.startupCommandDelivery !== 'shell-ready' - ) { - throw new Error(`Unknown startup delivery: ${String(args.startupCommandDelivery)}`) - } - // Preserve omitted launch options so bare New Tab reaches the structured-provider branch. const options = { ...(args.initialPrompt === undefined ? {} : { initialPrompt: String(args.initialPrompt) }), ...(args.successToast === undefined ? {} : { successToast: String(args.successToast) }), - ...(args.errorToast === undefined ? {} : { errorToast: String(args.errorToast) }), - ...(args.startupCommand === undefined - ? {} - : { startupCommand: String(args.startupCommand) }), - ...(args.startupCommandDelivery === undefined - ? {} - : { startupCommandDelivery: 'shell-ready' as const }), - ...(args.agentPrompt === undefined ? {} : { agentPrompt: String(args.agentPrompt) }) + ...(args.errorToast === undefined ? {} : { errorToast: String(args.errorToast) }) } return actions!.handleCreateTerminal( - agent, + undefined, Object.keys(options).length === 0 ? undefined : options ) }, diff --git a/mobile/src/test-support/rpc-recording/mutants/operation-mutations.ts b/mobile/src/test-support/rpc-recording/mutants/operation-mutations.ts index ee920691586..c5971a9861e 100644 --- a/mobile/src/test-support/rpc-recording/mutants/operation-mutations.ts +++ b/mobile/src/test-support/rpc-recording/mutants/operation-mutations.ts @@ -207,26 +207,6 @@ export const OPERATION_MUTATIONS = { before: ` ...(viewport && next === 'auto' ? { viewport } : {})`, after: ` ...(next === 'auto' ? { viewport } : {})` }, - // Send null instead of omitting afterTabId; only sessions without an active tab detect it. - 'create-after-tab-id-null': { - file: 'use-mobile-session-terminal-create-actions.ts', - before: ' const afterTabId = activeSessionTabId ?? undefined', - after: ' const afterTabId = activeSessionTabId' - }, - // Swap shell command and agent prompt; empty-option scenarios cannot detect it. - 'create-quick-command-keys': { - file: 'mobile-session-terminal-create-request.ts', - before: ` ...(options?.startupCommand ? { command: options.startupCommand } : {}), - ...(options?.startupCommandDelivery - ? { startupCommandDelivery: options.startupCommandDelivery } - : {}), - ...(options?.agentPrompt ? { agentPrompt: options.agentPrompt } : {}),`, - after: ` ...(options?.startupCommand ? { agentPrompt: options.startupCommand } : {}), - ...(options?.startupCommandDelivery - ? { startupCommandDelivery: options.startupCommandDelivery } - : {}), - ...(options?.agentPrompt ? { command: options.agentPrompt } : {}),` - }, // Remove the in-flight guard; only overlapping taps expose duplicate terminals. 'create-second-tap-in-flight': { file: 'use-mobile-session-terminal-create-actions.ts', diff --git a/mobile/src/worktree/last-visited-worktree-repo.test.ts b/mobile/src/worktree/last-visited-worktree-repo.test.ts index 14b68e4223f..61faf5bd7bc 100644 --- a/mobile/src/worktree/last-visited-worktree-repo.test.ts +++ b/mobile/src/worktree/last-visited-worktree-repo.test.ts @@ -14,18 +14,6 @@ describe('last visited worktree repo', () => { }) describe('readLastVisitedWorktreeRecord', () => { - it('reads absent, truncated, and wrong-shaped payloads as no history', () => { - expect(readLastVisitedWorktreeRecord(null)).toBeNull() - expect(readLastVisitedWorktreeRecord('')).toBeNull() - expect(readLastVisitedWorktreeRecord('{"hostId":"host-1"')).toBeNull() - expect(readLastVisitedWorktreeRecord('null')).toBeNull() - expect(readLastVisitedWorktreeRecord('"a string"')).toBeNull() - expect(readLastVisitedWorktreeRecord(JSON.stringify({ hostId: 'host-1' }))).toBeNull() - expect( - readLastVisitedWorktreeRecord(JSON.stringify({ hostId: 'host-1', worktreeId: 42 })) - ).toBeNull() - }) - it('rejects empty ids that would build a route to nowhere', () => { expect( readLastVisitedWorktreeRecord(JSON.stringify({ hostId: '', worktreeId: 'repo::/wt' })) diff --git a/mobile/src/worktree/workspace-filter-repos.test.ts b/mobile/src/worktree/workspace-filter-repos.test.ts index 3b7093e078d..39f6104c145 100644 --- a/mobile/src/worktree/workspace-filter-repos.test.ts +++ b/mobile/src/worktree/workspace-filter-repos.test.ts @@ -1,23 +1,5 @@ import { describe, expect, it } from 'vitest' import { buildFilterRepos } from './workspace-filter-repos' -import type { Worktree } from './workspace-list-sections' - -function row(worktreeId: string, repoId: string, hostId: Worktree['hostId']): Worktree { - return { - worktreeId, - repoId, - hostId, - repo: 'orca', - branch: 'feature', - displayName: worktreeId, - path: `/tmp/${worktreeId}`, - liveTerminalCount: 0, - hasAttachedPty: false, - unread: false, - isPinned: false, - linkedPR: null - } -} describe('the repo filter', () => { it("lists each host's same-named repo separately, by id, as the desktop's filter does", () => { @@ -49,13 +31,4 @@ describe('the repo filter', () => { ]) expect(repos[0]?.color).toBe('#111111') }) - - it('lists the repos the rows name until a catalog answers, still one per repo id', () => { - const repos = buildFilterRepos( - [], - [row('a', 'local-orca', 'local'), row('b', 'm4-orca', 'runtime:m4air')] - ) - - expect(repos.map((repo) => repo.id)).toEqual(['local-orca', 'm4-orca']) - }) }) diff --git a/mobile/src/worktree/workspace-list-pinned-lineage.test.ts b/mobile/src/worktree/workspace-list-pinned-lineage.test.ts index 9b4a4e94bea..7d9bfea7e98 100644 --- a/mobile/src/worktree/workspace-list-pinned-lineage.test.ts +++ b/mobile/src/worktree/workspace-list-pinned-lineage.test.ts @@ -1,9 +1,8 @@ import { NO_WORKSPACE_ROW_FILTERS } from '../../../src/shared/workspace-view/workspace-row-filters' import { join } from 'node:path' -import { describe, expect, it } from 'vitest' +import { expect, it } from 'vitest' import type { Worktree } from './workspace-list-sections' -import { NO_PROJECT_SECTION_CATALOG, buildSections } from './workspace-list-sections' -import { DEFAULT_WORKSPACE_STATUSES } from '../../../src/shared/workspace-statuses' +import { buildSections } from './workspace-list-sections' function worktree(overrides: Partial = {}): Worktree { const worktreePath = join('/tmp', 'orca', 'worktrees', 'feature') @@ -26,50 +25,6 @@ function worktree(overrides: Partial = {}): Worktree { } } -describe('a pinned parent with an unpinned child', () => { - const parent = worktree({ worktreeId: 'parent', displayName: 'parent', isPinned: true }) - const child = worktree({ - worktreeId: 'child', - displayName: 'child', - parentWorktreeId: 'parent' - }) - - function nesting(showPinnedInGroups: boolean) { - const sections = buildSections( - [child, parent], - 'name', - { ...NO_WORKSPACE_ROW_FILTERS }, - '', - 'repo', - new Set(), - NO_PROJECT_SECTION_CATALOG, - DEFAULT_WORKSPACE_STATUSES, - new Set(), - showPinnedInGroups - ) - return sections.map((section) => ({ - key: section.key, - rows: section.data.map((item) => [item.row.worktreeId, item.view.lineageDepth]) - })) - } - - const nested = [ - ['parent', 0], - ['child', 1] - ] - - it('moves the child into Pinned under its parent by default', () => { - expect(nesting(false)).toEqual([{ key: 'pinned', rows: nested }]) - }) - - it('nests the child under its parent in both sections when the desktop setting is on', () => { - expect(nesting(true)).toEqual([ - { key: 'pinned', rows: nested }, - { key: 'repo:repo-1', rows: nested } - ]) - }) -}) - it('follows a pin through a child hidden by search, like desktop', () => { const root = worktree({ worktreeId: 'root', displayName: 'alpha-root', isPinned: true }) const middle = worktree({ diff --git a/mobile/src/worktree/workspace-view-settings.test.ts b/mobile/src/worktree/workspace-view-settings.test.ts index ac76576c6f7..c63ae3e5b66 100644 --- a/mobile/src/worktree/workspace-view-settings.test.ts +++ b/mobile/src/worktree/workspace-view-settings.test.ts @@ -33,20 +33,6 @@ describe('the other-client filter on an older desktop', () => { }) describe('applyDesktopViewSettings', () => { - it('applies provided desktop fields and leaves missing ones untouched', () => { - const next = applyDesktopViewSettings(base, { - groupBy: 'pr-status', - hideSleepingWorkspaces: true, - filterRepoIds: ['repo-1'] - }) - expect(next).toEqual({ - ...base, - groupBy: 'pr-status', - sharesOtherClientFilter: false, - filters: { ...base.filters, hideSleepingWorkspaces: true, filterRepoIds: ['repo-1'] } - }) - }) - it("falls back to the desktop's legacy host scope when no host list is saved", () => { const scoped = applyDesktopViewSettings(base, { visibleWorkspaceHostIds: null, diff --git a/native/computer-use-linux/runtime_render_test.py b/native/computer-use-linux/runtime_render_test.py index d39c8112a08..1e25f3f032d 100644 --- a/native/computer-use-linux/runtime_render_test.py +++ b/native/computer-use-linux/runtime_render_test.py @@ -89,26 +89,16 @@ runtime = load_runtime() class FakeAccessible: - def __init__(self, role, name="", value="", children=(), counter=None): + def __init__(self, role, name="", value="", children=()): self.role = role self.name = name self.value = value self.children = list(children) - self.counter = counter or {"child_reads": 0} - for child in self.children: - child.use_counter(self.counter) - - def use_counter(self, counter): - self.counter = counter - for child in self.children: - child.use_counter(counter) def get_child_count(self): - self.counter["child_reads"] += 1 return len(self.children) def get_child_at_index(self, index): - self.counter["child_reads"] += 1 return self.children[index] def get_role_name(self): @@ -142,16 +132,6 @@ class FakeAccessible: return None -class FailingChildrenAccessible(FakeAccessible): - def get_child_count(self): - self.counter["child_reads"] += 1 - raise RuntimeError("defunct node") - - -def render(root): - return runtime.render_accessibility_tree(root, [0]) - - class SnapshotFixture(ExitStack): def __init__(self, root, app_name="Fixture"): super().__init__() @@ -161,8 +141,6 @@ class SnapshotFixture(ExitStack): self.clock = 0.0 self.timeout = (800, 15000) self.delays = {} - self.stalled = [] - self.captured_at = None self.restore = lambda: None self.bounds = {node: runtime.Rect(100 + i * 10, 200 + i * 20, 300, 400) for i, node in enumerate(runtime.all_nodes(root))} @@ -191,13 +169,11 @@ class SnapshotFixture(ExitStack): delay = self.delays.get(node, 0) self.clock += min(delay, allowance) if delay > allowance: - self.stalled.append(node.name) raise TimeoutError("unresponsive geometry") return self.bounds.get(node) def capture(self, bounds): self.clock += 1 - self.captured_at = self.clock return {"base64": json.dumps(bounds.to_json())} if bounds else None @@ -293,9 +269,7 @@ class RuntimeRenderTest(unittest.TestCase): {"name": "already active", "initial": 71, "expected": True, "native": False}, {"name": "delayed AT-SPI focus", "ack": False, "delay": 0.1, "expected": True, "native": False}, {"name": "ineffective true acknowledgment", "ack": True, "expected": True, "native": True}, - {"name": "ineffective false acknowledgment", "ack": False, "expected": True, "native": True}, {"name": "unmanaged helper", "ids": "70\n71\n", "managed": [71], "expected": True, "native": True}, - {"name": "minimized selected window", "minimized": True, "expected": True, "native": True}, {"name": "two accessible windows", "windows": 2}, {"name": "two native windows", "ids": "72\n71\n"}, {"name": "missing managed stack", "managed": None}, @@ -316,7 +290,7 @@ class RuntimeRenderTest(unittest.TestCase): def state(): if fixture.clock >= case.get("delay", float("inf")): active[0] = 71 - states = [] if case.get("minimized") else [FakeStateType.SHOWING] + states = [FakeStateType.SHOWING] if active[0] == 71: states.append(FakeStateType.ACTIVE) return FakeStateSet(*states) @@ -373,7 +347,7 @@ class RuntimeRenderTest(unittest.TestCase): def test_text_entry_inserts_into_the_focused_field_of_a_background_window(self): for tool in ("type_text", "paste_text"): - for value in ("there", "élan", "🚀 café"): + for value in ("there", "🚀 café"): for selection in ((6, 11), None): field = FakeAccessible("text", "Message", value="Hello world") field.caret, field.selection = 11, selection @@ -395,13 +369,8 @@ class RuntimeRenderTest(unittest.TestCase): cases = [ ("not-editable", 1, (6, 11)), ("count-error", TimeoutError("selection timed out"), (6, 11)), - ("count-missing", None, (6, 11)), - ("count-negative", -1, (6, 11)), ("multiple", 2, (6, 11)), ("range-error", 1, TimeoutError("range timed out")), - ("range-missing", 1, None), - ("range-empty", 1, (6, 6)), - ("range-reversed", 1, (11, 6)), ("range-outside", 1, (6, 12)), ] for tool in ("type_text", "paste_text"): @@ -438,30 +407,30 @@ class RuntimeRenderTest(unittest.TestCase): self.assertEqual((field.value, field.selection), ("Hello world", (6, 11))) def test_partial_text_replacement_fails_without_typing_again(self): - for tool in ("type_text", "paste_text"): - for failure in (False, True, TimeoutError("provider timed out"), "wrong-range"): - field = FakeAccessible("text", "Message", value="Hello world") - field.caret, field.selection = 11, (6, 11) - field.get_state_set = lambda: FakeStateSet(FakeStateType.FOCUSED, FakeStateType.EDITABLE) - field.get_editable_text_iface = lambda: field - def delete(node, _start, _end): - if failure == "wrong-range": - node.value = node.value[5:] - node.selection = None - return True - if isinstance(failure, Exception): - raise failure - return failure - with self.subTest(tool=tool, failure=failure), SnapshotFixture( - FakeAccessible("frame", "Editor", children=[field]) - ) as fixture, patch.object(runtime.Atspi.EditableText, "delete_text", delete), \ - patch.object(runtime, "type_text") as keys, patch.object(runtime, "paste_text") as paste: - fixture.root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) - with self.assertRaisesRegex(RuntimeError, "text_replacement_incomplete"): - runtime.run_operation({"tool": tool, "app": "Fixture", "text": "there", "noScreenshot": True}) - self.assertEqual(field.value, " worldthere" if failure == "wrong-range" else "Hello worldthere") - keys.assert_not_called() - paste.assert_not_called() + tool = "type_text" + for failure in (False, True, TimeoutError("provider timed out"), "wrong-range"): + field = FakeAccessible("text", "Message", value="Hello world") + field.caret, field.selection = 11, (6, 11) + field.get_state_set = lambda: FakeStateSet(FakeStateType.FOCUSED, FakeStateType.EDITABLE) + field.get_editable_text_iface = lambda: field + def delete(node, _start, _end): + if failure == "wrong-range": + node.value = node.value[5:] + node.selection = None + return True + if isinstance(failure, Exception): + raise failure + return failure + with self.subTest(tool=tool, failure=failure), SnapshotFixture( + FakeAccessible("frame", "Editor", children=[field]) + ) as fixture, patch.object(runtime.Atspi.EditableText, "delete_text", delete), \ + patch.object(runtime, "type_text") as keys, patch.object(runtime, "paste_text") as paste: + fixture.root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) + with self.assertRaisesRegex(RuntimeError, "text_replacement_incomplete"): + runtime.run_operation({"tool": tool, "app": "Fixture", "text": "there", "noScreenshot": True}) + self.assertEqual(field.value, " worldthere" if failure == "wrong-range" else "Hello worldthere") + keys.assert_not_called() + paste.assert_not_called() def test_unconfirmed_text_insertion_does_not_fall_back_to_another_write(self): write = FakeEditableText.insert_text @@ -473,51 +442,51 @@ class RuntimeRenderTest(unittest.TestCase): "wrong-text": "foobazbar", "count-unavailable": "foobarbar", } - for tool in ("type_text", "paste_text"): - for failure, expected in failures.items(): - field = FakeAccessible("text", "Message", value="foobar") - field.caret, field.selection = 6, (0, 3) - field.get_state_set = lambda: FakeStateSet(FakeStateType.FOCUSED, FakeStateType.EDITABLE) - field.get_editable_text_iface = lambda: field - def insert(node, position, text, length): - if failure == "no-op": - return True - write(node, position, "baz" if failure == "wrong-text" else text, 1 if failure == "truncated" else length) - if failure == "timeout-after-write": - raise TimeoutError("reply lost after insertion") - return failure != "false-after-write" - def count(node): - return None if failure == "count-unavailable" and node.value != "foobar" else len(node.value) - with self.subTest(tool=tool, failure=failure), SnapshotFixture( - FakeAccessible("frame", "Editor", children=[field]) - ) as fixture, patch.object(runtime.Atspi.EditableText, "insert_text", side_effect=insert), \ - patch.object(runtime.Atspi.Text, "get_character_count", side_effect=count), \ - patch.object(runtime, "type_text") as keys, patch.object(runtime, "paste_text") as paste: - fixture.root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) - with self.assertRaisesRegex(RuntimeError, "text_insertion_unconfirmed"): - runtime.run_operation({"tool": tool, "app": "Fixture", "text": "bar", "noScreenshot": True}) - self.assertEqual(field.value, expected) - self.assertEqual(field.selection, (0, 3)) - keys.assert_not_called() - paste.assert_not_called() + tool = "type_text" + for failure, expected in failures.items(): + field = FakeAccessible("text", "Message", value="foobar") + field.caret, field.selection = 6, (0, 3) + field.get_state_set = lambda: FakeStateSet(FakeStateType.FOCUSED, FakeStateType.EDITABLE) + field.get_editable_text_iface = lambda: field + def insert(node, position, text, length): + if failure == "no-op": + return True + write(node, position, "baz" if failure == "wrong-text" else text, 1 if failure == "truncated" else length) + if failure == "timeout-after-write": + raise TimeoutError("reply lost after insertion") + return failure != "false-after-write" + def count(node): + return None if failure == "count-unavailable" and node.value != "foobar" else len(node.value) + with self.subTest(tool=tool, failure=failure), SnapshotFixture( + FakeAccessible("frame", "Editor", children=[field]) + ) as fixture, patch.object(runtime.Atspi.EditableText, "insert_text", side_effect=insert), \ + patch.object(runtime.Atspi.Text, "get_character_count", side_effect=count), \ + patch.object(runtime, "type_text") as keys, patch.object(runtime, "paste_text") as paste: + fixture.root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) + with self.assertRaisesRegex(RuntimeError, "text_insertion_unconfirmed"): + runtime.run_operation({"tool": tool, "app": "Fixture", "text": "bar", "noScreenshot": True}) + self.assertEqual(field.value, expected) + self.assertEqual(field.selection, (0, 3)) + keys.assert_not_called() + paste.assert_not_called() def test_unconfirmed_caret_movement_does_not_report_text_entry_success(self): - for tool in ("type_text", "paste_text"): - for failure in (False, True, TimeoutError("provider timed out")): - field = FakeAccessible("text", "Message", value="Hello world") - field.caret, field.selection = 6, (6, 11) - field.get_state_set = lambda: FakeStateSet(FakeStateType.FOCUSED, FakeStateType.EDITABLE) - field.get_editable_text_iface = lambda: field - with self.subTest(tool=tool, failure=failure), SnapshotFixture( - FakeAccessible("frame", "Editor", children=[field]) - ) as fixture, patch.object(runtime.Atspi.Text, "set_caret_offset", side_effect=failure if isinstance(failure, Exception) else None, return_value=failure), \ - patch.object(runtime, "type_text") as keys, patch.object(runtime, "paste_text") as paste: - fixture.root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) - with self.assertRaisesRegex(RuntimeError, "text_caret_unconfirmed"): - runtime.run_operation({"tool": tool, "app": "Fixture", "text": "there", "noScreenshot": True}) - self.assertEqual((field.value, field.caret), ("Hello there", 6)) - keys.assert_not_called() - paste.assert_not_called() + tool = "type_text" + for failure in (False, True, TimeoutError("provider timed out")): + field = FakeAccessible("text", "Message", value="Hello world") + field.caret, field.selection = 6, (6, 11) + field.get_state_set = lambda: FakeStateSet(FakeStateType.FOCUSED, FakeStateType.EDITABLE) + field.get_editable_text_iface = lambda: field + with self.subTest(tool=tool, failure=failure), SnapshotFixture( + FakeAccessible("frame", "Editor", children=[field]) + ) as fixture, patch.object(runtime.Atspi.Text, "set_caret_offset", side_effect=failure if isinstance(failure, Exception) else None, return_value=failure), \ + patch.object(runtime, "type_text") as keys, patch.object(runtime, "paste_text") as paste: + fixture.root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) + with self.assertRaisesRegex(RuntimeError, "text_caret_unconfirmed"): + runtime.run_operation({"tool": tool, "app": "Fixture", "text": "there", "noScreenshot": True}) + self.assertEqual((field.value, field.caret), ("Hello there", 6)) + keys.assert_not_called() + paste.assert_not_called() def test_compacted_browser_records_keep_their_own_frames_and_indexes(self): tabs = [FakeAccessible("page tab", f"Tab {i}", value="1" if i == 9 else "") for i in range(10)] diff --git a/native/wayland-clipboard/protocol_test.py b/native/wayland-clipboard/protocol_test.py index 9562be3ccd1..4c0086fd0e7 100644 --- a/native/wayland-clipboard/protocol_test.py +++ b/native/wayland-clipboard/protocol_test.py @@ -168,22 +168,14 @@ class DataControlServer: class ClipboardProtocolTests(unittest.TestCase): - def test_both_protocols_preserve_bytes_and_serve_repeated_pastes(self): + def test_preserves_bytes_and_serves_repeated_pastes(self): text = ("遥か\r\nline two\n" * 20000).encode() - for protocol in ("zwlr_data_control", "ext_data_control"): - with self.subTest(protocol=protocol), DataControlServer(protocol) as server: - self.assertEqual(server.copy(text).returncode, 0) - self.assertEqual(server.paste(), text) - self.assertEqual(server.paste(), text) - server.send(server.source, 1) - self.assertTrue(server.disconnected.wait(1)) - - def test_unsupported_protocol_never_publishes_or_creates_a_popup(self): - with DataControlServer(None) as server: - result = server.copy(b"private text", {"DISPLAY": ""}) - self.assertEqual(result.returncode, 78) - self.assertIsNone(server.source) - self.assertEqual(result.stdout, b"") + with DataControlServer("ext_data_control") as server: + self.assertEqual(server.copy(text).returncode, 0) + self.assertEqual(server.paste(), text) + self.assertEqual(server.paste(), text) + server.send(server.source, 1) + self.assertTrue(server.disconnected.wait(1)) def test_size_limit_precedes_selection_publication(self): with DataControlServer("ext_data_control") as server: diff --git a/src/main/opencode/status-hooks/hook-service.test.ts b/src/main/opencode/status-hooks/hook-service.test.ts index 7511ec61949..f372ad34a71 100644 --- a/src/main/opencode/status-hooks/hook-service.test.ts +++ b/src/main/opencode/status-hooks/hook-service.test.ts @@ -6,9 +6,7 @@ import { mkdtempSync, readFileSync, rmSync, - statSync, symlinkSync, - utimesSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -20,7 +18,6 @@ const { getPathMock } = vi.hoisted(() => ({ })) import { OpenCodeHookService, openCode2HookService } from './hook-service' -import { getOpenCodePluginSource } from './plugin-source/status-plugin-module-source' import { resolveOpenCodeConfigDirectory } from '../../../shared/opencode-config-directory' beforeEach(() => { @@ -69,10 +66,6 @@ describe('OpenCodeHookService buildPtyEnv / clearPty round-trip', () => { rmSync(join(userDataDir, 'opencode-config-overlays'), { recursive: true, force: true }) }) - // OpenCode 2 reloads on mtime changes, resetting status mid-turn. - - // OpenCode 2 stats file-level symlink targets used by dotfile managers. - // A service reloading between writes must already find the TUI copy and stand down. it('writes the TUI copy before the server plugin file', () => { const pluginsDir = join(resolveOpenCodeConfigDirectory(), 'plugins') @@ -89,20 +82,6 @@ describe('OpenCodeHookService buildPtyEnv / clearPty round-trip', () => { rmSync(tuiDir, { recursive: true, force: true }) } }) - - it('leaves an up-to-date legacy plugin untouched and never creates the retired dir', () => { - const legacyDir = join(userDataDir, 'opencode-hooks') - new OpenCodeHookService().buildPtyEnv(daemonSessionId) - expect(existsSync(legacyDir)).toBe(false) - - const legacyPluginPath = join(legacyDir, 'shared', 'plugins', 'orca-opencode-status.js') - mkdirSync(join(legacyPluginPath, '..'), { recursive: true }) - writeFileSync(legacyPluginPath, getOpenCodePluginSource()) - const past = new Date('2020-01-01T00:00:00Z') - utimesSync(legacyPluginPath, past, past) - new OpenCodeHookService().buildPtyEnv(daemonSessionId) - expect(statSync(legacyPluginPath).mtimeMs).toBe(past.getTime()) - }) }) describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () => { diff --git a/src/main/opencode/text-tasks/opencode-text-task-session.test.ts b/src/main/opencode/text-tasks/opencode-text-task-session.test.ts index 5ef94a2c6fb..42fe29d7546 100644 --- a/src/main/opencode/text-tasks/opencode-text-task-session.test.ts +++ b/src/main/opencode/text-tasks/opencode-text-task-session.test.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { createServer, type ServerResponse } from 'node:http' import { once } from 'node:events' -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it } from 'vitest' import { runOpenCodeTextTaskSession } from './opencode-text-task-session' const servers: ReturnType[] = [] @@ -79,34 +79,6 @@ it('recovers and deletes an owned session when cancelled during creation without expect(requests).not.toContain('POST /api/session/ses_late/prompt') }) -it('preserves a completed title when deleting its session fails', async () => { - const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const url = await fixture((path, _body, response) => { - if (path.startsWith('POST /session?')) { - json(response, { id: 'ses_cleanup', permission: appliedV1Policy }) - } else if (path.startsWith('POST /session/ses_cleanup/message?')) { - json(response, { info: {}, parts: [{ type: 'text', text: 'Harbor Lantern' }] }) - } else { - response.writeHead(500).end() - } - }) - try { - await expect( - runOpenCodeTextTaskSession({ - version: 'v1', - v1SessionPolicyFiltersTools: true, - url, - password: 'test', - directory: '/workspace', - prompt: 'Name this chat', - signal: new AbortController().signal - }) - ).resolves.toBe('Harbor Lantern') - } finally { - warning.mockRestore() - } -}) - it('discards a cancelled borrowed v1 response without aborting or deleting its session', async () => { const controller = new AbortController() const submitted = Promise.withResolvers() diff --git a/src/main/pi/rpc/launch/rpc-launch.test.ts b/src/main/pi/rpc/launch/rpc-launch.test.ts deleted file mode 100644 index c3e8dcae086..00000000000 --- a/src/main/pi/rpc/launch/rpc-launch.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { buildPiRpcLaunch } from './rpc-launch' - -const options = { command: 'host-resolved-pi', cwd: '/host/folder', fullAccess: true } -describe('Pi RPC launch', () => { - it.each([ - '/host/.pi/agent/sessions/session.jsonl', - 'C:\\Users\\dev\\.pi\\agent\\sessions\\session.jsonl' - ])('passes the native session file unchanged: %s', (sessionFile) => { - expect(buildPiRpcLaunch({ ...options, sessionFile }).args).toEqual([ - '--mode', - 'rpc', - '--session', - sessionFile - ]) - }) - - it.each([['--provider', 'anthropic'], ['--provider=anthropic'], ['--model'], ['--model=']])( - 'rejects incomplete provider/model args: %j', - (...extraArgs) => { - expect(() => buildPiRpcLaunch({ ...options, extraArgs })).toThrow(/requires/) - } - ) - - it.each([ - '--mode=json', - '--print', - '-p', - '--no-session', - '--session=other', - '--resume', - '--continue' - ])('rejects arguments that bypass the chat mode or its session handle: %s', (arg) => { - expect(() => buildPiRpcLaunch({ ...options, extraArgs: [arg] })).toThrow('conflicts') - }) - - it('rejects a supervised permissions request instead of silently running in full access', () => { - expect(() => buildPiRpcLaunch({ ...options, fullAccess: false })).toThrow('full access only') - }) - - it('rejects an empty supplied resume handle', () => { - expect(() => buildPiRpcLaunch({ ...options, sessionFile: '' })).toThrow( - 'requires a session file' - ) - }) -}) diff --git a/src/main/pi/rpc/prompts/rpc-prompt.test.ts b/src/main/pi/rpc/prompts/rpc-prompt.test.ts deleted file mode 100644 index 2996b82911d..00000000000 --- a/src/main/pi/rpc/prompts/rpc-prompt.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import { PiRpcPromptError, preparePiRpcPrompt } from './rpc-prompt' - -const PNG = Buffer.from( - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lXcAAAAASUVORK5CYII=', - 'base64' -) - -function message(blocks: AgentJournalMessageItem['blocks']): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks } -} - -describe('Pi RPC prompt preparation', () => { - it('rejects URL refs with a typed unsupported attachment failure', async () => { - const readLocal = vi.fn(async () => PNG) - const rejected = await preparePiRpcPrompt( - message([{ type: 'image-ref', url: 'https://example.test/image.png' }]), - undefined, - { readLocal } - ).catch((error: unknown) => error) - expect(rejected).toBeInstanceOf(PiRpcPromptError) - expect(rejected).toMatchObject({ - failure: { kind: 'attachmentInvalid', attachment: { reason: 'unsupportedType' } } - }) - expect(readLocal).not.toHaveBeenCalled() - }) - - it('rejects a prompt beyond the RPC writer budget', async () => { - const oversizedText = 'x'.repeat(32 * 1024 * 1024) - await expect( - preparePiRpcPrompt(message([{ type: 'text', text: oversizedText }])) - ).rejects.toThrow('RPC write limit') - }) -}) diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx index ab8480f3ad7..8dd4bd1c5e1 100644 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx +++ b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx @@ -289,29 +289,6 @@ describe('ClientHostedBrowserPagePane failure records across a remount', () => { }) }) - it('keeps a useful local and published identity when the current document clears its title', async () => { - await act(async () => { - render() - }) - await act(async () => { - reportClientHostedGuestMetadata({ - webContentsId: 42, - kind: 'title', - title: '' - }) - }) - expect(storedPage()).toMatchObject({ - url: 'https://selfsigned.internal/', - title: 'https://selfsigned.internal/' - }) - expect( - vi.mocked(window.api.browser.publishClientPageMetadata).mock.calls.at(-1)?.[0].params - ).toMatchObject({ - url: 'https://selfsigned.internal/', - title: 'https://selfsigned.internal/' - }) - }) - it('retains the saved title until a first committed document exists, including a failed first load', () => { reportClientHostedGuestMetadata({ webContentsId: 42, @@ -340,26 +317,6 @@ describe('ClientHostedBrowserPagePane failure records across a remount', () => { expect(storedPage().title).toBe('Selfsigned') }) - it('reconciles a hidden commit on settlement even when metadata publication never answers', () => { - vi.mocked(window.api.browser.publishClientPageMetadata).mockImplementation( - () => new Promise(() => {}) - ) - const view = render() - act(() => view.unmount()) - reportClientHostedGuestMetadata({ - webContentsId: 42, - kind: 'navigation', - url: 'https://example.internal/next', - loading: true, - navigationRevision: 2 - }) - render() - act(() => reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'stop', loading: false })) - expect(storedPage().url).toBe('https://example.internal/next') - expect(storedPage().loading).toBe(false) - expect(storedPage().loadError).toBeNull() - }) - it('clears a standing failure after a successful same-URL reload', () => { render() failLoad() diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-metadata.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-metadata.test.ts index a432da5c2d5..a1d6a50c711 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-metadata.test.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-metadata.test.ts @@ -41,7 +41,6 @@ import { attachBrowserPageWebview } from './attach-browser-page-webview' import { useBrowserPageWebviewUrlSync } from '../navigate/use-browser-page-webview-url-sync' import { acceptBrowserGuestMetadata, - cachedBrowserGuestMetadata, clearBrowserGuestMetadata } from './browser-guest-metadata-cache' @@ -72,7 +71,7 @@ function nativeState(patch: Partial = {}): BrowserGuestMet } } -function mount(state: BrowserGuestMetadata, initiallyLoading = false) { +function mount(state: BrowserGuestMetadata) { const ref = (current: T) => ({ current }) const first: BrowserPage = { id: 'page-a', @@ -80,7 +79,7 @@ function mount(state: BrowserGuestMetadata, initiallyLoading = false) { worktreeId: 'worktree-a', url: 'https://example.test/attempted', title: 'Saved title', - loading: initiallyLoading, + loading: false, faviconUrl: null, canGoBack: true, canGoForward: false, @@ -296,77 +295,4 @@ describe('mounted browser metadata application', () => { disposers.push(dispose) expect(view.page().title).toBe('https://kagi.com/search?q=orca') }) - - it('keeps the saved title before the first document commits', () => { - const view = mount(nativeState({ navigationRevision: 0, url: '', title: '', loading: true })) - expect(view.page().title).toBe('Saved title') - expect(view.page().loading).toBe(true) - acceptBrowserGuestMetadata( - nativeState({ - revision: 2, - navigationRevision: 0, - kind: 'start', - url: '', - title: '', - loading: true - }) - ) - expect(view.page().title).toBe('Saved title') - acceptBrowserGuestMetadata( - nativeState({ - revision: 3, - navigationRevision: 0, - kind: 'stop', - url: '', - title: '', - loading: false - }) - ) - expect(view.page().title).toBe('Saved title') - expect(view.page().url).toBe('https://example.test/attempted') - expect(view.page().loading).toBe(false) - }) - - it('adopts a document that predates observation while native loading and saved loading are true', () => { - const view = mount( - nativeState({ - navigationRevision: 0, - url: 'https://current.test/c', - title: 'Current C', - loading: true - }), - true - ) - expect(view.page()).toMatchObject({ - url: 'https://current.test/c', - title: 'Current C', - loading: true - }) - }) - - it('reattaches a failed destination without replacing its address or clearing its certificate challenge', () => { - const loadError = { - code: -202, - description: 'ERR_CERT_AUTHORITY_INVALID', - validatedUrl: 'https://example.test/attempted' - } - const view = mount(nativeState({ loadError, hasCertificateFailure: true })) - expect(view.setUrl).not.toHaveBeenCalled() - expect(view.address).not.toHaveBeenCalled() - expect(view.page().url).toBe('https://example.test/attempted') - expect(view.page().loadError).toEqual(loadError) - expect(view.page().canGoBack).toBe(true) - }) - - it('keeps parked titles out of saved page state and restores the current title on reattach', () => { - const view = mount(nativeState()) - acceptBrowserGuestMetadata(nativeState({ revision: 2, kind: 'title', title: 'Next title' })) - expect(view.page().title).toBe('Next title') - view.dispose() - acceptBrowserGuestMetadata(nativeState({ revision: 3, kind: 'title', title: 'Parked title' })) - expect(view.page().title).toBe('Next title') - expect(cachedBrowserGuestMetadata(view.webview)?.title).toBe('Parked title') - const reattached = mount(nativeState({ revision: 4, title: 'Parked title' })) - expect(reattached.page().title).toBe('Parked title') - }) }) diff --git a/src/renderer/src/components/editor/image-viewer-zoom.test.ts b/src/renderer/src/components/editor/image-viewer-zoom.test.ts deleted file mode 100644 index 8307240ab00..00000000000 --- a/src/renderer/src/components/editor/image-viewer-zoom.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getPinchZoomFactor } from './image-viewer-zoom' - -describe('image viewer zoom helpers', () => { - it('normalizes line and page wheel delta modes', () => { - const pixelFactor = getPinchZoomFactor(1, 0) - const lineFactor = getPinchZoomFactor(1, 1) - const pageFactor = getPinchZoomFactor(1, 2) - - expect(lineFactor).toBeLessThan(pixelFactor) - expect(pageFactor).toBeLessThan(lineFactor) - }) - - it('bounds very large per-event zoom factors', () => { - expect(getPinchZoomFactor(-10_000, 0)).toBeCloseTo(getPinchZoomFactor(-100, 0)) - expect(getPinchZoomFactor(10_000, 0)).toBeCloseTo(getPinchZoomFactor(100, 0)) - expect(getPinchZoomFactor(-10_000, 0)).toBeLessThan(2) - expect(getPinchZoomFactor(10_000, 0)).toBeGreaterThan(0.5) - }) -}) diff --git a/src/renderer/src/components/feature-tips/feature-tip-modal-state.test.ts b/src/renderer/src/components/feature-tips/feature-tip-modal-state.test.ts deleted file mode 100644 index 12d7850efd7..00000000000 --- a/src/renderer/src/components/feature-tips/feature-tip-modal-state.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDefaultVoiceSettings } from '../../../../shared/constants' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import { getFeatureTipForModal } from './feature-tip-modal-state' - -// Session search defaults on so tests about the older tips don't see the session-search tip first. -function makeSettings( - voiceEnabled = false, - sessionSearchEnabled = true -): Pick { - return { - voice: { - ...getDefaultVoiceSettings(), - enabled: voiceEnabled - }, - aiVaultSearch: { enabled: sessionSearchEnabled, historyDays: null } - } -} - -describe('feature tip modal state', () => { - it('keeps rendering the opened tip after app open has marked it seen', () => { - const tip = getFeatureTipForModal({ - cliInstalled: false, - modalData: { tipId: 'voice-dictation' }, - seenTipIds: ['voice-dictation'], - featureInteractions: {}, - chatUiLaunchTipVariant: 'none', - settings: makeSettings(), - webClient: false - }) - - expect(tip?.id).toBe('voice-dictation') - }) -}) diff --git a/src/renderer/src/components/github-project/GhAuthErrorHelp.test.ts b/src/renderer/src/components/github-project/GhAuthErrorHelp.test.ts deleted file mode 100644 index 11f2c46c790..00000000000 --- a/src/renderer/src/components/github-project/GhAuthErrorHelp.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback -})) - -import { reloadOrcaRenderer } from './GhAuthErrorHelp' - -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -describe('GitHub Project auth remediation host routing', () => { - it('does not force navigation when the checkpointed reload is refused', async () => { - const reload = vi.fn(() => Promise.reject(new Error('checkpoint failed'))) - const locationReload = vi.fn() - const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) - vi.stubGlobal('window', { - api: { app: { reload } }, - location: { reload: locationReload } - }) - - reloadOrcaRenderer() - await vi.waitFor(() => expect(errors).toHaveBeenCalledTimes(1)) - - expect(reload).toHaveBeenCalledTimes(1) - expect(locationReload).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/commit/component-gates.test.ts b/src/renderer/src/components/right-sidebar/source-control/commit/component-gates.test.ts deleted file mode 100644 index 87135d7401e..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/commit/component-gates.test.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { expect, it } from 'vitest' -import { shouldRenderCommitArea } from './component-gates' - -it('keeps manual revert completion available until sequencer recovery is supported', () => { - expect(shouldRenderCommitArea(0, 'revert', false)).toBe(true) - expect(shouldRenderCommitArea(0, 'revert', true)).toBe(false) - expect(shouldRenderCommitArea(1, 'revert', false)).toBe(false) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-graph-svg.test.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-graph-svg.test.tsx index 7e5ccc8f0d5..d8f197b2eb7 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-graph-svg.test.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-graph-svg.test.tsx @@ -21,20 +21,6 @@ const wide: GitHistoryItemViewModel = { kind: 'node' } -it('keeps boundary strokes and restores full geometry when the graph column widens', () => { - const narrow = paths(draw(wide, 132)) - expect(narrow).toContain('M 132 0 V 24') - expect(narrow).not.toContain('M 143 0 V 24') - expect(narrow).toContain('M 11 0 V 12') - expect(narrow).toContain('M 11 12 V 24') - const full = draw(wide) - expect(paths(draw(wide, 300))).toEqual(paths(full)) - expect(paths(full)).toContain('M 264 0 V 24') - expect(paths(draw(wide, 132))).toEqual(narrow) - expect(full.querySelector('svg')?.getAttribute('viewBox')).toBe('0 0 275 24') - expect(draw(wide, 132).querySelector('svg')?.getAttribute('width')).toBe('275') -}) - it('preserves converging arcs whose strokes enter the graph column', () => { const view: GitHistoryItemViewModel = { ...wide, diff --git a/src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts b/src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts deleted file mode 100644 index d57bfc60f6d..00000000000 --- a/src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - SHORTCUT_LOCAL_SEARCH_QUERY_MAX_BYTES, - isShortcutLocalSearchQueryTooLarge, - matchesShortcutLocalSearch, - normalizeShortcutLocalSearchQuery, - type ShortcutRowModel -} from './ShortcutFilterRail' - -describe('ShortcutFilterRail search helpers', () => { - it('rejects oversized pasted shortcut searches before reading row metadata', () => { - const oversizedQuery = 'secret-shortcut-search'.repeat(SHORTCUT_LOCAL_SEARCH_QUERY_MAX_BYTES) - const row = { - get item(): ShortcutRowModel['item'] { - throw new Error('oversized shortcut searches must not scan shortcut metadata') - }, - get groupTitle(): string { - throw new Error('oversized shortcut searches must not scan shortcut groups') - }, - get effective(): readonly string[] { - throw new Error('oversized shortcut searches must not format keybindings') - }, - modified: false, - warnings: [] - } as ShortcutRowModel - - expect(isShortcutLocalSearchQueryTooLarge(oversizedQuery)).toBe(true) - expect(normalizeShortcutLocalSearchQuery(oversizedQuery)).toBeNull() - expect(matchesShortcutLocalSearch(row, oversizedQuery, 'win32')).toBe(false) - }) -}) From a44b496f28dc81b5d6611050a45561a2222903c3 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:27:28 -0800 Subject: [PATCH 26/40] refactor(watchers): group filesystem process modules by owner (#41265) * refactor(watchers): group process modules by concrete owners * refactor(watchers): consolidate direct limit imports --- config/flaky-test-pattern-baseline.txt | 3 - config/main-sync-fs-baseline.txt | 16 +- .../process-host-direct-import-baseline.txt | 2 +- config/recurring-timer-baseline.txt | 4 +- config/reliability-gates.jsonc | 61 +-- .../scripts/ci/sharding/ci-shard-timings.json | 37 +- .../runtime-file-watcher-fault-harness.mjs | 2 +- .../runtime-file-watcher-resource-probe.mjs | 4 +- .../vitest-node-runtime-files.mjs | 3 - .../parcel-watcher-canary-directory.ts | 0 .../parcel-watcher-child-launch.ts | 2 +- .../parcel-watcher-child-messaging.ts | 2 +- .../parcel-watcher-child-registry.test.ts | 0 .../parcel-watcher-child-registry.ts | 0 .../parcel-watcher-child-slot.ts | 0 .../parcel-watcher-child-termination.ts | 7 +- .../parcel-watcher-owned-children.test.ts | 2 +- .../parcel-watcher-owned-children.ts | 0 .../parcel-watcher-delivery-canary.ts | 9 +- .../parcel-watcher-delivery-health.test.ts | 61 +-- .../parcel-watcher-delivery-health.ts | 4 +- .../parcel-watcher-event-delivery.test.ts | 0 .../parcel-watcher-event-delivery.ts | 8 +- .../parcel-watcher-in-process-fallback.ts | 8 +- .../parcel-watcher-module-loader.ts | 0 ...arcel-watcher-shallow-file-subscription.ts | 0 ...arcel-watcher-shallow-subscription.test.ts | 206 +++++++++ .../parcel-watcher-shallow-subscription.ts | 2 +- .../rebinding-file-watch-noise.test.ts | 38 +- .../rebinding-file-watch.ts | 0 .../shallow-watch-delivery-probe.ts | 0 .../parcel-watcher-child-launch.test.ts | 60 --- .../parcel-watcher-event-cancellation.test.ts | 86 ---- .../parcel-watcher-process-dispose.test.ts | 4 +- .../parcel-watcher-process-entry.ts | 10 +- .../parcel-watcher-process.test.ts | 67 +-- .../watcher-process/parcel-watcher-process.ts | 4 +- ...-watcher-shallow-file-subscription.test.ts | 130 ------ ...arcel-watcher-shallow-subscription.test.ts | 405 ------------------ ...parcel-watcher-supervisor-capacity.test.ts | 194 --------- ...parcel-watcher-supervisor-disposal.test.ts | 52 --- ...parcel-watcher-unsubscribe-timeout.test.ts | 184 -------- .../rebinding-file-watch.test.ts | 116 ----- .../parcel-watcher-root-path-rewrite.test.ts | 17 +- .../watcher-aliased-root-fixture.ts | 0 .../watcher-directory-identity.ts | 0 .../watcher-event-root-path-rewrite.test.ts | 0 .../watcher-event-root-path-rewrite.ts | 0 .../runtime-watcher-disposal-owners.ts | 0 .../runtime-watcher-pending-assignment.ts | 10 +- .../runtime-watcher-pool-lifecycle.ts | 2 +- .../runtime-watcher-pool-state.ts | 2 +- .../runtime-watcher-predecessor-barriers.ts | 2 +- .../runtime-watcher-process-pool.ts | 8 +- .../runtime-watcher-quarantine-queue.ts | 2 +- .../runtime-watcher-subscription-failure.ts | 2 +- .../runtime-watcher-disposal-owners.test.ts | 103 ----- ...runtime-watcher-pending-assignment.test.ts | 50 --- .../runtime-watcher-pool-shutdown.test.ts | 79 ---- .../parcel-watcher-cancellation-restart.ts | 6 +- .../parcel-watcher-cancellation-tracker.ts | 3 +- .../parcel-watcher-child-recovery.ts | 6 +- ...parcel-watcher-crash-fuse-recovery.test.ts | 2 +- .../parcel-watcher-crash-fuse.test.ts | 19 - .../parcel-watcher-crash-fuse.ts | 0 ...cel-watcher-disconnect-termination.test.ts | 29 +- .../parcel-watcher-host-subscriptions.ts | 10 +- ...parcel-watcher-interrupted-cancellation.ts | 4 +- ...el-watcher-native-error-retirement.test.ts | 2 +- .../parcel-watcher-pending-cancellation.ts | 4 +- .../parcel-watcher-pending-subscribe.ts | 4 +- ...rcel-watcher-process-supervisor-options.ts | 0 .../parcel-watcher-process-supervisor.ts | 22 +- .../parcel-watcher-process-test-child.ts | 0 ...parcel-watcher-supervisor-capacity-wait.ts | 6 +- ...parcel-watcher-supervisor-capacity.test.ts | 97 +++++ .../parcel-watcher-supervisor-disposal.ts | 8 +- .../parcel-watcher-supervisor-message.ts | 6 +- .../parcel-watcher-supervisor-subscribe.ts | 15 +- .../filesystem-watcher-local-capacity.ts | 2 +- .../filesystem-watcher-local-install.ts | 2 +- ...filesystem-watcher-native-capacity.test.ts | 106 ----- .../watchers/filesystem-watcher-real.test.ts | 123 ------ .../watchers/filesystem-watcher-wsl.test.ts | 2 +- .../watchers/filesystem-watcher-wsl.ts | 2 +- .../watchers/filesystem-watcher.test.ts | 2 +- .../runtime-environment-preference.ts | 2 +- ...worktree-git-common-native-upgrade-poll.ts | 2 +- .../orcad/orcad-runtime-native-preflight.ts | 2 +- src/main/plugins/plugin-dev-watcher.test.ts | 43 +- src/main/plugins/plugin-dev-watcher.ts | 4 +- 91 files changed, 473 insertions(+), 2132 deletions(-) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-canary-directory.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-child-launch.ts (97%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-child-messaging.ts (77%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-child-registry.test.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-child-registry.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-child-slot.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-child-termination.ts (93%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-owned-children.test.ts (96%) rename src/main/ipc/filesystem/watcher-process/{ => child-lifecycle}/parcel-watcher-owned-children.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => event-delivery}/parcel-watcher-delivery-canary.ts (96%) rename src/main/ipc/filesystem/watcher-process/{ => event-delivery}/parcel-watcher-delivery-health.test.ts (55%) rename src/main/ipc/filesystem/watcher-process/{ => event-delivery}/parcel-watcher-delivery-health.ts (91%) rename src/main/ipc/filesystem/watcher-process/{ => event-delivery}/parcel-watcher-event-delivery.test.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => event-delivery}/parcel-watcher-event-delivery.ts (94%) rename src/main/ipc/filesystem/watcher-process/{ => native-subscriptions}/parcel-watcher-in-process-fallback.ts (92%) rename src/main/ipc/filesystem/watcher-process/{ => native-subscriptions}/parcel-watcher-module-loader.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => native-subscriptions}/parcel-watcher-shallow-file-subscription.ts (100%) create mode 100644 src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.test.ts rename src/main/ipc/filesystem/watcher-process/{ => native-subscriptions}/parcel-watcher-shallow-subscription.ts (98%) rename src/main/ipc/filesystem/watcher-process/{ => native-subscriptions}/rebinding-file-watch-noise.test.ts (63%) rename src/main/ipc/filesystem/watcher-process/{ => native-subscriptions}/rebinding-file-watch.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => native-subscriptions}/shallow-watch-delivery-probe.ts (100%) delete mode 100644 src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/parcel-watcher-event-cancellation.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/rebinding-file-watch.test.ts rename src/main/ipc/filesystem/watcher-process/{ => root-paths}/parcel-watcher-root-path-rewrite.test.ts (83%) rename src/main/ipc/filesystem/watcher-process/{ => root-paths}/watcher-aliased-root-fixture.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => root-paths}/watcher-directory-identity.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => root-paths}/watcher-event-root-path-rewrite.test.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => root-paths}/watcher-event-root-path-rewrite.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-disposal-owners.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-pending-assignment.ts (83%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-pool-lifecycle.ts (92%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-pool-state.ts (89%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-predecessor-barriers.ts (92%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-process-pool.ts (97%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-quarantine-queue.ts (96%) rename src/main/ipc/filesystem/watcher-process/{ => runtime-pool}/runtime-watcher-subscription-failure.ts (92%) delete mode 100644 src/main/ipc/filesystem/watcher-process/runtime-watcher-disposal-owners.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-shutdown.test.ts rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-cancellation-restart.ts (92%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-cancellation-tracker.ts (90%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-child-recovery.ts (93%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-crash-fuse-recovery.test.ts (97%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-crash-fuse.test.ts (82%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-crash-fuse.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-disconnect-termination.test.ts (92%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-host-subscriptions.ts (95%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-interrupted-cancellation.ts (84%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-native-error-retirement.test.ts (97%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-pending-cancellation.ts (90%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-pending-subscribe.ts (95%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-process-supervisor-options.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-process-supervisor.ts (92%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-process-test-child.ts (100%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-supervisor-capacity-wait.ts (92%) create mode 100644 src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-supervisor-disposal.ts (75%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-supervisor-message.ts (93%) rename src/main/ipc/filesystem/watcher-process/{ => supervision}/parcel-watcher-supervisor-subscribe.ts (90%) delete mode 100644 src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts delete mode 100644 src/main/ipc/filesystem/watchers/filesystem-watcher-real.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 8f37a728c8e..2f1a158344d 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -190,9 +190,6 @@ 1 test-no-real-time-wait:src/main/git/worktrees/removal/remove-worktree-branch-cleanup.test.ts 1 test-no-real-time-wait:src/main/git/worktrees/removal/worktree-prune-guard.test.ts 1 test-no-real-time-wait:src/main/grok/grok-hook-stdin-no-eof.test.ts -1 test-no-real-time-wait:src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts -1 test-no-real-time-wait:src/main/ipc/filesystem/watcher-process/rebinding-file-watch-noise.test.ts -1 test-no-real-time-wait:src/main/ipc/filesystem/watcher-process/rebinding-file-watch.test.ts 4 test-no-real-time-wait:src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts 1 test-no-real-time-wait:src/main/ipc/worktrees/creation/worktree-base-directory-poller-marker-fanout.test.ts 2 test-no-real-time-wait:src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index ff6de5dd7d7..8a089b6b082 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -273,15 +273,15 @@ 1 src/main/ipc/command-path/command-path-resolver.ts 4 src/main/ipc/diagnostics.ts 2 src/main/ipc/filesystem/access/filesystem-path-containment.ts -2 src/main/ipc/filesystem/watcher-process/parcel-watcher-canary-directory.ts -1 src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.ts -4 src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-canary.ts +2 src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-canary-directory.ts +1 src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-launch.ts +4 src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-canary.ts 3 src/main/ipc/filesystem/watcher-process/parcel-watcher-entry-path.ts -1 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.ts -1 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.ts -1 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts -1 src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts -1 src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts +1 src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-file-subscription.ts +1 src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.ts +1 src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-subscribe.ts +1 src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch.ts +1 src/main/ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite.ts 1 src/main/ipc/floating-workspace-directory.ts 1 src/main/ipc/macos-keyboard-layout-snapshot.ts 1 src/main/ipc/notification-authorization-status.ts diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 2bc95ef8cd6..7ba4f28af7d 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -39,7 +39,7 @@ src/main/git/wsl-git-read-environment.ts src/main/github/gh-utils.ts src/main/workspace-hooks/hooks.ts src/main/ipc/developer-permissions.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.ts +src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-launch.ts src/main/ipc/local-network-connection-test.ts src/main/ipc/macos-keyboard-input-source.ts src/main/ipc/macos-keyboard-layout-snapshot.ts diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index 8054472ea82..ca189d9124d 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -27,8 +27,8 @@ 1 src/main/git/refs/maintenance/pack-refs-lock-ownership.ts 1 src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts 1 src/main/hang-watchdog/main-thread-hang-watchdog.ts -2 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.ts -1 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.ts +2 src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-file-subscription.ts +1 src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.ts 1 src/main/ipc/runtime-environments/runtime-environment-preference.ts 1 src/main/ipc/worktrees/git/worktree-git-common-narrow-watch.ts 1 src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 37ace49618b..a86257f8967 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -12363,14 +12363,13 @@ "invariant": "Local runtime and SSH relay roots share one watcher child per host process while healthy and use at most four quarantine children after shard failure; native desktop, paired-runtime, and direct WSL snapshot children consume the same process-wide eight-child reservation and retry transient exhaustion without permanently disabling a root. Cancellation remains owned by its child generation and settles only after acknowledgement or bounded physical exit; paired-web retains cleanup ownership and can cancel before readiness even while capacity is exhausted, retries a failed unwatch after already-resolved or late physical exit without duplicating stream termination, replacements never overlap a still-retiring generation, and aborted or timed-out callers detach immediately even while queued behind same-root relay teardown. Destructive local and SSH cleanup holds one containment-aware watcher/terminal removal fence through descendant watcher and PTY physical exit plus parent Git/filesystem deletion; daemon and relay kill requests retain ownership until the actual subprocess exit callback or an equivalent positive dead-PID proof and propagate rejected signals or a bounded failure otherwise. A crash-fused shared shard moves affected roots into the bounded quarantine pool, a second fused quarantine ends those watch lifetimes, interrupted setup emits overflow after recovery, metadata work stays bounded, and the SSH relay, PTYs, Git, and other filesystem operations never load the watcher native addon or share its fault boundary.", "oracle": "Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", "pnpm run build:electron-vite", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs", @@ -12380,15 +12379,11 @@ "testFiles": [ "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", "src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts", - "src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts", - "src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts", - "src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts", + "src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts", "src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts", - "src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts", - "src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts", - "src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts", - "src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts", - "src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts", + "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts", + "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts", + "src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts", "src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts", "src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts", "src/main/ipc/worktrees-delete-pty-teardown.test.ts", @@ -12417,19 +12412,11 @@ { "file": "src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts", "assertions": [ - "a transient WSL child-capacity rejection automatically retries on release and renderer unwatch cancels the wait", - "failed SSH worktree removal restores every live renderer listener, emits overflow, and resumes precise events" + "pins Parcel to the Windows backend for local Windows watches; rejects installs during destructive removal and allows a retry afterward; never watches an SSH path on the local disk" ] }, { - "file": "src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts", - "assertions": [ - "typed native child-capacity exhaustion automatically retries after a serialized slot release", - "renderer unwatch cancels a pending native capacity retry before subscription restarts" - ] - }, - { - "file": "src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts", + "file": "src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts", "assertions": [ "capacity notification closes the release-before-listen race and serializes reserving waiters per released slot" ] @@ -12455,28 +12442,19 @@ "watch errors during replacement crawl terminate recovery and a late readiness ack cannot revive the failed root", "IPC disconnect recovery restores every existing root before accepting new setup", "queued abort removes one request without restarting healthy roots, while active abort or crawl-scoped timeout restores the shard", - "a crash-resubscribe crawl deadline and concurrent unsubscribe settle only after physical shard exit, or report physical-exit failure at the termination deadline", - "a close-only asynchronous spawn failure settles physical termination without waiting for the exit deadline", + "queues subscribe and unsubscribe behind the retiring child; bounds a pending crawl and restores healthy roots after setup timeout", "production runtime-pool disposal rejects later subscriptions without forking an overlapping child", "missing built entries fail closed" ] }, { - "file": "src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts", + "file": "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts", "assertions": [ - "a canary-independent native-unsubscribe deadline restarts the shard and restores healthy siblings after physical child exit", - "an unkillable child rejects the native unsubscribe with its retained physical-exit promise only at the bounded exit deadline" - ] - }, - { - "file": "src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts", - "assertions": [ - "one released physical slot launches one shared supervisor child for every waiting root, while partial/all cancellation and disposal remove the shared capacity barrier", "a waiter recursively re-enters the event-driven barrier when crash recovery reclaims its announced slot" ] }, { - "file": "src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts", + "file": "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts", "assertions": [ "pending-crawl cancellation after disconnect remains pending until the exact child exits", "ready and pending-crawl cancellation force disconnected-child exit even while a healthy sibling root remains", @@ -12484,13 +12462,6 @@ "an exit-deadline failure replaces the early cancellation and remains visible to synchronous unsubscribe until physical exit" ] }, - { - "file": "src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts", - "assertions": [ - "10,000 cancelled quarantine-assignment callers leave exactly one live anchor and zero waiters after grant", - "an already-aborted first caller synchronously releases pending assignment ownership" - ] - }, { "file": "src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts", "assertions": [ diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 477db43ea47..5208a1f2bf1 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -2036,28 +2036,22 @@ "src/main/ipc/filesystem/local-disk-write-precondition.test.ts": 8407, "src/main/ipc/filesystem/local-file-range-read.test.ts": 56, "src/main/ipc/filesystem/local-regular-file-read.test.ts": 78, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts": 57, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts": 93, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse.test.ts": 54, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts": 145, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-event-cancellation.test.ts": 58, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts": 162, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-native-error-retirement.test.ts": 120, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.test.ts": 59, + "src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts": 93, + "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts": 54, + "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts": 145, + "src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts": 162, + "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts": 120, + "src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts": 59, "src/main/ipc/filesystem/watcher-process/parcel-watcher-process-dispose.test.ts": 51, "src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts": 519, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-root-path-rewrite.test.ts": 135, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.test.ts": 241, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts": 235, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.test.ts": 106, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts": 135, + "src/main/ipc/filesystem/watcher-process/root-paths/parcel-watcher-root-path-rewrite.test.ts": 135, + "src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.test.ts": 241, + "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts": 235, "src/main/ipc/filesystem/watchers/filesystem-watcher-document-lifetime.test.ts": 557, "src/main/ipc/filesystem/watchers/filesystem-watcher-event-batch.test.ts": 59, "src/main/ipc/filesystem/watchers/filesystem-watcher-ignore-real.test.ts": 707, "src/main/ipc/filesystem/watchers/filesystem-watcher-large-batch.test.ts": 306, "src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts": 1252, - "src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts": 411, - "src/main/ipc/filesystem/watchers/filesystem-watcher-real.test.ts": 613, "src/main/ipc/filesystem/watchers/filesystem-watcher-stat-lifecycle.test.ts": 297, "src/main/ipc/filesystem/watchers/filesystem-watcher-wsl-stat-stop.test.ts": 107, "src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts": 119, @@ -2086,9 +2080,8 @@ "src/main/ipc/notifications-message-formatting.test.ts": 229, "src/main/ipc/notifications-subject-retirement.test.ts": 304, "src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts": 2761, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse-recovery.test.ts": 128, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-health.test.ts": 110, - "src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts": 4531, + "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse-recovery.test.ts": 128, + "src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-health.test.ts": 110, "src/main/ipc/pets/pet-bundle.test.ts": 48, "src/main/ipc/pets/pet.test.ts": 268, "src/main/ipc/plugin-marketplaces.test.ts": 430, @@ -2128,8 +2121,7 @@ "src/main/ipc/pty/pty-write-ipc-validation.test.ts": 5157, "src/main/ipc/pty/runtime/kill-same-id-respawn.test.ts": 3784, "src/main/ipc/pty/runtime/spawn-preflight-wsl-background-hold.test.ts": 1568, - "src/main/ipc/filesystem/watcher-process/rebinding-file-watch-noise.test.ts": 317, - "src/main/ipc/filesystem/watcher-process/rebinding-file-watch.test.ts": 4226, + "src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch-noise.test.ts": 317, "src/main/ipc/worktrees/removal/registered-worktree-root-ownership.test.ts": 498, "src/main/ipc/worktrees/removal/registered-worktree-root-refresh.test.ts": 224, "src/main/ipc/worktrees/removal/registered-worktree-root-stopped-distro.test.ts": 168, @@ -2161,9 +2153,6 @@ "src/main/ipc/runtime-environments/runtime-environments-repair.test.ts": 4122, "src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts": 5098, "src/main/ipc/runtime-upload-file-stream.test.ts": 144, - "src/main/ipc/filesystem/watcher-process/runtime-watcher-disposal-owners.test.ts": 47, - "src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts": 290, - "src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-shutdown.test.ts": 103, "src/main/ipc/runtime.test.ts": 3323, "src/main/ipc/sender-scoped-request-cancellation.test.ts": 80, "src/main/ipc/session-window-view-save.test.ts": 1998, @@ -2181,7 +2170,7 @@ "src/main/ipc/terminal-preview-output-stream.test.ts": 53, "src/main/ipc/terminal-render-desync-evidence.test.ts": 78, "src/main/ipc/terminal-startup-color-query-replies.test.ts": 265, - "src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.test.ts": 48, + "src/main/ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite.test.ts": 48, "src/main/workspaces/removal/watcher-removal-gate.test.ts": 384, "src/main/ipc/workspace-cleanup/workspace-cleanup-activity.test.ts": 76, "src/main/ipc/workspace-cleanup/workspace-cleanup-document-lifetime.test.ts": 1130, diff --git a/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs b/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs index 41553c836a1..e3c0969cb33 100644 --- a/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs +++ b/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs @@ -7,7 +7,7 @@ import { build } from 'esbuild' const ENTRY_PATH = resolve('out/main/parcel-watcher-process-entry.js') const SUPERVISOR_SOURCE = resolve( - 'src/main/ipc/filesystem/watcher-process/parcel-watcher-process-supervisor.ts' + 'src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor.ts' ) const WAIT_TIMEOUT_MS = 15_000 const require = createRequire(import.meta.url) diff --git a/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs b/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs index fd5a57f8a35..3856bbaedfa 100644 --- a/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs +++ b/config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs @@ -9,13 +9,13 @@ import { build } from 'esbuild' const ENTRY_PATH = resolve('out/main/parcel-watcher-process-entry.js') const POOL_SOURCE = resolve( - 'src/main/ipc/filesystem/watcher-process/runtime-watcher-process-pool.ts' + 'src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-process-pool.ts' ) const FAILURE_SOURCE = resolve( 'src/main/ipc/filesystem/watcher-process/parcel-watcher-process-failure.ts' ) const REGISTRY_SOURCE = resolve( - 'src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.ts' + 'src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.ts' ) const MAX_CHILD_RSS_KIB = 128 * 1024 const MAX_CHILD_CPU_PERCENT = 50 diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index d7f4c05c431..e6e67ccb73b 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -153,9 +153,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts', 'src/main/ipc/filesystem/watchers/filesystem-watcher-ignore-real.test.ts', 'src/main/ipc/runtime-environments/runtime-environment-preference.test.ts', - // Real fs.watch file bindings; Bun's watcher is not the one Electron runs. - 'src/main/ipc/filesystem/watcher-process/rebinding-file-watch.test.ts', - 'src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts', 'src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx', 'src/main/claude/claude-agent-sdk-contract-pins.test.ts', 'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts', diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-canary-directory.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-canary-directory.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-canary-directory.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-canary-directory.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-launch.ts similarity index 97% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-launch.ts index 8bb2dab9e3d..d9022a83946 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.ts +++ b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-launch.ts @@ -6,7 +6,7 @@ import { } from './parcel-watcher-canary-directory' import { reserveWatcherChild, WatcherChildCapacityError } from './parcel-watcher-child-registry' import { registerWatcherChildPhysicalExit } from './parcel-watcher-child-termination' -import type { WatcherToHostMessage } from './parcel-watcher-process-protocol' +import type { WatcherToHostMessage } from '../parcel-watcher-process-protocol' export type LaunchedWatcherChild = { child: ChildProcess diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-messaging.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-messaging.ts similarity index 77% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-child-messaging.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-messaging.ts index 73e429abed5..2f989af38bc 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-messaging.ts +++ b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-messaging.ts @@ -1,5 +1,5 @@ import type { ChildProcess } from 'node:child_process' -import type { HostToWatcherMessage } from './parcel-watcher-process-protocol' +import type { HostToWatcherMessage } from '../parcel-watcher-process-protocol' export function sendToWatcherChild(proc: ChildProcess, message: HostToWatcherMessage): void { try { diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-slot.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-slot.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-child-slot.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-slot.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-termination.ts similarity index 93% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-termination.ts index 297635c960b..23783a904fc 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts +++ b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-termination.ts @@ -2,12 +2,11 @@ import type { ChildProcess } from 'node:child_process' import { type PendingWatcherUnsubscribe, resolvePendingWatcherUnsubscribes -} from './parcel-watcher-host-subscriptions' -import { WatcherProcessFailure } from './parcel-watcher-process-failure' -import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS } from '../../../../shared/file-watch/runtime-file-watch-limits' +} from '../supervision/parcel-watcher-host-subscriptions' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS as WATCHER_PROCESS_EXIT_DEADLINE_MS } from '../../../../../shared/file-watch/runtime-file-watch-limits' export const WATCHER_PROCESS_HARD_KILL_DELAY_MS = 5_000 -export const WATCHER_PROCESS_EXIT_DEADLINE_MS = RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS const physicalExitPromises = new WeakMap>() const signalledChildren = new WeakSet() diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.test.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts similarity index 96% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.test.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts index a16136b1911..eb85490c851 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.test.ts +++ b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts @@ -5,9 +5,9 @@ import { WatcherOwnedChildren } from './parcel-watcher-owned-children' import { registerWatcherChildPhysicalExit, signalWatcherChild, - WATCHER_PROCESS_EXIT_DEADLINE_MS, WATCHER_PROCESS_HARD_KILL_DELAY_MS } from './parcel-watcher-child-termination' +import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS as WATCHER_PROCESS_EXIT_DEADLINE_MS } from '../../../../../shared/file-watch/runtime-file-watch-limits' afterEach(() => vi.useRealTimers()) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.ts rename to src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-canary.ts b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-canary.ts similarity index 96% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-canary.ts rename to src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-canary.ts index 89612feca71..eca13d596b5 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-canary.ts +++ b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-canary.ts @@ -4,9 +4,12 @@ import { type FSWatcher, mkdtempSync, rmSync, watch, writeFileSync } from 'node: import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as ParcelWatcher from '@parcel/watcher' -import { loadParcelWatcher } from './parcel-watcher-module-loader' -import { hasShallowWatchDelivered, noteShallowWatchDelivered } from './shallow-watch-delivery-probe' -import { errorMessage } from '../../../../shared/error-message' +import { loadParcelWatcher } from '../native-subscriptions/parcel-watcher-module-loader' +import { + hasShallowWatchDelivered, + noteShallowWatchDelivered +} from '../native-subscriptions/shallow-watch-delivery-probe' +import { errorMessage } from '../../../../../shared/error-message' const CANARY_INTERVAL_MS = 10_000 const CANARY_EVENT_TIMEOUT_MS = 5_000 diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-health.test.ts b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-health.test.ts similarity index 55% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-health.test.ts rename to src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-health.test.ts index db4a75ead09..f8ac493a621 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-health.test.ts +++ b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-health.test.ts @@ -3,7 +3,7 @@ import { acknowledgeWatcherSubscribe as ackSubscribe, currentWatcherChild, FakeWatcherChild as FakeChild -} from './parcel-watcher-process-test-child' +} from '../supervision/parcel-watcher-process-test-child' const { forkMock, existsSyncMock } = vi.hoisted(() => ({ forkMock: vi.fn(), @@ -21,10 +21,8 @@ import { CANARY_STALL_BACKOFF_INITIAL_MS, CANARY_STALL_BACKOFF_MAX_MS } from './parcel-watcher-delivery-canary' -import { WatcherProcessCrashFuse } from './parcel-watcher-crash-fuse' -import { WatcherDeliveryHealthMonitor } from './parcel-watcher-delivery-health' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' -import { createWatcherProcessSupervisor } from './parcel-watcher-process' + +import { createWatcherProcessSupervisor } from '../parcel-watcher-process' describe('watcher delivery stall reporting', () => { beforeEach(() => { @@ -71,56 +69,3 @@ describe('watcher delivery stall reporting', () => { supervisor.dispose() }) }) - -describe('WatcherDeliveryHealthMonitor', () => { - const record = (id: number, onOverflow: () => void): WatcherProcessSubscriptionRecord => ({ - id, - dir: `/repo-${id}`, - opts: {}, - callback: vi.fn(), - hooks: { onOverflow }, - interrupted: false, - crawlStarted: false - }) - - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('stops rescanning once no subscription is live', async () => { - const onOverflow = vi.fn() - const records = new Map([[1, record(1, onOverflow)]]) - const monitor = new WatcherDeliveryHealthMonitor(records, new WatcherProcessCrashFuse()) - monitor.childStarted() - monitor.update('stalled') - records.clear() - - await vi.advanceTimersByTimeAsync(30 * 60_000) - expect(vi.getTimerCount()).toBe(0) - - records.set(1, record(1, onOverflow)) - monitor.update('healthy') - expect(onOverflow).not.toHaveBeenCalled() - }) - - it('ignores reports before a child starts and after disposal', async () => { - const onOverflow = vi.fn() - const monitor = new WatcherDeliveryHealthMonitor( - new Map([[1, record(1, onOverflow)]]), - new WatcherProcessCrashFuse() - ) - monitor.update('stalled') - await vi.advanceTimersByTimeAsync(CANARY_STALL_BACKOFF_INITIAL_MS) - expect(vi.getTimerCount()).toBe(0) - - monitor.childStarted() - monitor.dispose() - monitor.update('stalled') - await vi.advanceTimersByTimeAsync(CANARY_STALL_BACKOFF_INITIAL_MS) - expect(onOverflow).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-health.ts b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-health.ts similarity index 91% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-health.ts rename to src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-health.ts index 2b40ff90f07..3ab54d75609 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-health.ts +++ b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-delivery-health.ts @@ -1,10 +1,10 @@ -import type { WatcherProcessCrashFuse } from './parcel-watcher-crash-fuse' +import type { WatcherProcessCrashFuse } from '../supervision/parcel-watcher-crash-fuse' import { CANARY_STALL_BACKOFF_INITIAL_MS, CANARY_STALL_BACKOFF_MAX_MS, type WatcherDeliveryHealth } from './parcel-watcher-delivery-canary' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' +import type { WatcherProcessSubscriptionRecord } from '../parcel-watcher-process-subscription' /** Rescan roots during OS event stalls with backoff, then once on recovery; the child keeps its streams. */ export class WatcherDeliveryHealthMonitor { diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts rename to src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.ts b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.ts similarity index 94% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.ts rename to src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.ts index 9803eaa774f..216af4f8475 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.ts +++ b/src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.ts @@ -1,12 +1,12 @@ import { stat } from 'node:fs/promises' -import { PrioritySemaphore } from '../../../../shared/priority-semaphore' -import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' +import { PrioritySemaphore } from '../../../../../shared/priority-semaphore' +import { mapWithConcurrency } from '../../../../../shared/map-with-concurrency' import type { Event as ParcelWatcherEvent } from '@parcel/watcher' -import { MAX_BATCHED_WATCHER_EVENTS } from '../watchers/filesystem-watcher-event-batch' +import { MAX_BATCHED_WATCHER_EVENTS } from '../../watchers/filesystem-watcher-event-batch' import type { WatcherProcessDeliveryOptions, WatcherProcessEvent -} from './parcel-watcher-process-protocol' +} from '../parcel-watcher-process-protocol' const DIRECTORY_STAT_CONCURRENCY = 8 const directoryStatSlots = new PrioritySemaphore(DIRECTORY_STAT_CONCURRENCY) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-in-process-fallback.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-in-process-fallback.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-in-process-fallback.ts rename to src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-in-process-fallback.ts index f3b4b7c90bf..e007954ab98 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-in-process-fallback.ts +++ b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-in-process-fallback.ts @@ -3,14 +3,14 @@ import { loadParcelWatcher } from './parcel-watcher-module-loader' import { createWatcherProcessEventDeliveryQueue, isParcelWatcherRescanRequiredError -} from './parcel-watcher-event-delivery' -import { WatcherProcessFailure } from './parcel-watcher-process-failure' +} from '../event-delivery/parcel-watcher-event-delivery' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' import type { WatcherProcessCallback, WatcherProcessHooks, WatcherProcessSubscription -} from './parcel-watcher-process-subscription' -import type { WatcherProcessSubscribeOptions } from './parcel-watcher-process-protocol' +} from '../parcel-watcher-process-subscription' +import type { WatcherProcessSubscribeOptions } from '../parcel-watcher-process-protocol' /** Vitest uses mocked Parcel directly; production fails closed when the child entry is missing. */ export async function subscribeWithInProcessWatcher( diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-module-loader.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-module-loader.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-module-loader.ts rename to src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-module-loader.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-file-subscription.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.ts rename to src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-file-subscription.ts diff --git a/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.test.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.test.ts new file mode 100644 index 00000000000..fb844005957 --- /dev/null +++ b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.test.ts @@ -0,0 +1,206 @@ +import { EventEmitter } from 'node:events' +import { statSync, watch } from 'node:fs' +import type * as Fs from 'node:fs' +import { mkdir, mkdtemp, rm, stat } from 'node:fs/promises' +import type * as FsPromises from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { watcherState } = vi.hoisted(() => ({ + watcherState: new Map< + string, + { + callback: (eventType: string, fileName: string | Buffer | null) => void + watcher: EventEmitter & { close: () => void } + } + >() +})) + +vi.mock('node:fs', async () => { + const actual = await vi.importActual('node:fs') + return { + ...actual, + statSync: vi.fn(actual.statSync), + watch: vi.fn( + ( + path: string, + _options: unknown, + callback: (eventType: string, fileName: string | Buffer | null) => void + ) => { + const watcher = new EventEmitter() as EventEmitter & { close: () => void } + watcher.close = () => watcher.emit('close') + watcherState.set(path, { callback, watcher }) + return watcher + } + ) + } +}) +vi.mock('node:fs/promises', async () => { + const actual = await vi.importActual('node:fs/promises') + return { ...actual, stat: vi.fn(actual.stat) } +}) + +import { startShallowDirectoryWatcher } from './parcel-watcher-shallow-subscription' + +function emit(path: string, fileName: string): void { + watcherState.get(path)?.callback('change', fileName) +} + +describe('shallow watcher subscription', () => { + beforeEach(() => { + watcherState.clear() + vi.mocked(statSync).mockReset() + vi.mocked(stat).mockReset() + }) + + it('emits only included primary files, including an existing nested directory', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) + try { + await mkdir(join(root, 'logs')) + const events: string[] = [] + const { promise, resolve } = Promise.withResolvers() + const subscription = startShallowDirectoryWatcher( + root, + ['HEAD', 'config', 'logs/HEAD'], + (nextEvents) => { + events.push(...nextEvents.map((event) => event.path)) + if ( + events.includes(join(root, 'config')) && + events.includes(join(root, 'logs', 'HEAD')) + ) { + resolve() + } + }, + (error) => { + throw error + } + ) + + emit(root, 'unrelated') + emit(join(root, 'logs'), 'unrelated') + emit(root, 'config') + emit(join(root, 'logs'), 'HEAD') + await promise + + expect(events).toContain(join(root, 'config')) + expect(events).toContain(join(root, 'logs', 'HEAD')) + expect(events).not.toContain(join(root, 'unrelated')) + expect(events).not.toContain(join(root, 'logs', 'unrelated')) + await subscription.unsubscribe() + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('does not forward events after unsubscribe', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) + try { + const events: string[] = [] + const subscription = startShallowDirectoryWatcher( + root, + ['HEAD'], + (nextEvents) => events.push(...nextEvents.map((event) => event.path)), + (error) => { + throw error + } + ) + await subscription.unsubscribe() + emit(root, 'HEAD') + const { promise, resolve } = Promise.withResolvers() + setImmediate(resolve) + await promise + expect(events).toEqual([]) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it.skipIf(process.platform === 'win32')( + 'preserves a literal backslash in an included filename', + async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) + const events: string[] = [] + const subscription = startShallowDirectoryWatcher( + root, + ['plugin\\name'], + (nextEvents) => events.push(...nextEvents.map((event) => event.path)), + (error) => { + throw error + } + ) + try { + emit(root, 'plugin\\name') + expect(events).toEqual([join(root, 'plugin\\name')]) + } finally { + await subscription.unsubscribe() + await rm(root, { recursive: true, force: true }) + } + } + ) + + it('rebinds a nested directory that is replaced, which leaves fs.watch deaf', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) + try { + await mkdir(join(root, 'logs')) + const events: string[] = [] + const subscription = startShallowDirectoryWatcher( + root, + ['HEAD', 'logs/HEAD'], + (nextEvents) => events.push(...nextEvents.map((event) => event.path)), + (error) => { + throw error + } + ) + const firstNested = watcherState.get(join(root, 'logs'))?.watcher + + // A 'rename' for the nested dir means the inode was swapped, so the old + // binding is dead and must be replaced rather than reused. + watcherState.get(root)?.callback('rename', 'logs') + + expect(watcherState.get(join(root, 'logs'))?.watcher).not.toBe(firstNested) + events.length = 0 + emit(join(root, 'logs'), 'HEAD') + expect(events).toContain(join(root, 'logs', 'HEAD')) + await subscription.unsubscribe() + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('resyncs included files when an initially missing directory becomes watchable', async () => { + vi.useFakeTimers() + const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) + let subscription: ReturnType | undefined + try { + const defaultWatch = vi.mocked(watch).getMockImplementation() + if (!defaultWatch) { + throw new Error('Missing watcher test implementation') + } + vi.mocked(watch) + .mockImplementationOnce(defaultWatch) + .mockImplementationOnce(() => { + throw new Error('ENOENT: logs directory does not exist') + }) + const events: string[] = [] + subscription = startShallowDirectoryWatcher( + root, + ['HEAD', 'logs/HEAD'], + (nextEvents) => events.push(...nextEvents.map((event) => event.path)), + (error) => { + throw error + } + ) + const logs = join(root, 'logs') + await mkdir(logs) + await vi.advanceTimersByTimeAsync(30_000) + await vi.waitFor(() => expect(watcherState.has(logs)).toBe(true)) + + expect(events).toContain(join(logs, 'HEAD')) + } finally { + await subscription?.unsubscribe() + vi.useRealTimers() + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.ts similarity index 98% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.ts rename to src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.ts index c6cfdf03737..8d7e0ef57a8 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.ts +++ b/src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import type { Event as ParcelWatcherEvent } from '@parcel/watcher' import { startShallowFileWatcher } from './parcel-watcher-shallow-file-subscription' import { closeFileSystemWatcher } from './rebinding-file-watch' -import { watcherDirectoryIdentity } from './watcher-directory-identity' +import { watcherDirectoryIdentity } from '../root-paths/watcher-directory-identity' export type ShallowWatcherSubscription = { unsubscribe: () => Promise diff --git a/src/main/ipc/filesystem/watcher-process/rebinding-file-watch-noise.test.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch-noise.test.ts similarity index 63% rename from src/main/ipc/filesystem/watcher-process/rebinding-file-watch-noise.test.ts rename to src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch-noise.test.ts index f32ed1110f0..122525de8cf 100644 --- a/src/main/ipc/filesystem/watcher-process/rebinding-file-watch-noise.test.ts +++ b/src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch-noise.test.ts @@ -1,6 +1,6 @@ import { EventEmitter } from 'node:events' import type * as Fs from 'node:fs' -import { mkdtempSync, rmSync, watch, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync, watch } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -36,53 +36,21 @@ vi.mock('node:fs', async () => { } }) -import { - closeFileSystemWatcher, - watchFileAcrossReplacement, - type RebindingFileWatch -} from './rebinding-file-watch' +import { closeFileSystemWatcher } from './rebinding-file-watch' let directory: string -let fileWatch: RebindingFileWatch | null beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'orca-rebinding-noise-')) nativeEvents.length = 0 nativeFailures.length = 0 - fileWatch = null }) -afterEach(async () => { - await fileWatch?.close() +afterEach(() => { rmSync(directory, { recursive: true, force: true }) }) -async function settle(): Promise { - await new Promise((resolve) => setTimeout(resolve, 250)) -} - describe('watchFileAcrossReplacement after a watcher error', () => { - it('closes promptly and rebinds once the runtime has closed the errored watcher', async () => { - const path = join(directory, 'index') - writeFileSync(path, 'index') - const onError = vi.fn() - fileWatch = watchFileAcrossReplacement(path, vi.fn(), onError) - await settle() - - nativeFailures.at(-1)?.(new Error('EPERM')) - expect(onError).toHaveBeenCalledOnce() - expect(fileWatch.isBound()).toBe(false) - await fileWatch.refresh() - expect(fileWatch.isBound()).toBe(true) - - nativeFailures.at(-1)?.(new Error('EPERM')) - const startedAt = Date.now() - await fileWatch.close() - fileWatch = null - // Well under the bounded close fallback: the errored watcher is not awaited at all. - expect(Date.now() - startedAt).toBeLessThan(500) - }) - it('bounds closing a watcher whose close event never arrives', async () => { vi.useFakeTimers() try { diff --git a/src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts rename to src/main/ipc/filesystem/watcher-process/native-subscriptions/rebinding-file-watch.ts diff --git a/src/main/ipc/filesystem/watcher-process/shallow-watch-delivery-probe.ts b/src/main/ipc/filesystem/watcher-process/native-subscriptions/shallow-watch-delivery-probe.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/shallow-watch-delivery-probe.ts rename to src/main/ipc/filesystem/watcher-process/native-subscriptions/shallow-watch-delivery-probe.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts deleted file mode 100644 index abba61574b4..00000000000 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { EventEmitter } from 'node:events' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as WatcherChildRegistry from './parcel-watcher-child-registry' - -const { forkMock, releaseReservationMock, signalPhysicalExitMock, writeFileSyncMock } = vi.hoisted( - () => ({ - forkMock: vi.fn(), - releaseReservationMock: vi.fn(), - signalPhysicalExitMock: vi.fn(), - writeFileSyncMock: vi.fn() - }) -) - -vi.mock('node:child_process', () => ({ fork: forkMock })) -vi.mock('node:fs', () => ({ writeFileSync: writeFileSyncMock })) -vi.mock('./parcel-watcher-canary-directory', () => ({ - createWatcherCanaryDirectory: vi.fn(() => null), - removeWatcherCanaryDirectory: vi.fn() -})) -vi.mock('./parcel-watcher-child-registry', async (importOriginal) => ({ - ...(await importOriginal()), - reserveWatcherChild: vi.fn(() => releaseReservationMock) -})) -vi.mock('./parcel-watcher-child-termination', () => ({ - registerWatcherChildPhysicalExit: vi.fn(() => signalPhysicalExitMock) -})) - -import { launchWatcherChild } from './parcel-watcher-child-launch' -import { reserveWatcherChild } from './parcel-watcher-child-registry' - -class LaunchChild extends EventEmitter { - pid = 1234 - stderr = new EventEmitter() -} - -describe('launchWatcherChild', () => { - beforeEach(() => { - vi.stubEnv('ORCA_WATCHER_CHILD_PID_FILE', '/tmp/orca-watcher.pid') - forkMock.mockReturnValue(new LaunchChild()) - releaseReservationMock.mockReset() - signalPhysicalExitMock.mockReset() - writeFileSyncMock.mockReset() - vi.mocked(reserveWatcherChild).mockReturnValue(releaseReservationMock) - }) - - it('releases physical capacity when an async spawn failure closes without exit', () => { - const child = new LaunchChild() - forkMock.mockReturnValue(child) - const onGone = vi.fn() - - expect(launchWatcherChild('/watcher.js', null, vi.fn(), onGone)).not.toBeNull() - child.emit('error', Object.assign(new Error('spawn failed'), { code: 'ENOENT' })) - child.emit('close', -2, null) - child.emit('exit', -2, null) - - expect(onGone).toHaveBeenCalledTimes(2) - expect(signalPhysicalExitMock).toHaveBeenCalledTimes(1) - expect(releaseReservationMock).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-event-cancellation.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-event-cancellation.test.ts deleted file mode 100644 index 0366e96fce3..00000000000 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-event-cancellation.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { setImmediate } from 'node:timers/promises' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - createWatcherProcessEventDeliveryQueue, - prepareWatcherProcessEvents -} from './parcel-watcher-event-delivery' -const { statMock } = vi.hoisted(() => ({ statMock: vi.fn() })) -vi.mock('node:fs/promises', () => ({ stat: statMock })) - -const delivery = { includeDirectoryMetadata: true, maxEventsPerBatch: 100 } -const directory = { isDirectory: () => true } -const events = (prefix: string, count: number) => - Array.from({ length: count }, (_, index) => ({ - type: 'update' as const, - path: `/${prefix}/${index}` - })) -beforeEach(() => { - statMock.mockReset() -}) - -describe('closed watcher metadata work', () => { - it('removes queued lookups before a new live subscription needs their slots', async () => { - const gate = Promise.withResolvers() - statMock.mockImplementation(async (path: string) => { - if (path.startsWith('/held/')) { - await gate.promise - } - return directory - }) - const held = prepareWatcherProcessEvents(events('held', 8), delivery) - await setImmediate() - expect(statMock.mock.calls.length).toBe(8) - const deliver = vi.fn(async () => undefined) - const onError = vi.fn() - const queue = createWatcherProcessEventDeliveryQueue(delivery, deliver, onError) - let live: ReturnType | undefined - try { - queue.enqueue(events('closed', 32)) - queue.close() - live = prepareWatcherProcessEvents(events('live', 1), delivery) - gate.resolve() - expect(await live).toEqual([{ type: 'update', path: '/live/0', isDirectory: true }]) - await held - await setImmediate() - expect(statMock.mock.calls.map(([path]) => path)).toEqual([ - ...events('held', 8).map((event) => event.path), - '/live/0' - ]) - expect(deliver).not.toHaveBeenCalled() - expect(onError).not.toHaveBeenCalled() - } finally { - gate.resolve() - queue.close() - await held - await live - } - }) - - it('lets active stats settle without starting the rest of a closed batch', async () => { - const gate = Promise.withResolvers() - statMock.mockImplementation(async () => { - await gate.promise - return directory - }) - const deliver = vi.fn(async () => undefined) - const onError = vi.fn() - const queue = createWatcherProcessEventDeliveryQueue(delivery, deliver, onError) - try { - queue.enqueue(events('active', 32)) - await setImmediate() - expect(statMock.mock.calls.length).toBe(8) - queue.close() - gate.resolve() - await setImmediate() - expect(statMock.mock.calls.length).toBe(8) - expect(deliver).not.toHaveBeenCalled() - expect(onError).not.toHaveBeenCalled() - await prepareWatcherProcessEvents(events('next', 8), delivery) - expect(statMock.mock.calls.length).toBe(16) - } finally { - gate.resolve() - queue.close() - await setImmediate() - } - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-dispose.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-dispose.test.ts index 2c989339e95..f02b418b32c 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-dispose.test.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-dispose.test.ts @@ -5,12 +5,12 @@ const { supervisorDispose, poolDispose } = vi.hoisted(() => ({ poolDispose: vi.fn<() => Promise>() })) -vi.mock('./parcel-watcher-process-supervisor', () => ({ +vi.mock('./supervision/parcel-watcher-process-supervisor', () => ({ WatcherProcessSupervisor: class { disposeAndWait = supervisorDispose } })) -vi.mock('./runtime-watcher-process-pool', () => ({ +vi.mock('./runtime-pool/runtime-watcher-process-pool', () => ({ RuntimeWatcherProcessPool: class { disposeAndWait = poolDispose } diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts index bf565b57fb1..69e04a8fe83 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts @@ -1,14 +1,14 @@ // Isolate native watcher teardown crashes so they cannot kill the app and its agent sessions (#7547). import type * as ParcelWatcher from '@parcel/watcher' -import { loadParcelWatcher } from './parcel-watcher-module-loader' -import { startShallowWatcher } from './parcel-watcher-shallow-subscription' -import { detectShallowWatchDelivery } from './shallow-watch-delivery-probe' -import { startWatcherDeliveryCanary } from './parcel-watcher-delivery-canary' +import { loadParcelWatcher } from './native-subscriptions/parcel-watcher-module-loader' +import { startShallowWatcher } from './native-subscriptions/parcel-watcher-shallow-subscription' +import { detectShallowWatchDelivery } from './native-subscriptions/shallow-watch-delivery-probe' +import { startWatcherDeliveryCanary } from './event-delivery/parcel-watcher-delivery-canary' import { createWatcherProcessEventDeliveryQueue, isParcelWatcherRescanRequiredError, type WatcherProcessEventDeliveryQueue -} from './parcel-watcher-event-delivery' +} from './event-delivery/parcel-watcher-event-delivery' import type { HostToWatcherMessage, WatcherProcessDeliveryOptions, diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts index 4f4c59e311d..f911df1044a 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts @@ -1,16 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WATCHER_PROCESS_CANCEL_TIMEOUT_MS } from './parcel-watcher-cancellation-tracker' -import { - terminateWatcherChild, - WATCHER_PROCESS_EXIT_DEADLINE_MS, - WATCHER_PROCESS_HARD_KILL_DELAY_MS -} from './parcel-watcher-child-termination' +import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS as WATCHER_PROCESS_CANCEL_TIMEOUT_MS } from '../../../../shared/file-watch/runtime-file-watch-limits' + import { acknowledgeWatcherSubscribe as ackSubscribe, currentWatcherChild, FakeWatcherChild as FakeChild, trackPromiseSettlement -} from './parcel-watcher-process-test-child' +} from './supervision/parcel-watcher-process-test-child' const { forkMock, existsSyncMock, mkdtempSyncMock, parcelSubscribeMock, rmSyncMock } = vi.hoisted( () => ({ @@ -58,21 +54,6 @@ describe('subscribeViaWatcherProcess', () => { vi.clearAllMocks() }) - it('accepts close without exit as physical child termination', async () => { - vi.useFakeTimers() - try { - const child = new FakeChild() - - const termination = terminateWatcherChild(child as never) - child.emit('close', -2, null) - - await expect(termination).resolves.toBe(true) - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - it('rejects and physically cancels a watcher error before subscription readiness', async () => { const callback = vi.fn() const promise = subscribeViaWatcherProcess('/repo', callback, {}) @@ -372,48 +353,6 @@ describe('subscribeViaWatcherProcess', () => { expect(healthyInterruption).toHaveBeenCalledTimes(1) }) - it('keeps process count bounded when a killed child never exits', async () => { - vi.useFakeTimers() - try { - const healthyPromise = subscribeViaWatcherProcess('/healthy', vi.fn(), {}) - const child = currentChild() - ackSubscribe(child) - await healthyPromise - - const controller = new AbortController() - const pending = subscribeViaWatcherProcess( - '/slow', - vi.fn(), - {}, - { - signal: controller.signal - } - ) - const pendingId = child.sent.at(-1)?.id - child.emit('message', { op: 'subscribe-started', id: pendingId }) - controller.abort() - const rejected = expect(pending).rejects.toThrow( - 'file watcher process did not exit after termination deadline' - ) - child.emit('message', { op: 'cancel-requires-restart', id: pendingId }) - - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_HARD_KILL_DELAY_MS) - expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL') - expect(forkMock).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync( - WATCHER_PROCESS_EXIT_DEADLINE_MS - WATCHER_PROCESS_HARD_KILL_DELAY_MS - ) - - await rejected - expect(forkMock).toHaveBeenCalledTimes(1) - expect(child.listenerCount('exit')).toBe(1) - expect(vi.getTimerCount()).toBe(0) - await expect(subscribeViaWatcherProcess('/later', vi.fn(), {})).rejects.toThrow('disposed') - } finally { - vi.useRealTimers() - } - }) - it('queues subscribe and unsubscribe behind the retiring child', async () => { const healthyPromise = subscribeViaWatcherProcess('/healthy', vi.fn(), {}) const first = currentChild() diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.ts index 1e2fa20f1cc..55032d1d6d2 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-process.ts @@ -1,11 +1,11 @@ -import { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' +import { WatcherProcessSupervisor } from './supervision/parcel-watcher-process-supervisor' import type { WatcherProcessSubscribeOptions } from './parcel-watcher-process-protocol' import type { WatcherProcessCallback, WatcherProcessHooks, WatcherProcessSubscription } from './parcel-watcher-process-subscription' -import { RuntimeWatcherProcessPool } from './runtime-watcher-process-pool' +import { RuntimeWatcherProcessPool } from './runtime-pool/runtime-watcher-process-pool' const sharedWatcherProcessSupervisor = new WatcherProcessSupervisor() // Healthy roots share a child; quarantine adds isolation only after faults to limit RSS. diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts deleted file mode 100644 index 39848e03d6b..00000000000 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { PRIMARY_CHECKOUT_METADATA_FILES } from '../../worktrees/git/worktree-git-common-metadata-files' -import { - MISSING_FILE_SWEEP_INTERVAL_MS, - startShallowFileWatcher -} from './parcel-watcher-shallow-file-subscription' -import type { ShallowWatcherSubscription } from './parcel-watcher-shallow-subscription' - -let commonDir: string -let subscription: ShallowWatcherSubscription | null -let paths: string[] - -beforeEach(() => { - commonDir = mkdtempSync(join(tmpdir(), 'orca-shallow-file-watch-')) - for (const directory of ['logs', 'objects/ab', 'refs/heads', 'worktrees/feature', 'lfs']) { - mkdirSync(join(commonDir, directory), { recursive: true }) - } - // packed-refs and config.worktree are deliberately absent at start. - for (const name of ['HEAD', 'index', 'config', 'logs/HEAD']) { - writeFileSync(join(commonDir, name), 'initial') - } - subscription = null - paths = [] -}) - -afterEach(async () => { - await subscription?.unsubscribe() - rmSync(commonDir, { recursive: true, force: true }) -}) - -function start(): void { - subscription = startShallowFileWatcher( - commonDir, - PRIMARY_CHECKOUT_METADATA_FILES, - (events) => paths.push(...events.map((event) => event.path)), - (error) => { - throw error - } - ) -} - -function replaceLikeGit(name: string, content: string): void { - const path = join(commonDir, name) - writeFileSync(`${path}.lock`, content) - renameSync(`${path}.lock`, path) -} - -async function settle(): Promise { - await new Promise((resolve) => setTimeout(resolve, 150)) -} - -async function expectEventFor(name: string): Promise { - await vi.waitFor(() => expect(paths).toContain(join(commonDir, name)), { timeout: 5_000 }) -} - -describe('shallow file watcher', () => { - it('ignores object, ref, lfs and linked-worktree churn under the common dir', async () => { - start() - await settle() - paths = [] - - writeFileSync(join(commonDir, 'objects/ab/cdef'), 'blob') - writeFileSync(join(commonDir, 'refs/heads/topic'), 'sha') - writeFileSync(join(commonDir, 'worktrees/feature/index'), 'index') - writeFileSync(join(commonDir, 'worktrees/feature/HEAD'), 'ref') - writeFileSync(join(commonDir, 'lfs/object'), 'large') - writeFileSync(join(commonDir, 'FETCH_HEAD'), 'fetched') - await settle() - - expect(paths).toEqual([]) - }) - - it('reports git lock-file replacements of the index every time', async () => { - start() - await settle() - - for (const content of ['one', 'two', 'three']) { - paths = [] - replaceLikeGit('index', content) - await expectEventFor('index') - await settle() - } - }) - - it('reports appends to the nested reflog', async () => { - start() - await settle() - paths = [] - - writeFileSync(join(commonDir, 'logs/HEAD'), 'initial\nmoved', { flag: 'w' }) - - await expectEventFor('logs/HEAD') - }) - - it('picks up a metadata file created after start when a sibling changes', async () => { - start() - await settle() - paths = [] - - writeFileSync(join(commonDir, 'packed-refs'), 'packed') - replaceLikeGit('HEAD', 'ref: refs/heads/topic') - - await expectEventFor('HEAD') - await expectEventFor('packed-refs') - paths = [] - replaceLikeGit('packed-refs', 'repacked') - await expectEventFor('packed-refs') - }) - - it('finds a metadata file created later with no sibling write, as pack-refs does', async () => { - start() - await settle() - paths = [] - - replaceLikeGit('packed-refs', 'packed') - - await vi.waitFor(() => expect(paths).toContain(join(commonDir, 'packed-refs')), { - timeout: MISSING_FILE_SWEEP_INTERVAL_MS + 3_000 - }) - }) - - it('reports a missing root as a watch error', async () => { - const onError = vi.fn() - subscription = startShallowFileWatcher(join(commonDir, 'missing'), ['HEAD'], () => {}, onError) - expect(onError).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.test.ts deleted file mode 100644 index bbe7814479e..00000000000 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.test.ts +++ /dev/null @@ -1,405 +0,0 @@ -import { EventEmitter } from 'node:events' -import { statSync, watch } from 'node:fs' -import type * as Fs from 'node:fs' -import { mkdir, mkdtemp, rename, rm, stat } from 'node:fs/promises' -import type * as FsPromises from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { basename, dirname, join } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { watcherState } = vi.hoisted(() => ({ - watcherState: new Map< - string, - { - callback: (eventType: string, fileName: string | Buffer | null) => void - watcher: EventEmitter & { close: () => void } - } - >() -})) - -vi.mock('node:fs', async () => { - const actual = await vi.importActual('node:fs') - return { - ...actual, - statSync: vi.fn(actual.statSync), - watch: vi.fn( - ( - path: string, - _options: unknown, - callback: (eventType: string, fileName: string | Buffer | null) => void - ) => { - const watcher = new EventEmitter() as EventEmitter & { close: () => void } - watcher.close = () => watcher.emit('close') - watcherState.set(path, { callback, watcher }) - return watcher - } - ) - } -}) -vi.mock('node:fs/promises', async () => { - const actual = await vi.importActual('node:fs/promises') - return { ...actual, stat: vi.fn(actual.stat) } -}) - -import { startShallowDirectoryWatcher } from './parcel-watcher-shallow-subscription' - -function emit(path: string, fileName: string): void { - watcherState.get(path)?.callback('change', fileName) -} - -describe('shallow watcher subscription', () => { - beforeEach(() => { - watcherState.clear() - vi.mocked(statSync).mockReset() - vi.mocked(stat).mockReset() - }) - - it('emits only included primary files, including an existing nested directory', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) - try { - await mkdir(join(root, 'logs')) - const events: string[] = [] - const { promise, resolve } = Promise.withResolvers() - const subscription = startShallowDirectoryWatcher( - root, - ['HEAD', 'config', 'logs/HEAD'], - (nextEvents) => { - events.push(...nextEvents.map((event) => event.path)) - if ( - events.includes(join(root, 'config')) && - events.includes(join(root, 'logs', 'HEAD')) - ) { - resolve() - } - }, - (error) => { - throw error - } - ) - - emit(root, 'unrelated') - emit(join(root, 'logs'), 'unrelated') - emit(root, 'config') - emit(join(root, 'logs'), 'HEAD') - await promise - - expect(events).toContain(join(root, 'config')) - expect(events).toContain(join(root, 'logs', 'HEAD')) - expect(events).not.toContain(join(root, 'unrelated')) - expect(events).not.toContain(join(root, 'logs', 'unrelated')) - await subscription.unsubscribe() - } finally { - await rm(root, { recursive: true, force: true }) - } - }) - - it('does not forward events after unsubscribe', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) - try { - const events: string[] = [] - const subscription = startShallowDirectoryWatcher( - root, - ['HEAD'], - (nextEvents) => events.push(...nextEvents.map((event) => event.path)), - (error) => { - throw error - } - ) - await subscription.unsubscribe() - emit(root, 'HEAD') - const { promise, resolve } = Promise.withResolvers() - setImmediate(resolve) - await promise - expect(events).toEqual([]) - } finally { - await rm(root, { recursive: true, force: true }) - } - }) - - it.skipIf(process.platform === 'win32')( - 'preserves a literal backslash in an included filename', - async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) - const events: string[] = [] - const subscription = startShallowDirectoryWatcher( - root, - ['plugin\\name'], - (nextEvents) => events.push(...nextEvents.map((event) => event.path)), - (error) => { - throw error - } - ) - try { - emit(root, 'plugin\\name') - expect(events).toEqual([join(root, 'plugin\\name')]) - } finally { - await subscription.unsubscribe() - await rm(root, { recursive: true, force: true }) - } - } - ) - - it('rebinds a nested directory that is replaced, which leaves fs.watch deaf', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) - try { - await mkdir(join(root, 'logs')) - const events: string[] = [] - const subscription = startShallowDirectoryWatcher( - root, - ['HEAD', 'logs/HEAD'], - (nextEvents) => events.push(...nextEvents.map((event) => event.path)), - (error) => { - throw error - } - ) - const firstNested = watcherState.get(join(root, 'logs'))?.watcher - - // A 'rename' for the nested dir means the inode was swapped, so the old - // binding is dead and must be replaced rather than reused. - watcherState.get(root)?.callback('rename', 'logs') - - expect(watcherState.get(join(root, 'logs'))?.watcher).not.toBe(firstNested) - events.length = 0 - emit(join(root, 'logs'), 'HEAD') - expect(events).toContain(join(root, 'logs', 'HEAD')) - await subscription.unsubscribe() - } finally { - await rm(root, { recursive: true, force: true }) - } - }) - - it('retries a failed replacement binding and resyncs after recovery', async () => { - vi.useFakeTimers() - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) - const logs = join(root, 'logs') - let subscription: ReturnType | undefined - try { - await mkdir(logs) - const events: string[] = [] - subscription = startShallowDirectoryWatcher( - root, - ['HEAD', 'logs/HEAD'], - (nextEvents) => events.push(...nextEvents.map((event) => event.path)), - (error) => { - throw error - } - ) - const initialAttempts = vi.mocked(watch).mock.calls.length - await rename(logs, join(root, 'old-logs')) - await mkdir(logs) - vi.mocked(watch).mockImplementationOnce(() => { - throw new Error('ENOSPC: watch limit reached') - }) - - await vi.advanceTimersByTimeAsync(30_000) - await vi.waitFor(() => expect(watch).toHaveBeenCalledTimes(initialAttempts + 1)) - await vi.advanceTimersByTimeAsync(30_000) - await vi.waitFor(() => expect(watch).toHaveBeenCalledTimes(initialAttempts + 2)) - - expect(events).toContain(join(logs, 'HEAD')) - events.length = 0 - emit(logs, 'HEAD') - expect(events).toEqual([join(logs, 'HEAD')]) - } finally { - await subscription?.unsubscribe() - vi.useRealTimers() - await rm(root, { recursive: true, force: true }) - } - }) - - it.each(['', 'logs'])( - 'recovers an inode-less %s replacement while ignoring ordinary timestamp changes', - async (parent) => { - vi.useFakeTimers() - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-inode-less-')) - const directory = join(root, parent) - const previousDirectory = join(dirname(directory), `${basename(directory)}-previous`) - let subscription: ReturnType | undefined - try { - if (parent) { - await mkdir(directory) - } - const previousBirthtime = 9_007_199_254_740_995n - const nextBirthtime = previousBirthtime + 1n - const previousIdentity = { dev: 1n, ino: 0n, birthtimeNs: previousBirthtime } - const nextIdentity = { ...previousIdentity, birthtimeNs: nextBirthtime } - const previous = Object.assign(statSync(directory, { bigint: true }), previousIdentity) - const healthy = Object.assign(statSync(directory, { bigint: true }), previousIdentity, { - mtimeNs: previous.mtimeNs + 1n, - ctimeNs: previous.ctimeNs + 1n - }) - const replacement = Object.assign(statSync(directory, { bigint: true }), nextIdentity) - const healthyReplacement = Object.assign( - statSync(directory, { bigint: true }), - nextIdentity, - { - mtimeNs: replacement.mtimeNs + 1n, - ctimeNs: replacement.ctimeNs + 1n - } - ) - vi.mocked(statSync).mockClear() - vi.mocked(stat).mockClear() - vi.mocked(statSync).mockReturnValueOnce(previous) - vi.mocked(stat) - .mockResolvedValueOnce(healthy) - .mockResolvedValueOnce(replacement) - .mockResolvedValueOnce(healthyReplacement) - const events: string[] = [] - subscription = startShallowDirectoryWatcher( - root, - [join(parent, 'HEAD')], - (nextEvents) => events.push(...nextEvents.map((event) => event.path)), - (error) => { - throw error - } - ) - const firstWatcher = watcherState.get(directory)?.watcher - const oldClosed = vi.fn() - firstWatcher?.on('close', oldClosed) - expect(firstWatcher).toBeDefined() - await vi.advanceTimersByTimeAsync(30_000) - expect(watcherState.get(directory)?.watcher).toBe(firstWatcher) - expect(events).toEqual([]) - expect(oldClosed).not.toHaveBeenCalled() - - await rename(directory, previousDirectory) - await mkdir(directory) - await vi.advanceTimersByTimeAsync(30_000) - const replacementWatcher = watcherState.get(directory)?.watcher - expect(replacementWatcher).not.toBe(firstWatcher) - expect(oldClosed).toHaveBeenCalledOnce() - expect(events).toEqual([join(directory, 'HEAD')]) - await vi.advanceTimersByTimeAsync(30_000) - expect(watcherState.get(directory)?.watcher).toBe(replacementWatcher) - expect(events).toEqual([join(directory, 'HEAD')]) - events.length = 0 - emit(directory, 'HEAD') - expect(events).toEqual([join(directory, 'HEAD')]) - } finally { - await subscription?.unsubscribe() - vi.useRealTimers() - await rm(root, { recursive: true, force: true }) - await rm(previousDirectory, { recursive: true, force: true }) - } - } - ) - - it.each([ - { parent: '', replaced: true }, - { parent: 'logs', replaced: true }, - { parent: '', replaced: false }, - { parent: 'logs', replaced: false } - ])( - 'admits a usable $parent identity once after an unknown binding (replaced=$replaced)', - async ({ parent, replaced }) => { - vi.useFakeTimers() - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-known-identity-')) - const directory = join(root, parent) - const previousDirectory = join(dirname(directory), `${basename(directory)}-previous`) - let subscription: ReturnType | undefined - try { - if (parent) { - await mkdir(directory) - } - const unknown = Object.assign(statSync(directory, { bigint: true }), { - dev: 1n, - ino: 0n, - birthtimeNs: replaced ? 0n : 1n, - ctimeNs: 1n - }) - const replacement = Object.assign(statSync(directory, { bigint: true }), { - dev: 1n, - ino: replaced ? 77n : 0n, - birthtimeNs: unknown.birthtimeNs, - ctimeNs: 2n - }) - vi.mocked(statSync).mockClear() - vi.mocked(stat).mockClear() - vi.mocked(statSync).mockReturnValueOnce(unknown) - vi.mocked(stat).mockResolvedValue(unknown) - const events: string[] = [] - const onError = vi.fn() - subscription = startShallowDirectoryWatcher( - root, - [join(parent, 'HEAD')], - (nextEvents) => events.push(...nextEvents.map((event) => event.path)), - onError - ) - const firstWatcher = watcherState.get(directory)?.watcher - const watchAttempts = vi.mocked(watch).mock.calls.length - expect(firstWatcher).toBeDefined() - await vi.advanceTimersByTimeAsync(30_000) - expect(watcherState.get(directory)?.watcher).toBe(firstWatcher) - expect(events).toEqual([]) - if (replaced) { - await rename(directory, previousDirectory) - await mkdir(directory) - } - vi.mocked(stat).mockResolvedValue(replacement) - await vi.advanceTimersByTimeAsync(29_999) - expect(watch).toHaveBeenCalledTimes(watchAttempts) - await vi.advanceTimersByTimeAsync(1) - const recovered = watcherState.get(directory)?.watcher - expect(recovered).not.toBe(firstWatcher) - expect(watch).toHaveBeenCalledTimes(watchAttempts + 1) - expect(events).toEqual([join(directory, 'HEAD')]) - await vi.advanceTimersByTimeAsync(30_000) - expect(watcherState.get(directory)?.watcher).toBe(recovered) - expect(watch).toHaveBeenCalledTimes(watchAttempts + 1) - expect(events).toEqual([join(directory, 'HEAD')]) - for (const current of [unknown, replacement]) { - vi.mocked(stat).mockResolvedValue(current) - await vi.advanceTimersByTimeAsync(30_000) - expect(watcherState.get(directory)?.watcher).toBe(recovered) - expect(watch).toHaveBeenCalledTimes(watchAttempts + 1) - expect(events).toEqual([join(directory, 'HEAD')]) - } - events.length = 0 - emit(directory, 'HEAD') - expect(events).toEqual([join(directory, 'HEAD')]) - expect(onError).not.toHaveBeenCalled() - } finally { - await subscription?.unsubscribe() - vi.useRealTimers() - await rm(root, { recursive: true, force: true }) - await rm(previousDirectory, { recursive: true, force: true }) - } - } - ) - - it('resyncs included files when an initially missing directory becomes watchable', async () => { - vi.useFakeTimers() - const root = await mkdtemp(join(tmpdir(), 'orca-shallow-watcher-')) - let subscription: ReturnType | undefined - try { - const defaultWatch = vi.mocked(watch).getMockImplementation() - if (!defaultWatch) { - throw new Error('Missing watcher test implementation') - } - vi.mocked(watch) - .mockImplementationOnce(defaultWatch) - .mockImplementationOnce(() => { - throw new Error('ENOENT: logs directory does not exist') - }) - const events: string[] = [] - subscription = startShallowDirectoryWatcher( - root, - ['HEAD', 'logs/HEAD'], - (nextEvents) => events.push(...nextEvents.map((event) => event.path)), - (error) => { - throw error - } - ) - const logs = join(root, 'logs') - await mkdir(logs) - await vi.advanceTimersByTimeAsync(30_000) - await vi.waitFor(() => expect(watcherState.has(logs)).toBe(true)) - - expect(events).toContain(join(logs, 'HEAD')) - } finally { - await subscription?.unsubscribe() - vi.useRealTimers() - await rm(root, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts deleted file mode 100644 index fade0774a9e..00000000000 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WATCHER_PROCESS_EXIT_DEADLINE_MS } from './parcel-watcher-child-termination' -import { - MAX_PHYSICAL_WATCHER_CHILDREN, - resetWatcherChildRegistryForTest -} from './parcel-watcher-child-registry' -import { - acknowledgeWatcherSubscribe, - currentWatcherChild, - FakeWatcherChild, - trackPromiseSettlement -} from './parcel-watcher-process-test-child' -import type { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' - -const { existsSyncMock, forkMock, mkdtempSyncMock, rmSyncMock } = vi.hoisted(() => ({ - existsSyncMock: vi.fn(), - forkMock: vi.fn(), - mkdtempSyncMock: vi.fn(() => '/tmp/orca-watcher-capacity-supervisor-test'), - rmSyncMock: vi.fn() -})) - -vi.mock('node:child_process', () => ({ fork: forkMock })) -vi.mock('node:fs', () => ({ - existsSync: existsSyncMock, - mkdtempSync: mkdtempSyncMock, - rmSync: rmSyncMock -})) - -import { createWatcherProcessSupervisor } from './parcel-watcher-process' - -const supervisors: WatcherProcessSupervisor[] = [] - -function createSupervisor(): WatcherProcessSupervisor { - const supervisor = createWatcherProcessSupervisor() - supervisors.push(supervisor) - return supervisor -} - -function currentChild(): FakeWatcherChild { - return currentWatcherChild(forkMock) -} - -describe('WatcherProcessSupervisor capacity wait', () => { - beforeEach(() => { - resetWatcherChildRegistryForTest() - vi.stubEnv('VITEST', '') - existsSyncMock.mockReturnValue(true) - forkMock.mockImplementation(() => new FakeWatcherChild()) - }) - - afterEach(() => { - for (const supervisor of supervisors.splice(0)) { - supervisor.dispose() - } - resetWatcherChildRegistryForTest() - vi.unstubAllEnvs() - vi.clearAllMocks() - vi.useRealTimers() - }) - - it('shares one released slot across same-supervisor capacity waiters', async () => { - vi.useFakeTimers() - const pending: Promise[] = [] - const children: FakeWatcherChild[] = [] - for (let index = 0; index < MAX_PHYSICAL_WATCHER_CHILDREN; index++) { - const supervisor = createSupervisor() - const controller = new AbortController() - const subscription = supervisor.subscribe( - `/stuck-${index}`, - vi.fn(), - {}, - { - signal: controller.signal - } - ) - pending.push(subscription.catch((error) => error)) - const child = currentChild() - children.push(child) - const id = child.sent.at(-1)?.id - child.emit('message', { op: 'subscribe-started', id }) - controller.abort() - child.emit('message', { op: 'cancel-requires-restart', id }) - } - expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN) - - const extraSupervisor = createSupervisor() - const firstExtra = extraSupervisor.subscribe('/over-cap-a', vi.fn(), {}) - const secondExtra = extraSupervisor.subscribe('/over-cap-b', vi.fn(), {}) - const firstSettled = trackPromiseSettlement(firstExtra) - const secondSettled = trackPromiseSettlement(secondExtra) - await Promise.resolve() - expect(firstSettled()).toBe(false) - expect(secondSettled()).toBe(false) - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - await Promise.all(pending) - - expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN) - expect(children.every((child) => child.listenerCount('exit') === 1)).toBe(true) - expect(vi.getTimerCount()).toBe(0) - - children[0].emit('exit', 0, null) - await vi.waitFor(() => - expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN + 1) - ) - const replacement = currentChild() - const subscribeMessages = replacement.sent.filter(({ op }) => op === 'subscribe') - expect(subscribeMessages.map(({ dir }) => dir)).toEqual(['/over-cap-a', '/over-cap-b']) - acknowledgeWatcherSubscribe(replacement, 0) - acknowledgeWatcherSubscribe(replacement, 1) - await expect(Promise.all([firstExtra, secondExtra])).resolves.toHaveLength(2) - - const blockedSupervisor = createSupervisor() - const firstController = new AbortController() - const secondController = new AbortController() - const firstBlocked = blockedSupervisor.subscribe( - '/cancelled-over-cap-a', - vi.fn(), - {}, - { - signal: firstController.signal - } - ) - const secondBlocked = blockedSupervisor.subscribe( - '/cancelled-over-cap-b', - vi.fn(), - {}, - { - signal: secondController.signal - } - ) - await Promise.resolve() - expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN + 1) - const secondBlockedSettled = trackPromiseSettlement(secondBlocked) - firstController.abort() - await expect(firstBlocked).rejects.toMatchObject({ code: 'subscribe_aborted' }) - await vi.advanceTimersByTimeAsync(0) - expect(secondBlockedSettled()).toBe(false) - secondController.abort() - await expect(secondBlocked).rejects.toMatchObject({ code: 'subscribe_aborted' }) - - const racedDisposeSupervisor = createSupervisor() - const racedDisposeWait = racedDisposeSupervisor.subscribe('/raced-dispose', vi.fn(), {}) - racedDisposeSupervisor.dispose() - await expect(racedDisposeWait).rejects.toMatchObject({ code: 'supervisor_disposed' }) - - const activeDisposeSupervisor = createSupervisor() - const activeDisposeWait = activeDisposeSupervisor.subscribe('/active-dispose', vi.fn(), {}) - await Promise.resolve() - activeDisposeSupervisor.dispose() - await expect(activeDisposeWait).rejects.toMatchObject({ code: 'supervisor_disposed' }) - - children[1].emit('exit', 0, null) - await Promise.resolve() - await Promise.resolve() - expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN + 1) - }) - - it('keeps waiting when crash recovery reclaims the announced slot', async () => { - const children: FakeWatcherChild[] = [] - for (let index = 0; index < MAX_PHYSICAL_WATCHER_CHILDREN; index++) { - const supervisor = createSupervisor() - const subscription = supervisor.subscribe(`/active-${index}`, vi.fn(), {}) - const child = currentChild() - children.push(child) - acknowledgeWatcherSubscribe(child) - await subscription - } - - const waitingSupervisor = createSupervisor() - const waiting = waitingSupervisor.subscribe('/waiting-root', vi.fn(), {}) - const waitingSettled = trackPromiseSettlement(waiting) - await Promise.resolve() - expect(waitingSettled()).toBe(false) - - children[0].connected = false - children[0].emit('exit', null, 'SIGSEGV') - await vi.waitFor(() => - expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN + 1) - ) - await Promise.resolve() - await Promise.resolve() - expect(waitingSettled()).toBe(false) - - supervisors[1].dispose() - children[1].emit('exit', 0, null) - await vi.waitFor(() => - expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN + 2) - ) - const waitingChild = currentChild() - expect(waitingChild.sent).toContainEqual(expect.objectContaining({ dir: '/waiting-root' })) - acknowledgeWatcherSubscribe(waitingChild) - await expect(waiting).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.test.ts deleted file mode 100644 index 705174a0ec7..00000000000 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { acknowledgeWatcherSubscribe, FakeWatcherChild } from './parcel-watcher-process-test-child' -import { resetWatcherChildRegistryForTest } from './parcel-watcher-child-registry' -import { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' - -const { forkMock } = vi.hoisted(() => ({ forkMock: vi.fn() })) -vi.mock('node:child_process', () => ({ fork: forkMock })) -vi.mock('node:fs', () => ({ - existsSync: vi.fn(() => true), - mkdtempSync: vi.fn(() => '/tmp/orca-watcher-disposal-test'), - rmSync: vi.fn() -})) - -const children: FakeWatcherChild[] = [] -beforeEach(() => { - resetWatcherChildRegistryForTest() - forkMock.mockImplementation(() => { - const child = new FakeWatcherChild() - children.push(child) - return child - }) -}) -afterEach(() => { - for (const child of children.splice(0)) { - child.emit('close') - } - vi.clearAllMocks() - resetWatcherChildRegistryForTest() -}) - -async function subscribe(supervisor: WatcherProcessSupervisor): Promise { - const pending = supervisor.subscribe('/repo', vi.fn(), {}) - const child = children.at(-1)! - acknowledgeWatcherSubscribe(child) - await pending - return child -} - -it('awaited supervisor disposal retains a child after prior synchronous disposal', async () => { - const supervisor = new WatcherProcessSupervisor({ useInProcessVitestFallback: false }) - const child = await subscribe(supervisor) - supervisor.dispose() - const finished = vi.fn() - const shutdown = supervisor.disposeAndWait().then(finished) - await new Promise((resolve) => setImmediate(resolve)) - expect(finished).not.toHaveBeenCalled() - await expect(supervisor.subscribe('/another', vi.fn(), {})).rejects.toThrow() - expect(forkMock).toHaveBeenCalledOnce() - child.emit('close') - await shutdown - expect(finished).toHaveBeenCalledOnce() -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts deleted file mode 100644 index 1412720a1cb..00000000000 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WATCHER_PROCESS_EXIT_DEADLINE_MS } from './parcel-watcher-child-termination' -import { WATCHER_PROCESS_UNSUBSCRIBE_TIMEOUT_MS } from './parcel-watcher-host-subscriptions' -import { - acknowledgeWatcherSubscribe as ackSubscribe, - currentWatcherChild, - FakeWatcherChild, - trackPromiseSettlement -} from './parcel-watcher-process-test-child' - -const { existsSyncMock, forkMock, mkdtempSyncMock, rmSyncMock } = vi.hoisted(() => ({ - existsSyncMock: vi.fn(), - forkMock: vi.fn(), - mkdtempSyncMock: vi.fn(() => '/tmp/orca-watcher-unsubscribe-timeout-test'), - rmSyncMock: vi.fn() -})) - -vi.mock('node:child_process', () => ({ fork: forkMock })) -vi.mock('node:fs', () => ({ - existsSync: existsSyncMock, - mkdtempSync: mkdtempSyncMock, - rmSync: rmSyncMock -})) - -import { - disposeWatcherProcess, - resetWatcherProcessForTest, - subscribeViaWatcherProcess -} from './parcel-watcher-process' - -const currentChild = (): FakeWatcherChild => currentWatcherChild(forkMock) - -describe('watcher native unsubscribe timeout', () => { - beforeEach(() => { - resetWatcherProcessForTest() - vi.stubEnv('VITEST', '') - existsSyncMock.mockReturnValue(true) - forkMock.mockImplementation(() => new FakeWatcherChild()) - }) - - afterEach(() => { - disposeWatcherProcess() - vi.unstubAllEnvs() - vi.clearAllMocks() - }) - - it('restarts the shard and restores a healthy sibling', async () => { - vi.useFakeTimers() - try { - const firstPromise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) - const first = currentChild() - ackSubscribe(first, 0) - const firstSubscription = await firstPromise - const siblingInterruption = vi.fn() - const siblingPromise = subscribeViaWatcherProcess( - '/sibling', - vi.fn(), - {}, - { onInterruption: siblingInterruption } - ) - ackSubscribe(first) - await siblingPromise - - const unsubscribe = firstSubscription.unsubscribe() - const isSettled = trackPromiseSettlement(unsubscribe) - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_UNSUBSCRIBE_TIMEOUT_MS) - - expect(first.kill).toHaveBeenCalledTimes(1) - expect(isSettled()).toBe(false) - first.emit('exit', 0, null) - await expect(unsubscribe).resolves.toBeUndefined() - - const replacement = currentChild() - expect(replacement).not.toBe(first) - expect(replacement.sent.filter((message) => message.op === 'subscribe')).toEqual([ - expect.objectContaining({ dir: '/sibling' }) - ]) - ackSubscribe(replacement) - expect(siblingInterruption).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('spawns a fresh child after the idle kill misses the exit deadline', async () => { - vi.useFakeTimers() - try { - const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) - const first = currentChild() - ackSubscribe(first, 0) - const subscription = await promise - - const unsubscribe = subscription.unsubscribe().catch((error: unknown) => error) - expect(first.kill).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - expect(first.kill).toHaveBeenLastCalledWith('SIGKILL') - // Destructive removal must fail closed when physical exit is unproved. - const error = (await unsubscribe) as Error & { physicalExit?: Promise } - expect(error).toMatchObject({ - message: 'file watcher process did not exit after termination deadline', - physicalExit: expect.any(Promise) - }) - - // The idle child owned no records; its zombie must not prevent a fresh supervisor child. - const respawnPromise = subscribeViaWatcherProcess('/repo2', vi.fn(), {}) - expect(forkMock).toHaveBeenCalledTimes(2) - const second = currentChild() - expect(second).not.toBe(first) - expect(second.sent[0]).toMatchObject({ op: 'subscribe', dir: '/repo2' }) - ackSubscribe(second) - await expect(respawnPromise).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) - - first.emit('exit', null, 'SIGKILL') - await error.physicalExit - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('spawns a fresh child for a subscribe queued before an idle exit deadline miss', async () => { - vi.useFakeTimers() - try { - const promise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) - const first = currentChild() - ackSubscribe(first, 0) - const subscription = await promise - - const unsubscribe = subscription.unsubscribe().catch((error: unknown) => error) - const queued = subscribeViaWatcherProcess('/repo2', vi.fn(), {}) - - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - const error = (await unsubscribe) as Error & { physicalExit?: Promise } - expect(error).toMatchObject({ - message: 'file watcher process did not exit after termination deadline', - physicalExit: expect.any(Promise) - }) - - expect(forkMock).toHaveBeenCalledTimes(2) - const second = currentChild() - expect(second.sent[0]).toMatchObject({ op: 'subscribe', dir: '/repo2' }) - ackSubscribe(second) - await expect(queued).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) - - first.emit('exit', null, 'SIGKILL') - await error.physicalExit - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('rejects only after an unkillable child reaches its exit deadline', async () => { - vi.useFakeTimers() - try { - const firstPromise = subscribeViaWatcherProcess('/repo', vi.fn(), {}) - const child = currentChild() - ackSubscribe(child, 0) - const firstSubscription = await firstPromise - const siblingPromise = subscribeViaWatcherProcess('/sibling', vi.fn(), {}) - ackSubscribe(child) - await siblingPromise - - const result = firstSubscription.unsubscribe().catch((error: unknown) => error) - const isSettled = trackPromiseSettlement(result) - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_UNSUBSCRIBE_TIMEOUT_MS) - expect(isSettled()).toBe(false) - - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - const error = (await result) as Error & { physicalExit?: Promise } - expect(error).toMatchObject({ - message: 'file watcher process did not exit after termination deadline', - physicalExit: expect.any(Promise) - }) - expect(vi.getTimerCount()).toBe(0) - - child.emit('exit', 0, null) - await error.physicalExit - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/rebinding-file-watch.test.ts b/src/main/ipc/filesystem/watcher-process/rebinding-file-watch.test.ts deleted file mode 100644 index d12a130dae6..00000000000 --- a/src/main/ipc/filesystem/watcher-process/rebinding-file-watch.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { watchFileAcrossReplacement, type RebindingFileWatch } from './rebinding-file-watch' - -let directory: string -let fileWatch: RebindingFileWatch | null - -beforeEach(() => { - directory = mkdtempSync(join(tmpdir(), 'orca-rebinding-file-watch-')) - fileWatch = null -}) - -afterEach(async () => { - await fileWatch?.close() - rmSync(directory, { recursive: true, force: true }) -}) - -function replaceAtomically(path: string, content: string): void { - const temporary = `${path}.${Math.random().toString(36).slice(2)}.tmp` - writeFileSync(temporary, content) - renameSync(temporary, path) -} - -async function settle(): Promise { - await new Promise((resolve) => setTimeout(resolve, 300)) -} - -describe('watchFileAcrossReplacement', () => { - it('keeps reporting writes across repeated atomic replacement', async () => { - const path = join(directory, 'index') - writeFileSync(path, '0') - const onChange = vi.fn() - fileWatch = watchFileAcrossReplacement(path, onChange, (error) => { - throw error - }) - await settle() - onChange.mockClear() - - for (const content of ['1', '2', '3']) { - const before = onChange.mock.calls.length - replaceAtomically(path, content) - await vi.waitFor(() => expect(onChange.mock.calls.length).toBeGreaterThan(before), { - timeout: 5_000 - }) - // Let the post-event re-stat rebind to the new inode before the next write. - await settle() - } - const before = onChange.mock.calls.length - writeFileSync(path, 'in place') - await vi.waitFor(() => expect(onChange.mock.calls.length).toBeGreaterThan(before), { - timeout: 5_000 - }) - }) - - it('ignores writes to siblings and subdirectories of the watched file', async () => { - const path = join(directory, 'HEAD') - writeFileSync(path, 'ref: refs/heads/main') - const onChange = vi.fn() - fileWatch = watchFileAcrossReplacement(path, onChange, (error) => { - throw error - }) - await settle() - onChange.mockClear() - - writeFileSync(join(directory, 'FETCH_HEAD'), 'noise') - replaceAtomically(join(directory, 'last-status.json'), '{}') - await settle() - - expect(onChange).not.toHaveBeenCalled() - }) - - it('binds a file created after the watch started once refreshed', async () => { - const path = join(directory, 'packed-refs') - const onChange = vi.fn() - fileWatch = watchFileAcrossReplacement(path, onChange, (error) => { - throw error - }) - expect(fileWatch.isBound()).toBe(false) - await fileWatch.refresh() - expect(onChange).not.toHaveBeenCalled() - - writeFileSync(path, 'created') - await fileWatch.refresh() - expect(onChange).toHaveBeenCalledOnce() - expect(fileWatch.isBound()).toBe(true) - await settle() - onChange.mockClear() - - writeFileSync(path, 'updated') - await vi.waitFor(() => expect(onChange).toHaveBeenCalled(), { timeout: 5_000 }) - }) - - it('drops the binding when the file is deleted and reports nothing after close', async () => { - const path = join(directory, 'config') - writeFileSync(path, 'a') - const onChange = vi.fn() - fileWatch = watchFileAcrossReplacement(path, onChange, (error) => { - throw error - }) - await settle() - rmSync(path) - await vi.waitFor(() => expect(onChange).toHaveBeenCalled(), { timeout: 5_000 }) - expect(fileWatch.isBound()).toBe(false) - - writeFileSync(path, 'b') - await fileWatch.refresh() - expect(fileWatch.isBound()).toBe(true) - await fileWatch.close() - onChange.mockClear() - writeFileSync(path, 'c') - await settle() - expect(onChange).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-root-path-rewrite.test.ts b/src/main/ipc/filesystem/watcher-process/root-paths/parcel-watcher-root-path-rewrite.test.ts similarity index 83% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-root-path-rewrite.test.ts rename to src/main/ipc/filesystem/watcher-process/root-paths/parcel-watcher-root-path-rewrite.test.ts index f776a2f9ad7..b31ec1c66c8 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-root-path-rewrite.test.ts +++ b/src/main/ipc/filesystem/watcher-process/root-paths/parcel-watcher-root-path-rewrite.test.ts @@ -11,7 +11,7 @@ import { acknowledgeWatcherSubscribe, currentWatcherChild, FakeWatcherChild -} from './parcel-watcher-process-test-child' +} from '../supervision/parcel-watcher-process-test-child' const { forkMock, existsSyncMock, mkdtempSyncMock, parcelSubscribeMock, rmSyncMock } = vi.hoisted( () => ({ @@ -40,10 +40,9 @@ import { disposeWatcherProcess, resetRuntimeWatcherProcessForTest, resetWatcherProcessForTest, - subscribeViaRuntimeWatcherProcess, subscribeViaWatcherProcess -} from './parcel-watcher-process' -import type { WatcherProcessEvent } from './parcel-watcher-process-protocol' +} from '../parcel-watcher-process' +import type { WatcherProcessEvent } from '../parcel-watcher-process-protocol' describe('watcher-process root path rewrite', () => { let root: AliasedWatcherRoot | null = null @@ -98,14 +97,4 @@ describe('watcher-process root path rewrite', () => { }) // The runtime pool is also what a relay host uses for every SSH worktree watch. - it('rewrites resolved-alias paths for runtime and relay watches', async () => { - root = await createAliasedWatcherRoot('watcher-rewrite-') - const delivered = await subscribeAndEmit(subscribeViaRuntimeWatcherProcess, root.aliasRoot, [ - { type: 'create', path: join(root.realRoot, 'docs', 'notes.md') } - ]) - - expect(delivered).toEqual([ - [{ type: 'create', path: join(root.aliasRoot, 'docs', 'notes.md') }] - ]) - }) }) diff --git a/src/main/ipc/filesystem/watcher-process/watcher-aliased-root-fixture.ts b/src/main/ipc/filesystem/watcher-process/root-paths/watcher-aliased-root-fixture.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/watcher-aliased-root-fixture.ts rename to src/main/ipc/filesystem/watcher-process/root-paths/watcher-aliased-root-fixture.ts diff --git a/src/main/ipc/filesystem/watcher-process/watcher-directory-identity.ts b/src/main/ipc/filesystem/watcher-process/root-paths/watcher-directory-identity.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/watcher-directory-identity.ts rename to src/main/ipc/filesystem/watcher-process/root-paths/watcher-directory-identity.ts diff --git a/src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.test.ts b/src/main/ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite.test.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.test.ts rename to src/main/ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite.test.ts diff --git a/src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts b/src/main/ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts rename to src/main/ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite.ts diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-disposal-owners.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-disposal-owners.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-disposal-owners.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-disposal-owners.ts diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pending-assignment.ts similarity index 83% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pending-assignment.ts index 57b48da725e..7c8bcc7e242 100644 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.ts +++ b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pending-assignment.ts @@ -1,6 +1,6 @@ -import { WatcherProcessFailure } from './parcel-watcher-process-failure' -import type { WatcherProcessHooks } from './parcel-watcher-process-subscription' -import { PromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import type { WatcherProcessHooks } from '../parcel-watcher-process-subscription' +import { PromiseSettlementWaiters } from '../../../../../shared/promise-settlement-waiters' const DEFAULT_QUARANTINE_WAIT_TIMEOUT_MS = 60_000 @@ -16,10 +16,6 @@ export class RuntimeWatcherPendingAssignment { this.settlementWaiters = new PromiseSettlementWaiters(basePromise, () => this.notifySettled()) } - get waiterCount(): number { - return this.settlementWaiters.waiterCount - } - wait(hooks: WatcherProcessHooks, onGranted: (assignment: T) => void): Promise { return this.settlementWaiters.wait({ signal: hooks.signal, diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-lifecycle.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pool-lifecycle.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-lifecycle.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pool-lifecycle.ts index de7f47e4055..41ce192f3d4 100644 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-lifecycle.ts +++ b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pool-lifecycle.ts @@ -1,4 +1,4 @@ -import { WatcherProcessFailure } from './parcel-watcher-process-failure' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' export class RuntimeWatcherPoolLifecycle { readonly isolatedRoots = new Set() diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-state.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pool-state.ts similarity index 89% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-state.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pool-state.ts index a99c9b93895..f87f1a2c41c 100644 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-state.ts +++ b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-pool-state.ts @@ -1,4 +1,4 @@ -import type { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' +import type { WatcherProcessSupervisor } from '../supervision/parcel-watcher-process-supervisor' export type RuntimeWatcherPoolSupervisor = Pick & Partial> diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-predecessor-barriers.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-predecessor-barriers.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-predecessor-barriers.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-predecessor-barriers.ts index f5301eb5432..6b94713a130 100644 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-predecessor-barriers.ts +++ b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-predecessor-barriers.ts @@ -1,4 +1,4 @@ -import type { WatcherProcessFailure } from './parcel-watcher-process-failure' +import type { WatcherProcessFailure } from '../parcel-watcher-process-failure' /** Retain exact failed-child ownership until its native handles are gone. */ export class RuntimeWatcherPredecessorBarriers { diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-process-pool.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-process-pool.ts similarity index 97% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-process-pool.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-process-pool.ts index 633ef7b0ac3..89dbc1cb010 100644 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-process-pool.ts +++ b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-process-pool.ts @@ -1,11 +1,11 @@ -import * as failures from './parcel-watcher-process-failure' -import { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' -import type { WatcherProcessSubscribeOptions } from './parcel-watcher-process-protocol' +import * as failures from '../parcel-watcher-process-failure' +import { WatcherProcessSupervisor } from '../supervision/parcel-watcher-process-supervisor' +import type { WatcherProcessSubscribeOptions } from '../parcel-watcher-process-protocol' import type { WatcherProcessCallback, WatcherProcessHooks, WatcherProcessSubscription -} from './parcel-watcher-process-subscription' +} from '../parcel-watcher-process-subscription' import { RuntimeWatcherPendingAssignment } from './runtime-watcher-pending-assignment' import { RuntimeWatcherDisposalOwners } from './runtime-watcher-disposal-owners' import { RuntimeWatcherPoolLifecycle } from './runtime-watcher-pool-lifecycle' diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-quarantine-queue.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-quarantine-queue.ts similarity index 96% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-quarantine-queue.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-quarantine-queue.ts index bc2b4cf5fd4..fecec423a60 100644 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-quarantine-queue.ts +++ b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-quarantine-queue.ts @@ -1,4 +1,4 @@ -import { WatcherProcessFailure } from './parcel-watcher-process-failure' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' type QuarantineWaiter = { dir: string diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-subscription-failure.ts b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-subscription-failure.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/runtime-watcher-subscription-failure.ts rename to src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-subscription-failure.ts index 5e238cab8ed..87e27c6c151 100644 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-subscription-failure.ts +++ b/src/main/ipc/filesystem/watcher-process/runtime-pool/runtime-watcher-subscription-failure.ts @@ -1,7 +1,7 @@ import { isWatcherProcessFailure, type WatcherProcessFailure -} from './parcel-watcher-process-failure' +} from '../parcel-watcher-process-failure' export function handleRuntimeWatcherSubscriptionFailure( error: unknown, diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-disposal-owners.test.ts b/src/main/ipc/filesystem/watcher-process/runtime-watcher-disposal-owners.test.ts deleted file mode 100644 index a889db510a4..00000000000 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-disposal-owners.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { RuntimeWatcherDisposalOwners } from './runtime-watcher-disposal-owners' - -function owner() { - return { - dispose: vi.fn(), - subscribe: vi.fn(), - disposeAndWait: vi.fn(async () => {}) - } -} - -it('retains retired cleanup and joins concurrent shutdown callers', async () => { - const owners = new RuntimeWatcherDisposalOwners() - const retired = owner() - const pending = Promise.withResolvers() - retired.disposeAndWait.mockReturnValue(pending.promise) - owners.retire(retired) - const shutdown = owners.disposeAndWait(() => {}) - expect(owners.disposeAndWait(() => {})).toBe(shutdown) - const finished = vi.fn() - const result = shutdown.then(finished) - await Promise.resolve() - expect(finished).not.toHaveBeenCalled() - expect(retired.disposeAndWait).toHaveBeenCalledOnce() - pending.resolve() - await result - await owners.disposeAndWait(() => {}) - expect(retired.disposeAndWait).toHaveBeenCalledOnce() -}) - -it('does not retry a newly failed attempt until a later explicit shutdown call', async () => { - const owners = new RuntimeWatcherDisposalOwners() - const failed = owner() - const sibling = owner() - const pending = Promise.withResolvers() - const failure = new Error('child still live') - failed.disposeAndWait.mockRejectedValueOnce(failure) - sibling.disposeAndWait.mockReturnValue(pending.promise) - const finished = vi.fn() - const shutdown = owners.disposeAndWait(() => { - owners.retire(failed) - owners.retire(sibling) - }) - const result = shutdown.catch((error: unknown) => { - finished() - return error - }) - await new Promise((resolve) => setImmediate(resolve)) - expect(finished).not.toHaveBeenCalled() - expect(owners.disposeAndWait(() => {})).toBe(shutdown) - expect(failed.disposeAndWait).toHaveBeenCalledOnce() - pending.resolve() - expect(await result).toMatchObject({ errors: [failure] }) - await owners.disposeAndWait(() => {}) - expect(failed.disposeAndWait).toHaveBeenCalledTimes(2) - expect(sibling.disposeAndWait).toHaveBeenCalledOnce() -}) - -it('retains synchronous failures and attempts sibling owners', async () => { - const owners = new RuntimeWatcherDisposalOwners() - const failed = owner() - const sibling = owner() - failed.disposeAndWait.mockImplementationOnce(() => { - throw new Error('sync failure') - }) - await expect( - owners.disposeAndWait(() => { - owners.retire(failed) - owners.retire(sibling) - }) - ).rejects.toThrow('watcher_pool_shutdown_incomplete') - expect(sibling.disposeAndWait).toHaveBeenCalledOnce() - await owners.disposeAndWait(() => {}) - expect(failed.disposeAndWait).toHaveBeenCalledTimes(2) -}) - -it('publishes the retained attempt before a synchronous disposal callback reenters', async () => { - const owners = new RuntimeWatcherDisposalOwners() - const child = owner() - const pending = Promise.withResolvers() - let nested: Promise | undefined - child.disposeAndWait.mockImplementation(() => { - owners.retire(child) - nested = owners.disposeAndWait(() => {}) - return pending.promise - }) - const shutdown = owners.disposeAndWait(() => owners.retire(child)) - expect(nested).toBe(shutdown) - expect(child.disposeAndWait).toHaveBeenCalledOnce() - pending.resolve() - await shutdown -}) - -it('refuses to acknowledge a supervisor without a physical-disposal API', async () => { - const owners = new RuntimeWatcherDisposalOwners() - const legacy = { dispose: vi.fn(), subscribe: vi.fn() } - await expect(owners.disposeAndWait(() => owners.retire(legacy))).rejects.toMatchObject({ - errors: [ - expect.objectContaining({ message: 'watcher_supervisor_awaited_disposal_unavailable' }) - ] - }) - expect(legacy.dispose).toHaveBeenCalledOnce() -}) diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts b/src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts deleted file mode 100644 index e73468aa799..00000000000 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RuntimeWatcherPendingAssignment } from './runtime-watcher-pending-assignment' - -describe('RuntimeWatcherPendingAssignment', () => { - it('removes ten thousand cancelled assignment callers while one anchor remains', async () => { - let resolveAssignment: (value: number) => void = () => undefined - const assignment = new RuntimeWatcherPendingAssignment( - new Promise((resolve) => { - resolveAssignment = resolve - }), - vi.fn(), - vi.fn() - ) - const anchor = assignment.wait({}, vi.fn()) - const controllers = Array.from({ length: 10_000 }, () => new AbortController()) - const cancelled = controllers.map((controller) => - assignment.wait({ signal: controller.signal }, vi.fn()).catch((error) => error) - ) - - for (const controller of controllers) { - controller.abort() - } - await Promise.all(cancelled) - - expect(assignment.waiterCount).toBe(1) - resolveAssignment(42) - await expect(anchor).resolves.toBe(42) - expect(assignment.waiterCount).toBe(0) - }) - - it('releases ownership for an already-aborted first caller', async () => { - const controller = new AbortController() - controller.abort() - const onNoWaiters = vi.fn() - const onSettled = vi.fn() - const assignment = new RuntimeWatcherPendingAssignment( - new Promise(() => {}), - onNoWaiters, - onSettled - ) - - await expect(assignment.wait({ signal: controller.signal }, vi.fn())).rejects.toMatchObject({ - code: 'subscribe_aborted' - }) - - expect(onNoWaiters).toHaveBeenCalledOnce() - expect(onSettled).toHaveBeenCalledOnce() - expect(assignment.waiterCount).toBe(0) - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-shutdown.test.ts b/src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-shutdown.test.ts deleted file mode 100644 index 1f37f3540c5..00000000000 --- a/src/main/ipc/filesystem/watcher-process/runtime-watcher-pool-shutdown.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { RuntimeWatcherProcessPool } from './runtime-watcher-process-pool' -import type { WatcherProcessHooks } from './parcel-watcher-process-subscription' -import { WatcherProcessFailure } from './parcel-watcher-process-failure' - -function supervisor() { - const pending = Promise.withResolvers() - let hooks: WatcherProcessHooks | undefined - return { - pending, - dispose: vi.fn(), - disposeAndWait: vi.fn(() => pending.promise), - subscribe: vi.fn( - async ( - _dir: string, - _callback: unknown, - _options: unknown, - options?: WatcherProcessHooks - ) => { - hooks = options - return { unsubscribe: vi.fn(async () => {}) } - } - ), - fail: () => - hooks?.onTerminalError?.( - new WatcherProcessFailure('failed', 'supervisor', 'process_unavailable') - ) - } -} - -it('awaits retired and replacement supervisors after logical retirement removed the old slot', async () => { - const old = supervisor() - const current = supervisor() - const create = vi.fn().mockReturnValueOnce(old).mockReturnValueOnce(current) - const pool = new RuntimeWatcherProcessPool({ createSupervisor: create }) - await pool.subscribe('/first', vi.fn(), {}) - old.fail() - await new Promise((resolve) => setImmediate(resolve)) - expect(old.disposeAndWait).toHaveBeenCalledOnce() - await pool.subscribe('/second', vi.fn(), {}) - const finished = vi.fn() - const shutdown = pool.disposeAndWait() - expect(pool.disposeAndWait()).toBe(shutdown) - const result = shutdown.then(finished) - current.pending.resolve() - await new Promise((resolve) => setImmediate(resolve)) - expect(finished).not.toHaveBeenCalled() - await expect(pool.subscribe('/third', vi.fn(), {})).rejects.toThrow('disposed') - expect(create).toHaveBeenCalledTimes(2) - old.pending.resolve() - await result -}) - -it('retains failure after synchronous pool disposal and retries it explicitly', async () => { - const child = supervisor() - const failure = new Error('child still running') - child.disposeAndWait.mockRejectedValueOnce(failure) - const pool = new RuntimeWatcherProcessPool({ createSupervisor: () => child }) - await pool.subscribe('/first', vi.fn(), {}) - const shutdown = pool.disposeAndWait() - await expect(shutdown).rejects.toMatchObject({ errors: [failure] }) - const retry = pool.disposeAndWait() - expect(child.disposeAndWait).toHaveBeenCalledTimes(2) - child.pending.resolve() - await retry -}) - -it('does not duplicate termination when a queued retirement races with synchronous disposal', async () => { - const child = supervisor() - const pool = new RuntimeWatcherProcessPool({ createSupervisor: () => child }) - await pool.subscribe('/first', vi.fn(), {}) - child.fail() - pool.dispose() - const shutdown = pool.disposeAndWait() - await new Promise((resolve) => setImmediate(resolve)) - expect(child.disposeAndWait).toHaveBeenCalledOnce() - child.pending.resolve() - await shutdown -}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-restart.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-cancellation-restart.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-restart.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-cancellation-restart.ts index 21f59d07f1d..252a222429a 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-restart.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-cancellation-restart.ts @@ -8,10 +8,10 @@ import type { WatcherCancellationTracker } from './parcel-watcher-cancellation-t import { createWatcherChildTerminationFailure, terminateWatcherChild -} from './parcel-watcher-child-termination' +} from '../child-lifecycle/parcel-watcher-child-termination' import { resetPendingSubscribeAttempt } from './parcel-watcher-pending-subscribe' -import { WatcherProcessFailure } from './parcel-watcher-process-failure' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import type { WatcherProcessSubscriptionRecord } from '../parcel-watcher-process-subscription' export function restoreWatcherRecordsAfterCancellation( records: Map, diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-cancellation-tracker.ts similarity index 90% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-cancellation-tracker.ts index 65d7cfcb136..e2c6ef6b18a 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-cancellation-tracker.ts @@ -1,5 +1,5 @@ import type { ChildProcess } from 'node:child_process' -import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS } from '../../../../shared/file-watch/runtime-file-watch-limits' +import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS as WATCHER_PROCESS_CANCEL_TIMEOUT_MS } from '../../../../../shared/file-watch/runtime-file-watch-limits' type CancelledSubscribe = { child: ChildProcess @@ -9,7 +9,6 @@ type CancelledSubscribe = { } // Allow legitimate crawls without letting wedged teardown block destructive cleanup indefinitely. -export const WATCHER_PROCESS_CANCEL_TIMEOUT_MS = RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS export class WatcherCancellationTracker { private readonly entries = new Map() diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-recovery.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-child-recovery.ts similarity index 93% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-child-recovery.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-child-recovery.ts index 124154eb563..de643134aa1 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-recovery.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-child-recovery.ts @@ -8,11 +8,11 @@ import type { WatcherCancellationTracker } from './parcel-watcher-cancellation-t import { createWatcherChildTerminationFailure, terminateWatcherChild -} from './parcel-watcher-child-termination' +} from '../child-lifecycle/parcel-watcher-child-termination' import { resetPendingSubscribeAttempt } from './parcel-watcher-pending-subscribe' import type { WatcherProcessCrashFuse } from './parcel-watcher-crash-fuse' -import { WatcherProcessFailure } from './parcel-watcher-process-failure' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import type { WatcherProcessSubscriptionRecord } from '../parcel-watcher-process-subscription' export function recoverWatcherRecordsAfterChildGone( records: Map, diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse-recovery.test.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse-recovery.test.ts similarity index 97% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse-recovery.test.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse-recovery.test.ts index b123e6f90fa..fbc96c484f3 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse-recovery.test.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse-recovery.test.ts @@ -18,7 +18,7 @@ vi.mock('node:fs', () => ({ rmSync: vi.fn() })) -import { createWatcherProcessSupervisor } from './parcel-watcher-process' +import { createWatcherProcessSupervisor } from '../parcel-watcher-process' const currentChild = (): FakeChild => currentWatcherChild(forkMock) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse.test.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts similarity index 82% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse.test.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts index 4d13767db1e..df203247d25 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse.test.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts @@ -1,7 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CRASH_FUSE_COOLDOWN_INITIAL_MS, - CRASH_FUSE_COOLDOWN_MAX_MS, CRASH_FUSE_TRIAL_STABLE_MS, WatcherProcessCrashFuse } from './parcel-watcher-crash-fuse' @@ -22,24 +21,6 @@ describe('WatcherProcessCrashFuse', () => { vi.restoreAllMocks() }) - it('reopens on a single trial crash with a doubled, capped cooldown', () => { - const fuse = new WatcherProcessCrashFuse() - tripAt(fuse, 0) - let openedAt = 80_000 - let cooldown = CRASH_FUSE_COOLDOWN_INITIAL_MS - for (let trip = 0; trip < 6; trip++) { - expect(fuse.isOpen(openedAt + cooldown - 1)).toBe(true) - const trialAt = openedAt + cooldown - expect(fuse.isOpen(trialAt)).toBe(false) - openedAt = trialAt + 1_000 - fuse.recordCrash(openedAt) - expect(fuse.isOpen(openedAt)).toBe(true) - cooldown = Math.min(cooldown * 2, CRASH_FUSE_COOLDOWN_MAX_MS) - } - expect(fuse.isOpen(openedAt + CRASH_FUSE_COOLDOWN_MAX_MS - 1)).toBe(true) - expect(cooldown).toBe(CRASH_FUSE_COOLDOWN_MAX_MS) - }) - it('resets escalation only after the trial child confirms delivery for the stable period', () => { const fuse = new WatcherProcessCrashFuse() tripAt(fuse, 0) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-crash-fuse.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts index b478775d1b7..de1477deca2 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts @@ -1,7 +1,9 @@ import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WATCHER_PROCESS_CANCEL_TIMEOUT_MS } from './parcel-watcher-cancellation-tracker' -import { WATCHER_PROCESS_EXIT_DEADLINE_MS } from './parcel-watcher-child-termination' +import { + RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS as WATCHER_PROCESS_CANCEL_TIMEOUT_MS, + RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS as WATCHER_PROCESS_EXIT_DEADLINE_MS +} from '../../../../../shared/file-watch/runtime-file-watch-limits' const { existsSyncMock, forkMock, mkdtempSyncMock, rmSyncMock } = vi.hoisted(() => ({ existsSyncMock: vi.fn(), @@ -22,8 +24,8 @@ import { disposeWatcherProcess, resetWatcherProcessForTest, subscribeViaWatcherProcess -} from './parcel-watcher-process' -import type { WatcherProcessSubscription } from './parcel-watcher-process-subscription' +} from '../parcel-watcher-process' +import type { WatcherProcessSubscription } from '../parcel-watcher-process-subscription' type SentMessage = { op: string; id: number } @@ -356,25 +358,6 @@ describe('watcher disconnect termination', () => { } }) - it('rejects unsubscribe at the physical-exit deadline', async () => { - vi.useFakeTimers() - try { - const { child, unsubscribe } = await subscribePair() - const failure = expect(unsubscribe()).rejects.toThrow( - 'file watcher process did not exit after termination deadline' - ) - child.connected = false - child.emit('disconnect') - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - - await failure - expect(forkMock).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - it('retires the child before settling a rejected native unsubscribe', async () => { const firstPromise = subscribeViaWatcherProcess('/first', vi.fn(), {}) const child = currentChild() diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-host-subscriptions.ts similarity index 95% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-host-subscriptions.ts index 577f3ee1b9f..5e1bd180469 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-host-subscriptions.ts @@ -3,18 +3,16 @@ import { resetPendingSubscribeAttempt, takePendingSubscribe } from './parcel-watcher-pending-subscribe' -import { isWatcherProcessFailure, WatcherProcessFailure } from './parcel-watcher-process-failure' -import type { HostToWatcherMessage, WatcherToHostMessage } from './parcel-watcher-process-protocol' +import { isWatcherProcessFailure, WatcherProcessFailure } from '../parcel-watcher-process-failure' +import type { HostToWatcherMessage, WatcherToHostMessage } from '../parcel-watcher-process-protocol' import type { WatcherProcessSubscription, WatcherProcessSubscriptionRecord -} from './parcel-watcher-process-subscription' -import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS } from '../../../../shared/file-watch/runtime-file-watch-limits' +} from '../parcel-watcher-process-subscription' +import { RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS as WATCHER_PROCESS_UNSUBSCRIBE_TIMEOUT_MS } from '../../../../../shared/file-watch/runtime-file-watch-limits' export type PendingWatcherUnsubscribe = (error?: Error) => void -export const WATCHER_PROCESS_UNSUBSCRIBE_TIMEOUT_MS = RUNTIME_FILE_WATCH_CANCEL_TIMEOUT_MS - const terminalTeardownFailures = new WeakMap() const pendingRecordUnsubscribes = new WeakMap>() const hostSubscriptions = new WeakMap< diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-interrupted-cancellation.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-interrupted-cancellation.ts similarity index 84% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-interrupted-cancellation.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-interrupted-cancellation.ts index 05b6f28eb17..bff8aec3654 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-interrupted-cancellation.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-interrupted-cancellation.ts @@ -1,6 +1,6 @@ import { resetPendingSubscribeAttempt } from './parcel-watcher-pending-subscribe' -import type { WatcherProcessFailure } from './parcel-watcher-process-failure' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' +import type { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import type { WatcherProcessSubscriptionRecord } from '../parcel-watcher-process-subscription' export function cancelInterruptedWatcherSubscribe(args: { record: WatcherProcessSubscriptionRecord diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-native-error-retirement.test.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts similarity index 97% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-native-error-retirement.test.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts index eb75dc9a8ef..88677d07b47 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-native-error-retirement.test.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts @@ -15,7 +15,7 @@ vi.mock('node:fs', () => ({ })) import { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' -import { WATCHER_PROCESS_EXIT_DEADLINE_MS } from './parcel-watcher-child-termination' +import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS as WATCHER_PROCESS_EXIT_DEADLINE_MS } from '../../../../../shared/file-watch/runtime-file-watch-limits' describe('native watcher error retirement', () => { let supervisor: WatcherProcessSupervisor diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-pending-cancellation.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-pending-cancellation.ts similarity index 90% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-pending-cancellation.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-pending-cancellation.ts index 877f85d275a..497654ed7cd 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-pending-cancellation.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-pending-cancellation.ts @@ -1,8 +1,8 @@ import type { ChildProcess } from 'node:child_process' import type { WatcherCancellationTracker } from './parcel-watcher-cancellation-tracker' import { takePendingSubscribe } from './parcel-watcher-pending-subscribe' -import type { WatcherProcessFailure } from './parcel-watcher-process-failure' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' +import type { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import type { WatcherProcessSubscriptionRecord } from '../parcel-watcher-process-subscription' type CancelPendingWatcherSubscribeOptions = { record: WatcherProcessSubscriptionRecord diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-pending-subscribe.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-pending-subscribe.ts similarity index 95% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-pending-subscribe.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-pending-subscribe.ts index f37c7b3dbf6..1bc1c5eadd9 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-pending-subscribe.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-pending-subscribe.ts @@ -1,8 +1,8 @@ -import { WatcherProcessFailure } from './parcel-watcher-process-failure' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' import type { PendingWatcherProcessSubscribe, WatcherProcessSubscriptionRecord -} from './parcel-watcher-process-subscription' +} from '../parcel-watcher-process-subscription' export function installPendingSubscribeControls( record: WatcherProcessSubscriptionRecord, diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-supervisor-options.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor-options.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-process-supervisor-options.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor-options.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-supervisor.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-process-supervisor.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor.ts index 2da4fc37e95..06d0ea5051a 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-supervisor.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor.ts @@ -1,19 +1,19 @@ import type { ChildProcess } from 'node:child_process' import { restartCancelledWatcherChild } from './parcel-watcher-cancellation-restart' import { WatcherCancellationTracker } from './parcel-watcher-cancellation-tracker' -import { getWatcherProcessEntryPath, watcherProcessEntryExists } from './parcel-watcher-entry-path' -import { WatcherChildSlot } from './parcel-watcher-child-slot' -import * as termination from './parcel-watcher-child-termination' -import { launchWatcherChild } from './parcel-watcher-child-launch' -import { sendToWatcherChild } from './parcel-watcher-child-messaging' +import { getWatcherProcessEntryPath, watcherProcessEntryExists } from '../parcel-watcher-entry-path' +import { WatcherChildSlot } from '../child-lifecycle/parcel-watcher-child-slot' +import * as termination from '../child-lifecycle/parcel-watcher-child-termination' +import { launchWatcherChild } from '../child-lifecycle/parcel-watcher-child-launch' +import { sendToWatcherChild } from '../child-lifecycle/parcel-watcher-child-messaging' import { recoverWatcherRecordsAfterChildGone, terminateDisconnectedWatcherChild } from './parcel-watcher-child-recovery' -import { resetWatcherChildRegistryForTest } from './parcel-watcher-child-registry' +import { resetWatcherChildRegistryForTest } from '../child-lifecycle/parcel-watcher-child-registry' import { WatcherSupervisorCapacityWait } from './parcel-watcher-supervisor-capacity-wait' import { WatcherProcessCrashFuse } from './parcel-watcher-crash-fuse' -import { WatcherDeliveryHealthMonitor } from './parcel-watcher-delivery-health' +import { WatcherDeliveryHealthMonitor } from '../event-delivery/parcel-watcher-delivery-health' import { cancelInterruptedWatcherSubscribe } from './parcel-watcher-interrupted-cancellation' import { type PendingWatcherUnsubscribe, @@ -21,17 +21,17 @@ import { resolvePendingWatcherUnsubscribes } from './parcel-watcher-host-subscriptions' import { cancelPendingWatcherSubscribe } from './parcel-watcher-pending-cancellation' -import type { WatcherProcessFailure } from './parcel-watcher-process-failure' +import type { WatcherProcessFailure } from '../parcel-watcher-process-failure' import type { WatcherProcessSubscribeOptions, WatcherToHostMessage -} from './parcel-watcher-process-protocol' +} from '../parcel-watcher-process-protocol' import type { WatcherProcessCallback, WatcherProcessHooks, WatcherProcessSubscription, WatcherProcessSubscriptionRecord -} from './parcel-watcher-process-subscription' +} from '../parcel-watcher-process-subscription' import type { WatcherProcessSupervisorOptions } from './parcel-watcher-process-supervisor-options' import { sendWatcherSubscribe, @@ -39,7 +39,7 @@ import { } from './parcel-watcher-supervisor-subscribe' import { disposeWatcherSupervisor } from './parcel-watcher-supervisor-disposal' import { handleWatcherSupervisorMessage } from './parcel-watcher-supervisor-message' -import { WatcherOwnedChildren } from './parcel-watcher-owned-children' +import { WatcherOwnedChildren } from '../child-lifecycle/parcel-watcher-owned-children' export class WatcherProcessSupervisor { private nextSubscriptionId = 1 diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-process-test-child.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-test-child.ts similarity index 100% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-process-test-child.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-process-test-child.ts diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity-wait.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity-wait.ts similarity index 92% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity-wait.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity-wait.ts index 87115f07aed..c199b8f07d1 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity-wait.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity-wait.ts @@ -1,9 +1,9 @@ import { onWatcherChildCapacityAvailable, WatcherChildCapacityError -} from './parcel-watcher-child-registry' -import { watcherHostFailure, WatcherProcessFailure } from './parcel-watcher-process-failure' -import { PromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' +} from '../child-lifecycle/parcel-watcher-child-registry' +import { watcherHostFailure, WatcherProcessFailure } from '../parcel-watcher-process-failure' +import { PromiseSettlementWaiters } from '../../../../../shared/promise-settlement-waiters' type CapacityWaitState = { waiters: PromiseSettlementWaiters diff --git a/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts new file mode 100644 index 00000000000..1a1ad5db6d8 --- /dev/null +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts @@ -0,0 +1,97 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { + MAX_PHYSICAL_WATCHER_CHILDREN, + resetWatcherChildRegistryForTest +} from '../child-lifecycle/parcel-watcher-child-registry' +import { + acknowledgeWatcherSubscribe, + currentWatcherChild, + FakeWatcherChild, + trackPromiseSettlement +} from './parcel-watcher-process-test-child' +import type { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' + +const { existsSyncMock, forkMock, mkdtempSyncMock, rmSyncMock } = vi.hoisted(() => ({ + existsSyncMock: vi.fn(), + forkMock: vi.fn(), + mkdtempSyncMock: vi.fn(() => '/tmp/orca-watcher-capacity-supervisor-test'), + rmSyncMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ fork: forkMock })) +vi.mock('node:fs', () => ({ + existsSync: existsSyncMock, + mkdtempSync: mkdtempSyncMock, + rmSync: rmSyncMock +})) + +import { createWatcherProcessSupervisor } from '../parcel-watcher-process' + +const supervisors: WatcherProcessSupervisor[] = [] + +function createSupervisor(): WatcherProcessSupervisor { + const supervisor = createWatcherProcessSupervisor() + supervisors.push(supervisor) + return supervisor +} + +function currentChild(): FakeWatcherChild { + return currentWatcherChild(forkMock) +} + +describe('WatcherProcessSupervisor capacity wait', () => { + beforeEach(() => { + resetWatcherChildRegistryForTest() + vi.stubEnv('VITEST', '') + existsSyncMock.mockReturnValue(true) + forkMock.mockImplementation(() => new FakeWatcherChild()) + }) + + afterEach(() => { + for (const supervisor of supervisors.splice(0)) { + supervisor.dispose() + } + resetWatcherChildRegistryForTest() + vi.unstubAllEnvs() + vi.clearAllMocks() + vi.useRealTimers() + }) + + it('keeps waiting when crash recovery reclaims the announced slot', async () => { + const children: FakeWatcherChild[] = [] + for (let index = 0; index < MAX_PHYSICAL_WATCHER_CHILDREN; index++) { + const supervisor = createSupervisor() + const subscription = supervisor.subscribe(`/active-${index}`, vi.fn(), {}) + const child = currentChild() + children.push(child) + acknowledgeWatcherSubscribe(child) + await subscription + } + + const waitingSupervisor = createSupervisor() + const waiting = waitingSupervisor.subscribe('/waiting-root', vi.fn(), {}) + const waitingSettled = trackPromiseSettlement(waiting) + await Promise.resolve() + expect(waitingSettled()).toBe(false) + + children[0].connected = false + children[0].emit('exit', null, 'SIGSEGV') + await vi.waitFor(() => + expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN + 1) + ) + await Promise.resolve() + await Promise.resolve() + expect(waitingSettled()).toBe(false) + + supervisors[1].dispose() + children[1].emit('exit', 0, null) + await vi.waitFor(() => + expect(forkMock).toHaveBeenCalledTimes(MAX_PHYSICAL_WATCHER_CHILDREN + 2) + ) + const waitingChild = currentChild() + expect(waitingChild.sent).toContainEqual(expect.objectContaining({ dir: '/waiting-root' })) + acknowledgeWatcherSubscribe(waitingChild) + await expect(waiting).resolves.toMatchObject({ unsubscribe: expect.any(Function) }) + }) +}) diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-disposal.ts similarity index 75% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-disposal.ts index 07bc73ef3ee..e3202f59c20 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-disposal.ts @@ -1,5 +1,5 @@ import type { ChildProcess } from 'node:child_process' -import { removeWatcherCanaryDirectory } from './parcel-watcher-canary-directory' +import { removeWatcherCanaryDirectory } from '../child-lifecycle/parcel-watcher-canary-directory' import type { WatcherCancellationTracker } from './parcel-watcher-cancellation-tracker' import { type PendingWatcherUnsubscribe, @@ -9,9 +9,9 @@ import { resetPendingSubscribeAttempt, takePendingSubscribe } from './parcel-watcher-pending-subscribe' -import { signalWatcherChild } from './parcel-watcher-child-termination' -import { watcherHostFailure } from './parcel-watcher-process-failure' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' +import { signalWatcherChild } from '../child-lifecycle/parcel-watcher-child-termination' +import { watcherHostFailure } from '../parcel-watcher-process-failure' +import type { WatcherProcessSubscriptionRecord } from '../parcel-watcher-process-subscription' export function disposeWatcherSupervisor( child: ChildProcess | null, diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-message.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-message.ts similarity index 93% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-message.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-message.ts index 25ff7c92535..85aec6fa11b 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-message.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-message.ts @@ -10,9 +10,9 @@ import { startInterruptedSubscribeTimeout, startPendingSubscribeTimeout } from './parcel-watcher-pending-subscribe' -import { WatcherProcessFailure } from './parcel-watcher-process-failure' -import type { WatcherToHostMessage } from './parcel-watcher-process-protocol' -import type { WatcherProcessSubscriptionRecord } from './parcel-watcher-process-subscription' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import type { WatcherToHostMessage } from '../parcel-watcher-process-protocol' +import type { WatcherProcessSubscriptionRecord } from '../parcel-watcher-process-subscription' type WatcherSupervisorMessageContext = { records: Map diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-subscribe.ts similarity index 90% rename from src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts rename to src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-subscribe.ts index f156945045f..46633b2c623 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts +++ b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-subscribe.ts @@ -1,28 +1,31 @@ import type { ChildProcess } from 'node:child_process' import { existsSync } from 'node:fs' -import { sendToWatcherChild } from './parcel-watcher-child-messaging' +import { sendToWatcherChild } from '../child-lifecycle/parcel-watcher-child-messaging' import { createHostWatcherSubscription, type PendingWatcherUnsubscribe } from './parcel-watcher-host-subscriptions' -import { subscribeWithInProcessWatcher } from './parcel-watcher-in-process-fallback' +import { subscribeWithInProcessWatcher } from '../native-subscriptions/parcel-watcher-in-process-fallback' import { installPendingSubscribeControls, resetPendingSubscribeAttempt } from './parcel-watcher-pending-subscribe' -import { WatcherProcessFailure } from './parcel-watcher-process-failure' -import { rewriteWatcherEvents, resolveWatcherRootPaths } from './watcher-event-root-path-rewrite' +import { WatcherProcessFailure } from '../parcel-watcher-process-failure' +import { + rewriteWatcherEvents, + resolveWatcherRootPaths +} from '../root-paths/watcher-event-root-path-rewrite' import type { HostToWatcherMessage, WatcherProcessSubscribeOptions -} from './parcel-watcher-process-protocol' +} from '../parcel-watcher-process-protocol' import type { WatcherProcessCallback, WatcherProcessHooks, WatcherProcessSubscription, WatcherProcessSubscriptionRecord -} from './parcel-watcher-process-subscription' +} from '../parcel-watcher-process-subscription' type WatcherSupervisorSubscribeOptions = { dir: string diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts index a68fbf58bf4..f6039763301 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-capacity.ts @@ -1,5 +1,5 @@ import type { WebContents } from 'electron' -import { onWatcherChildCapacityAvailable } from '../watcher-process/parcel-watcher-child-registry' +import { onWatcherChildCapacityAvailable } from '../watcher-process/child-lifecycle/parcel-watcher-child-registry' import { type LocalWatcherCapacityRetry, diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-install.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-install.ts index 2297a0e1497..02b1ff0ca63 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-local-install.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-local-install.ts @@ -2,7 +2,7 @@ import { stat } from 'node:fs/promises' import { isWslPath } from '../../../wsl/filesystem/unc-path-access' import { WATCHER_IGNORE_DIRS } from './filesystem-watcher-ignore' import { createWslWatcher, type WatchedRoot } from './filesystem-watcher-wsl' -import { WatcherChildCapacityError } from '../watcher-process/parcel-watcher-child-registry' +import { WatcherChildCapacityError } from '../watcher-process/child-lifecycle/parcel-watcher-child-registry' import { isWatcherProcessFailure } from '../watcher-process/parcel-watcher-process-failure' import type { LocalWatcherInstallResult, diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts deleted file mode 100644 index 30d6b525b62..00000000000 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { createWatcherSender } from './filesystem-watcher-test-sender' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock, statMock, subscribeViaWatcherProcessMock, disposeWatcherProcessMock } = - vi.hoisted(() => ({ - handleMock: vi.fn(), - statMock: vi.fn(), - subscribeViaWatcherProcessMock: vi.fn(), - disposeWatcherProcessMock: vi.fn() - })) - -vi.mock('electron', () => ({ ipcMain: { handle: handleMock } })) -vi.mock('node:fs/promises', () => ({ stat: statMock })) -vi.mock('../watcher-process/parcel-watcher-process', () => ({ - subscribeViaWatcherProcess: subscribeViaWatcherProcessMock, - disposeWatcherProcess: disposeWatcherProcessMock -})) -vi.mock('./filesystem-watcher-wsl', () => ({ createWslWatcher: vi.fn() })) -import { closeAllWatchers } from './filesystem-watcher-shutdown' -import { registerFilesystemWatcherHandlers } from './filesystem-watcher-handlers' -import { - MAX_PHYSICAL_WATCHER_CHILDREN, - reserveWatcherChild, - resetWatcherChildRegistryForTest, - WatcherChildCapacityError -} from '../watcher-process/parcel-watcher-child-registry' - -type HandlerMap = Record unknown> - -function fillWatcherChildCapacity(): (() => void)[] { - return Array.from({ length: MAX_PHYSICAL_WATCHER_CHILDREN }, () => { - const release = reserveWatcherChild() - if (!release) { - throw new Error('expected watcher child reservation') - } - return release - }) -} - -describe('native filesystem watcher capacity recovery', () => { - const handlers: HandlerMap = {} - - beforeEach(async () => { - handleMock.mockReset() - statMock.mockReset() - subscribeViaWatcherProcessMock.mockReset() - disposeWatcherProcessMock.mockReset() - resetWatcherChildRegistryForTest() - for (const key of Object.keys(handlers)) { - delete handlers[key] - } - handleMock.mockImplementation((channel, handler) => { - handlers[channel] = handler - }) - statMock.mockResolvedValue({ isDirectory: () => true }) - registerFilesystemWatcherHandlers() - await closeAllWatchers() - }) - - afterEach(async () => { - await closeAllWatchers() - resetWatcherChildRegistryForTest() - }) - - it('automatically retries a native root when a child slot is released', async () => { - const releases = fillWatcherChildCapacity() - const unsubscribe = vi.fn().mockResolvedValue(undefined) - subscribeViaWatcherProcessMock - .mockRejectedValueOnce(new WatcherChildCapacityError()) - .mockResolvedValueOnce({ unsubscribe }) - const sender = createWatcherSender(1) - const args = { worktreePath: '/tmp/native-capacity-root' } - - await handlers['fs:watchWorktree']({ sender }, args) - expect(subscribeViaWatcherProcessMock).toHaveBeenCalledOnce() - - releases.pop()?.() - await vi.waitFor(() => expect(subscribeViaWatcherProcessMock).toHaveBeenCalledTimes(2)) - // Writes between IPC completion and delayed installation require a resync. - await vi.waitFor(() => - expect(sender.send).toHaveBeenCalledWith('fs:changed', { - worktreePath: '/tmp/native-capacity-root', - events: [{ kind: 'overflow', absolutePath: '/tmp/native-capacity-root' }], - resync: true - }) - ) - - releases.forEach((release) => release()) - }) - - it('cancels the native capacity wait when its renderer unwatches', async () => { - const releases = fillWatcherChildCapacity() - subscribeViaWatcherProcessMock.mockRejectedValue(new WatcherChildCapacityError()) - const sender = createWatcherSender(1) - const args = { worktreePath: '/tmp/native-capacity-root' } - - await handlers['fs:watchWorktree']({ sender }, args) - handlers['fs:unwatchWorktree']({ sender: { id: sender.id } }, args) - releases.pop()?.() - await Promise.resolve() - await Promise.resolve() - - expect(subscribeViaWatcherProcessMock).toHaveBeenCalledOnce() - releases.forEach((release) => release()) - }) -}) diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-real.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-real.test.ts deleted file mode 100644 index ae85437e822..00000000000 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-real.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { createWatcherSender } from './filesystem-watcher-test-sender' -/* Use the real native watcher to catch missing packaged addons and verify end-to-end delivery (#4684, #4851). */ -import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock } = vi.hoisted(() => ({ handleMock: vi.fn() })) - -vi.mock('electron', () => ({ - ipcMain: { handle: handleMock } -})) - -import { closeAllWatchers } from './filesystem-watcher-shutdown' -import { registerFilesystemWatcherHandlers } from './filesystem-watcher-handlers' -import { - createAliasedWatcherRoot, - removeAliasedWatcherRoot, - type AliasedWatcherRoot -} from '../watcher-process/watcher-aliased-root-fixture' - -type HandlerMap = Record unknown> - -type FsChangedCall = { worktreePath: string; events: { kind: string; absolutePath: string }[] } - -// Poll native delivery and batching rather than assuming a fixed delay. -async function waitFor(predicate: () => boolean, timeoutMs = 8_000, stepMs = 50): Promise { - const deadline = Date.now() + timeoutMs - while (Date.now() < deadline) { - if (predicate()) { - return - } - await new Promise((resolve) => setTimeout(resolve, stepMs)) - } - throw new Error('waitFor: condition not met within timeout') -} - -describe('filesystem-watcher real @parcel/watcher integration', () => { - const handlers: HandlerMap = {} - let tempDir: string | null = null - let aliasedRoot: AliasedWatcherRoot | null = null - - beforeEach(async () => { - handleMock.mockReset() - for (const key of Object.keys(handlers)) { - delete handlers[key] - } - handleMock.mockImplementation((channel: string, handler: HandlerMap[string]) => { - handlers[channel] = handler - }) - registerFilesystemWatcherHandlers() - await closeAllWatchers() - }) - - afterEach(async () => { - await closeAllWatchers() - if (tempDir) { - await rm(tempDir, { recursive: true, force: true }) - tempDir = null - } - await removeAliasedWatcherRoot(aliasedRoot) - aliasedRoot = null - vi.clearAllMocks() - }) - - // Target Linux native delivery; macOS sandboxes can suppress callbacks despite loading the addon. - it.runIf(process.platform === 'linux')( - 'emits fs:changed for a file created in a watched directory', - async () => { - // Canonicalize macOS /var temp aliases before comparing event paths. - tempDir = await realpath(await mkdtemp(join(tmpdir(), 'orca-fswatch-real-'))) - const sendMock = vi.fn() - const sender = createWatcherSender(1, sendMock) - - await handlers['fs:watchWorktree']({ sender }, { worktreePath: tempDir }) - - const createdFile = join(tempDir, 'new-file.txt') - await writeFile(createdFile, 'hello') - - await waitFor(() => - sendMock.mock.calls.some( - ([channel, payload]) => - channel === 'fs:changed' && - (payload as FsChangedCall).events.some((event) => event.absolutePath === createdFile) - ) - ) - - const changed = sendMock.mock.calls.find(([channel]) => channel === 'fs:changed') - expect(changed).toBeDefined() - const payload = changed![1] as FsChangedCall - const event = payload.events.find((entry) => entry.absolutePath === createdFile) - expect(event).toBeDefined() - expect(['create', 'update']).toContain(event!.kind) - - await handlers['fs:unwatchWorktree']({ sender: { id: 1 } }, { worktreePath: tempDir }) - }, - 15_000 - ) - - // Alias watchers must preserve subscribed path spelling even when native events report resolved roots. - it('reports events under an aliased worktree root, not its resolved path', async () => { - const root = await createAliasedWatcherRoot('orca-fswatch-alias-') - aliasedRoot = root - await mkdir(join(root.realRoot, 'src'), { recursive: true }) - - const sendMock = vi.fn() - const sender = createWatcherSender(1, sendMock) - await handlers['fs:watchWorktree']({ sender }, { worktreePath: root.aliasRoot }) - - const expectedPath = join(root.aliasRoot, 'src', 'agent-edit.ts') - await writeFile(join(root.realRoot, 'src', 'agent-edit.ts'), 'hello') - - await waitFor(() => - sendMock.mock.calls.some( - ([channel, payload]) => - channel === 'fs:changed' && - (payload as FsChangedCall).events.some((event) => event.absolutePath === expectedPath) - ) - ) - - await handlers['fs:unwatchWorktree']({ sender: { id: 1 } }, { worktreePath: root.aliasRoot }) - }, 15_000) -}) diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts index 446489fcc07..f604fa4571b 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts @@ -11,7 +11,7 @@ vi.mock('@orca/process-host', () => ({ })) import { createWslWatcher } from './filesystem-watcher-wsl' -import { resetWatcherChildRegistryForTest } from '../watcher-process/parcel-watcher-child-registry' +import { resetWatcherChildRegistryForTest } from '../watcher-process/child-lifecycle/parcel-watcher-child-registry' import type { WatchedRoot, WslWatcherDeps } from './filesystem-watcher-wsl' const SNAPSHOT_START = '\0\x1e\0' diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts index 3c499f85538..0b61d46229d 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts @@ -6,7 +6,7 @@ import type { Event as WatcherEvent } from '@parcel/watcher' import { queueWatcherEvents } from './filesystem-watcher-event-batch' import { parseWslUncPath } from '../../../../shared/wsl-paths' import { createWslWatcherProcessExit, createWslWatcherStartup } from './wsl-watcher-process-exit' -import * as watcherChildRegistry from '../watcher-process/parcel-watcher-child-registry' +import * as watcherChildRegistry from '../watcher-process/child-lifecycle/parcel-watcher-child-registry' import { createDebouncedBatch, type DebouncedBatch } from './filesystem-watcher-batch-control' import { spawnWslWatcherProcess } from './wsl-watcher-spawn' diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts index 1c79a910b4e..e976d4e85a6 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts @@ -26,7 +26,7 @@ import { registerFilesystemWatcherHandlers } from './filesystem-watcher-handlers import { stat } from 'node:fs/promises' import { subscribe as subscribeParcelWatcher } from '@parcel/watcher' import { createWslWatcher } from './filesystem-watcher-wsl' -import { resetWatcherChildRegistryForTest } from '../watcher-process/parcel-watcher-child-registry' +import { resetWatcherChildRegistryForTest } from '../watcher-process/child-lifecycle/parcel-watcher-child-registry' import { acquireWatcherRemovalGate } from '../../../workspaces/removal/watcher-removal-gate' type HandlerMap = Record unknown> diff --git a/src/main/ipc/runtime-environments/runtime-environment-preference.ts b/src/main/ipc/runtime-environments/runtime-environment-preference.ts index df39b8a9402..67692106bbb 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-preference.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-preference.ts @@ -2,7 +2,7 @@ import type { GlobalSettings } from '../../../shared/global-settings-types' import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { getEnvironmentStorePath } from '../../../shared/remote-runtime/host-store/runtime-environment-store-records' import type { Store } from '../../persistence/loading-store/store' -import { watchFileAcrossReplacement } from '../filesystem/watcher-process/rebinding-file-watch' +import { watchFileAcrossReplacement } from '../filesystem/watcher-process/native-subscriptions/rebinding-file-watch' type PreferenceStore = Pick diff --git a/src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.ts b/src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.ts index 8070654d188..58b02038c63 100644 --- a/src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.ts +++ b/src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.ts @@ -1,4 +1,4 @@ -import { CRASH_FUSE_COOLDOWN_INITIAL_MS } from '../../filesystem/watcher-process/parcel-watcher-crash-fuse' +import { CRASH_FUSE_COOLDOWN_INITIAL_MS } from '../../filesystem/watcher-process/supervision/parcel-watcher-crash-fuse' // Retry when the crash fuse half-opens so fallback polling does not remain permanent until restart. export const GIT_COMMON_NATIVE_UPGRADE_INTERVAL_MS = CRASH_FUSE_COOLDOWN_INITIAL_MS diff --git a/src/main/orcad/orcad-runtime-native-preflight.ts b/src/main/orcad/orcad-runtime-native-preflight.ts index 48a0966ad0f..7e2c972c4c0 100644 --- a/src/main/orcad/orcad-runtime-native-preflight.ts +++ b/src/main/orcad/orcad-runtime-native-preflight.ts @@ -6,7 +6,7 @@ import { PTY_SPAWN_HEALTH_TIMEOUT_MS, runPtySpawnHealthProbe } from '../daemon/pty-subprocess/spawn-preflight' -import { WatcherProcessSupervisor } from '../ipc/filesystem/watcher-process/parcel-watcher-process-supervisor' +import { WatcherProcessSupervisor } from '../ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor' import { resolveWatcherProcessEntryPath } from '../ipc/filesystem/watcher-process/parcel-watcher-entry-path' import { resolveOrcadInstallRoot } from './orcad-app-paths' import { diff --git a/src/main/plugins/plugin-dev-watcher.test.ts b/src/main/plugins/plugin-dev-watcher.test.ts index a68073a151f..d0b33676872 100644 --- a/src/main/plugins/plugin-dev-watcher.test.ts +++ b/src/main/plugins/plugin-dev-watcher.test.ts @@ -5,16 +5,12 @@ import { realpath, stat } from 'node:fs/promises' import type * as FsPromises from 'node:fs/promises' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { subscribeViaWatcherProcess } from '../ipc/filesystem/watcher-process/parcel-watcher-process' -import type { - WatcherProcessCallback, - WatcherProcessHooks -} from '../ipc/filesystem/watcher-process/parcel-watcher-process-subscription' -import type { WatcherProcessSubscribeOptions } from '../ipc/filesystem/watcher-process/parcel-watcher-process-protocol' + import { createAliasedWatcherRoot as createNativeAliasedWatcherRoot, removeAliasedWatcherRoot, type AliasedWatcherRoot -} from '../ipc/filesystem/watcher-process/watcher-aliased-root-fixture' +} from '../ipc/filesystem/watcher-process/root-paths/watcher-aliased-root-fixture' import { PluginDevWatcher } from './plugin-dev-watcher' import type { PluginServiceHousekeeping } from './plugin-service-housekeeping' @@ -30,19 +26,11 @@ vi.mock('node:fs/promises', async () => { return { ...actual, realpath: vi.fn(actual.realpath), stat: vi.fn(actual.stat) } }) -type PluginWatchSubscription = { - path: string - callback: WatcherProcessCallback - options: WatcherProcessSubscribeOptions - hooks: WatcherProcessHooks - unsubscribe: ReturnType Promise>> -} - const devPath = resolve('plugins', 'demo') const originalPlatform = process.platform const subscribeMock = vi.mocked(subscribeViaWatcherProcess) -let subscriptions: PluginWatchSubscription[] = [] + let devWatchers: PluginDevWatcher[] = [] let housekeeping: PluginServiceHousekeeping | null = null let aliasedRoot: AliasedWatcherRoot | null = null @@ -55,9 +43,9 @@ beforeEach(() => { subscribeMock.mockReset() vi.mocked(statSync).mockReset() vi.mocked(stat).mockReset() - subscribeMock.mockImplementation(async (path, callback, options, hooks = {}) => { + subscribeMock.mockImplementation(async () => { const unsubscribe = vi.fn().mockResolvedValue(undefined) - subscriptions.push({ path, callback, options, hooks, unsubscribe }) + return { unsubscribe } }) }) @@ -69,7 +57,7 @@ afterEach(async () => { watcher.dispose() } devWatchers = [] - subscriptions = [] + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) await removeAliasedWatcherRoot(aliasedRoot) aliasedRoot = null @@ -103,25 +91,6 @@ function startDevWatcher( } describe('PluginDevWatcher', () => { - it('unsubscribes every subscription that resolves after disposal', async () => { - const pending: (() => void)[] = [] - subscribeMock.mockImplementation((path, callback, options, hooks = {}) => { - const unsubscribe = vi.fn().mockResolvedValue(undefined) - subscriptions.push({ path, callback, options, hooks, unsubscribe }) - return new Promise((settle) => pending.push(() => settle({ unsubscribe }))) - }) - const { watcher } = startDevWatcher() - watcher.dispose() - for (const settle of pending) { - settle() - } - await vi.waitFor(() => { - for (const subscription of subscriptions) { - expect(subscription.unsubscribe).toHaveBeenCalledOnce() - } - }) - }) - it('fences a pending binding check after disposal or restart', async () => { aliasedRoot = await createAliasedWatcherRoot('orca-plugin-dev-late-binding-') const { watcher } = startDevWatcher(undefined, undefined, [aliasedRoot.realRoot]) diff --git a/src/main/plugins/plugin-dev-watcher.ts b/src/main/plugins/plugin-dev-watcher.ts index ef2bf7f6b48..bc66901da03 100644 --- a/src/main/plugins/plugin-dev-watcher.ts +++ b/src/main/plugins/plugin-dev-watcher.ts @@ -4,8 +4,8 @@ import { basename, dirname, resolve } from 'node:path' import { subscribeViaWatcherProcess } from '../ipc/filesystem/watcher-process/parcel-watcher-process' import type { WatcherProcessSubscribeOptions } from '../ipc/filesystem/watcher-process/parcel-watcher-process-protocol' import type { WatcherProcessSubscription } from '../ipc/filesystem/watcher-process/parcel-watcher-process-subscription' -import { resolveWatcherRootPaths } from '../ipc/filesystem/watcher-process/watcher-event-root-path-rewrite' -import { watcherDirectoryIdentity } from '../ipc/filesystem/watcher-process/watcher-directory-identity' +import { resolveWatcherRootPaths } from '../ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite' +import { watcherDirectoryIdentity } from '../ipc/filesystem/watcher-process/root-paths/watcher-directory-identity' import { bumpPluginDevRevision, recordPluginDevEdit } from './plugin-dev-revision' import { isIgnoredPluginDevPath, pluginDevWatchIgnoreOptions } from './plugin-dev-watcher-ignore' From 5b2fba165db0b1f1123810f574eff9effac2b952 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:36:01 -0800 Subject: [PATCH 27/40] fix(account): say 'Signed out of Orca' after signing out (#41264) The toast after signing out of the Orca account read 'Signed out of profile'. Say what you signed out of. --- src/renderer/src/i18n/locales/en.json | 2 +- .../store/slices/orca-profiles/orca-profiles-auth-actions.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 191904f8f9e..e637bd705ac 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1750,7 +1750,7 @@ "33290e88ed": "Failed to connect profile", "9fcb07a796": "Profile connected", "2f6c78a039": "Failed to refresh profile auth", - "a37b5e6d37": "Signed out of profile", + "a37b5e6d37": "Signed out of Orca", "83600521e7": "Failed to sign out", "76deec8f58": "Failed to switch organization", "7d4bc516ee": "Failed to switch profile", diff --git a/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts index 40e808c424c..5908658f551 100644 --- a/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts +++ b/src/renderer/src/store/slices/orca-profiles/orca-profiles-auth-actions.ts @@ -190,7 +190,7 @@ export const createOrcaProfilesAuthActions: StateCreator< }) if (result.auth.state !== 'connected') { toast.success( - translate('auto.store.slices.orca.profiles.a37b5e6d37', 'Signed out of profile') + translate('auto.store.slices.orca.profiles.a37b5e6d37', 'Signed out of Orca') ) } return result From 057f5772e921ace2f4dbf6c93ded0c3c297f5c6e Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:39:46 -0800 Subject: [PATCH 28/40] refactor(mobile): group terminal document modules by domain (#41267) --- config/flaky-test-pattern-baseline.txt | 1 - .../document/create-terminal-document.ts | 31 +-- .../document/document-host-root.test.ts | 112 --------- .../document-module-source.test-support.ts | 34 --- .../src/terminal/document/document-scope.ts | 10 +- .../document/document-start-unwind.test.ts | 13 - .../document/{ => engine}/mode-mirroring.ts | 6 +- .../osc52-clipboard-bridge.test.ts | 2 +- .../{ => engine}/osc52-clipboard-bridge.ts | 7 +- .../document/{ => engine}/query-reply.ts | 8 +- .../document/{ => engine}/surface-swap.ts | 7 +- .../document/{ => engine}/term-observers.ts | 12 +- .../document/{ => engine}/terminal-init.ts | 39 +-- .../document/{ => engine}/terminal-theme.ts | 9 +- .../document/{ => engine}/webgl-recovery.ts | 5 +- .../document/{ => engine}/write-queue.test.ts | 18 +- .../document/{ => engine}/write-queue.ts | 4 +- .../{ => host-bridge}/host-message-router.ts | 28 +-- .../document/{ => host-bridge}/host-notify.ts | 6 +- .../host-bridge/message-bridge-fonts.test.ts | 60 +++++ .../{ => host-bridge}/message-bridge.ts | 10 +- .../document/laid-out-cell-box.test.ts | 228 ------------------ .../document/message-bridge-fonts.test.ts | 180 -------------- .../document/native-document-bundle.test.ts | 106 -------- .../{ => selection}/selection-menu-buttons.ts | 4 +- .../{ => selection}/selection-mode.ts | 8 +- .../{ => selection}/selection-overlay.ts | 10 +- .../{ => selection}/selection-range.test.ts | 36 +-- .../{ => selection}/selection-range.ts | 8 +- .../selection-state-and-eviction.ts | 8 +- .../{ => surface-input}/escape-introducers.ts | 0 .../{ => surface-input}/mouse-click-drag.ts | 12 +- .../mouse-input-encoding.ts | 4 +- .../mouse-mode-decset-scan.ts | 4 +- .../{ => surface-input}/mouse-report-cell.ts | 6 +- .../{ => surface-input}/osc-link-tap.ts | 12 +- .../surface-interaction-lifecycle.ts | 8 +- .../{ => surface-input}/surface-tap.ts | 10 +- .../surface-touch-gesture-stop.ts | 8 +- .../surface-touch-gestures.ts | 22 +- .../{ => surface-input}/tap-dispatch.ts | 14 +- .../{ => surface-input}/wheel-scroll.ts | 8 +- .../document/terminal-replay-scroll.test.ts | 213 ---------------- .../terminal/document/viewport-frame.test.ts | 161 ------------- .../bottom-row-backdrop.test.ts | 17 +- .../{ => viewport}/bottom-row-backdrop.ts | 4 +- .../document/{ => viewport}/cell-geometry.ts | 2 +- .../document/{ => viewport}/cell-metrics.ts | 2 +- .../document/{ => viewport}/fit-scale.ts | 8 +- .../keyboard-avoidance-metrics.ts | 9 +- .../viewport/laid-out-cell-box.test.ts | 51 ++++ .../{ => viewport}/laid-out-cell-box.ts | 6 +- .../normal-buffer-smooth-scroll.ts | 4 +- .../document/{ => viewport}/reflow.ts | 4 +- .../document/{ => viewport}/text-scaling.ts | 10 +- .../document/{ => viewport}/viewport-cell.ts | 2 +- .../document/viewport/viewport-frame.test.ts | 44 ++++ .../{ => viewport}/viewport-transform.ts | 6 +- ...erminal-keyboard-avoidance-webview.test.ts | 4 +- .../terminal/terminal-webview-engine.test.ts | 150 ------------ .../terminal-webview-query-reply.test.ts | 88 ------- .../terminal-webview-text-zoom.test.ts | 2 +- 62 files changed, 355 insertions(+), 1550 deletions(-) delete mode 100644 mobile/src/terminal/document/document-module-source.test-support.ts rename mobile/src/terminal/document/{ => engine}/mode-mirroring.ts (90%) rename mobile/src/terminal/document/{ => engine}/osc52-clipboard-bridge.test.ts (98%) rename mobile/src/terminal/document/{ => engine}/osc52-clipboard-bridge.ts (70%) rename mobile/src/terminal/document/{ => engine}/query-reply.ts (92%) rename mobile/src/terminal/document/{ => engine}/surface-swap.ts (88%) rename mobile/src/terminal/document/{ => engine}/term-observers.ts (76%) rename mobile/src/terminal/document/{ => engine}/terminal-init.ts (86%) rename mobile/src/terminal/document/{ => engine}/terminal-theme.ts (87%) rename mobile/src/terminal/document/{ => engine}/webgl-recovery.ts (94%) rename mobile/src/terminal/document/{ => engine}/write-queue.test.ts (86%) rename mobile/src/terminal/document/{ => engine}/write-queue.ts (97%) rename mobile/src/terminal/document/{ => host-bridge}/host-message-router.ts (83%) rename mobile/src/terminal/document/{ => host-bridge}/host-notify.ts (92%) create mode 100644 mobile/src/terminal/document/host-bridge/message-bridge-fonts.test.ts rename mobile/src/terminal/document/{ => host-bridge}/message-bridge.ts (92%) delete mode 100644 mobile/src/terminal/document/laid-out-cell-box.test.ts delete mode 100644 mobile/src/terminal/document/message-bridge-fonts.test.ts rename mobile/src/terminal/document/{ => selection}/selection-menu-buttons.ts (89%) rename mobile/src/terminal/document/{ => selection}/selection-mode.ts (80%) rename mobile/src/terminal/document/{ => selection}/selection-overlay.ts (93%) rename mobile/src/terminal/document/{ => selection}/selection-range.test.ts (72%) rename mobile/src/terminal/document/{ => selection}/selection-range.ts (94%) rename mobile/src/terminal/document/{ => selection}/selection-state-and-eviction.ts (89%) rename mobile/src/terminal/document/{ => surface-input}/escape-introducers.ts (100%) rename mobile/src/terminal/document/{ => surface-input}/mouse-click-drag.ts (96%) rename mobile/src/terminal/document/{ => surface-input}/mouse-input-encoding.ts (98%) rename mobile/src/terminal/document/{ => surface-input}/mouse-mode-decset-scan.ts (95%) rename mobile/src/terminal/document/{ => surface-input}/mouse-report-cell.ts (87%) rename mobile/src/terminal/document/{ => surface-input}/osc-link-tap.ts (89%) rename mobile/src/terminal/document/{ => surface-input}/surface-interaction-lifecycle.ts (75%) rename mobile/src/terminal/document/{ => surface-input}/surface-tap.ts (87%) rename mobile/src/terminal/document/{ => surface-input}/surface-touch-gesture-stop.ts (71%) rename mobile/src/terminal/document/{ => surface-input}/surface-touch-gestures.ts (94%) rename mobile/src/terminal/document/{ => surface-input}/tap-dispatch.ts (95%) rename mobile/src/terminal/document/{ => surface-input}/wheel-scroll.ts (90%) delete mode 100644 mobile/src/terminal/document/terminal-replay-scroll.test.ts delete mode 100644 mobile/src/terminal/document/viewport-frame.test.ts rename mobile/src/terminal/document/{ => viewport}/bottom-row-backdrop.test.ts (73%) rename mobile/src/terminal/document/{ => viewport}/bottom-row-backdrop.ts (95%) rename mobile/src/terminal/document/{ => viewport}/cell-geometry.ts (94%) rename mobile/src/terminal/document/{ => viewport}/cell-metrics.ts (93%) rename mobile/src/terminal/document/{ => viewport}/fit-scale.ts (94%) rename mobile/src/terminal/document/{ => viewport}/keyboard-avoidance-metrics.ts (90%) create mode 100644 mobile/src/terminal/document/viewport/laid-out-cell-box.test.ts rename mobile/src/terminal/document/{ => viewport}/laid-out-cell-box.ts (84%) rename mobile/src/terminal/document/{ => viewport}/normal-buffer-smooth-scroll.ts (95%) rename mobile/src/terminal/document/{ => viewport}/reflow.ts (89%) rename mobile/src/terminal/document/{ => viewport}/text-scaling.ts (91%) rename mobile/src/terminal/document/{ => viewport}/viewport-cell.ts (95%) create mode 100644 mobile/src/terminal/document/viewport/viewport-frame.test.ts rename mobile/src/terminal/document/{ => viewport}/viewport-transform.ts (93%) delete mode 100644 mobile/src/terminal/terminal-webview-query-reply.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 2f1a158344d..f3d05143634 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -617,7 +617,6 @@ 4 test-no-wall-clock:tests/e2e/cross-version-wire/release-checkout.unit.test.ts 2 test-no-wall-clock:tests/e2e/cross-version-wire/release-source-retention.unit.test.ts 1 test-no-wall-clock:tests/e2e/host-cold-park-remote-subscriber.unit.test.ts -2 test-timeout-needs-reason:mobile/src/terminal/document/native-document-bundle.test.ts 1 test-timeout-needs-reason:src/cli/agent-launch-process.test.ts 1 test-timeout-needs-reason:src/cli/runtime/serve-pid1-init-reaper.test.ts 1 test-timeout-needs-reason:src/cli/skills-install.test.ts diff --git a/mobile/src/terminal/document/create-terminal-document.ts b/mobile/src/terminal/document/create-terminal-document.ts index 750a10f5fc7..129c7b9ce5d 100644 --- a/mobile/src/terminal/document/create-terminal-document.ts +++ b/mobile/src/terminal/document/create-terminal-document.ts @@ -1,20 +1,21 @@ import { createTerminalDocumentScope } from './document-scope' import { cancelDocumentFrames } from './document-frame-registry' -import { startFitScale, stopFitScale } from './fit-scale' -import { handleMsg } from './host-message-router' -import { reportEngineError, startHostNotify, stopHostNotify } from './host-notify' -import { startMessageBridge, stopMessageBridge } from './message-bridge' -import { stopNormalBufferSmoothScroll } from './normal-buffer-smooth-scroll' -import { startSelectionMenuButtons } from './selection-menu-buttons' -import { stopSelectionOverlay } from './selection-overlay' -import { startSelectionStateAndEviction } from './selection-state-and-eviction' -import { startSurfaceSwap } from './surface-swap' -import { startSurfaceTouchGestures, stopSurfaceTouchGestures } from './surface-touch-gestures' -import { startTapDispatch, stopTapDispatch } from './tap-dispatch' -import { stopTerminalInit } from './terminal-init' -import { startTextScaling } from './text-scaling' -import { stopViewportTransform } from './viewport-transform' -import { startWebglRecovery, stopWebglRecovery } from './webgl-recovery' +import { startFitScale, stopFitScale } from './viewport/fit-scale' +import { handleMsg } from './host-bridge/host-message-router' +import { reportEngineError, startHostNotify, stopHostNotify } from './host-bridge/host-notify' +import { startMessageBridge, stopMessageBridge } from './host-bridge/message-bridge' +import { stopNormalBufferSmoothScroll } from './viewport/normal-buffer-smooth-scroll' +import { startSelectionMenuButtons } from './selection/selection-menu-buttons' +import { stopSelectionOverlay } from './selection/selection-overlay' +import { startSelectionStateAndEviction } from './selection/selection-state-and-eviction' +import { startSurfaceSwap } from './engine/surface-swap' +import { startSurfaceTouchGestures } from './surface-input/surface-touch-gestures' +import { stopSurfaceTouchGestures } from './surface-input/surface-touch-gesture-stop' +import { startTapDispatch, stopTapDispatch } from './surface-input/tap-dispatch' +import { stopTerminalInit } from './engine/terminal-init' +import { startTextScaling } from './viewport/text-scaling' +import { stopViewportTransform } from './viewport/viewport-transform' +import { startWebglRecovery, stopWebglRecovery } from './engine/webgl-recovery' import type { TerminalDocumentScope } from './document-scope' import type { TerminalDocument, TerminalDocumentHost } from './document-host-seams' diff --git a/mobile/src/terminal/document/document-host-root.test.ts b/mobile/src/terminal/document/document-host-root.test.ts index 07d6f366036..f08ac77329a 100644 --- a/mobile/src/terminal/document/document-host-root.test.ts +++ b/mobile/src/terminal/document/document-host-root.test.ts @@ -165,115 +165,3 @@ describe('two terminal documents on one page', () => { two.started.stop() }) }) - -function startMeasuredDocument() { - document.body.innerHTML = '' - const host = plantHost('pinch-host') - const engine = terminalDocumentDouble() - const parsedWrites: Array<() => void> = [] - const grid = Object.assign(engine.terminal, { - cols: 80, - rows: 24, - _core: { - _renderService: { - get dimensions() { - const k = grid.options.fontSize / 13 - return { css: { cell: { width: 7.5 * k, height: 15 * k } } } - } - } - } - }) - grid.resize = (cols: number, rows: number) => { - grid.cols = cols - grid.rows = rows - } - grid.onWriteParsed = (listener: () => void) => { - parsedWrites.push(listener) - return { dispose() {} } - } - const posted: Array> = [] - const started = createTerminalDocument({ - root: host, - postToHost: (message) => { - posted.push(message) - }, - hasEngine: () => true, - installHostTransport: () => () => {}, - installErrorReporter: () => () => {}, - paintDocumentBackground: () => {}, - viewportRect: () => ({ left: 0, top: 0, width: 412, height: 600 }), - createTerminal: () => grid, - createUnicode11Addon: () => null, - createWebglAddon: () => null - }) - started.send({ - type: 'init', - cols: 80, - rows: 24, - initialData: '', - preserveScroll: false, - frame: { width: 412, height: 600 } - }) - const write = () => parsedWrites.forEach((listener) => listener()) - return { started, posted, surface: surfaceOf(host), write } -} - -const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve())) -async function settle() { - for (let frame = 0; frame < 10; frame++) { - await nextFrame() - } -} - -const metricsOf = (posted: Array>) => - posted.filter((message) => message.type === 'keyboard-avoidance-metrics') - -function fireSurfaceTouch(type: string, surface: HTMLElement, xs: number[]) { - const event = new Event(type, { bubbles: true, cancelable: true }) - Object.defineProperty(event, 'touches', { - value: xs.map((x, identifier) => ({ identifier, clientX: x, clientY: 10, target: surface })) - }) - surface.dispatchEvent(event) -} - -function pinchTo(doc: ReturnType, spread: number, write = true) { - fireSurfaceTouch('touchstart', doc.surface, [10, 30]) - fireSurfaceTouch('touchmove', doc.surface, [10, 10 + spread]) - if (write) { - doc.write() - } - fireSurfaceTouch('touchend', doc.surface, []) -} - -// Pinch changes row pitch without a fit; release must replace metrics emitted during a mid-gesture write. -describe('keyboard-avoidance metrics across a pinch', () => { - it('reports the at-rest pitch after a pinch that releases onto the same preset', async () => { - const doc = startMeasuredDocument() - await settle() - const atRest = metricsOf(doc.posted).at(-1)?.rowPitch - expect(atRest).toBeGreaterThan(0) - - pinchTo(doc, 21) - await settle() - - const metrics = metricsOf(doc.posted) - expect(metrics.at(-1)?.rowPitch).toBe(atRest) - 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() - const before = metricsOf(doc.posted).length - - // Change settings before deferred refit, then release the pinch onto that same preset. - doc.started.send({ type: 'set-font-scale', fontScale: 1.5 }) - pinchTo(doc, 20, false) - await settle() - - const reported = metricsOf(doc.posted).slice(before) - expect(reported.map((message) => message.rowPitch)).toEqual([reported.at(-1)?.rowPitch]) - expect(reported.at(-1)?.rowPitch).toBeGreaterThan(20) - doc.started.stop() - }) -}) diff --git a/mobile/src/terminal/document/document-module-source.test-support.ts b/mobile/src/terminal/document/document-module-source.test-support.ts deleted file mode 100644 index 4c46e20b02c..00000000000 --- a/mobile/src/terminal/document/document-module-source.test-support.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { readdirSync, readFileSync } from 'node:fs' -import { join } from 'node:path' - -// Read source for structural checks: bundling merges scopes and renames identifiers. Execute bundles in their own tests. -// Resolve per call to keep module evaluation inert; DOM tests lack file URLs, so use import.meta.dirname. -const documentDirectory = () => import.meta.dirname - -const isDocumentModule = (name: string) => - name.endsWith('.ts') && !name.includes('.test.') && !name.includes('.test-support.') - -export function documentModuleSource(name: string): string { - return readFileSync(join(documentDirectory(), `${name}.ts`), 'utf8') -} - -// Read the directory so moving or adding document modules cannot silently evade source checks. -export function documentSourceText(): string { - return readdirSync(documentDirectory()) - .filter(isDocumentModule) - .sort() - .map((name) => readFileSync(join(documentDirectory(), name), 'utf8')) - .join('\n') -} - -// WebView checks include the surrounding HTML and styles as well as the document modules. -export function webviewPageSource(): string { - const html = join(documentDirectory(), '..', 'terminal-webview-html') - return [ - documentSourceText(), - ...readdirSync(html) - .filter((name) => name.endsWith('.ts') && !name.includes('.test')) - .sort() - .map((name) => readFileSync(join(html, name), 'utf8')) - ].join('\n') -} diff --git a/mobile/src/terminal/document/document-scope.ts b/mobile/src/terminal/document/document-scope.ts index 84fe2b78ec0..19589fd942a 100644 --- a/mobile/src/terminal/document/document-scope.ts +++ b/mobile/src/terminal/document/document-scope.ts @@ -24,13 +24,11 @@ import type { TerminalDocumentWebglAddon, TerminalInitialOscLink } from './document-terminal-shape' -import type { TerminalMouseGesture } from './mouse-click-drag' -import type { TerminalTouchState } from './surface-touch-gestures' -import type { TerminalTouchDispatch } from './tap-dispatch' -import type { TerminalDocumentThemeMessage } from './terminal-theme' +import type { TerminalMouseGesture } from './surface-input/mouse-click-drag' +import type { TerminalTouchState } from './surface-input/surface-touch-gestures' +import type { TerminalTouchDispatch } from './surface-input/tap-dispatch' +import type { TerminalDocumentThemeMessage } from './engine/terminal-theme' -export type * from './document-terminal-shape' -export type { TerminalDocumentHost, TerminalDocumentHostSeams } from './document-host-seams' // Keep cross-module mutable state per document; module-private state stays local to its factory-emitted module. export type TerminalDocumentState = { diff --git a/mobile/src/terminal/document/document-start-unwind.test.ts b/mobile/src/terminal/document/document-start-unwind.test.ts index e6d7ecc8506..220b105dbd8 100644 --- a/mobile/src/terminal/document/document-start-unwind.test.ts +++ b/mobile/src/terminal/document/document-start-unwind.test.ts @@ -21,19 +21,6 @@ const hostWithoutAnEngine = () => ({ }) describe('the document start sequence', () => { - it('unwinds the starts that completed when a later one throws', () => { - document.body.innerHTML = MARKUP_WITHOUT_THE_MENU - const previous = window.onerror - window.onerror = null - try { - expect(() => createTerminalDocument(hostWithoutAnEngine())).toThrow() - // No handle returned, so only factory unwind can restore window.onerror after the partial start. - expect(window.onerror).toBe(null) - } finally { - window.onerror = previous - } - }) - it('would have installed one, so the null above is a measurement', () => { document.body.innerHTML = MARKUP_WITH_THE_MENU const previous = window.onerror diff --git a/mobile/src/terminal/document/mode-mirroring.ts b/mobile/src/terminal/document/engine/mode-mirroring.ts similarity index 90% rename from mobile/src/terminal/document/mode-mirroring.ts rename to mobile/src/terminal/document/engine/mode-mirroring.ts index d9a4de7e0e3..ad75cecee7d 100644 --- a/mobile/src/terminal/document/mode-mirroring.ts +++ b/mobile/src/terminal/document/engine/mode-mirroring.ts @@ -1,6 +1,6 @@ -import { notify } from './host-notify' -import { getMouseTrackingMode } from './mouse-input-encoding' -import type { TerminalDocumentModes, TerminalDocumentScope } from './document-scope' +import { notify } from '../host-bridge/host-notify' +import { getMouseTrackingMode } from '../surface-input/mouse-input-encoding' +import type { TerminalDocumentModes, TerminalDocumentScope } from '../document-scope' export function emitModesIfChanged(scope: TerminalDocumentScope) { if (!scope.term) { diff --git a/mobile/src/terminal/document/osc52-clipboard-bridge.test.ts b/mobile/src/terminal/document/engine/osc52-clipboard-bridge.test.ts similarity index 98% rename from mobile/src/terminal/document/osc52-clipboard-bridge.test.ts rename to mobile/src/terminal/document/engine/osc52-clipboard-bridge.test.ts index d1f532be385..417a0376e76 100644 --- a/mobile/src/terminal/document/osc52-clipboard-bridge.test.ts +++ b/mobile/src/terminal/document/engine/osc52-clipboard-bridge.test.ts @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { Terminal } from '@xterm/xterm' import { afterEach, describe, expect, it } from 'vitest' -import { createTerminalDocumentScope, type TerminalDocumentScope } from './document-scope' +import { createTerminalDocumentScope, type TerminalDocumentScope } from '../document-scope' import { attachOsc52ClipboardBridge } from './osc52-clipboard-bridge' import { resetTerminalDataReplyAuthority, resumeTerminalDataReplyAuthority } from './query-reply' diff --git a/mobile/src/terminal/document/osc52-clipboard-bridge.ts b/mobile/src/terminal/document/engine/osc52-clipboard-bridge.ts similarity index 70% rename from mobile/src/terminal/document/osc52-clipboard-bridge.ts rename to mobile/src/terminal/document/engine/osc52-clipboard-bridge.ts index 1f674b4d837..2c01e1e364d 100644 --- a/mobile/src/terminal/document/osc52-clipboard-bridge.ts +++ b/mobile/src/terminal/document/engine/osc52-clipboard-bridge.ts @@ -1,6 +1,7 @@ -import { createOsc52OscHandler } from '../../../../src/shared/osc52-clipboard' -import { notify } from './host-notify' -import type { TerminalDocumentScope, TerminalDocumentTerminal } from './document-scope' +import { createOsc52OscHandler } from '../../../../../src/shared/osc52-clipboard' +import { notify } from '../host-bridge/host-notify' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentTerminal } from '../document-terminal-shape' // Deliver OSC 52 to the viewing device using the desktop parser and limits. export function attachOsc52ClipboardBridge( diff --git a/mobile/src/terminal/document/query-reply.ts b/mobile/src/terminal/document/engine/query-reply.ts similarity index 92% rename from mobile/src/terminal/document/query-reply.ts rename to mobile/src/terminal/document/engine/query-reply.ts index 7812d391e0e..b6a411f225a 100644 --- a/mobile/src/terminal/document/query-reply.ts +++ b/mobile/src/terminal/document/engine/query-reply.ts @@ -1,11 +1,11 @@ -import { installProgramStatusQueryResponder } from '../../../../src/shared/program-status/query-responder' +import { installProgramStatusQueryResponder } from '../../../../../src/shared/program-status/query-responder' import { enqueueWriteBoundary } from './write-queue' -import { notify } from './host-notify' +import { notify } from '../host-bridge/host-notify' +import type { TerminalDocumentScope } from '../document-scope' import type { TerminalDocumentDisposable, - TerminalDocumentScope, TerminalDocumentTerminal -} from './document-scope' +} from '../document-terminal-shape' export type QueryReplyTerminal = { attachCustomKeyEventHandler: (handler: () => boolean) => void diff --git a/mobile/src/terminal/document/surface-swap.ts b/mobile/src/terminal/document/engine/surface-swap.ts similarity index 88% rename from mobile/src/terminal/document/surface-swap.ts rename to mobile/src/terminal/document/engine/surface-swap.ts index f80186bf5de..355bf171d11 100644 --- a/mobile/src/terminal/document/surface-swap.ts +++ b/mobile/src/terminal/document/engine/surface-swap.ts @@ -1,7 +1,8 @@ -import { elementInRoot } from './document-host-seams' +import { elementInRoot } from '../document-host-seams' import { disposeTermObservers } from './write-queue' -import { attachSurfaceEventHandlers } from './surface-touch-gestures' -import type { TerminalDocumentScope, TerminalDocumentTerminal } from './document-scope' +import { attachSurfaceEventHandlers } from '../surface-input/surface-touch-gestures' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentTerminal } from '../document-terminal-shape' export type TerminalSurfaceSwap = { oldTerm: TerminalDocumentTerminal | null diff --git a/mobile/src/terminal/document/term-observers.ts b/mobile/src/terminal/document/engine/term-observers.ts similarity index 76% rename from mobile/src/terminal/document/term-observers.ts rename to mobile/src/terminal/document/engine/term-observers.ts index 2fb569ef3b3..06594dc2416 100644 --- a/mobile/src/terminal/document/term-observers.ts +++ b/mobile/src/terminal/document/engine/term-observers.ts @@ -1,11 +1,11 @@ import { afterWritesDrained, disposeTermObservers } from './write-queue' -import { paintBottomRowBackdrop } from './bottom-row-backdrop' -import { updateScrollIndicator } from './viewport-transform' -import type { TerminalDocumentScope } from './document-scope' -import { logFeedAndEvict } from './selection-state-and-eviction' -import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' +import { paintBottomRowBackdrop } from '../viewport/bottom-row-backdrop' +import { updateScrollIndicator } from '../viewport/viewport-transform' +import type { TerminalDocumentScope } from '../document-scope' +import { logFeedAndEvict } from '../selection/selection-state-and-eviction' +import { emitKeyboardAvoidanceMetrics } from '../viewport/keyboard-avoidance-metrics' import { emitModesIfChanged } from './mode-mirroring' -import { reportLaidOutCellBox } from './laid-out-cell-box' +import { reportLaidOutCellBox } from '../viewport/laid-out-cell-box' export function attachTermObservers(scope: TerminalDocumentScope) { if (!scope.term) { diff --git a/mobile/src/terminal/document/terminal-init.ts b/mobile/src/terminal/document/engine/terminal-init.ts similarity index 86% rename from mobile/src/terminal/document/terminal-init.ts rename to mobile/src/terminal/document/engine/terminal-init.ts index 8a0e5f0b691..c17b21df62e 100644 --- a/mobile/src/terminal/document/terminal-init.ts +++ b/mobile/src/terminal/document/engine/terminal-init.ts @@ -1,37 +1,38 @@ -import { parseTerminalKittyKeyboardFlags } from '../../../../src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-flags' -import { resetSmoothScrollOffset } from './normal-buffer-smooth-scroll' -import { stopSurfaceTouchGestures } from './surface-touch-gestures' -import { clearLongPress } from './tap-dispatch' -import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' -import { MOBILE_TERMINAL_CARET_OPTIONS } from '../terminal-webview-html/theme' -import { ESC } from './escape-introducers' -import { notify } from './host-notify' -import { reportLaidOutCellBox } from './laid-out-cell-box' -import { fontPxForScale } from './text-scaling' -import type { TerminalDocumentScope, TerminalDocumentTerminal } from './document-scope' -import { scheduleDocumentFrame } from './document-frame-registry' -import { applyFitScale } from './fit-scale' +import { parseTerminalKittyKeyboardFlags } from '../../../../../src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-flags' +import { resetSmoothScrollOffset } from '../viewport/normal-buffer-smooth-scroll' +import { stopSurfaceTouchGestures } from '../surface-input/surface-touch-gesture-stop' +import { clearLongPress } from '../surface-input/tap-dispatch' +import { emitKeyboardAvoidanceMetrics } from '../viewport/keyboard-avoidance-metrics' +import { MOBILE_TERMINAL_CARET_OPTIONS } from '../../terminal-webview-html/theme' +import { ESC } from '../surface-input/escape-introducers' +import { notify } from '../host-bridge/host-notify' +import { reportLaidOutCellBox } from '../viewport/laid-out-cell-box' +import { fontPxForScale } from '../viewport/text-scaling' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentTerminal } from '../document-terminal-shape' +import { scheduleDocumentFrame } from '../document-frame-registry' +import { applyFitScale } from '../viewport/fit-scale' import { isAltScreenActive, normalizeInitialData, updateMouseModeFromData -} from './mouse-mode-decset-scan' -import { captureInitialOscLinkTexts } from './osc-link-tap' +} from '../surface-input/mouse-mode-decset-scan' +import { captureInitialOscLinkTexts } from '../surface-input/osc-link-tap' import { attachOsc52ClipboardBridge } from './osc52-clipboard-bridge' import { attachProgramStatusQueryReplies, attachTerminalQueryReplyBridge, resetTerminalDataReplyAuthority } from './query-reply' -import { cancelSelect } from './selection-mode' -import { resetEvictionCounter } from './selection-state-and-eviction' +import { cancelSelect } from '../selection/selection-mode' +import { resetEvictionCounter } from '../selection/selection-state-and-eviction' import { beginTerminalSurfaceSwap, commitTerminalSurfaceSwap } from './surface-swap' import { attachTermObservers } from './term-observers' import { applyTerminalTheme } from './terminal-theme' import { attachWebglAddon, cancelWebglContextRecovery } from './webgl-recovery' import { afterWritesDrained, enqueueWrite, pumpWrites, resetWriteQueue } from './write-queue' -import { DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT } from '../../../../src/shared/terminal/replay/terminal-scrollback-policy' -import { activateOrcaTerminalUnicodeProvider } from '../../../../src/shared/terminal/appearance/terminal-unicode-provider' +import { DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT } from '../../../../../src/shared/terminal/replay/terminal-scrollback-policy' +import { activateOrcaTerminalUnicodeProvider } from '../../../../../src/shared/terminal/appearance/terminal-unicode-provider' function openTerminal(scope: TerminalDocumentScope, cols: number, rows: number) { const term = scope.createTerminal({ diff --git a/mobile/src/terminal/document/terminal-theme.ts b/mobile/src/terminal/document/engine/terminal-theme.ts similarity index 87% rename from mobile/src/terminal/document/terminal-theme.ts rename to mobile/src/terminal/document/engine/terminal-theme.ts index c24fd4ce8b3..a48ad2ee670 100644 --- a/mobile/src/terminal/document/terminal-theme.ts +++ b/mobile/src/terminal/document/engine/terminal-theme.ts @@ -1,7 +1,8 @@ -import { paintBottomRowBackdrop } from './bottom-row-backdrop' -import { colors } from '../../theme/mobile-theme' -import type { TerminalDocumentScope, TerminalDocumentTheme } from './document-scope' -import { resolveTerminalMinimumContrastRatio } from '../../../../src/shared/terminal-themes/terminal-contrast-correction' +import { paintBottomRowBackdrop } from '../viewport/bottom-row-backdrop' +import { colors } from '../../../theme/mobile-theme' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentTheme } from '../document-terminal-shape' +import { resolveTerminalMinimumContrastRatio } from '../../../../../src/shared/terminal-themes/terminal-contrast-correction' const TERMINAL_BACKGROUND_FALLBACK = colors.terminalBg diff --git a/mobile/src/terminal/document/webgl-recovery.ts b/mobile/src/terminal/document/engine/webgl-recovery.ts similarity index 94% rename from mobile/src/terminal/document/webgl-recovery.ts rename to mobile/src/terminal/document/engine/webgl-recovery.ts index c5b73a08bac..af443b7d538 100644 --- a/mobile/src/terminal/document/webgl-recovery.ts +++ b/mobile/src/terminal/document/engine/webgl-recovery.ts @@ -1,6 +1,7 @@ -import { flog } from './viewport-transform' +import { flog } from '../viewport/viewport-transform' import { applyTerminalTheme } from './terminal-theme' -import type { TerminalDocumentScope, TerminalDocumentWebglAddon } from './document-scope' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentWebglAddon } from '../document-terminal-shape' export function refreshTerminalSurface(scope: TerminalDocumentScope) { if (!scope.term) { diff --git a/mobile/src/terminal/document/write-queue.test.ts b/mobile/src/terminal/document/engine/write-queue.test.ts similarity index 86% rename from mobile/src/terminal/document/write-queue.test.ts rename to mobile/src/terminal/document/engine/write-queue.test.ts index 74cf723ff87..9a094466dfa 100644 --- a/mobile/src/terminal/document/write-queue.test.ts +++ b/mobile/src/terminal/document/engine/write-queue.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' -import { createTerminalDocumentScope } from './document-scope' +import { createTerminalDocumentScope } from '../document-scope' import * as writeQueue from './write-queue' -import { terminalDocumentDouble } from './document-terminal-double.test-support' +import { terminalDocumentDouble } from '../document-terminal-double.test-support' type QueueSnapshot = { slots: unknown[]; head: number } @@ -85,20 +85,6 @@ describe('terminal WebView write queue', () => { // Legacy compaction retention grows with backlog because it waits for consumed slots to exceed half the queue. - it('hands xterm a 100 KB write as ordered slices of at most 16 KB', () => { - const queue = createWriteQueue() - const input = Array.from({ length: 100 * 1024 }, (_v, i) => - String.fromCharCode(0x61 + (i % 26)) - ).join('') - queue.enqueue(input) - drain(queue) - - expect(queue.writes.map((write) => write.length)).toEqual([ - 16_384, 16_384, 16_384, 16_384, 16_384, 16_384, 4_096 - ]) - expect(queue.writes.join('')).toBe(input) - }) - it('runs boundary callbacks between writes', () => { const queue = createWriteQueue() const order: string[] = [] diff --git a/mobile/src/terminal/document/write-queue.ts b/mobile/src/terminal/document/engine/write-queue.ts similarity index 97% rename from mobile/src/terminal/document/write-queue.ts rename to mobile/src/terminal/document/engine/write-queue.ts index f8502991620..739df758d54 100644 --- a/mobile/src/terminal/document/write-queue.ts +++ b/mobile/src/terminal/document/engine/write-queue.ts @@ -1,5 +1,5 @@ -import type { TerminalDocumentScope } from './document-scope' -import { C1_CSI, ESC } from './escape-introducers' +import type { TerminalDocumentScope } from '../document-scope' +import { C1_CSI, ESC } from '../surface-input/escape-introducers' // Force Claude’s status dot to text presentation on iOS WebKit. const CLAUDE_STATUS_DOT = '\u23fa' diff --git a/mobile/src/terminal/document/host-message-router.ts b/mobile/src/terminal/document/host-bridge/host-message-router.ts similarity index 83% rename from mobile/src/terminal/document/host-message-router.ts rename to mobile/src/terminal/document/host-bridge/host-message-router.ts index 380b2f5f427..76f5d6c85c5 100644 --- a/mobile/src/terminal/document/host-message-router.ts +++ b/mobile/src/terminal/document/host-bridge/host-message-router.ts @@ -1,18 +1,18 @@ -import { suspendSurfaceTouchGestures } from './surface-interaction-lifecycle' -import type { TerminalDocumentScope } from './document-scope' -import { applyFitScale } from './fit-scale' +import { suspendSurfaceTouchGestures } from '../surface-input/surface-interaction-lifecycle' +import type { TerminalDocumentScope } from '../document-scope' +import { applyFitScale } from '../viewport/fit-scale' import { notify } from './host-notify' -import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' -import { emitModesIfChanged } from './mode-mirroring' -import { reflow } from './reflow' -import { resumeTerminalDataReplyAuthority } from './query-reply' -import { repositionOverlay } from './selection-overlay' -import { cancelSelect } from './selection-mode' -import { resetEvictionCounter } from './selection-state-and-eviction' -import { applyTerminalTheme } from './terminal-theme' -import { init, resize, write } from './terminal-init' -import { applyTextScale } from './text-scaling' -import { afterQueuedWrites, resetWriteQueue } from './write-queue' +import { emitKeyboardAvoidanceMetrics } from '../viewport/keyboard-avoidance-metrics' +import { emitModesIfChanged } from '../engine/mode-mirroring' +import { reflow } from '../viewport/reflow' +import { resumeTerminalDataReplyAuthority } from '../engine/query-reply' +import { repositionOverlay } from '../selection/selection-overlay' +import { cancelSelect } from '../selection/selection-mode' +import { resetEvictionCounter } from '../selection/selection-state-and-eviction' +import { applyTerminalTheme } from '../engine/terminal-theme' +import { init, resize, write } from '../engine/terminal-init' +import { applyTextScale } from '../viewport/text-scaling' +import { afterQueuedWrites, resetWriteQueue } from '../engine/write-queue' export type TerminalHostMessage = { active?: boolean diff --git a/mobile/src/terminal/document/host-notify.ts b/mobile/src/terminal/document/host-bridge/host-notify.ts similarity index 92% rename from mobile/src/terminal/document/host-notify.ts rename to mobile/src/terminal/document/host-bridge/host-notify.ts index 8c46eda659c..076aa4d21a4 100644 --- a/mobile/src/terminal/document/host-notify.ts +++ b/mobile/src/terminal/document/host-bridge/host-notify.ts @@ -1,7 +1,5 @@ -import type { TerminalDocumentScope } from './document-scope' -import type { TerminalEngineError } from './document-host-seams' - -export type { TerminalEngineError } from './document-host-seams' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalEngineError } from '../document-host-seams' export function notify(scope: TerminalDocumentScope, msg: Record) { if (!scope.interactionActive && (msg.type === 'terminal-input' || msg.type === 'terminal-tap')) { diff --git a/mobile/src/terminal/document/host-bridge/message-bridge-fonts.test.ts b/mobile/src/terminal/document/host-bridge/message-bridge-fonts.test.ts new file mode 100644 index 00000000000..a85284f042b --- /dev/null +++ b/mobile/src/terminal/document/host-bridge/message-bridge-fonts.test.ts @@ -0,0 +1,60 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createTerminalDocumentScope } from '../document-scope' +import { startMessageBridge, stopMessageBridge } from './message-bridge' +const originalFonts = Object.getOwnPropertyDescriptor(document, 'fonts') +afterEach(() => { + vi.useRealTimers() + if (originalFonts) { + Object.defineProperty(document, 'fonts', originalFonts) + } else { + Reflect.deleteProperty(document, 'fonts') + } +}) + +function pendingFonts() { + let finish = () => {} + let fail = () => {} + const loaded = new Promise((resolve, reject) => { + finish = () => resolve([]) + fail = () => reject(new Error('font unavailable')) + }) + Object.defineProperty(document, 'fonts', { + configurable: true, + value: { check: () => false, load: () => loaded } + }) + const postToHost = vi.fn() + const scope = createTerminalDocumentScope({ + postToHost, + hasEngine: () => true, + start: () => ({ shown: false, textScale: 1 }), + installHostTransport: () => () => {} + }) + return { fail, finish, loaded, postToHost, scope } +} + +describe('the terminal waits for its bundled glyphs', () => { + it('also ignores font completion after a timed-out document is disposed', async () => { + vi.useFakeTimers() + const fonts = pendingFonts() + const clearTextureAtlas = vi.fn() + fonts.scope.webglAddon = { dispose() {}, clearTextureAtlas } + startMessageBridge(fonts.scope) + await vi.advanceTimersByTimeAsync(2000) + stopMessageBridge(fonts.scope) + fonts.finish() + await fonts.loaded + expect(clearTextureAtlas).not.toHaveBeenCalled() + expect(fonts.postToHost).toHaveBeenCalledOnce() + }) + + it('withholds readiness until the font can paint the first terminal snapshot', async () => { + const fonts = pendingFonts() + startMessageBridge(fonts.scope) + expect(fonts.postToHost).not.toHaveBeenCalled() + fonts.finish() + await fonts.loaded + expect(fonts.postToHost).toHaveBeenCalledWith({ type: 'web-ready', cellBox: null }) + stopMessageBridge(fonts.scope) + }) +}) diff --git a/mobile/src/terminal/document/message-bridge.ts b/mobile/src/terminal/document/host-bridge/message-bridge.ts similarity index 92% rename from mobile/src/terminal/document/message-bridge.ts rename to mobile/src/terminal/document/host-bridge/message-bridge.ts index 68e91f51b59..36831774a5b 100644 --- a/mobile/src/terminal/document/message-bridge.ts +++ b/mobile/src/terminal/document/host-bridge/message-bridge.ts @@ -1,10 +1,10 @@ import { handleMsg, type TerminalHostMessage } from './host-message-router' import { notify, reportEngineError } from './host-notify' -import { laidOutCellBox } from './laid-out-cell-box' -import { prepareTerminal } from './terminal-init' -import { refreshTerminalSurface } from './webgl-recovery' -import type { TerminalDocumentScope } from './document-scope' -import type { TerminalDocumentHostFrame } from './document-host-seams' +import { laidOutCellBox } from '../viewport/laid-out-cell-box' +import { prepareTerminal } from '../engine/terminal-init' +import { refreshTerminalSurface } from '../engine/webgl-recovery' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentHostFrame } from '../document-host-seams' // Parse at the router boundary so native JSON transport and embedded object sends share one message shape. export function handleIncomingMessage( diff --git a/mobile/src/terminal/document/laid-out-cell-box.test.ts b/mobile/src/terminal/document/laid-out-cell-box.test.ts deleted file mode 100644 index 6b88bde535b..00000000000 --- a/mobile/src/terminal/document/laid-out-cell-box.test.ts +++ /dev/null @@ -1,228 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it, vi } from 'vitest' -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' -import { terminalDocumentDouble } from './document-terminal-double.test-support' -import { handleMsg } from './host-message-router' -import { TERMINAL_DOCUMENT_MARKUP } from '../terminal-webview-html/document-markup' - -afterEach(() => { - vi.unstubAllGlobals() - document.body.innerHTML = '' -}) - -describe('laidOutCellBox', () => { - function scopeWithCell( - cell: { width: number; height: number }, - fontSize: number, - posted: Record[] = [] - ) { - const scope = createTerminalDocumentScope({ postToHost: (message) => posted.push(message) }) - scope.currentTextScale = 1.25 - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the reader touches only cols, rows, options.fontSize and _core's render dimensions. - scope.term = { - cols: 55, - rows: 47, - options: { fontSize }, - _core: { _renderService: { dimensions: { css: { cell } } } } - } as unknown as typeof scope.term - return scope - } - - 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 } - const scope = scopeWithCell(cell, 16, posted) - reportLaidOutCellBox(scope) - reportLaidOutCellBox(scope) - Object.assign(scope.term!, { cols: 50 }) - reportLaidOutCellBox(scope) - cell.width = 9.75 - reportLaidOutCellBox(scope) - expect(posted).toEqual([ - { - type: 'cell-box', - cellBox: { fontScale: 1.25, cellWidth: 29 / 3, cellHeight: 21 }, - refit: false - }, - { - type: 'cell-box', - cellBox: { fontScale: 1.25, cellWidth: 9.75, cellHeight: 21 }, - refit: true - } - ]) - }) -}) - -describe('a started document', () => { - function started(host: TerminalDocumentHost = {}) { - document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP - const cell = { width: 23 / 3, height: 15 } - const renderListeners: (() => void)[] = [] - const built: { options: Record }[] = [] - const createTerminal = (options: Record) => { - const terminal = terminalDocumentDouble().terminal - const grid = Object.assign(terminal, { - cols: Number(options.cols), - rows: Number(options.rows), - options: { ...terminal.options, fontSize: Number(options.fontSize) }, - _core: { - _renderService: { - get dimensions() { - const k = grid.options.fontSize / 13 - return { css: { cell: { width: cell.width * k, height: cell.height * k } } } - } - } - }, - onRender: (listener: () => void) => { - renderListeners.push(listener) - return { dispose() {} } - } - }) - grid.resize = (cols: number, rows: number) => { - grid.cols = cols - grid.rows = rows - } - built.push({ options }) - return grid - } - const posted: Record[] = [] - const scope = createTerminalDocumentScope({ - installHostTransport: () => () => {}, - hasEngine: () => true, - createTerminal, - postToHost: (message) => posted.push(message), - ...host - }) - startTerminalDocument(scope) - const render = () => renderListeners.forEach((listener) => listener()) - const init = () => - handleMsg(scope, { type: 'init', cols: 55, rows: 47, initialData: '', preserveScroll: false }) - return { scope, cell, posted, render, built, init } - } - - const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve())) - async function untilReady(posted: Record[]) { - for (let frame = 0; frame < 30 && !posted.some((m) => m.type === 'ready'); frame++) { - await nextFrame() - } - } - const boxes = (posted: Record[]) => - posted.filter((m) => m.type === 'cell-box').map((m) => m.cellBox) - const refits = (posted: Record[]) => - posted.filter((m) => m.type === 'cell-box').map((m) => m.refit) - const reflowTo = (scope: TerminalDocumentScope, cols: number) => - handleMsg(scope, { type: 'reflow', cols, rows: 47 }) - - it('leaves no live terminal when opening the one it builds before ready throws', () => { - const double = terminalDocumentDouble() - double.terminal.open = () => { - throw new Error('no surface') - } - const { scope, posted } = started({ createTerminal: () => double.terminal }) - try { - expect(scope.term).toBeNull() - expect(double.disposals()).toBe(1) - expect(posted[0]).toEqual({ type: 'web-ready', cellBox: null }) - } finally { - stopTerminalDocument(scope) - } - }) - - it('builds nothing before ready for a view hidden when it mounted, and reports no box', () => { - const { scope, posted, built } = started({ start: () => ({ textScale: 1, shown: false }) }) - try { - expect(built).toHaveLength(0) - expect(posted[0]).toEqual({ type: 'web-ready', cellBox: null }) - } 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 { - expect(scope.surface?.style.visibility).toBe('hidden') - expect(scope.surface?.style.display).toBe('') - expect(posted[0]).toEqual({ - type: 'web-ready', - cellBox: { fontScale: 1, cellWidth: 23 / 3, cellHeight: 15 } - }) - init() - expect(scope.surface?.style.visibility).toBe('hidden') - await untilReady(posted) - expect(scope.surface?.style.visibility).toBe('') - expect(posted.filter((message) => message.type === 'cell-box')).toEqual([]) - } finally { - stopTerminalDocument(scope) - } - }) - - it('reports a paused renderer at ready, before ready itself', async () => { - const { scope, cell, posted, init } = started() - try { - cell.width = 7.8 - init() - await untilReady(posted) - const types = posted.map((m) => m.type) - expect(types.indexOf('cell-box')).toBeGreaterThan(-1) - expect(types.indexOf('cell-box')).toBeLessThan(types.indexOf('ready')) - expect(boxes(posted)).toEqual([{ fontScale: 1, cellWidth: 7.8, cellHeight: 15 }]) - } finally { - stopTerminalDocument(scope) - } - }) - - it('reports a text-size change on the render after it, not when the font is set', async () => { - // Font-size changes update xterm metrics synchronously; onRender observes the new box only after repaint. - const { scope, posted, render, init } = started() - try { - init() - await untilReady(posted) - const reported = boxes(posted).length - handleMsg(scope, { type: 'set-font-scale', fontScale: 1.25 }) - expect(boxes(posted)).toHaveLength(reported) - render() - expect(boxes(posted).at(-1)).toEqual({ - fontScale: 1.25, - cellWidth: (23 / 3) * (16 / 13), - cellHeight: 15 * (16 / 13) - }) - } 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 { - cell.width = 7.8 - init() - await untilReady(posted) - expect(refits(posted)).toEqual([true]) - cell.width = 7.9 - reflowTo(scope, 54) - render() - expect(refits(posted)).toEqual([true, false]) - } finally { - stopTerminalDocument(scope) - } - }) - - it('refits a re-init at the same grid with a different renderer', async () => { - const { scope, cell, posted, init } = started() - try { - init() - await untilReady(posted) - posted.length = 0 - cell.width = 7.8 - init() - await untilReady(posted) - expect(refits(posted)).toEqual([true]) - } finally { - stopTerminalDocument(scope) - } - }) -}) diff --git a/mobile/src/terminal/document/message-bridge-fonts.test.ts b/mobile/src/terminal/document/message-bridge-fonts.test.ts deleted file mode 100644 index 52572b997b1..00000000000 --- a/mobile/src/terminal/document/message-bridge-fonts.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it, vi } from 'vitest' -import { terminalDocumentDouble } from './document-terminal-double.test-support' -import { createTerminalDocumentScope } from './document-scope' -import { startMessageBridge, stopMessageBridge } from './message-bridge' -import { startTerminalDocument } from './create-terminal-document' -import { TERMINAL_DOCUMENT_MARKUP } from '../terminal-webview-html/document-markup' - -const originalFonts = Object.getOwnPropertyDescriptor(document, 'fonts') -afterEach(() => { - vi.useRealTimers() - if (originalFonts) { - Object.defineProperty(document, 'fonts', originalFonts) - } else { - Reflect.deleteProperty(document, 'fonts') - } -}) - -function pendingFonts() { - let finish = () => {} - let fail = () => {} - const loaded = new Promise((resolve, reject) => { - finish = () => resolve([]) - fail = () => reject(new Error('font unavailable')) - }) - Object.defineProperty(document, 'fonts', { - configurable: true, - value: { check: () => false, load: () => loaded } - }) - const postToHost = vi.fn() - const scope = createTerminalDocumentScope({ - postToHost, - hasEngine: () => true, - start: () => ({ shown: false, textScale: 1 }), - installHostTransport: () => () => {} - }) - return { fail, finish, loaded, postToHost, scope } -} - -describe('the terminal waits for its bundled glyphs', () => { - it('starts once by the deadline if font loading never settles', async () => { - vi.useFakeTimers() - const fonts = pendingFonts() - const ready = startMessageBridge(fonts.scope) - await vi.advanceTimersByTimeAsync(1999) - expect(fonts.postToHost).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - await ready - expect(fonts.postToHost).toHaveBeenCalledExactlyOnceWith({ type: 'web-ready', cellBox: null }) - expect(vi.getTimerCount()).toBe(0) - stopMessageBridge(fonts.scope) - }) - - it('clears the fallback atlas when a timed-out font arrives without repeating readiness', async () => { - vi.useFakeTimers() - const fonts = pendingFonts() - const terminal = terminalDocumentDouble().terminal - const refresh = vi.spyOn(terminal, 'refresh') - const clearTextureAtlas = vi.fn() - fonts.scope.term = terminal - fonts.scope.webglAddon = { dispose() {}, clearTextureAtlas } - startMessageBridge(fonts.scope) - await vi.advanceTimersByTimeAsync(2000) - expect(fonts.postToHost).toHaveBeenCalledOnce() - fonts.finish() - await fonts.loaded - expect(clearTextureAtlas).toHaveBeenCalledOnce() - expect(refresh).toHaveBeenCalledExactlyOnceWith(0, 23) - expect(fonts.postToHost).toHaveBeenCalledOnce() - expect(fonts.scope.cancelFontReadiness).toBeNull() - stopMessageBridge(fonts.scope) - }) - - it('cancels the deadline and ignores late font completion after disposal', async () => { - vi.useFakeTimers() - const fonts = pendingFonts() - const terminal = terminalDocumentDouble().terminal - const refresh = vi.spyOn(terminal, 'refresh') - const clearTextureAtlas = vi.fn() - fonts.scope.term = terminal - fonts.scope.webglAddon = { dispose() {}, clearTextureAtlas } - const ready = startMessageBridge(fonts.scope) - stopMessageBridge(fonts.scope) - await ready - expect(vi.getTimerCount()).toBe(0) - fonts.finish() - await fonts.loaded - await vi.advanceTimersByTimeAsync(2000) - expect(fonts.postToHost).not.toHaveBeenCalled() - expect(clearTextureAtlas).not.toHaveBeenCalled() - expect(refresh).not.toHaveBeenCalled() - }) - - it('also ignores font completion after a timed-out document is disposed', async () => { - vi.useFakeTimers() - const fonts = pendingFonts() - const clearTextureAtlas = vi.fn() - fonts.scope.webglAddon = { dispose() {}, clearTextureAtlas } - startMessageBridge(fonts.scope) - await vi.advanceTimersByTimeAsync(2000) - stopMessageBridge(fonts.scope) - fonts.finish() - await fonts.loaded - expect(clearTextureAtlas).not.toHaveBeenCalled() - expect(fonts.postToHost).toHaveBeenCalledOnce() - }) - - it('takes back its deadline after rejection and ignores a later deadline', async () => { - vi.useFakeTimers() - const fonts = pendingFonts() - const ready = startMessageBridge(fonts.scope) - fonts.fail() - await ready - expect(vi.getTimerCount()).toBe(0) - await vi.advanceTimersByTimeAsync(2000) - expect(fonts.postToHost).toHaveBeenCalledExactlyOnceWith({ type: 'web-ready', cellBox: null }) - stopMessageBridge(fonts.scope) - }) - - it('unwinds failed startup reached by the font deadline', async () => { - vi.useFakeTimers() - const fonts = pendingFonts() - document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP - fonts.scope.postToHost = (message) => { - if (message.type === 'web-ready') { - throw new Error('timed-out readiness transport failed') - } - fonts.postToHost(message) - } - const removeTransport = vi.fn() - fonts.scope.installHostTransport = () => removeTransport - startTerminalDocument(fonts.scope) - await vi.advanceTimersByTimeAsync(2000) - expect(removeTransport).toHaveBeenCalledOnce() - expect(fonts.scope.framesStopped).toBe(true) - expect(vi.getTimerCount()).toBe(0) - expect(fonts.postToHost).toHaveBeenCalledWith({ - type: 'error', - fatal: true, - message: expect.stringContaining('timed-out readiness transport failed') - }) - fonts.finish() - await fonts.loaded - expect(fonts.postToHost).toHaveBeenCalledOnce() - }) - - it('withholds readiness until the font can paint the first terminal snapshot', async () => { - const fonts = pendingFonts() - startMessageBridge(fonts.scope) - expect(fonts.postToHost).not.toHaveBeenCalled() - fonts.finish() - await fonts.loaded - 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 - fonts.scope.postToHost = (message) => { - if (message.type === 'web-ready') { - throw new Error('readiness transport failed') - } - fonts.postToHost(message) - } - const removeTransport = vi.fn() - fonts.scope.installHostTransport = () => removeTransport - startTerminalDocument(fonts.scope) - fonts.finish() - await fonts.loaded - await Promise.resolve() - expect(removeTransport).toHaveBeenCalledOnce() - expect(fonts.scope.framesStopped).toBe(true) - expect(fonts.postToHost).toHaveBeenCalledWith({ - type: 'error', - fatal: true, - message: expect.stringContaining('readiness transport failed') - }) - }) -}) diff --git a/mobile/src/terminal/document/native-document-bundle.test.ts b/mobile/src/terminal/document/native-document-bundle.test.ts index a253e26dec5..25b2c77ade4 100644 --- a/mobile/src/terminal/document/native-document-bundle.test.ts +++ b/mobile/src/terminal/document/native-document-bundle.test.ts @@ -1,17 +1,7 @@ // @vitest-environment happy-dom import { afterEach, describe, expect, it } from 'vitest' -import { terminalDocumentBundle } from '../../../scripts/build-terminal-document-script.mjs' -import { createTerminalDocument } from './create-terminal-document' import { TERMINAL_DOCUMENT_SCRIPT } from '../terminal-webview-document-script.generated' import { TERMINAL_DOCUMENT_MARKUP } from '../terminal-webview-html' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { createHash } from 'node:crypto' -import { - bundleDigestBuiltFrom, - machinePathCommentsIn -} from '../../test-support/webview-document-bundle-digest' - // Execute the shipped bundle through native message transport; structural module checks cannot prove the WebView entry runs. function engineDouble() { const opened: HTMLElement[] = [] @@ -67,10 +57,6 @@ function engineDouble() { return { Terminal, opened, written } } -function post(message: Record) { - window.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(message) })) -} - // Capture and remove listeners on both targets; native never stops its page-owned document, but tests must isolate evaluations. function recordMessageListeners(run: () => void) { const added: string[] = [] @@ -152,98 +138,6 @@ describe('the bundled native document', () => { expect(document.getElementById('terminal-surface')?.contains(opened[0]!)).toBe(true) }) - 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 - const posted: Record[] = [] - const { Terminal, opened, written } = engineDouble() - Object.assign(globalThis, { - ReactNativeWebView: { - postMessage: (message: string) => posted.push(JSON.parse(message)) - }, - Terminal, - __engineErrors: [] - }) - evaluateBundle() - - post({ type: 'set-theme', terminalTheme: { theme: { background: 'rgb(1, 2, 3)' } } }) - expect(document.documentElement.style.background).toBe('rgb(1, 2, 3)') - post({ type: 'write', data: 'early chunk' }) - expect(posted.map((message) => message.type)).not.toContain('error') - - post({ - type: 'init', - cols: 80, - rows: 24, - initialData: 'replayed', - terminalTheme: { theme: { background: 'rgb(4, 5, 6)' } }, - preserveScroll: false - }) - await new Promise((resolve) => setTimeout(resolve, 0)) - - expect(opened).toHaveLength(1) - expect(document.documentElement.style.background).toBe('rgb(4, 5, 6)') - expect(written.join('')).toContain('replayed') - expect(written.join('')).not.toContain('early chunk') - post({ type: 'ping', id: 4 }) - expect(posted).toContainEqual({ type: 'pong', pingId: 4 }) - }) - - it('keeps the transport it installed, where the page installs none', () => { - // Native transport lives for its page; embedded documents install no shell-message listeners. - document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP - const { Terminal } = engineDouble() - Object.assign(globalThis, { - ReactNativeWebView: { postMessage: () => {} }, - Terminal, - __engineErrors: [] - }) - - expect(evaluateBundle()).toEqual(['window', 'document']) - const posted: Record[] = [] - Object.assign(globalThis, { - ReactNativeWebView: { - postMessage: (message: string) => posted.push(JSON.parse(message)) - } - }) - post({ type: 'ping', id: 7 }) - expect(posted).toContainEqual({ type: 'pong', pingId: 7 }) - - const host = document.createElement('div') - host.innerHTML = TERMINAL_DOCUMENT_MARKUP - document.body.appendChild(host) - const { added: pageListeners } = recordMessageListeners(() => { - createTerminalDocument({ - root: host, - hasEngine: () => true, - installHostTransport: () => () => {}, - postToHost: () => {}, - paintDocumentBackground: () => {}, - installErrorReporter: () => () => {}, - capturedEngineErrors: () => [] - }).stop() - }) - expect(pageListeners).toEqual([]) - }) - - it('is the same bytes wherever its generator was run from', () => { - // Postinstall can run from another cwd; pin build paths so the shipped artifact stays reproducible and contains no machine paths. - const generator = join( - import.meta.dirname, - '../../../scripts/build-terminal-document-script.mjs' - ) - const here = createHash('sha256').update(TERMINAL_DOCUMENT_SCRIPT).digest('hex') - expect(bundleDigestBuiltFrom(tmpdir(), generator, 'terminalDocumentBundle')).toBe(here) - expect(machinePathCommentsIn(TERMINAL_DOCUMENT_SCRIPT)).toEqual([]) - }, 30_000) - - it('ships the current document bundle without runtime dependencies', async () => { - // A transitive preferences import once bundled AsyncStorage into the phone’s script; verify the built graph/artifact keeps presets dependency-free. - const { script, inputs } = await terminalDocumentBundle() - expect(inputs.filter((input) => input.includes('node_modules'))).toEqual([]) - expect(TERMINAL_DOCUMENT_SCRIPT).toBe(script) - }, 30_000) - it('reports a missing engine rather than starting without one', () => { document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP const posted: Record[] = [] diff --git a/mobile/src/terminal/document/selection-menu-buttons.ts b/mobile/src/terminal/document/selection/selection-menu-buttons.ts similarity index 89% rename from mobile/src/terminal/document/selection-menu-buttons.ts rename to mobile/src/terminal/document/selection/selection-menu-buttons.ts index 150e6a99b42..fb0671ebd93 100644 --- a/mobile/src/terminal/document/selection-menu-buttons.ts +++ b/mobile/src/terminal/document/selection/selection-menu-buttons.ts @@ -1,5 +1,5 @@ -import type { TerminalDocumentScope } from './document-scope' -import { notify } from './host-notify' +import type { TerminalDocumentScope } from '../document-scope' +import { notify } from '../host-bridge/host-notify' import { cancelSelect } from './selection-mode' import { repositionOverlay } from './selection-overlay' diff --git a/mobile/src/terminal/document/selection-mode.ts b/mobile/src/terminal/document/selection/selection-mode.ts similarity index 80% rename from mobile/src/terminal/document/selection-mode.ts rename to mobile/src/terminal/document/selection/selection-mode.ts index a463b5be93c..90583c5c8d7 100644 --- a/mobile/src/terminal/document/selection-mode.ts +++ b/mobile/src/terminal/document/selection/selection-mode.ts @@ -1,9 +1,9 @@ -import type { TerminalDocumentScope } from './document-scope' -import { notify } from './host-notify' +import type { TerminalDocumentScope } from '../document-scope' +import { notify } from '../host-bridge/host-notify' import { repositionOverlay, stopEdgeScroll } from './selection-overlay' import { seedWordSelection } from './selection-range' -import { resetSmoothScrollOffset } from './normal-buffer-smooth-scroll' -import { stopSurfaceTouchGestures } from './surface-touch-gesture-stop' +import { resetSmoothScrollOffset } from '../viewport/normal-buffer-smooth-scroll' +import { stopSurfaceTouchGestures } from '../surface-input/surface-touch-gesture-stop' // Keep overlay transitions outside range math to avoid an overlay import cycle. diff --git a/mobile/src/terminal/document/selection-overlay.ts b/mobile/src/terminal/document/selection/selection-overlay.ts similarity index 93% rename from mobile/src/terminal/document/selection-overlay.ts rename to mobile/src/terminal/document/selection/selection-overlay.ts index e16d38a9e2e..61f42b3e61c 100644 --- a/mobile/src/terminal/document/selection-overlay.ts +++ b/mobile/src/terminal/document/selection/selection-overlay.ts @@ -1,9 +1,9 @@ -import { getCellHeight, getTotalScale } from './cell-metrics' -import { cellToViewportPx } from './cell-geometry' -import type { TerminalDocumentScope } from './document-scope' -import { notify } from './host-notify' +import { getCellHeight, getTotalScale } from '../viewport/cell-metrics' +import { cellToViewportPx } from '../viewport/cell-geometry' +import type { TerminalDocumentScope } from '../document-scope' +import { notify } from '../host-bridge/host-notify' import { applyXtermSelection, selRange } from './selection-range' -import { viewportPoint, viewportToCell } from './viewport-cell' +import { viewportPoint, viewportToCell } from '../viewport/viewport-cell' const EDGE_SCROLL_PX = 40 diff --git a/mobile/src/terminal/document/selection-range.test.ts b/mobile/src/terminal/document/selection/selection-range.test.ts similarity index 72% rename from mobile/src/terminal/document/selection-range.test.ts rename to mobile/src/terminal/document/selection/selection-range.test.ts index 982c481718a..a1b66e4de75 100644 --- a/mobile/src/terminal/document/selection-range.test.ts +++ b/mobile/src/terminal/document/selection/selection-range.test.ts @@ -2,7 +2,7 @@ import { Unicode11Addon } from '@xterm/addon-unicode11' import { Terminal } from '@xterm/xterm' import { afterEach, describe, expect, it, vi } from 'vitest' -import { createTerminalDocumentScope, type TerminalDocumentScope } from './document-scope' +import { createTerminalDocumentScope, type TerminalDocumentScope } from '../document-scope' import { seedWordSelection } from './selection-range' const terminals: Terminal[] = [] @@ -31,40 +31,6 @@ async function fixture(text: string) { } describe('word selection uses the rendered xterm cell range', () => { - it.each([ - ['합성 행 0001', 0, '합성', 0, 4], - ['합성 행 0001', 1, '합성', 0, 4], - ['합성 행 0001', 2, '합성', 0, 4], - ['합성 행 0001', 3, '합성', 0, 4], - ['합성 행 0001', 5, '행', 5, 2], - ['합성 행 0001', 6, '행', 5, 2], - ['합성 행 0001', 10, '0001', 8, 4], - ['🙂 hello', 0, '🙂', 0, 2], - ['🙂 hello', 1, '🙂', 0, 2], - ['🙂 hello', 3, 'hello', 3, 5], - ['cafe\u0301 done', 3, 'cafe\u0301', 0, 4], - ['cafe\u0301 done', 5, 'done', 5, 4], - ['𐐀x done', 0, '𐐀x', 0, 2], - ['🧑‍💻 done', 0, '🧑‍💻', 0, 4], - ['🧑‍💻 done', 3, '🧑‍💻', 0, 4], - ['🇰🇷 done', 0, '🇰🇷', 0, 2], - ['가 나', 2, ' ', 2, 1], - ['before /tmp/file.ts after', 10, '/tmp/file.ts', 7, 12], - ['echo $HOME', 7, '$HOME', 5, 5], - ['see (a.ts)', 6, 'a.ts', 5, 4], - ['', 6, ' '.repeat(60), 0, 60] - ] as const)('selects %s at cell %i', async (text, col, expected, start, length) => { - const f = await fixture(text) - seedWordSelection(f.scope, col, 0) - expect(f.select).toHaveBeenLastCalledWith(start, 0, length) - expect(f.selected()).toBe(expected) - expect(f.scope.sel).toEqual({ - anchor: { col: start, row: 0 }, - focus: { col: start + length - 1, row: 0 }, - activeHandle: null - }) - }) - it('keeps cell mapping when a legacy WebView has no grapheme segmenter', async () => { const f = await fixture('합성 🙂 cafe\u0301') vi.stubGlobal('Intl', Object.assign(Object.create(Intl), { Segmenter: undefined })) diff --git a/mobile/src/terminal/document/selection-range.ts b/mobile/src/terminal/document/selection/selection-range.ts similarity index 94% rename from mobile/src/terminal/document/selection-range.ts rename to mobile/src/terminal/document/selection/selection-range.ts index ce3eda8b42c..315466722b8 100644 --- a/mobile/src/terminal/document/selection-range.ts +++ b/mobile/src/terminal/document/selection/selection-range.ts @@ -1,7 +1,7 @@ -import { getLineText } from './cell-geometry' -import type { TerminalDocumentScope, TerminalDocumentSelection } from './document-scope' -import type { TerminalDocumentLine } from './document-terminal-shape' -import { isTerminalWordSeparator } from '../../../../src/shared/terminal/input/terminal-word-separator' +import { getLineText } from '../viewport/cell-geometry' +import type { TerminalDocumentScope, TerminalDocumentSelection } from '../document-scope' +import type { TerminalDocumentLine } from '../document-terminal-shape' +import { isTerminalWordSeparator } from '../../../../../src/shared/terminal/input/terminal-word-separator' // Match xterm double-click: a space grows over spaces, anything else over non-separators. function joinsPressedWord(pressed: string, text: string) { diff --git a/mobile/src/terminal/document/selection-state-and-eviction.ts b/mobile/src/terminal/document/selection/selection-state-and-eviction.ts similarity index 89% rename from mobile/src/terminal/document/selection-state-and-eviction.ts rename to mobile/src/terminal/document/selection/selection-state-and-eviction.ts index e7201812e1e..04a6c5a1ac9 100644 --- a/mobile/src/terminal/document/selection-state-and-eviction.ts +++ b/mobile/src/terminal/document/selection/selection-state-and-eviction.ts @@ -1,9 +1,9 @@ -import { elementInRoot } from './document-host-seams' +import { elementInRoot } from '../document-host-seams' import { repositionOverlay } from './selection-overlay' import { cancelSelect } from './selection-mode' -import { notify } from './host-notify' -import type { TerminalDocumentScope } from './document-scope' -import { DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT } from '../../../../src/shared/terminal/replay/terminal-scrollback-policy' +import { notify } from '../host-bridge/host-notify' +import type { TerminalDocumentScope } from '../document-scope' +import { DESKTOP_TERMINAL_SCROLLBACK_ROWS_DEFAULT } from '../../../../../src/shared/terminal/replay/terminal-scrollback-policy' // Tap slop must exceed long-press slop so small finger jitter can cancel selection without dropping link/path taps. diff --git a/mobile/src/terminal/document/escape-introducers.ts b/mobile/src/terminal/document/surface-input/escape-introducers.ts similarity index 100% rename from mobile/src/terminal/document/escape-introducers.ts rename to mobile/src/terminal/document/surface-input/escape-introducers.ts diff --git a/mobile/src/terminal/document/mouse-click-drag.ts b/mobile/src/terminal/document/surface-input/mouse-click-drag.ts similarity index 96% rename from mobile/src/terminal/document/mouse-click-drag.ts rename to mobile/src/terminal/document/surface-input/mouse-click-drag.ts index d249cd8b147..3f177bf114f 100644 --- a/mobile/src/terminal/document/mouse-click-drag.ts +++ b/mobile/src/terminal/document/surface-input/mouse-click-drag.ts @@ -1,10 +1,10 @@ -import { handleDragMove, repositionOverlay, stopEdgeScroll } from './selection-overlay' -import { cancelSelect } from './selection-mode' -import { applyXtermSelection } from './selection-range' -import { notify } from './host-notify' +import { handleDragMove, repositionOverlay, stopEdgeScroll } from '../selection/selection-overlay' +import { cancelSelect } from '../selection/selection-mode' +import { applyXtermSelection } from '../selection/selection-range' +import { notify } from '../host-bridge/host-notify' import { getMouseTrackingMode, isSafeSgrMouseCoordinate } from './mouse-input-encoding' -import { viewportToCell } from './viewport-cell' -import type { TerminalDocumentScope } from './document-scope' +import { viewportToCell } from '../viewport/viewport-cell' +import type { TerminalDocumentScope } from '../document-scope' import { ESC } from './escape-introducers' import { notifyTerminalSurfaceTap } from './surface-tap' import { viewportToMouseReportCell } from './mouse-report-cell' diff --git a/mobile/src/terminal/document/mouse-input-encoding.ts b/mobile/src/terminal/document/surface-input/mouse-input-encoding.ts similarity index 98% rename from mobile/src/terminal/document/mouse-input-encoding.ts rename to mobile/src/terminal/document/surface-input/mouse-input-encoding.ts index 6f642296e42..a7115e20e4c 100644 --- a/mobile/src/terminal/document/mouse-input-encoding.ts +++ b/mobile/src/terminal/document/surface-input/mouse-input-encoding.ts @@ -1,5 +1,5 @@ -import { notify } from './host-notify' -import type { TerminalDocumentScope } from './document-scope' +import { notify } from '../host-bridge/host-notify' +import type { TerminalDocumentScope } from '../document-scope' import { ESC } from './escape-introducers' import { viewportToMouseReportCell } from './mouse-report-cell' diff --git a/mobile/src/terminal/document/mouse-mode-decset-scan.ts b/mobile/src/terminal/document/surface-input/mouse-mode-decset-scan.ts similarity index 95% rename from mobile/src/terminal/document/mouse-mode-decset-scan.ts rename to mobile/src/terminal/document/surface-input/mouse-mode-decset-scan.ts index 27638ddc687..0c333ca94ee 100644 --- a/mobile/src/terminal/document/mouse-mode-decset-scan.ts +++ b/mobile/src/terminal/document/surface-input/mouse-mode-decset-scan.ts @@ -1,5 +1,5 @@ -import { extractMouseModeScanTail } from './write-queue' -import type { TerminalDocumentScope } from './document-scope' +import { extractMouseModeScanTail } from '../engine/write-queue' +import type { TerminalDocumentScope } from '../document-scope' import { C1_CSI, ESC } from './escape-introducers' export function isAltScreenActive(data: unknown): data is string { diff --git a/mobile/src/terminal/document/mouse-report-cell.ts b/mobile/src/terminal/document/surface-input/mouse-report-cell.ts similarity index 87% rename from mobile/src/terminal/document/mouse-report-cell.ts rename to mobile/src/terminal/document/surface-input/mouse-report-cell.ts index 724f76b5cab..dfa14f89a56 100644 --- a/mobile/src/terminal/document/mouse-report-cell.ts +++ b/mobile/src/terminal/document/surface-input/mouse-report-cell.ts @@ -1,6 +1,6 @@ -import { getCellHeight, getCellWidth, getTotalScale } from './cell-metrics' -import { viewportPoint } from './viewport-cell' -import type { TerminalDocumentScope } from './document-scope' +import { getCellHeight, getCellWidth, getTotalScale } from '../viewport/cell-metrics' +import { viewportPoint } from '../viewport/viewport-cell' +import type { TerminalDocumentScope } from '../document-scope' export type MouseReportCell = { col: number; row: number; x: number; y: number } diff --git a/mobile/src/terminal/document/osc-link-tap.ts b/mobile/src/terminal/document/surface-input/osc-link-tap.ts similarity index 89% rename from mobile/src/terminal/document/osc-link-tap.ts rename to mobile/src/terminal/document/surface-input/osc-link-tap.ts index fbf227b2e3f..cbf8faff6ee 100644 --- a/mobile/src/terminal/document/osc-link-tap.ts +++ b/mobile/src/terminal/document/surface-input/osc-link-tap.ts @@ -1,13 +1,13 @@ -import { cellColToStringIndex, getLineText } from './cell-geometry' -import { viewportToCell } from './viewport-cell' +import { cellColToStringIndex, getLineText } from '../viewport/cell-geometry' +import { viewportToCell } from '../viewport/viewport-cell' +import type { TerminalDocumentScope } from '../document-scope' import type { TerminalDocumentLine, - TerminalDocumentScope, TerminalInitialOscLink, TerminalOscLinkService -} from './document-scope' -import type { ParsedFileLinkLocation } from '../../../../src/shared/file-links/file-link-location' -import { classifyTerminalOscLinkTarget } from '../../../../src/shared/terminal/links/terminal-osc-link-target' +} from '../document-terminal-shape' +import type { ParsedFileLinkLocation } from '../../../../../src/shared/file-links/file-link-location' +import { classifyTerminalOscLinkTarget } from '../../../../../src/shared/terminal/links/terminal-osc-link-target' export type TerminalOscLinkTarget = | { kind: 'url'; url: string } diff --git a/mobile/src/terminal/document/surface-interaction-lifecycle.ts b/mobile/src/terminal/document/surface-input/surface-interaction-lifecycle.ts similarity index 75% rename from mobile/src/terminal/document/surface-interaction-lifecycle.ts rename to mobile/src/terminal/document/surface-input/surface-interaction-lifecycle.ts index 3a3d5bdee9a..da61f5fbe23 100644 --- a/mobile/src/terminal/document/surface-interaction-lifecycle.ts +++ b/mobile/src/terminal/document/surface-input/surface-interaction-lifecycle.ts @@ -1,8 +1,8 @@ -import type { TerminalDocumentScope } from './document-scope' -import { stopSurfaceTouchGestures } from './surface-touch-gestures' -import { resetSmoothScrollOffset } from './normal-buffer-smooth-scroll' +import type { TerminalDocumentScope } from '../document-scope' +import { stopSurfaceTouchGestures } from './surface-touch-gesture-stop' +import { resetSmoothScrollOffset } from '../viewport/normal-buffer-smooth-scroll' import { clearLongPress } from './tap-dispatch' -import { stopEdgeScroll } from './selection-overlay' +import { stopEdgeScroll } from '../selection/selection-overlay' export function suspendSurfaceTouchGestures(scope: TerminalDocumentScope) { stopSurfaceTouchGestures(scope) diff --git a/mobile/src/terminal/document/surface-tap.ts b/mobile/src/terminal/document/surface-input/surface-tap.ts similarity index 87% rename from mobile/src/terminal/document/surface-tap.ts rename to mobile/src/terminal/document/surface-input/surface-tap.ts index 25acfc3ed9d..f9fcc81f4a4 100644 --- a/mobile/src/terminal/document/surface-tap.ts +++ b/mobile/src/terminal/document/surface-input/surface-tap.ts @@ -1,17 +1,17 @@ -import type { TerminalDocumentScope } from './document-scope' -import { notify } from './host-notify' +import type { TerminalDocumentScope } from '../document-scope' +import { notify } from '../host-bridge/host-notify' import { buildMouseClickInput, getMouseTrackingMode, isClickMouseTrackingMode } from './mouse-input-encoding' import { oscLinkAtViewportPoint } from './osc-link-tap' -import { viewportToCell } from './viewport-cell' -import type { ParsedFileLinkLocation } from '../../../../src/shared/file-links/file-link-location' +import { viewportToCell } from '../viewport/viewport-cell' +import type { ParsedFileLinkLocation } from '../../../../../src/shared/file-links/file-link-location' import { findTerminalFileLinksAtBufferPosition, findTerminalHttpLinkAtBufferPosition -} from '../../../../src/shared/terminal/links/terminal-link-buffer-hit-testing' +} from '../../../../../src/shared/terminal/links/terminal-link-buffer-hit-testing' export function notifyTerminalSurfaceTap( scope: TerminalDocumentScope, diff --git a/mobile/src/terminal/document/surface-touch-gesture-stop.ts b/mobile/src/terminal/document/surface-input/surface-touch-gesture-stop.ts similarity index 71% rename from mobile/src/terminal/document/surface-touch-gesture-stop.ts rename to mobile/src/terminal/document/surface-input/surface-touch-gesture-stop.ts index 7be26e3ccdd..385d32d3067 100644 --- a/mobile/src/terminal/document/surface-touch-gesture-stop.ts +++ b/mobile/src/terminal/document/surface-input/surface-touch-gesture-stop.ts @@ -1,7 +1,7 @@ -import type { TerminalDocumentScope } from './document-scope' -import { cancelDocumentFrame } from './document-frame-registry' -import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' -import { updateTransform } from './viewport-transform' +import type { TerminalDocumentScope } from '../document-scope' +import { cancelDocumentFrame } from '../document-frame-registry' +import { emitKeyboardAvoidanceMetrics } from '../viewport/keyboard-avoidance-metrics' +import { updateTransform } from '../viewport/viewport-transform' // Leaf module so selection mode can end gestures without importing the gesture handlers. export function stopSurfaceTouchGestures(scope: TerminalDocumentScope) { diff --git a/mobile/src/terminal/document/surface-touch-gestures.ts b/mobile/src/terminal/document/surface-input/surface-touch-gestures.ts similarity index 94% rename from mobile/src/terminal/document/surface-touch-gestures.ts rename to mobile/src/terminal/document/surface-input/surface-touch-gestures.ts index 6dc83231bf1..a276b14d212 100644 --- a/mobile/src/terminal/document/surface-touch-gestures.ts +++ b/mobile/src/terminal/document/surface-input/surface-touch-gestures.ts @@ -1,30 +1,28 @@ -import { getCellHeight, getTotalScale } from './cell-metrics' -import type { TerminalDocumentScope } from './document-scope' -import { cancelDocumentFrame, scheduleDocumentFrame } from './document-frame-registry' -import { touchesInRoot } from './document-host-seams' -import { clampPan } from './fit-scale' -import { notify } from './host-notify' +import { getCellHeight, getTotalScale } from '../viewport/cell-metrics' +import type { TerminalDocumentScope } from '../document-scope' +import { cancelDocumentFrame, scheduleDocumentFrame } from '../document-frame-registry' +import { touchesInRoot } from '../document-host-seams' +import { clampPan } from '../viewport/fit-scale' +import { notify } from '../host-bridge/host-notify' import { attachSurfaceMouseClickDragHandler } from './mouse-click-drag' import { routeScrollLines, shouldRouteScrollToTerminalInput } from './mouse-input-encoding' import { applyNormalBufferScrollDelta, enqueueNormalBufferScrollDelta, resetSmoothScrollOffset -} from './normal-buffer-smooth-scroll' +} from '../viewport/normal-buffer-smooth-scroll' import { dispatcherShouldBlockSurface } from './tap-dispatch' import { applyTextScale, MAX_TEXT_SCALE, MIN_TEXT_SCALE, snapToTextScalePreset -} from './text-scaling' -import { updateTransform } from './viewport-transform' -import { viewportPoint } from './viewport-cell' +} from '../viewport/text-scaling' +import { updateTransform } from '../viewport/viewport-transform' +import { viewportPoint } from '../viewport/viewport-cell' import { attachSurfaceWheelHandler } from './wheel-scroll' import { stopSurfaceTouchGestures } from './surface-touch-gesture-stop' -export { stopSurfaceTouchGestures } - const RELEASE_VELOCITY_MAX_AGE_MS = 100 type TerminalGestureSurface = HTMLElement & { __orcaSurfaceHandlersAttached?: boolean } diff --git a/mobile/src/terminal/document/tap-dispatch.ts b/mobile/src/terminal/document/surface-input/tap-dispatch.ts similarity index 95% rename from mobile/src/terminal/document/tap-dispatch.ts rename to mobile/src/terminal/document/surface-input/tap-dispatch.ts index 10b479d60fe..f2fb4da87e1 100644 --- a/mobile/src/terminal/document/tap-dispatch.ts +++ b/mobile/src/terminal/document/surface-input/tap-dispatch.ts @@ -1,15 +1,15 @@ -import { handleDragMove, stopEdgeScroll } from './selection-overlay' -import { cancelSelect, enterSelect } from './selection-mode' -import { notify } from './host-notify' -import { viewportToCell } from './viewport-cell' -import type { TerminalDocumentScope } from './document-scope' -import { queuedNormalBufferScrollReachesRow } from './normal-buffer-smooth-scroll' +import { handleDragMove, stopEdgeScroll } from '../selection/selection-overlay' +import { cancelSelect, enterSelect } from '../selection/selection-mode' +import { notify } from '../host-bridge/host-notify' +import { viewportToCell } from '../viewport/viewport-cell' +import type { TerminalDocumentScope } from '../document-scope' +import { queuedNormalBufferScrollReachesRow } from '../viewport/normal-buffer-smooth-scroll' import { notifyTerminalSurfaceTap } from './surface-tap' import { eventTargetInRoot, touchesInRoot, type TerminalDocumentTargetContainer -} from './document-host-seams' +} from '../document-host-seams' const LONG_PRESS_MS = 500 diff --git a/mobile/src/terminal/document/wheel-scroll.ts b/mobile/src/terminal/document/surface-input/wheel-scroll.ts similarity index 90% rename from mobile/src/terminal/document/wheel-scroll.ts rename to mobile/src/terminal/document/surface-input/wheel-scroll.ts index 44fb73d8aee..93993072a9f 100644 --- a/mobile/src/terminal/document/wheel-scroll.ts +++ b/mobile/src/terminal/document/surface-input/wheel-scroll.ts @@ -1,11 +1,11 @@ -import { getCellHeight, getTotalScale } from './cell-metrics' -import { notify } from './host-notify' +import { getCellHeight, getTotalScale } from '../viewport/cell-metrics' +import { notify } from '../host-bridge/host-notify' import { routeScrollLines, shouldRouteScrollToTerminalInput } from './mouse-input-encoding' import { enqueueNormalBufferScrollDelta, resetSmoothScrollOffset -} from './normal-buffer-smooth-scroll' -import type { TerminalDocumentScope } from './document-scope' +} from '../viewport/normal-buffer-smooth-scroll' +import type { TerminalDocumentScope } from '../document-scope' const WHEEL_SEQUENCE_IDLE_MS = 150 diff --git a/mobile/src/terminal/document/terminal-replay-scroll.test.ts b/mobile/src/terminal/document/terminal-replay-scroll.test.ts deleted file mode 100644 index bf0d1d583c6..00000000000 --- a/mobile/src/terminal/document/terminal-replay-scroll.test.ts +++ /dev/null @@ -1,213 +0,0 @@ -// @vitest-environment happy-dom -import { Terminal } from '@xterm/xterm' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { TERMINAL_DOCUMENT_MARKUP } from '../terminal-webview-html' -import { createTerminalDocumentScope, type TerminalDocumentScope } from './document-scope' -import { startTerminalDocument, stopTerminalDocument } from './create-terminal-document' -import { terminalDocumentDouble } from './document-terminal-double.test-support' -import type { TerminalDocumentTerminal } from './document-terminal-shape' -import { handleMsg } from './host-message-router' -import { afterWritesDrained } from './write-queue' -import { startEdgeScroll } from './selection-overlay' - -const scopes: TerminalDocumentScope[] = [] - -function createReplayHarness() { - const frames: FrameRequestCallback[] = [] - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - frames.push(callback) - return frames.length - }) - vi.stubGlobal('cancelAnimationFrame', () => {}) - document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP - const terminals: Terminal[] = [] - const writeCompletions: (() => void)[] = [] - let deferWrites = false - const scope = createTerminalDocumentScope({ - hasEngine: () => true, - installHostTransport: () => () => {}, - createTerminal: (options) => { - const terminal = new Terminal({ - cols: typeof options.cols === 'number' ? options.cols : 80, - rows: typeof options.rows === 'number' ? options.rows : 24, - scrollback: 5000, - allowProposedApi: true - }) - terminals.push(terminal) - // Real xterm parser and viewport, without a canvas renderer. - return { - ...terminalDocumentDouble().terminal, - get cols() { - return terminal.cols - }, - get rows() { - return terminal.rows - }, - get buffer() { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm's own buffer; only getCell's cell parameter is narrower in the document shape, as in terminal-web-document-mount.ts. - return terminal.buffer as unknown as TerminalDocumentTerminal['buffer'] - }, - write: (data, callback) => - terminal.write(data, () => { - if (callback && deferWrites) { - writeCompletions.push(callback) - } else { - callback?.() - } - }), - clear: () => terminal.clear(), - reset: () => terminal.reset(), - resize: (cols, rows) => terminal.resize(cols, rows), - scrollToLine: (line) => terminal.scrollToLine(line), - scrollLines: (lines) => terminal.scrollLines(lines), - scrollToBottom: () => terminal.scrollToBottom(), - dispose: () => terminal.dispose() - } - }, - createUnicode11Addon: () => null, - createWebglAddon: () => null, - postToHost: () => {} - }) - startTerminalDocument(scope) - scopes.push(scope) - - const snapshot = Array.from({ length: 200 }, (_, index) => `ROW_${index}`).join('\r\n') - return { - scope, - terminals, - replay: (preserveScroll: boolean, cols: number, initialData = snapshot) => { - handleMsg(scope, { - type: 'init', - cols, - rows: 24, - initialData, - preserveScroll - }) - frames.shift()?.(0) - }, - drain: () => new Promise((resolve) => afterWritesDrained(scope, resolve)), - parse: () => new Promise((resolve) => terminals.at(-1)!.write('', resolve)), - holdReplays: (hold: boolean) => { - deferWrites = hold - }, - releaseHeldReplays: () => { - for (const complete of writeCompletions.splice(0).toReversed()) { - complete() - } - } - } -} - -type ReplayHarness = ReturnType - -async function readAt40ThenOvertakeHiddenReplay({ - hiddenReplayData, - duringHiddenReplay -}: { - hiddenReplayData?: string - duringHiddenReplay?: (harness: ReplayHarness) => void -} = {}) { - const harness = createReplayHarness() - harness.replay(false, 80) - await harness.drain() - harness.terminals[0]!.scrollToLine(40) - harness.holdReplays(true) - harness.replay(true, 81, hiddenReplayData) - await harness.parse() - expect(harness.scope.pendingSurface).not.toBeNull() - duringHiddenReplay?.(harness) - harness.holdReplays(false) - harness.replay(true, 82) - await harness.drain() - // The overtaken replay's late completion must not commit it or move the reader. - harness.releaseHeldReplays() - expect(harness.scope.pendingTerm).toBeNull() - expect(document.querySelectorAll('#terminal-container > div')).toHaveLength(1) - return harness.scope.committedTerm!.buffer.active -} - -afterEach(() => { - for (const scope of scopes.splice(0)) { - stopTerminalDocument(scope) - } - vi.unstubAllGlobals() - vi.useRealTimers() -}) - -describe('mobile terminal replay reading position', () => { - it.each([ - { name: '' }, - { - name: ' that printed live output', - duringHiddenReplay: (harness: ReplayHarness) => - handleMsg(harness.scope, { type: 'write', data: '\r\nLIVE' }) - } - ])( - 'keeps the reading position when a resize snapshot overtakes a hidden replay$name', - async ({ name: _name, ...overtake }) => { - const buffer = await readAt40ThenOvertakeHiddenReplay(overtake) - - expect(buffer.viewportY).toBe(40) - expect(buffer.getLine(40)?.translateToString(true)).toBe('ROW_40') - } - ) - - it.each([ - { - name: 'the terminal was cleared', - duringHiddenReplay: (harness: ReplayHarness) => handleMsg(harness.scope, { type: 'clear' }) - }, - { - name: 'the hidden replay was an alternate screen', - hiddenReplayData: '\x1b[?1049h\x1b[HTUI' - } - ])('follows the bottom when $name', async ({ name: _name, ...overtake }) => { - const buffer = await readAt40ThenOvertakeHiddenReplay(overtake) - - expect(buffer.type).toBe('normal') - expect(buffer.viewportY).toBe(buffer.baseY) - }) -}) - -it('returns to the prompt during a replay and keeps it there when ready', async () => { - const harness = createReplayHarness() - harness.replay(false, 80) - await harness.drain() - const visible = harness.terminals[0] - if (!visible) { - throw new Error('Missing visible terminal') - } - visible.scrollToLine(40) - harness.holdReplays(true) - harness.replay(true, 81) - await harness.parse() - handleMsg(harness.scope, { type: 'scroll-to-bottom' }) - expect(visible.buffer.active.viewportY).toBe(visible.buffer.active.baseY) - harness.releaseHeldReplays() - await harness.drain() - const ready = harness.scope.committedTerm - expect(ready?.buffer.active.viewportY).toBe(ready?.buffer.active.baseY) -}) - -it('keeps the prompt visible after interrupting selection edge scrolling', async () => { - const harness = createReplayHarness() - harness.replay(false, 80) - await harness.drain() - const terminal = harness.terminals[0] - if (!terminal) { - throw new Error('Missing terminal') - } - terminal.scrollToLine(40) - vi.useFakeTimers() - startEdgeScroll(harness.scope, -1) - vi.advanceTimersByTime(120) - expect(terminal.buffer.active.viewportY).toBe(38) - - handleMsg(harness.scope, { type: 'scroll-to-bottom' }) - vi.advanceTimersByTime(180) - expect(terminal.buffer.active.viewportY).toBe(terminal.buffer.active.baseY) - - startEdgeScroll(harness.scope, -1) - vi.advanceTimersByTime(60) - expect(terminal.buffer.active.viewportY).toBe(terminal.buffer.active.baseY - 1) -}) diff --git a/mobile/src/terminal/document/viewport-frame.test.ts b/mobile/src/terminal/document/viewport-frame.test.ts deleted file mode 100644 index 976602c386f..00000000000 --- a/mobile/src/terminal/document/viewport-frame.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { startTerminalDocument, stopTerminalDocument } from './create-terminal-document' -import { createTerminalDocumentScope, type TerminalDocumentScope } from './document-scope' -import type { TerminalDocumentHost, TerminalViewportChange } from './document-host-seams' -import { terminalDocumentDouble } from './document-terminal-double.test-support' -import { handleMsg } from './host-message-router' -import { viewportToMouseReportCell } from './mouse-report-cell' -import { handleDragMove } from './selection-overlay' -import { TERMINAL_DOCUMENT_MARKUP } from '../terminal-webview-html/document-markup' -import { viewportToCell } from './viewport-cell' -import { computeFitScale } from './viewport-transform' - -const HEADER = 82 -const CELL = { width: 7.5, height: 15 } - -function scopeWithGrid(host: TerminalDocumentHost = {}): TerminalDocumentScope { - const scope = createTerminalDocumentScope(host) - const terminal = terminalDocumentDouble().terminal - const cell = () => { - const k = terminal.options.fontSize / 13 - return { width: CELL.width * k, height: CELL.height * k } - } - const grid = Object.assign(terminal, { - cols: 55, - rows: 40, - _core: { - _renderService: { - get dimensions() { - return { css: { cell: cell() } } - } - } - } - }) - grid.resize = (cols: number, rows: number) => { - grid.cols = cols - grid.rows = rows - } - scope.term = grid - return scope -} - -const started: TerminalDocumentScope[] = [] - -beforeEach(() => { - vi.useFakeTimers() -}) - -afterEach(() => { - while (started.length > 0) { - stopTerminalDocument(started.pop()!) - } - vi.restoreAllMocks() - vi.useRealTimers() -}) - -function startedWithGrid(host: TerminalDocumentHost): TerminalDocumentScope { - document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP - const grid = scopeWithGrid().term! - const scope = createTerminalDocumentScope({ - installHostTransport: () => () => {}, - hasEngine: () => true, - createTerminal: () => grid, - ...host - }) - startTerminalDocument(scope) - started.push(scope) - handleMsg(scope, { type: 'init', cols: 55, rows: 40, initialData: '', preserveScroll: false }) - return scope -} - -const nextFrame = () => vi.advanceTimersToNextFrame() - -async function framesUntil(done: () => boolean, { required = true } = {}) { - for (let frame = 0; frame < 30 && !done(); frame++) { - await nextFrame() - } - if (required) { - expect(done()).toBe(true) - } -} - -const FIT_390 = 390 / (7.5 * 55) - -const pageHost = (): TerminalDocumentHost => ({ - viewportRect: () => ({ left: 0, top: HEADER, width: 412, height: 600 }) -}) - -describe("the document's frame on the page", () => { - it('maps a tap below a header to the cell the WebView reports for the same spot', () => { - const native = viewportToCell(scopeWithGrid(), 30, 150) - const page = viewportToCell(scopeWithGrid(pageHost()), 30, 150 + HEADER) - expect(native).toEqual({ col: 4, row: 10 }) - expect(page).toEqual(native) - }) - - it('reports a mouse cell below a header as the WebView does', () => { - const native = viewportToMouseReportCell(scopeWithGrid(), 30, 150) - const page = viewportToMouseReportCell(scopeWithGrid(pageHost()), 30, 150 + HEADER) - expect(native).toMatchObject({ col: 4, row: 10 }) - expect(page).toEqual(native) - }) - - it('keeps the fit at 1 while the host is hidden and measures 0x0', () => { - // Inactive react-native-screens routes use display:none and have no measurable host box. - const scope = scopeWithGrid({ - viewportRect: () => ({ left: 0, top: 0, width: 0, height: 0 }) - }) - expect(computeFitScale(scope)).toBe(1) - }) - - it('commits no fit before the host has a box, and one once it has', async () => { - // Initial hidden mounts wait for real RN layout; subsequent hide/show is handled by the mount adapter. - let box = { left: 0, top: 0, width: 0, height: 0 } - const widthsRead: number[] = [] - const changes: ((change: TerminalViewportChange) => void)[] = [] - const scope = startedWithGrid({ - viewportRect: () => { - widthsRead.push(box.width) - return box - }, - observeViewport: (onChange) => { - changes.push(onChange) - return () => {} - } - }) - const scales: string[] = [] - const style = scope.surface!.style - const write = style.setProperty - vi.spyOn(style, 'setProperty').mockImplementation((name, value, priority) => { - if (name === 'transform') { - const transform = String(value) - scales.push(/scale\(([^)]*)\)/.exec(transform)?.[1] ?? transform) - } - write.call(style, name, value, priority) - }) - await framesUntil(() => widthsRead.includes(0)) - await nextFrame() - expect(scales).toEqual([]) - box = { left: 0, top: 0, width: 390, height: 600 } - changes.forEach((onChange) => onChange('resized')) - await framesUntil(() => scales.length === 2) - expect(scales).toEqual(['1', String(FIT_390)]) - }) - - it("edge-scrolls at the host's own edges, not the window's", () => { - const scope = startedWithGrid({ - viewportRect: () => ({ left: 0, top: 100, width: 412, height: 600 }) - }) - scope.selMode = 'select' - scope.sel = { anchor: { col: 0, row: 5 }, focus: { col: 3, row: 5 }, activeHandle: 'end' } - const edge = (clientY: number) => { - handleDragMove(scope, 'end', 30, clientY) - return scope.edgeScrollDir - } - expect(edge(580)).toBe(0) - expect(edge(680)).toBe(1) - expect(edge(400)).toBe(0) - expect(edge(120)).toBe(-1) - }) -}) diff --git a/mobile/src/terminal/document/bottom-row-backdrop.test.ts b/mobile/src/terminal/document/viewport/bottom-row-backdrop.test.ts similarity index 73% rename from mobile/src/terminal/document/bottom-row-backdrop.test.ts rename to mobile/src/terminal/document/viewport/bottom-row-backdrop.test.ts index c90034e3405..b8817137d34 100644 --- a/mobile/src/terminal/document/bottom-row-backdrop.test.ts +++ b/mobile/src/terminal/document/viewport/bottom-row-backdrop.test.ts @@ -2,11 +2,10 @@ import { Terminal } from '@xterm/xterm' import { afterEach, describe, expect, it } from 'vitest' -import { DEFAULT_TERMINAL_THEME } from '../terminal-webview-html/theme' import { lastRowBackground } from './bottom-row-backdrop' -import { stopTerminalDocument } from './create-terminal-document' +import { stopTerminalDocument } from '../create-terminal-document' -import { createTerminalDocumentScope, type TerminalDocumentScope } from './document-scope' +import { createTerminalDocumentScope, type TerminalDocumentScope } from '../document-scope' const NAVY = 'rgb(14, 20, 37)' @@ -39,18 +38,6 @@ describe("xterm's own cells", () => { } } }) - - it('reads the visible bottom row while scrolled back', async () => { - const term = new Terminal({ cols: 10, rows: 2, scrollback: 10, allowProposedApi: true }) - try { - await write(term, '\r\n\x1b[48;2;14;20;37m\x1b[K\x1b[0m\r\n\r\n') - expect(lastRowOf(term)).toBe(DEFAULT_TERMINAL_THEME.background) - term.scrollToLine(0) - expect(lastRowOf(term)).toBe(NAVY) - } finally { - term.dispose() - } - }) }) const started: TerminalDocumentScope[] = [] diff --git a/mobile/src/terminal/document/bottom-row-backdrop.ts b/mobile/src/terminal/document/viewport/bottom-row-backdrop.ts similarity index 95% rename from mobile/src/terminal/document/bottom-row-backdrop.ts rename to mobile/src/terminal/document/viewport/bottom-row-backdrop.ts index 49864e1c1cc..9b506acfe14 100644 --- a/mobile/src/terminal/document/bottom-row-backdrop.ts +++ b/mobile/src/terminal/document/viewport/bottom-row-backdrop.ts @@ -1,5 +1,5 @@ -import { elementInRoot } from './document-host-seams' -import type { TerminalDocumentScope } from './document-scope' +import { elementInRoot } from '../document-host-seams' +import type { TerminalDocumentScope } from '../document-scope' import { getMeasuredCellHeight, getTotalScale } from './cell-metrics' const DEFAULT_BACKGROUND = -1 diff --git a/mobile/src/terminal/document/cell-geometry.ts b/mobile/src/terminal/document/viewport/cell-geometry.ts similarity index 94% rename from mobile/src/terminal/document/cell-geometry.ts rename to mobile/src/terminal/document/viewport/cell-geometry.ts index 5c16efb3e66..5fb659ce290 100644 --- a/mobile/src/terminal/document/cell-geometry.ts +++ b/mobile/src/terminal/document/viewport/cell-geometry.ts @@ -1,5 +1,5 @@ import { getCellHeight, getCellWidth, getTotalScale } from './cell-metrics' -import type { TerminalDocumentScope } from './document-scope' +import type { TerminalDocumentScope } from '../document-scope' export function cellToViewportPx(scope: TerminalDocumentScope, col: number, absRow: number) { if (!scope.term) { diff --git a/mobile/src/terminal/document/cell-metrics.ts b/mobile/src/terminal/document/viewport/cell-metrics.ts similarity index 93% rename from mobile/src/terminal/document/cell-metrics.ts rename to mobile/src/terminal/document/viewport/cell-metrics.ts index 37daa7adcda..c0b00aa2302 100644 --- a/mobile/src/terminal/document/cell-metrics.ts +++ b/mobile/src/terminal/document/viewport/cell-metrics.ts @@ -1,4 +1,4 @@ -import type { TerminalDocumentScope } from './document-scope' +import type { TerminalDocumentScope } from '../document-scope' // Keep pure metrics below fit/transform/overlay dependencies to avoid cycles. diff --git a/mobile/src/terminal/document/fit-scale.ts b/mobile/src/terminal/document/viewport/fit-scale.ts similarity index 94% rename from mobile/src/terminal/document/fit-scale.ts rename to mobile/src/terminal/document/viewport/fit-scale.ts index d3fa4679ba9..d359af9083e 100644 --- a/mobile/src/terminal/document/fit-scale.ts +++ b/mobile/src/terminal/document/viewport/fit-scale.ts @@ -1,9 +1,9 @@ -import { repositionOverlay } from './selection-overlay' +import { repositionOverlay } from '../selection/selection-overlay' import { computeFitScale, flog, updateTransform } from './viewport-transform' import { getCellWidth, getTotalScale } from './cell-metrics' -import type { TerminalDocumentScope } from './document-scope' -import type { TerminalViewportChange } from './document-host-seams' -import { scheduleDocumentFrame } from './document-frame-registry' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalViewportChange } from '../document-host-seams' +import { scheduleDocumentFrame } from '../document-frame-registry' import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' // Keep content covering the viewport; smaller dimensions pin top-left rather than floating. diff --git a/mobile/src/terminal/document/keyboard-avoidance-metrics.ts b/mobile/src/terminal/document/viewport/keyboard-avoidance-metrics.ts similarity index 90% rename from mobile/src/terminal/document/keyboard-avoidance-metrics.ts rename to mobile/src/terminal/document/viewport/keyboard-avoidance-metrics.ts index 4b5eee4d659..5fa88c51cc7 100644 --- a/mobile/src/terminal/document/keyboard-avoidance-metrics.ts +++ b/mobile/src/terminal/document/viewport/keyboard-avoidance-metrics.ts @@ -1,10 +1,7 @@ import { getMeasuredCellHeight, getTotalScale } from './cell-metrics' -import { notify } from './host-notify' -import type { - TerminalDocumentCell, - TerminalDocumentLine, - TerminalDocumentScope -} from './document-scope' +import { notify } from '../host-bridge/host-notify' +import type { TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentCell, TerminalDocumentLine } from '../document-terminal-shape' export function lineHasVisibleContent( scope: TerminalDocumentScope, diff --git a/mobile/src/terminal/document/viewport/laid-out-cell-box.test.ts b/mobile/src/terminal/document/viewport/laid-out-cell-box.test.ts new file mode 100644 index 00000000000..ba8a578b4f3 --- /dev/null +++ b/mobile/src/terminal/document/viewport/laid-out-cell-box.test.ts @@ -0,0 +1,51 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { reportLaidOutCellBox } from './laid-out-cell-box' +import { createTerminalDocumentScope } from '../document-scope' +afterEach(() => { + vi.unstubAllGlobals() + document.body.innerHTML = '' +}) + +describe('laidOutCellBox', () => { + function scopeWithCell( + cell: { width: number; height: number }, + fontSize: number, + posted: Record[] = [] + ) { + const scope = createTerminalDocumentScope({ postToHost: (message) => posted.push(message) }) + scope.currentTextScale = 1.25 + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the reader touches only cols, rows, options.fontSize and _core's render dimensions. + scope.term = { + cols: 55, + rows: 47, + options: { fontSize }, + _core: { _renderService: { dimensions: { css: { cell } } } } + } as unknown as typeof scope.term + return scope + } + + 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 } + const scope = scopeWithCell(cell, 16, posted) + reportLaidOutCellBox(scope) + reportLaidOutCellBox(scope) + Object.assign(scope.term!, { cols: 50 }) + reportLaidOutCellBox(scope) + cell.width = 9.75 + reportLaidOutCellBox(scope) + expect(posted).toEqual([ + { + type: 'cell-box', + cellBox: { fontScale: 1.25, cellWidth: 29 / 3, cellHeight: 21 }, + refit: false + }, + { + type: 'cell-box', + cellBox: { fontScale: 1.25, cellWidth: 9.75, cellHeight: 21 }, + refit: true + } + ]) + }) +}) diff --git a/mobile/src/terminal/document/laid-out-cell-box.ts b/mobile/src/terminal/document/viewport/laid-out-cell-box.ts similarity index 84% rename from mobile/src/terminal/document/laid-out-cell-box.ts rename to mobile/src/terminal/document/viewport/laid-out-cell-box.ts index 01ebd00860e..ce33657cc83 100644 --- a/mobile/src/terminal/document/laid-out-cell-box.ts +++ b/mobile/src/terminal/document/viewport/laid-out-cell-box.ts @@ -1,6 +1,6 @@ -import { sameCellBox, type TerminalLaidOutCellBox } from '../terminal-cell-box' -import type { TerminalDocumentScope } from './document-scope' -import { notify } from './host-notify' +import { sameCellBox, type TerminalLaidOutCellBox } from '../../terminal-cell-box' +import type { TerminalDocumentScope } from '../document-scope' +import { notify } from '../host-bridge/host-notify' export function laidOutCellBox(scope: TerminalDocumentScope): TerminalLaidOutCellBox | null { const term = scope.term diff --git a/mobile/src/terminal/document/normal-buffer-smooth-scroll.ts b/mobile/src/terminal/document/viewport/normal-buffer-smooth-scroll.ts similarity index 95% rename from mobile/src/terminal/document/normal-buffer-smooth-scroll.ts rename to mobile/src/terminal/document/viewport/normal-buffer-smooth-scroll.ts index 95b8853d7bc..47ac9d5795e 100644 --- a/mobile/src/terminal/document/normal-buffer-smooth-scroll.ts +++ b/mobile/src/terminal/document/viewport/normal-buffer-smooth-scroll.ts @@ -1,7 +1,7 @@ import { getCellHeight, getTotalScale } from './cell-metrics' import { updateScrollIndicator } from './viewport-transform' -import type { TerminalDocumentScope } from './document-scope' -import { cancelDocumentFrame, scheduleDocumentFrame } from './document-frame-registry' +import type { TerminalDocumentScope } from '../document-scope' +import { cancelDocumentFrame, scheduleDocumentFrame } from '../document-frame-registry' export function clampNormalScrollLines(scope: TerminalDocumentScope, lines: number) { if (!scope.term || !scope.term.buffer || !scope.term.buffer.active || lines === 0) { diff --git a/mobile/src/terminal/document/reflow.ts b/mobile/src/terminal/document/viewport/reflow.ts similarity index 89% rename from mobile/src/terminal/document/reflow.ts rename to mobile/src/terminal/document/viewport/reflow.ts index be170ce133b..a90df65e348 100644 --- a/mobile/src/terminal/document/reflow.ts +++ b/mobile/src/terminal/document/viewport/reflow.ts @@ -1,8 +1,8 @@ import { applyFitScale } from './fit-scale' -import { isAlternateBufferActive } from './mouse-input-encoding' +import { isAlternateBufferActive } from '../surface-input/mouse-input-encoding' import { updateScrollIndicator } from './viewport-transform' import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' -import type { TerminalDocumentScope } from './document-scope' +import type { TerminalDocumentScope } from '../document-scope' // Rewrap scrollback after PTY width changes; skip alternate screens, whose full repaints can lose SGR under local resize. export function reflow(scope: TerminalDocumentScope, cols: number, rows: number) { diff --git a/mobile/src/terminal/document/text-scaling.ts b/mobile/src/terminal/document/viewport/text-scaling.ts similarity index 91% rename from mobile/src/terminal/document/text-scaling.ts rename to mobile/src/terminal/document/viewport/text-scaling.ts index a5ae909c64d..9b2ed5e7482 100644 --- a/mobile/src/terminal/document/text-scaling.ts +++ b/mobile/src/terminal/document/viewport/text-scaling.ts @@ -1,10 +1,10 @@ import { getCellHeight, getCellWidth } from './cell-metrics' -import { elementInRoot } from './document-host-seams' -import { TERMINAL_TEXT_SCALES } from '../terminal-text-scales' -import type { TerminalDocumentScope } from './document-scope' -import { scheduleDocumentFrame } from './document-frame-registry' +import { elementInRoot } from '../document-host-seams' +import { TERMINAL_TEXT_SCALES } from '../../terminal-text-scales' +import type { TerminalDocumentScope } from '../document-scope' +import { scheduleDocumentFrame } from '../document-frame-registry' import { applyFitScale } from './fit-scale' -import { fitDimensionsFromCell } from '../terminal-grid-fit' +import { fitDimensionsFromCell } from '../../terminal-grid-fit' // Re-init temporarily clears ready; latch prior readiness so width reflow cannot turn a transient error fatal. diff --git a/mobile/src/terminal/document/viewport-cell.ts b/mobile/src/terminal/document/viewport/viewport-cell.ts similarity index 95% rename from mobile/src/terminal/document/viewport-cell.ts rename to mobile/src/terminal/document/viewport/viewport-cell.ts index bce7910d2fc..39268267d0e 100644 --- a/mobile/src/terminal/document/viewport-cell.ts +++ b/mobile/src/terminal/document/viewport/viewport-cell.ts @@ -1,5 +1,5 @@ import { getCellHeight, getCellWidth, getTotalScale } from './cell-metrics' -import type { TerminalDocumentScope } from './document-scope' +import type { TerminalDocumentScope } from '../document-scope' // Subtract the host origin before grid mapping; embedded terminals sit below headers while native windows start at zero. export function viewportPoint(scope: TerminalDocumentScope, clientX: number, clientY: number) { diff --git a/mobile/src/terminal/document/viewport/viewport-frame.test.ts b/mobile/src/terminal/document/viewport/viewport-frame.test.ts new file mode 100644 index 00000000000..3eab8712a04 --- /dev/null +++ b/mobile/src/terminal/document/viewport/viewport-frame.test.ts @@ -0,0 +1,44 @@ +// @vitest-environment happy-dom +import { describe, expect, it } from 'vitest' +import { createTerminalDocumentScope, type TerminalDocumentScope } from '../document-scope' +import type { TerminalDocumentHost } from '../document-host-seams' +import { terminalDocumentDouble } from '../document-terminal-double.test-support' +import { computeFitScale } from './viewport-transform' + +const CELL = { width: 7.5, height: 15 } + +function scopeWithGrid(host: TerminalDocumentHost = {}): TerminalDocumentScope { + const scope = createTerminalDocumentScope(host) + const terminal = terminalDocumentDouble().terminal + const cell = () => { + const k = terminal.options.fontSize / 13 + return { width: CELL.width * k, height: CELL.height * k } + } + const grid = Object.assign(terminal, { + cols: 55, + rows: 40, + _core: { + _renderService: { + get dimensions() { + return { css: { cell: cell() } } + } + } + } + }) + grid.resize = (cols: number, rows: number) => { + grid.cols = cols + grid.rows = rows + } + scope.term = grid + return scope +} + +describe("the document's frame on the page", () => { + it('keeps the fit at 1 while the host is hidden and measures 0x0', () => { + // Inactive react-native-screens routes use display:none and have no measurable host box. + const scope = scopeWithGrid({ + viewportRect: () => ({ left: 0, top: 0, width: 0, height: 0 }) + }) + expect(computeFitScale(scope)).toBe(1) + }) +}) diff --git a/mobile/src/terminal/document/viewport-transform.ts b/mobile/src/terminal/document/viewport/viewport-transform.ts similarity index 93% rename from mobile/src/terminal/document/viewport-transform.ts rename to mobile/src/terminal/document/viewport/viewport-transform.ts index d39c5afafd3..5dc6e251a3b 100644 --- a/mobile/src/terminal/document/viewport-transform.ts +++ b/mobile/src/terminal/document/viewport/viewport-transform.ts @@ -1,7 +1,7 @@ import { paintBottomRowBackdrop } from './bottom-row-backdrop' -import { repositionOverlay } from './selection-overlay' -import { shouldRouteScrollToTerminalInput } from './mouse-input-encoding' -import type { TerminalDocumentScope } from './document-scope' +import { repositionOverlay } from '../selection/selection-overlay' +import { shouldRouteScrollToTerminalInput } from '../surface-input/mouse-input-encoding' +import type { TerminalDocumentScope } from '../document-scope' import { getCellWidth, getTotalScale } from './cell-metrics' // First live output can widen a buffer measured during replay; permit one fresh fit before preserving user zoom. diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts index 4a80fb6f2c4..3a07b277e6e 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts @@ -2,8 +2,8 @@ import { Terminal } from '@xterm/xterm' 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 { emitKeyboardAvoidanceMetrics } from './document/viewport/keyboard-avoidance-metrics' +import { commitFitScale } from './document/viewport/fit-scale' function runMetricsOver(term: unknown, fitScale = 1): Record[] { const notifications: Record[] = [] diff --git a/mobile/src/terminal/terminal-webview-engine.test.ts b/mobile/src/terminal/terminal-webview-engine.test.ts index bae8c70c67a..c1f48ded583 100644 --- a/mobile/src/terminal/terminal-webview-engine.test.ts +++ b/mobile/src/terminal/terminal-webview-engine.test.ts @@ -2,77 +2,8 @@ import { Script } from 'node:vm' import { parse } from 'acorn' import { describe, expect, it, vi } from 'vitest' -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 } from './document/webgl-recovery' -import { XTERM_HTML } from './terminal-webview-html' - -function createWebglRecoveryHarness(failSecondAttach = false) { - const timers: Array<() => void> = [] - const addons: Array<{ - clearTextureAtlas: ReturnType - dispose: ReturnType - fireContextLoss: () => void - }> = [] - const term = { - rows: 24, - options: { theme: {}, minimumContrastRatio: 0, fontSize: 13 }, - refresh: vi.fn(), - loadAddon: vi.fn(() => { - if (failSecondAttach && addons.length === 2) { - throw new Error('retry unavailable') - } - }) - } - function WebglAddon() { - let contextLoss = () => {} - const addon = { - clearTextureAtlas: vi.fn(), - dispose: vi.fn(), - fireContextLoss: () => contextLoss() - } - addons.push(addon) - return Object.assign(addon, { - onContextLoss: (listener: () => void) => { - contextLoss = listener - } - }) - } - const logged: Record[] = [] - vi.spyOn(globalThis, 'setTimeout').mockImplementation((callback: TimerHandler) => { - if (typeof callback === 'function') { - timers.push(() => { - callback() - }) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the document holds this only to clear it, and nothing here clears a timer. - return timers.length as unknown as ReturnType - }) - const scope = createTerminalDocumentScope({ - createWebglAddon: () => WebglAddon(), - postToHost: (message) => logged.push(message) - }) - // 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 - attachWebglAddon(scope, true) - return { - addons, - logged, - term, - timers - } -} - describe('terminal WebView bundled engine', () => { - it('keeps the assembled terminal HTML free of external engine URLs', () => { - expect(XTERM_HTML).not.toMatch(/\bhttps?:\/\//) - expect(XTERM_HTML).not.toContain('cdn.jsdelivr.net') - expect(XTERM_HTML).not.toContain('